Interrupt-based measuring

This commit is contained in:
mandlm 2016-02-14 19:02:59 +01:00
parent ca31fcc1ed
commit c277b2d85f

View file

@ -1,12 +1,37 @@
#include "environment.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdio.h>
#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;
PORTB |= (1 << PB0);
_delay_us(15);
PORTB &= ~(1 << PB0);
_delay_us(20);
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;
PORTD |= (1 << PD4);
_delay_ms(25);
PORTD &= ~(1 << PD4);
_delay_ms(25);
char buffer[16];
sprintf(buffer, "%3i cm", cm);
sprintf(buffer, "%3i cm", dist);
lcd.set(buffer);
}
}
_delay_ms(200);
_delay_ms(250);
}
}