Remote ESP8266-based Garage Door sensor

I’ve got a bunch of z-wave light switches and plugs in my house and I use OpenHab as my centralized home automation system. I have a detached garage and neighbors have experienced occasional break-ins in similar garages where people stole tools and what-no. In fact, a couple years ago, the padlock on the sliding lock  was broken (yes, sadly, I do not have a garage-door opener…really embarrassing for a home-automation guy..but I’ve got this really funky pivoting metal door that reminds me of an aircraft hanger or something. Anyway, suffice it to say, motor-driven opening would be challenging.) ON closer inspection, I realized it was because someone had been hammering on it…I guess one night while we were out of town or something, because hammering a lock on that metal door would be loud.

Now, one problem is, I’m pretty forgetful, so there have certainly been times when I forgot to lock it, or even forgot to close it. Since I already had z-wave going on, I figured I’d try a z-wave tilt-switch. I set of OpenHab so that when the garage door state changes, I get a text. It also reminds me after sundown if the door is still open. This kind of worked, but z-wave is not guaranteed delivery, and I think the distance to the garage from the nearest node, combined with the RF-blocking metal door, resulted in a pretty poor success rate reporting the ‘closed’ stated (the tilt sensor fires once, then sleeps).

So, I decided I could probably do better using an ESP8266 sensor I built myself.

My first attempt involved setting the ESP (01) leveraging the deep sleep option to wake up every 60 seconds, check the state of an input connected to to a mercury switch, and when the state has changed, connect to my WiFi network and send a message to my OpenHab server via MQTT. I should note that, since deep sleep loses the current run-state – it really just wakes up and starts init.lua from the beginnning) I used an Realtime Clock (RTC) storage register to store the “last known state”..that’s all documented here and there on the web. This work really well, but I only got about six weeks of battery life out of a 3.7V LiPo battery…really two short to be acceptable – I needed to figure out a better design.

I figure, an better approach is one where the sensor is actually powered off most of the time, then powers-on, connects to WiFi, and sends a message when the mercury tilt switch closes, then fires another message when the door closes. The problem is – if I just wire the power through the mercury tilt switch, when the door closes, power is lost and the ESP can’t send the “closed” message. I tried a big capacitor supplying some power for a bit after the tilt switch opens, but even a big-honkin’ one didn’t provide enough juice to run for more than a fraction of a second.

What I wound up doing was using the mercury switch to supply power when the door opens – so on power-up, it sends the “open” message, then I have a parallel power path which uses a P-channel MOSFET to supply power after the door closes. The gate of the MOSFET is connected to a GPIO pin, so the ESP actually powers itself off once it sends the “closed” message by setting the GPIO HIGH, thus turning off the MOSFET. Since the ESP-12 operates at 3.3V, you need a TTL level MOSFET. I used an NDP6020. Here is an example of a circuit which I kind of used as the basis for this secondary power path:relay-mosfet-p-channel-switch8

The at-rest current leakage on MOSFETs is supposed to be really low, so I think I’ll get really good battery life with this approach. I didn’t worry about the diode, and an ESP-12 is basically in place of the relay.

I did need one additional sensor, since I couldn’t think of a simple way to have the mercury switch act as both a power supply switch AND a GPI sensor. I had a couple 3-axis accelerometers around, so I used on of those, with one axis tied to the ADC pin on the ESP-12 through a voltage divider that bring the 1 to 3.3V output down to the 0 to 1V range the ESP ADC pin expects.

Here is a Fritzing and schematic of the prototype:

 

 

GarageFritzing

 

 

 

 

 

 

GarageSchematic

 

 

 

 

I’ll deploy it shortly and provide an update on the reliability and battery life in the near future.

Advertisements
Posted in Technical | 3 Comments

NodeMCU Custom Builds for ESP8266

OK, just a quick blurb in case anyone else runs into this incredibly frustrating experience:

I’m playing with some sensors where I’m interested in really low power consumption. Basically, I want to go into deep sleep, which only draws <100uA, and wake up every minute or so, check an input, and report it to an MQTT broker if the state has changed. I also want to read from a DH11 temp/humidity sensor every 30 minutes or so, and report the values, regardless of whether the GPIO changed. I’m mainly working with NodeMCU right now, rather than “native” SDK code.

