So your touch sensor is not working?

sensorWe have all experienced it, you buy something at Aliexpress. It arrives and you confirm receipt before you have time to test everything and then when you finally get around to that… there is a problem.
That happened to me with a TTP223B capacitive touch sensor. Whatever I tried, the output remained low. Slightly frustrated I was looking at the rather simple board and thought that there really couldn’t be much wrong with it.
ttp223-icFound a datasheet of the TTP223B ic that is on this module and started measuring. Well to make a long story short, the input pin (pin 3) seemed to have no connection with the sensorplate. When I would just touch the input pin, it switched very well. According to an application note in the datasheet capacitor C1 should be between  the input and  the ground and as it should be connected it also should be connected to the  sensorplate, which in fact it was. Turns out pin 3 was not connected to anything. A small wire that I soldered between the top of C1 and  pin 3 remedied everything and after that the sensor worked wonder well.
On checking the feedback of people who ordered this sensor, I noticed many experienced the same problem. No doubt the manufacturer (not perse the seller) must have known about this.

ttp233

Update two channels (different API’s) in Thingspeak

Uploading to two different channels in Thingspeak is fairly easy and can be done with the code below.
The code does close connection in between the uploads, perhaps that isnt necessary but I had some trouble getting it to work without closing the connection,not saying it cant be done

void  sendDataToThingspeak(void)
{

// make TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(thingspeakServer, httpPort)) {
    return;
  }

  String url = "/update?key=";
  url += writeAPIKey;
  url += "&field1=";
  url += String(humidity);//
  url += "&field2=";
  url += String(humiditySetPoint );//
  url += "&field3=";
  url += String(humidifier);
  url += "&field4=";
  url += String(autoMode); //
  url += "&field5=";
  url += String(t);
  url += "\r\n";

  // Send request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
               
  // Second channel            

//-------- Make new connection
 if (!client.connect(thingspeakServer, httpPort)) {
    return;
  }
  url = "/update?key=";
  url += writeAPIKey2;
  url += "&field1=";
  url += String(value1);// 
  url += "&field2=";
  url += String(value2 );// 
  url += "\r\n";
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
 Serial.println("Thingspeak");
}

Connect ESP8266 with Thingspeak through LUA: Analog pin and Internal ReferenceVoltage

esp8266-thingspeakluaConnecting your ESP to Thingspeak with a program written in your Arduino IDE is quite easy and those programs come a dime a dozen.
However, when I went to look for a program that did the same in LUA I came a cross a number of programs that simply didn’t work.
So I had to give it a go myself.
The below program is more or less a skeleton for thingspeak connection. It reads two values and posts those on Thingspeak. As it was just for testing I didnt want to add a lot of sensors, so th eonly two values read are the Internal reference voltage and the analog value from ADC0.
To make the program easily adaptable, I readthe sensors in a seperate function.
If you want to add a variable resistor to test the ADC, mind you that it can only take 1 Volt input so you need a voltage divider that limits it to 1 volt instead of 3.3 Volt.
When using the program dont forget your network credentials and  Thingspeak API Key

WRITEKEY="T3I6T9YF67JE527" -- set your thingspeak.com key
wifi.setmode(wifi.STATION)
wifi.sta.config("YourSSID","YourPW")
wifi.sta.connect()
tmr.delay(1000000)
volt=0 --Internal reference voltage
ana=0 -- analog port A0 Mind you, this one has a 1 Volt max

--read sensor
function ReadSensor()
volt = node.readvdd33()
ana=adc.read(0) -- 1V=1023
print("Internal Ref.Voltage: " ..(volt/1000).."."..(volt%1000).." Volt")
print("Analoog: "..ana)
end 

-- send to https://api.thingspeak.com 
function sendTS() 
conn = nil
conn = net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)success = true print(payload)end)
conn:on("connection",
   function(conn, payload)
   print("Connected")
   conn:send('GET /update?key='..WRITEKEY..'&field1='..(volt/1000)..'.'..(volt%1000)..'&field2='..ana..'HTTP/1.1\r\n\
   Host: api.thingspeak.com\r\nAccept: */*\r\nUser-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n\r\n')end)
conn:on("disconnection", function(conn, payload) print('Disconnected') end)
conn:connect(80,'184.106.153.149')
end

ReadSensor()
sendTS()
tmr.alarm(1,6000,1,function()ReadSensor()sendTS()end)

