You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
1.3 KiB
88 lines
1.3 KiB
10 years ago
|
//
|
||
|
// Basic Sonar example
|
||
|
//
|
||
|
|
||
|
#include <avr/io.h>
|
||
|
#include <avr/interrupt.h>
|
||
|
#include <util/delay.h>
|
||
|
#include <stdint.h>
|
||
|
#include <stdbool.h>
|
||
|
|
||
|
#include "lib/uart.h"
|
||
|
#include "lib/sonar.h"
|
||
10 years ago
|
#include "lib/stream.h"
|
||
10 years ago
|
|
||
|
|
||
|
|
||
|
// 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);
|
||
|
|
||
10 years ago
|
while(sonar_busy) {
|
||
10 years ago
|
// Sonar is asynchronous
|
||
|
// Here we just wait for it to complete
|
||
|
}
|
||
|
|
||
10 years ago
|
int16_t res = sonar_result;
|
||
10 years ago
|
|
||
|
|
||
|
// Print
|
||
|
if (res < 0) {
|
||
10 years ago
|
put_str(uart, "NO OBSTACLES\r\n");
|
||
10 years ago
|
} else {
|
||
10 years ago
|
put_i16f(uart, res, 1); // one decimal place
|
||
|
put_str(uart, " cm\r\n");
|
||
10 years ago
|
}
|
||
|
|
||
|
|
||
|
// a delay...
|
||
|
_delay_ms(500);
|
||
|
}
|
||
|
}
|