// Arduino, HM-10, App Inventor 2 // // Example Project Part 2: Turn an LED on and off 2 way control 01 // By Martyn Currey. www.martyncurrey.com // // Pins // BT VCC to Arduino 5V out. // BT GND to GND // Arduino D8 (ASS RX) - BT TX no need voltage divider // Arduino D9 (ASS TX) - BT RX through a voltage divider // Arduino D2 - Resistor + LED // Arduino D3 - 10K pull down resistor + button switch // AltSoftSerial uses D9 for TX and D8 for RX. While using AltSoftSerial D10 cannot be used for PWM. // Remember to use a voltage divider on the Arduino TX pin / Bluetooth RX pin // Download from https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html #include AltSoftSerial ASSserial; // Constants for hardware const byte LEDPin = 2; const byte SwitchPin = 3; // general variables boolean LED_State = false; boolean switch_State = false; boolean oldswitch_State = false; char c=' '; void setup() { Serial.begin(9600); Serial.print("Sketch: "); Serial.println(__FILE__); Serial.print("Uploaded: "); Serial.println(__DATE__); Serial.println(" "); ASSserial.begin(9600); Serial.println("AltSoftSerial started at 9600"); Serial.println(" "); pinMode(LEDPin, OUTPUT); digitalWrite(LEDPin,LOW); pinMode(SwitchPin, INPUT); } // void setup() void loop() { checkSwitch(); checkRecievedData(); } void checkSwitch() { // Simple toggle switch function with even simpler debounce. boolean state1 = digitalRead(SwitchPin); delay(1); boolean state2 = digitalRead(SwitchPin); delay(1); boolean state3 = digitalRead(SwitchPin); if ((state1 == state2) && (state1==state3)) { switch_State = state1; if ( (switch_State == HIGH) && (oldswitch_State == LOW) ) { // toggle LED_State. LED_State = ! LED_State; // If LED_State is HIGH then LED needs to be turned on. if ( LED_State == HIGH) { digitalWrite(LEDPin,HIGH); // turn on the LED ASSserial.print("1" ); // tell the app the LED is now on Serial.println("Sent - 1"); } else { digitalWrite(LEDPin,LOW); // turn off the LED ASSserial.print("0"); // tell the app the LED is now off Serial.println("Sent - 0"); } } oldswitch_State = switch_State; } } void checkRecievedData() { // Read from the Bluetooth module and turn the LED on and off if (ASSserial.available()) { c = ASSserial.read(); Serial.println(c); // The ascii code for 0 is dec 48 // The ascii code for 1 is dec 49 if ( c== 48) { digitalWrite(LEDPin, LOW); LED_State = LOW; } if ( c== 49) { digitalWrite(LEDPin, HIGH); LED_State = HIGH; } } }