嘿我正在尝试建立一个项目,我有一个浮动电平开关连接到我的Arduino板的第2针,另一端连接到arduino上的5v。
我希望软件在交换机变为高电平时显示一条消息,但此时它会直接显示消息,我知道交换机没有设置为高电平,因为我手里拿着它。
将来它会在信号变高时发送短信,用于使用浮球液位开关进行洪水监测。
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "sms.h"
SMSGSM sms;
//To change pins for Software Serial, use the two lines in GSM.cpp.
int numdata;
boolean started=false;
char smsbuffer[160];
char n[20];
int closed=0;//Sets initial signal to 0
const int switchPin = 2;
int switchState = 0; // current state of the button
int lastswitchState = 0; // previous state of the button
void setup()
{
//Serial connection.
Serial.begin(9600);
Serial.println("GSM Shield for Flood Early Warning System \n");
pinMode(switchPin, INPUT);
//Start configuration of shield with baudrate.
//For http uses is recommended to use 4800 or slower.
}
void loop() {
closed=digitalRead(switchPin);
// compare the buttonState to its previous state
if (switchState != lastswitchState) {
// if the state has changed, increment the counter
if (switchState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
Serial.println("on");
} else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state,
//for next time through the loop
lastswitchState = switchState;
if (closed == HIGH) {
Serial.println ("Switch signal received");
if (gsm.begin(2400)){
Serial.println("\n status=READY");
started=true;
}
else Serial.println("\n status=IDLE");
if(started){
//Enable this two lines if you want to send an SMS.
if (sms.SendSMS("0871234567", "Arduino SMS"))//Number you wish to text and the message to be sent
Serial.println("\nSMS sent OK");//Alert for Serial monitor once sms sent
}
}
}
答案 0 :(得分:1)
您应该通过10KOhm电阻将输入引脚连接到GND。见https://www.arduino.cc/en/Tutorial/DigitalPins:
“这也意味着,配置为pinMode(引脚,INPUT)的引脚没有任何连接,......将报告引脚状态看似随机的变化,从环境中拾取电噪声,或者电容耦合状态附近的一针。“。
https://www.arduino.cc/en/Reference/DigitalRead:
如果引脚没有连接到任何东西,digitalRead()可以返回HIGH或LOW(这可以随机改变)。
换句话说,当您的开关打开时,输入引脚未处于已定义状态(开启或关闭)。通过添加一个下拉电阻(输入引脚和GND之间的10 KOhm电阻,电阻“拉下”(=接地)你的引脚,除非开关闭合,在这种情况下连接到+ 5V占优势(因为它是直接连接,没有电阻器。)