Ultrasonic Sensor in AVR

1.5k views Asked by At

I am working on creating an ultrasonic range detector. I am currently testing the sensor to make sure that it is functioning properly. I have connected the echo pin and trigger pin to PC4 and PC5 respectively. When I run this code, ideally it would send 6 to my display. However, it is displaying 0. This leads me to believe that code is not properly interfacing with the sensor. Please help.

#define F_CPU 16000000UL

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

void DisplayIt(int i);

int main(void)
{

    while(1)
    {
        DDRC = 0xFF;
        int i = 0;
        PORTC = 0b00000000;
        _delay_us(2);
        PORTC = 0b00100000;
        _delay_us(10);
        PORTC = 0x00;

        DDRC = 0x00;
        if (PINC == 0b00010000)
        {
            i = 6;
        }
        DisplayIt(i);
    }

}
2

There are 2 answers

2
UncleO On

PINC and PORTC are the same register.

PORTC = 0x00; sets the contents of this register to 0 just before you read it.

0
Janice Kartika On

I do not know what ultrasonic sensor did you use. But I supposed that's because you did not wait until the sensor received its echo signal. Based on ultrasonic sensor I have ever used, SRF04, it has a timing diagram like this:

enter image description here

I modify your code so it will have an ability to print "6" when the sensor detect an object in front of it (which we know it from the arrival of echo signal).

Here is the code:

while(1) {
  DDRC = 0xFF;  // Configure all Port C pins as an output
  int i = 0;

  PORTC = 0b00100000;  // Write 1 (high) to PORTC.5 (trigger pin)
  _delay_us(10);  // Keep PORTC.5 to give high signal output for 10us
  PORTC = 0x00;  // Write 0 (low) to PORTC.5

  // The code above completes Trigger Input To Module (see Timing Diagram image)

  DDRC = 0x00;  // Configure all Port C pins as an input
  while (PINC.4 == 0);  // Wait until PINC.4 (echo pin) has 1 (high) value
  if(PINC.4 == 1) i = 6;  // Once PINC.4 is high, while loop will break and this line will be executed

  DisplayIt(i);

  _delay_ms(10);  // Allow 10ms from End of Echo to Next Trigger Pulse
}