About Ultrasonic Sensors:
An ultrasonic sensor module has an ultrasonic transmitter, receiver and a control circuit.
It has 4 pins:
Trigger
Echo
Vcc
Ground
When we give trigger signal, the module will send 8 cycles of 40kHz ultrasonic pulses. These pulses go into the air, and at the same time, the ECHO pin becomes HIGH. After reflection from any any object/obstacle on its path they are reflected back and are received by the receiver. Now the ECHO pin goes to LOW state.
So, our code has to perform two task:
1. Give Trigger Signal.
2. Based on the time for which ECHO pin remains HIGH, calculate the distance.
We can keep a note of time by two methods:
1. Polling. (Run a while loop).
2. Interrupt. (Stop the timer when ECHO pin becomes LOW).
An ultrasonic sensor module has an ultrasonic transmitter, receiver and a control circuit.
It has 4 pins:
Trigger
Echo
Vcc
Ground
When we give trigger signal, the module will send 8 cycles of 40kHz ultrasonic pulses. These pulses go into the air, and at the same time, the ECHO pin becomes HIGH. After reflection from any any object/obstacle on its path they are reflected back and are received by the receiver. Now the ECHO pin goes to LOW state.
So, our code has to perform two task:
1. Give Trigger Signal.
2. Based on the time for which ECHO pin remains HIGH, calculate the distance.
We can keep a note of time by two methods:
1. Polling. (Run a while loop).
2. Interrupt. (Stop the timer when ECHO pin becomes LOW).
Calculating Distance:
Velocity of ultrasonic signal = velocity of sound waves = v = 340 m/s.
Distance in cm = v * t (in microseconds) / 2.
d = t/58 cm.
Based on the above calculations, the code for Atmega32 is:
#include<avr/io.h>
#include<util/delay.h>
#include<compat/deprecated.h>
#include"uart.c"
#include"uart.h"
#include<avr\interrupt.h>
#include<stdlib.h>
uint8_t counter;
void ultraj(void);
int calculate(void);
void main()
{
DDRC = 0xFF;
PORTC = 0;
uart_init(UART_BAUD_SELECT(9600,F_CPU));
while(1)
{
ultraj();
}
}
void ultraj()
{
PORTC = 0xFF;
DDRA = 0x01;
char buf[40] = {0};
int distance;
cbi(PORTA,0);
_delay_us(10);
sbi(PORTA,0);
_delay_us(10);
cbi(PORTA,0);
TCNT0 = 0x00;
TIMSK = (1<<TOIE0);
cbi(PORTA,1);
sei();
while(!(PINA&(1<<1)));
TCCR0 = 0x03;
while(PINA&(1<<1));
TCCR0 = 0x00;
distance = calculate();
itoa(distance,buf,10);
uart_puts("disttnace : ");
uart_puts(buf);
uart_puts("\n\r");
_delay_ms(70);
}
int calculate()
{
int timea,timeb,timec,timed;
int dist;
char chara[20] = {0};
timea = counter*255;
timeb = TCNT0+timea;
timec = timeb*2.44;
timed = (timec/58);
itoa(timed,chara,10);
uart_puts(chara);
dist = timed;
return dist;
}
ISR(TIMER0_OVF_vect)
{
counter++;
}
No comments:
Post a Comment