1

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 Answers2

2

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
}
Janice Kartika
  • 502
  • 1
  • 3
  • 14
0

PINC and PORTC are the same register.

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

UncleO
  • 8,299
  • 21
  • 29
  • So how do I fix that because I need to clear that in order to stop the triggering? – Blake Doran Dec 17 '16 at 18:03
  • 2
    You will need to edit your question to indicate the type of sensor. Is it HC-SR04? In that case, you are reading the echo too early. Refer to the timing diagram. Trigger the pulse; wait for the pulse to be sent; Time how long the pin is high. You are reading the pin before the pulses are sent. That is why it is still low. There are lots of tutorials and code samples for this sensor available. Sparkfun has some simple code for Arduino that you can adapt, as well as the datasheet. – UncleO Dec 18 '16 at 00:24