From c277b2d85f3915133d76b9bfba3310b93d5602ed Mon Sep 17 00:00:00 2001 From: mandlm Date: Sun, 14 Feb 2016 19:02:59 +0100 Subject: [PATCH] Interrupt-based measuring --- UltraSonic/dist/main.cpp | 96 ++++++++++++++++++++++------------------ 1 file changed, 52 insertions(+), 44 deletions(-) diff --git a/UltraSonic/dist/main.cpp b/UltraSonic/dist/main.cpp index 15f8c54..d964463 100644 --- a/UltraSonic/dist/main.cpp +++ b/UltraSonic/dist/main.cpp @@ -1,12 +1,37 @@ #include "environment.h" #include +#include #include #include #include "ShiftRegister.h" #include "KS0066.h" +#include "Pin.h" + +volatile bool measuring = false; +volatile int16_t dist = 0.0; + +ISR(INT1_vect) +{ + if (PIND & (1 << PD3)) + { + measuring = true; + TCNT1 = 0; + } + else if (measuring == true) + { + dist = TCNT1 * 0.09175; + + measuring = false; + } +} + +ISR(TIMER1_COMPA_vect) +{ + measuring = false; +} int main(void) { @@ -15,65 +40,48 @@ int main(void) ShiftRegister shiftRegister(&PORTC, PC4, &PORTC, PC2, &PORTC, PC3); KS0066 lcd(shiftRegister); + // led ports to output + DDRD |= (1 << PD6) | (1 << PD5); + lcd.set("Ultra-sonic"); - DDRB |= (1 << PB0); // PB0 trigger output - DDRB &= ~(1 << PB1); // PB1 pulse input + DDRD |= (1 << PD4); // PD4 trigger output + DDRD &= ~(1 << PD3); // PD3 pulse input // Timer 1, normal mode TCCR1A = 0; + TCCR1B |= (1 << WGM12); // CTC // Timer 1, clk/64 prescaler TCCR1B |= (1 << CS10) | (1 << CS11); - _delay_ms(2000); + // Timer 1, output compare interrupt 1A + TIMSK |= (1 << OCIE1A); + + // Timer 1, compare value + OCR1A = 30000; + + _delay_ms(500); lcd.clear(); + // INT1, on change + GICR |= (1 << INT1); + MCUCR |= (1 << ISC10); + + sei(); + while (true) { - uint8_t errorNum = 0; + PORTD |= (1 << PD4); + _delay_ms(25); + PORTD &= ~(1 << PD4); + _delay_ms(25); - PORTB |= (1 << PB0); - _delay_us(15); - PORTB &= ~(1 << PB0); - _delay_us(20); + char buffer[16]; + sprintf(buffer, "%3i cm", dist); + lcd.set(buffer); - TCNT1 = 0; - while ((PINB & (1 << PB1)) == 0 && errorNum == 0) - { - if (TCNT1 > 60000) - { - errorNum = 1; - lcd.set("Timeout"); - } - } - - if (errorNum == 0) - { - TCNT1 = 0; - - while ((PINB & (1 << PB1)) != 0 && errorNum == 0) - { - if (TCNT1 > 60000) - { - errorNum = 2; - lcd.set("No object"); - } - } - - if (errorNum == 0) - { - uint16_t ticks = TCNT1; - - uint16_t cm = (ticks * 1.835) / 20.0; - - char buffer[16]; - sprintf(buffer, "%3i cm", cm); - lcd.set(buffer); - } - } - - _delay_ms(200); + _delay_ms(250); } }