我已经开始深入研究Arduino和不同类型的传感器,这是很有趣的,但我担心我的编码太明确了。我有很多编码公司程序的经验,虽然它不是C/C++。我不认为自己是初学者,但我认为有些地方不对劲。
我会把我的代码放在这部分。(它使用PING())传感器来根据发射的超音波信号的传播时间来检测一个物体的距离。这张草图摘自TinkerCad网站,在这里可以找到: tinkercad.com。
/*
Ping))) Sensor
This sketch reads a PING))) ultrasonic rangefinder and returns the distance to the closest object in range. To do this, it sends a pulse to the sensor to initiate a reading, then listens for a pulse to return. The length of the returning pulse is proportional to the distance of the object from the sensor.
The circuit:
* +V connection of the PING))) attached to +5V
* GND connection attached to ground
* SIG connection attached to digital pin 7
http://www.arduino.cc/en/Tutorial/Ping
This example code is in the public domain.
*/
const int speedOfSoundInAirInMetersPerSecond = 343;
const float speedOfSoundInAirInCentimeterPerMicrosecond =
speedOfSoundInAirInMetersPerSecond / 10000.0;
const float centimeterToInchRatio = 2.54;
int inches = 0;
int cm = 0;
long readTravelTimeInMicroseconds(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
// I had to divided that speed by 2 because
// I'm only interested in the time which took
// signal to reach an object. I don't need to know
// how much distance we covered by the signal to the object and back.
cm = (speedOfSoundInAirInCentimeterPerMicrosecond / 2)
* readTravelTimeInMicroseconds(7, 7);
inches = (cm / centimeterToInchRatio);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.println("cm");
delay(100);
}发布于 2020-12-22 22:46:45
VeryLongIdentifiersInCamelCase不会使代码显式化。他们只会增加噪音。10000很奇怪。毕竟,每秒有1000000微秒。我花了相当长的时间才意识到,在米到厘米的转换中隐藏了两个数量级。pulseIn超时时间为1秒。实际上,这意味着在170米(约500英尺)的范围内没有障碍物。我很怀疑你的硬件在这么远的地方能探测到回声。为了更好的响应,缩短超时时间是安全的。inPulse。目前,您正在返回0距离,实际上它意味着距离实际上是无限的。value是高的,pulseIn()等待引脚从低到高,开始计时,然后等待引脚变低,停止计时。返回脉冲的长度(以微秒为单位),这意味着它返回回波的持续时间,而不是您想要的周转时间。不幸的是,我没有硬件可玩。你的代码给出了合理的结果吗?https://codereview.stackexchange.com/questions/253783
复制相似问题