我使用2 HC-05蓝牙模块在2个Arduino Nanos之间进行通信。
我已经将HC-05的波特率设置为9600,一个是主人,另一个为从属。
主始终发送值-1,尽管值应来自模拟输入。
我已经检查了模拟读物,并且值正确。
但是,当我检查蓝牙串行读数时,值为-1。
有人可以帮助我吗?
主代码
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3);
int state = 0;
const int ledPinon = 8; //the pin your led is connected to
const int ledPin = 7; //the pin your led is connected to
int xPin = A1;
int xPosition = 0;
int val = 0;
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
pinMode(xPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
xPosition = analogRead(xPin);
val = map(xPosition, 0, 1023, 0, 180);
if (mySerial.available()){
if (xPosition > 506) {
digitalWrite(ledPin, HIGH);
mySerial.write(val); //sends a 1 through the bluetooth serial link
}
else if ((xPosition <506)||(xPosition >502)){
mySerial.write('0');
digitalWrite(ledPin, LOW);
}
else if (xPosition <502){
mySerial.write(val);
backblink();
}
int check = mySerial.read();
Serial.print(val);
Serial.print(" | ");
Serial.println(check);
delay(200);
}
}
void ledblink(){
digitalWrite(ledPinon, HIGH);
delay(200);
digitalWrite(ledPinon, LOW);
delay(200);
}
void backblink(){
digitalWrite(ledPin, HIGH);
delay(80);
digitalWrite(ledPin, LOW);
delay(80);
}
从代码
#include <SoftwareSerial.h>
#include <Servo.h>
SoftwareSerial mySerial(2, 3);
int BluetoothData; // the data given from Computer
Servo ESC;
int state;
const int ledPinon = 8; //the pin your led is connected to
const int ledPin = 7; //the pin your led is connected to
const int ledPinback = 6; //the pin your led is connected to
void setup() {
// initialize digital pin 8 as an output.
Serial.begin(9600);
mySerial.begin(9600);
pinMode(ledPin, OUTPUT);
ESC.attach(9);
ledblink();
}
void loop() {
Serial.println(state);
if (mySerial.available()>0) { // Checks whether data is comming from the serial port
state = mySerial.read(); // Reads the data from the serial port
BluetoothData = state;
ESC.write(BluetoothData);
Serial.println(state);
}
// Controlling the LED
if (BluetoothData > 90) {
digitalWrite(ledPin, HIGH); // LED ON
}
else{
digitalWrite(ledPin, LOW); // LED ON
//backblink(); // LED ON
}
}
void ledblink(){
digitalWrite(ledPinon, HIGH);
delay(200);
digitalWrite(ledPinon, LOW);
delay(200);
}
void backblink(){
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);
}
在主代码中,所有可能将任何东西发送到从属的行都位于serial.able.abable。但是,由于从未将任何东西发送给主人,所以总是会返回0。因此主人可能根本没有发送任何东西。