Skip to content

Instantly share code, notes, and snippets.

@mattstep
Created January 23, 2012 05:10
Show Gist options
  • Save mattstep/1660772 to your computer and use it in GitHub Desktop.
Save mattstep/1660772 to your computer and use it in GitHub Desktop.
ADC to PWM using an ATtiny13a for driving a plasma speaker.
#include <avr/io.h>
int main(void)
{
// Setup ADC2 as an input, using an internal voltage reference, with left bit alignment in ADCH|ADCL
ADMUX = (1 << REFS0) | (1 << MUX1) | (1 << ADLAR);
// Enable the ADC, Start the conversion, Autotrigger, and /16 prescale
ADCSRA = (1 << ADEN) | (1 << ADSC) | (1 << ADATE) | (1 << ADPS2);
// Setup fast PWM output on OCB0
OCR0B = 0x80; //Initialize OCR0B to result in 1/2 duty cycle.
DDRB = (1 << PB1); // Set the direction of PortB pin 1 (pin 6 on pdip) as output
// Use OCR0B as the PWM output, run in Fast PWM Mode with a 0xFF top
TCCR0A = (1 << COM0B1) | (1 << WGM01) | (1 << WGM00);
TCCR0B = (1 << CS00); // Run at full internal clock speed, no prescaling
unsigned char floor = 0x08;
while(1)
{
unsigned char adc_input = ADCH;
if (adc_input > 0xFF - floor)
OCR0B = 0xFF;
else
OCR0B = adc_input + floor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment