Arduino 使用按钮停止电机旋转,即使蓝牙已连接
我使用的是Arduino Nano、蓝牙模块HC-05和一个按钮。 我想在收到蓝牙信号时旋转电机,并在按下按钮时停止旋转,但此处不应断开蓝牙信号。在连接蓝牙并按下按钮时,电机应停止旋转。 问题是当信号通过蓝牙或串行传输时,电机会旋转,但当我们按下按钮停止旋转时,电机不会停止。 下面是我试过的Arduino 使用按钮停止电机旋转,即使蓝牙已连接,arduino,bluetooth,arduino-ide,Arduino,Bluetooth,Arduino Ide,我使用的是Arduino Nano、蓝牙模块HC-05和一个按钮。 我想在收到蓝牙信号时旋转电机,并在按下按钮时停止旋转,但此处不应断开蓝牙信号。在连接蓝牙并按下按钮时,电机应停止旋转。 问题是当信号通过蓝牙或串行传输时,电机会旋转,但当我们按下按钮停止旋转时,电机不会停止。 下面是我试过的 #include <SoftwareSerial.h> SoftwareSerial Bluetooth(10,6); const int buttonPin = 5; // the p
#include <SoftwareSerial.h>
SoftwareSerial Bluetooth(10,6);
const int buttonPin = 5; // the pin that the pushbutton is attached to
const int motorPin = 9;
const int ledPin = LED_BUILTIN; // the pin that the LED is attached to
int buttonState = 0; // current state of the button
int Data;
void setup() {
Serial.begin(9600);
Bluetooth.begin(9600);
Bluetooth.println("Send 1 to open LOCK. Send 0 to close LOCK");
Serial.println("Send 1 to open LOCK. Send 0 to close LOCK");
delay(1000);
Bluetooth.println("Waiting for command...");
Serial.println("Waiting for command...");
pinMode(buttonPin, INPUT);
pinMode(motorPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
if (Bluetooth.available())
{
Data=Bluetooth.read();
if(Data=='1'){
Serial.println("Motor rotating");
Serial.println(buttonState);
digitalWrite(motorPin, HIGH);
}
if (Data=='1' and buttonState == 1){
Serial.println("Motor stop");
Serial.println(buttonState);
digitalWrite(motorPin, LOW);
digitalWrite(ledPin, HIGH);
}
else{;}
}
}
#包括
软件串行蓝牙(10,6);
常量int buttonPin=5;//按钮所连接的销
常数int motorPin=9;
const int ledPin=LED_内置;//LED连接到的管脚
int buttonState=0;//按钮的当前状态
int数据;
无效设置(){
Serial.begin(9600);
蓝牙开始(9600);
Bluetooth.println(“发送1打开锁,发送0关闭锁”);
Serial.println(“发送1打开锁,发送0关闭锁”);
延迟(1000);
println(“等待命令…”);
Serial.println(“等待命令…”);
pinMode(按钮输入,输入);
引脚模式(电机引脚,输出);
引脚模式(LED引脚,输出);
}
void循环(){
//读取按钮输入引脚:
buttonState=digitalRead(buttonPin);
if(Bluetooth.available())
{
Data=Bluetooth.read();
如果(数据=='1'){
串行打印(“电机旋转”);
Serial.println(按钮状态);
数字写入(motorPin,高);
}
如果(数据='1'和按钮状态==1){
串行打印(“电机停止”);
Serial.println(按钮状态);
数字写入(motorPin,低电平);
数字写入(ledPin,高电平);
}
else{;}
}
}
我只试着用按钮控制,但效果很好。按下按钮时,电机停止,松开按钮时,电机旋转。我发现您的代码存在以下问题
否则,当buttonState=1时,这两个条件都将执行,这将导致间歇启动和停止电机的意外结果。我发现您的代码存在以下问题