// https://www.adnbr.co.uk/articles/adc-and-pwm-basics
// code: https://gist.github.com/adnbr/9289235
#define F_CPU 9600000
#define LED PB1
#include <avr/io.h>
void pwm_setup(){
TCCR0B |= (1<<CS01); // prescale 8
TCCR0A |= (1<<WGM01) | (1<<WGM00);// fast PWM
// Clear OC0B output on compare match, upwards counting.
TCCR0A |= (1<<COM0B1);
}
void pwm_write(int val)
{
OCR0B = val;
}
void adc_setup(void)
{
// set the ADC input to PB2/ADC1
ADMUX |= (1<<MUX0); // mux1/0=01 select adc1
ADMUX |= (1<<ADLAR);
// set the prescaler 128 , adps2 add by me
ADCSRA |= (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0)|(1<<ADEN);
}
int adc_read(void)
{
ADCSRA |= (1<<ADSC); // start conversion
while(ADCSRA&(1<<ADSC));
return ADCH;
}
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);
}
}
ーーーーーーーーーINT0ーーーーーーーーーーーーー
// https://kurobekoblog.com/attiny_gaibuwarikomi
#include <avr/interrupt.h>
volatile byte state = 0;
int16_t cnt;
ISR(INT0_vect){
state = 1;
}
void sw_up(){
switch(state){
case 0:
break;
case 1:
cnt = 1000;
state = 2;
break;
case 2:
cnt --; // avoid chattering
if(cnt == 0){
PORTB ^= 0b00000001; // toggle led on off
state = 0;
}
}
}
void setup(){
DDRB |= 0b0000001 ; // pb0 output
PORTB |= 0b0000010 ; // pb1 input pullup
MCUCR &= ~0b00000011; // if low level, int0 occur
GIMSK |= (1<<INT0) ; // int0 enable
sei();
}
void loop(){
sw_up();
}
注:pb3をinput pullupでスイッチにつなぎ、スイッチはグランドともつなぐ
#include <avr/interrupt.h>
#include <avr/sleep.h>
#define F_CPU 960000UL
#define LED PB0
//#define SWITCH PINB3 どっちでもうごくが。。。。
#define SWITCH PB3
ISR(PCINT0_vect){ // 0番台の割り込みがpcint0~5ピンに割当られているようだ
if(PINB & _BV(SWITCH)){
PORTB ^= _BV(LED);
}
}
int main(void)
{
DDRB |= _BV(LED); // SET PORT B0 AS OUTPUT(ALL OTHERS ARE INPUT)
PORTB = 0b0001000 ; // pb3(switch) input pullup
PCMSK |= _BV(SWITCH); // SET PCINT MASK TO LISTEN TO PORT B3
GIMSK |= _BV(PCIE);
sei();
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
for (;;){
sleep_mode();
}
}
ーーーーーーPCINTもう一つーーーーーーーーー
0 件のコメント:
コメントを投稿