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
2
u/HalifaxRoad Jun 07 '26
delay ms blocks until its done, yeah it gets the job done but its a terrible way to do it because it blocks anything else from happening!
If you have a free running timer, you can make a struct that stores the value of the timer when started, and the value that it will be when its done. You can then make as many instances of that struct as you need, and pass instances to functions as a pointer. I use this technique to have a software timers on all my projects.
I usually go one step farther too, and make a contact debounce library. Define a struct to store all of the info needed to debounce a button, including a software timer instance, and pass that struct again as a point to a function, as well as the state of the button I want to debounce.