SO…the ESP8266 has a “deep sleep” mode, called using node.dsleep(us), which really just shuts off everything but the Real Time Clock (RTC), which drops XPD_DCDC (usually GPIO15) to gnd briefly when the timer expires. Tie that signal to RST, and the chip CPU will initialize when the timer expires and run your code from boot-up. NodeMCU has nifty rtctime and rtcmem modules now that let you read the Real Time Clock value, like after you wake up, and use 128 words of space in the RTC storage to persist info between wakeups.

OK, cool, but after flashing various verions of NodeMCU to my test chips, I get nothing but the following error, presented here for search engine to hit, whenever I try to access the rtctime or rtcmem functions:

“attempt to index global ‘rtctime’ (a nil value)” or “attempt to index global ‘rtcmem’ (a nil value)”

So, my suspicion is, the base NodeMCU firmwares are not being built with the relatively new support for the RTC modules built in. BINGO! After building a custom firmware that includes the module, these functions are available.  I will say, however, that the “rtctime” function desn’t appear to work as advertised. The docs seem to imply you will get the time, including the time that has elapsed while in deep sleep. Currently, I’m not seeing this behavior…it seems like it’s initialized at every boot. Persisting values via “rtcmem” is working well, though, so I can just do simple modulus on an incrementing number I store on every 1 minute “wake” to send temp data every 30 minutes or so.

This being said, a quick shout out to the excellent site, http://nodemcu-build.com/ 

This site lets you build a custom NodeMCU firmware image off the current master (or dev) branch, and include modules optionally, as you see fit. Check it out and donate (as I did) if you find it useful. It’s SO much easier that screwing around with build chains – jsut select the modules you want an click a button – you get an email when your build is ready (almost immediately for me)… and give this guy a few bucks, he deserves it for saving you the time!

Posted in Technical, Uncategorized | Leave a comment

LightSuit V2.0

Well, it’s well past Christmas and things have finally settled down for me a bit, so I figure it’s high time I blog in a bit of detail about my main Christmas technology focus – Version 2 of the AustinLightGuy Light Suit. I’ll post links to resources I incorporated this year at the bottom of this post.

I’ve been wanting to do a major upgrade on the original light suit for some time with these main goals in mind:

  • Upgrade the strands of commercial LED Christmas lights to strings of fully-addressable RGB lights
  • Have cooler built-in patterns and improve the responsiveness of the lights to music when going in “synchronized” mode – both for the suit and synchronized devices.
  • Have MANY, inexpensive synchronized light devices
  • Crank Up the Sound!

I’ll address the last first, since it was the easiest…

Cranking Up the Sound

Turns out most places we go to in our light suits are actually pretty noisy – there’s usually lot’s of people around talking and maybe even other music sources…Christmas music on the PA around the Zilker Tree and Trail of Lights (GREAT job on the Trail of Lights this year, by the way, despite modest entry fees – kudos to organizers and sponsors), music in bars, etc. It would be cool if the Suit could be synchronized to ambient music, but it’s usually kind of drowned out by crowd noise, so I figured I’d try out somethingsuitspeakers else – crank up the volume on the suit.

The original solution, which was just a crummy little set of bluetooth speakers that paired to my phone, was way to quite. So this year, I just got a set of relatively high-powered PC speakers, rigged them up to where they could be snapped on to the new suit, and drove them directly from the line-level audio (which is actually a pass-thru on the new master controller that I’ll describe shortly). They run off the same 12V “power bus” that the whole suit runs on (more on that later). I wrapped them in nice, fluffy faux fur to make them Christmassy.

These pretty much rocked, but in bars, they still got drowned out a lot of the time, so I wound up going with the (single, for now) pre-programmed pattern.

2.0

Ok, so now on to the interesting technical stuff…

I wanted to be able to synchronize even more “remote devices” this year – beyond the two staffs, the light cape and LakewayLightGuy’s suit. But I also wanted to retain backwards compatibility with those devices so I didn’t have to completely rebuild them, as well. It just so happens that I had recent been turned on to the ESP8266 family of devices. These are basically amazingly cheap SOC modules that contain a processor, flash RAM, and even WiFi, all in really small form-factors. There are really bare-bones boards (like the ESP-01) incorporating this chipset that can be had for as low as a couple bucks from China, up to more sophisticated boards, like the NodeMCU dev board and the EspToy, which provide good on-board power regulation, USB serial-to-TTL circuitry (necessary to flash them), and LIPO battery charging. There’s a huge community of support out here for these things, two or three tool chains, lots of code libraries, and many excellent blogs, including Pete’s excellent tech.scargill.net. The incredibly low price of these things (especially vs. the pretty expensive and proprietary XBee modules I’ve been using) led me down the path of deciding I should migrate to WiFi-based synchronization using ESP8266-based boards. I played around with a myriad of them, but wound up using a NodeMCU, an EspToy, and multiple ESP-01’s.

Latency Problems

To test the WiFi concept, I cobbled together a prototype setup where I took existing Arduino suit controller and had it feed RGB values via serial port to NodeMCU dev board (the “master”). I wrote some simple LUA code to set the device up as an Access Point, then send UDP broadcast packets out every time it received a set of RGB values over the serial port. I also created a “slave” by flashing a basic ESP-01 with a version of firmware that supports WS2811/12 (standard in latest build) and wrote some simple LUA code (based in part on an example here) to connect to the Access Point and listen for UDP broadcasts. When it got a UDP packet, it would pull the RGB bytes out and write them to a short string of WS2812’s I was experimenting with (similar to this). The result was pretty good – although the packet rate is a little low I think probably around 10hz, so 10 updates a second, or maybe a tad lower. I tried using my home wifi instead of setting up my master as an access points, but that was actually slower. I really still need to try to recreate the code using the native SDK and C (or preferably, an Arduino sketch) to see if I get better packet rates.

The real problem is – there is some latency between when a sound occurs and the data packet makes it across the serial port, then over Wifi, to the “slave”. The delay is in the neighborhood of a half a second. As a result, the lights are sync’d to the music, but the response lags by about a half second. The delay is more obvious when you ahve it next to one of my XBee “slave” devices, since those respond with almost no lag at all 😦

My first thought was that I could introduce a hardware chip that does audio delay – I did something with a “bucket brigade” chip years ago – or maybe just by an off-the-shelf delay circuit. I didn’t really find anything I like much off-the-shelf…mostly guitar-oriented stuff that was pretty pricey (and big). Then I ran across Teensy! The Teensy (3.2) is a little dev board, with your usual array of I/O pins, but it’s got a 72Mhz ARM processor as well as ADC (analog-to-digital) and DAC (digital to analog) ports. You basically write Arduino sketches and use the “Teensyduino loader” to load your code onto the Teensy. It’s inventor, Paul Stroffregen, seems to be pretty into Audio or something, because he’s got a stupendous audio library and he provides a really cool online tool (built on Node-Red) to wire audio flows together graphically then export code. There are simple examples for wiring line-in and line-out to the ADC and DAC in the help that accompanies the nodes.

Here’s an example, taking and ADC input, piping it through a delay, then feeding the result the the DAC:

Then you just add little bits of code to do stuff like set the delay on channel 1:

delay(0, 300); // delay channel 0 300ms

Since the Teensy has plenty of horsepower, so it can also me my master processor, replacing the Arduino. And Teensy also does FFT, so by using it as my master processor, I no longer need the MSGEQ7 hardware to due octave analysis like in V1!

That’s a lot of stuff going on in my new master controller, so I also decided I would drive my suit, which used to be connected directly to the Triac board in my master controller, via a new “slave”, which would just house an ESP8266 as a UDP receiver and WS2811 driver, and a 12V to 5V regulator to drop by suit power supply down to the 5V the WS2811 strings want.

So here’s the high-level picture:

Bigpicture

And here’s the new master and new suit slave:

Complicated, I know.  In the next post, I’ll go into a little more detail on some of this, some of the cool things it let me do, and some additional complications I ran into.

 

Resources

Here are links to stuff that went into this build. Many of them link to Amazon, EBay, or AliExpress, so if they go stale, I apologize. I’ll try to make the descriptions usefully google-able.

Creative Inspire T12 2.0 amplified speakers: http://amzn.com/B0028N6YH0
Teensy 3.2 dev board (72Mhz ARM processor): http://www.pjrc.com/store/teensy32.html
23LC1024 SRAM chip: http://www.mouser.com/ProductDetail/Microchip-Technology/23LC1024-I-P
ESP8266 devices:
* NodeMCU Dev Board: http://nodemcu.com/index_en.html
* ESPToy 1.21: http://rayshobby.net/introducing-esptoy-1-21-with-lipo-charger/
* A bunch of plain old ESP-01’s: http://r.ebay.com/fG130b
XBee Modules: http://www.mouser.com/ProductDetail/Digi-International/XB24-AWI-001
Some cheap, little heat sinks: http://www.aliexpress.com/snapshot/6955208975.html
WS2811 RGB LED strings: http://www.aliexpress.com/snapshot/6890770046.html
2596 Buck Converter step-down regulators: http://amzn.com/B018JPGKQK
Buck/Boost Power Regulators (boost from 5v to 30V): http://amzn.com/B00WMB6OMI

 

