Showing posts with label Arduino Counter. Show all posts
Showing posts with label Arduino Counter. Show all posts

Friday, October 19, 2012

Lap Timer Build Along Part 4 - Adding the IR Detector

The final part of the lap timer build along is also the easiest part, involving only the IR Detector and an optional LED with current limiting resistors.

The previous steps can be found in the project index section of RC Arduino -
http://rcarduino.blogspot.com/p/project-index.html

A good introduction to IR Detectors is provided on the Ada Fruit website here -

http://learn.adafruit.com/ir-sensor

To start our build we need a small section of strip board and a set of three wires for power, ground and IR Out.

These can be soldered to the strip board so each leg of the IR Detector is connected through the copper strips of the strip board to one strand of the cable. In the picture I have used a section of ribbon cable, the cable should be long enough to suite your application, for example long enough to mount the detector on the steering column support of your Kart and allow you to attach the main unit to the steering wheel - don't make the cable longer than necessary it will only get in the way and may pick up interference.

Notice that the IR Detector is facing away from the connecting wires and that there is room for some additional components between the detector and the connecting wires, this is to allow us to add an indicator ID.

Reverse Side View

Next we add a 10K current limiting resistor between the output of the IR Detector and the wire we will be connecting to our Arduino interrupt pin.

For this resistor to have any effect we need to cut the copper track underneath the resistor so that the current has to pass through the resistor, a 3mm or 3.5mm drill bit will do this nicely.

Reverse view showing the cut in the copper track beneath the 10K resistor

Next we need to add the current limiting resistor for our indicator LED, I am using 560, but anything from 500 to 800 Ohms should be fine. This resistor connects from the row with the VCC Pin of the detector to the row below the Vout pin. From here we can also add two short lengths of connecting wire for our indicator LED, on wire should come from the VOut track and another from the track below VOut where we have just added the resistor.

This is to allow use to add an indicator LED which will light whenever the unit receives an IR Signal, this is useful as it will let you know if there is environmental interference such as reflected sunlight or fluorescent lighting.

At this point you should have the following circuit -
You can now add an indicator LED of whatever colour will be most visible in your application. To connect the LED, the long leg should be connected to the length of wire which is soldered to the same row as the 560 Ohm resistor, the shorted leg should be connected to same the same row as the Vout pin of the IR Detector.

You can test this set up immediately by connecting 4 to 6 volts to the circuit, the positive voltage should be applied to the top row, the ground should be connected to the middle row. If you use a TV Remote or the Transponder from part 3 of the build along, you should see the LED Light, if not, try swapping the LED around incase it was soldered in reverse.

This is essentially the same circuit as shown in the Lady Ada tutorial -

http://learn.adafruit.com/ir-sensor/testing-an-ir-sensor

Assuming that you have tested your detector correctly, we can now connect it to the Lap Timer.

To do this we need to connect the Vcc wire (top pin/wire in the picture assuming the detector is facing away from the connecting wires) to the 5V supply of the Arduino. Next we need to connect the center wire to the ground of the Arduino. Finally connect the bottom wire to digital pin 2 of your Arduino.

Congratulations, you have now finished the electronics however to be able to use the lap timer you need to build a small enclosure for the detector, without this sunlight and many type of indoor lighting will saturate your detector so that it is unable to detect signals. As I am based in Dubai where the sun is always fierce I have gone as far as spraying the inside of my enclosure with ultra matt camouflage paint. You can see the enclosures I have used in the following clips of the timer in action, not that the indicator LED is on the outside of the enclosure where we can see it - you knew that already right ?

Build Along Lap Timer in action complete with IR Detector as built in this post


I have recently added a few extensions to the project including a count down mode and support for external audio, you can see the new menu options and see them in action at the track in the following two clips -


New Menu Options
At the track with external audio enabled


The external audio option uses an LM386 based amplifier to drive external speakers. You can use this IC to add big sound to any Arduino project, here is a link to the circuit as used in the Lap Timer -

http://rcarduino.blogspot.com/2012/08/adding-audio-to-arduino-projects.html

If you would like the latest code, contact me through the arduino forum for a zip file containing the full project.

Future Developments - I am considering adding support for three additional transponder types -

1) Magnetic - I am told that many Kart Tracks use a magnetic strip under the track which lapping Karts detect using a window sensor such as you would use for home security.
2) Commercial Beacons - The commercial beacons used at many auto racing tracks use a well know pattern of pulses, it would make sense to support this pattern allowing users to 'arrive and drive' without having to place your own transponder around the track.
3) User selected pulse length - Allow the user to choose a pulse length, this would allow two or three systems to be used alongside each other. All of the calculations needed to build your own unique transponder are linked in previous parts of build along.

Stay tuned.

Duane B

Sunday, August 19, 2012

Adding Audio to Arduino Projects

Sometimes a project just needs to be louder, whether its a synthesizer, alarm clock, autonomous robot or the RC Arduino lap timer.

In the case of the lap timer, I want people in the club house to know when a lap record has been broken, it all adds to the pressure and the fun of racing.

One incredibly simple solution to getting more sound from a micro controller is the LM386 series of amplifier chips. These can give project quality audio for less than a dollar.  They even make a passable one dollar MP3 docking station and are the basis of the 'little gem' guitar amplifier.


LM386-N4 Big Audio In A Tiny Package - 

Parts List - 
1 x LM386-N4
2 x 100uf Electrolytic Capacitors
1 x 0.1uf Capacitor
1 x 100Ohm Resistor
1 x 10K Potentiometer

Circuit pictured is used to drive a PC Speaker in the RCArduino Lap Timer project - See the video.


The LM386 Minimal Components Circuit

The datasheet for the LM386-N4 which I am using provides some example circuits but these require non standard capacitors - by non standard I really mean that most of us keep 'decade' capacitors meaning the tens - 0.01uf , 0.1uf, 1uf, 10uf, 100uf. The sample circuits require 250uf and 0.05 uf capacitors.

As I didn't have these values, I built the sample circuits with 100's in series and 0.1's in parallel to get 200uf and 0.05uf. After playing with the circuit for a while I removed the series and parallel capacitors leaving just a single 100uf and one 0.01 uf capacitor. This variation of the recommended circuit works perfectly well, and is now included in the built version of the RCArduino Lap Timer.

So for a super simple chip to add quality sound and volume to a project order a few LM386N4's its amazing how many projects can benefit from bigger sound when its as easy as this.


Simplified LM386N4 Circuit To Drive PC Speakers From A Micro controller

Caution : The new generation of 32 Bit ARM chips used by the Arduino Due are less able to sink and source current than the AVR Chips used in the 8-bit Arduinos. A number of users have reported burnt out DAC (Digital To Analog Converter) outputs while using the Arduino Due. It is suggested that a series current limiting resistor should be used between the Arduino Due DAC Outputs and external circuitry.

There are currently a number of topics covering the Arduino DAC outputs and pin protection in general on the Arduino Due forum - http://arduino.cc/forum/index.php/board,87.0.html

The circuit below shows a suitable circuit for 8-bit AVR Arduinos - UNO, Mega, Leonardo etc.



 Data sheet with alternative circuits and full application details -

http://www.ti.com/lit/ds/symlink/lm386.pdf

The RCArduino Five Dollar Synthesizer, Arduino audio played through the LM386 amplifier driving a PC Speaker

Project details here -
http://rcarduino.blogspot.com/2012/10/five-dollar-synthesiser.html

 


The Auduino
The five dollar synth is a great project if your up to re purposing an existing keyboard, if not, you really have to build an Auduino.

The Auduino is one of the best sounding Arduino Audio projects, it is also the easiest to build requiring only five potentiometers.
 
Update: The first video is my own Auduino, any others I post are enhanced Auduino's which for one reason of another are nicer than mine, so skip mine and have a look at what everyone else is able to get from this simple sketch through the use of clever additions -

My Own Audiuno - 
Totally standard Audiuno code with output direct to a PC Speaker using the LM386 Amplifier circuit shown in this post.


Auduino By DenkiTribe

A very musical Audiuno based jam -

The project enclosure seems to be closely related to a pizza box but we can forgive that for the very musical session. Modifications are obviously the stylus based pitch control and the addition of external echo.



Auduino By 'TheHangMansAxe'

As far as I can tell, thehangmansaxe has enhanced his auduino with two additions

1) An LED and LDR that 'gates' the output, for those of us with no audio background, gating is essentially connecting and disconnecting a signal from the output.

In DIY Projects LDRs are often used for this as they have an output which is a rough approximation to many stringed instrument where the initial note is loud but then decays away over time. LDRs initially react to light very quickly, but when the light is removed, they settle more slowly allowing the not to linger slightly.

At around the 1 minute mark the user shows the LED switching on and off through the side of the instrument.


2) Thermin style note sensing. The user does not provide any details, but I assume that the note is being controlled by infra red bouncing off the users hand. The original Audiuno design provided on tinkerkit uses five analogue inputs to control the sound, generally these are connected to puts but can also be replaced by any device capable of providing and analogue output.

UPDATE - 25/10/2012 - Added this section to explain how the Auduino works. It needs diagrams and rewritting for reduced length and increased clarity.


How does the Auduino work ?
While I am a big fan of the Auduino, its not that well documented. It is described as a 'granular synthesiser', I spent a lot of time reading up on granular synthesis and reverse engineering the code before I was able to understand exactly how the Auduino generates its particular sound.

A granular synthesizer is usually described as generating sound by rapidly repeating a small 'grain' of sound and if you read through the Auduino code you will certainly find repeated reference to grains however what and where are the grains ?

Outside of the Auduino project, the term grain is most often used to describe grains of sound which are sampled from real life speech, instruments or environmental sounds - a grain is a very short sample in the order of 1/10 to 1/10,000th of a second as opposed to the sampled vocal and drum tracks that you might be familiar with.

Pereshaped points out in the comments below that the synthesis technique used by the Auduino is closer to 'Vosim' that grain synthesis.
 
The Auduino code is actually very clever and efficient, instead of storing a grain the Auduino generates the grain in realtime using a simple counter.
The variables grainPhaseAcc and grainPhaseAcc2 are basically just counters. They count up, then down at a rate determined by grainPhaseInc and grainPhaseInc2. If you were to plot the value of these variables over time each one would give you a triangle waveform.

  // Increment the phase of the grain oscillators
  grainPhaseAcc += grainPhaseInc;
  grain2PhaseAcc += grain2PhaseInc;

The two variables grainPhaseInc and grainPhaseInc2 are directly controlled by two of the Auduino inputs. Adjust the potentiometers up and down and you will hear a frequency component of the output rise and fall in pitch as the relevant triangle wave increases and decreases in frequency.

These are not our main pitch control though, vary them up and down and while the quality of the note will change dramatically, the pitch of the note will stay the same.

The note pitch is controlled by the variable synchPhaseInc. This has an interesting job to do, it controls the rate at which yet another counter - synchPhaseAcc overflows. Whenever this counter overflows, it resets the the two triangle waveforms to an initial synchronized position. This periodic resetting of the two waveforms is what causes repetition of a repeatable 'grain' of sound. The rate of repetition gives the output its pitch.


Its actually a lot more interesting than that, what makes the Auduino sound so engaging is that as you increase or decrease the output frequency so you adjust the amount of the grain that is repeated adding additional layers of colour to the output tones.

The final stroke of genius in the Auduino design (its not my design so I am allowed to say this) is the use of the pentatonic scale. Instead of allowing you to choose any frequency you like the main pitch control is mapped to the musical scale know as the pentatonic scale. This is what gives the Auduino a kind of bluesy sound and ensures that you will never hit a duff note. For more on the pentatonic scale check out the wikipedia article.


