我一直在创建一个涉及Mq-3传感器的项目。当传感器增加51%时,RedLED就会闪烁。关于这一点,我根据比率和我从答复者收集的数据建立了一个使用的公式。
sensorVal=analogRead(sensorPin); //read SensorPin
sensorCalc51=(322./150.)*sensorVal; //This is the 51% value that the arduino makes that is dependent on the sensorValif (sensorVal >= sensorCalc51) { //the condition involves both the sensorVal and sensorCalc51
for (int i=0; i<=20; i=i+1) {
analogWrite(redPin,255);
delay (500);
analogWrite(redPin,000);
delay (500);
}正如您在代码中所看到的,该条件永远不会为真,因为公式总是使sensorCalc51高于sensorVal。我需要通过一个按钮使sensorCalc51锁定它的最新值,这样当用户在传感器上呼吸时,它不会变得更高,而且它实际上使条件成为现实。
发布于 2022-03-19 01:08:43
您应该将sensorCalc51封装在if语句中,并将值存储在全局或静态本地:
void test() {
static float sensorCalc51 = 10000.0; //to insure it doesn't fire before it's set properly
int sensorVal;
sensorVal = analogRead(sensorPin); //read SensorPin
// now check if the button is pressed. If so update sensorCalc51
// the digitalRead will be HIGH or LOW when switch is pressed
// depending on the type of switch
if (digitalRead(mySwitch)) {
sensorCalc51 = (322. / 150.) * sensorVal;
}
if (sensorVal >= sensorCalc51) {
for (int i = 0; i <= 20; i = i + 1) {
analogWrite(redPin, 255);
delay (500);
analogWrite(redPin, 000);
delay (500);
}
}
}https://stackoverflow.com/questions/71528149
复制相似问题