Now I haven’t been completely honest here, as it isnt really good practice to read the internal Voltage and the A0 port as it reads either the one or the other.
When using the  A0 to read internal voltage  in the Arduino IDE rather than in LUA ADC_MODE(ADC_VCC); in combination with ESP.getVcc() is now the correct way to do it. Using readvdd33 causes problems

A quick introduction to LUA on the ESP8266: create an Accespoint and LAN client to switch a lamp

If you have been using an ESP8266 with the Arduino IDE, you will nevertheless have heard about LUA and you may be curious to try it.

The object of this article is not to teach LUA, but rather to quickly show  how to get started.

Though some ESP8266 modules and boards come with the LUA interpreter installed, once you have flashed programs to your ESP8266 with your Arduino IDE, that interpreter is gone. So, first we may need to reflash LUA interpreter back in the ESP8266 again:

Putting LUA (back) on your ESP8266.

flasherGo to github.com/ nodemcu and choose the nodemcu-flasher. Download and unpack it. Connect your ESP8266 to your 3v3 USB TTL converter. Go to the Win32/Release folder and start the ESP8266Flasher.exe. Set your ESP8266 in flash mode in the way that is suitable for the board you are using.

Select the proper com port and click ‘Flash’. When the program is done it will return 2 MAC addresses: one for an Accespoint and the other one or a ‘station’.

Close the flasher and reset the ESP8266.

The ESP8266 is now ready for LUA programming.

Uploading LUA Programs

In order to upload a program to your LUA interpreter/ESP8266, there are several programs. I am using ESPlorer. Download and unpack that program and start it with ‘Esplorer.bat’ .

Presuming your ESP8266 is still connected to your computer, choose the proper Com port and baudrate in the right side pane of the program and click connect. The esp8266 will now likely reprt itself and come back with the message: “no init.lua”.

The ‘init.lua’ file is the file that is executed on boot. If we want our program to start on boot, that is the name we will give it.

As it is not my intention to teach LUA here, we will use an existing program: Go back to the Nodemcu github and choose “nodemcu-firmware”. Then clicl ‘lua-examples’, choose ‘webap_toggle_pin.lua, then  click RAW. Copy the code and go back to the ESPlorer program. Choose the ‘Nodemcu/Micropython’ tab and the Scripts tab and paste the copied program in the leftpane of the ESPlorer program.

Save the program as ‘init.lua’  and then upload it to the ESP (under the File tab).

Once the program is uploaded, reset the ESP8266.

As the program configures an Accespoint, go to the wireless connections on your computer. You should see an accesspoint there called ‘test’ log on to that one. When it asks for a password provide ‘ 12345678’. Once you are logged on, go to ip 192.168.4.1. You should be presented with a webpage that allows you to toggle a pin.

Now that may be handy, as te esp8266 is not connected to the internet it can only be accessed from a limited distance. But what if you want to switch a lamp from the other sidof the world? Well i will show you how to change the accespoint created in an accesspoint and LAN client so you can log into it either directly, or via your router.

You need to configure the first 2 lines as follows:

esplorer8266The firstline is changed into ‘wifi.STATIONAP’ this configures the ESP8266 both as an AP and a LAN client. The next line that configures the AP is left untouched, but the LAN still needs to be configured wih ssid and password as shown in the picture. Upload the altered program to the ESP and reset it. The ESP is now both a direct Accesspoint as well as connected to the internet via your router.

gpioOne more remark: the gpio pins of the ESP8266 are not directly translated to the numbers of the ‘pins’  in the program. If you are not using a Wemos D1 or NodeMCU, but rather an ESP8266-01 and you ant to switch GPIO2, in the program you need to state ‘pin4’

 

Solarpower for ESP8266

wemospsuNeeded a solar powersupply for an ESP8266-01. As the ESP8266-01 needs 3.3 Volt, a LiPo cell seemed a good choice for a battery. However, fully loaded these give 4.2 Volt, which is too much for the ESP8266. In order to get to 3.3Volt a Lowdrop (LDO) regulator is necessary.

As the ESP8266 does require a hefty current when it is transmitting, the regulator needs to give some 500mA.

