/ Published in: C
The code for my heartbeat electronic sculpture.
Built using AVR Studio 4 for the ATiny8.
Expand |
Embed | Plain Text
#include <avr/io.h> #include <util/delay.h> // Some macros that make the code more readable #define output_low(port,pin) port &= ~(1<<pin) #define output_high(port,pin) port |= (1<<pin) #define set_input(portdir,pin) portdir &= ~(1<<pin) #define set_output(portdir,pin) portdir |= (1<<pin) #define LON 1 #define LOF 0 #define LED_COUNT 12 uint8_t led_table[] = { LOF, PB0, PB1, LOF, PB1, PB0, LOF, PB0, PB2, LOF, PB2, PB0, LOF, PB0, PB4, LOF, PB4, PB0, LOF, PB1, PB2, LOF, PB2, PB1, LOF, PB1, PB4, LOF, PB4, PB1, LOF, PB2, PB4, LOF, PB4, PB2 }; void clear_leds() { set_input(DDRB, PB0); set_input(DDRB, PB1); set_input(DDRB, PB2); set_input(DDRB, PB4); } void set_led(uint8_t index, uint8_t state) { uint8_t i = (index * 3); uint8_t s = led_table[i]; uint8_t p1 = led_table[i + 1]; uint8_t p2 = led_table[i + 2]; set_output(DDRB, p1); set_output(DDRB, p2); if(state == LON) { output_low(PORTB, p1); output_high(PORTB, p2); } else { output_low(PORTB, p1); output_low(PORTB, p2); } } void delay_10us(uint8_t us) { uint8_t delay_count = F_CPU / 2000000; volatile uint8_t i; while (us != 0) { for (i=0; i != delay_count; i++); us--; } } void do_pwm_fade(uint8_t index, uint8_t start_duty, uint8_t end_duty, uint8_t rate) { uint8_t duty; uint8_t j; duty = start_duty; while (duty != end_duty) { for (j = 0; j < rate; j++) { set_led(index, LON); delay_10us(duty); set_led(index, LOF); delay_10us(255-duty); } if (start_duty < end_duty) duty++; else duty--; } } int main(void) { // initialize the direction of the B port to be outputs // on the 3 pins that have LEDs connected while(1) { for(int i=0; i < LED_COUNT; i++) { clear_leds(); do_pwm_fade(i, 0, 255, 1); do_pwm_fade(i, 255, 0, 1); } } }
Comments
Subscribe to comments
You need to login to post a comment.

include
include
// Some macros that make the code more readable
define output_low(port,pin) port &= ~(1
include
include
// Some macros that make the code more readable
define output_low(port,pin) port &= ~(1