我正在使用Arduino Uno + HC SR04超声波距离传感器,我想添加一个电位计来手动设置最小/最大距离。到目前为止,我已经能够测量距离(例如,移动物体更近/更远),但没有设置最大值或最小值。通过这个电位计,我想在值达到最小值或最大值时停止程序。不幸的是,我不知道如何把它放在代码中,所以任何帮助都将非常感激。对于任何参考,这是我的工作代码到目前为止没有安装电位器。
void setup()
{
pinMode (2, OUTPUT);
pinMode (5, OUTPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(2, HIGH);
long duration, cm;
pinMode(3, OUTPUT);
digitalWrite(3, LOW);
delayMicroseconds(2);
digitalWrite(3, HIGH);
delayMicroseconds(3);
digitalWrite(3, LOW);
pinMode(4, INPUT);
duration = pulseIn(4, HIGH);
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.println(" cm");
delay(150);
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
答案 0 :(得分:0)
我真的不明白你的意思:
“我想停止距离传感器测量,例如传感器没有检测到5cm内的任何物体(5cm是通过电位器设定的最小值)”
然后向左打开以放置所需的功能
PS:对不起,我有一些个人问题
// http://www.parsicitalia.it/files/HC-SR04-Datasheet.pdf
// HC-SR04
// Sentry Angle : max 15 degree
// Sentry Distance : 2cm - 500cm
// High-accuracy : 0.3cm
// Input trigger signal : 10us TTL impulse
// Echo signal : output TTL PWL signal
// Size : 45*20*15mm
int _trigPin = 11; //Trig - green Jumper
int _echoPin = 12; //Echo - yellow Jumper
int _sensorMaxRng = 500; //cm
int _sensorMinRng = 2; //cm
int _potentiometer = 9; // Potentiometer - Analog Pin
int _val = 0;
int _borderLineVal = 0;
long _duration, _cm, _inches, _potentioRng;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
cleanRefreshSensor();
_val = analogRead(_potentiometer); //reading the Potentiometer value interval: 0 - 1023
_potentioRng = (long)((_sensorMaxRng - _sensorMinRng) / 1023);
Serial.println(_val);
Serial.println(_potentioRng);
pinMode(_echoPin, INPUT);
_duration = pulseIn(_echoPin, HIGH); // duration is the time (in microseconds) from the sending of the ping to the reception of its echo off of an object
// convert the time into a distance
// The speed of sound is "340 m/s" or "29 microseconds/centimeter"
_cm = _duration / 2 / 29.1; //Calculate the distance based on the speed of sound divided by 2 ( signal going and coming back)
_inches = _duration / 2 / 74;
Serial.print(_inches);
Serial.print(" in, ");
Serial.print(_cm);
Serial.print(" cm");
Serial.println();
if(_cm > _potentioRng){
Serial.print(" IN ");
}
else
{
Serial.print(" OUT ");
}
delay(150);
}
// The sensor is triggered by a HIGH pulse of 10 or more microseconds
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
void cleanRefreshSensor()
{
digitalWrite(_trigPin, LOW);
delayMicroseconds(5);
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
}