Showing posts with label Bluetooth. Show all posts
Showing posts with label Bluetooth. Show all posts

Wednesday, April 19, 2017

Fun with Robots, IR Decoding, LED Matrix, etc.

Fig 1: Three experiment--two with the samsung remote on the left, one with the Radio Shack remote on the right--to control a +Adafruit Industries 8x8 Bicolor LED Matrix
I haven't posted in a while because several interests have kept me very busy. This all started withe the +Parallax Board of Education (BOE) Robot kit. I asked for and received on for Christmas a couple of years ago and let it ripen until I was ready.  I decided that it would make a good project to do with my 7-year-old granddaughter when she visits this summer--but first, I should make sure that I can build it without a lot of fumbling. Fumbling is good, but watching me figure out what dumb thing I did is not always interesting to a 7yr-old. I followed the tutorial and learned quite a bit, The last project that I did used infrared for proximity sensing to avoid obstacles. At the same time, +Adafruit Industries, via The Desk of Lady Ada, provided some great information on IR. So, I decided to play and learn further.
Fig 2: +Parallax BOE Bot with 2 IR transmitters aand 2 IR receivers

IR Decoding the Hard Way

Following the +Adafruit Industries tutorial on IR Sensing, I was able to decode only some of the buttons on my Samsung TV Remote (see Figure 1). Using the remote is a 2-step process: first decode the signals send by the buttons, then use the decoded signals in a different sketch that takes action based on the buttons. Using this method (see the Raw IR Decoder and ircommander code on github), I was able to decode some of the buttons and use them in a sketch.  

Quick diversion:  I have had big plans to use a 32x32 LED Matrix that I bought in a parking assistant project that will display faces to convey the emotions evoked by a car getting increasingly closer. I decided to use the 8x8 bicolor matrix and backpack to prove the concept, and use the remote to signal which face to display. Figure 1 shows the initialized yellow face (looks orange to me). So, I needed to follow the tutoral for the matrix and backback library.

I was able to merge code from the bicolor8x8 example code in the Adafruit LED Backpack library with code from the ircommander sketch referenced above. After adding the decoded remote buttons to a newly created library (see the IR Sensor tutorial and the project video cited at the end of this post), I was able to change the face on the matrix based on the remote buttons.

I found both the coding aspect and the operation of the technique to be less than perfect.  Maintaining a separate library with very long sequences of numbers just to test what button  was pressed seems a bit much. In operation, the code seems to reset itself randomly, and only respond to buttons when it feels like. This may be me, and I will investigate, but read on to see a much neater technique.

IR Decoding an Easier Way

After working through the above, I watched Lady Ada work through Chris Young's IRLib2 in one of the Desk of Lady Ada epdisodes cited above.  Chris, aka cyborg5, is a frequent visitor to the Adafruit Show and Tell, and has done a lot of great work (see his blog).  Both the decoding and the processing techniques are simplifies greatly, and his library handles several IR protocols. The IRLIB2 tutorial describes it all very well.  You wind up with one simple code that you supply in a sketch so you can determine what button was pressed--straightforward, and I was able to decode all the buttons with no missed presses. From there it was a matter of simplifying the sketch I wrote earlier to display faces on the LED matrix.  Again, the project video shows all this.

Controlling Motors with IR

Since we started with robots, I thought it would be interesting to control motors with IR.  It was a simple matter to modify the IRLib2 sketch above to direct the continuous rotation servos.  I took code from the BOE-Bot project, and code from the Adafruit_PWMServoDriver library tutorial, and it went smoothly.  The servos in the BOE-Bot are different from the Adafruit ones, so I had to go to the data sheet to see what values to use to get them to move as I wanted. I was able to decode all the buttons on the Samsung remote, and used the arrow keys to simulate moving the robot forward, back, left, and right.

I first did this without the PWM Servo FeatherWing. Because the feather is 3V logic, I needed a level shifter to handle the signals from the board to the servos. That worked, but added a few connections and I used the Arduino servo library as opposed to the Adafruit library which allowed for simpler code.

