Arduino Code for Bluetooth modules
/* BLUETOOTH MASTER HC-05 */ #include <SoftwareSerial.h> const int ledPin = 13; //led Pin const int rxPin = 0; //SoftwareSerial RX PIN, connect to HC-06 TX PIN const int txPin = 1; //SoftwareSerial TX PIN, connect to HC-06 RX PIN //level shifting to 3.3 Volts may be needed SoftwareSerial mySerial(rxPin, txPin); //RX, TX int state = 0; //if state is 1, the LED will TURN ON and //if state is 0, the LED will TURN OFF int flag = 0; //flag to prevent duplicate messages void setup() { //sets pins as output pinMode(ledPin, OUTPUT); mySerial.begin(9600); //initializing serial connection w/ HC-06 MASTER Serial.begin(9600); //initializing serial connection to PC running the program digitalWrite(ledPin, LOW); //Arduino Master LED on digital PIN 13 is initially OFF Serial.println("Ready to Test Communication '0' for ON '1' for OFF"); //sent to PC } void loop() { //Read Serial input and saves it in the state variable if(Serial.available()>0) { state = Serial.read(); flag = 0; //clear the flag to print the state } //if the state is '0' the LED will TURN OFF if(state == '0') { digitalWrite(ledPin, LOW); if(flag == 0) { Serial.println("Switch slave LED: OFF"); //echoes the instruction received from the PC mySerial.print("0"); //sends instruction to slave flag = 1; } //read the reply message from the slave and send it to the PC one byte at the time while(mySerial.available() > 0) { char inByte = mySerial.read(); Serial.write(inByte); } } //if state is '1' the LED will TURN ON else if(state == '1') { digitalWrite(ledPin, HIGH); if(flag == 0) { Serial.println("Switch slave LED: ON"); //echoes the instruction received to the PC mySerial.print("1"); //sends instruction to Arduino Slave flag = 1; } //read the reply message from the slave and send it to the PC one byte at the time while(mySerial.available() > 0) { char inByte = mySerial.read(); Serial.write(inByte); } } }