A picture speaks a thousand works and Miro2424 has kindly posted this video of an Auduino in action on youtube. In the video you will see the two triangle waves superimposed on each other, you will see and hear how they are used to create both the pitch and the tone of the sound.


Auduino By Miro2424
I have been trying to learn how an 'addative', 'grain' or 'frequency on frequency' synthesizer like the Auduino works. This clip from Miro2424 shows the Auduino output visualised through what I am guessing is a high end PC Sound card. In the clip you can see the two triangular grains super imposed on each other and how they are used to create and vary the sound. Very happy to have found this, it makes it all easier to understand.




Everyone should have at least one Auduino, if you have a spare Arduino and 5 potentionmeters you can build one right now - http://code.google.com/p/tinkerit/wiki/Auduino

UPDATE - 01/02/2012
Here is another great variation on the Auduino by Moshang, this one also has the coolest name 'The Groovesizer' and also the best looking case of any I have seen so far.

The groovesizer extends the Auduino with a built in sixteen step sequencer.

Full details here - http://moshang.net/soundjeweler_blog/technique/groovesizer-diy-16-step-sequencer-and-synth/




UPDATE - 16/11/2012 - The Auduino is the original work of Peter Knight, the project home page appears to be inactive. RCArduino has previously reported a bug fix to the project which has not been updated. On the basis that the project is no longer active, a full version of the Auduino code including the bug fix and an added echo effect can be found on RCArduino -
http://rcarduino.blogspot.com/2012/11/auduino-with-delay.html
These two RC Arduino projects can also be built using identical hardware, upload them to your Auduino for a change of scene, you can always re upload the Auduino when your finished.

http://rcarduino.blogspot.com/2012/10/arduino-modular-synthesizer-part-one.html



Duane B

Friday, August 17, 2012

Arduino Serial Servos

Creative Commons License
RCArduinoSerialServos by DuaneB is licensed under a Creative Commons Attribution-NonCommercial 3.0 Unported License.
Based on a work at rcarduino.blogspot.com.


It is possible to drive a bank of upto 10 independently controlled servos using just two Arduino pins. The concept can easily be expanded to 20 servos using only four pins.

There is very little that is new in the world and this technique definitely isn't new but here is my explanation and a ready made library and test sketch for you to try.

If you have read any of the previous posts on the RCArduino blog you will know that a servo is controlled using a pulse which is between 1000 and 2000 microseconds long.

Its all here if you need a refresher -
http://rcarduino.blogspot.com/2012/01/how-to-read-rc-receiver-with.html

At its most basic a pulse is simply setting a pin high and then setting it low again. The Servo library created by Michael Margolis does this in software, its well know, well supported and a very flexible library.

Here is a quick overview of the Servo Library
http://rcarduino.blogspot.com/2012/01/can-i-control-more-than-x-servos-with.html

Flexibility comes at a cost.

If you were to review the source code of the servo library you would see that a lot of the code is there to give users the choice of which pins to use. By moving this flexibility to hardware we can reduce the code required to generate servo signals and also reduce the Arduino resources to just two pins for each bank of ten servos. The code is also much small and faster as a result.

How does it work ?
The RCArduinoSerialServo library relies on a 4017 decade counter - its an incredibly simple chip that is often used in introductory courses to create LED Chasers.

Sample LED Chaser Using 4017 - The first line represent the clock signal, lines O0 to O9 represent the 4017 outputs. The clock switches the outputs on in sequence giving an LED chaser effect.



The chip has 10 outputs which are switched on in sequence based on a clock signal. This is very similar to what the Arduino Servo Library does in software, it sets the first servo pin high, then sets a timer to come back and set the pin low to end the pulse, at the same time, its sets the next servo pin high to begin that servos pulse, then sets the timer to come back again to end this new pulse and begin the next one.

