I'm trying to figure out how to create some non-blocking code to strobe some RGB leds with analogwrite 7 times a second; I'm really not to sure how to go about this. If anybody could give me some help that'd be great! :)
What you want can be achieved with your MCUs timers and their associated interrupts. Timers are basically counters that run inside your hardware and they run decoupled from your code. Since one usually knows how fast these timers tick (e.g. how long it takes to count from one to two and so on) you can specify events that happen when a certain amount of timer ticks passed. I suggest you have a look at SimpleTimer and Timer1 (the second page is only for ATmega168/328) Both pages include some code samples where they specify some method that will be called every x milliseconds. |
|||||
|
Timers are the best way to go, (much) less overhead and you don't have to worry about it elsewhere in your code (other than managing variable use between your main loop and your ISRs). But I do have a habit of doing things the hard way in code first and then move to timers once I've got it the way I'd like. Here is sample code to flash the on board LED X times per second, I have calculated it to mean, ON 7 times per second and OFF 7 times as well (meaning, there is a change of state 14 times per second). This code isn't efficient, it doesn't take into consideration that the value is already set or not, it just writes the value that it should be right now. Finally, to go to analogWrite and use PWM, just change:
to
code:
Remember there is overhead with digital (and analog) writes, so (as I mentioned) you could check to see if the value is set already or not and skip the write. |
|||
|
analogWrite()
doesn't calldelay()
. – Ignacio Vazquez-Abrams Jun 1 '14 at 18:18