Friday, March 16, 2012

Arduino as Analog Function Generator

I realized that outputting functions over the serial port is a little too much overhead.  However, my MFCs can be controlled by analog signals on input pin 4 in the miniDIN.  So I decided to see if the Arduino can output reasonable signals by PWM.

I generated a sin using PWM and filtered the signal using a simple RC circuit (tau = 1 msec).  It took a little fiddling with the Control Register of the appropriate timer (I had to remove prescaling) to get good output PWM frequency, but it looks pretty good.

This is my test code:


unsigned long t0;


void setup() {
    pinMode(9, OUTPUT); 
    t0 = millis();
    
    TCCR1B = 0x01;
}


void loop() {
    analogWrite(9, (int) (255.0 * 0.5 *(1.0 + sin( (float) ((millis()-t0) % 1000) * 2.0 * 3.14 * 5.0 / 1000))));    
}

UPDATE: click here for explanation of my choice of RC filter

Along the way, I found this useful blog with info about the Arduino:
http://softsolder.com
http://softsolder.com/2010/09/05/arduino-mega-1280-pwm-to-timer-assignment/
http://softsolder.com/2009/02/21/changing-the-arduino-pwm-frequency/ 

No comments:

Post a Comment