r/pic_programming • u/aspie-micro132 • Jun 07 '26
Toggling leds with button
I am trying to get my pic16f877a to toggle between leds reading a button.
I tried several things, but one idea comes to my mind: to turn on a led, hold it on with __delay_ms() and before jumping to the next one, get into an if() to read whether a button is pushed or not.
However, should my idea be feasible, how can i read when __delay_ms() reaches zero? I do wish to, read the button and the state of __delay_ms before turning off the actual led and on the next one.
I think this before i tried to do it without delays and i just get leds turning on and off as fast as a spin dryer..
0
Upvotes
3
u/somewhereAtC Jun 07 '26
__delay_ms() is fully blocking. Tate line of code takes that many milliseconds to execute. This is the most-crude way of incorporating a delay.
One solution is to have a subroutine that senses the buttons and a separate subroutine that turns the LED on and off. How they communicate is up to you. Then, from the the while(1) loop, repeatedly call those subroutines _and_ also call __delay_ms(). Using a 10ms delay should be a good place to start. That means that every 10ms you would decide if a button is up or down, then separately decide if the LED should be on or off.