NodeMCU ESP8266 http relay control with 12v battery monitor and wifi configuration – Part 2

Part 2. (looking for Part 1?)

In our part 1 of this article we learned how to take a stock nodemcu esp8266 and flash it with the latest version of nodemcu. We also learned how to send and run files onto the unit using ESPlorer. In this final part 2, we will finally get to the guts of the how to set up a NodeMCU ESP8266 which provides a web interface for relay control, 12v battery monitor, and wifi configuration.

Some newbie hints on coding the NodeMCU ESP8266 with Lua scripts

NodeMCU default behavior loads the init.lua script on boot. When beginning to code and test out its functionality, its a good idea to just load your setup parameters in the init.lua script and for the init.lua script to call another lua file to run the bulk of the code. This lets you comment out the auto loading of the secondary lua script and lets you load it manually using the ESPlorer tool until you are certain the code doesn’t cause a kernel panic and leave you in an endless bootloop.

I ran into an issue where I didnt do this, and my ESP8266 bootlooped. I then needed to reflash the unit with a lower version of firmware, then reflash the unit with the newer firmware in order to wipe out its filesystem contents which contained the crappy code. What a waste of time.

Below is an example with the line calling the main.lua file to run commented out so I can just run it manually instead of automatically on startup:

Init.lua for testing

OK back to the topic at hand which was creating a wifi connected battery charger which can also allow me to monitor the battery voltage on my deep cycle battery left in Shasta. Whew!

The Hardware

My basic battery charger relay control and battery voltage monitor over http project involves just a few parts:

  1. A NodeMCU ESP8266 development board off ebay, or you can buy one from amazon here
  2. One (1) 110v-240v 30A 5v relay (to switch the power on or off to the battery charger)
  3. One (1) LED (visual indicator to show if charging or not – optional)
  4. Two (2) 1/4W resistors (I used a 1M ohm for R1 and a 330k ohm for R2 to make a voltage divider)
  5. One (1) Ceramic Disc .1uf 25v Capacitor (to normalize the voltage readings)

Wiring the NodeMCU to the hardware

Wiring is pretty straightforward: Im using the v0.9 NodeMCU development board but could only find the NodeMCU v1.0 image for the illustration below, but the pinout is pretty much the same. Just pay attention to the pin designations:




Some hints on wiring:

  1. I’m powering the ESP8266 board with a USB power adapter so there isn’t any power source shown
  2. Remember that R1 is the resistor closest to positive and that R2 is the resistor closest to negative (ground).
  3. If you get a small ceramic disc capacitor, the leads are not polarized and can be connected whichever way.
  4. Dont forget to connect the NodeMCU board GND to Battery GND or the analog read values will be wrong.
  5. I know in the illustration above, the LED leads are reversed and I also didn’t add a resistor to the LED (but the LED seems to be fine).
  6. I didnt show how to connect the relay to the power switching of the battery charger as your needs will be a little different from mine. But I am using one relay to control the AC input into the charger, and the other relay to disconnect the positive battery lead from charger to battery so the charger will not inadvertently drain the battery when left connected.

Calculating voltage divider values (the hardware side)

The ESP8266 Analog read pin (A0) on the NodeMCU development board has a voltage maximum of 3.1v. If using a bare ESP8266 module (such as an ESP-12) it is a voltage maximum of 1 volt. Since were using the development board, we will be finding resistor values to divide the 12-15v coming from the deep cycle battery into a reading the analog pin can sample, anything under 3.1v.

Be aware that the higher the resistance of the resistors, the lower the readings you’ll end up seeing at the analog pin in the ESPlorer console. If you choose a ratio of 10k ohms and a 3300 ohm resistor , then you’ll see a higher analog dc read value on the pin vs using a 1M ohm and a 330k ohm resistor (which is what i’m using). The reason that i’m using higher resistance value resistors is because i’m trying to minimize current drain when the circuit is left connected. If I am understanding this correctly, using this resistor combination only draws about 6 µA.

To calculate the resistor values you will need for your application, head over to this great resource which teaches you the basics: (There’s also a handy voltage divider calculator for you to use to determine your specific resistor values.)

If youre already overwhelmed, just keep in mind that the main idea is to divide the large 12-15v of the battery into a smaller voltage we can sample with the analog read pin on the NodeMCU board. Once the big (12-15v) voltage is divided and within the range the ESP8266 can coherently sample (below 3.1v), we just need to configure the software side of things to make everything work.


Two resistors with the correct resistance ratio will divide your input voltage

Finding your LSB to calibrate your voltage…WTF? – The software side

If you’re like me and this is your first electronics project requiring software and hardware all working together, the above heading will probably sound like you…its what I sounded like when trying to wrap my head around this analog read calibration concept.

Its simple once you get your head around it though.

Once we have our voltage divider working as it should, it will bring the voltage down to a level our analog pin can read (from 0-3.1v). However, the values shown by the console output wont display the voltage of the battery as we recognize it, but will instead show values in the range of 0-1024. This doesn’t help us much, so we just have to apply a little division to get real world values (the voltage level) from the 0-1024 reading.


In this case, we test the battery with a calibrated and known working multi-meter to get the current voltage of the battery, then do some division with the the ADC Value reading we get in the console when you click on the ‘READ DC VOLTAGE’ button on the battery charger control webpage.

