Hi, I just started to use Arduino and in our project, we need to establish communication between 2 Bluetooth modules. We are using HM18 module. However, the mySerial.available() always returns 0 although the 2 Bluetooth could connect automatically (light stop blinking).
Code for sending
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11);
int trigPin = 6;
int echoPin = 7;
int ledp=8;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(19200);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() { // run over and over
long duration, distance;
digitalWrite(trigPin,HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration=pulseIn(echoPin, HIGH);
distance =(duration/2)/29.1;
// Serial.print(distance);
// Serial.println("CM");
delay(10);
if((distance<=20))
{
digitalWrite(ledp,HIGH);
mySerial.write(111);
//Serial.println("distance");
Serial.println("distance");
delay(500);
}
else{
digitalWrite(ledp,LOW);
}
}
code for receiving
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11);
int ledp=8;
int buz=9;
int timesRepeat=0;
void setup() {
pinMode(ledp,OUTPUT);
pinMode(buz,OUTPUT);
// Open serial communications and wait for port to open:
Serial.begin(19200);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
mySerial.println("Hello, world?");
}
void loop() { // run over and over
if (mySerial.available()>0) {
delay(1);
int data = mySerial.read();//read()readStringUntil('\n')
//Serial.println("mySerialavailable");
//Serial.println(data);
//if alert condition match
if(timesRepeat!=0){
timesRepeat--;
digitalWrite(ledp,HIGH);
delay(50);
digitalWrite(ledp,LOW);
}
else{
if(data==111){
Serial.println("alert");
//digitalWrite(ledp,HIGH);
timesRepeat=20;
}
}
}
}
I've been working on this for hours but still no clue,,,
Thanks for the help in advance!