We can achieve the same result using the 4017 Decade counter and only two Arduino pins. The pin we are most interested in is the clock pin of the 4017 Counter. When we pulse the clock pin, the 4017 will switch the current pin low and set the next pin high - effectively ending the current servo pulse and beginning a new one - just like the hardware LED Chaser above and the Servo Library does in software.

In order to control servos all we need to do is generate a clock pulse based on the required servo pulse durations.

Serial Servos - By controlling the space between clock pulses, we can control the pulse duration for each of 10 channels using only 1 Arduino pin.




Taking a closer look at the clock pulse - 

Here we can clearly see that the clock pulse itself is very short, around 1 millionth of a second. However by varying the time between clock pulses we can control the time that each channel is high - the channel pulse width. 

The second and third clock pulse are clearly closer together and this can be seen in the narrow pulse width of channel O1 and also the servo angle, in the previous image.




Here is the Timer1 Output compare servo routine where it all happens -

// if we are at then end of our ten channels - pulse the reset pin to reset the counter to channel 0 
// else pulse the clock pin to advance to the next channel
// the setOutPutTimerForPulseDuration function sets the timer1 output compare register
// so that it will trigger this function again when we need to end the current pulse and 
// begin the next one, thats it, thats all we need to do to control 10 servos with 2 pins.

void CRCArduinoSerialServos::OCR1A_ISR()
{
  if(m_sCurrentOutputChannel >= RC_CHANNEL_OUT_COUNT)
  {
    m_sCurrentOutputChannel = 0;

    PORTB|=16;

    CRCArduinoSerialServos::setOutputTimerForPulseDuration();

    PORTB^=16;
 }
 else
 {
    PORTB|=2;

    CRCArduinoSerialServos::setOutputTimerForPulseDuration();

    PORTB^=2;
  }
    m_sCurrentOutputChannel++;
}

Looking at the generated assembly code, the whole thing takes only two millionths of a second thats only slightly little longer than a single call to digitalWrite.

Here is a sample sketch which you can use to try the library, it outputs 10 channels from a digital pin 9, reset is through pin 12.

For you to be able try things for yourself, it also reads the pulse width back in using an interrupt on pin2. Each channel is set to a pulse width 100 microseconds greater than the previous channel - ie. Channel 0 = 1000, Channel 1 = 1100, Channel 9 = 1900. You can use the interrupt on pin 2 to read the pulse width back in from each of your channels and show it in the serial monitor.

Don't forge that if you want to drive servos with your Arduino you will need to provide separate power to the servos, here's why -

http://rcarduino.blogspot.com/2012/04/servo-problems-with-arduino-part-1.html

http://rcarduino.blogspot.com/2012/04/servo-problems-part-2-demonstration.html

Install the CPP and .H files into a library folder named RCArduinoChannels

Here is a basic schematic, its that simple - total cost - about 30 cents.



The Sketch -

Note that if the code looks long, it isnt, its all comments, for each line of code there are many many lines of comments for you to read should you wish.

Duane B

// RCArduinoSerialServos by DuaneB is licensed under a Creative Commons Attribution-NonCommercial 3.0 Unported License.
// Based on a work at rcarduino.blogspot.com.

#include <RCArduinoSerialServos.h>

volatile uint32_t ulRiseTime;
volatile uint32_t ulPulseWidth;

void setup()
{
  Serial.begin(9600);
  Serial.println("RCArduinoSerialServos");
 
  // set the channels
  for(uint16_t nChannel = 0;nChannel < RC_CHANNEL_OUT_COUNT;nChannel++)
  {
    CRCArduinoSerialServos::writeMicroseconds(nChannel,1000+(nChannel*100));
  }

  CRCArduinoSerialServos::begin();
 
  attachInterrupt(0,calcPulse,CHANGE);
}

void loop()
{
  delay(10);

  if(ulPulseWidth != 0)
  {
    // disable interrupts so that our pulse value does not get overwritten while we try and read it
    uint8_t sReg = SREG;
    cli();
   
    // take a local copy of the pulse witdth so that we can reenable interrupts as soon as possible
    uint32_t ulLocalPulseWidth = ulPulseWidth;
   
    // clear the pulse width so that we will only pick up new values written by calcPulse rather
    // than keep printing old values.
    ulPulseWidth = 0;
   
    // turn interrupts back on
    SREG = sReg;
   
    // print the pulse width
    Serial.println(ulLocalPulseWidth);
  }
 
}

// Read pulse width applied to digital pin 2 (interrupt 0)
void calcPulse()
{
  if(digitalRead(2))
  {
    ulRiseTime = micros();
  }
  else
  {
    ulPulseWidth = micros()- ulRiseTime;
  }
}




The .H File -


/*****************************************************************************************************************************
// RCArduinoChannels by DuaneB is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
//
// http://rcarduino.blogspot.com
//
*****************************************************************************************************************************/


#include "Arduino.h"

// Dont change this,
// if you do not need ten channels, just leave some of the 4017 pins disconnected.
#define RC_CHANNEL_OUT_COUNT 10

// Minimum and Maximum servo pulse widths, you could change these,
// Check the servo library and use that range if you prefer
#define RCARDUINO_SERIAL_SERVO_MIN 1000
#define RCARDUINO_SERIAL_SERVO_MAX 2000

//////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// CRCArduinoSerialServos
//
// A class for generating signals in combination with a 4017 Counter
//
// Output upto 10 Servo channels using just digital pins 9 and 12
// 9 generates the clock signal and must be connected to the clock pin of the 4017
// 12 generates the reset pulse and must be connected to the master reset pin of the 4017
//
// The class uses Timer1, as this prevents use with the servo library
// The class uses pins 9 and 12
// The class does not adjust the servo frame to account for variations in pulse width,
// on the basis that many RC transmitters and receivers designed specifically to operate with servos
// output signals between 50 and 100hz, this is the same range as the library
//
// Use of an additional pin would provide for error detection, however using pin 12 to pulse master reset
// at the end of every frame means that the system is essentially self correcting
//
// Note
// This is a simplified derivative of the Arduino Servo Library created by Michael Margolis
// The simplification has been possible by moving some of the flexibility provided by the Servo library
// from software to hardware.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////

class CRCArduinoSerialServos
{
public:
    CRCArduinoSerialServos();

    // configures timer1
    static void begin();

    // called by the timer interrupt service routine, see the cpp file for details.
    static void OCR1A_ISR();

    // called to set the pulse width for a specific channel, pulse widths are in microseconds - degrees are for wimps !
    static void writeMicroseconds(uint8_t nChannel,uint16_t nMicroseconds);

protected:
    // this sets the value of the timer1 output compare register to a point in the future
    // based on the required pulse with for the current servo
    static void setOutputTimerForPulseDuration();

    // Records the current output channel values in timer ticks
    // Manually set by calling writeChannel, the function adjusts from
    // user supplied micro seconds to timer ticks
    volatile static uint16_t m_unChannelSignalOut[RC_CHANNEL_OUT_COUNT];

    // current output channel, used by the timer ISR to track which channel is being generated
    static uint8_t m_sCurrentOutputChannel;

    // two helper functions to convert between timer values and microseconds
    static uint16_t ticksToMicroseconds(uint16_t unTicks);
    static uint16_t microsecondsToTicks(uint16_t unMicroseconds);
};



The CPP File - 


/*****************************************************************************************************************************
// RCArduinoSerialServos by DuaneB is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
//
// http://rcarduino.blogspot.com
//
*****************************************************************************************************************************/

#include "arduino.h"
#include "RCArduinoSerialServos.h"

/*----------------------------------------------------------------------------------------

This is essentially a derivative of the Arduino Servo Library created by Michael Margolis

As the technique is very similar to the Servo class, it can be useful to study in order
to understand the servo class.

What does the library do ? It uses a very inexpensive and common 4017 Counter IC
To generate pulses to independently drive up to 10 servos from two Arduino Pins

As previously mentioned, the library is based on the techniques used in the Arduino Servo
library created by Michael Margolis. This means that the library uses Timer1 and Timer1 output
compare register A.

OCR1A is linked to digital pin 9 and so we use digital pin 9 to generate the clock signal
for the 4017 counter.

Pin 12 is used as the reset pin.

*/