Posted in Uncategorized | 2 Comments

Building another (better) PiCam security camera

I blogged briefly about building a security camera back in a previous post. It worked so well I decided to build another, but with a few improvements based on past experience…

I used this WiFi adapter (from Aazon): TRENDnet Wireless N 150 Mbps Mini USB 2.0 Adapter, TEW-649UB.  It’s supported out-of-the box by th OS, PLUS, you can easily pop open the housing and their a standard (tiny) wifi antenna connector on the circuit board. This let by connect a full, external antenna I had from dismantling and old router or something.

I followed this original Instuctable up to step 6:
Instead of Motion, I use VLC to stream the video.
I created two scripts in my /home/pi directory…
start-vlc.sh:
#! /bin/sh
sudo raspivid -o – -t 0 -n -w 800 -h 480 -fps 6 | cvlc -vvv stream:///dev/stdin –sout ‘#rtp{sdp=rtsp://:8160/}’ :demux=h264 :h264-fps=6 2>&1 | tee /var/log/vlc.log &
 
restart-vlc.sh:
#! /bin/sh
echo “$(date) – stopping vlc” >> /var/log/vlcstart.log
sudo ps -ef | grep -e ‘vlc \-I’ | grep -v grep | awk ‘{print $2}’ | xargs -i kill {} 2&>/dev/null || echo “vlc-streamer already stopped”
sleep 3
sudo raspivid -o – -t 0 -n -w 800 -h 480 -fps 6| cvlc -vvv stream:///dev/stdin –sout ‘#rtp{sdp=rtsp://:8160/}’ :demux=h264 :h264-fps=6 > /var/log/vlc.log 2>&1 &
 
I changed the run permissions on both files:
chmod 755 start-vlc.sh
chmod 755 restart-vlc.sh
Both scripts start the VLC streamer streaming H.264 800×400 video over RTSP at about 6 frames per second. That can all be changed, for example, you could use a different encoding..there are many examples for using different options on the internets. RTDP is fast, but be aware that one downside is that it is over UDP only, so doesn’t work if you want to stream outside your firewall.  I found I can easily go faster on the frames per second – just make sure to change both the “-fps n” and “:h264-fps=n” parameters to match. When I tried larger frame sizes though (liek 1024×768), I kept seeing it start to rebuffer. It would continue to do that, each time takin glonger and longer until it became unworkable…not sure exactly what was going on there, but 800×480 doesn’t do it, so I went with that.
I created a script in named vlc-streamer in /etc/init.d for starting and stopping the streamer as a service:
#! /bin/sh
# /etc/init.d/vlc-streamer
 
# Carry out specific functions when asked to by the system
case “$1” in
  start)
    echo “Starting vlc”
    # run application you want to start
    echo “$(date) – starting vlc” >> /var/log/vlcstart.log
    sudo -u pi /home/pi/start-vlc.sh &> /var/log/vlc.log
    ;;
  stop)
    echo “Stopping vlc”
    # kill application you want to stop
    echo “$(date) – stopping vlc” >> /var/log/vlcstart.log
    sudo ps -ef | grep -e ‘vlc \-I’ | grep -v grep | awk ‘{print $2}’ | xargs kill -9
    ;;
 
  restart)
    echo “Stopping vlc”
    echo “$(date) – stopping vlc” >> /var/log/vlcstart.log
    sudo ps -ef | grep -e ‘vlc \-I’ | grep -v grep | awk ‘{print $2}’ | xargs -i kill {} 2&>/dev/null || echo “vlc-streamer already stopped”
sleep 3
    echo “Starting vlc”
    echo “$(date) – starting vlc” >> /var/log/vlcstart.log
    sudo -u pi /home/pi/start-vlc.sh &> /var/log/vlc.log
    ;;
  *)
    echo “Usage: /etc/init.d/vlc {start|stop}”
    exit 1
    ;;
esac
exit 0

And finally, I added the startup to /etc/rc.local so that the service will start up automatically when the system starts:

# Start camera streaming
service vlc-streamer start
I set up the camera in iSpy using a custom profile. Configure it as an FFMPEG (H264) camera with an rtsp:// url pointing to your camera’s IP address and using the UDP protocol:
Image
Another deviation from the article – On my second camera, I wanted a real, durable, weatherproof enclosure – not the fake plastic kind of thing they use in the article. I used this Evertech B00LU2NPVS enclosure, again from Amazon which, for for $45 bucks, gave me a full IP66 weatherproof enclosure, plus built-in IR leds and a fan. I just glued the camera to the rubber diaphragm and the circuit board to the included mounting plate with some silicone caulk.
Note that this housing is actually QUITE large compared to the crummy little consumer WiFi camera enclosures. In fact, it was really kind of unnecessarily big for the PiCam – almost 18″ long. I ended up cutting about 4 or 5 inches off the tail end with a hacksaw, which actually worked pretty well. Because of that, I had to drill a new access hole in the bottom for the power cord. I also drilled a small hole in the back to mount the WiFi antenna connector I had scavenged.

A note about power: The IR led array and fan take 12v. The housing comes with a convenient DC “bullet” plug that connects to the IR assembly, and there is another pair of wires that come off the IR assembly to supply your camera, but they supply the same 12V. I connected these to a buck an adjustable buck regulator – a really convenient and efficient regulator that costs about 5 bucks on Amazon and can take a variety of input voltage and output whatever you adjust it to…in my case 5V. I then fed the 5V in to the USB power connector on the Pi by cutting up a USB cable and splicing it in.

 

02/16/2016 Update:

To improve stability a bit more, I tweaked the restart scripts (already reflected in the code, above). I also changed the output redirection, so it doesn’t spit stuff out to the console and redirects it to vlc.log properly.

Next, I created a script to check that the WiFi is connected, and force an attempt to reconnect if not. Then I set that up to run every five minutes via cron.

check-wifi.sh:
#! /bin/sh
count=$(ping -c 4 192.168.2.1 | grep ‘received’ | awk -F’,’ ‘{ print $2 }’ | awk ‘{ print $1 }’)
if [ $count -eq 0 ]; then
# 100% failed
echo “Restarting wifi”
sudo /sbin/ifdown wlan0
sleep 10
sudo /sbin/ifup –force wlan0
else
echo “Wifi looks good!”
fi
 
/etc/crontab:
#! /bin/sh
# Monitor remote host every 30 minutes using monitorHost
5 * * * * root /home/pi/check-wifi.sh

 

Finally, created a monitor in iSpy, so that if the connection is lost and reconnect failes, iSpy will launch a script to automatically try to restart the service.

First, I set up my pc so you can ssh to the PiCam without entering a password. After installing cygwin and making sure the cygwin\bin directory is in my default system PATH, I set up an encrypted keypair using this example on StackOverflow: http://stackoverflow.com/questions/16928004/how-to-enter-ssh-password-using-bash

Then I created a batch file to call the service restart command remotely and registerrd it as the “Reconnect Failed” Action in iSpy:

restartPiCam2CLV.bat:
rem try 5 times
set /A count = 5 
:DoWhile
 if %count% == 0 goto EndDoWhile
  set /A count = %count% -1
  ssh pi@192.168.x.yyy sudo service vlc-streamer restart
  if %errorlevel% == 0 goto EndDoWhile
  if %count% GTR 0 goto DoWhile
:EndDoWhile
exit \B
Image1

Failed connection Action

If the connection goes away and the automatic reconnect fails, iSpy will invoke the script.
Posted in Technical, Uncategorized | Leave a comment

Easy, Cheap Connector for ESP-01

One thing that’s been pretty annoying playing with the ESp-01 variant of the ESP8266 modules is the pinout form factor. The 2×4 pin configuration does not plug into a prototyping breadboard conveniently, and also doesn’t lend itself to connectors you might use in a more permanent solution very well – I was ganging two pieces of Arduino headers, using several female-ended jumper wire or gluing together multiple female ends to make a 2×8 connector…and that kind of thing.

While browsing parts at Fry’s, a really simple solution occurred to me. I got some plain old .1″ pin  spacing ribbon cable headers and a piece of ribbon cable. You could also use the prototyping ribbon cables that have male pins at the end for plugging into breadboards. (sorry for the blurry pics)

IMG_20151204_080211499

 

