Tuesday, October 21, 2008

Arduino: Custom Analog Voltage

If you’re like me, you always want what you can't have. Today it's an analog voltage output on Arduino's on pin 12.



The beauty of open source hardware and the Arduino is that there's a ton built-in functions. However, for a Pin Visualizer project I was working on I needed to output an analog voltage on a pin that didn't have hardware PWM.

So here's is a way to put an Analog Voltage on any pin.


Parts:

1. Arduino
2. 500 ohm resistor
3. 1uF Capacitor

Code:

/****************************/
/* Title: PWM on any pin */
/* By: Chris Ladden */
/* www.liquidware.org */
/****************************/

/* Analog output pin */
#define ANALOG_PIN 12

/* The PWM period. For smaller output caps, make this shorter */
#define PWM_PERIOD 100

void setup()
{
/* Make the pin an output */
pinMode(ANALOG_PIN, OUTPUT);
}

/* 20 = 20% duty cycle = 1.0 VDC */
/* 50 = 50% dutyCycle = 1.2 VDC */
/* 70 = 70% duty cycle = 3.5 VDC */
unsigned char dutyCycle=70;
volatile unsigned char x;

void loop()
{
/* Pin output, high */
digitalWrite(ANALOG_PIN, HIGH);
for (x=0;x

/* Pin output, low */
digitalWrite(ANALOG_PIN,LOW);
for (x=0;x< (PWM_PERIOD-dutyCycle);x++) { ; }
}

No comments: