DIY Gate Sensor for Home Assistant

In our basement we have a baby gate, which surprisingly keeps our cat out of the gym and golf sim areas.

Sometimes we forget to close the gate, so I needed a sensor to monitor its state. I still had the breadboard from the air quality monitor project, so it was quick to add a magnetic door switch and test things out with the D1 Mini clone.

I have extra sensors, so those were kept in the project and allowed me to get rid of the shitty DHT22 I added to the golf remote. Everything worked, but I want to save my last two D1 minis and use them for something with the screens I have for them. So I swapped in an Adafruit Feather HUZZAH ESP8266, which I got with AdaBox 3 or 4 in 2017 and made minor changes to the code.

Parts:

References:

ESPHome YAML code:

substitutions:
  slug: gate
  friendly: Gate

esphome:
  name: ${slug}
  friendly_name: ${friendly}

esp8266:
  board: huzzah

logger:
  level: WARN

api:
  encryption:
    key: 'xxx'

ota:
  - platform: esphome
    password: "xxx"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  manual_ip:
    static_ip: x.x.x.x
    gateway: x.x.x.x
    subnet: 255.255.255.0

i2c:

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO14
      mode:
        input: true
        pullup: true
    name: ${friendly}
    device_class: door

sensor:
  - platform: htu21d
    model: SI7021
    temperature:
      name: Temperature
      id: ${slug}_temp
    humidity:
      name: Humidity
      id: ${slug}_humid

  - platform: aht10
    variant: AHT20
    temperature:
      name: AHT21 Temperature
      id: ${slug}_aht21_temp
    humidity:
      name: AHT21 Humidity
      id: ${slug}_aht21_humid

  - platform: ens160_i2c
    address: 0x53
    eco2:
      name: CO²
    tvoc:
      name: VOC
    aqi:
      id: demo_aqi
      name: AQI
    compensation:
      temperature: ${slug}_aht21_temp
      humidity: ${slug}_aht21_humid

text_sensor:
  - platform: template
    name: AQI Rating
    lambda: |-
      switch ( (int) ( id( ${slug}_aqi ).state ) ) {
        case 1: return {"Excellent"};
        case 2: return {"Good"};
        case 3: return {"Moderate"};
        case 4: return {"Poor"};
        case 5: return {"Unhealthy"};
        default: return {"N/A"};
      }

I also added this to my configuration.yaml because I wanted a gate icon instead of the door, due to the device class of the binary sensor:

template:
 - binary_sensor:
    - name: Gate
      unique_id: gate_template
      device_class: door
      state: "{{ is_state( 'binary_sensor.basementgate_gate', 'on' ) }}"
      icon: |
        {% if is_state( 'binary_sensor.basementgate_gate', 'on' ) %}
        mdi:gate-open
        {% else %}
        mdi:gate
        {% endif %}

I figured I might as well use one of the fancy Adafruit Perma-Proto boards I had, which makes soldering all of the connections much easier. As a bonus it was nearly a perfect fit for the case.

The magnetic switch and Si7021 will live outside the box, so those couldn’t get soldered yet. After connecting power I checked the ESPHome logs to make sure everything was working.

I cut holes in a project box, finished soldering, and used hot glue to secure the board..

I reversed the swing of the gate, placed my device, and attached the two sides of the magnetic switch to the gate.

In Home Assistant an automation runs whenever the stairs light is turned off to check the state of the gate. If it’s open, a notification is sent to our phones.

I’m enjoying these little electronics projects, and it feels good to finally put various parts to use.

Home Assistant Air Quality Monitors from IKEA Vindriktning

IKEA recently discontinued Vindriktning, their older air quality monitor.

Inside the device, they put a cubic PM1006K particle sensor. I bought three for $16.95 each last year, because I’d seen people hack them by adding sensors and a Wi-Fi microcontroller to send all of the data to Home Assistant. For my modding I bought:

The YouTube video linked above is a great guide to follow. I didn’t connect wires to the fan or the light sensor since I had no use for them. I also didn’t stack my sensors because I wanted the BME280 to be outside of the enclosure, where it would be less affected by the heat produced by the ENS160 and D1.

Even with the sensor outside of the case, the BME280 still reads high, because it heats itself up. I actually tested different lengths of wires and placements of the sensor before realizing I was still going to have to adjust the data. An ESPHome filter made the adjustment easy, which I did individually for each unit after comparing to a mobile Ecobee thermostat sensor. This is the code from the unit for my shop.

substitutions:
  slug: shop
  friendly: Shop

esphome:
  name: ${slug}-air-quality
  friendly_name: ${friendly} Air Quality

esp8266:
  board: d1_mini

logger:
  level: WARN

api:
  encryption:
    key: 'xxx'

ota:
  - platform: esphome
    password: 'xxx'

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  manual_ip:
    static_ip: xxx
    gateway: xxx
    subnet: 255.255.255.0

i2c:
  frequency: 100kHz

uart:
  - rx_pin: D7
    baud_rate: 9600

sensor:
  - platform: pm1006
    pm_2_5:
      name: PM 2.5µm

  - platform: bme280_i2c
    address: 0x76
    temperature:
      name: Temperature
      id: ${slug}_temp
      filters:
        - offset: -3.38
    humidity:
      name: Humidity
      id: ${slug}_humid
      filters:
        - offset: 7.63
    iir_filter: 16x

  - platform: aht10
    variant: AHT20
    temperature:
      name: AHT21 Temperature
      id: ${slug}_aht21_temp
    humidity:
      name: AHT21 Humidity
      id: ${slug}_aht21_humid

  - platform: ens160_i2c
    address: 0x53
    eco2:
      name: CO²
    tvoc:
      name: VOC
    aqi:
      id: ${slug}_aqi
      name: AQI
    compensation:
      temperature: ${slug}_aht21_temp
      humidity: ${slug}_aht21_humid

text_sensor:
  - platform: template
    name: AQI Rating
    lambda: |-
      switch ( (int) ( id( ${slug}_aqi ).state ) ) {
        case 1: return {"Excellent"};
        case 2: return {"Good"};
        case 3: return {"Moderate"};
        case 4: return {"Poor"};
        case 5: return {"Unhealthy"};
        default: return {"N/A"};
      }

These resources were a huge help when I wired everything up and made changes to the YAML code:

Here is how I’m displaying the data on one of my Home Assistant dashboards.

As I was working on this project I knew I wanted a couple more air quality monitors around the house, which will be finished soon.

Update: I’ve had to make a small update by adding a 47uF capacitor to each ENS160 board, because they have power issues, causing the reading to stop for periods of time. My boards matched up with the right ones in the picture at that link. Here’s a picture of another ENS160 I modified, since it was a tight squeeze to made the modification on the devices I posted about here with everything already wired up. I also realized I was powering these through the 3V3 pin instead of VIN, so I fixed that.

I’ve also improved the display of the data on my dashboard by using mini-graph-card.

Creating an ESPHome Remote Control Device with Infrared & Radio Frequency

In order to automate the processes of getting the golf sim ready to play and shutting it all down when finished I needed to create a remote control device. I’m using Home Assistant (HA) to run my home smart system (more posts to come), but two things involved with the golf sim aren’t connected to the network:

The projector has an infrared (IR) remote and the light has a radio frequency (RF) remote. I’ve done some things with IR and still had a stash of IR LEDs (for transmitting) and receivers. I’ve never attempted any RF stuff, so I ordered a 5 pack of 433mhz wireless RF transmitter and receiver pairs.

Since I’m using HA, I let ESPHome handle all of the main programming. All I had to do was wire everything properly and get the configuration correct. I made use of an old ESP8266 NodeMCU microcontroller and worked on the IR aspect of the project first.

When I took the picture I was using a 470Ω resistor, which I eventually switched to 100Ω, to increase the strength of the IR signal. The transistor is a PN2222A. Here’s the ESPHome configuration:

esphome:
  name: golf-remote
  friendly_name: Golf Remote

esp8266:
  board: nodemcuv2

logger:

api:
  encryption:
    key: "xxxxxxxxxx"

ota:
  - platform: esphome
    password: "xxxxxxxxxx"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  manual_ip:
    static_ip: x.x.x.x
    gateway: x.x.x.x
    subnet: 255.255.255.0

remote_receiver:
  - id: GOLF_IR_RX
    pin:
      number: D1
      inverted: True
      mode:
        input: True
        pullup: True
    dump: all

remote_transmitter:
  - id: GOLF_IR_TX
    pin: D2
    carrier_duty_percent: 50%

I used the receiver to intercept the codes sent by the projector’s actual remote when pressing the Power, Input, and OK buttons. Then I created some buttons.

button:
  - platform: template
    name: Projector Power
    on_press:
      - remote_transmitter.transmit_nec:
          transmitter_id: GOLF_IR_TX
          address: 0x3000
          command: 0xFD02
  - platform: template
    name: Projector Input
    on_press:
      - remote_transmitter.transmit_nec:
          transmitter_id: GOLF_IR_TX
          address: 0x3000
          command: 0xFB04
  - platform: template
    name: Projector OK
    on_press:
      - remote_transmitter.transmit_nec:
          transmitter_id: GOLF_IR_TX
          address: 0x7788
          command: 0xE619

It all went very smooth. Next I connected the circuits for the RF components, which was straightforward. Here are the pinouts from the Amazon product page.

I soldered on the antennas (smaller one to the transmitter) and connected everything on the breadboard.

By using examples from the documentation I was able to intercept RF codes.

When I tried to recreate those codes through the transmitter the results weren’t matching up and the spotlight wasn’t responding. It took some trial and error to configure the various parameters of the receiver. Here’s the end result, with the combined configuration for IR and RF.

esphome:
  name: golf-remote
  friendly_name: Golf Remote

esp8266:
  board: nodemcuv2

logger:

api:
  encryption:
    key: "xxxxxxxxxx"

ota:
  - platform: esphome
    password: "xxxxxxxxxx"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  manual_ip:
    static_ip: x.x.x.x
    gateway: x.x.x.x
    subnet: 255.255.255.0

remote_receiver:
  - id: GOLF_IR_RX
    pin:
      number: D1
      inverted: True
      mode:
        input: True
        pullup: True
    dump: all
  - id: GOLF_RF_RX
    pin:
      number: D6
      mode:
        input: True
        pullup: True
    dump:
      - rc_switch
    tolerance: 50%
    filter: 250us
    idle: 4ms
    buffer_size: 2kb # only for ESP8266

remote_transmitter:
  - id: GOLF_IR_TX
    pin: D2
    carrier_duty_percent: 50%
  - id: GOLF_RF_TX
    pin: D6
    carrier_duty_percent: 100%

After using the remote_receiver instances to get the button press codes I needed, I commented out that section of the code. If I ever need to add more functionality to my remote, I can enable the receivers at that point. Here are the button codes for the spotlight.

  - platform: template
    name: Spotlight On
    on_press:
      - remote_transmitter.transmit_rc_switch_raw:
          transmitter_id: GOLF_RF_TX
          code: '111001000000100100000011'
          protocol: 1
          repeat:
            times: 10
            wait_time: 0s
  - platform: template
    name: Spotlight Off
    on_press:
      - remote_transmitter.transmit_rc_switch_raw:
          transmitter_id: GOLF_RF_TX
          code: '111001000000100100000001'
          protocol: 1
          repeat:
            times: 10
            wait_time: 0s
  - platform: template
    name: Spotlight Green
    on_press:
      - remote_transmitter.transmit_rc_switch_raw:
          transmitter_id: GOLF_RF_TX
          code: '111001000000100100000111'
          protocol: 1
          repeat:
            times: 10
            wait_time: 0s

Then I was able to use both sets of buttons in scripts, which can feed to Alexa for voice commands.

Once everything was tested I wired and soldered a more permanent circuitboard. I included a folded dollar bill for scale.

I was planning to mount it in the ceiling, but the IR was having trouble, because the projector’s receiver faces the ground. Mounting it to the side of the PC cart worked great.

This was a lot of fun!

Update: Less than a week later I’ve already modified it, by adding a DHT22, which reports temperature and humidity. Might as well use that empty D7 pin on the microcontroller.

Unboxing: HackerBoxes #0022 – BBC Micro:Bit

The latest HackerBox came in the mail yesterday. I managed to avoid any spoilers so thought I’d see how dumb I can sound as I figured out what was in the box.

I’m looking forward to checking out the Micro:Bit and its blocks editor. The 128×64 OLED and WiFi modules will definitely get used in projects at some point.

