In AVR microcontroller programming, input/output ports are used to interface with external devices such as sensors, switches, LEDs, motors, and other peripherals. Here’s an example of how to program AVR input/output ports using C language:
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
// Set PORTB as output and PORTC as input
DDRB = 0xFF;
DDRC = 0x00;
while(1)
{
// Read the value of PINC3
if(PINC & (1 << PINC3))
{
// If PINC3 is high, turn on LED connected to PB0
PORTB |= (1 << PB0);
}
else
{
// If PINC3 is low, turn off LED connected to PB0
PORTB &= ~(1 << PB0);
}
}
}
In this example, we set PORTB as an output port by setting all of its pins to output mode. We set PORTC as an input port by setting all of its pins to input mode. Then, we use a while loop to continuously check the value of PINC3. If PINC3 is high, we turn on an LED connected to PB0 by setting the corresponding bit in PORTB to high. If PINC3 is low, we turn off the LED by setting the corresponding bit in PORTB to low.
Note that the &
and |
operators are used to manipulate individual bits in the port registers. The <<
operator is used to shift the binary value of 1
to the left by a certain number of bits to set a particular bit high or low. The ~
operator is used to invert the value of a bit. The util/delay.h
library is used to create a delay between each loop iteration.
Leave a Reply