I have been working on a simple project on AVR microcontroller atmega16 on proteus simulation.
The project is:
When I push the push button it increments the seven segment to number 9 and after that if the we pushed the button again it overflows and return again to 0.
When I change the (flag=1;) position at while loop code it gives me different outputs and by this I mean when I push the push button it didn't response after the pushing.
It may require another pushing to the button to increment the seven segment proteus simulation
The only code that worked properly is when set flag=1;
before exiting (the second if and else conditions)
So my question is what actually happened when I change the flag=1;
statement position at the code.
#include<avr/io.h>
#include<avr/interrupt.h>
char flag=1;
char num=0;
void INT2_Init(void){
DDRB&=~(1<<2);
SREG|=(1<<7);
GICR|=(1<<INT2);
MCUCSR|=(1<<ISC2);
}
ISR(INT2_vect){
flag=0;
GIFR|=(1<<INTF2);
}
int main(void){
DDRC=0x0f;
PORTC=0;
DDRB&=~(1<<2);
INT2_Init();
while(1){
if(flag==0){
if(num>8){
num=0;
PORTC=(PORTC&0xf0)|num;
}
else{
num ;
PORTC=(PORTC&0xf0)|num;
}
}
flag=1;
}
}
CodePudding user response:
It is not entirely clear to me what you are asking. Do you just struggle to understand the code? Do my comments help?
#include<avr/io.h>
#include<avr/interrupt.h>
char flag=1;
char num=0;
void INT2_Init(void){
DDRB&=~(1<<2);
SREG|=(1<<7);
GICR|=(1<<INT2);
MCUCSR|=(1<<ISC2);
}
// sets flag to 0 on external interrupt (button press)
ISR(INT2_vect){
flag=0;
GIFR|=(1<<INTF2);
}
int main(void){
DDRC=0x0f;
PORTC=0;
DDRB&=~(1<<2);
INT2_Init();
while(1){
// if flag was set to 0 in external interrupt -> increment (or overflow) number on segment display
if(flag==0){
if(num>8){
num=0;
PORTC=(PORTC&0xf0)|num;
}
else{
num ;
PORTC=(PORTC&0xf0)|num;
}
}
// reset the flag to 1 to prevent num from being incremented continuously
flag=1;
}
}
I would suggest to move flag=1;
inside the if
to make the intent clear that the statement should only execute once with every button press.
while(1) {
// if flag was set to 0 in external interrupt -> increment (or overflow) number on segment display
if(flag==0){
// reset the flag to 1 to prevent num from being incremented continuously
flag=1;
if(num>8){
num=0;
PORTC=(PORTC&0xf0)|num;
}
else{
num ;
PORTC=(PORTC&0xf0)|num;
}
}
}
It is also advisable to use self descriptive variable names. Like buttonWasPressed
instead of flag
for example. That makes code like that much easier to read.
CodePudding user response:
@Rev no i mean what is the difference in these three codes as each of them has a different response pattern in simulation
while(1){
if(flag==0){
if(num>8){
num=0;
PORTC=(PORTC&0xf0)|num;
}
else{
num ;
PORTC=(PORTC&0xf0)|num;
}
}
flag=1;
}
while(1){
flag=1;
if(flag==0){
if(num>8){
num=0;
PORTC=(PORTC&0xf0)|num;
}
else{
num ;
PORTC=(PORTC&0xf0)|num;
}
}
}
while(1){
if(flag==0){
if(num>8){
num=0;
PORTC=(PORTC&0xf0)|num;
flag=1;
}
else{
num ;
PORTC=(PORTC&0xf0)|num;
flag=1;
}
}
}