Another thing I needed to worry about was timer conflicts. I had come across this before, in my Donkey Project, but Chris' tutorial gave a straightforward explanation and solution. The problem is that the servo library uses Timer1 and on the 32u4 Feather IRLib2 does too. It was necessary to go into one of the associated libraries and change one line of code to re-assign the timer.  You'll get better instruction in the tutorial than I can give here.  Again, the project video shows the results.
Controlling 2 FS90R continuous rotation servos from an Adafruit BLE Feather and PWM Servo FeatherWing

Trying a Different Remote

A while back, Radio Shack sold some MAKE project kits, including robotics. During an earlier RS bankruptcy, I acquired a RS remote at a big discount and still had it in inventory, so I decided to try it out. Using the IRLib2 approach to decoding, I found the the protocol was not one of supported ones. A look at the datasheet for the PT2248 chip in the remote revealed that ot used the Toshiba protocol. So, I had to go back to the hard way, and I got that to work.  See the video.

IR Affects the BOE-Bot

Just for grins, I took out the BOE-Bot, let it runon the floor, and chased it with a remote.  The bot's IR retrievers detected the transmissions, and the bot reacted accordingly (moving left or right as if it had detected an obstacle).

Project Video

See the project video on YouTube

Monday, August 15, 2016

Control AC Devices over the Internet



When I built the project described in my post on controlling devices from a smartphone, my brother-in-law said "yeah, but can you do that over the internet?"  The answer was yes, but I needed to wait until my +Adafruit Industries Feather Huzzah with ESP8266 WiFi arrived. I had already decided to use adafruit.io as the browser component.  It was super easy to set up a dashboard and two feeds-a button interface to turn the light on and off and a text feed (output from the Huzzah) so I could see what the code thinks it's doing (see the tutorials at the adafruit.io link provided above.

By following the tutorials and code examples, and cloning what I could from tmy bluetooth project (see above), I got it working very quickly.  However, I wanted it to be a useful device that I could give to my brother-in-law. As noted in other posts, he has helped with all kinds of projects.  So, I needed a project box, a circuit board and a few other things, and I needed to do some designing. My first thought was to find a 120V relay and make my own Power Switch Tail.  In studying the schematic, I found that there were all kinds of circuit protections included, so I decided to go with a commercial product.  The powerswitch was US$26, so I looked for an alternative.  I found this AC/DC Control Relay on Amazon. The price has gone up by $2 since I bought it, but it's still $9 less than the powerswitch and has more capability. For example, it has 4 receptacles, 2 normally off and 2 normally on, so it can control multiple devices.

Parts and supplies list, partially annotated

  • AC/DC Comtrol Relay (takes input from the Huzzah: a signal line and a ground line; different from powerswitch tail, which also takes a DC power input; in addition the logic is opposite--power swith tail closes the relay on LOW, this one closes it on HIGH) )
  • +Adafruit Industries Feather Huzzah with ESP8266 WiFi Board
  • 2-wire JST connectors (connect to the relay)
  • LEDs (I used 5mm, one green, one red)
  • resistors (current-limiting for LEDs--I used 330Ohm)
  • 22-gauge solid core hookup wire 
  • tinned copper bus wire
  • project box (this was tight, but I wanted it small)
  • circuit board (I started to use plain perf board, but it broke--these boards were not quite the right size, so I had to file them. The soldering pads were useful.)
  • 3/8" 4-40 machine screws (to attache the circuit board to the standoffs in the box)
  • Drill and bits
  • A set of files (to deburr the drilled holes, and to size the holes properly)
  • Normal project tools: soldering iron and accessories, multimeter, strippers, clippers, helping hands and/or Panavise Jr., and the like
  • Super Glue or the like to fix the LEDs and JST to the box
  • Heat shrink tubing

Concept

The circuit is very simple, maybe deceptively so.  As you will see in the code, it connects to wifi, then connects to adafruit.io, and turns everything off at the start (in setup), then waits for orders from adafruit.io.  The toggle button on the adafruit.io dashboard sends info to the Huzzah, and depending on the state of the lamp (or whatever device you have plugged into the relay), it toggles the state.

The LEDs are used as indicators.  The green LED turns on after successful connection to adafruit.io (if it's not on, there's a problem). The red LED turns on and off with the lamp or other device (also to help see what's going on).

Schematic


Assembly

I spent a lot of time planning where to put the LEDS and the JST connectot. I had some scrap ABS plastic left from my robot cart project, so I used that to test a few options:




I wanted the JST to be recessed, but that didn't work out. I liked the LED holders, but they took up too much room in the box.

I drilled a hole in one end of the box for the USB cable, then drilled 3 3/16" holes in one side for the LEDs and JST connector.  The holes needed to be enlarged, so I took time to get just enough room to get the components through, while still not allowing the whole component to pass.

I had to expand two of the mounting holes on the circuit board to get the screws through. The other two holes did not line up with the standoffs.  I planned to mount the board with the soldering pads down, so I could keep the minimal wiring out of the way.

I positioned the Huzzah on the board, and used hookup wire to fix the back end to the circuit board through the mounting holes.  I had to remove one later to allow access to one of the LED holes in the case.  I ran black hookup wire under the board from the HUZZAH GND pin to the Ground bus on the other side of the board.  I soldered the hookup wire to the GND pin and to the soldering pad in the corner of the opposite side.  I ran tinned copper bus wire from the hookup wire down that side of the board and soldered each corner.


Next, I conencted the 330Ohm resistors through the board to the Ground bus and soldered them to it, then cut the wires on the female end of the JST to length, positioned it in the hole in the box, and soldered the black wire to the Ground bus and the red wire to pin 2 (see schematic above).

Note: if I were to do this again, I would run the Ground bus down the opposite side of the board, solder one end of the resistors to it on the underside, and solder the other ends of the resistors to the ground leads of the LEDs. That would make it neater.

I then took the time to test the circuit to be sure the connections were OK.  Using the Arduino IDE serial monitor and the relay with a lamp plugged in, I found that all was good.  I then added the LEDs, connecting the proper leads to the resistors and to the correct pins, and soldering.  One more test showed the LEDs functioning properly, so I screwed the circuit board to the box.

The final touches were to trim the connections to the resistors, use some electrical tape for insulation, and to super glue the LEDs and JST connector to the box.  Finally, I spliced the male end of the JST to hookup wires leading to the corresponding connections on the relay (there is a terminal block on the relay).  After testing the connections for continuity with my multimeter, I applied heat shrink to each splice and then a long piece of heat shrink to the whole connection.
Enclosure before gluing LEDS and JST and adding screws

Project Video

On my youtube channel

Code

/***************************************************
  Adafruit MQTT Library ESP8266 Example

  Must use ESP8266 Arduino from:
    https://github.com/esp8266/Arduino

  Works great with Adafruit's Huzzah ESP board:
  ----> https://www.adafruit.com/product/2471
  products from Adafruit!

  Written by Tony DiCola for Adafruit Industries.
  Adafruit IO example additions by Todd Treece.
  MIT license, all text above must be included in any redistribution
 ****************************************************/
/*  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing */

/*2015-08-15 Virgil Machine
  Light goes on, light goes off, internet style
  I used the adfruit.io tutorial and the adafruit esp8266
  tutorial and library examples to get the connection stuff.
  The logic is mainly cloned from my bluetooth example 
  (see virgilmachine.blogspot.com). Connects to WIFI, connects 
  to adafruit.io, turns on green LED to indicate connection,inbitializes 
  logic and devices to off, then waits for instructions from 
  adafruit.io--toggle switch to turn light on and off. Sets relay
  pin to HIGH, also turns on red LED and on-board LED, and vice versa.
  */
#include
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

// function prototypes
void connect(void);

/****************************** Pins ******************************************/

#define LAMP           2  // AC/DC Control Relay 
#define LED            0  // on-board LED
#define POWER_LED      4  // lED to show power on
#define LAMP_LED       5  // lED to show LAMP on

/************************* WiFi Access Point *********************************/
//use your own values here

#define WLAN_SSID       "SSID"
#define WLAN_PASS       "PASSWORD"

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883
//use your own values here
#define AIO_USERNAME    "USERNAME"
#define AIO_KEY         "adafruit.io KEY"

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;

// Store the MQTT server, client ID, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM    = AIO_SERVER;
// Set a unique MQTT client ID using the AIO key + the date and time the sketch
// was compiled (so this should be unique across multiple devices for a user,
// alternatively you can manually set this to a GUID or other random value).
const char MQTT_CLIENTID[] PROGMEM  = __TIME__ AIO_USERNAME;
const char MQTT_USERNAME[] PROGMEM  = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM  = AIO_KEY;
int current = 0;
char light_on[] = "Light Goes On";
char light_off[] = "Light Goes Off";
//2016-08-08 vm char stuff replaced by boolean
bool lamp_on = false;  //initalized to off to match the rest of the code

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_CLIENTID, MQTT_USERNAME, MQTT_PASSWORD);

