Simple WiFi relay board (3): A 1 relay Chinese Website module


In an earlier post, I discussed how to quickly  make  a one channel WiFi relay with a relay module an ESP8266-01 and some Dupont cables.
In a later post, I showed how to make a 4 channel WiFi relay with an ESP8266-01 and a 4 channel relay board.

Both posts were a consequence of 2 videos by Ralph Bacon, discussing his slightly disappointing adventures with 2 commercially available Wifi relay boards, based on an ESP8266-01.
Out of interest I bought one of those boards -knowing the shortcomings Ralph pointed out- that I presumed I could fix.

The board comes with an ESP8266-01s. It has a Reset button, which isn’t really useful. The GPIO0 drives the relay through a 7002 FET, GPIO2 drives an LED and TX and Rx are not connected to anything.

The crux of this board is that it is really designed for the ESP8266-01S, although it can be made to work with the regular ESP8266-01. The ESP8266-01S is a version that already has pull-ups on GPIO0 and GPIO2, albeit that one of those pullups is through an onboard  LED. The regular ESP8266-01 does not have these pull ups and the relay board  does not provide them.

The relay module uses only one pin, GPIO0. It is connected to the gate of a 2007 FET that switches the relay and that is exactly where the problem starts. During startup, the ESP needs GPIO0 to be HIGH, unless you want to go to flash mode, when it needs to be LOW.
But as the ESP8266-01S correctly pulls pin GPIO0 HIGH, the relay will immediately be activated at startup. Hence he designer added a pull down resistor. Due to the presence of the Pull up on GPIO0 on the ESP8266-01 board, that needed to be a very strong pull down resistor and a 2k resistor was chosen. But now the GPIO0 pin is pulled LOW at startup, putting it in flash mode.

There are some simple solutions for this:

  • remove the 2k resistor. However this will activate the relay at start up.
  • reroute the triggersignal to  come from pin GPIO1 (Tx) or GPIO3 (Rx) (but you still need to remove the 2k resistor)

The latter solution is fairly simpel because of the long PCB trace going from GPIO0 to the gate of the FET

 

 

Advertisement

Simple WiFi relay board (2): A 4 channel DIY WiFi relay board with ESP8266-01

Driving a 4 channel relay board with ESP8266-01 through MQTT or Webserver


In a previous post I discussed making a WiFi relay inspired by the trouble  Ralph Bacon had with a single relayboard from Aliexpress. Given the fact that the Sonoff SV is relatively cheap (don’t forget the shipping cost though), and the WiFi relay at AliExpress even cheaper, it is a nickle and dime question whether it is wise to DIY such a project yourself. However, if you already have an unused ESP8266-01 and a relay lying around, basically all you need are some DuPont cables to connect the two (as shown in my previous post).

It becomes more interesting to use all 4 pins of an idle lying ESP8266-01 and add a 4 channel relay board.
The ESP8266-01 however is a bit particular with the pins it has,as two of the 4 I/O pins are the pins that need to be pulled HIGH on startup whereas the remaining two pins are the UART. Those UART pins can be used as GPIO, but the problem is that they do not know that, they need to be told that they are no longer UART but in fact GPIO. We do that with a special pinMode command (more about that later).

The relayboard I had in mind is a bit peculiar. I discussed the full workings of this board in an earlier post.

For now however suffice to say the inputs need an active LOW to  close the relays, while in rest, the inputs are HIGH.
That is in fact quite handy when using an ESP8266-01, as two of the 4 pins, GPIO0 and GPIO2, need to be pulled high on start-up, something this circuit actually does. It is necessary though to feed the board, including the optocoupler with 5Volt. The connections between the ESP8266-01 and the relay board are made as follows:

If you are using a different relay board that does not have it’s inputs pulled high in rest and you are using the ‘old’ ESP8266 module, then you need to add 10k pull-ups on GPIO 0 and GPIO2. Not necessary if you are using the ESP8266-01S.

A reminder: the relayboard needs 5Volt and the ESP-01 needs 3.3Volt.  You could use an LDO like the AMS1117 3.3 to drop the 5Volt to 3.3 however,do not connect the two Vcc’s directly. Wait, let me emphasize that: DO NOT CONNECT THE Vcc OF THE ESP TO THE VCC OF THE RELAY BORD, JUST DONT!!!!

The full board
The ESP8266-01 adapter board

Finally, put it in a nice enclosure

4 Channel relay housing
4 Channel relay housing

Software

MQTT
For theMQTT  program I followed the structure that is used by computourist with regard to the use of MQTT messages.
The idea behind that is that commands going from MQTT broker to the node are called ‘southbound’  (‘sb’), while the ones going to the broker (so usually the ‘ state’) are called ‘northbound’ (‘nb’). (with ‘southbound being a command and northbound being the status). The specific functions in the node are addressed as numbered devices.
This has advantages and disadvantages. The disadvantage being that you get codes like: “home/sb/node01/dev17” rather than something like: “home/cmd/wifirelay/relay1“.
Also the handling of the incoming MQTT is bound to a specified length, so altering it needs to be done with some consideration.
The advantages are that the handling of the code is easier and in fact extending the code with more functions is fairly easy.
What happens in fact is that once a subscribed MQTT code comes in, it is stripped to a its last two digits. These digits define the function it fulfills.
The Payload can be “ON”, “OFF”, “READ”, or a number, depending on the function chosen. The “READ”  payload reads and returns the state of the specific function (‘device’)  that is being read. Some ‘devices’ -as for instance the IP number or the MAC address, can only be read and not ‘set’.

The full list of devices is as follows:
00 uptime: read uptime in minutes
01 interval: read/set transmission interval for push messages
02 RSSI: read WiFi signal strength
03 version: read software version
05 ACK: read/set acknowledge message after a ‘set’ request

10 IP: Read IP address
11 SSID: Read SSID
12 PW: Read Password

16 read/set relay1 output
17 read set relay2 output
18 read set relay3 output
19 read set relay4 output

92 error: tx only: device not supported
91 error: tx only: syntax error
99 wakeup: tx only: first message sent on node startup

As I mentioned earlier, the UART pins need to be told that they should behave like GPIO pins. That can be done with the statement:
pinMode(1,FUNCTION_3);
pinMode(3,FUNCTION_3);

However, this will not work when there are any hardware serial statements left (such as Serial.print, Serial.begin).

Also, the device will not boot if you happen to pull pin 1 (Tx) down.
So in order to control the relays from e.g. OpenHAB, this is what you add to your itemsfile:

Switch rel1 "WiFi relay 1 [%s]" (GF_Corridor) { mqtt="[mosquitto:home/sb/node01/dev17:command:*:default]" }
Switch rel2 "WiFi relay 2 [%s]" (GF_Corridor) { mqtt="[mosquitto:home/sb/node01/dev18:command:*:default]" }
Switch rel3 "WiFi relay 3 [%s]" (GF_Corridor) { mqtt="[mosquitto:home/sb/node01/dev19:command:*:default]" }
Switch rel4 "WiFi relay 4 [%s]" (GF_Corridor) { mqtt="[mosquitto:home/sb/node01/dev16:command:*:default]" }

this will render the following menu:

The program can be downloaded here. FYI, I trimmed down an existing, bigger program of mine. I left a bit of code here and there that might not be of immediate use in this project, but may come in handy if you want to use the code on a Wemos.

WebServer

If you do not want to use MQTT, then a webserver might be what you are looking for. I adapted a program from Rui Santos (Original can be found here). to be suitable for use on an ESP8266-01.

Another possibility is to put Tasmota on it, or control it via Firebase.

Cost:

  • relayboard 1.80 euro
  • ESP8266-01 1.45 euro
  • 5 and 3.3Volt module 0.40ct

Simple WiFi relay board (1): an overview of two popular modules on Chinese Websites

In his video nr 107 youtuber Ralph Bacon describes his ‘frustration’ with an ESP8266-01 based wireless relay he got from AliExpress.

Wifi relay with ESP8266-01 and STC15F104 microprocessor

His frustration is understandable as that particular module is needlessly complicated. It seems the ESP8266-01 is mainly there to make the WiFi connection, while the relay is triggered by yet another microprocessor, the STC15F104. Communication between the two is via the serial port of the ESP8266, as if the designers thought, how can we make this in the dumbest way possible.
If you want to use this relay, this is how to do it:

Set the serialport to 9600 with : Serial.begin(9600);

To enable the Relay send the proper command bytes to serial port:

const byte ReBufferON[] = {0xA0, 0x01, 0x01, 0xA2};
Serial.write(ReBufferON, sizeof(ReBufferON));

To disable the Relay send the following bytes to the serial port:
const byte reBufferOFF[] = {0xA0, 0x01, 0x00, 0xA1};
Serial.write(ReBufferON, sizeof(ReBufferOFF));

Apparently it will also work with AT commands.

The circuit looks like this

###

An even simpler board

The ‘simple’ relay board

