Introduction: ESP-12 Toolbox - Seamless Integration of Multiple Sensor Measurements, Alarm Detection, Time Stamping, Email & Twitter Notification, Push to the Cloud and Plenty of Room for Your Application, All in One ESP-12 Module EDITED
New sketch file in Section 11 fixes a bug with the kWh power calculation.
The arrival of the ESP8266 device has significantly boosted the design possibilities open to us due to its super low cost and built-in features especially in the Internet of things (IoT) arena. The latter immediately leads us to think of features such as automatic emailing, tweeting, cloud storage and wireless remote control, all readily available in the Arduino world but not always so easy to implement especially for the novice and in particular if you want to mix and match these features to work together.As a retired professional design engineer, one of my design approaches was always to "look at the bigger picture" and try to create whenever possible "re-usable modules" both within the hardware and software worlds so minimizing the need to "re-invent the wheel" each new project.
My other desire is not to have to learn new tools for each project and in this case the Arduino IDE long ago became one of my favourite design environments. Thanks to the Arduino crew, we now have the ESP8266 integrated into their IDE so now we have the best of both worlds and life is good. This instructable is a first step towards my goal of creating a range of re-usable ESP8266 application modules using the Arduino IDE but not requiring an actual Arduino board (I.e. they fit solely within a single ESP8266 module). There are several published projects that present solutions similar to those included here but I am yet to find one that successfully integrates everything seamlessly into one project. With this in mind, I present a "one stop shop" project that includes several popular and useful functions integrated into a simple hardware configuration based around a single ESP-12 device (however equally usable with the other available ESP8266 modules subject to the IO limits of each module). It is able to connect to the house WiFi network and thus gain access to the internet with all of the prescribed functions working seamlessly and reliably together with each other whilst at the same time being modular in approach allowing you to simply call them on their own or together within your own sketch. As well as each function, I have included a very simple demonstration application in the void() loop to allow you to test and see how each feature operates. You can replace this with your own application including other measurements and functions to suit your own requirements and simply by calling the relevant function when required and/or adapting them when necessary. Within this sketch we have ...
- Temperature and humidity measurements using the DHT11 or DHT22 sensor
- AC mains current and power consumption monitoring using a current transformer.
- Simple alarm detection and messaging using any suitable hardware or software sensor.
- Transmission of up to 8 separate measured parameters to the cloud via a ThingSpeak account.
- Emailing of the measured data and/or alarm messages to any specified email address.
- Tweeting of the measured data and/or alarm message to your Twitter account
The project hardware is presented in breadboard format without a final PCB layout or power supply solution since the final implementation will depend on your own application needs but the complete design as shown as measured with my multi-meter runs on a 3.3V supply at a maximum current of 90 mA. I have NOT included an obvious function namely "remote control". The reason for this is simple. I do have it within my toolkit but it is having reliability problems therefore needing more work - this will be added at a later date. Full downloadable instructions and where relevant, component data sheets are supplied for each element of the project. If you like it, please vote for it - I have to justify my time at the computer to my wife :)
I should mention that there is plenty of I/O and memory space still available in the device to allow you to take this sketch and adapt to your own application .... happy making :)
Step 1: Parts List
The project is modular in terms of software and hardware so I have split the parts list up into sections depending on its functionality.
Most if not all of the components can be purchased from the usual online retailers including Amazon, Ebay, Bidorbuy and of course a load of Chinese retailers such as Banggood, AliExpress and Alibaba
Basic (minimum) components
- 1 x ESP-12 or ESP-12E board. Other ESP modules may be used and depending on the module.
- 1 x Perforated board approx. 30 x 35mm
- Connectors for the perforated board
2 x 8 way female or male "stacking header"
1 x 6 way female or male header (extended pins not required) - ESP-12E only
- 2 x SPST push button switches used for "manual reset" and "boot to flash mode". The type is not critical and for this project a simple PCB mounting type was used.
- 1 x 3.3V RT232RL or CP2102 USB to TTL interface board. There are so many versions of this board available it is difficult to specify one version. The main criteria are ...
: Take care with the 5V/3.3V issue. Some are 5V and others are 3.3V but many can be switched between 5V and 3.3V
: The pin arrangement varies with the type but is normally printed on the silkscreen. The important connections are Tx, Rx, 0V and 3.3V output
: You will not require this card if your chosen ESP8266 module already has a USB connector on the board.
- 2 x 10K0 resistors (actual value and type are not so critical). For use as pull-up resistors for the SPST pushbutton switches
- Current transformer (CT). Many types are available with or without an internal shunt (burden) resistor and for different current ranges. The one that I used was an SCT 013 30A/1V purchased from Amazon and is a 30A device with a 1V output meaning that there is already a built-in burden resistor. I recommend that you use one that does NOT have a built-in resistor because this gives you maximum design flexibility and allows you to best match the CT to the 1V input range of the ESP-12 analogue channel.
- If a burden resistor is not included then you need to provide one and the value of this needs to be calculated based on your measuring range and the type of CT purchased. Instructions are given later in section 4 for this calculation. The recommended resistor type is metal film 1% or better for its stability and tolerance. Carbon resistors are NOT recommended.
- Resistors. 1 x 10K and 1 x 56K. the recommended type is metal film 1% or better. Carbon resistors are NOT recommended.
- 1 x 10uF 16V Electrolytic capacitor (higher voltage rating is fine).
- A 2.5mm or 3.5 mm audio jack socket depending on what type of plug is attached to the CT.
- For testing of this project, you do not need anything more than a digital signal such as a push button switch to simulate the occurrence of an alarm signal. The actual alarm device in your application can be a Passive Infra Red (PIR) movement device, an alarm mat, door/window contact switch etc. As a guide, I have specified an HR SR501 PIR device as one of the most common devices on the market and a data sheet is include in the final section. Care must be taken with the power supply and signal output of your device and the SR501 needs 5V for its power supply, its alarm output however is specified at 3V
- An SPST switch is required as an "alarm enable signal. here I used a simple PCB mounting slide switch but again, this is not a critical component.
- 2 x 10K pull up resistors (to the 3.3V power rail) for both the alarm and alarm enable inputs. The resistor type and tolerance is not critical.
Temperature and humidity measurement
- A DHT22 or its lower performance but cheaper cousin DHT11 is used for this dual measurement. I include a data sheet for both devices to help with the specification.
- 1 x 4K7 resistor is needed for the device digital output signal to the ESP-12. The resistor type and tolerance is not critical.
- I have not included a specific 3.3V DC power supply directly in the project because your choice of solution will depend heavily on your total application specification, packaging and configuration. There are many pre-built 3.3V power modules available and of course you can build your own or regulate down from an already existing DC supply. Nevertheless, the topic of power is important and will be discussed again later.
Step 2: Arduino IDE Set Up
A-B. In the Arduino IDE, open the FILE-PREFERENCES-SETTINGS window and enter the URL (highlighted in yellow in the picture) into the "Additional Boards Manager" URL field and select OK
C. Select the menu option TOOLS-BOARD-BOARDS MANAGER and scroll down to locate the option "esp8266 by ESP8266 Community (should be the last item on the list) and click INSTALL
After the files are downloaded, close down and re-start the Arduino IDE. We can now select the board that we are using from the menu option TOOLS-BOARD-GENERIC ESP8266 MODULE
Plug in the FT232RL or CP2102 or your ESP8266 board with built-in USB connector to the computer and you should be able to select the correct COM port number that it is assigned to.
D. Note the required library files that will need to be installed.
The ESP8266WiFi.h and WifiClient.h libraries are included in the ESP8266 library but you will need to install DHT.h and WiFIClient.h in the usual way through the IDE Library manager.
At this point the IDE is "ready to go" and you can start with the sketch ....
Step 3: ESP-12 or ESP-12E Preparation for Breadboard Use
The ESP_12 or ESP-12E module as supplied is unfortunately not compatible with a breadboard or
stripboard usage without some work to make it more user friendly. Fortunately with the correct tools and a steady hand, this is not so difficult and I include the following instructions to allow you to adapt it for easy prototype work.
A-B-D. You will need a pair of pointed nose pliers/pointers, wire cutters, a small piece of perforated board typically 30 x 35 mm, some thin single strand wire with the insulation removed, a soldering iron with a fine tip and solder and the PCB mounting connectors as per the parts list.
Note that unlike the ESP-12E, the ESP-12 does not have the 6 connectors at the end opposite the aerial. In this case or if you do not want to use the additional IO that the ESP-12E offers, you can miss the end male header mounting.
C. I highly recommend the use of a “third hand” assembly tool with or without the magnifying glass as this can be quite fiddly without a holding fixture whilst you are fixing and soldering the wires.
E. Before connecting each wire to the ESP-12 terminals, strip off the isolation of the single strand wire (you don't have to worry about them shorting as this will be handled later). Push the wire through the ESP-12 board circuit board terminal and bend it back. Arrange the wire so that it points away from the board (see photo) and gently solder it ensuring that you do not apply too much solder (possible short circuit to other terminals or the ESP case) or you overheat the board. Take your time, it can be fiddly but you will soon become an expert with practice. Cut the now attached wire so that there is 15 to 20 mm sticking out from the terminal pad.
F. Repeat this for each output pad on the ESP board.
G-H. The next step is to mount the ESP board onto the non-copper side of the perforated board. This also can be a bit tricky as the wires are very thin and bendy but patience will serve you well. Making sure that you have selected the correct location on the board to later fit the headers, one at a time using the pliers / tweezers thread each wire into the corresponding hole in the perforated board and gently pull it through to take up the slack. Repeat for each wire as per the photo. Take care not to snap the wires but if you soldered them correctly they will be able withstand a bit of force.
I. Then insert the female headers in the row next to where you brought the wires through – each pin should line up aside one of the wires. Solder just one of the header pins to allow you to fix the header in the board ensuring the header pin protrude at right angles through the board (a future concern when plugging the final assembly into the breadboard) Next take each wire in turn and gently guide it around the pin next to it and wrap it around the base of the pin. Solder the wire and base of the pin to the board copper pad, trim any surplus wire with the cutters taking care not to cut the wire leading to the ESP module and that there is no short circuit to the adjacent pin.
J. Repeat for each pin. Fit the next header and repeat the process for each pin. If you are fitting a third header for the ESP-12E extra IO pins then note that this time, the male or female header does not have extending pins as we do not want them to plug into the motherboard.
K. Note that the photo of the completed assembly shows a male header for this connection but a female header can also be used if preferred. You have now finished the conversion.
Check the alignment and straightness of the pins by plugging the assembly into a breadboard. With the majority of standard breadboards, due to the large size of the plug in board, you will probably have to use the connectors on the assembly to make connections to the ESP board rather than the breadboard.
L. Once assembled on the perforated board, unfortunately you lose sight of the pin identification information written on the device so use this diagram as a top view representation of the ESP-12E module. The ESP-12 does not have the I/O of pins 9-14 however the remaining pins are the same
Step 4: Calculation the Value of the CT Shunt (burden) Resistor (Power Monitoring Only)
The first question to answer is “do I need a shunt (also called a burden) resistor as some current transformers (CT) have it built in. In my case I used a SCT013 30A/1V device which includes the burden resistor and so produces a 1 volt output at 30A load current however this is also available without the burden resistor.
So assuming that your device does NOT contain a burden resistor, you need to provide one and as such you need to calculate the value required for your burden resistor Rb. Its job is to convert your CT current into a voltage value.
First, …. Some basics … When we state numerical values of AC mains voltages and currents we are normally referring to their Root Mean Square values (Vrms, I rms), their inter-relationships with other important terms can be defined as:
- Vpeak = 1.414 x Vrms
- V peak to peak ( Vp-p) = 2 x Vpeak = 2.824 x Vrms
The currents values (Ip-p, Irms etc) also follow the same relationships (I.e Ipeak = 1.414 x Irms).
The issue to take care of is that the ESP8266 analogue input convertor will be exposed to the Vp-p of the CT output rather than the RMS values that we are more familiar and interested in. This means that the maximum Vrms that the 0-1V DC analogue input input can cope with is (1 / 2.828) = 0.35Vrms.
You need to determine from the CT specification its maximum primary current (E.g 30A rms) and the turns ratio of the transformer (E.g. typically 500 to 5000). Start by dividing your maximum primary current by your CT’s turns ratio. This will give you the maximum rms current to be developed across the burden resistor at the maximum load current.
So a 30A rms device with a turns ratio 0f 1800:1 gives a secondary current of 0.01666A rms or 16.66mA rms.
We use Ohms law to calculate the resistance required to develop 0.35 Vrms at 30A rms primary current (R=V/I) gives us R=0.35/0.01666=21R.
This value can be achieved with standard resistors by combining a 10R+10R+1.0R in series. (Note that I have not taken into account any tolerances in these calculations). This gives the possibility of measuring up to 30A at your mains voltage.
To calculate how many amps your CT needs to sense, take the maximum continuous power you are expecting to measure and divide this by your mains line voltage (usually 110, 220, 230 or 240V depending on your country).
My mains supply is 220V AC giving me the possibility to measure upto (220 x 30) watts = 6.6 kW. Clearly if you use a different transformer and/or have a different mains line voltage these numbers will be different so you need to chose your CT and size your resistor appropriately taking care with the RMS to peak to peak consideration for the ADC.
When the burden resistor is built in, it saves some work and a component but removes any design flexibility and risks limiting your power measurement range if you have a lower mains line voltage. (E.g. The built in resistor of the SCT013 is 62R so as it stands, I have a reduced sensitivity since my calculation above shows 21R is my ideal resistor. Although I have not tried it (yet), I am expecting that I can maybe improve this by adding resistors in parallel with the CT output to reduce the total resistance closer to the 21R requirement for my scaling requirements or alternatively I must change the CT to another type.
I lifted the following data from another instructable (see section 11) as an indicator to some commercially available CT’s (I have not checked their accuracy!)
- Murata 56050C – 10A – 50:1
- Talema AS-103 – 15A – 300:1
- Talema AC-1020 – 20A – 1000:1
- Alttec L01-6215 – 30A – 1000:1
- Alttec L01-6216 – 40A – 1000:1
- Talema ACX-1050 – 50A – 2500:1
- Alttec L01-6218 – 60A – 1000:1
- Talema AC-1060 – 60A – 1000:1
- Alttec L01-6219 – 75A – 1000:1
- Alttec L01-6221 – 150A – 1000:1
Step 5: Hardware - Wiring the Breadboard ... the Minimum Configuration
The actual components used will depend on what functionality you require so simply install on the breadboard which modules are relevant to you.
The basic ESP-12 module & support components are common to all and therefore represent the minimum configuration and essentially is the ESP8266 mounted on the perforated board as described in step 4 and then just plugged into the breadboard. Any wires to be connected to the actual ESP-12 module are to be plugged into the corresponding header connector soldered to the board.
You should also mount and connect the two SPST push buttons S2 (reset) & S4 (flash boot mode) together with 10K pull up resistors and the FT232RL USB to TTL interface board. If you are not using the latter to provide the 3.3V supply then also connect an external 3V3 power supply instead of using the 3.3V output of the FT232 (leave this unconnected).
Any final project is unlikely to have the FT232 board permanently connected unless you require communications between the computer and the module. The choice of power supply is very important - see the next section for more discussion.
Step 6: Hardware - Wiring the Breadboard ... Optional Modules
A. The choice of power supply is very important - the most important 1st point is that the basic power supply voltage requirement is strictly 3.3V. Current consumption will depend on the hardware used and also the operating mode of the ESP8266 module (E.g. consumption is higher when the WiFi is operating). The other very important point is that the supply voltage must be stable, I found that if the supply is not adequately regulated, the supply can suffer from occasional “glitches” or dips in the voltage for several milliseconds at a time. These are not normally a major problem but I found that occasionally a programming failure would occur during upload. The solution is to simply make sure you use a robust regulated supply and I suggest placing a 1000uF electrolytic capacitor across the 3.3V supply.
There is much discussion on the internet groups as to whether the USB to TTL serial interface board can supply enough power to the ESP-12 directly with many saying “no” and recommending that a separate supply is always used.
My own experience after testing 4 separate FT232 boards and using them to also power the components (ensuring that it is linked to 3V3 rather than 5V!) and 2 different 3.3V external supplies, all worked fine albeit with the occasional programming upload failure (not a fatal problem, if this happens, you should just reset the board and repeat the upload).
Temperature and humidity sensor
B. The sensor chosen for measuring temperature and humidity is the well proven and easily available DHT22 (or it's lower spec relative DHT11). It is a combined relative humidity and temperature sensor and it transmits its data serially in digital format on its data pin. The DHT22 sensor can be powered directly from our local 3.3V voltage and measures from -40oC to +80oC with an accuracy of +/- 0.5oC for temperature and +/-2% for relative Humidity. Its sensing period is approximately 2 seconds and so we allow a minimum time between successive readings of approx. 4 seconds to be safe..
For more details of the sensors refer to the DHT11/22 data sheet enclosed with this project. The DHT11/22 modules although having different dimensions and colours have identical pin layout as per below
1. VCC - Connected to the 3.3V supply
2. Data out. Connected to GPIO2 of the ESP-12 module with an 4.7K pull up resistor to the 3.3V power rail.
3. Not connected
4. Ground – connected to 0V
Power consumption measurement
C. This is surprisingly straightforward and is focused on the current transformer providing a 0-1 peak to peak sine voltage (at full resistive load). To measure this correctly with the single ended DC analogue input converter, we reference the CT output to a voltage value ½ of the value of the range of the A/D converter. The latter being 1V gives us a reference value of 0.5V DC. This is achieved with the resistor chain R4 & R5 across the 3.3V power rails. The reference voltage at the junction of R4 & R5 is (3.3 x R4)/(R4+R5) = 33/66 = 0.5V DC. This will now allow the ESP8266 A/D input to measure a 1Vpp value sine wave.
D. The alarm trigger is a simple configurable low to high or high to low digital (via the sketch) input switch transition on GPIO14 with a debounce window of 1 second (I.e. it must be active for 1 second before responding). This means that the trigger device can be a PIR movement sensor, door or window switch, floor mat or simply anything that gives us a digital status change when our alarm threshold is activated. The only critical criteria here is that the input switching voltages must not exceed 3.3 V. If you have anything more than that, you should consider level conversion by whatever method is appropriate E.g. resistive ladder, opto isolator, transistor, relay etc.
E. We do not want the alarm to be active all of the time so I have included an extra input switch on GPIO12 that acts as an alarm enable/disable. When this is OFF, the alarm input has no effect.
Note. This is a “demo” program for the alarm function. To prevent unwanted repeats of the alarm message if the alarm condition persists, I have included a 3 minute “lock out window” after an alarm activation.
It is expected that you would refine the alarm procedure to suit your own particular requirements and preferences.
Step 7: Set Up a ThingSpeak Account
A. First you must sign up for an account at www.thingspeak.com
B. After creating your account, follow the onscreen instructions to create a new Channel ….
C. Set up the channel name and then tick the box on the right hand side of each field name to activate it and then type in the name of up to 8 data fields that you will be sending to the account from the sketch.. In our example, we have used 5 of the data fields Current, power, kWh, humidity and temperature. For now you do not need to fill in any of the other data boxes for the channel. Pressing the “Save Channel” button will save the data and the channel is created.
Note at the bottom of the screen, there is also a “Clear Data” button that allows you to clear out any stored data when required.
D. On saving the channel data, you are presented with the main channel screen and you will see a plot of each field that you have entered. You can set up each field plot separately by clicking on the settings button at the top right hand corner of each field plot. Near the top of this screen, you will see the tabs that take you to each section of the channel settings …
E. Selecting the API keys takes you to the “Write API key”.
You should copy and paste this to the API string value in the sketch …
F. To use the Twitter function, of course you first need a Twitter account and then you can link it to the Thingspeak channel by the ThingTweet app accessible from the Apps tab on the main screen.
G-H. Enter your Twitter details on pressing the “Link Twitter Account” button and then copy and paste the resulting API key into the sketch …
Note that there are many other interesting Apps with Thingspeak worthy of some checking out on your own that will allow you to process further the data that you have pushed to your channel.
Step 8: Set Up a Gmail Account ...
Setting up the gmail account is pretty straightforward but care must be taken in ensuring that the correct log
in details are entered into the sketch.
B. The parameters to be set up can be found in the Gsender.h tab in the sketch and are highlighted in yellow in the diagram.
A. Open up the website https://www.base64encode.org/ and enter your account log in username into the top box.
A-B. Press the “ENCODE” button. A base64 encoded version of your username will appear in the second box.
Cut and paste this into the highlighted part of the EMAILBASE64_LOGIN value making sure that the value is enclosed in quotation marks.
Repeat the process by typing your account password into the top box and cut and pasting the encoded version into the EMAILBASE64_PASSWORD field.
B. Replace the FROM field with the email address that you want to appear in the From field of the email that is sent out (note that this can be any email address).
The account part of the sketch is now set up.
C. The last task for you is to change the security of your gmail account to allow the sketch to connect to it.
Go to your Google account settings at https://myaccount.google.com/security#activity and enable "Allow less secure apps" at the bottom right hand side of the page. This means that apps only need your email and password when logging in to your gmail account.
If you are concerned about security, set up a new gmail account just to use with this sketch
Step 9: The Sketch .....
Before compilation, set up the WiFi login, email and twitter configurations in the sketch ...
B. Enter the SSID of your network and its password into these lines of the sketch.
J. At this point of the sketch you should enter email address of the person you want the alarm message sending to, the email subject line and message content that you want to send to your designated email address and your tweet alarm message (they can be different) that are automatically sent when the alarm is activated. If you do not do this then I will receive the message :).
Make sure that before you compile and upload the sketch, you follow the following reset sequence ....:
1. Press the S4 button (Boot to flash mode) connected to the GPIO0 pin
2. Then press the S2 Reset button connected to the RST pin
3. Then release S2 (Reset)
4. Then release S4
This will force the ESP-12 to boot up in the correct mode for flash programming.
Compile and upload the sketch to the ESP12 board.
A. If you get an upload message at the end of uploading then you have not pressed the switches in the correct sequence or incorrectly wired the switches.
C. Open up the serial monitor window of the IDE ensuring that the baudrate is set to 115200 or your value if you changed it in the sketch and press the S2 reset button momentarily to reset the sketch.
Assuming that you have correctly loaded the WiFi network SSID and password in the sketch, the screen should show all of the essential parameters of your connection to your own network connection.
D. The sketch is loaded with a simple void() application that checks the keyboard for selected key depressions. Depending on the selected key, the routine will run one of the standalone functions. It also calls the Check_Alarm_And_Email_Tweet_If_Active function for possible alarm activity and flashes the heart beat LED once per loop to indicate healthy activity.
The keyboard actions result in …
E. Press “h” (lowercase) followed by the enter key to get and then view on the serial monitor the temperature & humidity data
F. Press “p” (lowercase) followed by the enter key to get and view the current (I), power (P), totalised power value (since last reset or power on) and the last stored temperature and humidity data
G. Press “T” (uppercase) followed by the enter key to go online to the NTP server and get & display the latest time in hours, minutes and seconds
H. Press “d” (lowercase) followed by the enter key will get fresh sensor data and send it to your enabled Thingspeak data channel on the cloud.
I. Press “t” (lowercase) followed by the enter key to get fresh sensor data and then send it to your twitter account that you will have linked to your Thingspeak account.
K. Press “e” (lowercase) followed by the enter key to get fresh sensor data and then email it to your chosen email address. If on running the sketch, you see “rejected” at line 235, you have loaded in correct login details or not reduced the security settings of the gmail account
L. Activate your designated alarm input for greater than 1 second and then release it. The unit will send the pre-programmed messages to both the chosen email address and your Twitter account.
M. As per the original compliation , the ESP-12 remains disconnected from the WiFi network when it is not performing one of the required functions (I.e it connects to the WiFi before performing its task and then disconnects. This is controlled by the Boolean flag “WiFi_Connect_On_Demand” that is passed to each of the WiFi sensitive functions.
If WiFi_Connect_On_Demand is true, the function will automatically connect and disconnect the network as it is required. If false, the functions will assume that the Wifi is permanently connected.
Should you wish to run the system with the WiFi permanently connected (E.g. if you also have a remote control function running that requires a continual connection) then you should set the flag “WiFi_Connect_On_Demand_Global” to false in the WiFi start up parameters at the start of the sketch.
The current demo application calls the routine only on demand
The current demo application program, the power calculation is only called on demand by the keyboard, for the kilowatt hour calculation to be accurate, the power calculation needs to be called periodically (e.g every minute) otherwise the integration time between measurements will not be adequate.
Step 10: Calibration of the Power Monitoring Channel
So, you have compiled the sketch after loading in all of the required configuration parameters but when you run the Read_CT_And_Calculate_Current_And_Power() function, you get incorrect readings for current and power!
Assuming that your load is within the range that you have calculated for your CT shunt resistor there are two possible reasons for such an error
A. You have not set the LineVoltage parameter to the correct value for your mains supply or more likely the calibration parameter CT_Scalar_Coefficient is not correct for the CT configuration that you are using.
This needs setting to an appropriate value for your set up and the only way that we can really do this is by either comparing the sketch calculated value under measurement conditions with another power or current monitoring unit that you conveniently have or by calibrating with a know electrical load - preferably a resistive one so that we do not introduce reactive or inductive losses. Acceptable test loads could be several incandescent lamps, a kettle, iron.
B. The "must have" is a knowledge of what the load actually is in terms of amps and/or power consumption in Watts. The best method is certainly to be able to used a reference measurement device. An AC clamp meter is ideal for measuring the current - the "clamp" part of the meter is actually a CT and you simply clamp it around the live power feed to your load. The domestic power meters available on the market also use a CT device separate to the display device in the same way that we are using ours. Last but not least you can also get socket power monitors that plug into your wall socket and you plug the load into a socket that is integral to the monitor.
Any of these devices allows you to test a range of test loads and you can directly compare the sketch reading with the test meter to obtain the the two readings necessary to check the calibration and then correct it. (Switch the load on and take a reading by pressing the "p" key followed by the "Enter" key.
We need the "sketch reading" and the "correct reading" from the test meter (Amps or Watts) for a range of variable loads preferably at the low end and at the high end E.g. 200W and 2000W.
If you are not using a test meter but simply relying on the stated load (E.g 2x100W lamps, 2000 heater etc) then the "correct reading" will simply be the known load.
The link between the correct scaling factor(CSF), the present scaling factor (32.4), the "sketch reading" and the correct reading is given by:
(CSF/32.4) = (sketch reading) / correct reading) (same equation with the current or power readings)
This gives us CSF = (sketch reading x 32.4) / (correct reading)
If possible, do this several times with different loads (without changing the sketch coefficient) and take the average of the calculated CSF and then replace the current value of 32.4 in the sketch with your calculated one.
Repeat the test and check that the readings with the new coefficient are satisfactory
If you start with negative readings from the sketch then either increase the test load and/or change the CT_Scalar_Coefficient to an arbitrary value until you obtain a positive measurement reading.
It is clear that you are dealing with dangerous mains voltages that can be fatal if not handled properly. The CT transformers used in both the sketch and the test equipment if used do not connect directly to the mains supply. It is sufficient to clamp the measuring device or CT around either the single live or neutral wire of the mains circuit (not both!) however even this act may bring you into close proximity with exposed live terminals.
TAKE CARE!! if you are not sure what you are doing, seek help from a more qualified person.
Step 11: Downloadable Files and URL Links ....
This section points you to additional resources to help you build this project.
The file "Datasheets.zip" gives you data sheets for:
- DHT11 and DHT22 temperature & humidity sensor
- SCT013 30/1V Current transformer
- SR501 PIR movement detector
Other files include:
- "Formatted_ESP_12_Toolbox_sketch.zip" - this is the actual sketch file as a pdf that I have formatted to quickly and easily highlight in colours, the fields that you need to change to adapt the sketch to your situation plus I have formatted the functions to help reading and hopefully understanding.
- "ESP_12_Toolbox_sketch_V1.4.zip" - the actual Arduino IDE sketch including the gsender.cpp and g.sender.h files. Unzip these 3 files and put them into a subdirectory "ESP_12_Toolbox_1V1" from your normal Arduino sketch directory
a) You MUST put your own email login details into the file GSENDER.h otherwise the email function will not work.
b) You MUST derive your own Thinkspeak APIs otherwise the Thingspeak upload will not work
- "Instructable_ESP-12_Toolbox_Project_Documentation.pdf" - this is essentially this complete instructable in pdf format allowing you to view the instructions off line
As well as a lot of experimentation, the key to any successful build is ... research. It is great to be able to do everything from scratch but today we live in a world where "open source" grants us access to so much information we can pick and chose when go for originality or let someone else do some of the ground work.
The instructables.com site alone is a wealth of information on all sorts of interesting topics and I list just a few here that helped me towards this instructable. I included them as acknowledgment to just some of the enablers of my work and this project is not meant to be the "final article" but more to be an enabler for other makers.
For encoding your login information for the email sending function - https://www.base64encode.org/