gpt4 book ai didi

c++ - 创建串行监视器输出循环

转载 作者:行者123 更新时间:2023-11-30 20:35:52 24 4
gpt4 key购买 nike

给你的小描述...我正在尝试使用arduino uno来实现它,所以我按下一个按钮来打开整个程序,而不是按住按钮,而是按下并让它释放以使其打开,然后再次执行此操作把它关掉。当它打开时,它需要每 1 秒输出一次 LDR 给出的数据。

无论如何,在串行监视器(数据输出)中,我希望它首先说“关”,然后在按下按钮后说“开”。我已经走到这一步了。

我的问题是当它打开时,我不知道如何让它显示每秒的 LDR 光感量,同时还测试如果它超过 500,例如,它应该停止并说警报已触发。并且之后也可以关闭。

这是我的代码:

   // Devices attached
const int buttonPin = 2; // Pin that BUTTON uses
const int sensorPin = 0; // Pin that SENSOR uses

// List of dynamic variables
int pushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastbuttonState = 0; // previous state of the button

void setup()
{
// Set the BUTTON as an INPUT
pinMode(buttonPin, INPUT);
// Create serial prompt
Serial.begin(9600);
}

void loop()
{
// read the pushbutton current state
buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state
if (buttonState != lastbuttonState)
{

// if the state has changed, increment the counter
if (buttonState == HIGH)
{
// if the current state is HIGH then the button
// wend from off to on:
pushCounter++;

int sensorValue = 0;
// Divides counter by 2, if remainder (not0), then the following
if (pushCounter % 2 == 0){
analogWrite(sensorPin, HIGH);
Serial.println("Power ON");
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
delay(1000);
}
else
{
analogWrite(sensorPin, LOW);
Serial.println("OFF");
}

// Debouncing delay
delay(250);
}

// Save the current BUTTON state as the LAST state
lastbuttonState = buttonState;

}
}

最佳答案

您的要求似乎是任务多线程的问题。在裸露的arduinos中这是不可能的。 arduino 是单线程的。

analogRead() 不会将引脚设置为可读,但会返回该引脚中的值。

使用模拟A0代替数字引脚0

const int sensorPin = A0;      // Pin that SENSOR uses
boolean isOn = false;
int sensorValue = 0, pinValue = 0;

void loop()
{
buttonState = digitalRead(buttonPin);
if(buttonState != lastbuttonState && buttonState == HIGH) {
pushCounter++;
lastbuttonState = buttonState;
}
if (pushCounter % 2 == 0){
Serial.println("Power ON");
isOn = true;
} else {
Serial.println("OFF");
isOn = false;
}
if(isOn) {
pinValue = analogRead(sensorPin);
Serial.println(pinValue);
if(pinValue > 500) { Serial.println("Alarm triggered"); }
delay(1000);
}
}

关于c++ - 创建串行监视器输出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37383063/

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