我有一个正确连接的 ping))) 传感器 (HC - SR04)。
我在没有接地的情况下启动它(否则它甚至不想启动)并且它一直将 0 写入串行窗口(距离)。一旦我将它插入接地引脚,我会得到几行正确的距离读数,然后它会停止并挂起,串行窗口中没有更多结果,并且电路板本身似乎处于故障状态,我需要拔掉插头将其从 USB 断开,断开接地,然后重新插入 USB。
问题的原因可能是什么?
代码:
#define echoPin 2 // Echo Pin
#define trigPin 4 // Trigger Pin
#define LEDPin 13 // Onboard LED
int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int currentDistance = 0;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}
void loop() {
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
if (distance >= maximumRange || distance <= minimumRange){
/* Send a negative number to computer and Turn LED ON
to indicate "out of range" */
Serial.println("-1");
digitalWrite(LEDPin, HIGH);
} else {
/* Send the distance to the computer using Serial protocol, and
turn LED OFF to indicate successful reading. */
Serial.println(distance);
digitalWrite(LEDPin, LOW);
}
//Delay of 50 ms before next reading.
delay(50);
}
- - - - - - - - - - - - 更新 - - - - - - - - - - - - - -----
似乎问题不在于传感器,而在于串行接口:我在板上连接了一个LED,并根据距离给它一个模拟值。一旦 Arduino 被“卡住”,LED 就会继续正常工作,所以我猜问题是 Arduino 关闭了串行接口并停止通过 USB 传输数据。
如何解决这个问题?