In his follow up video # 110  Ralph describes another, simpler relay board (pictured), that also frustrated him as the manufacturer apparently had not included the necessary pull-up resistors on the Chip Enable and on GPIO0 and GPIO2. (Edit: this turned out not to be entirely true as the board comes with an ESP8266-01S that has the necessary pullups on board)

Both videos came in my focus again, when i discussed the ‘simpler’ board with a diy mate and frequent commenter. It is very cheap to buy and once you add the resistors (to make it start up correctly) factually you have a Sonoff SV.
Ofcourse the Sonoff SV is less than 5 Euro (plus shipping), as opposed to the ‘brandless’ relay board only costing some 2.60 euro, so you might as well get the real thing, but it opens some interesting perspectives, especially as I had most of the stuff laying around namely an ESP8266-01 a relay module and a 3.3Volt power module, all fairly cheap. Just a couple of DuPont cables to connect the three, and it should be fine. I know it is all nickles & dimes stuff but lets do a quick calculation.

Total 2.08 euro as opposed to 2.62 euro (in a nicer package), so not really cost effective to ‘DIY’  but if you have the stuff laying around, better to use it than for it gather dust. It also allows you to choose another pin than GPIO2 to drive the relay.
Ralph also offers a program to replace the existing firmware in the ESP8266, as well as a phone app (all found in the description of his video). Ofcourse it is also possible to replace the firmware with MQTT responsive firmware. For that you could e.g. use my Sonoff Touch program, albeit that in line 17, you have to change “TouchLED=12;”  to “TouchLED=2;

But why stop there? the ESP8266-01 has 4 I/O pins, if we ad a small 220->5V power module and a 4 channel relay board, we could make a sonoff 4ch. These cost about 22 Euro. So that would be more rewarding to build.
That however will be for part 2.

Flashing Sonoff Touch – No soldering

Although it is not really a big thing to solder an angled header in a SonOff Touch in order to reprogram it, one also has to solder a wire to the GPIO-0 pin of the ESP8285 chip as the SonOff Touch has no button that can be used to get it into flash mode.
I therefore wondered if it wouldn’t be possible to flash the Sonoff Touch without any soldering. Spoiler: yes it is possible, but you need some dexterity.
First open the Sonoff Touch. This is easiest done with cautiously prying a screwdriver on between the casing and the frontplate at the side.
once that is done you can see a small board that you can just pull-out.
On that board there are 4 in line holes that we need to connect an FTDI programmer to. On the bottom side of the board is also a 2×2 male header. That is the one that we just pulled out of its header in the housing. We are going to need that header a bit later as well.

indicated  the function of the 1×4 header in the image. You are going to need an FTDI to USB module  THAT YOU CAN SET TO 3.3 VOLT. You also will need a 1×4  straight pinheader and 4 female to female DuPont wires.
Now make the following connection between the 1×4 male header and the FTDI to USB connector:

header FTDI module
Ground Ground
Tx Rx
Rx Tx
Vcc Vcc

To make clear, if it already wasn’t, this is a connection to a loose, 4 pin male header.
The next thing you need is a female to male DuPont cable. Connect the female end to the ground connection on the 2×2 header.

Also, you need to identify GPIO0 on the ESP8285 chip:

 

For the final flashing you need a bit of dexterity but this is what you do:

  • Have your Arduino IDE available with the  required program loaded.
  • Under tools-boards choose the generic 8285 module
  • Flash size 1 Mbyte 16k SPIFFS
  • Make sure the FTDI module is not connected to the USB port of your computer.
  • Now press the 4 pin male header that is connected to your FTDI module in the proper holes. Make sure it is the right way around, so Ground connects to ground, Vcc to Vcc, Rx to Tx and Tx to Rx. If there is a bit of slack between the header and the holes. push against the pins with  the mouse of yr thumb or with your little finger, so it makes  poper connection.
  • Now take the male pin of the DuPont cable that you connected to the ground on the 2×2 pin header and push it against GPIO 0.
    Keep it in place with your thumb.
  • You still should have one hand free. Use that to push the FTDI module in the USB connection of your computer.
  • Once that is done, you can let go of the male pin pressed against GPIO0
  • In the IDE chose the right port and press ‘upload’.

That’s it.

So, what program should you upload to make the Sonof Touch work?
Of course there is Tasmota and many people are very happy with it. Truthfully, I found it cumbersome and couldn’t even compile it. Considering all we need to do is switch 1 pin, it shouldn’t be so hard to write something simple.
Given the fact that the Sonoff Touch will most likely disappear in the wall and you don’t want to have to take it out and flash it again, two things come in very handy in the program:

  • OTA (Over The Air) flashing
  • WiFiManager

