Finally getting somewhere with electronics
Saturday, March 28th, 2009
I feel like I am finally getting somewhere with this electronics thing.
A month ago I bought an ATMega168 microcontroller from Spark Fun Electronics. Having programed for several years now I felt like venturing into microcontrollers.
So far I have made an LED blink, read the value of a potentiometer and now I have a tri color LED fading between all the different colors.
My next challenge is to control the speed of a motor, which is proving to be a bit difficult.
This is all hopefully leading to something useful. I have been thinking about an RC helicopter with an attached camera for arial photography but that is a little ways down the road to say the least.
To get the tri color led to work I used PWM (Pulse Width Modulation). as long as you keep the micro running fast enough it will not look like it’s blinking.
The key was that the led has 1 positive pin and 3 ground pins that control the individual colors. So when the voltage is lower, it is actually brighter.
I wired the positive lead (the longest) to VCC and each of the three grounds to an output pin on the ATMega168 through an appropriate resistor. the colors are a little uneven because I didn’t have precise enough resistors (red takes a different current than green and blue).
Source Code:
#include <avr/io.h>
#define STEPS 255
//change these to the pins you have connected to the led
#define RED 5
#define BLUE 4
#define GREEN 3
void ioinit(void); //Initializes IO
void fadePin(int pin, int destination);
//gentally fades a pin to destination. assumes starting at oposite value.
int main (void) {
ioinit(); //Setup IO pins and defaults
//zero is fully on because output pins are connected to ground pins
PORTC |= (1 << RED);
PORTC |= (1 << GREEN);
PORTC |= (1 << BLUE);
//start with red
fadePin(RED, 0);
//loop forever
while(1) {
fadePin(BLUE, 0); //purple
fadePin(RED, 1); //blue
fadePin(GREEN, 0); //turquist
fadePin(BLUE, 1); //green
fadePin(RED, 0); //yellow
fadePin(GREEN, 1); //red
}
return(0);
}
void fadePin(int pin, int destination) {
if(destination == 0)
destination = -1;
//i controls the PWM
int i=0;
for(float j=0.0f; j<1.0f; j+=0.0001f) {
i++;
if(i>STEPS)
i=0;
//destination makes everything negative if it is zero (before we change it)
if(i * destination < STEPS * j * destination) {
//turn pin on
PORTC |= (1 << pin);
} else {
//turn pin off
PORTC &= ~(1 << pin);
}
}
//make sure to end with the desired value
if(destination == 1) {
//turn pin on
PORTC |= (1 << pin);
} else {
//turn pin off
PORTC &= ~(1 << pin);
}
}
void ioinit (void) {
//1 = output, 0 = input
DDRC = 0b11111111; //All outputs on Port C
}
Filed under: Electronics
Leave a Reply