/****************************** Feeds ***************************************/

// Setup a feed called 'lamp' for subscribing to changes.
// Notice MQTT paths for AIO follow the form: /feeds/
const char LAMP_FEED[] PROGMEM = AIO_USERNAME "/feeds/UncleJimThing";
Adafruit_MQTT_Subscribe lamp = Adafruit_MQTT_Subscribe(&mqtt, LAMP_FEED);
// Use feed UncleJimText as TEXT_FEED for publishing changes.
// Notice MQTT paths for AIO follow the form: /feeds/
const char TEXT_FEED[] PROGMEM = AIO_USERNAME "/feeds/UncleJimText";
Adafruit_MQTT_Publish text = Adafruit_MQTT_Publish(&mqtt, TEXT_FEED);
/*************************** Sketch Code ************************************/

void setup() {

  // setup relay and LED pins as outputs and start off as LOW
  pinMode(LAMP, OUTPUT);
  digitalWrite(LAMP, LOW);  //default to off at startup (had this backwards) 
  pinMode(LED, OUTPUT);  //for testing
  digitalWrite(LED, LOW);  //default to off at startup
  // setup pins for indicator LEDS 
  pinMode(LAMP_LED, OUTPUT);
  digitalWrite(LAMP_LED, LOW);  //default to off at startup
  // POWER_LED IS SET to HIGH in connect() routine, after successful connection
  //but default to off until then
  pinMode(POWER_LED, OUTPUT);  //to show if we're connected
  digitalWrite(POWER_LED, LOW);  //default to off at startup 
  
  Serial.begin(115200);

  Serial.println(F("Uncle Jim IO Example"));

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  delay(10);
  Serial.print(F("Connecting to "));
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(F("."));
  }
  Serial.println();

  Serial.println(F("WiFi connected"));
  Serial.println(F("IP address: "));
  Serial.println(WiFi.localIP());

  // listen for events on the lamp feed
  mqtt.subscribe(&lamp);

  // connect to adafruit io
  /* when we connect successfully, the LED is turned on
  so we enter loop with the POWER_LED indicator on
  but it's off until then
  */
  connect();
/****2016-07-17 VM 
     We want the test to say "light goes off at startup, since we set if off in setup
     I think this will work here--***experiment***
****/
     text.publish(light_off);
}

void loop() {

  Adafruit_MQTT_Subscribe *subscription;

  // ping adafruit io a few times to make sure we remain connected
  if(! mqtt.ping(3)) {
    // reconnect to adafruit io
    if(! mqtt.connected())
    { digitalWrite(POWER_LED, LOW);  //turn off LED to show we're not connected  
      connect();
    }  
  }


  // this is our 'wait for incoming subscription packets' busy subloop
  while (subscription = mqtt.readSubscription(1000)) {

    // we only care about the lamp events
    if (subscription == &lamp) {

      // convert mqtt ascii payload to int
      char *value = (char *)lamp.lastread;
      Serial.print(F("Received: "));
      Serial.println(value);
      Serial.print(F("\nlamp-state in: "));
      Serial.println(lamp_on);
      int current = atoi(value);
      if (lamp_on) {  
        Serial.println(light_off);
        text.publish(light_off);
        digitalWrite(LAMP, LOW);  //RELAY
        digitalWrite(LED, LOW);  //ON-BOARD
        digitalWrite(LAMP_LED, LOW); //INDICATOR
      } else {  
        Serial.println(light_on);
        text.publish(light_on);
        digitalWrite(LAMP, HIGH); 
        digitalWrite(LED, HIGH);
        digitalWrite(LAMP_LED, HIGH);          
      } 
      lamp_on = !lamp_on; //toggle lamp state         
      Serial.print(F("\nlamp-state out: "));
      Serial.println(lamp_on);
  
      Serial.print(F("\nSending button value: "));
      Serial.print(value);
      Serial.print("... ");

    }   //if subscription is lamp
  }     //while subscription
}       //loop

