I have a project to program a microcontroller PIC18F, I have to connect a switching circuit to the microcontroller board, this switching circuit has an electric lock and a buzzer to be connected to it.
The lock is initially powered. It is supposed that when I send '1', the buzzer will be powered with a square wave and the lock will be powered off. When it receives '0', the buzzer will be switched off without powering the lock again. When it receives '2' the lock should be powered but if the buzzer was unpowered before, it should not be powered again.
My confusion is in the last part. When I send '2' via the hyperterminal, and I sent '0' before it, the buzzer is powered again.
Here is the code,
void buzzertest();
char uart_rd;
int buzzer;
void main() {
TRISB=0X00;
PORTB=0x00;
RB5_bit = 0xFF; //lock open
UART1_Init(9600); // Initialize UART module at 9600 bps
while (1) { // Endless loop
if (UART1_Data_Ready()) // If data is received,
{
buzzer=1;
uart_rd = UART1_Read(); // read the received data,
if(uart_rd =='1') {
RB5_bit = 0x00; //lock closed
buzzertest();
}
if(uart_rd =='0' ){ //disable buzzer
RB1_bit = 0x00; //buzzer
buzzer=0;
}//end if
buzzer=0;
if(uart_rd =='2'){ //disable lock
RB5_bit=0xFF;
if(buzzer!=1){
buzzertest();
}
}//end if
} //end outer if
} //end while
}//end main
void buzzertest(){
while(1){
RB1_bit = 0xFF; //buzzer
Delay_ms(1000);
RB1_bit = 0x00; //buzzer
Delay_ms(1000);
if (UART1_Data_Ready())
break;
}//end while loop
}
Can please anyone help me solving this?
You're setting
buzzer
to 0 outside theif(uart_rd='0')
block. So when you come to theif(uart_rd='2')
block,buzzer
is always 0 and so theif(buzzer!=1)
block is always called.Have you tried stepping through this with a debugger? It would show up this kind of thing easily. You could also change those
if
blocks either to aswitch
statement or a series ofif
/else if
statements to avoid these sorts of issues.