int main(void)
{
DDRD = 0x00 ;
DDRB = DDRB | 0b00100000 ;
while (1)
{
while(!(PIND & (1<<6))){
PORTB |= 1<<PORTB5 ;
}
while((PIND & (1<<6))) {
PORTB &= ~(1<<PORTB5) ;
}
}
return 0;
}
I am trying to create a basic security system by using a switch that when broken is picked up by PIND7, then sets PB5. And Vicd versa, when the switch is set, the low signal is picked up by PIND7 then clears the bit on PB5.
The micro-controller is not having a problem when the switch is set, it clears the bit in PB5 immediately, but when the switch breaks, it takes about 30 seconds for the bit in PB5 to be set.
Thank you for any help you can give, I apologize if my code is sloppy I am just a beginner
Best Answer
A simple truth table usually helps a lot.
Here's my try at deciphering it from your text:
This truth table simply says, if PIND6 is 0, then PORTB5 should be 1, and "vice versa". In proper terms, PORTB5 is the logical NOT of PIND6.
This is the mathematical equation for what we want:
PORTB5 = !PIND6 which is the same as \$\text{PORTB}_5 = \overline{\text{PIND}_6}\$.
I don't think you want to have two while loops in your major while loop. That's not a good way for checking a state, since you can get stuck in them. As I believe you are getting.
What you should do instead is to either use an if statement or simply assigning PORTD, or use either of them together with a debounced input. I will show all three of them with some space between. You should not keep all three, you should choose one of them.
Here's some untested code:
So technically, just replace your while statements with if statements and learn the word "logical invert" and you'll be on the good side.
If you'd want to be pedantic about it, or "proper", then you should use interrupts together with internal timers, because they make the code more efficient. But this code will solve the problem as you have presented it.