bluetooth code programming

Hi All

I'm trying to understand some programming ...

I have a bluetooth shield running right, and I'm able to send a "word" to the module with my cell phone.

I would want to send a text (ie "led on") to light on a LED

which lines should I add to my code please ?
Kind regards
Philippe

Since you did not bother to post your code I do not see how we can tell you "which lines should I add to my code please ?"

Here is example code to read the Bluetooth serial port and turn on the onboard LED (pin 13 on Uno, Nano, Mega). Send "led on" (no quotes) to turn the LED on and "led off" to turn the LED off. This code uses example 2 method from the serial input basics tutorial and the strcmp() function. The data from the sender must be terminated with a line feed character (0x0a, '\n').

#include <SoftwareSerial.h>
SoftwareSerial bt(4, 5); // RX | TX

const byte numChars = 16;
char receivedChars[numChars];   // an array to store the received data

const byte ledPin = 13;

boolean newData = false;

void setup()
{
   Serial.begin(38400);  // ****** set serial monitor to this baud rate
   bt.begin(38400);  // ******* insert the baud rate for your BT module (usual default is 9600)
   Serial.println("<Arduino is ready>");
   pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, LOW);
}

void loop()
{
   recvWithEndMarker();
   if (newData == true)
   {
      Serial.println(receivedChars);
      if (strcmp(receivedChars, "led on") == 0)
      {
         digitalWrite(ledPin, HIGH);
      }
      if (strcmp(receivedChars, "led off")== 0)
      {
         digitalWrite(ledPin, LOW);
      }
      newData = false;
   }
}

void recvWithEndMarker()
{
   static byte ndx = 0;
   char endMarker = '\n';
   char rc;

   while (bt.available() > 0 && newData == false)
   {
      rc = bt.read();
      //Serial.print(rc);
      if (rc == '\r')
      {
         return;
      }
      if (rc != endMarker)
      {
         receivedChars[ndx] = rc;
         ndx++;
         if (ndx >= numChars)
         {
            ndx = numChars - 1;
         }
      }
      else
      {
         receivedChars[ndx] = '\0'; // terminate the string
         ndx = 0;
         newData = true;
      }
   }
}

Assuming your bluetooth module is connected via serial this code will respond to on and off commands

/**
   Control Led via bluetooth
   Assume bluetooth via serial like https://www.forward.com.au/pfod/BLE/index.html#Adafruit
*/
#include "SafeString.h" // my SafeString library from the Arduino library manager

char onCmd[] = "on";
char offCmd[] = "off";
char delimiters[] = " \r\n"; // space CR NL are cmd delimiters or accept after 2sec

const size_t maxCmdLength = 5; // length of largest command to be recognized, can handle longer input but will not tokenize it.
createSafeString(input, maxCmdLength + 1); //  to read input cmd, large enough to hold longest cmd + leading and trailing delimiters
createSafeString(token, maxCmdLength + 1); // for parsing, capacity should be >= input
bool skipToDelimiter = true; // bool variable to hold the skipToDelimiter state across calls to readUntilToken()
// set skipToDelimiter = true to skip initial data upto first delimiter.
// skipToDelimiter = true can be set at any time to next delimiter.
unsigned long TIMEOUT_MS = 2000; // 2sec

// assuming you bluetooth is connected via Serial
void setup() {
  Serial.begin(9600);    // Open serial communications and wait a few seconds
  for (int i = 10; i > 0; i--) {
    delay(500);
  }
  // first run without any outputting any error msgs or debugging
  //SafeString::setOutput(Serial); // enable error messages and debug() output to be sent to Serial
}

void handleonCmd() {
  // turn led On here
}
void handleoffCmd() {
  // turn led Off hereSerial.println(); Serial.println(F(" Found offCmd"));
}

void loop() {
  if (input.readUntilToken(Serial, token, delimiters, skipToDelimiter, false, TIMEOUT_MS )) {
    //                                  use false to suppress echo of input, back to bluetooth
    if (token == onCmd) {
      handleonCmd();
    } else if (token == offCmd) {
      handleoffCmd();
    } // else token is empty
  }
  // rest of code here if any
}

You don't need to send a \r or \n the command will be accepted after 2sec. All other words will be ignored

Hi drmpf,

good example code. Nevertheless I want to post a version with a minor change
you named the SafeString-variables "Input" and "token". especcially the word "input" is so general that it might be hard to understand for newbees what it really is.

So I renamed then to "myInputStr" and "myTokenStr" to indicate through the prefix "my" it is a user-choosable name and the suffix "Str" to indicate it is SafeString-variable.

/**
   Control Led via bluetooth
   Assume bluetooth via serial like https://www.forward.com.au/pfod/BLE/index.html#Adafruit
*/
#include "SafeString.h" // my SafeString library from the Arduino library manager

char onCmd[]  = "on";
char offCmd[] = "off";
char delimiters[] = " \r\n"; // space CR NL are cmd delimiters or accept after 2sec

