From 256e96afc33aa76f7eadaa9727e487f487ba7e4a Mon Sep 17 00:00:00 2001 From: MightyPork Date: Thu, 30 Apr 2015 02:47:15 +0200 Subject: [PATCH] sonar example --- examples/Makefile | 4 +- examples/sonar_simple.c | 88 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 examples/sonar_simple.c diff --git a/examples/Makefile b/examples/Makefile index ded8c57..ace5778 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -11,14 +11,14 @@ EFUSE = 0x05 ## === Source files === # Main C file -MAIN = lcd_test.c +MAIN = sonar_simple.c # Extra C files in this folder LOCAL_SOURCE = # Library directory (with C files) EXTRA_SOURCE_DIR = lib/ # C files in the library directory -EXTRA_SOURCE_FILES = uart.c lcd.c +EXTRA_SOURCE_FILES = uart.c lcd.c sonar.c uart_ansi.c ## === Programmer === diff --git a/examples/sonar_simple.c b/examples/sonar_simple.c new file mode 100644 index 0000000..fceff97 --- /dev/null +++ b/examples/sonar_simple.c @@ -0,0 +1,88 @@ +// +// Basic Sonar example +// + +#include +#include +#include +#include +#include + +#include "lib/uart.h" +#include "lib/arduino_pins.h" +#include "lib/sonar.h" + + + +// All PCINT vectors must call sonar_handle_pci +ISR(PCINT0_vect) +{ + if (sonar_handle_pci()) return; + + // Here you can do your other stuff +} + +// This way, they are linked to PCINT0 +// so we can avoid code duplication +ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect)); +ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect)); + + + +// Timer overflow - if sonar has a timeout -> 0xFFFF in result. +ISR(TIMER1_OVF_vect) +{ + if (sonar_handle_t1ovf()) return; + + // ... +} + + + + +void main() +{ + // Init UART communication + uart_init(9600); + + + // Create and init Sonar instance + sonar_t so; + + // Args: pointer to your sonar_t, and 2 pin aliases - Trig & Echo + sonar_init(&so, A0, A1); + + // You can have more than one sonar connected, but only one can measure at a time + + + // Allow interrupts + sei(); + + + while(1) { + + // Measure + sonar_start(&so); + + while(sonar_busy()) { + // Sonar is asynchronous + // Here we just wait for it to complete + } + + int16_t res = sonar_result(); + + + + // Print + if (res < 0) { + uart_puts("NO OBSTACLES\r\n"); + } else { + uart_puti(res, 1); // one decimal place + uart_puts(" cm\r\n"); + } + + + // a delay... + _delay_ms(500); + } +}