Close

Reading from a US-100 Ultrasonic Sensor

A project log for PWM examples with multiple architectures

This is the cheat sheet for the Embedded Hardware Workshop

mike-szczysMike Szczys 11/09/2014 at 19:030 Comments

Reading the US-100 ultrasonic distance sensor is easy:

It would be better to use a hardware timer but this does work. This code example is for the Tiva C Launchpad board.
/*################################################
# Reading US-100 Ultrasonic Sensor using
# the Tiva C Launchpad
#
#
# This example reads from a US-100 ultrasonic sensor
# * Jumper should not be in place
# * VCC to 3.3V
# * GND to GND
# * Trigger to PF2
# * Echo to PF4
#
# It would be much better to use a hardware time
# instead of incrementing "counter" as I've done here
#
# The blue LED is on the same pin as trigger so it
# will flash like crazy
#
# When working correctly the red LED will light up
# when an obstacle is close to the sensor
#
#################################################*/


#include "driverlib/pin_map.h"
#include <stdint.h>
#include <stdbool.h>
#include "inc/hw_gpio.h"
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "driverlib/sysctl.h"
#include "driverlib/pin_map.h"
#include "driverlib/gpio.h"
#include "driverlib/rom.h"

//Max wait time for reading the sensor:
#define MAX_TIME 7500

void delayMS(int ms) {
    SysCtlDelay( (SysCtlClockGet()/(3*1000))*ms ) ;
}

uint32_t measureD(void) {
    //Pull trigger high
    GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, GPIO_PIN_2);
    //wait appropriately
    SysCtlDelay(SysCtlClockGet()/(3*10)) ; //Delay 10uS
    //Pull trigger low
    GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, 0);
    //Monitor echo for rising edge
    while (ROM_GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4) == 0) { }
    uint32_t counter = 0;
    
    //loop counter checking for falling edge; MAX_TIME make sure we don't miss it
    while ((ROM_GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4) != 0) && (counter < MAX_TIME)) { counter++; }
    
    //return value
    return counter;
   
}

int main(void)
{
    //Set the clock
    SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC |   SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);

    //Enable PortF
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);

    //LED Pins as outputs
    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1 | GPIO_PIN_2 ); //LED on PF1, Trigger on PF2 (there's also an LED there)
    GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, 0);
    ROM_GPIOPinTypeGPIOInput(GPIO_PORTF_BASE, GPIO_PIN_4);
    ROM_GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_4, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPD);



    while(1)
    {   
        if (measureD() < 750) { GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, GPIO_PIN_1); } //LED ON
        else { GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1, 0); } //LED OFF

        delayMS(20);

    }

}

Discussions