// connect to adafruit io via MQTT
void connect() {

  Serial.print(F("Connecting to Uncle Jim IO... "));

  int8_t ret;

  while ((ret = mqtt.connect()) != 0) {

    switch (ret) {
      case 1: Serial.println(F("Wrong protocol")); break;
      case 2: Serial.println(F("ID rejected")); break;
      case 3: Serial.println(F("Server unavail")); break;
      case 4: Serial.println(F("Bad user/pass")); break;
      case 5: Serial.println(F("Not authed")); break;
      case 6: Serial.println(F("Failed to subscribe")); break;
      default: Serial.println(F("Connection failed")); break;
    }

    if(ret >= 0)
      mqtt.disconnect();

    Serial.println(F("Retrying connection..."));
    delay(5000);

  }

  Serial.println(F("Uncle Jim IO Connected!"));
  digitalWrite(POWER_LED, HIGH);  //turn on LED to show we're connected  
}

Saturday, May 28, 2016

Control AC devices with a Smartphone

I found this tutorial and thought it was a cool idea. It describes how to control a light (or any AC device) from a Bluetooth app on a smartphone.

I thought it would be something that my granddaughter would enjoy when she comes this summer. The tutorial gives what I assume is a lot of useful information, but it gets into the weeds of bluetooth much more than I'm interested in at this point, and all I want is to allow a 6-year-old to turn a light on and off.

I followed the tutorial though steps 1 and 2.  Step one uses Blink to flash an LED. Step two adds a button with some interrupt handling. The authors do not mention that in order to get this code to work without a bluetooth nRF8001 module connected, you need to comment out the line "blePeripheral.begin();" in setup--otherwise it hangs there--I guess waiting for a bluetooth board. So I got steps 1 and 2 working.

For step 3, I need to add a board. I have the +Adafruit Industries Bluetooth LE module  (nRF8001 chip) that the authors suggest, but I found it simpler to use the Adafruit Feather Bluefruit LE board (nRF51822 chip) . Since the boards use different Nordic chips, I had to figure out how to get the code to work. The Make tutorial uses the BLEPeripheral library, which I did not get to work, so I used the Adafruit_BluefruitLE_nRF51 library, and the functions are very different.

The code in the Make tutorial looked overly complex for what I wanted,  Since this is my first Bluetooth project, so I wanted to start slowly.  Following the Adafruit tutorial, I installed the " Adafruit_BluefruitLE_nRF51" library and the Adafruit BLE connect app for Android and started working through the example programs. "bleuart_cmdmode" did what I needed: communicate between the module and the app. I set it up so that sending "ON"--all caps--turns the light on and "OFF"--caps again--turns it off,

With nothing but the Feather, a resistor, and an LED I was able to turn the LED on and off from my phone. After 40 years of programming I still get a kick out of seeing something work the first time--no matter how simple.

Next I needed to add the PowerSwitch Tail. It was very simple, except that I did not have a screwdriver small enough to tighten the terminal blocks. Fortunately, my brother-in-law has tools (in addition to skills) and we got it connected. I connected pin 1 to the 3.3V rail on the breadboard, pin 2 to pin 6 on the Feather (the LED pin), and pin 3 to the ground rail on the breadboard.  Then I plugged one end of the PowerSwitch to a 110VAC wall receptacle and plugged a light into the other end.

