C language not only has various characteristics of high-level languages, but also can operate hardware and carry out structured programming. Programs written in C language are easier to transplant. They can generate concise and reliable target codes. In terms of code efficiency and code The execution speed is completely comparable to assembly. Using C language for microcontroller programming is the development trend of embedded programming. However, in fields such as embedded control, it is often necessary to control a certain binary bit. However, except for C environments such as Keil C51, many microcontroller C environments do not have keywords to expand the definition of bit variables, and even the hardware of the microcontroller itself does not Assembly instructions for single bit operations, which makes users accustomed to MCS-51 core microcontroller Keil C51 programming troubled by the fact that their C environment cannot perform bit operations on bit variables.
1 Use the "read-modify-write" method to implement bit operations on a single bit
In ANSIC, the "read-modify-write" method is generally used to implement the bit operation of a single bit, and a certain bit is cleared to 0 through the "AND" operation with 0. If the b0 bit of the i variable is set to 0, the implementation method is i=i&0xfe. By "ORing" with 1, a certain position is set to 1. If the b0 bit of the i variable is set to 1, the implementation method is i=i|0x01. Through the "XOR" operation with 1, a certain bit is inverted. If the b0 bit of the i variable is inverted, the implementation method is i=i^0x01.
Note: Do not affect other bits when using the "read-modify-write" method. That is, when a bit is cleared, other bits are "ANDed" with 1; when a certain bit is set to 1, other bits are "ORed" with 0; when negated, other bits are "ORed". Bits are XORed with 0.
In order to facilitate programming and increase program readability, many programmers like to use the following shift method to implement single-bit bit operations. The statements are concise and readable. For example, a light-emitting diode is connected to the B port of a microcontroller. The lighting operation method is as follows:
#define bit(x) (1<<(x))
#define LED 2
How to use it:
PORTB|=bit(LED); //Set the third position of PORTB to 1, click
//Light up the LED connected to the I/O port
In this mode, shift operations will be added when the program is running, and the generated code will be large, take a long time to execute, and have poor real-time performance. Some C environments directly define bits as follows, and the generated code will not have shift operations:
2 Implement bit operations through bit field methods
Standard C provides a structure-based data structure - BitField. Bitfield divides the binary in a storage unit into several different areas. And explain the number of bits in each area. Each domain has a domain name, which allows operations by domain name in the program. The definition format of the bit field is as follows:
struct bit field structure name {
bit field list};
the format of the bit field list is: type specifier bit domain name: bit field length such as:
struct k{
unsigned int a: 1
unsigned int: 2
unsigned int b: 3
unsigned int: 0 / /airspace
}k1;
illustrate:
1) The bits are arranged from low to high, until one storage unit is filled, and then the next unit is arranged according to the address;
2) A bit field can have no domain name, but cannot be referenced, such as the second field, in which case it is only used to fill or adjust the position;
3) The fourth line is called the empty field. The purpose is to divide the remaining part of the current storage unit into a field and fill it with 0.
The reference of the bit field is very simple, such as:
k1.a=1; //Set the b0 bit of k1 to 1
k1.b=7; //position b3-5 of k1 to 111
Defining bit variables through bit fields is an important way and method to implement single bit operations. Using bit fields to define bit variables produces compact and efficient code. The method defined is as follows:
By defining bits through bit fields and then defining them through macros, programs such as Keil C51 can be easily ported to other C compilers, so that you no longer have to worry about no bit operations.
For all I/O ports of a microcontroller, by specifying the bit field structure to the I/O port address, the I/O ports can be macro-defined using bit fields. In this way, operating the I/O ports can be programmed like Keil C51 Just as convenient.
3 Application examples of bit operations based on bit fields
Many microcontrollers do not have hardware SPI, and many board-level peripheral devices have SPI interfaces, and some peripheral devices are not standard SPI, that is, the total number of binary digits in communication is not an integer multiple of 8. Here is a routine for simultaneous collection and Send 0-16 bits, full-duplex mode, see the routine notes for specific usage. Note: Many microcontrollers need to initialize the I/O ports used before use. clk and din are output ports, and dout is the input port. At the same time, a function GET_BIT (x, y) defined by the read-modify-write macro is used here. ).
This SPI module has been successfully applied to SPI communication between microcontrollers and MAX7219 and CH451.
For C language environments that do not have extended bit variables, and MCUs that do not perform bit operations on a single bit in assembly, operating the I/O port through the bit field method is the best method. MCUs that have bit operation instructions for a single bit in assembly . Assembly can be embedded, but the portability and other performance of the program will be reduced. It is recommended to use the bit field method.
Previous article:Implementation method of bit operations in single chip C environment
Next article:Design of automatic horn tone player based on AT89C51 microcontroller
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
- Innolux's intelligent steer-by-wire solution makes cars smarter and safer
- 8051 MCU - Parity Check
- How to efficiently balance the sensitivity of tactile sensing interfaces
- What should I do if the servo motor shakes? What causes the servo motor to shake quickly?
- 【Brushless Motor】Analysis of three-phase BLDC motor and sharing of two popular development boards
- Midea Industrial Technology's subsidiaries Clou Electronics and Hekang New Energy jointly appeared at the Munich Battery Energy Storage Exhibition and Solar Energy Exhibition
- Guoxin Sichen | Application of ferroelectric memory PB85RS2MC in power battery management, with a capacity of 2M
- Analysis of common faults of frequency converter
- In a head-on competition with Qualcomm, what kind of cockpit products has Intel come up with?
- Dalian Rongke's all-vanadium liquid flow battery energy storage equipment industrialization project has entered the sprint stage before production
- Allegro MicroSystems Introduces Advanced Magnetic and Inductive Position Sensing Solutions at Electronica 2024
- Car key in the left hand, liveness detection radar in the right hand, UWB is imperative for cars!
- After a decade of rapid development, domestic CIS has entered the market
- Aegis Dagger Battery + Thor EM-i Super Hybrid, Geely New Energy has thrown out two "king bombs"
- A brief discussion on functional safety - fault, error, and failure
- In the smart car 2.0 cycle, these core industry chains are facing major opportunities!
- The United States and Japan are developing new batteries. CATL faces challenges? How should China's new energy battery industry respond?
- Murata launches high-precision 6-axis inertial sensor for automobiles
- Ford patents pre-charge alarm to help save costs and respond to emergencies
- New real-time microcontroller system from Texas Instruments enables smarter processing in automotive and industrial applications
- Popular Science | Power Management Knowledge
- TI Reference Voltage (VREF) Application Design Tips
- The difference between multilayer PCB and LTCC
- The basis of the difference between TTL and CMOS
- About Puzhong Technology 51 microcontroller development board v3.0, LED part of the problem
- Understanding bandwidth
- Circuit output grounding problem.
- When AD software needs to drill vias to connect the network in the inner electrical layer segmentation, what is the minimum distance between the vias and the inner electrical layer segmentation edge?
- The United States is pressing forward: blacklisting 38 Huawei subsidiaries in an attempt to block Huawei's outsourcing of chips
- 【GD32450I-EVAL】+ 06SDRAM Introduction