Saturday, July 8, 2023

Creating an NFC Card Reader for Home Assistant

 


Every wish you could tap your phone, or a 'credit card' to a reader in your home and have it kick off an automation or scene?  Home Assistant has supported the use of NFC tags for multiple years now.  This article provides supporting information for building your own NFC card reader for use in Home Assistant.  It is recommended that you first watch the YouTube video of this project.

Introduction


There are a few different methods of scanning and using NFC tags in Home Assistant.  By far, the easiest method does not require any hardware beyond the NFC tags themselves and you mobile phone.


Most modern cell phones have NFC built-in.  Using this, and the Home Assistant companion app, you can scan most NFC tags (whether credit-card, button or key fob style) and a tag will automatically be created in Home Assistant.  There are even sticker-style tags that can be placed inside a CD or DVD case, or even inside the cover of a book.  Once the tag is created in Home Assistant, it can be used as an automation trigger.

So, if your phone can act as a reader, why would you want to build a DIY reader?  There are multiple reasons why a standalone reader might make sense for you.  When using the phone, first off, you must have your phone handy.  You must have NFC enabled on your phone (uses additional battery).  You may or may not want to install the Home Assistant companion app on your phone.

Or you may have a situation where you want multiple cards in a single location to run different automations.  Some examples might include:
  • Cards to launch various music services or playlists
  • Cards to launch various streaming services or videos
  • Cards to set different scenes in a room
  • Cards to enable or disable other automations
  • etc.
These are just a few examples of where it might be beneficial to have a standalone reader next to a series of cards.  This is the subject of this article.  If you want to know more about how to use a smart phone to scan tags into Home Assistant, see the links at the end of this article for a good beginning article.

Purchasing a Pre-built Reader


This project is primarily built on the previous work done by an individual who goes by the handle of Adonno.  He also offers prebuilt versions of the reader in a 3D printed enclosure.  If you want to skip the build, you can purchase one of his prebuilt versions on his web site here.  

But I generally prefer to build my own devices, and I do make a couple of hardware changes to his original version.  I'll note those changes below, but you could also build his original version. A link to his build is included at the end of this article.

Parts List


As always, I like begin with a parts list.  As mentioned above, I made a few substitutions from the original version.

QTY

Description

Notes

1

PN532 NFC Card Reader Module

 

1

Wemos D1 Mini (ESP8266)

 

1

Common anode RGB LED

 

1

Vibrating Motor

 

1

ElectroCookie Prototype Board

 

1

Resistor (220Ω – 10kΩ)

 

1

5V 2.5A Power Supply

Most phone chargers will suffice

1

USB to Micro USB Cable

 

-

NFC Cards (or other tags)

Various styles available

-

20 gauge Solid Core wire

 

-

22 gauge stranded wire

 

-

Straight Pin Headers

Needed for PN532

 

 

 

 

Optional Item(s)

 

 

Inkjet/Laserjet labels

For labeling NFC cards

 

For Testing/Prototyping

 

 

½ size Breadboard

 

 

Breadboard jumper set

 

 

Dupont Jumpers

 

 

 

 

 

 

 

Some of these links may be Amazon affiliate links.  Use of these links will not affect your pricing, but this blog may earn a small commission if you make a purchase.

In Adonno's original version, a single WS2812b LED pixel was used in place of the common anode RGB LED and a piezo buzzer was used in place of the vibrating motor.  

I opted for an single RGB LED instead of a WS2812b pixel for two reasons.  One, you may not have a strip of WS2812b LEDs and purchasing an entire strip for just one pixel is much less cost-effective than purchasing a small pack of common anode LEDs and because my 3D printed enclosure will be black (for Wife Acceptance Factor reasons) and the WS2812b LED would not shine through the black faceplate.

I also opted for the vibrating motor instead of the piezo buzzer because I did not want the sound/noise from a buzzer, but instead a mild vibration to indicate, along with the LED, a successful card read.  

ESPHome Code


Before building and testing a breadboard version, we need to install the ESPHome code onto the D1 Mini.  There are multiple ways to create the ESPHome node with the code.  I found the easiest way is to create a new ESPHome Node (and give it a name like tagreader or maybe tagreader-location if you plan on building more than one).  Then you can copy/paste the code from either Adonno's repo (if using his hardware) or my version if using the common anode LED and vibrating motor.  You can find a copy of my version of the code in this gist file.

The primary difference between Adonno's code and mine is the definition of the LED and buzzer:

# LED Indicator
light:
  - platform: rgb
    id: activity_led
    name: "RGB LED"
    red: output_red
    green: output_green
    blue: output_blue    
    
output:
  - platform: esp8266_pwm
    id: output_red
    pin: GPIO2
    inverted: true
  - platform: esp8266_pwm
    id: output_green
    pin: GPIO14
    inverted: true
  - platform: esp8266_pwm
    id: output_blue
    pin: GPIO12
    inverted: true

  # Vibration Motor - will turn off after 500ms
  - platform: gpio
    id: vibra
    pin: GPIO15
    name: "Vibration"
    restore_mode: ALWAYS_OFF
    on_turn_on:
      - delay: 500ms
      - switch.turn_off: vibra

There are a few other changes, including how the buzzer is called in my code.  In either case, be sure to update the copied code with your wifi SSID, passwords, etc.  These are highlighted via comments in the code.  I'm not going to cover installing ESPHome onto the D1 Mini, nor integrating the new ESPHome node into Home Assistant as this is covered in the video version of this article and a lot of other places.

Wiring Diagram and Breadboard Testing


Once the ESPHome code is installed, I recommend that you first create a breadboard version to test before creating the soldered version.  Here is the general wiring diagram:

Click to enlarge

While the above images shows the final version on an ElectroCookie version, the layout of the ElectroCookie is exactly the same as a 1/2 size breadboard, so you can use jumpers, Dupont cables, etc. for testing.  Note that in the above diagram, the PN532 has been removed (dotted orange line shows where it will be), but you can just connect it with Dupont cables for testing.



Note that the PN532 supports three different communication protocols, UART (Universal Asynchronous Receive/Transmit), I2C (Inter-Integrated Circuit) and SPI (Serial Peripheral Interface), but you must set tiny DIP switches on the board to indicate the communication method you are going to use.

In this case we will be using I2C, so we must set the DIP switches on the board accordingly.


For I2C, the first DIP switch needs to be on the "on" position and switch 2 in the off position.

Once you have assembled the breadboard version, connect it to 5V via USB cable.  When the boot process finishes, the LED should briefly flash and the vibrating motor should briefly vibrate.

Now, open Home Assistant and navigate to Settings  => Tags.  Hold a new or previously unused NFC card, fob or tag in front of the PN532 reader and the LED should briefly light up green, the vibrating motor should vibrate for 1/2 second and a new tag should automatically appear in Home Assistant:


Note that the tag will originally have a tag ID number.  I highly recommend that you click the gear icon on the right and give your tag a meaningful name.  


If you plan on having multiple cards, you may also wish to label the card or tag itself.  You can write directly on the tag with something like a Sharpie, or you can print a label and place it on the card/tag.




Once you've assured all is working, you can transfer the parts to a final soldered version on the ElectroCookie board.

Final Assembly


The wiring on the ElectroCookie basically duplicates the breadboard version.  You just have to be a bit creative with how you run the wiring to get everything to fit.

Click to enlarge

The vibrating motor will eventually be attached to the lid of my enclosure. And because my 3D printed enclosure has mounting posts for the ElectroCookie board (it accepts M2 screws), it also allows me to complete some of the wiring on the underneath side of the board.


Be sure to connect the two ground (negative) rails on the ElectroCookie board as shown in the diagram above, but do not connect the positive rails.  I used 20 gauge solid core wire for all the connections between thru-holes on the ElectroCookie board and 22 gauge stranded wire for the connections to the LED and vibrating motor.

If you do not have a 3D printer, there are a number of small project boxes that can be found on Amazon or elsewhere that can be adapted for this project.  You may need to adjust the location of some components, like the LED, that I placed in the above location so that it would align with my enclosure.


And here is my final version, all put together inside of the enclosure:


The enclosure is just slightly bigger than a playing card/NFC card and it is about as tall as a deck of standard playing cards.  The only external wiring is the USB power cable.

Any NFC card/tag can be scanned by just holding/tapping over the solid portion of the enclosure.  The final thing to do is power it up and try scanning some tags with Home Assistant.

Scanning Tags


As described above, adding a tag is as simple as opening up Home Assistant, navigating to System => Tags and tapping a new tag to the reader.


The new tag will show up with a tag ID number.  You can give this a friendly name by clicking the gear icon and entering the desired name.  You can scan as many tags as you like, whether these be cards, buttons, key fobs, etc.


If you scan a tag that has already been recorded, it will simply update the 'Last scanned' time of the existing tag.  Once you have scanned the tags you plan to use, you can now use them as triggers in automations.

Creating Automations


You can easily create an automation from any tag by clicking the automation symbol (little robot looking icon) next to the tag name or by creating a new blank automation from the automation UI.


If you click the automation next to the tag from the tag screen, Home Assistant will automatically create the appropriate trigger for you.  If you are starting with a blank automation, simply select "tag" for the trigger, then drop down the list to select the tag you wish to use as the trigger.



Now you can add any optional conditions and the actions for this automation.


In my case, I'm running an existing script that handles turning on the home theater components, selecting the proper input and launching the YouTube TV service.  But you can use any valid action(s) for your automations.

Creating your automation in YAML

If you happen to be like me and prefer to create your automations in YAML so that they can be placed in packages or other files outside of the primary automations.yaml file, the process is much the same:

  # =====================================
  #   NFC Card Scanning (basement reader)
  # =====================================
  - alias: Tag Scanned YouTube TV
    trigger:
      - platform: tag
        tag_id: 2D-81-6D-37
        # device_id: c468ca7c820f0fc6c1f73f4d7b7d3d49
    action:
      service: script.turn_on
      target:
        entity_id: script.btn_roku_youtube_tv

The one caveat here, at least as of the time of this article, is that you cannot use the tag friendly name in YAML... you must use the actual tag ID number.  If you do not recall the tag number, you can find it by returning to Tags under the Settings and clicking the gear icon of the tag.  This will show you the tag ID.



In addition, you can optionally specify a device ID in the trigger (or conditions).  The device ID is the device that scanned the tag.  This means that you could use different automations for the same tag based on which device scanned it, such as a different family member's phone or a card reader in a different room.  To get the device ID, go to the Developer Tools => Events.


Under Listen to Events, enter tag_scanned under Event to subscribe to and click 'Start Listening'.  Now scan any tag with that device and the device_id will be returned in the event data.  Use of the device ID as part of the trigger is optional.  I'm not using that in my automations, so I have it remarked out in my sample YAML above.

Create as many automations as you like, based on the tag ID, device ID or both!  Now, a simply tap of a tag to a reader will immediately launch that automation.

Conclusions and Future Thoughts


While tags have been a part of Home Assistant for a while now, I never found a good use case in our home.  But the recent 'cord cutting' of a major satellite service that we had used for over 26 years and going to strictly streaming services resulted in some major differences in how we control the home theater system to watch TV.  This seemed like a good test case for using a card reader and some NFC tags.

And since implementing it, it has become one of my wife's favorite new things in Home Assistant, substantially simplifying the process over multiple remotes.  Big WAF (wife approval factor) points for me on this one!  It also makes it very easy and intuitive for visitors and guests to control the home theater.

I also now have a better understanding of how else tags might be used around the house.  While I think there are some situations where something like a Zigbee button will suffice, I can also see situations where a tag reader might be a better fit.  Let me know down in the comments how you use tags and tag readers in your Home Assistant installation. 

Links and Additional Info





If you'd like to support future content on this blog and the related YouTube channel, or just say thanks for something that helped you out, you can say thanks by buying me a one-off cup of coffee at:

No comments:

Post a Comment

To help eliminate spam and to keep all conversations civil, submitted comments are moderated. Therefore your post may not show up immediately. Please be patient as most reviews are completed within a few hours.