Power Switch Tail with jumper wires, ready for hookup
The PowerSwitch is a Normally Open relay, so when you hook it up the device (light in my case) is off.  When pin 2 on the PowerSwitch is set LOW, the relay closes and the device turns on.  This is the reverse of the way my code worked, so when the LED was on (Feather pin 6 HIGH), the light was off and vice versa.  This makes a little sense--it gives you some light when the AC light is off, but it's not intuitive for a 6-year-old to say "ON"and turn a light off.  So, I added a pin (5), connected pin 2 of the PowerSwitch to that, and set it LOW for ON and HIGH for OFF.

Project Video.

Now that I feel comfortable with the concepts (as far as I've gone), I can go back to the original Make tutorial and learn more. This is cool.

Here's the code that goes with the video (as mentioned above it's a modification of the "bleuart_cmdmode" example in the Adafruit Bluefruit nRF51 library):

/*********************************************************************
 This is an example for our nRF51822 based Bluefruit LE modules

 Pick one up today in the adafruit shop!

 Adafruit invests time and resources providing this open source code,
 please support Adafruit and open-source hardware by purchasing
 products from Adafruit!

 MIT license, check LICENSE for more information
 All text above, and the splash screen below must be included in
 any redistribution
*********************************************************************/

#include
#include
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)
  #include
#endif

#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"

#include "BluefruitConfig.h"

/*=========================================================================
    APPLICATION SETTINGS

    FACTORYRESET_ENABLE       Perform a factory reset when running this sketch
   
                              Enabling this will put your Bluefruit LE module
                              in a 'known good' state and clear any config
                              data set in previous sketches or projects, so
                              running this at least once is a good idea.
   
                              When deploying your project, however, you will
                              want to disable factory reset by setting this
                              value to 0.  If you are making changes to your
                              Bluefruit LE device via AT commands, and those
                              changes aren't persisting across resets, this
                              is the reason why.  Factory reset will erase
                              the non-volatile memory where config data is
                              stored, setting it back to factory default
                              values.
       
                              Some sketches that require you to bond to a
                              central device (HID mouse, keyboard, etc.)
                              won't work at all with this feature enabled
                              since the factory reset will clear all of the
                              bonding data stored on the chip, meaning the
                              central device won't be able to reconnect.
    MINIMUM_FIRMWARE_VERSION  Minimum firmware version to have some new features
    MODE_LED_BEHAVIOUR        LED activity, valid options are
                              "DISABLE" or "MODE" or "BLEUART" or
                              "HWUART"  or "SPI"  or "MANUAL"
    -----------------------------------------------------------------------*/
    #define FACTORYRESET_ENABLE         1
    #define MINIMUM_FIRMWARE_VERSION    "0.6.6"
//    #define MODE_LED_BEHAVIOUR          "MODE"
    #define MODE_LED_BEHAVIOUR          "MANUAL" //2016-05-27 vm
    #define TAIL_PIN                    5
    #define LED_PIN                     6
    int LED_STATE;
    char* x;
    char y;
/*=========================================================================*/

// Create the bluefruit object, either software serial...uncomment these lines
/*
SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);

Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,
                      BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);
*/

/* ...or hardware serial, which does not need the RTS/CTS pins. Uncomment this line */
// Adafruit_BluefruitLE_UART ble(Serial1, BLUEFRUIT_UART_MODE_PIN);

/* ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST */
Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */
//Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,
//                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,
//                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);


// A small helper
void error(const __FlashStringHelper*err) {
  Serial.println(err);
  while (1);
}

