---

Showing posts with label library. Show all posts
Showing posts with label library. Show all posts

Tuesday, January 31, 2012

Arduino Timer Library

I have developed a simple to use library that gets around a load of problems that arise when you start trying to do much inside 'loop'. It can change pin values or run a callback function. It seems like such an obvious thing that I doubt its original, so I would like to hear of similar projects.

DOWNLOAD Thanks to Jack Christensen for hosting it and the improvements and version management he has added to it.

 


The library does not interfere with the built-in timers, it just uses 'millis' in a crude type of scheduler to decide when something needs doing.

Examples

The Arduino 'delay' function is both a blessing and a curse. Its great for showing beginners how to make an LED flash. But as soon as you get more complex and start slowing down your 'loop' function  you will run into problems.

A classic example is turning a relay on for 10 minutes. The 'delay'-way looks like this:

int pin = 13;

void setup()
{
  pinMode(13, OUTPUT);
  digitalWrite(pin, HIGH);
  delay(10 * 60 * 60 * 1000);
  digitalWrite(pin, LOW);
}

void loop()
{
}

The disadvantage of the delay approach is that nothing else can go on while the 'delay' is happening. You cannot update a display, or check for key presses for example.

My 'Timer' library version looks like this:


#include "Timer.h"

Timer t;
int pin = 13;

void setup()
{
  pinMode(pin, OUTPUT);
  t.pulse(pin, 10 * 60 * 1000, HIGH); // 10 minutes  
}

void loop()
{
  t.update();
}

The 'pulse' method takes arguments of a pin to change, the period to change it for and its initial state.

The call to t.update() will take a matter of microseconds to run, unless the appropriate period of time has passed.

Lets look at another example that uses two timer events. One to flash an LED and another that reads A0 and displays the result in the Serial Monitor.


#include "Timer.h"

Timer t;
int pin = 13;

void setup()
{
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  t.oscillate(pin, 100, LOW);
  t.every(1000, takeReading);
}

void loop()
{
  t.update();
}

void takeReading()
{
  Serial.println(analogRead(0));
}

The first thing to notice is that we are using a callback function called 'takeReading'. We connect it to the Timer using the 'every' command, which in this case, will call the function every second.

We have also attached another event to the timer using the method 'oscillate'. This will cause the LED to toggle state every 100 milliseconds.

Each of the events has an integer ID associated with it, so that you can stop an event, as we do in this example below, which will write to the serial monitor every 2 seconds, flash the LED and after 5 seconds, stop the LED flashing fast, and flash it 5 times slowly.


#include "Timer.h"

Timer t;

int ledEvent;

void setup()
{
  Serial.begin(9600);
  int tickEvent = t.every(2000, doSomething);
  Serial.print("2 second tick started id=");
  Serial.println(tickEvent);
  
  pinMode(13, OUTPUT);
  ledEvent = t.oscillate(13, 50, HIGH);
  Serial.print("LED event started id=");
  Serial.println(ledEvent);
  
  int afterEvent = t.after(10000, doAfter);
  Serial.print("After event started id=");
  Serial.println(afterEvent); 
  
}

void loop()
{
  t.update();
}

void doSomething()
{
  Serial.print("2 second tick: millis()=");
  Serial.println(millis());
}


void doAfter()
{
  Serial.println("stop the led event");
  t.stop(ledEvent);
  t.oscillate(13, 500, HIGH, 5);
}


You can attach up to 10 events to a timer.

Installation

As with all libraries, unzip the file into the 'libraries' folder in your Arduino directory, which will be in something like 'My Documents\Arduino' on Windows, 'Documents/Arduino' on Mac etc. If this is the first library you have installed, you will need to create a directory there called 'libraries'.

The library is compatible with both Arduino 1.0 and earlier versions.

Reference


int every(long period, callback)
 Run the 'callback' every 'period' milliseconds.
 Returns the ID of the timer event.

int every(long period, callback, int repeatCount)
 Run the 'callback' every 'period' milliseconds for a total of 'repeatCount' times.
 Returns the ID of the timer event.

int after(long duration, callback)
 Run the 'callback' once after 'period' milliseconds.
 Returns the ID of the timer event.

int oscillate(int pin, long period, int startingValue)
 Toggle the state of the digital output 'pin' every 'period' milliseconds. The pin's starting value is specified in 'startingValue', which should be HIGH or LOW.
 Returns the ID of the timer event.