Get the ADC value by clicking the READ DC VOLTAGE button on the battery charger control webpage

Get the ADC Value by clicking the READ DC VOLTAGE button on the battery charger control webpage


For example:

Multimeter reading  of battery = 12.56v
ADC Value reading from adc pin in ESPlorer console = 581
Math: 12.56/581 = LSB
LSB = 0.02161790

Now just use that LSB number to replace the LSB number in the main.lua script below and your voltage reading will be calibrated for our project!

The Code

Now that we have the ESP8266 running a current version of NodeMCU and are able to control it with ESPlorer, we can finally get to the fun stuff, running scripts! I’ve provided the code snippets below to peruse, but you can also just download the init.lua and main.lua files below to upload to your NodeMCU unit immediately. Both these scripts combined produce the webpage shown below and make everything work.

Download: (right click and save link as…)

The battery charger control webpage

The battery charger control webpage

INIT.LUA – A description

The init.lua file in my project does all the wireless heavy lifting. If the unit is powered on and does not establish a connection to an access point, it will then configure itself as an access point with SSID of “BatteryNode” with password of “password” which you can then connect to using a phone or computer. Once your device is connected to the “BatteryNode” access point, you then navigate using your web browser to to bring up the battery charger control webpage (make sure you turn off mobile data if the phone does not detect an internet connection using the “BatteryNode” AP or you wont be able to navigate to the IP).

After the webpage loads, at the bottom of the screen is a section to enter the SSID and password of the access point you want the NodeMCU battery charger unit to connect to. Be aware that the information you enter is case sensitive. Weird hangups or kernel panics happen when you don’t enter the credentials exactly. If you enter in an SSID that does not exist, the unit will kernel panic and reboot.

Wifi configuration section

Wifi configuration section

Once the unit connects to the access point you specified, it will then configure itself as a regular wireless client instead of an access point and you’ll be disconnected from the “BatteryNode” AP. It will also assign itself a static IP of

If you’re going to be using the ESP8266 unit on a different subnet than specified in the scripts, you’ll need to change the IP configuration in the init.lua script to match yours. You may also just comment out the lines below in order for the unit to get its IP address using DHCP.

Init.lua code

MAIN.LUA – A description

Main.lua handles the main processing of commands, it sets up the pins, defines the variables, and serves the website. Remember the LSB value you calculated earlier? You’ll need to remember to replace the LSB value in the main.lua file with your own LSB for it to correctly show your voltage on the webpage.

The ESP8266 will remember the relay state indicated by “OFF” or “ON”

The battery charger control webpage

Relay Control buttons

The readings will also change color of the voltage reading based on the following table (I skipped the orange color so its just green, yellow, and red).



webpage voltage reading in green

Main.lua code

There you have it, a guide which should allow you to have a fully functioning ESP8266 webserver which allows you to control a relay (which controls a battery charger), monitor the voltage of a 12v battery, and configure the wireless settings without needing to upload any new lua scripts. This was tested on a NodeMCU development board v0.9 with NodeMCU version

Some final thoughts and credit where credit is due

I’m sure the scripts could be optimized and reduced in size, and I welcome any tweaks or comments to anything i’ve written above. What i’ve essentially done is taken some smoothly written code from all over the internet and adapted it for my purposes. Below is a list of the resources I used to help build this project. They were the few articles that were written in a way where I could understand and also adapt for my own use. I couldn’t have done this project without them.

TCP/IP Http server with NodeMCU:

Setting up an access point with the ESP8266 or connecting as a client automatically:

Voltage Divider info:

Read Part 1 on how to set up a NodeMCU ESP8266 which provides a web interface for relay control, 12v battery monitor, and wifi configuration.

Post to Twitter

7 thoughts on “NodeMCU ESP8266 http relay control with 12v battery monitor and wifi configuration – Part 2

  1. ajithparma

    Everything is very open with a clear description of the
    issues. It was really informative. Your site is extremely helpful.

  2. Andy

    I’ve been wanting to tackle this for a while now and I finally have the time to try it out. I’d also like to find the amount of current the load is drawing. Could that be built into this also? If so, would you be able to provide some help with that?

    Thanks for your work and writing this out for those of us with little experience. You’ve made it really easy to grasp. I wish there were more tutorials out there like this.


  3. Jimmy

    This is rely good, but I cant connect to home router?
    Is there any here up fore a job control 4 channel rely over web using nodemcu I rely like to here about it.


  4. Den

    Hi there .. What a great article ..thank you ..very insightful indeed.
    Would you happen to have arduino code for the same project ?
    I have an ESP-12F and would love to try it on there and will happily give feedback etc
    thank you kindly


  5. Blog Master Post author

    For the value to continually update, you would need the screen to refresh every few seconds since it is plain HTML. You would also need to call the function every time the page is loaded.

  6. cento

    good evening I was trying your code I have appropriately modified the resistive divider for 1-100V.
    I tried to understand if the operation reads automatically with cycle.I tried to put a fixed voltage then to lower the voltage and wait, but the status of the relay does not change, until I press READ VALUE. so the readings are not automated? do I always need to press to detect the voltage? THANK YOU

Leave a Reply

Your email address will not be published. Required fields are marked *