PIC microcontroller CCS C language (#IF, #ENDIF usage)

Publisher:muhaoying2017Latest update time:2016-09-27 Source: eefocus Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
 #IF expr

#ELSE

#ELIF

#ENDIF

Syntax: #if expr

code

#elif expr

code

#else

code

#endif

expr is a constant expression, a standard operator or a preprocessor identifier;

Code is any standard C source program.

Purpose: The preprocessor evaluates the constant expression and, if the value is non-zero, processes all lines above the optional #ELSE or #ENDIF.

NOTE: You cannot use C variables in #IF, only those created by the preprocessor via #define.

The preprocessor expression DEFINED(id) can be used to return 1 if id is defined, and 0 if id is not defined.

Example: #if MAX_VALUE>255

long value; //If MAX_VALUE>255, define value as a long integer variable

#else

int value; //If MAX_VALUE is not greater than 255, define value as an integer variable

#endif

Example file: ex_extee.c

File: ex_extee.c is as follows:

#if defined(__PCB__) //If the PCB compiler is used, the return value of defined(__PCB__) is 1

#include <16c56.h> //Include 16c56.h header file

#fuses HS, NOWDT, NOPROTECT //HS: high speed crystal/resonator, NOWDT: do not use WDT

                               // NOPROTECT: Program memory code is not protected

#use delay(clock=20000000) // Enable the built-in functions: delay_ms() and delay_us()

                               //#USE DELAY() must appear before #use rs232().

#use rs232(baud=9600, xmit=PIN_A3, rcv=PIN_A2)

//Use the baud rate as 9600,

//The sending pin is PIN_A3

//The receiving pin is PIN_A2

//Enable built-in functions: GETC, PUTC and PRINTF, kbhit();

#elif defined(__PCM__)

#include <16F877.h>

#fuses HS,NOWDT,NOPROTECT,NOLVP

#use delay(clock=20000000)

#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)  // Jumpers: 8 to 11, 7 to 12

#elif defined(__PCH__)

#include <18F452.h>

#fuses HS,NOWDT,NOPROTECT,NOLVP

#use delay(clock=20000000)

#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)  // Jumpers: 8 to 11, 7 to 12

#endif //End if definition

#include //Include input.c header file

#include <2416.c> //Include 2416.c header file

void main() {

   BYTE value, cmd; //Declare byte variables value, cmd

   EEPROM_ADDRESS address; //Use EEPROM_ADDRESS instead of long int, which is 16 bits

   init_ext_eeprom(); //Initialize the I/O pins connected to eeprom

   do {

      do {

         printf("\r\nRead or Write: ");

         cmd=getc(); //Read a byte from RS232 port

         cmd=toupper(cmd); //Convert lowercase letters in cmd into uppercase letters and send them to cmd

         putc(cmd);

      } while ( (cmd!='R') && (cmd!='W') ); //Until R or W is entered

printf("\n\rLocation: ");

 

#if sizeof(EEPROM_ADDRESS)==1 

//If EEPROM_ADDRESS is defined as 1 byte, sizeof(EEPROM_ADDRESS)==1 returns 1

      address = gethex();

#else //If EEPROM_ADDRESS is defined to be greater than 1 byte

#if EEPROM_SIZE>0xfff

      address = gethex();

#else // EEPROM_SIZE is less than 0xfff

      address = gethex1(); //Read a byte from the RS232 port and store the high byte address for eeprom

#endif //End if definition

      address = (address<<8)+gethex(); //Read 2 bytes from RS232 port and store low byte address for eeprom

#endif //End if definition

      if(cmd=='R') //If you enter R, execute the following

         printf("\r\nValue: %X\r\n",READ_EXT_EEPROM( address ) );

      if(cmd=='W') {

         printf("\r\nNew value: ");

         value = gethex(); //Input from RS232, prepare for writing eeprom value

         printf("\n\r");

         WRITE_EXT_EEPROM( address, value );

      }

   } while (TRUE);

}

 

 

File: input.c is as follows:

#include //Include CTYPE.H header file

BYTE gethex1() {

   char digit; //declare byte variable digit

   digit = getc(); //Read a byte from the RS232 port

   putc(digit); //Write a byte to the RS232 port

   if(digit<='9') //Return the read byte in hexadecimal

     return(digit-'0'); //If the read ASCII code is less than or equal to 39, subtract 30 and return it in hexadecimal

   else

     return((toupper(digit)-'A')+10); //If the read ASCII code is greater than 39, subtract 41 from it, add 10 and return

}

 

BYTE gethex() {

   int lo, hi; //declare integer variables lo, hi

   hi = gethex1(); //Read a byte from the RS232 port and store it in hi

   lo = gethex1(); //Read a byte from the RS232 port and store it in lo

   if(lo==0xdd)

     return(hi);

   else

     return( hi*16+lo );

}

 

void get_string(char* s, int max) {

   int len; //declare integer variable len

   char c; //declare byte type variable c

   --max; //Initialize max value

   len=0; //Initialize len value

   do {

     c=getc(); //Read a byte from the RS232 port and store it in c

     if(c==8) { // If Backspace is the space key

        if(len>0) {

          only--;

          putc(c); //Write c to RS232

          putc(' ');

          putc(c);

        }

     } else if ((c>=' ')&&(c<='~'))

       if(len

         s[len++]=c;

         putc(c);

       }

   } while(c!=13);

   s[len]=0;

}

 

// stdlib.h is required for the ato_ conversions

// in the following functions

#ifdef _STDLIB //If _STDLIB is defined, execute the following

signed int get_int() {

  char s[5]; //declare character array s[5]

  signed int i; //Declare a signed integer variable i

  get_string(s, 5); //Read 5 bytes from the RS232 port and store them in the s array

  i=atoi(s); //Convert the string in array s[] into an integer and send it to i

  return(i);

}

 

signed long get_long() {

  char s[7]; //declare character array s[7]

  signed long l; //Declare a signed long integer variable l

  get_string(s, 7); //Read 7 bytes from the RS232 port and store them in the s array

  l=atol(s); //Convert the string in array s[] into a long integer and send it to l

  return(l);

}

 

float get_float() {

  char s[20]; //declare character array s[7]

  float f; //declaration of dot-type variable l

  get_string(s, 20); //Read 20 bytes from the RS232 port and store them in the s array

  f = atof(s); //Convert the string in array s[] into a symbol number and send it to f

  return(f);

}

#endif //End if definition

 

File: 2416.c is as follows:

////   Library for a MicroChip 24LC16B                         ////

////   init_ext_eeprom();    Call before the other functions are used   ////

////   write_ext_eeprom(a, d);  Write the byte d to the address a      ////

////   d = read_ext_eeprom(a);  Read the byte d from the address a    ////

////   b = ext_eeprom_ready();  Returns TRUE if the eeprom is ready  ////

////                            to receive opcodes              ////

////   The main program may define EEPROM_SDA                ////

////   and EEPROM_SCL to override the defaults below.             ////

////                            Pin Layout                    ////

////   -----------------------------------------------------------               ////

////   |                                                        |   ////

////   | 1: NC   Not Connected   | 8: VCC   +5V                   |   ////

////   | 2: NC   Not Connected   | 7: WP    GND                   |  ////

////   | 3: NC   Not Connected   | 6: SCL   EEPROM_SCL and Pull-Up |   ////

////   | 4: VSS  GND           | 5: SDA   EEPROM_SDA and Pull-Up |  ////

////   -----------------------------------------------------------     ////

#ifndef EEPROM_SDA //If EEPROM_SDA is not defined, execute the following

#define EEPROM_SDA PIN_C4 //用EEPROM_SDA replace PIN_C4

#define EEPROM_SCL  PIN_C3   //用EEPROM_SCL代替PIN_C3

#endif //End if definition

#use i2c(master, sda=EEPROM_SDA, scl=EEPROM_SCL)

     // Set the master to host mode

     //Unless FORCE_HW is specified, a software function emulating I2C will be generated.

// Enable I2C_START, I2C_STOP until the next #USE I2C appears.

// Enable I2C_READ, I2C_WRITE until the next #USE I2C occurs.

// Enable I2C_POLL until the next #USE I2C occurs.

     //Specify the sda ​​pin as EEPROM_SDA, and the scl pin as EEPROM_SCL

#define EEPROM_ADDRESS  long int   //用EEPROM_ADDRESS代替long int

#define EEPROM_SIZE 2048 //Replace 2048 with EEPROM_SIZE

void init_ext_eeprom() {

   output_float(EEPROM_SCL); //Set the EEPROM_SCL pin as input, open collector connection

   output_float(EEPROM_SDA); //Set the EEPROM_SDA pin as input, open collector connection

}

 

BOOLEAN ext_eeprom_ready() {

   int1 ack; //declare bit variable ack

   i2c_start(); //Send start condition

   ack = i2c_write(0xa0); //Send slave address 0xa0; if ack=0, it means slave responds (ACK);

//If ack=1, it means the slave does not respond (NO ACK);

   i2c_stop(); //Send stop condition

   return !ack;

} // ext_eeprom_ready() function, if it returns 1, it means the slave is ready; if it returns 0, it means the slave is busy or the eeprom is broken

 

void write_ext_eeprom(long int address, BYTE data) {

   while(!ext_eeprom_ready()); //If the slave is busy, the host waits

   i2c_start(); //Send start condition

   i2c_write( (0xa0|(BYTE)(address>>7))&0xfe); //Send the high byte of the command word (send write command)

   i2c_write(address); //Send the low byte of the command word

   i2c_write(data); //Send data

   i2c_stop(); //Send stop condition

}

 

BYTE read_ext_eeprom(long int address) {

   BYTE data; //Declare byte variable data

   while(!ext_eeprom_ready()); //Send the device address first, if the slave is busy, the host waits

   i2c_start(); //Here is: send restart condition

   i2c_write( (0xa0|(BYTE)(address>>7))&0xfe); //Send the high byte of the command word (send write command)

   i2c_write(address); //Send the low byte of the command word

   i2c_start(); //Send start condition

   i2c_write( (0xa0|(BYTE)(address>>7))|1); //Send the high byte of the command word (send a read command)

   data=i2c_read(0); //Read I2C data, then send ack=0 (no need for slave response)

   i2c_stop(); //Send stop condition

   return(data); //Return the read I2C data

}

The above example is mainly used to read and write 24C16, and verify it through PC RS232

Reference address:PIC microcontroller CCS C language (#IF, #ENDIF usage)

Previous article:PIC microcontroller CCS C language (#IFDEF, #ENDIF usage)
Next article:PIC microcontroller CCS C language (#FUSES usage)

Recommended ReadingLatest update time:2024-11-16 15:27

Design of WiFi temperature and humidity intelligent switch based on 51 single chip microcomputer
1. Hardware Solution The hardware circuit is mainly composed of single-chip microcomputer circuit, temperature and humidity acquisition circuit, LCD display circuit, relay circuit and wifi module circuit. This design uses STC89C51 single-chip microcomputer to complete the control process of the whole system. The mobil
[Microcontroller]
Design of WiFi temperature and humidity intelligent switch based on 51 single chip microcomputer
Operational Amplifier Input
Abstract: When does input bias current become a concern? Which architecture offers the lowest offset voltage? This application note introduces common op-amp input structures with their associated design advantages and challenges. Operational amplifier (op amp) inputs vary widely in structure and performance. This d
[Power Management]
Programmable-Gain Amplifier, Using the MAX532 DAC
Abstract: This application note discusses how to use the MAX532 to build a programmable gain amplifier (PGA) that's suitable for AC gain control. No external components are necessary. Equations are provided to easily calculate the output values. -- ================================================
[Analog Electronics]
Programmable-Gain Amplifier, Using the MAX532 DAC
MCU and FIFO interface assembly program
In the following program, the microcontroller reads the data in the FIFO and sends it out from the serial port. ;********************************** ef bit p3.3 ;fifo empty flag rst bit p3.5 ;reset fifo read bit p3.7 ;read fifo org 0000h ljmp main org 0030h main: ;------ initial timer mov tmod,
[Microcontroller]
Using FIFO to implement bidirectional parallel asynchronous communication between DSPs
    Abstract: This paper introduces the method of using the FIFO chip CY7C419 of CYPRESS Company to realize bidirectional parallel asynchronous communication between DSPs. This method is simple, practical and fast, and is especially suitable for mutual transmission of small amounts of data. The article gives the pin
[Embedded]
What is fifo? What does fifo mean? Difference between GPIF and FIFO
1. What is FIFO? FIFO is the abbreviation of First In First Out. It is a first-in-first-out data buffer. The difference between it and ordinary memory is that it has no external read and write address lines, which makes it very simple to use. However, its disadvantage is that it can only write and read data sequentia
[Microcontroller]
In Qorvo's view, what are the opportunities and challenges of WiFi 6?
Recently, Xiaomi and Huawei have launched a number of WiFi 6 routers, and the FCC has allowed the 6Ghz frequency band to be opened for WiFi use, which has aroused great interest in WiFi 6 and WiFi 6E in the industry. Seeing the unlimited opportunities brought by the new standard, many chip companies and related termin
[Network Communication]
In Qorvo's view, what are the opportunities and challenges of WiFi 6?
Design and implementation of large capacity FIFO based on SRAM/DRAM
introduction   CMMB (China Mobile Multimedia Broadcasting) is China's first mobile broadcasting and television standard with independent intellectual property rights for mobile terminals. It is also a portable mobile multimedia broadcasting and television product jointly launched by China Mobile Communications Corpo
[Microcontroller]
Design and implementation of large capacity FIFO based on SRAM/DRAM
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号