此代码用于控制使用超声波传感器(HC-SR04)的LED。当它上传到arduino时,它会设置红色LED并关闭绿色LED(默认)。此外,如果我们在半径20厘米的传感器前放置一些东西,绿色LED会亮起,红色LED会熄灭。如果我们接受它,它将设置默认值。
#define trigPin 8
#define echoPin 7
#define ledRed 11 //red
#define ledGreen 12 //green
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledRed, OUTPUT);
pinMode(ledGreen, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
// delayMicroseconds(1000); - Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1; //formula to get distance in cm
//default led condition
digitalWrite(ledRed,HIGH);
digitalWrite(ledGreen,LOW);
if (distance <20) { // This is where the LED On/Off happens
digitalWrite(ledRed,LOW); // When the Red condition is met, the Green LED should turn off
digitalWrite(ledGreen,HIGH);
}
Serial.print(distance);
delay(1000);
}
需要更多帮助,如何在python中控制它。简单地使用pyserial或pyfirmata库?