+volatile struct
+{
+ uint8_t pwm_int: 1;
+ uint8_t adc_int: 1;
+ uint8_t tmr_int: 1;
+}
+intflags;
+
+static void inline led_on()
+{
+ DDRB |= _BV( PB5 );
+ led_is_on = 1;
+}
+
+static void inline led_off()
+{
+ led_is_on = 0;
+ DDRB &= ~_BV( PB5 );
+// ADCSRA &= ~(_BV(ADIE) | _BV(ADIF));
+}
+
+/* ------------ Logging/Debugging ----------- */
+
+unsigned char debug_state EEMEM;
+
+static void inline debug_setstate(unsigned char val)
+{
+ eeprom_write_byte(&debug_state, val);
+}
+
+#define LOG_BUFFER 64
+uint16_t log_buffer[LOG_BUFFER] EEMEM;
+unsigned char log_buffer_count;
+uint16_t log_buffer2[LOG_BUFFER];
+volatile unsigned char stop = 0;
+
+static void inline init_log()
+{
+ debug_setstate(1);
+ log_buffer_count = 0;
+}
+
+static void log_word(uint16_t word) {
+ if (log_buffer_count >= LOG_BUFFER)
+ return;
+
+ // eeprom_write_word(&log_buffer[log_buffer_count], word);
+ log_buffer2[log_buffer_count] = word;
+ log_buffer_count++;
+
+ if (log_buffer_count == LOG_BUFFER) {
+ unsigned char i;
+ for (i=0; i < LOG_BUFFER; i++) {
+ eeprom_write_word(&log_buffer[i],
+ log_buffer2[i]);
+ }
+ debug_setstate(0x42);
+ }
+}
+
+/* ------------ Timer ----------- */
+
+volatile uint16_t clock = 0;
+
+static void inline init_tmr()
+{
+ TCCR0A = _BV(WGM00);
+ TCCR0B = _BV(CS02) | _BV(CS00); // 1 kHz
+ OCR0A = 12; // 100 Hz
+ TIMSK |= _BV(OCIE0A);
+ DDRA |= _BV( PA0 );
+
+ clock = 0;
+}
+
+static void inline tmr_handler()
+{
+ unsigned char c = clock & 0x1F;
+ unsigned char c1 = clock & 0xFF;
+
+ ++clock;
+#if 0
+ if (c == 10 || c == 30)
+ led_on();
+
+ if (c == 20 || c == 40)
+ led_off();
+#endif
+
+ if (c == 0x02 || c == 0x08)
+ led_on();
+ if (c == 0x05 || c == 0x0b)
+ led_off();
+
+ if ((clock & 0x7F) == 0x1F) {
+ if (c1 < 0x80) {
+ adc_exp = 0x80;
+ } else {
+ adc_exp = 0x20;
+ }
+ }
+ ADCSRA |= _BV(ADSC);
+#if 0
+ if (led_is_on && adcval != 0xFFEE) {
+ adcval = 0xFFEE;
+
+ ADCSRA |= _BV(ADIF) | _BV(ADIE) | _BV(ADSC);
+ }
+#endif
+}
+
+ISR(TIMER0_COMPA_vect)
+{
+ tmr_handler();
+}
+
+/* ------------ PWM ----------- */
+
+static void inline init_pwm()