mercoledì 18 ottobre 2017

ESP8266–01 Home Made Dev Board v1











In this post I describe the way I have designed and built a simple and useful development board for ESP8266–01





The main goal of this board is to make the use of ESP8266–01 simple during development phase on breadboard.





Schema

The schema is quite simple.
A detailed explanation on how to correctly connect EPS8266–01 pins is available here [http://www.instructables.com/id/How-to-use-the-ESP8266-01-pins/?ALLSTEPS]





The pinheader J1 and J2, in the above electrical schema, are the 8 pin of the ESP8266–01 module (as seen from above view)





The 5 pin on the left, in the above electrical schema, are the pin of the dev board. More in detail:
  • VCC: 3V3 (+) from a couple of AA batteries or any other power source (in the schema is writte 5V as I was not able to change it in Fritzing)
  • GND: the negative (-) wire from the two AA batteries or from any DC 3V3 power source
  • USB GND: the ground from the USB2TTL module
  • USB RX/TX: RX/TX from the USB2TTL module
The two pin top-right are the GPIO0 and PIO2 available on the ESP8266–10 module
The pin header J3 and J4 are not electrically connected and wired and are only used to mount the dev board on the breadboard
Two micro-buttons are available to reset the ESP8266–01 module (SW RST) and to switch into flashing/programming mode (SW GPIO0)





PCB

The PCB has been made using Fritzing software and is a single side PCB for an easy development at home










Making the PCB

I have use a home made development process to build the PCB which is called “toner transfer”. In short I have printed the circuit on glossy photo paper with a laser printer and later transferred the PCB tracks on the copper clad with a normal iron (borrowed from my wife :) )





The result is not 100% perfect (doing that at home with basic tools) as half track and few pad have not been transferred correctly





No worries, we are maker so we always find a solution. I have manually corrected the missing toner with a permanent maker (the pad which are missing are the one which are not electrically connected so no big issue)
Below the final result after the copper etching





Now I remove the toner with some simple acetone (borrowed from my wife)





now I drill the board with a 1mm drill bit





Assembling the Board

Now it is time to assemble the board with just few components
Here the list of components:





I start by soldering the resistors, the pin header and then the push buttons





Below the final result











and also with ESP8266–01 module





and everything mounted on breadboard





File

The full fritzing project with electrical schema and PCB layout is available here qui

Suggestion

The two pin header rows on the side of the dev board, are slightly larger than the breadboard. In order to overcame this small issue I have removed the 6th pin from the row.
In version 2 of this board I will fix this bug but until then I can use the dev board with the small trick explained above.
This allows me to work on my project base don ESP8266–01 in a clean and easy way avoiding flying wires.






venerdì 13 ottobre 2017

Control Arduino over Bluetooth






In this post I describe how I connected Arduino Uno (for other Arduino types the wiring are similar) with a JY-MCU HC-06 Bluetooth module I had bought some time ago.










This module allows me to connect via my phone or tablet or PC Bluetooth. The module is seen by Arduino as a serial communication and is therefore easy to manage. I already have a small project in mind for my home with this module, but for the moment, let us concentrate on how to use the module. In order to do it we need to follow the below steps:
  1. Module configuration
  2. Using the module
Below a picture showing the wiring between the Bluetooth module and Arduino







I have used 4 different wires of Black, Brown, Red and Orange color. The wires are connected in the following manner to the Bluetooth module:

  • Black -> VCC
  • Brown -> GND
  • Red -> TX
  • Orange -> RX










Now let’s connect the other side of the wires to Arduino as in the picture below










  • Black -> pin +5V
  • Brown-> pin GND
  • Red-> pin 10
  • Orange-> pin 11




It is important to wire the Bluetooth module to Arduino as described as the configuration software is expecting to have the RX on pin 10 and the TX on pin 11.
So in other words it is a cross connection like this:
  • Bluetooth TX → Arduino RX (pin 10)
  • Bluetooth RX -> Arduino TX (pin 11)





Once the wiring is completed, load the below sketch to your Arduino:


 

#define ROBOT_NAME "YOUR ARDUINO NAME"

// If you haven't configured your device before use this
#define BLUETOOTH_SPEED 9600
// If you are modifying your existing configuration, use this:
// #define BLUETOOTH_SPEED 57600

#include <softwareserial.h>

// Swap RX/TX connections on bluetooth chip
//   Pin 10 --> Bluetooth TX
//   Pin 11 --> Bluetooth RX
SoftwareSerial mySerial(10, 11); // RX, TX


/*
  The posible baudrates are:
    AT+BAUD1-------1200
    AT+BAUD2-------2400
    AT+BAUD3-------4800
    AT+BAUD4-------9600 - Default for hc-06
    AT+BAUD5------19200
    AT+BAUD6------38400
    AT+BAUD7------57600 - Johnny-five speed
    AT+BAUD8-----115200
    AT+BAUD9-----230400
    AT+BAUDA-----460800
    AT+BAUDB-----921600
    AT+BAUDC----1382400
*/


void setup()
{
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.println("Starting config");
  mySerial.begin(BLUETOOTH_SPEED);
  delay(1000);

  // Should respond with OK
  mySerial.print("AT");
  waitForResponse();

  // Should respond with its version
  mySerial.print("AT+VERSION");
  waitForResponse();

  // Set pin to 0000
  mySerial.print("AT+PIN0000");
  waitForResponse();

  // Set the name to ROBOT_NAME
  mySerial.print("AT+NAME");
  mySerial.print(ROBOT_NAME);
  waitForResponse();

  // Set baudrate to 57600
  mySerial.print("AT+BAUD7");
  waitForResponse();

  Serial.println("Done!");
}

void waitForResponse() {
    delay(1000);
    while (mySerial.available()) {
      Serial.write(mySerial.read());
    }
    Serial.write("\n");
}

void loop() {}



If everything went well you should see in your serial monitor something like the below:







At this stage the Bluetooth module is properly configured and ready to be used for communication with other devices.
The Bluetooth module can be now disconnected from Arduino because we need to connect it slightly differently.
To make sure the module works, I have created a simplest example (see below).
I want to turn ON or turn OFF two LED from my cellphone by sending simple command to Arduino.





The commands have the below simple format
# PIN — COMANDO
where
  • PIN: pin number on Arduino
  • COMANDO: ON or OFF
As an example the following command:
10-ON
sets the pin 10 of Arduino to HIGH
while the command
10-OFF
sets the pin 10 of Arduino to LOW
I have created a very simple circuit wiring on breadboard shown below
I have connected pin 8 and 10 of Arduino to two LED through a current limiting resistor (don’t forget to add a 220 Ohm or similar resistor to protect the LED and the Arduino’s GPIOs).












How you can see the JY-MCU Bluetooth module is connected to Arduino in a different way compared to the configuration phase. More in detail now the wiring is:

  • Black -> pin +5V
  • Brown -> pin GND
  • Red-> pin 0 (RX)
  • Orange-> pin 1 (TX)




This way the Bluetooth module is seen by Arduino as a serial communication. I have created a simple sketch that is awaiting and executes a command received via Bluetooth protocol.
Obviously, the sketch is quite basic and used just to verify the operation and is not solid enough for a more serious use but should help figure out better how use the module itself.


 
#include &lt'string.h>

//struttura del comando
struct CMD {
  int  pin;  //pin da controllare
  char *cmd; //comando da applicare al pin (ON|OFF)
};

int i = 0;
int readByte = 0;
char buff[255]; //contiene i dati ricevuti
struct CMD parsed_cmd; //comando ricevuto

void setup()
{
  Serial.begin(57600); 
  bt_println("Init!!!!");
}

//pulisce il buffer dopo che e' stato utilizzato
void clear_buff()
{
  for (i=0; i < 255; i++)
    buff[i] = 0;
}

//println verso bluetooth
void bt_println(String str)
{
  Serial.println(str);
  delay(10);
}

//print verso bluetooth
void bt_print(String str)
{
  Serial.print(str);
  delay(10);
}

//parsing della stringa ricevuta in un comando da eseguire
//comando ha il seguente formato:  PIN--COMANDO. esempio: 13--OFF; 13--ON
struct CMD read_command(char *command)
{
  struct CMD cmd;
  const char s[3] = "--";
  char *token;
 
  token = strtok(command, s);
  cmd.pin = atoi(token);
  
  token = strtok(NULL, s);
  cmd.cmd = token;  

  return cmd;
}

int validate_cmd(struct CMD cmd)
{
  return ((cmd.pin > 0) && ((String(cmd.cmd) == "ON") || (String(cmd.cmd) == "OFF")));
}

void execute_cmd(struct CMD cmd)
{
  int pin = cmd.pin;
  int status = (String(cmd.cmd) == "ON")?HIGH:LOW; 
 
  bt_println(String("Settin PIN: ") + String(pin) + String(" to ") + String(status));
  
  pinMode(pin, OUTPUT);
  digitalWrite(pin, status); 
}

void loop()
{
  clear_buff();  
  delay(1000);
  
  if ((readByte = Serial.available()) > 0) {
    bt_println("-------------------------");
    
    Serial.readBytes(buff, readByte);
    
    bt_println(String("Parsing commnand: ") + buff);
        
    parsed_cmd = read_command(buff);
    
    if (validate_cmd(parsed_cmd)) {   
      bt_println(String("Serial PIN = ") + String(parsed_cmd.pin));
      bt_println(String("Serial STATUS = ") + parsed_cmd.cmd);
      execute_cmd(parsed_cmd);
    }
    else
      bt_println("ERROR: COMMAND NOT VALID!");
  }
}


Now that we have completed the configuration of the bluetooth module and the wiring of the simple test circuit, we can just load the sketch on Arduino.
To make sure everything works correctly I installed a simple app on my Android phone (for iOS there are similar apps).
The App I have used is called BluetoothTerminal.
This app allows me to type characters (commands) and send them via Bluetooth to my Arduino.
In the video you see that the LEDs turn ON and OFF when I send the correct command to Arduino.
The module I used has a pin equal to 0000 for pairing Bluetooth with the cellphone.


















MQTT 101 for ESP8266






Introduction

Recently many people asked my help in the implementation of ESP8266 sketches to let two or more modules communicate over the MQTT protocol.
This article provides and describes a basic MQTT source code working skeleton to interconnect ESP8266 modules over MQTT protocol.
The goal of this code is to provide a start point to beginner developers to develop their application by extending it.





MQTT

The main site for MQTT (Message Queuing Telemetry Transport) is [http://mqtt.org/].
MQTT is define in this way: “MQTT is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport.”
The basic and key actors in a Publish/Subscribe architecture are:
  • A communication Broker : a central communication component which orchestrates all the communication processes and that manages the entire life-cycle of topics and messages
  • An agent which take the role of Publisher: sending messages to a specific topic living within a given MQTT
  • An agent which take the role of Subscriber: receiving messages from a specific topic on a broker
  • A Topic: a dedicated communication channels between devices


In this architecture a Publisher communicates with one or more Subscriber without knowing its/their identity (any type of addressing)
In other words when a Publisher wants to communicate, it just sends a message to a broker for a specific topic.
After the message has been delivered to the broker, it’s broker responsibility to propagate the message to all the Subscriber which are “listening” of a given topic (Publisher and Subscriber must publish and listen on the same topic).
Such architecture is present in many different IT domains and it is not limited to MQTT only.
As an example (over simplified), the Pub/Sub architecture is used by most of the GUI systems (Windows, Linux, …). For instance when I click on a button in a window, the windows manager send a message (Publisher). The handler of the button is listening (Subscriber) and when receiving a message from the manager it execute a specific piece of code (i.e. close the window)





ESP and MQTT

The MQTT protocol and its Pub/Sub architecture perfectly fits in the communication between ESP8266 devices and between ESP8266 and the external world (cloud). This provides a very easy, lightweight and fast communication mechanism to be used in ESP8266 projects.
A huge advantage, from a networking and security point of view, is that a given ESP can communicates with external devices with no necessity to open a TCP port in the router/firewall (if you implement a more traditional web model yo must open a port in your firewall to accept incoming web requests).
The MQTT protocol is supported by virtually any platform out there and for sure by Android, iOS, Javascript. This allow for an easy communication between a mobile/web application and an ESP module.

CLOUDMQTT

The MQTT broker I typically use for my projects and in this sketch is provided by https://www.cloudmqtt.com/


The cloud service is available in different pricing tiers, included my preferred one: the free of charge :)


Once you have sign-up to the service you can access the cloud console


Here you can find all the detailed information about your MQTT broker that you can use to configure the ESP sketch





MQTT Basic

The sample code allows one or more ESP to communicate over MQTT protocol and is available here github.
Below some important #define which should be configured before compiling and uploading the sketch to ESP8266


  • WIFI_SSID: the SSID of your WiFi network
  • WIFI_PASSWD: WiFi password
  • MQTT_CLIENT_ID: just a unique (random) ID for your MQTT client
  • MQTT_SERVER: the FQDN of the MQTT broker
  • MQTT_UNAME: authentication user name at the broker
  • MQTT_PASSWD: authentication password at the broker
  • MQTT_BROKER_PORT: listening broker port
  • MQTT_TOPIC: the MQTT topic on which exchange messages
  • ESP_NAME: a name for your ESP module
  • ESP_PUB_ROLE: ESP is behaving as a Publisher
  • ESP_SUB_ROLE: ESP is behaving as a Subscriber

ESP Libraries

This code uses the following libraries
MQTT.h and PubSubClient.h — v 1.99.0 — https://github.com/Imroy/pubsubclient





MQTT Basic Testing

The demonstration code can be tested either with 2x ESP communication between each other or 1x ESP and 1x MQTT client (for instance I will show how to use a mosquitto client on Linux, but any other MQTT client will be ok)

ESP as Publisher

On the ESP sketch un-comment #define ESP_PUB_ROLE, then compile and upload the generated binary to ESP
Once the program starts you can see in the serial monitor something similar to the below


On a Linux shell you need to subscribe to this topic: esp8266/sensori
you can use the following command:
mosquitto_sub -h <host name> -p <port> -u <user name> -p <password> -i <client id univoco> t- esp8266/sensori
where the parameters between <> are the one visible in your CloudMQTT cloud console


As you can see from the screenshot, my client running on Linux somewhere in the Internet receives commands (the string “Hello I m ESP-my_ESP_8266”) from my ESP8266 running on my desk in my office. Pretty cool ah!!

ESP as Subscriber

On the ESP sketch un-comment #define ESP_SUB_ROLE, then compile and upload the generated binary to ESP
Once the program starts you can see in the serial monitor something similar to the below


On the Linux client now I send commands to my ESP through the following command:
mosquitto_pub -h <host name> -p <port> -u <user name> -p <password> -i <client id univoco> t- esp8266/sensori -m “hi this is another ESP8266”
where the parameters between <> are the one visible in your CloudMQTT cloud console


As you can see from the screenshot, my ESP8266 running on my desk receives commands from my Linux client.

Conclusion

The MQTT protocol and the Pub/Sub architecture are used in different environments and especially in the IoT market. They provide and lightweight and flexible communication mechanism that we can leverage to give our Arduino/ESP projects connectivity to the cloud or local network.
Let me know if you find this short introduction to MQTT on ESP useful and if use it in your projects send me a picture :)