Skip to content

Instantly share code, notes, and snippets.

@lyhcode
Created October 10, 2012 08:30
Show Gist options
  • Save lyhcode/3864060 to your computer and use it in GitHub Desktop.
Save lyhcode/3864060 to your computer and use it in GitHub Desktop.
Arduino + HC-SR04 超音波測距控制 LED 燈閃爍
#define TRIGPIN 10
#define ECHOPIN 13
#define LED1 8
#define LED2 9
long ping() {
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
return pulseIn(ECHOPIN, HIGH)/58;
}
void setup() {
pinMode(TRIGPIN, OUTPUT);
pinMode(ECHOPIN, INPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
}
void loop() {
long cm = ping();
if (cm <= 100) {
digitalWrite(LED1, HIGH);
delay(cm*1.5 + 10);
digitalWrite(LED1, LOW);
digitalWrite(LED2, HIGH);
delay(cm*1.5 + 10);
digitalWrite(LED2, LOW);
}
delay(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment