003 - Connecting and Disconnecting using Button

Welcome back to the RoboRemo tutorial.
In this tutorial I show how to connect and disconnect using a button, so instead of selecting menu -> connect -> ... you just press a button on the interface. In this way you can also connect to Bluetooth device without pairing. You just need to know its hardware (MAC) address, and the device must accept connections without authentication.
Note: For some applications, you may want to require authentication and / or encryption. Check your Bluetooth module datasheet on how to do that.



Arduino sketch same as in previous tutorial, just in case someone needs it:

// RoboRemo Tutorial 3 - Connecting and Disconnecting using Button
// www.roboremo.com

// Copyright 2020 roboremo.com
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// The above copyright notice and disclaimer shall be included
// in all copies or substantial portions of the Software.

// Hardware setup:

// PUSHBUTTON  Arduino
// PIN1 ------ D3
// PIN2 ------ GND

// Bluetooth   Arduino
// GND ------- GND
// VCC ------- 5V
// TX-O ------ RX0
// RX-I ------ TX1

#define BUTTON 3
#define BAUDRATE 115200

boolean switchON;
int b;
char cmd[100];
int cmdIndex;

void execute(char* cmd) {
  if(strcmp(cmd, "led 1")==0) {
    switchON = !switchON;
    if(switchON) {
      digitalWrite(LED_BUILTIN, HIGH); // LED -> ON
      Serial.print("led 1\n"); // virtual LED -> ON
    } else {
      digitalWrite(LED_BUILTIN, LOW);  // LED -> OFF
      Serial.print("led 0\n"); // virtual LED -> OFF
    }
  }
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  
  pinMode(BUTTON, INPUT_PULLUP);
  switchON = false;
  
  cmdIndex = 0;
  delay(500);
  Serial.begin(BAUDRATE);
}

void loop() {
  if(Serial.available()) {
    char c = (char)Serial.read();
    if(c=='\r' || c=='\n') {
      cmd[cmdIndex] = 0;
      cmdIndex = 0;
      execute(cmd);
    } else {      
      cmd[cmdIndex++] = c;
    }
  }

  // b is used for debouncing the pushbutton
  if(digitalRead(BUTTON) == HIGH) {
    // pushbutton not pressed
    b = 0;
  } else {
    // pushbutton pressed
    if(b < 100) {
      b++;
      delay(1);
    }
    // if still pressed, b will stall to 100
  }

  if(b == 99) {
    // this will get true only once
    // while pushbutton pressed
    execute("led 1");
  }
}