Possibilities are the SPX3819 (500mA, dropvoltage 340mV, maxinput 20V) (found on the Lolin NodeMCU-ESP12E) and the AP2112 (600mA, dropvoltage 250mV, maxinput 6V) ( found on the Adafruit Huzzah). As the maxinput will be 4.2Volt, I have chosen the AP2112. The HT7333, that is recommended for e.g. the backside of the ESP8266-12 adapter plate has a drop voltage of 100mV. However, that is measured at 40mA and the datasheet gives no info on the dropvoltage at higher currents, so I would steer clear of that one for battery power.
Other possible options are the RT9013 (That is for instance found on the Wemos D1 mini) and the XC6203

The LiPo battery is being charged by a small TP4056 module. These have a maxinput of 8 Volt, hence a 6 Volt solarpanel will do nicely.

Capacity of the LiPo and the Solarpanel depend on the current needed. If you put the esp8266 to sleep in between transmission it can last long on a battery, especially if it is charged throughout the day.

BruteForce code finding in an RGB Infrared LEDstrip

irrgbledNeed:

  • Arduino.
  • IR Infrared RGB lightstrip
  • IR LED 940nm
  • resistor 560ohm

If you have one of those RGB LED strips that come with those standard 24 or 44 key transmitters and you need the IRcodes so you can send them from an Arduino to control your lightstrip, it is easy to use one of the IR libraries, such as that of Ken Shirrif and use the receive sketch to sniff the codes from the receiver. But what if you lost your transmitter or for some reason the receive sketch doesnt recognize it. Well, then there is another possibiliuty: BruteForce

As I understood these IR units usually work with the NEC protocol. I will not bore you with the sync bits and timing and the stopbits as we have the library to take care of that. The essence of the NEC protocol is a 32 bit pulse-train, in which the first byte (8bits) is the address, the second byte is the inverse address, the 3rd byte is the command and the 4th byte the inverse command. With inverse I mean that in binary form all the 1’s and 0’s are switched. So if a specific command would be “10101011” then the inverse is “01010100”. In the mean time I had come across an instructable (but cant find it anymore) of someone who wrote a program to generate codes for his IR controlled lamp). He generated his own 38kHz signal, something I didnt want to do, but it gave me the idea to not sniff my transmitter, but to scan the ledstrip bij sending possible codes to it. Now 32 bits seems like a lot of possible codes but it isnt. Remember how the NEC protocol was build: 1 address byte and 1 control byte. As I had come to understand the address byte didnt really matter (it does though), at most I would have to send 256 codes and single out the 24 (and hopefully more)

/* ********************************
This code quickly checks what codes will work with an IR RGB LEDstrip.
Adapt the delay for a quick scan or for precise jot down of the  code and its effect
02 november 2016
by DIY_bloke
********************************/ 

unsigned long command = 0;
#include  //Ken Shirriff's IRremote.h
IRsend irsend;

byte  al, ar, cl, cr;// the address and command byte and their inverse
unsigned int a, c;// the complete address and command byte
unsigned long totaal = 0L;// the 32 byte long to send to plug into the NEC protocol

void setup() {
  Serial.begin(9600);
  Serial.println("Arduino Ready");
}

void loop() {
  for (al = 0; al < 255; al++)   //we start with address 0
  {
Serial.println(al);
    for (cl = 0x0; cl < 255; cl++) // and with command 0. We first loop through the commands     {       doen(al, cl);        totaal = combineint(c, a);        Serial.print("Address> ");
       Serial.print(al,DEC);
       Serial.print(" Command> ");
       Serial.print(cl,DEC);
       Serial.print("> ");
       //Serial.print(c);
       Serial.print(" Total ");
       Serial.println(totaal,HEX);

      irsend.sendNEC(totaal, 32);
      delay(100); // Optional
    }
  }
}
//makes a long from two integers
unsigned long combineint (unsigned int rechts, unsigned long links)
{
  unsigned long value2 = 0L;
  value2 = links << 16;
  value2 = value2 | (rechts);
  return value2;
}
unsigned int doen(byte ag, byte cg)
{
  ar = ag ^ 0xFF;
  cr = cg ^ 0xFF;
  a = 256 * ag + ar;
  c = cg << 8 | cr;
}

int Combine(byte b1, byte b2)
{
  int combined = b1 << 8 | b2;
  return combined;
}

The program is fairly simple. It defines byte variables for the address and the command It inverts the address and the command so then there are 4 bytes.

It first combines the address bytes and the command bytes each to 1 integer and then it combines the address integer and the command integer to a long variable. Actually this proved to be the hardest part as I encountered some wrong values as I overlooked some variables that needed to be unsigned (Thanks Yoh there for putting me on track again).

