// https://adnbr.co.uk/articles/adc-and-pwm-basics
/* ---------------------------------------------------------------------
* PWM LED Brightness control for ATtiny13.
* Datasheet for ATtiny13: http://www.atmel.com/images/doc2535.pdf
*
* Pin configuration -
* PB1/OC0B: LED output (Pin 6)
* PB2/ADC1: Potentiometer input (Pin 7)
*
* ~100 bytes.
*
* Find out more: http://bit.ly/1eBhqHc
* -------------------------------------------------------------------*/
// 9.6 MHz, built in resonator
#define F_CPU 9600000
#define LED PB1
#include <avr/io.h>
void adc_setup (void)
{
// Set the ADC input to PB2/ADC1
// admux https://garretlab.web.fc2.com/arduino/inside/hardware/arduino/avr/cores/arduino/wiring_analog.c/analogRead.html
ADMUX |= (1 << MUX0); // analog pin select // ADC1 i.e. PB2
ADMUX |= (1 << ADLAR); // 左詰めで結果をいれる?
// Set the prescaler to clock/128 & enable ADC
// At 9.6 MHz this is 75 kHz.
// See ATtiny13 datasheet, Table 14.4.
// ADEN::ADC-OK, ADPS1 AND ADPS0 TO 1/8 ? (1<<ADPS2) | が抜けている?
ADCSRA |= (1 << ADPS1) | (1 << ADPS0) | (1 << ADEN);
}
int adc_read (void)
{
// https://awawa.hariko.com/chira-ura/atmega168-chapter23-jp.html
// Start the conversion
ADCSRA |= (1 << ADSC); // ADC START CONVERSION
// Wait for it to finish
while (ADCSRA & (1 << ADSC)); // 読み取りおわったらADCSRAはゼロとなる?
return ADCH; // 上位8ビットのみ返す
}
void pwm_setup (void)
{ // https://usicolog.nomaki.jp/engineering/avr/avrPWM.html
// Set Timer 0 prescaler to clock/8.
// At 9.6 MHz this is 1.2 MHz.
// See ATtiny13 datasheet, Table 11.9.
TCCR0B |= (1 << CS01); // prescale 1/8
// Set to 'Fast PWM' mode
TCCR0A |= (1 << WGM01) | (1 << WGM00);
// Clear OC0B output on compare match, upwards counting.
TCCR0A |= (1 << COM0B1);
}
void pwm_write (int val)
{
OCR0B = val;
}
int main (void)
{
int adc_in;
// LED is an output.
DDRB |= (1 << LED);
adc_setup();
pwm_setup();
while (1) {
// Get the ADC value
adc_in = adc_read();
// Now write it to the PWM counter
pwm_write(adc_in);
}
}
0 件のコメント:
コメントを投稿