int oscillate(int pin, long period, int startingValue, int repeatCount)
 Toggle the state of the digital output 'pin' every 'period' milliseconds 'repeatCount' times. The pin's starting value is specified in 'startingValue', which should be HIGH or LOW.
 Returns the ID of the timer event.

int pulse(int pin, long period, int startingValue)
 Toggle the state of the digital output 'pin' just once after 'period' milliseconds. The pin's starting value is specified in 'startingValue', which should be HIGH or LOW.
 Returns the ID of the timer event.

int stop(int id)
 Stop the timer event running.
 Returns the ID of the timer event.

int update()
 Must be called from 'loop'. This will service all the events associated with the timer.

Conclusion

Have a go with the library, please let me know what you think.


About the Author
These are my books. Click on the image below to find out more about them.

About the Author
These are my books. Click on the image below to find out more about them.


                                                                                                                           

Friday, September 16, 2011

New Arduino Library for Sparkfun Si4703 FM Receiver Breakout Board

The Sparkfun Si4703 FM Receiver Breakout Board is a great little FM radio, complete with RDS and a 100mW stereo amp.



There is example code for using it and top marks to Nathan Seidle from Sparkfun for working out how to use the pesky thing from the largely opaque datasheet for the receiver chip.

I have been making myself the 'ultimate' FM receiver. Arduino-based and using nice controls, solar-charging of battery with charging data and an LCD display for the RDS data. I will post on this when its finished.

The software engineer in me railed at just hacking away at Nathan's example. So I put his code in a library and also fixed some of the problems with RDS and did a bit of tidying.

You can download it from here. Continuing Nathan's licensing arrangement, I also offer it as 'Beer-ware'. If you are feeling extremely grateful then by all means buy one of my books (see right panel).

Here is an example app, just connect up the three pins at the top of the sketch but remember Vcc for the breakout board is 3.3V NOT 5V. 5V will kill it:


#include <Si4703_Breakout.h>
#include <Wire.h>


int resetPin = 2;
int SDIO = A4;
int SCLK = A5;


Si4703_Breakout radio(resetPin, SDIO, SCLK);
int channel;
int volume;
char rdsBuffer[10];


void setup()
{
  Serial.begin(9600);
  Serial.println("\n\nSi4703_Breakout Test Sketch");
  Serial.println("===========================");  
  Serial.println("a b     Favourite stations");
  Serial.println("+ -     Volume (max 15)");
  Serial.println("u d     Seek up / down");
  Serial.println("r       Listen for RDS Data (15 sec timeout)");
  Serial.println("Send me a command letter.");
  


  radio.powerOn();
  radio.setVolume(0);
}


void loop()
{
  if (Serial.available())
  {
    char ch = Serial.read();
    if (ch == 'u') 
    {
      channel = radio.seekUp();
      displayInfo();
    } 
    else if (ch == 'd') 
    {
      channel = radio.seekDown();
      displayInfo();
    } 
    else if (ch == '+') 
    {
      volume ++;
      if (volume == 16) volume = 15;
      radio.setVolume(volume);
      displayInfo();
    } 
    else if (ch == '-') 
    {
      volume --;
      if (volume < 0) volume = 0;
      radio.setVolume(volume);
      displayInfo();
    } 
    else if (ch == 'a')
    {
      channel = 930; // Rock FM
      radio.setChannel(channel);
      displayInfo();
    }
    else if (ch == 'b')
    {
      channel = 974; // BBC R4
      radio.setChannel(channel);
      displayInfo();
    }
    else if (ch == 'r')
    {
      Serial.println("RDS listening");
      radio.readRDS(rdsBuffer, 15000);
      Serial.print("RDS heard:");
      Serial.println(rdsBuffer);      
    }
  }
}


void displayInfo()
{
   Serial.print("Channel:"); Serial.print(channel); 
   Serial.print(" Volume:"); Serial.println(volume); 
}



Here is the public part of the class definition.


class Si4703_Breakout
{
  public:
    Si4703_Breakout(int resetPin, int sdioPin, int sclkPin);
    void powerOn(); // call in setup
void setChannel(int channel);   // 3 digit channel number
int seekUp(); // returns the tuned channel or 0
int seekDown();
void setVolume(int volume); // 0 to 15
void readRDS(char* message, long timeout);
// message should be at least 9 chars
// result will be null terminated
// timeout in milliseconds




About the Author
These are my books. Click on the image below to find out more about them.