Skip to content

Instantly share code, notes, and snippets.

@sosnovskyas
Created February 20, 2018 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sosnovskyas/3ea21807fc2ce318b871628d25a5e4ce to your computer and use it in GitHub Desktop.
Save sosnovskyas/3ea21807fc2ce318b871628d25a5e4ce to your computer and use it in GitHub Desktop.
ATtiny 5/10: Read ADC2 (PB2) and output servo PWM signal on PB0 and PB1
/*
Read ADC2 (PB2) and output servo signal on PB0 and PB1.
ATtiny5 or 10 at default 1MHz.
*/
#include <avr/io.h>
int main(void)
{
// ADC channel 2
ADMUX = 2;
// Disable digital input on PB2
DIDR0 = (1<<ADC2D);
// Enable ADC, presc 1:8 for 125kHz ADC-clock
ADCSRA = (1<<ADEN) | (1<<ADPS1) | (1<<ADPS0);
// PB0 and 1 output.
DDRB = (1<<PB0) | (1<<PB1);
// Timer0 50Hz PWM, 1us tick, mode 14 with ICR0 as TOP.
ICR0 = 19999; // 1MHz / 50Hz - 1
// Start with 1.5 ms pulse-width
OCR0A = OCR0B = 1500;
// OC0A and OC0B non inverting PWM, mode bit 1
TCCR0A = (1<<COM0A1) | (1<<COM0B1) | (1<<WGM01);
// mode bits 2 and 3, presc 1:1
TCCR0B = (1<<WGM03) | (1<<WGM02) | (1<<CS00);
while(1)
{
uint8_t i;
uint16_t adc4;
// Take four ADC samples, add them in adc4
for (i = 0, adc4 = 0; i < 4; i++)
{
// Start a conversion
ADCSRA |= (1<<ADSC);
// wait until it's finished
while (ADCSRA & (1<<ADSC))
; // Nothing
adc4 += ADCL;
}
// Set PWM to 990 to 2010 ms from ADC.
OCR0A = 990 + adc4;
// OCR0B "inverted" servo signal
OCR0B = 2010 - adc4;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment