Last active
August 29, 2015 14:08
-
-
Save svenwltr/d18f43d9211f675070de to your computer and use it in GitHub Desktop.
ATmega 8 - PWM test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BUILDDIR=build | |
BASENAME=pwm_test | |
MMCU=atmega8 | |
all: clean compile burn | |
clean: | |
rm -f $(BUILDDIR)/$(BASENAME).elf | |
rm -f $(BUILDDIR)/$(BASENAME).hex | |
rmdir $(BUILDDIR) | |
compile: | |
mkdir -p $(BUILDDIR) | |
avr-gcc \ | |
-mmcu=$(MMCU) \ | |
-O3 \ | |
-o $(BUILDDIR)/$(BASENAME).elf \ | |
$(BASENAME).c | |
objcopy \ | |
-O ihex $(BUILDDIR)/$(BASENAME).elf \ | |
$(BUILDDIR)/$(BASENAME).hex | |
burn: | |
avrdude \ | |
-p m8 \ | |
-P /dev/ttyUSB0 \ | |
-c avr910 \ | |
-U flash:w:$(BUILDDIR)/$(BASENAME).hex:a |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define F_CPU 8000000UL | |
#include <avr/io.h> | |
#include <util/delay.h> | |
#include <math.h> | |
uint8_t pwm(uint8_t x) { | |
double fx = (double) x; | |
return pow(2.,8.*fx/256.)-1; | |
} | |
void set_rgb(uint8_t r, uint8_t g, uint8_t b) { | |
OCR2 = pwm(r); | |
OCR1A = pwm(g); | |
OCR1B = pwm(b); | |
} | |
int main (void) { | |
DDRB = (1<<PB1) | (1<<PB2) | (1<<PB3); // set output pins | |
DDRD = 0xff; | |
// configure 16 bit counter | |
TCCR1A = (1<<WGM10) | (1<<COM1A1) | (1<<COM1B1); // PWM, phase correct, 8 bit. | |
TCCR1B = (1<<CS11) | (1<<CS10); // Prescaler 64 = Enable counter | |
// configure 8 bit counter | |
TCCR2 = (1<<WGM20) | (1<<COM21) | (1<<CS22); // PWM, phase correct, 8 bit. | |
PORTD = pwm(0xff); | |
uint16_t step = 0; | |
while(1) { | |
uint8_t val = step&0xff; | |
uint8_t edge = (step>>8)&7; | |
PORTD = val; | |
step++; | |
switch(edge) { | |
// black | |
case 0: set_rgb(val, 0, 0); break; | |
// red | |
case 1: set_rgb(0xff, val, 0); break; | |
// orange | |
case 2: set_rgb(0xff-val, 0xff, 0); break; | |
// yellow | |
case 3: set_rgb(0, 0xff, val); break; | |
// green | |
case 4: set_rgb(val, 0xff, 0xff); break; | |
// white | |
case 5: set_rgb(0xff, 0xff-val, 0xff); break; | |
// purple | |
case 6: set_rgb(0xff-val, 0, 0xff); break; | |
// blue | |
case 7: set_rgb(0, 0, 0xff-val); break; | |
// black | |
} | |
_delay_ms(5); | |
}; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment