#include #include //see http://www.engblaze.com/microcontroller-tutorial-avr-and-arduino-timer-interrupts/ long prev_sound_input_event;//when the prev sound input was detected in microseconds volatile long prev_signal_output_event;//when the prev signal output was generated in microseconds int val = 0; // variable to store the analog read read int prev_val= 0; // variable to store the previous analog read read void setup() { Serial.begin(115200); pinMode(8, OUTPUT); //initialze analog read analogReference(EXTERNAL); prev_val = analogRead(0); val = analogRead(0); // initialize Timer1 cli(); // disable global interrupts TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // same for TCCR1B //(# timer counts + 1) = (target time) / (timer resolution) //(# timer counts + 1) = (1.0 s) / (6.4e-5 s) //(# timer counts + 1) = 15625 //(# timer counts) = 15625 - 1 = 15624 float target_time = 1.0;//seconds float timer_resolution = 6.4e-5;//seconds int timer_counts = target_time/timer_resolution - 1; // set compare match register to desired timer count: OCR1A = timer_counts; // turn on CTC mode: TCCR1B |= (1 << WGM12); // Set CS10 and CS12 bits for 1024 prescaler: TCCR1B |= (1 << CS10); TCCR1B |= (1 << CS12); // enable timer compare interrupt: TIMSK1 |= (1 << OCIE1A); sei(); // enable global interrupts } void loop() { // read the input pin val = analogRead(0); //sound detected if difference is large enough if (abs(val-prev_val) > 3){ //record sound input event time long sound_input_event = micros(); //only measure delay if sound events are more than 0.5s apart if(abs(sound_input_event-prev_sound_input_event) > 500000){ prev_sound_input_event = sound_input_event; Serial.print("D"); long total_latency = sound_input_event - prev_signal_output_event; Serial.println(total_latency); } prev_val = val; } } ISR(TIMER1_COMPA_vect) { prev_signal_output_event = micros(); digitalWrite(8, !digitalRead(8)); Serial.print("A"); Serial.println(prev_signal_output_event); }