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

标签 c++ c arduino

给你的小描述...我正在尝试使用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/

相关文章:

c++ - Arduino Sketch 编译然后在上传时卡住

c++ - WAP八进制转二进制

c++ - 如何使用 C 预处理器将连接的字符串转换为宽字符?

serial-port - 在 Windows 2000 上使用 USB 下载的 Arduino 编程失败

C 用对应于索引的值初始化一个(非常)大的整数数组

c - "*="在C编程中到底是什么意思?

c++ - 将一个字符串分成一个数组

C++判断硬盘剩余空间

c++ - 在泛型函数中接受指针/迭代器

c - 如何以不同模式在同一数据库上打开两个 SQLite 上下文?