const size_t maxCmdLength = 5; // length of largest command to be recognized, can handle longer input but will not tokenize it.
createSafeString(myInputStr, maxCmdLength + 1); //  to read input cmd, large enough to hold longest cmd + leading and trailing delimiters
createSafeString(myTokenStr, maxCmdLength + 1); // for parsing, capacity should be >= myInputStr
bool skipToDelimiter = true; // bool variable to hold the skipToDelimiter state across calls to readUntilToken()
// set skipToDelimiter = true to skip initial data upto first delimiter.
// skipToDelimiter = true can be set at any time to next delimiter.
unsigned long TIMEOUT_MS = 2000; // 2sec

// assuming your bluetooth is connected via Serial
void setup() {
  Serial.begin(9600);    // Open serial communications and wait a few seconds
  for (int i = 10; i > 0; i--) {
    delay(500);
  }
  // first run without any outputting any error msgs or debugging
  //SafeString::setOutput(Serial); // enable error messages and debug() output to be sent to Serial
}

void handleonCmd() {
  // turn led On here
}
void handleoffCmd() {
  // turn led Off hereSerial.println(); Serial.println(F(" Found offCmd"));
}

void loop() {
  if (myInputStr.readUntilToken(Serial, myTokenStr, delimiters, skipToDelimiter, false, TIMEOUT_MS )) {
    //                                  use false to suppress echo of input, back to bluetooth
    if (myTokenStr == onCmd) {
      handleonCmd();
    } else if (myTokenStr == offCmd) {
      handleoffCmd();
    } // else myTokenStr is empty
  }
  // rest of code here if any
}

what your post does not explain is what kind of character-sequence has to be send to make it work

best regards Stefan

Thanks stefan. Works with any text sequence. It will ignore all space delimited words except on and off
and can handle unlimited length inputs

Hi all
thanks for your feedback
here's the code I'm using :

#include <SoftwareSerial.h>   //Software Serial Port
#define RxD 7  // sur le module jumper TX sur 6
#define TxD 6 //sur le module jumper RX sur 7
#define DEBUG_ENABLED  1
SoftwareSerial blueToothSerial(RxD,TxD);

void setup()
{
Serial.begin(9600);
pinMode(RxD, INPUT);
pinMode(TxD, OUTPUT);
setupBlueToothConnection();
}
void loop()
{
char recvChar;
while(1)
{
if(blueToothSerial.available())
{
recvChar = blueToothSerial.read();
Serial.print(recvChar);
}
if(Serial.available())
{
recvChar  = Serial.read();
blueToothSerial.print(recvChar);
}
}
}
void setupBlueToothConnection()
{
blueToothSerial.begin(9600); // Set BluetoothBee BaudRate to default baud rate 38400
blueToothSerial.print("\r\n+STWMOD=0\r\n"); // set the bluetooth work in slave mode
blueToothSerial.print("\r\n+STNA=SeeedBTSlave\r\n"); // set the bluetooth name as "SeeedBTSlave"
blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
blueToothSerial.print("\r\n+STAUTO=0\r\n");  // Auto connection should be forbidden here
delay(2000); // This delay is required
Serial.print("\r\n+INQ=1\r\n"); // make the slave bluetooth inquirable
Serial.println("The slave bluetooth is inquirable!");
delay(2000);  // This delay is required.
blueToothSerial.flush();
}

Other examples can be found in e.g. Robin's updated Serial Input Basics thread. Go through it to understand and get some ideas.

PS
You will have to replace serial by a software serial instance (based on your code).

Thank you to all

groundfungus code works fine for example

But ... is there some library conflict if I want to add a servo to my code

I've an error message ... '

bluetooth_led:24:1: error: 'recvWithEndMarker' was not declared in this scope

Merry Christmas

But ... is there some library conflict if I want to add a servo to my code

What leads you to believe that?

bluetooth_led:24:1: error: 'recvWithEndMarker' was not declared in this scope

You should post the code that causes the error. My guess is that there is a curly bracket (}) missing to close the loop() function. Use the IDE autoformat tool (ctrl-t or Tools, Auto Format) and you might see where the problem is.

If that is not it, post the code.

And please post the entire error message. It is easy to do. There is a button (lower right of the IDE window) called "copy error message". Copy the error and paste into a post in code tags. Paraphrasing the error message leaves out important information.

groundFungus:
What leads you to believe that?
You should post the code that causes the error. My guess is that there is a curly bracket (}) missing to close the loop() function. Use the IDE autoformat tool (ctrl-t or Tools, Auto Format) and you might see where the problem is.

If that is not it, post the code.

And please post the entire error message. It is easy to do. There is a button (lower right of the IDE window) called "copy error message". Copy the error and paste into a post in code tags. Paraphrasing the error message leaves out important information.

Thanks, you were right (a missing curly bracket)
Best regards