gpt4 book ai didi

c - Arduino 开发环境 : Print once inside loop

转载 作者:太空宇宙 更新时间:2023-11-04 06:36:44 26 4
gpt4 key购买 nike

我正在使用 LDR 告诉我 Arduino 是否有光。我的代码非常简单,但与其发送垃圾邮件“light light light light”,我希望它说一次“light”,然后如果灯熄灭,让它说一次“No light”。从“readanalogvoltage”编辑的代码:

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);

// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);

// print out the value you read:
if (voltage > 1.5)
{
Serial.print("Light");
Serial.println();
delay(5000);
}

if (voltage < 1.5)
{
Serial.print("No Light");
Serial.println();
delay(50);
}

}

最佳答案

保留一个保存最后状态的变量:

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

int wasLit = 0;

// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);

// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);

// print out the value you read:
if (!wasLit && voltage > 1.5) {
wasLit = 1;
Serial.print("Light");
Serial.println();
delay(5000);
} else if(wasLit && voltage <= 1.5) {
wasLit = 0;
Serial.print("No Light");
Serial.println();
delay(50);
}
}

关于c - Arduino 开发环境 : Print once inside loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14045105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com