How to use C language to manipulate the I/O port of AVR (taking iccavr as an example ):
Example 1: Define pb0 as output and output as high
Ddrb = bit (0); // defines pb0 as the output.
Portb | = bit (0); // pb0 outputs a high level
Example 2: Define pb0 and PB1 as outputs, and pb0 outputs Low levels. PB1 outputs high levels.
Ddrb | = bit (0) | bit (1); // defines pb0 and PB1 as the output.
Portb | = bit (0) | bit (1); // pb0, PB1 output high level
Example 3: Flip the value of the pb0 data register, that is, if it is 1, it turns to 0, if it is 0, it turns to 1.
Portb ^ = bit (0); // pb0 outputs a high level that is equal to or greater than 0, which is the same as 1 or which is equal to 0.
Example 4: Flip the values of the pb0 and PB1 data registers. That is, if the value is 1, the value is 0. If the value is 0, the value is 1.
Portb ^ = bit (0) | bit (1); // pb0 outputs the high level. Unfortunately, I didn't see it before.
Example 5: define the type of PBS and PB3 as input without pulling resistance
Ddrb & = ~ (BIT (2) | bit (3); // you can call this operation to define the following parameters:
Portb & = ~ (BIT (2) | bit (3); // set the port to 0 without the pull-up resistance.
Example 6: define the type of PBS and PB3 as input with a pulling resistance. That is, when these pins are not referenced, the default value is high.
Sfior & = ~ Bit (PUD); // The sfior register's pull-up resistor control bit pud is set to 0. In the entire code, this sentence can not appear, or only appear once. Because it is a control bit that controls all the pull-up resistors.
Ddrb & = ~ (BIT (2) | bit (3); // you can call this operation to define the following parameters:
Portb | = bit (2) | bit (3); // set port to 1 to meet another condition of the pull-up resistance.
Example 7: ddrb = bit (0) | bit (1) and ddrb | = bit (0) | bit (1)
Assume that the ddrb status is 1000 0000 before executing the preceding two commands.
If you execute ddrb = bit (0) | bit (1), the ddrb status changes to: 0000 0011
If you execute ddrd | = bit (0) | bit (1), the ddrb status changes to: 1000 0011
The previous statement first clears all previous states, and the last statement retains the previous state.
In practice, the last sentence is more commonly used.
Example 8: Do I have other expressions besides bit (3) in position 3?
Ddrb | = bit (3 );
Ddrb | = 1 <3;
Ddrb | = 0x08;
Ddrb | = 0b00001000;
Article from Network