Advertisement
uwezi

20210309_attiny13_timer

Mar 9th, 2021
817
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. /*
  2.  * 20210309_tiny13_timer.c
  3.  *
  4.  * Created: 2021-03-09 21:08:38
  5.  * Author : uwezi
  6.  */
  7.  
  8. // output on PB3, active high
  9. // trigger on PB1 / INT0 active low
  10.  
  11. #define F_CPU 1200000UL
  12.  
  13. #include <avr/io.h>
  14. #include <util/delay.h>
  15. #include <avr/interrupt.h>
  16. #include <util/atomic.h>
  17.  
  18. volatile int16_t timeout = 0;
  19. volatile int16_t settime = 0;
  20.  
  21. ISR(INT0_vect)
  22. {
  23.   timeout = settime;
  24.   PORTB |= (1 << PB3);
  25. }
  26.  
  27.  
  28. // timer interrupt about 586/s
  29. ISR(TIM0_OVF_vect)
  30. {
  31.   if (timeout > 0)
  32.   {
  33.     timeout --;
  34.   }
  35.   else
  36.   {
  37.     PORTB &= ~(1 << PB3);
  38.   }
  39. }
  40.  
  41.  
  42. int main(void)
  43. {
  44.   int16_t dummy;
  45.   DDRB   = (1 << PB3);
  46.   // pull-up on PB1
  47.   PORTB |= (1 << PB1);
  48.  
  49.   // ADC channel ADC2
  50.   // internal ref
  51.   // normal adjustment
  52.   // 1:8 prescaler 150 kHz
  53.   ADMUX  = (0 << REFS0) | (0 << ADLAR) | (1 << MUX1) | (0 << MUX0);
  54.   ADCSRA = (1 << ADEN) | (0 << ADSC) | (0 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
  55.   // first conversion
  56.   ADCSRA |= (1 << ADSC);
  57.   while (ADCSRA & (1 << ADSC)) { }
  58.   settime = ADC;
  59.  
  60.   // timer 0 normal counting
  61.   // 1:8 prescaler
  62.   // 1.2 MHz / 8 / 256 = 585.9375 Hz
  63.   TCCR0A = 0b00000000;
  64.   TCCR0B = (0 << CS02) | (1 << CS01) | (0 << CS00);
  65.   TIMSK0 = (1 << TOIE0);
  66.  
  67.   // falling edge triggers INT0
  68.   MCUCR |= (1 << ISC01) | (0 << ISC00);
  69.   GIMSK |= (1 << INT0);
  70.   sei();
  71.  
  72.   while (1)
  73.   {
  74.     // update settime from resistor setting
  75.     ADCSRA |= (1 << ADSC);
  76.     while (ADCSRA & (1 << ADSC)) { }
  77.     dummy = 7*settime + ADC;
  78.     dummy = dummy / 8;  
  79.     ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
  80.     {
  81.       settime = dummy;
  82.     }      
  83.     _delay_ms(100);
  84.   }
  85. }
  86.  
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement