Today I posted an experimental class called PulsePattern on the playground for generating [HIGH LOW] pulse patterns with the help of Timer1.
The idea is to have an array of [LOW|HIGH] periods that is used by Timer1 as alarm trigger one by one. When alarm goes of a predefined pin flips from HIGH to LOW or vice versa. Timer1 is encapsulated by an instance of the class called PPGenerator, PP = PulsePattern of course. When all elements of the array are used it restarts at the begin of the array. The array can contain as many elements as you like (restricted by free memory of course)
Elaborated patterns can be placed into a pattern array and "played back" by the timer. PatternPlayer might be a better name? One can change the contents of the array runtime or reinitialize the PPGenerator with another array. A fun feature is using an array with an odd number of entries (try it).
Not implemented
Placing the pattern in an array is fast, but I am thinking of a callback function that returns the next period to the timer. It is much slower due to function call overhead but it can encapsulate the pattern array or calculate the next period e.g. based upon sensor values. e.g. increase frequency or duty cycle when dew point temperature drops.
The sample sketch explains how it can be used.
//
// FILE: SOS_demo2.pde
// AUTHOR: Rob Tillaart
// DATE: 2012-11-23
//
// PUPROSE: demo of the PulsePattern Library
// uses timer1
//
#include "PulsePattern.h"
uint16_t SOSpattern[] = {
500,500,500,500,500,1500, // S in morse
1500,500,1500,500,1500,1500, // O in morse
500,500,500,500,500,1500 }; // S in morse
uint8_t patternSize = 18;
uint8_t startLevel = LOW;
void setup()
{
Serial.begin(9600);
Serial.println("Start PulsePattern");
// as the prescaler = 1024 the periods of the pattern are a
// few percent less than a millisecond
PPGenerator.init(13, SOSpattern, patternSize, startLevel, PRESCALE_1024);
PPGenerator.start();
}
void loop()
{
// dummy code that does something in the foreground
Serial.println(millis());
delay(1000);
}
As always, ideas, comments and remarks are welcome!