2 Arduino与HC05和HC06模块之间的通信

时间:2017-02-11 14:08:58

标签: bluetooth arduino

我想在2个Arduino和HC05(主站)和HC06(从站)之间进行蓝牙通信。我成功配对2个模块,但是当我发送一个从电位器读取的字节时,从机接收另一个值,可以是128,-1,248。下面是Arduino的代码< / p>

Arduino大师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);    
    }
}

感谢您的每一个答案

1 个答案:

答案 0 :(得分:1)

在奴隶草图中,您应将slave.read()替换为parseInt()

read()函数将读取单个字节。当master发送整数值potpin = 130时,函数println(potpin)将其转换为3个字节(编码为ascii字符),并将发送它们。在从属端,您必须读取所有传入的字节,存储在字符串中,并在整数变量中转换字符串。 parseInt()将在一行中完成。