我想在2Arduino与HC05(主)和HC06 (从)之间执行蓝牙通信。我成功地完成了两个模块的配对,但当我发送从电位器读取的字节时,从机会收到另一个值,即128,-1,248。下面是Arduino的代码
Arduino master HC05
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
int potpin = 0; // analog pin used to connect the potentiometer
void setup()
{
// start the serial communication with the host computer
Serial.begin(9600);
Serial.println("Arduino with HC-05 is ready");
// start communication with the HC-05 using 9600
BTserial.begin(9600);
Serial.println("BTserial started at 9600");
}
void loop()
{
BTserial.println(analogRead(potpin));
delay(100);
Serial.println(analogRead(potpin));
}Arduino从HC06
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo;
SoftwareSerial slave(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
int c = 0;
int val;
void setup()
{
// start the serial communication with the host computer
Serial.begin(9600);
Serial.println("Arduino with HC-06 is ready");
// start communication with the HC-05 using 9600
slave.begin(9600);
Serial.println("BTserial started at 9600");
myservo.attach(9);
}
void loop()
{
if (slave.available())
{
val= slave.read();
Serial.println(val);
val = map(val, 0, 1023, 0, 180);
myservo.write(val);
delay(15);
}
}感谢你的每一个回答
发布于 2017-02-11 23:10:28
在从属草图中,您应该用parseInt()替换slave.read()。
read()函数将读取单个字节。当主机发送整数值potpin=130时,函数println(potpin)会将其转换为3个字节(编码为ascii字符),并将它们发送出去。在从机端,你必须读取所有传入的字节,存储在字符串中,并将字符串转换为整型变量。parseInt()将在单行中做到这一点。
https://stackoverflow.com/questions/42176832
复制相似问题