How to make a response in Bluetooth module (Arduino) - arduino

I connected my Bluetooth module to the mobile phone and made up a code to communicate between Arduino and mobile through Bluetooth (send messages from Bluetooth module to device and vice versa).
Now I want to make a response, which means that if I send from the mobile "hi" the arduino replies and says "Hello" or whatever.
I have tried tons of codes but none worked, so would anyone please help me?
#include <SoftwareSerial.h>
SoftwareSerial myserial (6,5);
void setup() {
myserial.begin(9600);
Serial.begin (9600);
}
void loop() {
if (myserial.available()) {
Serial.write(+ myserial.read());
}
if (Serial.available()) {
myserial.write(Serial.read());
}
}
Another code but making a loop without sending anything
#include <SoftwareSerial.h>
SoftwareSerial myserial(6,5); //Arduino: R:5,T:6; bluetooth: T:5, R:6;
void setup() {
myserial.begin(9600);
Serial.begin (9600);
}
void loop() {
if (myserial.available()) {
Serial.write(myserial.read());
}
if (Serial.available()) {
myserial.write(Serial.read());
}
for (int i = 0; i=2; i++) {
myserial.write("hello");
}
if (myserial.read() =="n") {
myserial.write("hello");
}
}

You need to build your serial string char by char using the SerialEvent() interrupt, then do a String comparison using the .equals method. Despite many people will tell you that String types are 'evil' (see this and this) it might be a good solution for making things clearer (and perhaps a bit easier if you don't want to mess with C char strcmp() functions and pointers. In the end, the String type is there for you and I see no reason for not using it in general projects.
Based on the SerialEvent() documentation [1], and the String reference [2], you could do something like:
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
//Then you compare the inputString with the word you want to detect using the .equals method from the String class
if(inputString.equals("Hi"){
Serial.println("Hello");
}
// clear the string for a new comparison:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the hardware serial RX. This
routine is run between each time loop() runs, so using delay inside loop can
delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
EDIT 1: Of course, you can replace the Serial object from this example code with your own myserial object from the BlueTooth communication.

Related

How to make serial reading asynchronously to main loop

I have arduino with code below. It has encoder, and prints something on encoder turn. But also it receive a lot of data, so if arduino is reading serial main loop stops and encoder loosing steps. How can I write code where encoders printing has always priority?
code:
#include <Encoder.h>
String receivedData = "";
Encoder encoder1(24, 25);
long position1 = -999;
long newPosition1;
void setup() {
Serial.begin(57600);
}
void loop() {
newPosition1 = encoder1.read();
if (newPosition1 != position1) {
Serial.print("PrintSomething");
}
position1 = newPosition1;
Serial.flush();
if(Serial.available() > 0) {
receivedData = Serial.readStringUntil(';');
if (receivedData == "?") {
Serial.print("3," + String(deviceId) + ",0,0,3;");
}
doSomethingImmediatly();
}
}
Important thing is in reality i have 6 encoders, so i can't use interrupts. And doSomethingImmediatly function should run as fast as possible.
Funny thing is if i use higher braud the problem is even more visible.
I would strongly suggest using SerialEvent instead of polling for serial data. This way, you build the serial string char by char and you can decide where to stop reading.
I would rather poll the encoders to avoid using clock cycles reading the status of every encoder sequentially. Otherwise, reconsider using a different library that might offer better performance (like RotaryEncoder from mathertel)
Based on the number of encoders that you are trying to read and the potential bottlenecks that you will encounter at 16 MHz (most common clock speed from Arduino - unless us Due or Mega-), I advise porting your application to a Teensy Microcontroller (> 3.2)
Keep in mind, there is no such thing as 'priorities' unless, as lurker mentioned, you use RTOS. You have to play with timings and efficient logic
For instance, a skimmed example code would look like the following (it shows only one polling routine):
unsigned long previousEncoderTime;
unsigned long pollPeriod = 200; // Poll every 200 ms
char serialString[] = " "; // Empty serial string variable
bool stringFinished = false; // Flag to indicate reception of a string after terminator is reached
void setup(){
previousEncoderTime = 0;
}
void loop(){
unsigned long now = millis();
if (now - previousEncoderTime >= pollPeriod){
previousEncoderTime = now;
// Encoder reading routine
}
if (stringFinished){ // When the serial Port has received a command
stringFinished = false;
// Implement your logic here
}
}
void serialEvent()
{
int idx = 0;
while (Serial.available())
{
char inChar = (char)Serial.read();
if (inChar == '\n') // The reading event stops at a new line character
{
serialTail = true;
serialString[idx] = inChar;
}
if (!serialTail)
{
serialString[idx] = inChar;
idx++;
}
if (serialTail)
{
stringFinished = true;
Serial.flush();
serialTail = false;
}
}
}

Arduino SIM900 GSM how to Join Char on String

I am currently making an Arduino project with GSM900 GSM GPRS. In this project, I have to receive data sent from a phone. I could easily receive data with a single character, but I can`t join does character to obtain a full word (String). I have to use this full word inside an If statement if this word equals to that other word (string), make something...
#include <SoftwareSerial.h>
// Configure software serial port
SoftwareSerial SIM900(7, 8);
//Variable to save incoming SMS characters
char incoming_char=0;
String newchar = "";
void setup() {
// Arduino communicates with SIM900 GSM shield at a baud rate of 19200
SIM900.begin(19200);
Serial.begin(19200);
// Give time to your GSM shield log on to network
delay(20000);
// AT command to set SIM900 to SMS mode
SIM900.print("AT+CMGF=1\r");
delay(100);
// Set module to send SMS data to serial out upon receipt
SIM900.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
}
void loop() {
if(SIM900.available() >0) {
incoming_char=SIM900.read();
Serial.print(incoming_char);
}
}
I tried putting this command on the the if statement inside the loop, but after i tried comparing the words, it wouldnt work.
void loop() {
if(SIM900.available() >0) {
incoming_char=SIM900.read();
newString = incoming_char + "";
Serial.print(incoming_char);
}
if (newString == "Test"){
Serial.println("It worked");
}
}
The output that i get from the Monitor Serial is this:
+CMT: "+myNumber","","19/09/20,16:31:05-12"
Test
void loop() {
if (SIM900.available() >0) {
incoming_char=SIM900.read();
newString += incoming_char;
Serial.print(incoming_char);
}
if (newString.endsWith("Test")) {
Serial.println("It worked");
}
}
For does who are wondering how it finished:
Thanks to phoenixstudio...
void loop() {
if(SIM900.available() >0) {
incoming_char=SIM900.read();
newString += incoming_char;
Serial.print(incoming_char);
}
if (newString.endsWith("Test1")){
Serial.println("Worked1");
}
if (newString.endsWith("Test2")){
Serial.println("Worked2");
}
if (newString.endsWith("Test3"){
Serial.println("Worked3");
}
}

how to read char array from serial monitor and command arduino accordingly?

currently, I am working on a project to read char inputs from serial monitor and command Arduino to switch on/off specific pins. The problem I am facing is, I am unable to read the complete char array entered in the serial monitor. can anyone tell me what am I doing wrong?
#define X 13 //led pin
char txt[15];
int i;
int Status=0;
void setup() { // put your setup code here, to run once:
pinMode(X,OUTPUT);// setting the pin flow of control as output
Serial.begin(9600);
while(!Serial)
{
; //to wait for pc to connect
}
Serial.println("\nHome Automation");
dashprint();
}
void loop() { // put your main code here, to run repeatedly:
if(Serial.available()>0)
{ i=0;
while(Serial.available()>0) //if serial available
{ char inchar=Serial.read();
txt[i]=inchar; // add char to txt string
i++;// increment to where to write next
txt[i]='\0'; //null termination
}
Serial.print(txt);
check();
}
}
void dashprint() //to print dashes
{
Serial.println("-----------------------------------------------");
Serial.println("give me some command"); //ask for command
}
void check()
{ if(strncmp(txt,"ON",2)==0)
{
digitalWrite(X,HIGH);
Status=1;
}
else if(strncmp(txt,"OFF",3)==0)
{ digitalWrite(X,LOW);
Status=0;
}
else if(txt=="STATUS")
{
}
else Serial.println("ERROR");
}
output:
Home Automation
give me some command
OERROR
NERROR
ERROR
expected output:
Home Automation
give me some command
ON
Your arduino is too fast to read the text "ON" in one round.
9600 is 1 ms per character.
A simple workaround is, to add a little delay
if(Serial.available()>0) {
delay(3); // wait for the whole message
i=0;
while(Serial.available()>0) {
...
ADD:
Additionally, you obviously receive a '\n' (newline) character. Make sure it's not causing troubles.
And increase the delay or have a better approach in general, if you expect more than 3 characters ( "STATUS" )
struct MYObject {char a[256];};
//structure works well with EEPROM put and get functions.
//also lets to input large strings, more then 64 bytes, as http
void setup() {
MYObject str ={" "};
Serial.begin(115200);
while (!Serial.available()) delay (10); //wait for string
int i = 0;
int k= Serial.available();
while (k > 0){
char inchar = Serial.read(); //read one by one character
str.a[i] = inchar;
i++;
if (k < 3) delay (10); //it gives possibility to collect more characters on stream
k = Serial.available();
}
str.a[i]='\0'; //null terminator
//now lets see result
Serial.println(str.a);
//.....
}

Basic Arduino serial communication

I'm just trying to get the very basics of serial communication started; I'm trying to use this example I found, from what I understand it should be working. I just want what I type into the serial monitor to be output back, so I can see how it works. I also tried removing the while serial.available in case the serial monitor doesn't trigger that condition.
Here is my code:
// Buffer to store incoming commands from serial port
String inData;
void setup() {
Serial.begin(9600);
Serial.println("Initialized\n");
}
void loop() {
while (Serial.available() > 0)
{
char received = Serial.read();
inData += received;
// Process message when new line character is received
if (received == '\n')
{
Serial.println("Arduino Received: ");
Serial.println(inData);
inData = ""; // Clear received buffer
}
}
}
It currently uploads fine, and prints "initialized", but it doesn't work if I try to "send" any data.
Serial.read() returns an int.
You need to cast to (char) in order to store it as a char.
char received = (char)Serial.read();
Maybe you are never receiving any data for some reason.
Let's try something super simple. Use serialEvent() as suggested by sohnryang and then print some text as soon as Serial.available() triggers:
while (Serial.available() > 0) {
Serial.println("Something has been received");
}
You should see this message every time you send something to Arduino.
Use SerialEvent. So the code will look like this.
String inData;
void setup() {
Serial.begin(9600);
Serial.println("Initialized\n");
}
void loop() {
}
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
inData += inChar;
if (inChar == '\n') {
Serial.println("Arduino Recieved : ");
Serial.println("inData");
inData = "";
}
}
}

How to transmit a String on Arduino?

I want 2 Arduinos Leonardo to communicate, send a string for instance, so I have to use Serial1 to communicate via RS232 on pins 0 (RX) and 1 (TX).
I need to write binary data in that pins, the problem is how can I send a String using Serial1.write. Serial1.print works without errors but I think it does not do what I want. Any suggestion?
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
while (!Serial); // while not open, do nothing. Needed for Leonardo only
}
void loop() {
String outMessage = ""; // String to hold input
while (Serial.available() > 0) { // check if at least one char is available
char inChar = Serial.read();
outMessage.concat(inChar); // add Chars to outMessage (concatenate)
}
if (outMessage != "") {
Serial.println("Sent: " + outMessage); // see in Serial Monitor
Serial1.write(outMessage); // Send to the other Arduino
}
}
this line Serial1.write(outMessage); is giving me the error
"no matching function for call to 'HardwareSerial::write(String&)'"
You're using the String object(Wiring/C++). The function is using C strings: Serial.write(char*). To turn it into a C string, you use the toCharArray() method.
char* cString = (char*) malloc(sizeof(char)*(outMessage.length() + 1);
outMessage.stoCharArray(cString, outMessage.length() + 1);
Serial1.write(cString);
If we do not allocate the memory for our C string with malloc, we will get a fault. The following code WILL crash.
void setup() {
Serial.begin(9600);
String myString = "This is some new text";
char* buf;
Serial.println("Using toCharArray");
myString.toCharArray(buf, myString.length()+1); // **CRASH** buf is not allocated!
Serial.println(buf);
}
void loop() {
// put your main code here, to run repeatedly:
}
In the Serial Monitor the only message we will get is: Using toCharArray. At that point execution stops. Now if we correct the problem and use malloc() to allocate memory for our buffer and also use free() when done....
void setup() {
Serial.begin(9600);
String myString = "This is some new text";
char* buf = (char*) malloc(sizeof(char)*myString.length()+1);
Serial.println("Using toCharArray");
myString.toCharArray(buf, myString.length()+1);
Serial.println(buf);
Serial.println("Freeing the memory");
free(buf);
Serial.println("No leaking!");
}
void loop() {
// put your main code here, to run repeatedly:
}
The output we see in the Serial Monitor is:
Using toCharArray
This is some new text
Freeing the memory
No leaking!
Use toCharArry(), write() uses char*, not string, here is what i mean:
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
while (!Serial);
}
void loop() {
String outMessage = "";
while (Serial.available() > 0) {
char inChar = Serial.read();
outMessage.concat(inChar);
}
if (outMessage != "") {
Serial.println("Sent: " + outMessage);
char* CharString; //
outMessage.toCharArray(cString, outMessage.length()) // My Changes Are Here
Serial1.write(CharString); //
}
}

Resources