//#define serial
String readStr = "";
char buf;
int flag = 0;
int ledState = 0;
int red = 6;
#ifndef serial
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(3, 2);
#endif
void setup() {
// put your setup code here, to run once
#ifndef serial
BTSerial.begin(9600);
BTSerial.println("Commands: 'led on' 'led off'");
#else
Serial.begin(9600);
while(!Serial);
Serial.println("Commands: 'led on' 'led off'");
#endif
pinMode(red, OUTPUT);
}
void loop() {
readSerial();
if ((readStr != "led on" && readStr != "led off" && readStr != "") && (flag == 0)) {
#ifdef serial
Serial.println("invalid command:");
Serial.println(readStr);
#else
BTSerial.println("invalid command:");
BTSerial.println(readStr);
#endif
readStr = "";
flag = 1;
}
if ((readStr == "led on" || ledState == 1) && (flag == 0)) {
flag = 1;
ledState = 1;
readStr = "";
#ifdef serial
Serial.println("brightness (soft - normal - hard)");
while(Serial.available() <= 0) { }
#else
BTSerial.println("brightness (soft - normal - hard)");
while(BTSerial.available() <= 0) { }
#endif
readSerial();
if (readStr == "soft") {
analogWrite(red, 25);
#ifdef serial
Serial.println("brightness is soft");
#else
BTSerial.println("brightness is soft");
#endif
readStr = "";
}
if (readStr == "normal") {
analogWrite(red, 127);
#ifdef serial
Serial.println("brightness is normal");
#else
BTSerial.println("brightness is normal");
#endif
readStr = "";
}
if (readStr == "hard") {
analogWrite(red, 255);
#ifdef serial
Serial.println("brightness is hard");
#else
BTSerial.println("brightness is hard");
#endif
readStr = "";
}
}
if (readStr == "led off" && flag == 0) {
flag = 1;
ledState = 0;
#ifdef serial
Serial.println("led is off");
#else
BTSerial.println("led is off");
#endif
readStr = "";
digitalWrite(red, LOW);
}
}
void readSerial () {
#ifndef serial
if (BTSerial.available() > 0) {
while (BTSerial.available() > 0) {
delay(2);
buf = BTSerial.read();
readStr += buf;
}
flag = 0;
BTSerial.println(readStr.length());
}
#else
if (Serial.available() > 0) {
while (Serial.available() > 0) {
delay(2);
buf = Serial.read();
readStr += buf;
}
flag = 0;
Serial.println(readStr.length());
}
#endif
}
what this does is it waits for an input on the bluetooth terminal and stores it in a string.
I use the android app: "Serial Bluetooth Terminal"
But here comes the problem. If i used the code on the Serial monitor, it works just fine. But on the app, it keeps saying "invalid command". I added some code to see how many characters there are in the string and I found out there are always two characters added.
I connected it to a led display and get weird symbols at the end of the word.
Does anybody know how to fix this?
Thanks in advance.