Once those 4 bytes are a 32 bit Long, that is fed into the NEC protocol of the IRremote library. The address loops from 0 to 255 and once that is done the address byte increases with 1 and it starts allover again, so there are 256² =65536 possibilities to go through to find 24 codes.

Now obviously that would be a worst case scenario. But even then that can be rather quick. So once you have attached an IR LED to pin 3 (either through a resistor or a decent driver) power up your RGB strip (bij plugging it in the grid) and use your remote to switch it ON. The program will eventually find the ON code, but it would be a pity if that was the last code because then you have missed the activity of the LED strip. There is a delay in the code that you begin to set for 50msec. then start the code. The program then starts going through all commands and address possibilities. Now suppose the 24 codes would all be huddled together in the last 25 spaces of the 65536 possibilities. then it would take you 65512 *50msec= 55min to get to your codes.

That may seem long, but you dont have to do watch. The only thing you need to do is once you see your RGB ledstrip change color, check the serial monitor to see what address range you are at. Then stop the program, change the outer (address) loop to start from that address and set the delay to say 1 second and then note what code causes what effect. Now maybe you are 1 or 2 positions off, but if you know just whereabout it is just try sending the ones around it. I was lucky, ALL my codes where on address page 1 and then it took me about 5 minutes to find them all.

Also, remember that when the IR LED on your arduino is spitting out codes every 50ms your remote wont be able to do much anymore, so dont be surprised if it suddenly seems to ‘not work’ anymore. Cover the IR LED on the arduino and you will see your remote come alive again

Just one remark on IR LED’s
In Ken’s library discussion, he uses a 1 k resistor to directly drive an IR LED from pin 3 of the Arduino. That is definitely possible. However, it will not reach far. IR LEDś can easily be fed with 100mA as they only get small pulses. Obviously an arduino pin is not suitable for that.
a simple transistor driver for 5 Volt, with a series resistor of 33 ohm will usually do nicely. Be sure to check it for your specific situation.

ESP8266 with webserver-MQTT-Emoncms-Thingspeak-OTA

The graph shows that  when in automode, the humidifier is switched on when the  humidity  goes  2 degrees (the hysteresis) under the Setpoint
The graph shows that when in automode, the humidifier is switched on when the humidity goes 2 degrees (the hysteresis) under the Setpoint

On Github, Krzysztof has published a truly excellent series of articles regarding the use of an ESP8266 that reads a humidity sensor and publishes the data on a personal webserver, as well as on emoncms (an energymonitoring cloud) and allows to  take action depending on the reading of the  sensor, either manually or automatically and to do that via a webserver, or via MQTT or OpenHAB.
Anyone who is interested in this subject should surely read his  set of articles that starts basically from scratch and keeps adding functionality.

As I am not really partial to emoncms, but more of a Thingspeak user, I decided to add a Thingspeak module to his program.
As a base I used this program.
To add Thingspeak functionality do the following:
under the section: Emoncms configuration add:

//
// Thingspeak configuration
//
const char* thingspeakServer = "api.thingspeak.com";
const char* writeAPIKey = "yourThingspeakWriteApi";
// function prototypes required by Arduino IDE 1.6.7
void  sendDataToThingspeak(void);

in the main loop (thus in void loop(void) )
above (or below) sendDataToEmoncms();
add: sendDataToThingspeak();

Add a tab called “Thingspeak” and add there the following:

void  sendDataToThingspeak(void)
{
// make TCP connections
WiFiClient client;//this one is probably not necessary
const int httpPort = 80;
if (!client.connect(thingspeakServer, httpPort)) {
return;
}

String url = "/update?key=";
url += writeAPIKey;
url += "&field1=";
url += String(humidity);
url += "&field2=";
url += String(humiditySetPoint );
url += "&field3=";
url += String(humidifier);
url += "&field4=";
url += String(autoMode);

url += "\r\n";

// Send request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + thingspeakServer + "\r\n" +
"Connection: close\r\n\r\n");
}

Ofcourse one still needs to setup a Thingspeak account, but that is well known how I presume. One also needs to setup an Emoncms account, buthat is well described in the series of articles, or one can decide to delete that functionality.
For MQTT I have used a public broker, but one can decide to set it up on say a Raspberry Pi