From my little experience with IOT devices I know that code is crucial and most of the painful troubleshooting siuations are more often caused by code than wiring.
Therfore I prefer not to comment my code within the code section but in the story where it's more human readable and to give you space to make your own code comments.
This code let's you connect to the module and after receiving a specific string LED will turn on or off.
Let's...
1. ...Beginint LED = 13;
=> assign onboard LED PIN#include <SoftwareSerial.h>
=> adding SoftwareSerial library
=> BTTX (TXD) on digital 9
#define BTTX 9
=> BTRX (RXD) on digital 10
#define BTRX 10
=> declare SerialBT function
SoftwareSerial SerialBT(BTTX, BTRX);
SerialBT.begin(57600);
=> setting serial baud rateSerialBT.println("Bluetooth connection established");
=> SerialBT.println will send data like a string to the App.
delay(300);
=> add a delay to avoid congestion
if (SerialBT.available())
=> check if Bluetooth connection is available
=> declare msg variable as String to receive commands
{
String msg = SerialBT.readString();
if(msg == "on\r\n")
=> check if message is "on\r\n"*
=> turn on LED
{
digitalWrite(13, HIGH);
=> sent status to app
SerialBT.println("LED is ON"); }
else
=> check if message is "off\r\n"*
if(msg == "off\r\n")
=> turn off LED
{
digitalWrite(13, LOW);
=> sent status to app
SerialBT.println("LED is OFF"); }
}
1. Turn on Bluetooth and search for your HC-05 device
2. Connect to device using 4-digit secret
3. Download App "Serial Bluetooth Terminal"
4. Open app and go to menu -> devices and select your HC-05
5. Type on or off at buttom of screen and hit -> send button
- don't use other variable names than "BTTX" for TXD and "BTRX" for RXD. I wanted to be cool and used my own variable names, causing me a bad headache :-/
- use correct baud rate (57600 should do it for HC-05) otherwise module will send reverse (⸮⸮⸮)- or green question-marks to Serial.
*Your phone will add a carriage return and newline after each string you sent. Your on will be received as on\r\n at Bluetooth module. Consider this in your if conditional.
Comments