Knowing the Micro:bit sells for less than $20, this box seemed light on value, so I had a look. Like last time, all prices are from Amazon unless noted.

  • HackerBoxes #0022 Collectable Reference Card – $1 (estimate)
  • BBC Micro:Bit – $16.99
  • BBC Micro:Bit Connector Breakout Kit – $5.38 (kitronik.co.uk)
  • Twin AA Battery Holder – $2.79
  • OLED 128×64 pixel I2C Display – $6.99
  • Alligator Clip Jumper Wires – $1.50 (estimate)
  • Miniature Solderless Breadboard – $3.26
  • ESP-01 Wi-Fi Modules – $2.60
  • Six LED Indicator Module – $1.10 (2 for $2.21 on aliexpress.com)
  • Passive Piezo Buzzer – $1 (estimate)
  • AMS1117 3.3V Regulator Module – $1 (estimate)
  • Header Pins – $1 (estimate)
  • DuPont Jumpers – $1 (estimate)
  • Micro USB Cable – $5
  • Micro USB Breakout Module – $1.84
  • Exclusive Micro:Bit Decal – $1 (estimate)

Several of these items are extremely cheap and only sold in multiples so I gave generous estimates. Total comes to $53.45. Things in that $3-7 range really add up quickly. Still a good value for the $44 subscription.

If you’re interested in learning more about this particular box, check out the Instructables guide or leave a comment and I’ll try to answer.

 

HackerBox #0020: Summer Camp

I managed not to look at any spoilers before HackerBox #0020 arrived, so I recorded a video when I opened it and talked through the items, trying to figure out what the theme was.

 

So, yep, it’s a badge inspired by the badges for Def Con (I had seen this story a week or two before, which HB shared as a hint on their Facebook page). Due to vacation, it was a couple of weeks before I was able to put this thing together. Hope you enjoy all of my mistakes in the assembly video. 🙂

There is a lot more to think about when recording what you’re doing and trying to keep talking throughout. I think it was an improvement over the video I did for the 5v relay module though. I really need to build a tripod or overhead mount of some kind so the GoPro is more stable. I may look into a newer GoPro as well with better battery life and a screen.

More details about the badge and demo code provided by HackerBoxes can be found on the Instructable page for this box. My customized demo code is in a hackerbox0020-demo repo on GitHub.

Update: I’ve updated my demo code to have examples of how to use the SD card that is on the back of the TFT.

Code with Microsoft for Beginners and Makers

It’s been quite some time since I’ve used any Microsoft products. They are really stepping up their game when it comes to makers and creating tools to teach people how to code.

Makecode (by Microsoft) is a site similar to Scratch. Both are great way for kids (or adults) to get started with programming. The powerful part is the drag and drop interface which simplifies coding. Instead of having to remember the syntax of a for statement, in the block editor you drag over a for block and fill in a couple of fields with the values for the variables. You don’t even need to buy a board to get started because the site has an emulator built right in.

makecode-circuit-playground-light-rotate.gif

Makecode has support for a bunch of microcontrollers aimed at beginners. Currently it works with micro:bit, Circuit Playground Express, Minecraft, Sparkfun Inventors Kit, and Chibi Chip. I selected the Circuit Playground Express for my example above.

They’ve also built a Visual Studio Code extension for Arduino, which is now open sourced. I downloaded VSC and installed the extension. I didn’t play with it very long, but it looks like it’ll be my new editor for Adruino projects. It does things that every programming IDE should do, like code completion, which the Arduino IDE still does not do. I also installed some Python extensions, so I’ll have to see how it compares to the Atom editor, which is what I’ve been using for Python programming.

visual-studio-code

Makerfocus ESP8266

One of the recommended products that came up recently for me on Amazon was a set of 2 Makerfocus ESP8266 NodeMCU boards for $15.99. I’m familiar with the chip from using the Adafruit Feather HUZZAH with ESP8266 WiFi that came with AdaBox003. That board runs for $16.95 though.

The reviews for these were good and any issues people had were resolved quickly by the seller. I figured it was worth the little bit of risk to try out these boards as a way to have some WiFi capabilities on hand. When they arrived, I ran a few quick tests in the Arduino IDE and had no problems uploading code or connecting to Adafruit IO with some of the example programs. The boards are slightly wider than the Feathers I’m used to working with, so there is just a single row of holes on either side when plugged into a breadboard. One other difference is no JST connector for a Lithium Ion battery.

If you’re looking for a cheap intro to Arduino or a way to get an electronics project on your network, check out these microcontrollers.