Skip to content

Instantly share code, notes, and snippets.

@murilopontes
Created March 26, 2014 20:18
Show Gist options
  • Save murilopontes/9792298 to your computer and use it in GitHub Desktop.
Save murilopontes/9792298 to your computer and use it in GitHub Desktop.
#define HCSR04_TRIG PD_3
#define HCSR04_ECHO PD_2
void setup()
{
Serial.begin(115200);
pinMode(HCSR04_TRIG,OUTPUT);
pinMode(HCSR04_ECHO,INPUT);
}
void loop()
{
digitalWrite(HCSR04_TRIG,0); //trig off for 2us
delayMicroseconds(10);
digitalWrite(HCSR04_TRIG,1); //trig on for 10us
delayMicroseconds(10);
digitalWrite(HCSR04_TRIG,0); //trig off
//150us=minimum echo
//25ms=maximum echo
//38ms=no-return echo
long echo=pulseIn(HCSR04_ECHO,HIGH,40000);
if(echo>250&&echo<25000){
double distance_cm=echo/58.2;
Serial.println(distance_cm);
delayMicroseconds(40000-echo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment