Friday, June 16, 2017

Python run on Raspberry Pi (and PC running Ubuntu) to plot serial data from ESP8266/NodeMCU

Last post show a simple program run on ESP8266/NodeMCU to read Analog Input and send to Serial. And display the data on Raspberry Pi 3 using Arduino IDE Serial Plotted. This post show a Python example run on Raspberry Pi 3/Raspbian Jessie with PIXEL, to plot the serial data graphically using matplotlib library.



pyserialplot.py
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial
import platform

print("Python version: " + platform.python_version())
print("matplotlib version: " + mpl.__version__)

fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1030)
xdata, ydata = [0]*100, [0]*100
SerialIn = serial.Serial("/dev/ttyUSB0",9600)

def update(data):
    line.set_ydata(data)
    return line,

def run(data):
    global xdata, ydata
    x,y = data
    if (x == 0):
        xdata = [0]*100
        ydata = [0]*100
    del xdata[0]
    del ydata[0]
    xdata.append(x)
    ydata.append(y)
    line.set_data(xdata, ydata)
    return line,

def data_gen():
    x = 9
    while True:
        if (x >= 9):
            x = 0
        else:
            x += 0.1
            
        try:
            inRaw = SerialIn.readline()
            inInt = int(inRaw)
        except:
            inInt = 0
            
        yield x, inInt

ani = animation.FuncAnimation(fig, run, data_gen, interval=0, blit=True)
plt.show()


This python example can be run on both Python 2 and 3. To run this on Raspberry Pi/Raspbian Jessie with PIXEL, matplotlib library is need.

For Python 2:
$ sudo apt-get install python-matplotlib

For Python 3:
$ sudo apt-get install python3-matplotlib

In the following code, we have to get the port connected.
SerialIn = serial.Serial("/dev/ttyUSB0",9600)

In Raspberry Pi/Raspbian Jessie with PIXEL, it is /dev/ttyUSB0 normal. We can check it with:
$ ls /dev/ttyUSB0*




Run on Ubuntu:

The Python script work on PC/Ubuntu also. This video show running on Ubuntu 17.04/Payton 3.6 (actually behind Windows 10/VirtualBox).


In order to run with newest Python 3.6 on Ubuntu 17.04, you have to install Python 3.6 and corresponding IDLE and pip.

And install packages using command:
$ sudo python3.6 -m pip install numpy
$ sudo python3.6 -m pip install matplotlib
$ sudo python3.6 -m pip install pyserial


About Saving graph of matplotlib:

Suppose I can click the Save button on matplotlib navigation toolbar to save the graph to file (reference: matplotlib - Interactive navigation).

But when I test it on Raspberry Pi with matplotlib 1.4.2, it is not work.

When test it on PC running Ubuntu 17.04/Python 3.6 with matplotlib 2.0.2, I can save the graph. But the navigation toolbar disappear after saved.



Thursday, June 15, 2017

ESP8266/NodeMCU read Analog Input and send to Raspberry Pi via Serial/USB

This example of ESP8266/NodeMCU read input from A0, and output to Serial. The receiving side is a Raspberry Pi 3 running Raspbian Jessie with PIXEL and Arduino IDE installed, the result is display graphically using Arduino IDE's Serial Plotter. All job done on Raspberry Pi 3. ESP8266/NodeMCU connect to the Raspberry Pi 3 with USB.


To run the whole in Raspberry Pi, you have to:
- Install Arduino IDE on Raspberry Pi/Raspbian Jessie with PIXEL
Add Arduino core for ESP8266 to Arduino IDE

The simple program run on ESP8266/NodeMCU, ESP8266_AnalogIn_SerialOut.ino. (Suppose it work on other Arduino also, such as Uno.)
const int analogIn = A0;
int analogVal = 0;
bool led = 1;

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {

  digitalWrite(LED_BUILTIN, led);
  led = !led; 
  analogVal = analogRead(analogIn);
  Serial.println(analogVal);
  delay(500);
}

Next:
A Python example run on Raspberry Pi 3/Raspbian Jessie with PIXEL, to plot the serial data graphically using matplotlib library.

Add Arduino core for ESP8266 to Arduino IDE (run on Raspberry Pi/Raspbian Jessie with PIXEL)

Last post show how to "Install and run Arduino IDE on Raspberry Pi/Raspbian Jessie with PIXEL". We can add Arduino core for ESP8266 to Boards Manager, such that we can develop ESP8266/NodeMCU program on Raspberry Pi directly, without using PC. For sure, the compiling time will be longer than on PC.

Add Additional Board Manager URL for ESP8266 board:
> File > Preference
> Add "http://arduino.esp8266.com/stable/package_esp8266com_index.json" in Additional Board Manager URLs.

Add ESP8266 board to Arduino IDE:
- Open Boards Manager in Arduino IDE
- Search "esp8266" or "NodeMCU", you will find "esp8266 by ESP8266 Community". Install it.

This video show how to, and run the Blink example on ESP8266/NodeMCU. The Raspberry Pi 3 connect to a 4" 800x480 HDMI IPS LCD Display, so it display in low resolution.

Next:
ESP8266/NodeMCU read Analog Input and send to Raspberry Pi via Serial/USB
A Python example run on Raspberry Pi 3/Raspbian Jessie with PIXEL, to plot the serial data graphically using matplotlib library.


Tuesday, June 13, 2017

ESP32/Arduino core for ESP32 example, simple Web control RGB LED

My former post show how to program ESP32 with Arduino core for ESP32 to output PWM to GPIO using ledcWrite(). This exercise modify from the post of "NodeMCU/ESP8266 Arduino Core example, simple http server to output PWM", port to ESP32/Arduino core for ESP32, to implement a simple web control RGB LED.


NodeMCU32_WebRGBLED.ino
/* 
 *  This sketch run on ESP32 with Arduino core for ESP32,
 *  demonstrates how to set up a simple HTTP-like server.
 *  The server will set a GPIO pins depending on the request,
 *  to control the brightness of RGB LED connected to:
 *    23 : BLUE
 *    22 : GREEN
 *    21 : RED
 *    
 *    http://server_ip/rgb/rrggbb/
 *    where rr is the value set RED
 *    where gg is the value set GREEN
 *    where bb is the value set BLUE
 *    then terminate with '/'
 *  server_ip is the IP address of the ESP32, will be 
 *  printed to Serial when the module is connected.
*/
#include <WiFi.h>

const char* ssid = "ssid";
const char* password = "password";
WiFiServer server(80);

#define MAX_LED_VALUE 99
// use first 3 channels of 16 channels (started from zero)
#define LEDC_CHANNEL_0_R  0
#define LEDC_CHANNEL_1_G  1
#define LEDC_CHANNEL_2_B  2

// use 13 bit precission for LEDC timer
#define LEDC_TIMER_13_BIT  13

// use 5000 Hz as a LEDC base frequency
#define LEDC_BASE_FREQ     5000

// LED PINs
#define LED_PIN_R   21
#define LED_PIN_G   22
#define LED_PIN_B   23

/*
Because Multiple libraries were found for "WiFi.h",
Arduino IDE will: 
 Used: ...\Arduino\hardware\espressif\esp32\libraries\WiFi
 Not used: C:\Program Files (x86)\Arduino\libraries\WiFi

And exit with error:
'min' was not declared in this scope

So I have to program my own min()
 */
uint32_t min(uint32_t num1, uint32_t num2){
  if(num1 < num2){
    return num1;
  }else{
    return num2;
  }
}

// Arduino like analogWrite
// value has to be between 0 and valueMax
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = MAX_LED_VALUE) {
  // calculate duty
  uint32_t duty = (LEDC_BASE_FREQ / valueMax) * min(value, valueMax);

  // write duty to LEDC
  ledcWrite(channel, duty);
}

void setup() {
  Serial.begin(115200);
  delay(10);
  
  // Setup timer and attach timer to a led pins
  ledcSetup(LEDC_CHANNEL_0_R, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
  ledcAttachPin(LED_PIN_R, LEDC_CHANNEL_0_R);
  ledcSetup(LEDC_CHANNEL_1_G, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
  ledcAttachPin(LED_PIN_G, LEDC_CHANNEL_1_G);
  ledcSetup(LEDC_CHANNEL_2_B, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
  ledcAttachPin(LED_PIN_B, LEDC_CHANNEL_2_B);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  
  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  
  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  
  // Match the request
  int valR, valG, valB;
  String subStringR, subStringG, subStringB;
  int index = req.indexOf("/rgb/");
  if(index != -1){
    if(req.charAt(index+11)=='/'){
      subStringR = req.substring(index+5, index+7);
      subStringG = req.substring(index+7, index+9);
      subStringB = req.substring(index+9, index+11);
      Serial.println("R: " + subStringR);
      Serial.println("G: " + subStringG);
      Serial.println("B: " + subStringB);

      valR = subStringR.toInt();
      valG = subStringG.toInt();
      valB = subStringB.toInt();
      Serial.println("valR: " + String(valR));
      Serial.println("valG: " + String(valG));
      Serial.println("valB: " + String(valB));
      
    }
    else{
      Serial.println("Not terminated with /");
      client.stop();
      return;
    }
  }
  else {
    Serial.println("No /rgb/ found");
    client.stop();
    return;
  }

  // Set GPIOs according to the request
  // No check valid of the requested setting
  ledcAnalogWrite(LEDC_CHANNEL_0_R, valR);
  ledcAnalogWrite(LEDC_CHANNEL_1_G, valG);
  ledcAnalogWrite(LEDC_CHANNEL_2_B, valB);
  
  client.flush();

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIOs of RGB is now ";
  s += String(valR) +":" + String(valG) + ":" + String(valB);
  s += "</html>\n";

  // Send the response to the client
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

  // The client will actually be disconnected 
  // when the function returns and 'client' object is detroyed
}



Connection:


Install and run Arduino IDE on Raspberry Pi/Raspbian Jessie with PIXEL


This video show how to download, install and run Arduino IDE Linux ARM version (1 JUNE 2017 release), on Raspberry Pi 3 with Raspbian Jessie with PIXEL (2017-04-10 release). The Raspberry Pi connect to a 4" 800x480 HDMI IPS LCD Display, so it display in low resolution.

(All steps run on Raspberry Pi, remotely via VNC Viewer)

- Visit Arduino Software page. Scroll download to HOURLY BUILDS section, click to download Linux ARM version. It's release 1 JUNE 2017 currently.

- Extract the downloaded file.

- Change to the extracted directory.

- Run the install shell script.
$ sudo ./install.sh

- A short-cut will be added in MENU -> Programming -> Arduino IDE

You can also update library and board in the installed Arduino IDE.


Test with a simple program to read/write between Raspberry Pi and Arduino via Serial/USB.


testUsb.ino
int byteIn;

void setup() {
  Serial.begin(9600);
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.print("Program started\n");
}

// the loop function runs over and over again forever
void loop() {
  if(Serial.available() > 0){
    byteIn = Serial.read();
    if(byteIn == '0'){
      digitalWrite(LED_BUILTIN, LOW);
      Serial.print("LED OFF\n");
    }else if(byteIn == '1'){
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.print("LED ON\n");
    }else{
      Serial.print("unknown!\n");
    }
  }
}

Next:
Add Arduino core for ESP8266 to Arduino IDE (run on Raspberry Pi/Raspbian Jessie with PIXEL)

Monday, June 5, 2017

Arduino core for ESP32, output PWM to GPIO using ledcWrite()


For ESP-32 Wifi/Bluetooth module with Arduino core for ESP32, to output PWM to GPIO, we can call ledcWrite(), something like Arduino analogWrite() function.

It's a example to output PWM to GPIO 21, 22 and 23, to control color/brightness of RGB LED.
/*
 Arduino core for ESP32 example: output PWM to GPIO using ledcWrite()
 Modify from the example code:
 /ESP32/examples/AnalogOut/LEDCSoftwareFade
*/

// use first 3 channels of 16 channels (started from zero)
#define LEDC_CHANNEL_0_R  0
#define LEDC_CHANNEL_1_G  1
#define LEDC_CHANNEL_2_B  2

// use 13 bit precission for LEDC timer
#define LEDC_TIMER_13_BIT  13

// use 5000 Hz as a LEDC base frequency
#define LEDC_BASE_FREQ     5000

// LED PINs
#define LED_PIN_R   21
#define LED_PIN_G   22
#define LED_PIN_B   23

// Arduino like analogWrite
// value has to be between 0 and valueMax
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 255) {
  // calculate duty
  uint32_t duty = (LEDC_BASE_FREQ / valueMax) * min(value, valueMax);

  // write duty to LEDC
  ledcWrite(channel, duty);
}

void setup() {
  // Setup timer and attach timer to a led pins
  ledcSetup(LEDC_CHANNEL_0_R, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
  ledcAttachPin(LED_PIN_R, LEDC_CHANNEL_0_R);
  ledcSetup(LEDC_CHANNEL_1_G, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
  ledcAttachPin(LED_PIN_G, LEDC_CHANNEL_1_G);
  ledcSetup(LEDC_CHANNEL_2_B, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
  ledcAttachPin(LED_PIN_B, LEDC_CHANNEL_2_B);
}

void loop() {
  ledcAnalogWrite(LEDC_CHANNEL_0_R, 0);
  ledcAnalogWrite(LEDC_CHANNEL_1_G, 0);
  ledcAnalogWrite(LEDC_CHANNEL_2_B, 0);
  delay(1000);

  for(int i = 0; i < 255; i++){
    ledcAnalogWrite(LEDC_CHANNEL_0_R, i);
    delay(10);
  }
  for(int i = 255; i > 0; i--){
    ledcAnalogWrite(LEDC_CHANNEL_0_R, i);
    delay(10);
  }

  for(int i = 0; i < 255; i++){
    ledcAnalogWrite(LEDC_CHANNEL_1_G, i);
    delay(10);
  }
  for(int i = 255; i > 0; i--){
    ledcAnalogWrite(LEDC_CHANNEL_1_G, i);
    delay(10);
  }

  for(int i = 0; i < 255; i++){
    ledcAnalogWrite(LEDC_CHANNEL_2_B, i);
    delay(10);
  }
  for(int i = 255; i > 0; i--){
    ledcAnalogWrite(LEDC_CHANNEL_2_B, i);
    delay(10);
  }

  for(int i = 0; i < 255; i++){
    ledcAnalogWrite(LEDC_CHANNEL_0_R, i);
    ledcAnalogWrite(LEDC_CHANNEL_1_G, i);
    ledcAnalogWrite(LEDC_CHANNEL_2_B, i);
    delay(10);
  }
  for(int i = 255; i > 0; i--){
    ledcAnalogWrite(LEDC_CHANNEL_0_R, i);
    ledcAnalogWrite(LEDC_CHANNEL_1_G, i);
    ledcAnalogWrite(LEDC_CHANNEL_2_B, i);
    delay(10);
  }
}


Connection:
Reference:
Example at /ESP32/examples/AnalogOut/LEDCSoftwareFade
or here.

Next:
ESP32/Arduino core for ESP32 example, simple Web control RGB LED

Thursday, June 1, 2017

NodeMCU/ESP8266 Arduino Core example, simple http server to output PWM

Last post show a dummy example of NodeMCU/ESP8266 Arduino Core to output PWM to control color/brightness of RGB LED.

It's another example to setup a simple HTTP-like server, to receive request from client, output PWM, to control color/brightness of RGB LED.


NodeMCU_WiFiWebServer_RGB.ino
/*
 *  This sketch run on NodeMCU (ESP8266),
 *  demonstrates how to set up a simple HTTP-like server.
 *  The server will set a GPIO pins depending on the request,
 *  to control the brightness of RGB LED connected to:
 *    D0 : BLUE
 *    D1 : GREEN
 *    D2 : RED
 *    
 *    http://server_ip/rgb/rrggbb/
 *    where rr is the value set RED
 *    where gg is the value set GREEN
 *    where bb is the value set BLUE
 *    then terminate with '/'
 *  server_ip is the IP address of the NodeMCU, will be 
 *  printed to Serial when the module is connected.
 */

#include <ESP8266WiFi.h>

const char* ssid = "Xtation";
const char* password = "password";

int ledB = D0;
int ledG = D1;
int ledR = D2;

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);

  // prepare GPIOs for RGB LED
  pinMode(D0, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  analogWriteRange(99); //PWM: 0~99
  
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  
  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  
  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  
  // Match the request
  int valR, valG, valB;
  String subStringR, subStringG, subStringB;
  int index = req.indexOf("/rgb/");
  if(index != -1){
    if(req.charAt(index+11)=='/'){
      subStringR = req.substring(index+5, index+7);
      subStringG = req.substring(index+7, index+9);
      subStringB = req.substring(index+9, index+11);
      Serial.println("R: " + subStringR);
      Serial.println("G: " + subStringG);
      Serial.println("B: " + subStringB);

      valR = subStringR.toInt();
      valG = subStringG.toInt();
      valB = subStringB.toInt();
      Serial.println("valR: " + String(valR));
      Serial.println("valG: " + String(valG));
      Serial.println("valB: " + String(valB));
      
    }
    else{
      Serial.println("Not terminated with /");
      client.stop();
      return;
    }
  }
  else {
    Serial.println("No /rgb/ found");
    client.stop();
    return;
  }

  // Set GPIOs according to the request
  // No check valid of the requested setting
  analogWrite(ledR, valR);
  analogWrite(ledG, valG);
  analogWrite(ledB, valB);
  
  client.flush();

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIOs of RGB is now ";
  s += String(valR) +":" + String(valG) + ":" + String(valB);
  s += "</html>\n";

  // Send the response to the client
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

  // The client will actually be disconnected 
  // when the function returns and 'client' object is detroyed
}


Connection same as in last post:



Compare with ESP32 version: ESP32/Arduino core for ESP32 example, simple Web control RGB LED

NodeMCU/ESP8266 Arduino Core analog output PWM

Example of NodeMCU with ESP8266 Arduino Core to output PWM by calling analogWrite(), to control brightness of RGB LED.



NodeMCU_PWM.inf
int ledB = D0;
int ledG = D1;
int ledR = D2;

void setup() {
  pinMode(D0, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  //Set PWM frequency 500, default is 1000
  //Set range 0~100, default is 0~1023
  analogWriteFreq(500);
  analogWriteRange(100);
}

// the loop function runs over and over again forever
void loop() {
  analogWrite(ledR, 0);
  analogWrite(ledG, 0);
  analogWrite(ledB, 0);
  delay(500);
  analogWrite(ledR, 100);
  analogWrite(ledG, 100);
  analogWrite(ledB, 100);
  delay(500);
  analogWrite(ledR, 0);
  analogWrite(ledG, 0);
  analogWrite(ledB, 0);
  delay(500);

  int i;
  for(i=0; i<100; i++){
    analogWrite(ledR, i);
    delay(10);
  }
  analogWrite(ledR, 0);
  
  for(i=0; i<100; i++){
    analogWrite(ledG, i);
    delay(10);
  }
  analogWrite(ledG, 0);
  
  for(i=0; i<100; i++){
    analogWrite(ledB, i);
    delay(10);
  }
  analogWrite(ledB, 0);

  for(i=0; i<100; i++8){
    analogWrite(ledR, i);
    analogWrite(ledG, i);
    analogWrite(ledB, i);
    delay(10);
  }

  for(i=100; i>0; i--){
    analogWrite(ledR, i);
    analogWrite(ledG, i);
    analogWrite(ledB, i);
    delay(10);
  }

}

Reference:
analogWrite(pin, value) enables software PWM on the given pin. PWM may be used on pins 0 to 16. Call analogWrite(pin, 0) to disable PWM on the pin. value may be in range from 0 to PWMRANGE, which is equal to 1023 by default. PWM range may be changed by calling analogWriteRange(new_range).

PWM frequency is 1kHz by default. Call analogWriteFreq(new_frequency) to change the frequency.

Next:
simple http server to output PWM, to control color/brightness of RGB LED.


Tuesday, May 23, 2017

Control GPIOs of NodeMCU (ESP8266) with ESP8266 core for Arduino, to read Buttons and write LEDs

This example show how to read input (D5, D6 & D7) from buttons, and write output (D0, D1 & D2) to LEDs accordingly. For the input, all set INPUT_PULLUP to enable internal pull-up resistor, so no external resistors needed.


Connection:

/*
NodeMCU IO index vs ESP8266 pin
IO index  ESP8266 pin
    0     [*] GPIO16
    1     GPIO5 
    2     GPIO4 
    3     GPIO0
    4     GPIO2
    5     GPIO14  
    6     GPIO12
    7     GPIO13
    8     GPIO15
    9     GPIO3
    10    GPIO1
    11    GPIO9
    12    GPIO10
[*] D0(GPIO16) can only be used as gpio read/write. 
No support for open-drain/interrupt/pwm/i2c/ow.
https://nodemcu.readthedocs.io/en/master/en/modules/gpio/
 */
 
void setup() {
  pinMode(D0, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D5, INPUT_PULLUP);
  pinMode(D6, INPUT_PULLUP);
  pinMode(D7, INPUT_PULLUP);
}

// the loop function runs over and over again forever
void loop() {
  if(digitalRead(D5)){
    digitalWrite(D0, LOW);
  }else{
    digitalWrite(D0, HIGH);
  }

  if(digitalRead(D6)){
    digitalWrite(D1, LOW);
  }else{
    digitalWrite(D1, HIGH);
  }

  if(digitalRead(D7)){
    digitalWrite(D2, LOW);
  }else{
    digitalWrite(D2, HIGH);
  }

}


Usage of GPIO:
At the beginning, I want to use D6, D7 and D8 as input. But D8 always return LOW. After googled and found schematic diagram of NodeMCU DevKit v1.0 here: https://github.com/nodemcu/nodemcu-devkit-v1.0/blob/master/NODEMCU_DEVKIT_V1.0.PDF. It's found that GPIO15 (D8) connect to GND via a resistor, so always return LOW.

And MATTERS NEEDING ATTENTION can be found in the schematic diagram:
On every boot/reset/wakeup, GPIO15 MUST keep LOW, GPIO2 MUST keep HIGH. 
GPIO0 HIGH -> RUN MODE, LOW -> FLASH MODE.
When you need to use the sleep mode, GPIO16 and RST should be connected, and GPIO16 will output LOW to reset the system at the time of wakeup.

So, I change using D5.


Monday, May 15, 2017

Nextion Project

This playlist created by ITEAD Studio, with DEMOs of Nextion Display and Nextion Editor.

Nextion NX3224T024 Generic 2.4" TFT 320 x 240 Intelligent LCD Touch Screen Display

Asiawill Nextion NX3224T024 Generic 2.4" TFT 320 x 240 Resolution Intelligent LCD Touch Screen Display

Overview:
Nextion is a Seamless Human Machine Interface (HMI) solution that provides a control and visualisation interface between a human and a process, machine, application or appliance. It is the best solution to replace the traditional LCD and LED Nixie tube. Nextion includes hardware part (a series of TFT boards) and software part (the Nextion editor). The Nextion TFT board uses only one serial port to communicate. It lets you avoid the hassle of wiring. We notice that most engineers spend much time in application development but get unsatisfactory results. In this situation, Nextion editor has mass components such as button, text, progress bar, slider, instrument panel etc. to enrich your interface design. And the drag-and-drop function ensures that you spend less time in programming, which will reduce 99% of your development workloads. With the help of this WYSIWYG editor, designing a GUI is a piece of cake. It's easy to adapt Nextion family HMI to existing projects, you just need to provide it a UART.

Features:

  • Compatible with Raspberry Pi A+, B+ and Raspberry Pi 2
  • RGB 65K true to life colours
  • TFT Screen with integrated 4-wire Resistive Touch Panel
  • Easy 4 pin interface to any TTL Serial Host
  • 4M Flash memory for User Application Code and Data
  • On board micro-SD card for firmware upgrade
  • Visual Area:36.72mm(L)¡Á48.96mm(W)
  • Adjustable Brightness:0~180 nit, the interval of adjustment is 1%
  • 5V90mA power conusmption
  • Display Resolution: 320 * 240
  • Display Interface: Serial
  • Screen Type: Touch Screen
  • Display Controller: No
  • TFT display interface: N/A
  • Display Size: 2.4¡±
  • Expand:
  • SD Card Socket
  • Touch Screen
  • Package include:
  • 1x Nextion 2.4'' display,
  • 1x Wire,
  • 1x Power supply test board
  • Note: there's a small power supply test board and a wire for you to test if the electricity supply is enough or not.

Wednesday, May 10, 2017

Control GPIO (external IO pins) of NodeMCU (ESP8266) with ESP8266 core for Arduino


With ESP8266 core for Arduino, we can load and run the build-in basic example of "Blink" on NodeMCU to toggle the on board LED. We can also employ the same methods to control other io pin, or GPIO.



Connection:



There are many version of ESP8266, the printed mark on PCB may not the io number of ESP8266 MCU, you have to check it for your board. This example run on NodeMCU with marking and CPU pin assignment:
NodeMCU IO index vs ESP8266 pin
IO index  ESP8266 pin
    0     [*] GPIO16  
    1     GPIO5 
    2     GPIO4 
    3     GPIO0 
    4     GPIO2 
    5     GPIO14  
    6     GPIO12
    7     GPIO13
    8     GPIO15
    9     GPIO3
    10    GPIO1
    11    GPIO9
    12    GPIO10
[*] D0(GPIO16) can only be used as gpio read/write. 
No support for open-drain/interrupt/pwm/i2c/ow.
https://nodemcu.readthedocs.io/en/master/en/modules/gpio/

If you run on NodeMCU and select board of NodeMCU 1.0, you can use D1~D10 to access the pins. Refer to pins_arduino.h. Both D1 and 5 refer to the same pin.



If you run on other module, and select other board, may be the compile will report error of  'D1' was not declared in this scope. You have to specify the io# of the MCU, 5 in this case.


NodeMCU_Blink.ino
/*
NodeMCU IO index vs ESP8266 pin
IO index  ESP8266 pin
    0     [*] GPIO16  
    1     GPIO5 
    2     GPIO4 
    3     GPIO0 
    4     GPIO2 
    5     GPIO14  
    6     GPIO12
    7     GPIO13
    8     GPIO15
    9     GPIO3
    10    GPIO1
    11    GPIO9
    12    GPIO10
[*] D0(GPIO16) can only be used as gpio read/write. 
No support for open-drain/interrupt/pwm/i2c/ow.
https://nodemcu.readthedocs.io/en/master/en/modules/gpio/
 */

/*
 * For NodeMCU (8266) both D1 and 5 refer to the same pin
 * For others, such as "Generic ESP8266 Module", it will
 * report error of: 'D1' was not declared in this scope.
 */
const int io5 = 5;

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pins as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  //pinMode(D1, OUTPUT);
  pinMode(io5, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  //digitalWrite(D1, HIGH);
  digitalWrite(io5, HIGH);
  delay(500);
  //digitalWrite(D1, LOW);
  digitalWrite(io5, LOW);
  delay(500);
  digitalWrite(LED_BUILTIN, LOW);
  //digitalWrite(D1, HIGH);
  digitalWrite(io5, HIGH);
  delay(500);
  //digitalWrite(D1, LOW);
  digitalWrite(io5, LOW);
  delay(500);
}

Next:
Control GPIOs of NodeMCU (ESP8266) with ESP8266 core for Arduino, to read Buttons and write LEDs

Monday, April 24, 2017

ESP32 Simple Web Server to control external LED

It's a example of ESP32 Wifi Bluetooth Module with Arduino core for ESP32, to implement a simple WiFi web server, to toggle LED.



Connect a LED/resistor to GPIO 21:

You can find the example in Arduino IDE:


What you have to do is change the ssid, password and the io number of the LED.

SimpleWiFiServer.ino
/*
  WiFi Web Server LED Blink

 A simple web server that lets you blink an LED via the web.
 This sketch will print the IP address of your WiFi Shield (once connected)
 to the Serial monitor. From there, you can open that address in a web browser
 to turn on and off the LED on pin 21.

 If the IP address of your shield is yourAddress:
 http://yourAddress/H turns the LED on                      
 http://yourAddress/L turns it off

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * WiFi shield attached
 * LED attached to pin 21

 created for arduino 221 Nov 2012
 by Tom Igoe

ported for sparkfun esp32 
31.01.2017 by Jan Hendrik Berlin
 
 */

#include <WiFi.h>

const char* ssid     = "ssid";
const char* password = "password";

WiFiServer server(80);

void setup()
{
    Serial.begin(115200);
    pinMode(21, OUTPUT);      // set the LED pin mode

    delay(10);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(2100);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    
    server.begin();

}

int value = 0;

void loop(){
 WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("new client");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();

            // the content of the HTTP response follows the header:
            client.print("Click <a href=\"/H\">here</a> turn the LED on pin 21 on<br>");
            client.print("Click <a href=\"/L\">here</a> turn the LED on pin 21 off<br>");

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {    // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }

        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
          digitalWrite(21, HIGH);               // GET /H turns the LED on
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(21, LOW);                // GET /L turns the LED off
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }
}

Connect I2C 128X64 OLED (SSD1306) to ESP32, using esp8266-oled-ssd1306


esp8266-oled-ssd1306 is a I2C display driver for SSD1306 OLED displays connected to an ESP8266 or ESP32. I have a ole post show how to "NodeMCU/ESP8266 + OLED 0.96" 128x64 I2C SSD1306 using esp8266-oled-ssd1306 library". This post show how to use it on ESP-32S Wifi Bluetooth Module, with Arduino core for ESP32.


To install esp8266-oled-ssd1306 to Arduino IDE, refer to the post "NodeMCU/ESP8266 + OLED 0.96" 128x64 I2C SSD1306 using esp8266-oled-ssd1306 library".

Connect I2C OLED to ESP32:

ESP32 3V3 - OLED VCC
ESP32 GND - OLED GND
ESP32 GPIO 21 - OLED SDA
ESP32 GPIO 22 - OLED SCL

Open SSD1306SimpleDemo, and replace the code:
SSD1306  display(0x3c, D3, D5);

to:
SSD1306  display(0x3c, 21, 22);

This video show how to:

Sunday, April 23, 2017

ESP-32S Wifi Bluetooth Module - control GPIO to blink LED, using Arduino core for the ESP32



This example show how to modify the most basic Blink example, run on ESP-32S Wifi Bluetooth Module using Arduino core for the ESP32, control GPIO to toggle external LED.


Connection:
The GPIO 21 is used in this example.


(Fritzing part of Node32s is used here)

ESP32Blink.ino
int LED = 21;

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);                       // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(100);                       // wait for a second
}


Get the WiFi MAC address of ESP32 Module

This example show how to get the WiFi MAC address of ESP32 Module, using Arduino core for ESP32. In this example, I just want to know the MAC address only, without connect to any hotspot, so no ssid and password needed (or it will connect to last ssid).


ESP32_WiFi.ino
/*
 * ESP-32 Example, 
 * start WiFi (without ssid and password)
 * and print the MAC address to Serial.
 * http://arduino-er.blogspot.com/
 */

#include <WiFi.h>

byte mac[6];

void setup()
{
    Serial.begin(115200);
    delay(1000);

    Serial.println();
    Serial.print("Program Start...");

    WiFi.begin();
    Serial.println("WiFi began");
    WiFi.macAddress(mac);
    
    Serial.print("MAC: ");
    Serial.print(mac[0],HEX);
    Serial.print(":");
    Serial.print(mac[1],HEX);
    Serial.print(":");
    Serial.print(mac[2],HEX);
    Serial.print(":");
    Serial.print(mac[3],HEX);
    Serial.print(":");
    Serial.print(mac[4],HEX);
    Serial.print(":");
    Serial.println(mac[5],HEX);

}

void loop(){

}

It match with the scanned address of the wireless router.




Remark:
May be it's something wrong on my ESP32 board; sometimes the program halt on the code WiFi.begin() without return. Try to close Serial Monitor, disconnect and reconnect ESP32 USB cable, then run Serial Monitor.

Tuesday, April 18, 2017

Introducing the Arduino MKRFOX1200

The MKRFOX1200 is a powerful board that combines the functionality of the Zero and Sigfox connectivity. It is the ideal solution for Makers looking to design IoT projects with minimal previous experience in networking.

ESP-32S Wifi Bluetooth Module

It is a Wifi Bluetooth Combo Module with ESP32-D0WDQ6 chip, named Goouuu-ESP32.





Compare with NodeMCU with ESP8266 WiFI module.





ESP32 is a low-cost, low-power system on a chip (SoC) series with Wi-Fi & dual-mode Bluetooth capabilities! The ESP32 series of chips presently includes ESP32-D0WDQ6 (and ESP32-D0WD), ESP32-D2WD, and ESP32-S0WD. At its heart, there's a dual-core (or single-core) Tensilica Xtensa LX6 microprocessor with a clock rate of up to 240 MHz. ESP32 is highly integrated with built-in antenna switches, RF balun, power amplifier, low-noise receive amplifier, filters, and power management modules. Engineered for mobile devices, wearable electronics, and IoT applications, ESP32 achieves ultra-low power consumption through power saving features including fine resolution clock gating, multiple power modes, and dynamic power scaling. ~ know more: http://esp32.net/


Useful links:
Arduino core for the ESP32
- Espressif Documents, EN/CN.

Related:
Install Arduino core for ESP32 to Arduino IDE, on Windows 10, and example list



Tuesday, April 11, 2017

First try Arduino Web Editor/Arduino 101 with Gyro example

My first try Arduino Web Editor/Arduino 101 with Gyro example. Assume Arduino plug-ins was installed correctly, and Arduino 101 is connect to PC.







The Arduino Web Editor allows you to write code and upload sketches to any official Arduino and Genuino board from your web browser (Chrome, Firefox, Safari and Edge) after installing a plugin (repository available here).


~ Getting Started with the Arduino Web Editor

Tuesday, April 4, 2017

Electronics Cookbook: Practical Electronic Recipes with Arduino and Raspberry Pi

Electronics Cookbook: Practical Electronic Recipes with Arduino and Raspberry Pi

If you’re among the many hobbyists and designers who came to electronics through Arduino and Raspberry Pi, this cookbook will help you learn and apply the basics of electrical engineering without the need for an EE degree. Through a series of practical recipes, you’ll learn how to solve specific problems while diving into as much or as little theory as you’re comfortable with.

Author Simon Monk (Raspberry Pi Cookbook) breaks down this complex subject into several topics, from using the right transistor to building and testing projects and prototypes. With this book, you can quickly search electronics topics and go straight to the recipe you need. It also serves as an ideal reference for experienced electronics makers.

This cookbook includes:

  • Theoretical concepts such as Ohm’s law and the relationship between power, voltage, and current
  • The fundamental use of resistors, capacitors and inductors, diodes, transistors and integrated circuits, and switches and relays
  • Recipes on power, sensors and motors, integrated circuits, and radio frequency for designing electronic circuits and devices
  • Advice on using Arduino and Raspberry Pi in electronics projects
  • How to build and use tools, including multimeters, oscilloscopes, simulations software, and unsoldered prototypes


Monday, April 3, 2017

Program the Siemens IOT2000 With Arduino IDE

The new Internet of Things gateway from Siemens (Simatic) has been released! It's based on the Intel Galileo Gen2 chipset.

This tutorial show how to "Program the New IOT2000 From Siemens With Arduino IDE!".

Friday, March 31, 2017

Arduino for Kids

Arduino for Kids

Key Features
  • Get clearly-written code with descriptions and comments in the code that explain each the code section
  • The book comes with separate code files of one entire program at a time, as well as many diagrams and separate downloadable files that contain colored photos explaining steps in the book
  • Kids can build multiple projects during the course of the book, and by the end, they will have working projects of their own
Book Description
The mission of this book is to integrate technology with the tools that children already use for crafts so that they feel technology is an extension of their playtime. We use coding, sensors, and micro-controllers integrated with art and craft supplies, origami, and playdough. There are 10 fun-filled chapters that talk to children directly, and give clear instructions for non-technical parents too.

We use Arduino as the controller of choice due to its easy availability and large community. By the end of the book, children will comfortably be able to set up their Arduino, read and understand code, manipulate code, and ultimately write their own code for projects. They will also be able to use basic sensors and know how components connect to each other. All the learning takes place with lots of colorful pictures and the circuits are neatly presented using wiring.

What you will learn
  • Presents variables, functions, loops, arrays, and libraries in ways that children will understand, enabling them to start writing simple programs by themselves
  • Shows children how to set up Arduino and understand the internal functioning in a simple manner
  • Teaches them the importance of connections in electronics and helps them arrive at ways to connect by themselves
  • Demonstrates various sensors, sensor selection, and ultimately shows them how to build their own sensor by the last chapter
  • Teaches them the concept of registers as a use case of Arduino pin expansion to accommodate more LEDs or sensors so that they do not feel limited by the number of ports
  • Helps them to become nice and empathetic inventors through interactive exercises (such as making a friend happy with a proximity sensor, and giving "life" to a plant)

Learning C for Arduino

Learning C for Arduino

Key Features
  • Get hands-on experience with the Ardruino board and learn to control it with your programming skills
  • Learn the essential concepts of C such as variables, data structures, functions, loops, and pointers
  • Work with electronic devices such as LEDs, switches, and motors and connect them to Arduino using C
Book Description
Are you excited to explore the small yet powerful Arduino board, but are you wondering how to explore it without having programming and/or microcontroller skills? Then this book is what you are looking for. It will not only help you explore the world of Arduino with C programming, but also aid you in controlling your Arduino board.

The book will start with the fundamentals of C programming and programming topics, such data types, functions, decision making, program loops, pointers, and structures, with the help of an Arduino board. Then you will get acquainted with Arduino interactions with sensors, LEDs, and autonomous systems and setting up the Arduino environment. Moving on you will also learn how to work on the digital and analog I/O, establish serial communications with autonomous systems, and integrate with electronic devices. By the end of the book, you will be able to make basic projects such as LED cube and smart weather system that leverages C.

What you will learn
  • Play with mathematical operations using C
  • Use logical operations and loops to play with LEDs and the Arduino board
  • Create custom functions using C and connect an SD card to the Arduino
  • Use Object-oriented Programming to connect a GSM module to the Arduino board
  • Play with an LCD board and Servo using standard Arduino libraries
  • Build projects using Arduino such as a LED cube, a smart weather system, and home security
  • Identify and fix common errors on an Arduino board

Sunday, March 19, 2017

Arduino Programming with .NET and Sketch

Arduino Programming with .NET and Sketch

Leverage .NET and Sketch in Arduino development implementation and integrate it into your .NET program.

There are many Arduino models and compatible shields that can be used in Arduino boards. Integrating between an Arduino platform and .NET technology or Sketch can produce more advantages. Arduino Programming using .NET and Sketch shows readers how to do so with practical Arduino projects, such as preparing a development environment, performing sensing and actuating with external devices, implementing Windows Remote Arduino and building a simple IoT program.

Use this quick reference to learn the basics of the Arduino platform for multiple models and start your Arduino programming in .NET and Sketch today.

What You'll Learn:
  • Learn the basics of the Arduino platform
  • Prepare and set up Arduino development
  • Develop Arduino program using .NET and Sketch 
  • Perform sensing and actuating on Arduino boards
  • Implement Windows Remote Arduino
  • Build a simple IoT program
Who This Book Is For:

.NET and Sketch developers who want to learn Arduino programming.


Tuesday, February 21, 2017

Arduino TIAN Development Workshop

Arduino TIAN Development Workshop

Arduino TIAN is a development tool with enabling IoT platform to accelerate your project. This book helps you to get started with Arduino TIAN. The following is highlight topics in this book:
* Preparing Development Environment
* Getting Started with Arduino TIAN
* Arduino TIAN Sketch Programming
* Arduino TIAN Linux Programming
* Working with Bluetooth on Arduino TIAN
* Building IoT Program for Arduino TIAN
* Energy Saving and RTC Libraries

Saturday, February 11, 2017

Building Arduino PLCs: The essential techniques you need to develop Arduino-based PLCs

Building Arduino PLCs: The essential techniques you need to develop Arduino-based PLCs

Learn the fundamentals of PLCs and how to control them using Arduino software to create your first Arduino PLC. You will learn how to draw Ladder Logic diagrams to represent PLC designs for a wide variety of automated applications and to convert the diagrams to Arduino sketches.

A comprehensive shopping guide includes the hardware and software components you need in your tool box. You will learn to use Arduino UNO, Arduino Ethernet shield, and Arduino WiFi shield.

Building Arduino PLCs shows you how to build and test a simple Arduino UNO-based 5V DC logic level PLC with Grove Base shield by connecting simple sensors and actuators. You will also learn how to build industry-grade PLCs with the help of ArduiBox.

What You'll Learn
  • Build ModBus-enabled PLCs
  • Map Arduino PLCs into the cloud using NearBus cloud connector to control the PLC through the Internet
  • Use do-it-yourself light platforms such as IFTTT
  • Enhance your PLC by adding Relay shields for connecting heavy loads
Who This Book Is For 

Engineers, designers, crafters, and makers. Basic knowledge in electronics and Arduino programming or any other programming language is recommended.

Tuesday, January 17, 2017

Monday, January 2, 2017

Building Wireless Sensor Networks Using Arduino (Community Experience Distilled)

Leverage the powerful Arduino and XBee platforms to monitor and control your surroundings

Building Wireless Sensor Networks Using Arduino (Community Experience Distilled)

About This Book
  • Build your own low-power, wireless network using ready-made Arduino and XBee hardware
  • Create a complex project using the Arduino prototyping platform
  • A guide that explains the concepts and builds upon them with the help of examples to form projects
Who This Book Is For
This book is targeted at embedded system developers and hobbyists who have some working knowledge of Arduino and who wish to extend their projects using wireless connectivity.

What You Will Learn

  • Interact with XBee boards using the XCTU program on Windows, OS X, or Linux
  • Make your Arduino boards communicate wirelessly, using XBee modules in the advanced API mode
  • Centrally collect and store measured sensor data, in the cloud or your own database
  • Connect the coordinator Arduino to the Internet and send data to web services
  • Control your environment automatically, based on sensor input from your network
  • Interact with off-the-shelf ZigBee Home Automation devices
  • Make your devices battery-powered and let them sleep to get months or even years of battery life

In Detail
Arduino has been established as the de facto standard microcontroller programming platform, being used for one-off do-it-yourself projects as well as prototypes for actual products. By providing a myriad of libraries, the Arduino community has made it very easy to interact with pretty much any piece of hardware out there. XBee offers a great range of low-power wireless solutions that are easy to work with, by taking all of the complexity of wireless (mesh) networking out of your hands and letting you focus on what to send without worrying about the how. Building wireless sensor networks is cost-effective as well as efficient as it will be done with Arduino support.

The book starts with a brief introduction to various wireless protocols, concepts, and the XBee hardware that enables their use. Then the book expands to explain the Arduino boards to you, letting them read and send sensor data, collect that data centrally, and then even control your home from the Internet. Moving further more advanced topics such as interacting through the standard Zigbee Home Automation protocol, or making your application power-efficient are covered. By the end of the book, you will have all the tools needed to build complete, real-world solutions.

Style and approach
A hands-on guide, featuring a single home automation project that can be built as described or with endless variations. Every step is illustrated with complete examples and screenshots, allowing you to build the examples swiftly.