These work great, and cost mabe 50 cents each to make (max). Note they only had 20-pin connectors, so I only use the 8 on one side and they only had 9-conductor cable, so a got a length of that an peeled of one conductor 🙂

IMG_20151204_080244917

Posted in Technical | 1 Comment

Lessons Learned with ESP-201

I recently ordered several more ESP8266 modules, and of that set, I decided to get a couple of ESP-201’s. These were appealing because they’re still fairly bare-bones (and therefore extremely cheap – about $4US each), lacking an on-bard regulator or serial chip, but they also bring out a lot more IO lines to pin pads, and seemed more convenient for plugging into a prototyping breadboard.

UPDATE : Note that, as noted on another blog, “Compared to ESP-12 this module has 6 more pins broken out – D0, D1, D2, D3, CLK, CMD (GPIO6-GPIO11). But only two of them (D2, D3) can be used as regular GPIOs after slight hardware modification.” Yuck! Looking forward to the ESP32!

I encountered a couple of issues that took a fair amount of googling to figure out, so I figured I’d pass them on.

First, as others have pointed out, the pin labels are on the underside, which is really annoying.  like most ESP8266’s, you have to pull CH_EN high, and to flash it, you have to pull GPIO0 low. You ALSO have to pull GPIO15 LOW, though, which is different from other ESP variants. Once I pulled 15 low, GPIO2 high, and GPIO0 low, I was able to flash the module.

However…I was flashing a NodeMCU image onto them, intending to keep it consistent with the other modules I’ve been playing with for my Light Suit V2 project. But it turns out, the ESP-201 is specifically designed to work with the SDK and it does NOT work with NodeMCU flash images. You pretty much much need to use the SDK or, as I do, use the Arduino plugin to handle the compiling and flashing for you.

CORRECTION: ESP-201 WORKS FINE with NodeMCU, you just have to have the pin levels
right a boot to get it into a mode where you can load .lua files and run on boot – specifically, pull CH_EN high, as you normally do, and pull their pin “IO15” (really pin 13 on the chip, I guess?) LOW. To flash, pull GPIO0 low, as usual. This wound up working and now I’m much happier 🙂
ESP201_Frontesp-201_pinout

The Arduino plugin makes coding with ESP’s really easy since it builds and flashes your code to the module in one easy step without requiring you to go learn complex code build chain crap. Once I switched to that environment, the usual process of pulling GPIO0 high, followed by programming, worked well.  I haven’t really done much with it yet, but I presume it will work pretty much like any other variant using the Arduino toolset.

Posted in Uncategorized | Leave a comment

Can’t upload new LUA files once ESP8266 init.lua starts

I’ve been having this frustrating problem with my NodeMCU projects on the cheaper ESP8266 devices: Once you get into a loop in your code, or worse yet, if you have an error that causes a reboot loop, there’s no way to upload a new .lus file short of re-flashing – a major pain!

Well, I finally found a nice solution on Big Dan’s blog. Thanks to Big Dan, a simple code addition for startup of you app in init.lua gives you time to interrupt it using a simple “snippet” assigned to a button in NodeMCU.

Add some code like this to your init.lua:

function startup()
    if abort == true then
        print('startup aborted')
        return
        end
    print('in startup')
    dofile('test.lua')
    end

abort = false
tmr.alarm(0,5000,0,startup)

Then edit the code behind a “snippet” button to execute “abort=true”. Then you just have to click that snippet button before 5 seconds expire at startup time to abort starting your code.  Many thanks, Big Dan!

Posted in Uncategorized | Leave a comment

Light Dimming Using Ardiuno with Inverters

Since there’s not a lot of information about it out there in one place, I thought I’d share some insight into a problem I’ve been grappling with – dimming 110V LED lights run off an inverter using Arduino-driven triacs.

Recently, I’ve been experimenting with dimming strings of LED lights using an Arduino and similar devices. My goal is to kick my Light Suit up a notch by going from simple on-off flashing patterns to dimming intensities, ultimately driven by sound spectrum intensities – so that the strings throb in sync with music sources.

There is a trick to dimming 110V AC strings – since you’re typically using triacs to control hihg-voltage AC power, you have to worry about “Zero Crossing”. The problem is that, once you turn a triac on, it stays on until the voltage falls to the “zero crossing” point – the point at which the voltage is at (actually near) zero, even if you turn off the controlling voltage. So, to dim 110V strings, you actually have to do some timing – where you wait a small amount of time into the phase of the AC sine wave before turning the triac on. That way, you only voltage during a portion of the since wave – reducing the overall power. There’s a good article on the technique here: http://playground.arduino.cc/Main/ACPhaseControl. That is basically the setup I’m using.