// Timer1 Output Compare A interrupt service routine
// call out class member function OCR1A_ISR so that we can
// access out member variables
ISR(TIMER1_COMPA_vect)
{
    CRCArduinoSerialServos::OCR1A_ISR();
}

void CRCArduinoSerialServos::OCR1A_ISR()
{
    // If the channel number is >= 10, we need to reset the counter
    // and start again from zero.
    // to do this we pulse the reset pin of the counter
    // this sets output 0 of the counter high, effectivley
    // starting the first pulse of our first channel
  if(m_sCurrentOutputChannel >= RC_CHANNEL_OUT_COUNT)
  {
    // reset our current servo/output channel to 0
    m_sCurrentOutputChannel = 0;

    // pulse reset on the counter - we set it high here
    PORTB|=16;

    // set the duration of the output pulse
    CRCArduinoSerialServos::setOutputTimerForPulseDuration();

    // finish the reset pulse - we set it low here
    PORTB^=16;
 }
 else
 {
  // pulse the clock pin high
    PORTB|=2;

    // set the duration of the output pulse
    CRCArduinoSerialServos::setOutputTimerForPulseDuration();

    // finish the clock pulse - set it back to low
    PORTB^=2;
  }
    // done with this channel so move on.
    m_sCurrentOutputChannel++;
}

// After we set an output pin high, we need to set the timer to comeback for the end of the pulse
void CRCArduinoSerialServos::setOutputTimerForPulseDuration()
{
  OCR1A = TCNT1 + m_unChannelSignalOut[m_sCurrentOutputChannel];
}

// updates a channel to a new value, the class will continue to pulse the channel
// with this value for the lifetime of the sketch or until writeChannel is called
// again to update the value
void CRCArduinoSerialServos::writeMicroseconds(uint8_t nChannel,uint16_t unMicroseconds)
{
    // dont allow a write to a non existent channel
    if(nChannel > RC_CHANNEL_OUT_COUNT)
        return;

  // constraint the value just in case
  unMicroseconds = constrain(unMicroseconds,RCARDUINO_SERIAL_SERVO_MIN,RCARDUINO_SERIAL_SERVO_MAX);

  // disable interrupts while we update the multi byte value output value
  uint8_t sreg = SREG;
  cli();
 
  m_unChannelSignalOut[nChannel] = microsecondsToTicks(unMicroseconds);

  // enable interrupts
  SREG = sreg;
}

uint16_t CRCArduinoSerialServos::ticksToMicroseconds(uint16_t unTicks)
{
    return unTicks / 2;
}

uint16_t CRCArduinoSerialServos::microsecondsToTicks(uint16_t unMicroseconds)
{
 return unMicroseconds * 2;
}

void CRCArduinoSerialServos::begin()
{
    // set the pins we will to outputs
    pinMode(9,OUTPUT);
    pinMode(12,OUTPUT);

    // pulse reset
    digitalWrite(12,HIGH);
    digitalWrite(12,LOW);

    TCNT1 = 0;              // clear the timer count  

    // Initilialise Timer1
    TCCR1A = 0;             // normal counting mode
    TCCR1B = 2;     // set prescaler of 64 = 1 tick = 4us

    // ENABLE TIMER1 OC1A INTERRUPT
    TIFR1 |= _BV(OCF1A);     // clear any pending interrupts;
    TIMSK1 |=  _BV(OCIE1A) ; // enable the output compare interrupt 

    OCR1A = TCNT1 + 4000; // Start in two milli seconds
}

// See the .h file
volatile uint16_t CRCArduinoSerialServos::m_unChannelSignalOut[RC_CHANNEL_OUT_COUNT];
uint8_t CRCArduinoSerialServos::m_sCurrentOutputChannel;