0

我有兩個藍牙模塊(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 

IFIN奴隸部分,而不是LDR讀數,如果我發送一個字符串「hello」,則打印爲:

<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 

我已經提到這個串口通訊鏈接0​​

有人可以幫助我,因爲我是新的arduino。

+0

相反BTSerial.read的()嘗試BTSerial .readString()就像在[docs](https://www.arduino.cc/en/Serial/ReadString)中一樣,並且它會容易很多@ vishruth-kumar –

+0

謝謝!得到它的工作! –

+0

太棒了!我會將其作爲官方答覆發佈 –

回答

0

直接讀取一個字符串到一個變量,你可以使用:

BTSerial.readString() 

代替:

BTSerial.read() 

像官方documentation