Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino: using Serial and Software Serial with bluetooth module

My purpose is to use Arduino to set up communication between a PC and an Android device using an HC-05 bluetooth module.

I use the USB communication between the PC and the Arduino (Serial Monitor) and a SoftwareSerial to connect to the HC-05.

My problem is that the communication works well from BT to the PC, but doesn't work as expected in the other way. When sending from the PC to BT all the characters sent are received by the BT device only when I close the Serial Monitor on the PC or when I reset the Arduino.

I've excluded a problem with the BT Module or the Android application because if in Arduino I implement an "ECHO" code (write in Android and the send in Android) everything works fine.

With the Arduino code posted below the expected behaviour is: Arduino reset-> Hello word sent, Serial monitor opened-> nothing happens, character written on serial monitor-> character received on BT, character written on BT-> character received on Serial Monitor, Serial monitor closed-> nothing happens.

The real behaviour is: Arduino reset-> Hello word sent, Serial monitor opened-> 2 Hello word on BT and 1 ("goodnight") on PC, character written on serial monitor-> nothing, character written on BT-> character received on Serial Monitor, Serial monitor closed-> previous written character(s) in serial monitor received + Hello Word.

How can I fix this problem?

Code:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX, TX
int a=0;
char c;
char d;
void setup() {
  Serial.begin(9600);
  Serial.println("Goodnight moon!");
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}
void loop() {
  delay(10);
  if (Serial.available()) {
    c=Serial.read();
    delay(10);
    Serial.write(c);
  }
  delay(10);
  if (mySerial.available()) {
    d=mySerial.read();
    delay(10);
    mySerial.write(d);

  }
}
like image 824
user2706612 Avatar asked Aug 22 '13 09:08

user2706612


1 Answers

This code is working for me on an Arduino Mini Pro (should be the same as UNO) with an HC-05. I have the HC-05 paired with my laptop. Using HyperTerminal on the COM port associated with the HC-05 and the Arduino serial console, I can send messages bidirectionally. The Serial.println statements show up in the Hyperterminal window like they should.

#include <SoftwareSerial.h>

#define rxPin 8
#define txPin 7

SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char myChar ; 

void setup() {
  Serial.begin(9600);   
  Serial.println("Goodnight moon!");

  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop(){
  while(mySerial.available()){
    myChar = mySerial.read();
    Serial.print(myChar);
  }

  while(Serial.available()){
   myChar = Serial.read();
   mySerial.print(myChar);
  }
}
like image 157
imjosh Avatar answered Sep 27 '22 22:09

imjosh