The code also gives MQTT feedback about the

  • MAC
  • IP
  • Filename
  • SignalStrength

It can be downloaded here

Reading the DHT11 or DHT22 on the Raspberry via an overlay and send it to the openHab REST API

In an earlier tutorial I showed how to read the popular DHTxx sensor on a Raspberry Pi and then to MQTT that into Openhab.
However, there are more ways to skin a cat, so what I like to do this time is:

1) Read the sensor with a device tree overlay on a Raspi and then
2) Send the data to OpenHab with the REST-API

I am not saying one method is better than the other, but suppose you dont want to install an MQTT server because all your other channels don’t need MQTT, then the REST API comes in handy.

1) Reading the DHT sensor
First we need to load the dht11 overlay at boot-up
Do
sudo nano /boot/config.txt
and add:

dtoverlay=dht11,gpiopin=4

obviously one can pick another pin here, or declare a different sensor such as the DHT22 or DHT21 (AM2301)

then all you have to do is to read the following 2 files:

/sys/devices/platform/dht11@0/iio:device0/in_temp_input
/sys/devices/platform/dht11@0/iio:device0/in_humidityrelative_input

Once you have loaded the overlay and connected your sensor, a simple:
cat /sys/devices/platform/dht11@0/iio:device0/in_temp_input,
would show you the temperature.
whereas:
cat /sys/devices/platform/dht11@0/iio:device0/in_humidityrelative_input, would show you the humidity

Upon doing that in a python program, I noticed there can be quite a number of I/O errors. This seems to be a frequent problem with this overlay, so in order not to interrupt the program, I had to do a bit of Error catching.

2) Sending values to OpenHab
The REST API is fairly simple to use. We only need 1 line for every Item we want to update. Such a line looks like this:
requests.put('http://192.168.xxx.yyy:800/rest/items/<YOUR ITEM>/state',value).
The ‘value’-variable needs to be a string.

3) Wrapping it up
A simple Python program would look like so:

import time
import requests
tfile='/sys/devices/platform/dht11@0/iio:device0/in_temp_input'
hfile='/sys/devices/platform/dht11@0/iio:device0/in_humidityrelative_input'

def read_temp_raw():
   f=open(tfile,'r')
   lines=float(f.read())/1000.0
   f.close()
   return lines

def read_humidity_raw():
   b=open(hfile,'r')
   hlines=float(b.read())/1000
   b.close()
   return hlines

while True:
   try:
     T=str(read_temp_raw())
     print(T)
     H=str(read_humidity_raw())
     print(H)
     time.sleep(2)
     #Put your own IP and Itemnames here,
     requests.put('http://192.168.1.103:8080/rest/items/<ITEMNAME>/state',T)
     requests.put('http://192.168.1.103:8080/rest/items/<ITEMNAME>/state',H)

   except IOError:
      print("I/O error")

Beware that Python programs rely on proper indenting. As this sometimes can be corrupted by publication on a website, I will leave an image of the properly indented program below:

As I am not the world’ s best python coder, I am sure improvements can be made, but at least this code will get you up and running fast.
Since the OpenHAB items are updated through the REST API, they do not need a channel in the itemsfile, that could look as simple as this:

Number HH "REST Humidity [%.0f %%]" <humidity> (Weather)
Number HT "REST temperature [%.1f °C]" <temperature> (Weather)

Controlling a GPIO pin on a remote raspberry

In an earlier post I showed how one could address the raspberry GPIO pins from within OpenHab (or NodeRed for that matter). The only limitation here was that it was on a raspberry that also hosted OpenHAB.

What if you have a RaspberryPi whose pins you want to control from within OpenHab, while openHab is in fact operating from another machine?

In that case  MQTT seems the best option. I wrote a Python program that will do just that.
If you installed Jessie or Stretch, it comes already with Python 2.7 which is quite suitable for this goal.
You will need two libraries:

The lightweight MQTT client Eclipse Paho Mqtt: Here I describe how to install it, but you could also just do:
pip install paho-mqtt

The second one you need to install is the Rpi.GPIO library.
LadyAda gives a good explanation  how to do that, but it basically comes down to issuing the command:
sudo apt-get install python-dev python-rpi.gpio

The Python program itself is fairly simple, but there are a few things to point out
The Rpi.GPIO library has two modes to set up the pins. it has ‘BCM mode’ and ‘BOARD mode’
These two modes refer to the numbering of the pin.

The GPIO.BOARD option specifies that you are referring to the pins by the number of the pin in the plug – i.e the numbers printed on the board.

