I have written a small PIC program in mikroC for turning on and off an led with same push button. That is pressing the switch will turn on the led and if the same switch is pressed again the led will turn off. Here is the program that I wrote
void main()
{
TRISB=0X00;
TRISC=OXFF;
PORTB=0X00;
PORTC=0XFF;
while(1)
{
if (portc.f3==0) /*checking if the switch is pressed*/
portb = ~portb; /*if the switch is pressed, the led will go off if it is already on or the led will go on if the it is already off*/
portc = 0xff;
}
}
}
another version of the same program that I have written is
void main()
{
int flag=0;
TRISB=0X00;
TRISC=OXFF;
PORTB=0X00;
PORTC=0XFF;
while(1)
{
if (portc.f3==0 && flag==0)
{
portb = 0xff;
flag=1;
portc=0xff
}
if (portc.f3==0 && flag==1)
{
porb=0x00;
flag=0;
portc=0xff;
}
}
}
in both cases it doesn't works as expected. when i press switch the led turns on but after some time it turns off itself (without pressing the switch again).
please help me and make me know whats wrong with my programs if any.
3 Answers 3
Try a 10k pullup resistor on the input pin. Unconnected inputs can float undesirably.
schematic
simulate this circuit – Schematic created using CircuitLab
Try debouncing in software.
I would try something like this for the loop:
while(1)
{
//Check to see whether the switch is pressed and flag is set.
//Then, toggle the port and reset the flag.
if (portc.f3==0 && flag==1)
{
portb = ~portb;
flag = 0;
}
//Now, wait until the switch is released until the port can be toggled again.
//This way, if you hold the button down, it will not keep toggling the port
//repeatedly. It will only toggle it once, then wait for the button to be released.
else if (portc.f3==1 && flag==1)
{
flag = 1;
}
}
In addition, as mentioned earlier, a pull-up resistor is a must, and debouncing of some sort is a good idea. When the switch is pressed it will tend to switch back and forth between high and low very rapidly a few times during the transition. You can alleviate this problem via software or hardware.
This looks like a good debouncing reference. In software, it can be as simple as setting a delay in the poll routine. In hardware, the RC debounce circuit is an elegant solution.
use:
delay_ms(500);
after setting the led on and off
-
\$\begingroup\$ This does not address the issue in the question \$\endgroup\$W5VO– W5VO2015年12月16日 05:03:39 +00:00Commented Dec 16, 2015 at 5:03
portc=0xff
\$\endgroup\$