This repository has been archived on 2024-12-15. You can view files and clone it, but cannot push or open issues or pull requests.
AVR-Stuff/UltraSonic/dist/main.cpp

86 lines
1.3 KiB
C++
Raw Permalink Normal View History

#include "environment.h"
#include <avr/io.h>
2016-02-14 18:02:59 +00:00
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdio.h>
#include "ShiftRegister.h"
#include "KS0066.h"
2016-02-14 18:02:59 +00:00
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)
{
DDRC |= (1 << PC4) | (1 << PC3) | (1 << PC2);
ShiftRegister shiftRegister(&PORTC, PC4, &PORTC, PC2, &PORTC, PC3);
KS0066 lcd(shiftRegister);
2016-02-14 18:02:59 +00:00
// led ports to output
DDRD |= (1 << PD6) | (1 << PD5);
lcd.set("Ultra-sonic");
2016-02-14 18:02:59 +00:00
DDRD |= (1 << PD4); // PD4 trigger output
DDRD &= ~(1 << PD3); // PD3 pulse input
// Timer 1, normal mode
TCCR1A = 0;
2016-02-14 18:02:59 +00:00
TCCR1B |= (1 << WGM12); // CTC
// Timer 1, clk/64 prescaler
TCCR1B |= (1 << CS10) | (1 << CS11);
2016-02-14 18:02:59 +00:00
// Timer 1, output compare interrupt 1A
TIMSK |= (1 << OCIE1A);
// Timer 1, compare value
OCR1A = 30000;
_delay_ms(500);
lcd.clear();
2016-02-14 18:02:59 +00:00
// INT1, on change
GICR |= (1 << INT1);
MCUCR |= (1 << ISC10);
sei();
while (true)
{
2016-02-14 18:02:59 +00:00
PORTD |= (1 << PD4);
_delay_ms(25);
PORTD &= ~(1 << PD4);
_delay_ms(25);
2016-02-14 18:02:59 +00:00
char buffer[16];
sprintf(buffer, "%3i cm", dist);
lcd.set(buffer);
2016-02-14 18:02:59 +00:00
_delay_ms(250);
}
}