The GPIO.BCM option means that you are referring to the pins by the “Broadcom SOC channel” number, these are the numbers after “GPIO” that can be seen in the various pinout diagrams

If you are still a bit puzzled, you can try and issue “the gpio readall” command on your terminal and depending on the type of Raspberry you have, you may get outputs like this for the Rpi3:

or this one for the B+
You will also need to set the IP for your particular MQTT broker and need to change the topic according to your wishes.

The program currently switches one pin ON or OFF. it is not particularly hard to expand that for more than one pin. The working can be controlled by the gpio readall command (check in the column ‘V’ what the state of the pin is)

I saved the program in my home/pi directory. It can be started by
python mqttpublish2.py (or any other name you want to give it). It is best to have it start at boot-up
Output will look like this:
A slight word of warning: Python sees indents as part of the command structure. If after downloading my file you go change it, be careful not to mess up the indents.
Edit: In the mean time I expanded the program a bit, it now sends the state of the pin as a seperate topic. It also sends the IP nr, the program name and an ‘alive’ message on startup. It uses pin 18.

 

Dimming an AC lamp via MQTT

Years ago I published a TRIAC dimmer that could be controlled by a simple microcontroller such as an arduino. Times have changed and right now it is of more importance to be able to control that lamp from a home automation system such as OpenHab, Homematic or NodeRed.

So, let’s have a look at the circuit first:
This is a rather classic circuit. It detects the zerocrossing on the grid and then a microcontroller ignites the TRIAC with a time delay that determines the brightness of the attached Lamp.  The full cycle is 10mS (at 50Hz)
A circuit like this is easy to make for very low cost (1-2 Euro).

However, if you shy away from soldering  such a circuit, there are ready made modules available as well:
You should not need to pay more than 3-4 USD for such a module. Anything above that is robbery

Software to control this dimmer would look something like this:


#include <Ethernet.h>
#include <PubSubClient.h>
#include  <TimerOne.h>

#define CLIENT_ID       "Dimmer"
#define PUBLISH_DELAY   3000

String ip = "";
bool startsend = HIGH;
uint8_t mac[6] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x07};

volatile int i=0;               // Variable to use as a counter volatile as it is in an interrupt
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin1 = 4;// Output to Opto Triac
int dim1 = 0;// Dimming level (0-100)  0 = on, 100 = 0ff

int inc=1;          // counting up or down, 1=up, -1=down
int freqStep = 100; // make this 83 for 60Hz gridfrequency

EthernetClient ethClient;
PubSubClient mqttClient;
long previousMillis;

void zero_cross_detect() {    
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(AC_pin1, LOW);       // turn off TRIAC (and AC)
}                                 

// Turn on the TRIAC at the appropriate time
void dim_check() {                   
  if(zero_cross == true) {              
    if(i>=dim1) {                     
      digitalWrite(AC_pin1, HIGH); // turn on light       
      i=0;  // reset time step counter                         
      zero_cross = false; //reset zero cross detection
    } 
    else {
      i++; // increment time step counter                     
    }                                
  }                                  
} 

void setup() {
  
  attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);
  pinMode(4, OUTPUT);

  // setup serial communication

  Serial.begin(9600);
  while (!Serial) {};
  Serial.println(F("dimmer"));
  Serial.println();

  // setup ethernet communication using DHCP
  if (Ethernet.begin(mac) == 0) {
    Serial.println(F("Unable to configure Ethernet using DHCP"));
    for (;;);
  }

  Serial.println(F("Ethernet configured via DHCP"));
  Serial.print("IP address: ");
  Serial.println(Ethernet.localIP());
  Serial.println();

  ip = String (Ethernet.localIP()[0]);
  ip = ip + ".";
  ip = ip + String (Ethernet.localIP()[1]);
  ip = ip + ".";
  ip = ip + String (Ethernet.localIP()[2]);
  ip = ip + ".";
  ip = ip + String (Ethernet.localIP()[3]);
  //Serial.println(ip);

  // setup mqtt client
  mqttClient.setClient(ethClient);
  mqttClient.setServer( "192.168.1.103", 1883); // <= put here the address of YOUR MQTT server //Serial.println(F("MQTT client configured")); mqttClient.setCallback(callback); Serial.println(); Serial.println(F("Ready to send data")); previousMillis = millis(); mqttClient.publish("home/br/nb/ip", ip.c_str()); } void loop() { // it's time to send new data? if (millis() - previousMillis > PUBLISH_DELAY) {
  sendData();
  previousMillis = millis();

  }

  mqttClient.loop();
  Serial.print("dim1 in loop = ");
  Serial.println(dim1);
}

