传感器通过蓝牙读取通信

时间:2017-04-05 07:01:30

标签: serialization bluetooth android-sensors arduino-uno arduino-ide

我有两个蓝牙模块(HC05)连接到单独的arduinos。一个充当主人,另一个充当奴隶。一个LDR连接到从属部分,它将连续读取并通过蓝牙发送给主机。

模块已成功配对。我甚至可以使用连接到从属设备的按钮来控制连接到主设备的LED。

自从4天以来,我一直在努力在主人的串行监视器上获得LDR的读数。

项目的奴隶部分(拥有LDR):

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
#define ldrPin A0
int ldrValue = 0;
void setup() {
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  pinMode(ldrPin, INPUT);
  BTSerial.begin(9600);
  Serial.begin(9600);

}
void loop() 
{
  ldrValue = analogRead(ldrPin);
  BTSerial.println(ldrValue);
  Serial.println(ldrValue);
  delay(1000);
 }

项目的主要部分将获得reaings并在串行监视器上显示:

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
const byte numChars = 1024;
char receivedChars[numChars];   // an array to store the received data

boolean newData = false;

void setup() {
    pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
    digitalWrite(9, HIGH);
    BTSerial.begin(9600);
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
}

void loop() {
    recvWithEndMarker();
    showNewData();
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (BTSerial.available() > 0 && newData == false) {
        rc = BTSerial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChars);
        newData = false;
    }
}

但问题是在串行监视器中,串行监视器中只显示最高位(392中为3)。读数是正确的,但不显示完整的读数。 串口监视器显示如下:

<Arduino is ready>
This just in ... 1
This just in ... 1
This just in ... 1
This just in ... 1
This just in ... 1
This just in ... 3
This just in ... 3
This just in ... 3
This just in ... 3
This just in ... 3

如果我发送字符串“hello”,如果在Slave部分而不是LDR读数,那么它打印为:

<Arduino is ready>
This just in ... h
This just in ... h
This just in ... h
This just in ... h
This just in ... h
This just in ... h

我已将此链接称为串行通信Serial input basics

有人可以帮助我,因为我是arduino的新手。

1 个答案:

答案 0 :(得分:0)

要将字符串直接读入变量,您可以使用:

BTSerial.readString() 

而不是:

BTSerial.read() 

就像在官方documentation

中一样