Arduino Serial.println奇怪的错误 [英] Arduino Serial.println weird bug

查看:77
本文介绍了Arduino Serial.println奇怪的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试arduino,并使用状态开关对一些按钮进行了编程.如果它是"on",那么它会"off",反之亦然.

I'm trying out arduino and have programmed some button with a state switch. If it was "on" then it turns "off" and versa.

#include <Bounce.h>

const int buttonPin = 2;     
const int ledPin =  6;      

int ledState = HIGH;     
int a = LOW;            
int b = LOW;  
Bounce push1 = Bounce( buttonPin,5 );

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  push1.update ( );
  int x = digitalRead(push1.read());
  if (x != b) {
    if (x == HIGH) {
      if (a == HIGH) {
        a = LOW;
        }
        else {
          a = HIGH;
        }
  }
  else {
    }
  }

digitalWrite(ledPin, a);
Serial.println(a);  // Weird thing
b = x;
}

它工作正常,但是奇怪的是,当我编程时,我添加了一些串行打印来监视通过COM的输出.然后,在一切正常之后,我想消除 Serial.println(a); ,但是那是行不通的!

It works well, but weird thing is that when i was programming i added some Serial prints to monitor output thru COM. Then after it all worked well i wanted to eliminate Serial.println(a); but it doesn't work then!

循环完全不响应我的按钮按下.我想念什么吗?什么会引起这种事情?也许我错过了一些东西,所以新鲜的眼睛会很棒:)

The loop doesn't respond to my button pressing at all. Am I missing something? What could cause this kind of thing ? Maybe i missed something, so fresh eye would be great : )

非常感谢!

推荐答案

您正在通过调用 digitalRead(push1.read())来读取按钮的状态.

You are reading the state of the button by calling digitalRead(push1.read()).

几乎可以肯定这是不正确的(但是我还没有使用过Bounce库). push1.read()正在读取按钮的状态,大概是HIGH(0x1)或LOW(0x0).然后,此按钮状态值将用作读取对 digitalRead 的调用中的引脚.因此,在我看来,您正在读取的是引脚0或1的状态,而不是按钮所在的引脚2的状态.如果我没记错的话,针脚0和1是硬件串行端口.

This is almost certainly incorrect (but I haven't used the Bounce library). push1.read() is reading the state of the button, presumably HIGH (0x1) or LOW (0x0). This button state value is then being used as the pin to read in the call to digitalRead. So, it looks to me like you are reading the state of either pin 0 or 1, not pin 2 where the button is. If I remember correctly pins 0 and 1 are the hardware serial port.

更改:

int x = digitalRead(push1.read());

收件人:

int x = push1.read();

看看效果是否更好.

我怀疑 Serial.println(a)是一条红鲱鱼,它肯定会延迟.串行端口和代码之间可能发生奇怪的交互,因为我相信您是从串行端口而不是按钮读取按钮状态"( x ).

I suspect the Serial.println(a) is a red-herring, it would certainly be acting as a delay. There may be a weird interaction happening between the serial port and your code as I believe you are reading the "button state" (x) from the serial port not the button.

这篇关于Arduino Serial.println奇怪的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