|
How to get started with microcontrollers - Part 2
Interfacing with a computer, controlling motors, servos etc.
|
|
|
Example 2.2 - Fading led
Thing to learn: basic usage of PWM (Pulse-width modulation)
Wikipedia - Pulse-width modulation
Next we fade a led by using PWM. Basically we are flashing the led very fast and we control the brightness by
changing the duty cycle of pulses (on and off ratio). For example if we set the PWM to a duty cycle of 50%, the
led is on for half of the time and off for the other so it looks like its running on half brightness.
Parts:
- ATiny45
- 100 nF capacitor
- Red led
- 270 ohm resistor, current limiting resistor for the led (use LedCalc to calculate the right resistor for different leds)

Example 2.2

Example 2.2
/**
* MetkuMods - http://metku.net/
* How to get started with AVR microcontrollers, part 2
* Example 2.2 - Fading led
*
* Author: Aki Korhonen
* Date: 2009-04-29
*/
// If clock speed isn't set in the project settings then it is set here
#ifndef F_CPU
#define F_CPU 1000000UL // 1 MHz
#endif
#include <avr/io.h>
#include <inttypes.h>
#include <util/delay.h>
// Led at PB0, OCR0A
#define LED 0
// Min and max values for the PWM
// You can fine tune how bright and dim the led goes
// Minimum for MIN is 0 and maximum for MAX is 255
#define PWM_MIN 0
#define PWM_MAX 128
int main(void)
{
DDRB = 0xFF;
PORTB = 0x00;
// Value for the register and step size
// "value" equals brightness of the led
// 0 = off | 255 = full brightness
uint8_t value = 0;
uint8_t step = 1;
// -------------------------
// Initialize PWM
// 8-bit PWM, Phase correct
// 8 bits give us 256 levels of brightness
TCCR0A |= (1<<WGM00);
// Clear OC0A/OC0B on Compare Match
// Set OC0A/OC0B at BOTTOM (non-inverting mode)
TCCR0A |= (1<<COM0A1);
// Set prescaler to 8
// 1 MHz / 8*256 = ~490 Hz PWM frequency
TCCR0B |= (1<<CS01);
// -------------------------
// The program fades the led from off to on and vice versa
while(1)
{
// Write the value to the Output Compare Register A
OCR0A = value;
// Increment the value by step
value += step;
// If we reach the maximum value, invert the direction and vice versa
if(value >= PWM_MAX)
step *= -1;
else if(value <= PWM_MIN)
step = 1;
// Wait for 40 ms
_delay_ms(40);
}
return 0;
}
|