A problem I’ve been encountering though, is that I’m running these strings off of a 12V-powered inverter. That was the easy way to take commercial string of LED lights attached to the suit and still be mobile. The problem I’m running into is that, at least in the case of small, inexpensive inverters, they use a modified sine wave, not a true sine wave. Google it for more details, but this is basically a notched square wave which emulates a sine wave in terms of total power delivered. But since the beginning and end of each phase of a modified square wave are at zero voltage, if you try to turn the triac ON at the beginning or end of the phase, it doesn’t happen, since the voltage is at zero.

Image1

You have to turn in on at some point during the “notch”, which is a narrower window than you have with a full sine wave.

Image2

What was happening for me was that, at low or high dim values, the lights would start flickering erratically or not coming on at all. Limiting the triac firing to the window of the actually square “modified sine” wave helps tremendously. It’s also worth noting that my two inverters behave differently – one flickers quite a bit even when I limit the firing window. I’m guessing it must be a “dirty” square wave or something, but can’t really be sure without a oscilloscope (this is one of those occasions where I really consider plunking down some $$ for one).

Also, I’m not sure why, but I still get some flickering when I drive the triacs from an Arduino Uno. When I use a chipKIT uC32 (an 80Mhz pic-32 “Arduino clone”), it works smoothly. I have know idea what’s going on here, but I’m kind of guessing that the speed with which the Arduino responds to a hardware interrupt can very a bit based on how busy the processor is or something.

Posted in Uncategorized | Leave a comment

ESP8266 Update

OK, since my first post on the ESP8266 and some replies I posted there as I made progress getting it to work, I’ve now had a chance to play with it a bit more.

One thing about the inexpensive ‘bare-bones’ variants – the advice everyone gives about NOT powering them from your serial adapter is definitely valid. I got significantly more flakiness with them, especially when trying to flash. Sometime it would take several tries to flash correctly. At times, the power draw even seems to have messed up USB hub, causing my mouse to go dead, for instance. The flashing flakiness applies both to flashing the full firmware and to simply trying to flash .LUA files to them.

So far, I’ve done almost all my experimenting using LUA and ESPlorer. This is mainly due to the convenience and to eliminate potential weirdness the Arduino build for ESP8266 might introduce. I’m not saying there is any – I just want to have a controlled comparison before digging deeper.

I do think there could be some issues trying to use certain Arduino libraries with the ESP, though. NodeMCU appears to be essentially a single-threaded, event-driven language, like Node.js. Since some Arduino libraries likely rely on interrupts for timing (SoftwareSerial, for example), you could end up messing up timing within the core firmware that controls the WiFi stack. So far, I have no evidence of this, it is mainly conjecture.

My little test project is to read the temperature from a TMP102 sensor from Sparkfun (my version has been retired, but the new one is essentially the same) and publish it to my OpenHAB server via MQTT over WiFi. The TMP102 uses an I2C connection with some specific addressing. Fortunately, both MQTT and I2C libraries are compiled into the latest NodeMCU firmware – I really just had to write a little MQTT code and pilfer some I2C communication code from Christee@nodemcu.com, which I found in the BMP085 module under the LUA firmware project: https://github.com/nodemcu/nodemcu-firmware, and wire the SDA and SCL pins to GPIO14 and 12, respectively. My complete set of code is here: https://github.com/acoulson2000/ESP8266-TMP102. One more thing – apparently LUA is integer-based (lame) and this messed up my conversions to Centigrade. I had to download and flash a floating-point-capable firmware image (nodemcu_float_0.9.6-dev_20150406.bin) from https://github.com/nodemcu/nodemcu-firmware/releases.

In any case, I mentioned in my last previous post on ESP8266 boards that both bare-bones boards I got have on-board 3.3V regulators. While this is true, they appear to be too wimpy to prove reliable when flashing or adding peripherals. Out-of-the box, I experienced a lot of flashing flakiness with the ESP-07 and ESP-12 cheapo boards, and little to none with the ESPToy. Using an external 3.3V source improved things immensely, though. At first, I just tapped the 3.3V source off an Arduino Uno connected to a USB port for power, and piped this stright to the 3.3V pin on the ESP-07 daughterboard – the little hole was just the right size to except a jumper pin 🙂  This made the device MUCH more stable.

Having had success with that, I decided to see about upgrading the chip to something that could provide more current. The seller himself indicated that it was not wise rely on the LDO (Low Drop-out regulator – similar to this one) on the ESP-07 and that its presence was actually a mistake (I think he just sources the things bulk from China, but he knows something about what he’s reselling). He recommended an LM1117MP-3.3 (linked here from DigiKey), so I ordered a couple, intending to swap out the chip. They’re both surface-mount, so this requires some soldering skills, but I was up for it. Unfortunately, I did not look compare the specs of both carefully. While they are both surface-mount chips, the 7333 is a SOT-223-3 which has smaller pins than the LM1117-33, which is a SOT-223-4. It has wider pin spacing AND the pins are not in the same order.

LM1117-22 Grafted onto ESP-07

LM1117-22 Grafted onto ESP07

So, I removed the original chip, the soldered the new one one, but spun around and with a jumper on the ground pin to connect to the original ground pad. I also put a little tape underneath it to prevent inadvertent contact with any of the boards though-hole exposed metal.

CaptureMan, after that, that thing works beautifully! I haven’t had a flash problem yet. I flashed two different firmwares and I even went into the ESPlorer Settings tab and cranked it up to Turbo mode. It still flashed program files flawlessley.

That was a lot of trouble to go to, when the ESPToy works right out of the box, but I think it proves out that an ESP-07 combined with some minimal components for a total price of about $5 is totally viable.

Here are shots of pretty much exactly the same sensor, the left one using the ESPToy powered and communicating to the PC directly over a USB cable, the right one connected to the PC via a USB-UART serial adapter. The Arduino is there purely as an easy way to get a 5V power supply while prototyping – I’ll switch to an AC adapter for the real deployment.

ESPToy with TMP102 Sensor

ESPToy with TMP102 Sensor

ESP-07 with Minimal Motherboard and TMP102 Sensor

ESP-07 with Minimal Motherboard and TMP102 Sensor

Next up…more esperimenting with the Arduino port for ESP8266!

 

 

Posted in Uncategorized | Leave a comment

Bluetooth HC-05 and Connection Status Detection

I have a project I’m anticipating where I want a bluetooth module connected to an Arduino.  I’m going to have the bluetooth module connected to an Arduino under my car seat. I’ll have the bluetooth pair with my phone automatically, then an app on my phone will send a short string through the bluetooth module to the Arduino, which will then set the position of my power seat to my preference. The same will work for my wife (naturally, mine will take precedence if we’re both nearby 😉 Ideally, I’d like to have the Arduino in sleep mode and have a signal from the bluetooth module wake it up via a hardware interrupt.

So, I found these cheap HC-05 and HC-06 Bluetooth-to-serial modules out there, which is nearly perfect. One problem – I bought one, and it wound up being an HC-06. Turns out, the State pin, which is tied to GPIO09 on the HC-06 ‘daughterboard’, and is supposed to go high when the bluetooth pairs, doesn’t work on the HC-06. I’m blogging this in case anyone else is looking to detect the state of the pairing on an HC-0X module.

Some research indicated the firmware is different on the HC-06 and that feature just isn’t even supported. Supposedly, it is supported on the HC-05. OK, no biggie – they’re, like, $5 ordered from China, mounted on a nice little break-out board. So, I order a couple of HC-05 and a couple weeks later they show up. I plug one in, pair it AND….still no go! Hmmm..in the meantime I’ve been reading about a lot of AT commands you can send these suckers (you configure them using an “AT” command set, sort of like my first modem – a 300 baud modem, I’ll have you know). I won’t document how to get into the console here – that’s document extensively all over the place.

Anyway, I’m thinking…hmm…maybe there’s one that enables that function? I found the AT command set for the HC-05 is thoroughly documented here, and sure enough, the “AT+POLAR” command does just that! The engrish docs read a little counter-intuitively – you actually need to send “AT+POLAR=0,0” to set the board up to turn the onboard LED high and raise GPIO9 (board pin 32) HIGH when paired. But once I tried that setting, it worked like a charm! Oh, and by the way, the opposite (AT+POLAR=1,1) results in the on-board LED flashing slowly when paired and GPIO9 just always stays low.

Hope this helps anyone else looking to do the same.

Posted in Uncategorized | Leave a comment