void sendData() {
  char msgBuffer[20];
  if (mqttClient.connect(CLIENT_ID)) {
    mqttClient.subscribe("home/br/sb");
    if (startsend) {
     
      mqttClient.publish("home/br/nb/ip", ip.c_str());
      startsend = LOW;
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  char msgBuffer[20];
  
   payload[length] = '\0';            // terminate string with '0'
  String strPayload = String((char*)payload);  // convert to string
  Serial.print("strPayload =  ");
  Serial.println(strPayload); //can use this if using longer southbound topics
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");//MQTT_BROKER
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  Serial.println(payload[0]);

dim1=strPayload.toInt();

}

The value freqStep is usually set at 75 or 78 with this type of circuits, which allows for 128 steps of dimming at 50Hz gridfrequency. I have set the value here purposely to 100 allowing for only 100 steps, which is convenient for use in OpenHAB as  the slider goes from 0-100%.
The calculation is as follows:

EDIT 2019 There is a library for the Arduino, the ESP8266 and the ESP32.

50Hz
As we have two zerocrossings per sine wave, the frequency of zerocrossings is 100Hz. Therefore the period between two zerocrossings is 10mSec is 10000uS.
So if you want to have 100 levels of dimming the steps you need to take are 10000/100=100uS

60Hz
The frequency of zerocrossings is 120Hz, therefore the period between two zerocrossings is 8.3mS is 8300uS. So if you want to have 100 levels of dimming, the steps you need to take are 8300/100=83uS -> freqStep=83

 

Controlling Neopixel or RGB LED with Openhab

Controlling Neopixels or RGB LEDs from an ESP8266, controlled by OpenHab is fairly simple. I will present here a working system with a Colorpicker, some predefined buttons and sliders. It will be updateable by OTA and provide some  feedback to openhab on the node parameters

Using a Colorpicker
The sitemap and items file are fairly easy, just using a Colorpicker. I will describe some additions, but the basic files are quite simple

itemsfile

Group All
Color RGBLed "NeoPixel Color" (All)
String RGBLedColor (All) {mqtt=">[mosquitto:OpenHab/RGB:command:*:default]"}

There are 2 items here. One item contains the HSB value, coming from the colorpicker, The other item, that will not be visible on the screen, will contain the calculated RGB code that will be sent out via MQTT.

sitemap file is as follows:

sitemap NeoPixel label="NeoPixel"
{
	Frame label="NeoPixel" {
		Colorpicker item=RGBLed icon="slider"
	}
}

The colorpicker sends an HSB (Hue, Saturation, Brightness) code, but that isnt anything a regular Neopixel LED or regular RGB LED can use, so I set up a rule that triggers on any change of the RGB item to change the HSB code into a regular RGB code. That RGBcode is joined in 1 string called ’ color’. The rule then assigns that ‘color’ string to a new item called “RGBLedColor”

rules file

import org.eclipse.smarthome.core.library.types.DecimalType
import org.eclipse.smarthome.core.library.types.HSBType

rule "Set HSB value of item RGBLed to RGB color value"
when
	Item RGBLed changed
then
	val hsbValue = RGBLed.state as HSBType

	val brightness = hsbValue.brightness.intValue 
	val redValue = ((((hsbValue.red.intValue * 255) / 100) *brightness) /100).toString
	val greenValue = ((((hsbValue.green.intValue * 255) / 100) *brightness) /100).toString
	val blueValue = ((((hsbValue.blue.intValue * 255) / 100) *brightness) /100).toString

	val color = redValue + "," + greenValue + "," + blueValue

	sendCommand( RGBLedColor, color)
end

//part of Neopixel conf files

On the receiving end, there is a Wemos D1 mini that controls a NeoPix strip. The ‘color’ string is split in its separate RGB values. As such it could also be used for an RGB LED or seperate Red, Green, Blue Led’s.
The code is reacting to one MQTT topic, basically switching the entire strip at one go in the desired color and brightness, but I added a structure catching some other MQTT topics that now go to empty routines but that could be used for patterns like a breathing light or a moving pattern. As illustration I added a simple red-blue pattern that responds to MQTT “OpenHab/RGB/scene” with payload “2”  I am using the broker name ‘mosquitto’, if your broker has a different name you needto modify that.

I have to say though that this is not the most efficient way of adding topics, but for beginners it is easiest to follow.
A much more efficient way is to keep the topics of one specified length with only say the last 2 or 3 characters defining the desired action and then only checking for those last characters. A good example of this is for instance in the gateway or sonoff code on https://github.com/computourist/ESP8266-MQTT-client4. For readability sake however, in this example I have chosen to use a more traditional approch and as long as you just want to control some LEDs it is easier.

The ESP8266 code does send some information back: it returns the software version, the IP number and the RSSI.
With regard to the software version and IP number… if you have several ESP8266’s and or Arduino’s in your system, it is easy to lose track which one does what and with what software.

The ESP8266 code is OTA updateable
I have used a fork of the O’Leary PubSub library that makes it easier to send variables as the MQTT payload without having to resort to setting up buffer space and using c_string. Library is here4: https://github.com/Imroy/pubsubclient4.
If you already have the O’Leary PubSub library installed, you will need to put the library files in your sketch folder and change #include <PubSubClient.h> into #include “PubSubClient.h”

Sending predefined colors
If next to the Colorpicker you also want to be able to send predefined colors via a button, then you only need to add some lines in the items and sitemap file:

add to itemsfile:

    Switch NEO_RED	"Red"	<red> {mqtt=">[mosquitto:OpenHab/RGB:command:ON:255,0,0]"}
    Switch NEO_YELLOW	"Yellow"	<yellow>	{mqtt=">[mosquitto:OpenHab/RGB:command:ON:100,96,0]"}
    Switch NEO_BLUE	"Blue"	<darkblue>{mqtt=">[mosquitto:OpenHab/RGB:command:ON:0,0,255]"}

add to the sitemap:

Switch item=NEO_RED mappings=[ON="ON"]
Switch item=NEO_YELLOW mappings=[ON="ON"]
Switch item=NEO_BLUE mappings=[ON="ON"]

As it can be a bit of a bother to find and type all the codes for the colors you may want, I added for download some 160 predefined color settings to pick and add to your sitemap and itemsfile, including some simple icons. As these items already send an R,G,B, code they do not need the rulesfile, only the colorpicker does.

How about Sliders
Perhaps you do not want to use a colorpicker but just individual sliders for Red, Green and Blue.
That is quite easy too.
add the following to your itemsfile:

Dimmer NEO_SLIDERRED "Neopixel Red [%d %%]"  <red> {mqtt=">[mosquitto:OpenHab/RGB/RED:command:*:default]"}
Dimmer NEO_SLIDERGREEN "Neopixel Green [%d %%]" <green> {mqtt=">[mosquitto:OpenHab/RGB/GREEN:command:*:default]"}
Dimmer NEO_SLIDERBLUE "Neopixel Blue [%d %%]" <blue> {mqtt=">[mosquitto:OpenHab/RGB/BLUE:command:*:default]"}

and this to your sitemap

Slider item=NEO_SLIDERRED 
Slider item=NEO_SLIDERGREEN
Slider item=NEO_SLIDERBLUE

Normally that would be enough already, but our ESP8266 program is expecting one input rather than seperate RGB inputs. That is because the colorpicker we used before sends one string of info.
We could add topics to the ESp8266 program to respond to individual RG and B values (and that is what the MQTT topics OpenHab/RGB/RED, OpenHab/RGB/GREEN, and OpenHab/RGB/Blue would be for), but it might be easier to combine those and send as one. For that we need a new rule.

add this to your rules file:

rule "Send  RGB items from slider"
when
Item NEO_SLIDERRED changed or
Item NEO_SLIDERGREEN changed or
Item NEO_SLIDERBLUE changed
then
val redValue=  Math::round(2.55* (NEO_SLIDERRED.state as DecimalType).intValue)
val greenValue=  Math::round(2.55* (NEO_SLIDERGREEN.state as DecimalType).intValue) //
val blueValue=  Math::round(2.55* (NEO_SLIDERBLUE.state as Number).intValue)
val color = redValue + "," + greenValue + "," + blueValue
	sendCommand( RGBLedColor, color)
end

While we are at it
If you want the Filename, IP number and RSSI to show up, add the following to your items file:

Number W_RSSI  "RSSI [%d dbm]" <signal>  {mqtt="<[mosquitto:home/nb/weer/RSSI:state:default]"}
String W_IP "IP [%s]" <network>   {mqtt="<[mosquitto:home/nb/weer/IP:state:default]"}
String W_version "Software versie [%s]" <version>  {mqtt="<[mosquitto:home/nb/weer/version:state:default]"}
String W_MAC "MAC [%s]" <mac> (Wweather) {mqtt="<[mosquitto:home/nb/weer/mac:state:default]"}
Number W_IP_Uptime "Uptime [%d min]" <clock> (Wweather) {mqtt="<[mosquitto:home/nb/weer/uptime:state:default]"}

and the following lines to your sitemap:

   Text item=W_RSSI
   Text item=W_IP
   Text item=W_version
   Text item=W_MAC
   Text item=W_IP_Uptime

download11
https://drive.google.com/open?id=0B9IqgvBSA4aUVzgzRE9MUUY3U2M11

Although I tried on a Wemos D1 mini, I presume this will also work perfectly on the ESP8266-01. Perhaps a great way to use those if you still have on your scrapheap as this is typically a minimal pin project.

The ESP8266 program
The Esp8266 program is rather self explanatory and going into it too deep might fall outside the openhab scope a bit, but in brief, you will find several ino files and a userconfig.h file. These all should be in the same directory and it is sufficient to open the NeopixelOpenhab_vx.ino file in your IDE. The other files will then open up too.

You need to make a few modifications in the userdata.h file.

The essential changes are your password, your SSID and the address of your MQTT server. The other options are indeed ‘optional’, can leave them as is.
the Filename is sent back to openhab as an MQTT message, so in the future you will still know what file it was you put in your ESP8266. obviously you would need to fill out the correct filename.

A handy module to control neopixels from am ESP8266-01 is described here.

OpenHab GPIO Example

I know this might not directly be Arduino or ESP8266 related, but I thought I’d publish it anyway as it may come in handy with openhab

First of all, install the GPIO binding in the PaperUI. After one has done that, there isnt really much else to do on that binding. There is no services/gpio.cfg although some of the documentation mentions that file.

Before I go further it is good to note that I used the openhabian distro and I presume a lot of things are already OK in that, but if you did a manual install, it might be good to check if the user ‘openhab’ is member of ‘gpio’ and if not, set that with

sudo adduser openhab gpio

That’s basically all one needs to do.
Let’s setup an ‘input’ which in openhab is a ‘Contact’ and an ‘output’, which in openhab is a Switch. In fact, those are the only states the binding allows.

There is no pressing need to define anything in your sitemap file if e.g. you add the items to a group in your itemsfile, but if you prefer a sitemap then add this to your sitemap file:

Switch item=GPIO_LAMP
Text item=GPIO_BUTTON

Let’s pick some pins to use. It is easiest to use pins on the Raspberry header that are close to a ground pin.

Looking at the pin out of the raspi, we see that for instance GPIO pins 21,13,5, 7, 10, 27,22,24,25,12,16,26, 3, 4, 8 and 17 are next to a ground pin, but some of those have reserved functions so i stayed away from those.
I picked GPIO23 and GPIO24 as that one is also close to a 3V3 pin and when using that as input one can always decide later to make that have a HIGH or a LOW input.The configuration string for the binding is defined as follows:

gpio="pin:PIN_NUMBER [debounce:DEBOUNCE_INTERVAL] [activelow:yes|no] [force:yes|no] [initialValue:high|low]"

for those who consider this as double dutch, it will become clear in the items definition:

Add this to your items file:

Switch GPIO_LAMP "Lamp" (LivingRoom) { gpio="pin:23 force:yes" }
Contact GPIO_BUTTON "Button [%s]" (LivingRoom) { gpio="pin:24 activelow:yes" }

The group ‘LivingRoom’ is not mandatory if you have defined your sitemap and of course you may use another group that suits you more.

The Switch that I set up is quite simple. In fact it already would be enough if it would have been:

Switch GPIO_LAMP "Lamp" {gpio="pin:23"}.

But with ‘force:yes’ we force the use of the pin even if it would have been in use by another process. Obviously that might not be the most elegant way to do it, but as i am pretty sure I am not using it for another process, I just wanted to make sure Openhab would have the pin available.

The current of a GPIO pin is far to small to drive any significant load as it can deliver some 60mA I think.
But the output can drive a small LED to test it… but use a 330 ohm series resistor, no matter what other websites tell you: you dont want to fry your GPIO pin. Eventually it would be more useful to drive a small relay module as long as it has a separate transistor to drive the relay (I know, I am cautious)

The configuration allows for some other parameters.
i already mentioned ‘force:yes|no

activelow yes|no  this means that when the switch is off, there is no voltage on the pin
initialValue:high:low determines the state the pin will take during initialisation.
debounce:interval is used to set the debounce value for the switch in milisecs

If we look at the output, I have not added an activelow because I thought that was the default value (but correct me if I am wrong)
If we look at our input, I set that to activelow, because the way the button works is it applies voltage to trigger the pin and I added it because I was not sure about the default
I did not set a debounce for the contact, but you could state:

Contact GPIO_BUTTON "Button [%s]" (LivingRoom) { gpio="pin:24 debounce:10 activelow:yes" }