For this lab, you must write C code that will turn ON LEDs 1 to 4 when push butt
ID: 3562462 • Letter: F
Question
For this lab, you must write C code that will turn ON LEDs 1 to 4 when push button PB1 is pushed. The program must turn ON LEDs 5 to 8 when push button PB2 is pushed.
PB1 is wired to Port A0, PB2 is wired to Port A1. Both these pins must be configured as input pins.
The LEDs 1 to 8 must be wired to Port B.
LED8 to PortB0
LED7 to PortB1
LED6 to PortB2
LED5 to PortB3
LED4 to PortB4
LED3 to PortB5
LED2 to PortB6
LED1 to PortB7
You must write the code in C and run it first in Full Chip Simulation, and, in the lab, download it in the board. CodeWarrior does not allow you to modify the content of a port configured with input bits.
Explanation / Answer
Explanation:
This is a simple program, perhaps simplest, and an introduction to Atmega16. To make a led blink you have to set (logic 1) and reset (logic 0) a pin of the controller continuously.
DDR is data direct resister, DDR determines whether a particular pin of a port will work as an input or as an output, writing logic 1 to DDR makes the pin behave as output pin, writing logic 1 to DDR makes the pin behave as input pin. As we I wrote DDRA=0xFF, it will make all pins of portA work as output pin. Suppose you need only PA2 ( pin3 of portA ) as output pin, you need to write 1 to Bit 0 of data direction resister for portA (DDRA). You can write like this
DDRA=0x01;
or
DDRA|=(1<<PA2);
C-Code:
#include<avr/io.h>
#include<util/delay.h>
//defining macros
#define Set_BIT(port,bit_position) port|=(1<<bit_position)
#define CLEAR_BIT(port,bit_position) port&=~(1<<bit_position)
#define IS_BIT_CLEAR(port,bit_position) !(port&(1<<bit_position))
int main(void)
{
char PB1_status,PB2_status;
// set portB as out put
DDRB=0xFF
//configuring only pin PA0 as input without disturbing other pins of PORTA
CLEAR_BIT(PORTA,0);
//configuring only pin PA1 as input without disturbing other pins of PORTA
CLEAR_BIT(PORTA,1);
//activating pullups for both pins PA0 and PA1.so untill PB1,PB2 buttons pushed these pins are high
Set_BIT(port,0);
Set_BIT(port,1);
//all the pins of portB is reset means initially turning OFF all LEDs
PORTB=0x00;
// run forever
while(1)
{
//when the PB1 is pushed the pin of PA0 will be connected to ground,means PB1_status becomes low
PB1_status=IS_BIT_CLEAR(PORTA,0);
//when the PB2 is pushed the pin of PA1 will be connected to ground,means PB2_status becomes low
PB2_status=IS_BIT_CLEAR(PORTA,0);
if(PB1_status==0)
{
//turning ON LEDs 1 to 4 when push button PB1 is pushed
PORTB=0xF0;
_delay_ms(1000); //wait for 1sec
}
else if(PB2_status==0)
{
//turning ON LEDs 5 to 8 when push button PB2 is pushed
PORTB=0x0F;
_delay_ms(1000); //wait for 1sec
}
else
{
PORTB=0x00;
}
}//end of main while(1) loop
return(0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.