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;
}

Monday, April 25, 2016

On the air!

As described in  this post  the antenna (G5RV Jr) was mounted yesterday. Today, we finished the connections (see photo), and hooked up the Ten Tec Jupiter.
Ladder line connected to coax via a juntion box, to the balun and off to the rig
I was able to hear a lot on 20 meters and some on 40.  It's tough to break in at times, and it's not always clear whether I'm not getting through or some one else is transmitting over me. Very often, you only hear one side of a conversation.  For example, I could hear someone in the Czech Republic clearly. At one point he was talking to someone in Connecticut, probably 200-300 miles from hear, but I could not here the Connecticut station.  Propagation is funny like that.

I did check into a marine net just to be sure I was getting out, and a relay station in Georgia confirmed the check-in. Later I spoke with someone in Portugal and someone else in Nicaragua.  This is cool. Tommorow morning I'll try ECARS (East Coast Amateur Radio Service) to see how I do on 40 meters.

Sunday, April 24, 2016

G5RV Jr mounted--almost all set


On the house (middle)--J-Pole for 2 meters on the left
G5RV Jr on the mast with balun and juntion box
I wanted to get my new antenna mounted and installed yesterday (23 April) so I could get on the air for Marconi Day.  Unfortunately, it rained and we decided to be safe.


Today, we go the antenna mounted on the house and ran the horizontal wires out to trees, The job went smoothly almost without issue.  The only problem was that the ladder line extended down farther than I expected. We measured, and it was 19+ft.  I went back and checked the specs, which say 16ft. I went to my 2 meter rig and raised a local ham with the same antenna, and he verified the 16ft. 

So, we took the antenna down, cut the ladder line down, desoldered the existing connection from ladder line to the SO-239, and soldered the shorter piece. Then we re-mounted the antenna and ran the horizontals out to trees in the back yard. We used ropes connected to the insulators to secure the antenna to the trees, and inserted 24" rubber bungees for strain relief.

By that time we were ready to call it a day.  For tomorrow:

  1. mount the choke balun on then house
  2. mount a waterproof juntion box next to the balun
  3. connect the balun to the ladder line inside the junction box
  4. connect coax to the balun, with a lightning arrestor  between them
  5. ground the lightning arrestor to the ground rod
  6. run the coax through the wall to the shack and connect to the HF rig
  7. figure out what I need to do for station ground
  8. get on the air!

Saturday, April 9, 2016

@MAKE: Electronics Experiment 34 started

As I mentioned in this post, I became discouraged by the need for a $20 cable to program a $3 microcontroller, particularly since Charles did not mention it it the parts list or supplies.  Also, Charles dismissed the less expensive option of using a computer's serial port.  I submitted an erratum to the publishers on this--since the book's subtitle is "Learning by Discovery" and it's a +Make: book, I though it would be more in the spirit of the book to lead the reader to discover and make. I love the book and it has provided me with great deal of learning and satisfaction, but I found this irritating.  I got over it, and now I'm on to the project.

Also, I have not found any posts or videos of these experiments, so I might as well do it.

But first, I needed a serial port. Most late-model computers do not have the old-fashioned 9-pin RS232 ports for what is normally called a DB9 connector but really is DE9. Fortunately, I hoard old computers and have a 14-year old Windows XP computer with serial ports on the motherboard.  If there had been on a PCI card rather than the motherboard, I could have swapped that out  into my regular desktop.  That left me with 2 choices:  fire up the XP machine and use that to program the PICAXE, or buy a PCI card for my desktop. Since I doing this because I'm cheap, I chose the former. PCI cards cost US$7 and up from Amazon, Newegg, and the like, and as low as $4 on eBay. If I decide to use the PICAXE for more than this project, that's an option.

The XP machine started up fine, and I was able to download and install the PICAXE software according to the book instructions (or see the PICAXE web site).  I still needed a cable.  Here again, I had two options:
1. find a serial to something cable, cut it, figure out which wires go to which pin, and connect the 3 wires I need to the PICAXE
2. make my own
Again, this is a makers' book, so I decided to make one.  A quick Google yielded this set of instructions. I bought a DB9F (as in female) connector from Amazon. Following the aforementioned instructions, I soldered 24" solid core wires to the pins I needed:
red wire to pin 2       (Rx--receive--computer in)
green wire to pin 3   (Tx--transmit--computer out) I didn't have white solid core wire
black wire to pin 5   (Ground)
I heatshrinked the connections for insulation.
I then cut a servo wire in half and kept the half with the end that I could connect to a 3-pin header on the breadboard and:

  1. slid small heatshrink on each lead
  2. slid larger heatshrink over the 3 wires to the DB9
  3. spliced the servo wires to the connector wires with solder, matching the wires by color (red/red/ black/ black, white/green) 
  4. heatshrinked the splices
  5. heatshrinked the cable
  6. snapped the cover on the serial connector end