/**************************************************************************/
/*!
    @brief  Sets up the HW an the BLE module (this function is called
            automatically on startup)
*/
/**************************************************************************/
void setup(void)
{
//2016-05-27 define light pins as output and set them to off
//(relay on switch tail is reverse--flops closed for on when low)
  pinMode(LED_PIN, OUTPUT);
  pinMode(TAIL_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);
  digitalWrite(TAIL_PIN, HIGH);
  LED_STATE = 0;
//  while (!Serial);  // required for Flora & Micro--2016-05-28 vm causes feather to hang if not
//  connected via usb
//2016-05-27 end
delay(500);

  Serial.begin(115200);
  Serial.println(F("Adafruit Bluefruit Command Mode Example"));
  Serial.println(F("---------------------------------------"));

  /* Initialise the module */
  Serial.print(F("Initialising the Bluefruit LE module: "));

  if ( !ble.begin(VERBOSE_MODE) )
  {
    error(F("Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?"));
  }
  Serial.println( F("OK!") );

  if ( FACTORYRESET_ENABLE )
  {
    /* Perform a factory reset to make sure everything is in a known state */
    Serial.println(F("Performing a factory reset: "));
    if ( ! ble.factoryReset() ){
      error(F("Couldn't factory reset"));
    }
  }

  /* Disable command echo from Bluefruit */
  ble.echo(false);

  Serial.println("Requesting Bluefruit info:");
  /* Print Bluefruit information */
  ble.info();

  Serial.println(F("Please use Adafruit Bluefruit LE app to connect in UART mode"));
  Serial.println(F("Then Enter characters to send to Bluefruit"));
  Serial.println();

  ble.verbose(false);  // debug info is a little annoying after this point!

  /* Wait for connection */
  while (! ble.isConnected()) {
      delay(500);
  }
//Serial.println(
  // LED Activity command is only supported from 0.6.6
//  if ( ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )
//  {
    // Change Mode LED Activity
    Serial.println(F("******************************"));
    Serial.println(F("Change LED activity to " MODE_LED_BEHAVIOUR));
    ble.sendCommandCheckOK("AT+HWModeLED=" MODE_LED_BEHAVIOUR);
    Serial.println(F("******************************"));
//  }
}

/**************************************************************************/
/*!
    @brief  Constantly poll for new command or response data
*/
/**************************************************************************/
void loop(void)
{
  // Check for user input
  char inputs[BUFSIZE+1];

  if ( getUserInput(inputs, BUFSIZE) )
  {
    // Send characters to Bluefruit
    Serial.print("[Send] ");
    Serial.println(inputs);

    ble.print("AT+BLEUARTTX=");
    ble.println(inputs);

    // check response stastus
    if (! ble.waitForOK() ) {
      Serial.println(F("Failed to send?"));
    }
  }

  // Check for incoming characters from Bluefruit
  ble.println("AT+BLEUARTRX");
  ble.readline();
  if (strcmp(ble.buffer, "OK") == 0) {
    // no data
    return;
  }
  // Some data was found, its in the buffer
  Serial.print(F("[Recv] ")); Serial.println(ble.buffer);
//2016-05-27 vm test buffer for ON or OFF, display results  on serial monitor and bluetooth device,
//turn LED and Light on or off (or do nothing)
  if (strcmp(ble.buffer,"ON")== 0) {
      Serial.println("Light ON");
      ble.print("AT+BLEUARTTX=");
      ble.println("Light ON");
      digitalWrite(LED_PIN, HIGH);
      digitalWrite(TAIL_PIN, LOW); //relay logic is reverse of LED
  } else if (strcmp(ble.buffer,"OFF")== 0) {
      Serial.println("Light OFF");
      ble.print("AT+BLEUARTTX=");
      ble.println("Light OFF");
      digitalWrite(LED_PIN, LOW);
      digitalWrite(TAIL_PIN, HIGH);    //relay logic is reverse of LED
  } else {
      Serial.println("Light not changed");
      ble.print("AT+BLEUARTTX=");
      ble.println("Light not changed");
  }
  ble.waitForOK();
}

/**************************************************************************/
/*!
    @brief  Checks for user input (via the Serial Monitor)
*/
/**************************************************************************/
bool getUserInput(char buffer[], uint8_t maxSize)
{
  // timeout in 100 milliseconds
  TimeoutTimer timeout(100);

  memset(buffer, 0, maxSize);
  while( (!Serial.available()) && !timeout.expired() ) { delay(1); }

  if ( timeout.expired() ) return false;

  delay(2);
  uint8_t count=0;
  do
  {
    count += Serial.readBytes(buffer+count, maxSize);
    delay(2);
  } while( (count < maxSize) && (Serial.available()) );

  return true;
}