为串行监视器输出创建循环

时间:2016-05-23 05:16:38

标签: 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;

  }
}

1 个答案:

答案 0 :(得分:0)

您的要求似乎是任务多线程的问题。在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);
  }
}