Viola, I had a cable.  Here are some photos of the process.
Tools and supplies ready 
to make the PICAXE cable
DB9F ready to solder

soldered wires ready for heatshrink
finished cable


Next step:  configure the breadboard:
  1. add a 2.1mm barrel jack to bring unregulated 9V to the breadboard via wall wart or 9V battery
  2. add a voltage regulator circuit to deliver clean 5V to the power rails on each side of the breadboard
    .  the circuit consists of 2 100uf capacitors, 2 .1uf capacitors, and an LM7805 voltage regulator
    .  Charles' instructions are good, see schematic
  3. add the PICAXE to the breadboard and connect it to power and to the computer serial output
    .  I have a PICAXE 08M2, pin 2 is serial in and pin 7 is serial out, so the red wire (computer out) goes to pin 2 (see next bullet), and the white wire (computer in) goes to pin 7 (i,e, computer in to PICAXE out, computer our to PICAXE in)
    .  actually the red wire goes to a breadboard hole in a row between a 10K resistor that goes to a breadboard ground rail and a 22K resistor that goes to PICAXE pin 2--keeping pin 2 pulled to GND when it's not receiving
    .  PICAXE pin 1 goes to a breadboard 5V rail, and pin 8 goes to a breadboard ground rail
  4. Add an LED for testing--connected to PICAXE pin 6 and on to GND through a 330Ohm resistor
Fritzing diagram of circuit--the business on the left is the voltage regulator circuit



I had a heck of a time with the voltage circuit.  I kept getting ~9V out. I tried multiple units, and checked ny wiring.  Finally I set up a circuit like the L7805 datasheet, and it worked--exactly 5V out. I was going to submit another erratum on the book, but as I wrote ti it didn't make sense that I would get 9V out, so I rewired it in a different spot on the breadboard: 4.98V out.  I moved it back to the original location: 9V out.  I'm doing something stupid, but I'm ready to move on to the PICAXE and test my cable, so I'll put it back where it works and declare victory.

breadboarded circuit with messy wires

Now, we're ready to test the cable and circuit.

Oops.  I cannot get the XP machine to recognize the PICAXE./  I have a problem with my cable (although I don't think so, but I'll check), the circuit, my computer, or something else. It could be the breadboard--I suspect that's the problem with the voltage regulator circuit--see above.  I've done some preliminary checking, but I'm not there yet.  The book is absolutely no help on this since Charles went the non-Maker route, I'll do another post if/when I get something working.






Monday, April 4, 2016

I passed my General tonight!

Step 2 on my Ham Radio journey. Now I need to buy an HF rig and build a multi-band dipole.

Sunday, April 3, 2016

Adjustable Power Supply Problem Solved - DUH!

I have this very useful Compact Switching Power Supply - Selectable Output 3-12VDC from +Adafruit Industries.

I noticed a while back that the polarity was not what I thought--center-pin negative instead of center-pin positive.  It didn't matter a whole lot, because I used it a lot for my 5V Regulated Power Supply, and since I used my meter to check which was + and which was -, I got away with it.  Later, I found that the adapter did not work in certain applications.

I put that away for a while, but it just started to bug me again, so I Google'd the problem and was taken to the Adafruit product page (see above).  Reading the not so fine print, I saw that the device can switch from center pin positive to negative. Next question: how?

I did not find an answer, so I went to look at the device.  It comes with tips to accommodate various size receptacles.  I turns out that the wire to the adapter has + and - on each side, and the tips have CEN with an arrow. So, if you want center pin positive, mate the side marked CEN to the side marked +, and vice versa. I never noticed that before. Live and learn. Anyway, my problem is solved. I must be some kind of genius!

Saturday, March 26, 2016

Adafruit OLED display on Arduino

I have been neglecting my Arduino interests in favor of amateur radio recently. So, I bought a book "Arduino for Ham Radio."

One simple project to get me started is a compass display.  The book call for a LCD module, which I have, but I also have an +Adafruit Industries OLED 128X64 display that I haven used yet.  So, I dug it out, soldered on the header pins, downloaded the Adafruit libraries, and uploaded an example to an +Arduino Uno clone that I had lying around.  I'm now sensitive to clones, and from now on will only by genuine Arduinos, but since I had this one I used it.

I made one small change to the program, just for grins:  changed "Hello World" to "Hello Town" and passed that message as a variable rather than a literal. No big deal, but I'm refreshing my Arduino skills.

I have ordered the compass module--after I get it I'll finish the project and post results here.

Here's a video.