Showing posts with label ESP03. Show all posts
Showing posts with label ESP03. Show all posts

Friday, March 20, 2015

Publish data from your ESP8266 to thingspeak.com

On this posts ( post#1, post#2) I've presented how to create a channel, fields, API KEYS on thingspeak.com

Now will publish some data from ESP8266 to thingspeak.com. Can be any kind of data, from
temperature, humidity, voltage you name it. As long as it has a value, can be published.

Add following  lines after the include statements. (Can use the blinky code as skeleton).

#include "espconn.h" 
LOCAL struct espconn *pCon = NULL;
LOCAL my_count = 0;
LOCAL your_value = 33;




Add the following code in the user_init() function.

const char ssid[32] = "my_home_ssid";
const char password[32] = "my_home_password";

struct station_config stationConf;

wifi_set_opmode( STATION_MODE );
os_memcpy(&stationConf.ssid, ssid, 32);
os_memcpy(&stationConf.password, password, 32);
wifi_station_set_config(&stationConf); 
wifi_station_connect();
//connect to the previous pCon created structure
int ret = 0;
ret = espconn_connect(pCon);

if(ret == 0) 
      INFO("espconn_connect OK!\r\n");
else
{
      //INFO("espconn_connect FAILED!\r\n");  
      char *fail;
      os_sprintf(fail, "%d \r\n", ret);
      //INFO(fail);
      //clean up allocated memory
      if(pCon->proto.tcp)
          os_free(pCon->proto.tcp);
      os_free(pCon);
      pCon = NULL;
} 

Add this code in a timer function like in this example:

pCon = (struct espconn *)os_zalloc(sizeof(struct espconn));
if (pCon == NULL)
{
        os_printf("pCon ALLOCATION FAIL\r\n");
        return;
}

pCon->type = ESPCONN_TCP;
pCon->state = ESPCONN_NONE;
    
pCon->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));
pCon->proto.tcp->local_port = espconn_port();
//set up the server remote port
pCon->proto.tcp->remote_port = 80;

//set up the remote IP
uint32_t ip = ipaddr_addr("184.106.153.149"); //IP address for thingspeak.com
os_memcpy(pCon->proto.tcp->remote_ip, &ip, 4);

//set up the local IP
struct ip_info ipconfig;
wifi_get_ip_info(STATION_IF, &ipconfig);
os_memcpy(pCon->proto.tcp->local_ip, &ipconfig.ip, 4);

//register publish_thingspeak_connect_cb that will be called when the
//connection with the thingspeak is done. In this call back function
// will actualy do the data sending
espconn_regist_connectcb(pCon, publish_thingspeak_connect_cb);



where the callback function is:


static void ICACHE_FLASH_ATTR publish_thingspeak_connect_cb(void *arg)
{
  //INFO("========>publish_thingspeak_connect_cb\r\n");
  my_count++;

  struct espconn *pespconn = (struct espconn *)arg;

  char payload[128];

  char field1[10];
  char field2[10];

  os_sprintf(field1, "%d", your_value);
  os_sprintf(field2, "%d", my_count);

  os_sprintf(payload, "GET /update?  api_key=YOUR_THINGSPEAK_API_KEY&field1=%s&field2=%s\r\n", field1, field2);

  espconn_sent(pespconn, payload, strlen(payload));
  
}

and need to be added before the user_main function.

Change my_count and your_value with your data. 

Notes:

1. The time between to posts on thingspeak.com must be greater then 15 seconds.
2. Up to 8 fields can be used to post data on thingspeak.com





Thursday, March 19, 2015

Example: Blink a LED

Like in the Arduino case one of the first thinks to try it is to blink an LED.

The following link contains the code for blink an LED.

Materials:

  • ESP-01 - or other version 
  • LED 
  • SERIAL to USB

If you have my setup described here 

1. put the the archive into this directory

/opt/Espressif/ESP8266_SDK   

2. untar the file

tar -xvf blinky.tar

3. enter in the app directory

cd blinky

4. compile the code

make clean ; make.

5. Upload the resulting files ( from the firmware directory) to your ESP after this steps

5.1 Unplug the VCC power pin
5.2 Connect the GPIO0 pin to ground
5.3.Use the command to write the firmware

./burnESP


Anatomy of the code

 The main application file is the user_main.c file located in 
/opt/Espressif/ESP8266_SDK/blinky/user

The file content is:


#include "ets_sys.h"
#include "osapi.h"
#include "gpio.h"
#include "os_type.h"
#include "user_config.h"

#define user_procTaskPrio        0
#define user_procTaskQueueLen    1
os_event_t    user_procTaskQueue[user_procTaskQueueLen];
static void user_procTask(os_event_t *events);

static volatile os_timer_t some_timer;


void some_timerfunc(void *arg)
{
    //Do blinky stuff
    if (GPIO_REG_READ(GPIO_OUT_ADDRESS) & BIT2)
    {
        //Set GPIO2 to LOW - TURN OFF the LED
        gpio_output_set(0, BIT2, BIT2, 0);
    }
    else
    {
        //Set GPIO2 to HIGH - TURN ON the LED
        gpio_output_set(BIT2, 0, BIT2, 0);
    }
}

//Do nothing function
static void ICACHE_FLASH_ATTR  user_procTask(os_event_t *events)
{
    os_delay_us(10);
}

//Init function 
void ICACHE_FLASH_ATTR user_init()
{
    // Initialize the GPIO subsystem.
    gpio_init();

    //Set GPIO2 to output mode
    PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2);

    //Set GPIO2 low
    gpio_output_set(0, BIT2, BIT2, 0);

    //Disarm timer
    os_timer_disarm(&some_timer);

    //Setup timer
    os_timer_setfn(&some_timer, (os_timer_func_t *)some_timerfunc, NULL);

    //Arm the timer, &some_timer is the pointer 1000 is the fire time in ms
    //0 for once and 1 for repeating timer
    os_timer_arm(&some_timer, 1000, 1);
    
    //Start os task
    system_os_task(user_procTask, user_procTaskPrio,user_procTaskQueue, user_procTaskQueueLen);
}


and is pretty much self explanatory.

1. Include the necessary headers. See that user_config.h is empty so if you can use this app as a skeleton for your future applications. 

2. In user_init() function the GPIO is initialized, GPIO2 is set up as an output pin and is set
to 0 (LOW, GND).

3. A timer is defined (some_timer) and initialized and the  callback function is set to be called every 1000ms (1sec) interval. 

4. Callback function some_timerfunc is doing all the stuff, if the LED is ON turn it to OFF,
otherwise turn the LED ON.


If you want to add extra functionality check this post for how to have arduino like functions
to manipulate your GPIO. 

Happy codding !!! 

Thursday, March 12, 2015

Arduino function for ESP8266

        If programming the GPIO is hard for you as a beginner but you are familiar with Arduino functions, the following functions can be used as have the same name as in the Arduino IDE.

First define some data in an .h file.

#define HIGH 0x1
#define LOW 0x0
#define INPUT 0x1
#define OUTPUT 0x0
                                                   /*   GPIO | SDK board    |       */
                                                   /*   --------------------|       */
int gpio_pin_register[16] = {PERIPHS_IO_MUX_GPIO0_U,    // 0  gpio 0        | 
                             PERIPHS_IO_MUX_U0TXD_U,    // 1  gpio 1        | 
                             PERIPHS_IO_MUX_GPIO2_U,    // 2  gpio 2        | 
                             PERIPHS_IO_MUX_U0RXD_U,    // 3                |
                             PERIPHS_IO_MUX_GPIO4_U,    // 4  gpio 4        | 
                             PERIPHS_IO_MUX_GPIO5_U,    // 5  gpio 5 buzzer | 
                             PERIPHS_IO_MUX_SD_CLK_U,   // 6                |
                             PERIPHS_IO_MUX_SD_DATA0_U, // 7                |
                             PERIPHS_IO_MUX_SD_DATA1_U, // 8                |
                             PERIPHS_IO_MUX_SD_DATA2_U, // 9  gpio 9        | 
                             PERIPHS_IO_MUX_SD_DATA3_U, // 10 gpio 10       | 
                             PERIPHS_IO_MUX_SD_CMD_U,   // 11               |
                             PERIPHS_IO_MUX_MTDI_U,     // 12 gpio12  blue  | 
                             PERIPHS_IO_MUX_MTCK_U,     // 13 gpio13  green | 
                             PERIPHS_IO_MUX_MTMS_U,     // 14 gpio14  white | 
                             PERIPHS_IO_MUX_MTDO_U};    // 15 gpio15  red   | 
                             

#define GPIO_PIN_ADDR(i)    (GPIO_PIN0_ADDRESS + i*4)


Now the Arduino like functions can be added:

/********************************************************************
* FunctionName: pinMode
* Description : set up a pin mode.
* Parameters  : pin: pin mumber
*             : mode 0 for OUTPUT or 1 for INPUT
*             : pullup 0 for pullup DISABLED and 1 for pullup ENABLED
*             : pulldown not yet supported
* Returns     : None                                                     
*********************************************************************/

void ICACHE_FLASH_ATTR pinMode(uint8_t pin, uint8_t mode, uint8_t pullup) {
    if ((0x1 << pin) & 0b110101) {
        PIN_FUNC_SELECT(gpio_pin_register[pin], 0); //0,2,4,5
    } else {
        PIN_FUNC_SELECT(gpio_pin_register[pin], 3);
    }
    PIN_PULLDWN_DIS(gpio_pin_register[pin]);
    if(pullup)
      PIN_PULLUP_EN(gpio_pin_register[pin]);
    else  
      PIN_PULLUP_DIS(gpio_pin_register[pin]);
    if (mode) {
        GPIO_REG_WRITE(GPIO_ENABLE_W1TC_ADDRESS, 1<<pin); // GPIO input
    } else {
        GPIO_REG_WRITE(GPIO_ENABLE_W1TS_ADDRESS, 1<<pin); // GPIO output
    }
}


Example:
pinMode(0, OUTPUT, 0); //is setting the GPIO 0 as an OUTPUT with pullup disabled

If you want to control also the pulldown add an extra parameter and call the 
PIN_PULLDWN_DIS(gpio_pin_register[pin])for disable and PIN_PULLDWN_EN(gpio_pin_register[pin])for pulldown enable.


Next function are the well known Arduino function for read and write:

/********************************************************************
* FunctionName: digitalWrite
* Description : use to set up HIGH or LOW on a GPIO pin
* Parameters  : pin: pin mumber
*             : state HIGH or LOW
* Returns     : None                                                     
*********************************************************************/

void ICACHE_FLASH_ATTR 
digitalWrite(uint8_t pin, uint8_t state) {
    if (state) {
        GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, 1<<pin); // set GPIO pin high
    } else {
        GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, 1<<pin); // set GPIO pin low
    }
}
/********************************************************************
* FunctionName: digitalRead
* Description : use to set up HIGH or LOW on a GPIO pin
* Parameters  : pin: pin mumber
* Returns     : 1 if pin is HIGH or 0 if pin is LOW                                                     
*********************************************************************/

int ICACHE_FLASH_ATTR 
digitalRead(uint8_t pin) {
    return (GPIO_REG_READ(GPIO_OUT_ADDRESS)>>pin) & 1;
}



Example:

digitalWrite(0, HIGH); //set HIGH the GPIO 0 pin

int gpio_state = digitalRead(0); will return 1 if the GPIO 0 pin's is HIGH or 0 if is LOW

If you save your .h file in the include directory, just use #include "your_file_name.h" in your user_main.c.


For controlling GPIO16 see this post.








Tuesday, March 10, 2015

Usefull tools #2

If you want a nice gauge to display some data you can use the google's one with the help from thingspeak.com.


Thingspeak.com Plugin

For this gauge we will need to read data from thingspeak.com and this require an API Read Key that can be generated from the API KEYS menu.



Now go to the Plugin menu from the Main Menu:



and click on "New Plugin"


and select the Google Gauge and "Create Plugin".

Now you can modify the Javascript with your channel id and the READ API Key:


  // set your channel id here
  var channel_id = 87654;
  // set your channel's read api key here if necessary
  var api_key = 'Q68B3YMORI9S49JJ';
  // maximum value for the gauge
  var max_gauge_value = 100;
  // name of the gauge

  var gauge_name = 'My_gauge_name';

To include the new created gauge in other page you can use the HTML TAG <IFRAME>.

<iframe width="330" height="360" style="border: 1px solid #cccccc;" src="http://api.thingspeak.com/plugins/2345" ></iframe>



Post man #1 - 3V3 relays board

Today I've received a new order from aliexpress.com.

A board with four relays working on 3V3.




I will use the relays to control the irrigation system that is now driven by a Raspberry Pi.

So, the ESP201 will replace the Raspberry Pi that did a very good job in the last three years.

I am using the 3V3 relays just for fun, I've tested the ESP201 with 5V relays and are working normally from my point of view.  



Thursday, March 5, 2015

Making your own environment for ESP8266.

If you don't want to use my setup described here, you can make your own setup using your own distribution.

You can make your own environment for compiling your code or the demo code for the ESP8266.

Step 1.

Download ova image  ( lunbuntu 14.04) for VirtualBox or install your preferred Linux distribution.

User is esp8266 and password is  espressif

sudo apt-get install git autoconf build-essential gperf bison flex texinfo libtool libncurses5-dev 

wget gawk libc6-dev python-serial libexpat1-dev

Step 2.

sudo mkdir /opt/Espressif

Step 3.

sudo chown esp8266 /opt/Espressif/

Step 4.

cd /opt/Espressif

Step 5.

git clone -b lx106 git://github.com/jcmvbkbc/crosstool-NG.git

Step 6.

cd crosstool-NG/

./bootstrap && ./configure --prefix=`pwd` && make && make install

Step 7.

./ct-ng xtensa-lx106-elf

Step 8.

./ct-ng build

Note: It takes about 25 minutes !!!!!!!

Step 9.

Edit the .profile file from /home/esp8266 and add the line

PATH="$HOME/bin:/opt/Espressif/crosstool-NG/builds/xtensa-lx106-elf/bin:$PATH"

Step 10.

cd /opt/Espressif

wget -O esp_iot_sdk_v0.9.5_15_01_23.zip https://github.com/esp8266/esp8266-

wiki/raw/master/sdk/esp_iot_sdk_v0.9.5_15_01_23.zip

Note: is the SDK from 23 Jan 2015. Verify if there is a new one.

Step 11.

unzip esp_iot_sdk_v0.9.5_15_01_23.zip 

mv esp_iot_sdk_v0.9.5 ESP8266_SDK/

Step 12.

cd /opt/Espressif/ESP8266_SDK

wget -O lib/libc.a https://github.com/esp8266/esp8266-wiki/raw/master/libs/libc.a

wget -O lib/libhal.a https://github.com/esp8266/esp8266-wiki/raw/master/libs/libhal.a

wget -O include.tgz https://github.com/esp8266/esp8266-wiki/raw/master/include.tgz

tar -xvzf include.tgz

rm include.tgz

Step 13.

cd /opt/Espressif

git clone https://github.com/themadinventor/esptool esptool-py

chown -R esp8266 crosstool-NG/

sudo ln -s $PWD/esptool-py/esptool.py crosstool-NG/builds/xtensa-lx106-elf/bin/

Step 14.

The SDK esp_iot_sdk_v0.9.5_15_01_23.zip has a directory named Document with some pdf files about API, AT commands and release notes.

Step 15. 

Copy the "at" directory from /opt/Espressif/ESP8266_SDK/examples and compile it

cp -R /opt/Espressif/ESP8266_SDK/examples/at /opt/Espressif/ESP8266_SDK/

cd /opt/Espressif/ESP8266_SDK/at

make clean

make 

The result resides in the /opt/Espressif/ESP8266_SDK/bin directory

Flashing the code. Note that the above command is on long line. You can put the command into a file flashEsp, give that file executable rights and use it with ./flashEsp

sudo /opt/Espressif/esptool-py/esptool.py --port /dev/ttyUSB0 write_flash 0x3C000 /opt/Espressif/ESP8266_SDK/bin/blank.bin 0x00000 /opt/Espressif/ESP8266_SDK/bin/eagle.flash.bin 0x40000 /opt/Espressif/ESP8266_SDK/bin/eagle.irom0text.bin OR /opt/Espressif/esptool-py/esptool.py -p /dev/ttyUSB0 write_flash 0x40000 ../bin/eagle.irom0text.bin write_flash 0x00000 ../bin/eagle.flash.bin


I hope I didn't missed any step.



Use my ESP8266 environment !!!

User ESP8266
password espressif

Let's see how you can compile our first example of code.

To do this download the virtual box ova from my drive.

Apply this ova file to a Virtual Box.

Start the virtual machine

go to /opt/Espressif/ESP8266_SDK/ where there are two directories with examples:

IoTDemo - a web server controlling  some GPIO's
at - build a custom AT command along with all command that are supportded by the at library


go to /opt/Espressif/ESP8266_SDK/IoTDemo/
make clean
make

two files are generated into the /opt/Espressif/ESP8266_SDK/bin directory.
!!!
No boot needed.
Generate eagle.flash.bin and eagle.irom0text.bin successully in folder bin.
eagle.flash.bin-------->0x00000
eagle.irom0text.bin---->0x40000
!!!

 Use those files and the optional blank image blank.bin or you can use this command
to write the files.

sudo /opt/Espressif/esptool-py/esptool.py --port /dev/ttyUSB0 write_flash 0x3C000 /opt/Espressif/ESP8266_SDK/bin/blank.bin 0x00000 /opt/Espressif/ESP8266_SDK/bin/eagle.flash.bin 0x40000 /opt/Espressif/ESP8266_SDK/bin/
eagle.irom0text.bin

Write the files on ESP-01.
1. Power off the ESP-01
2. Connect GPIO0 to GND
3. Power on the ESP-01
4. Burn firmware

Write the files on ESP201 Dev Board.
1. Power off the ESP-201
2. Keep pressed S2 and power the board
3. Release the S2 switch
4. Burn firmware

Notes:


  1. In /opt/Espressif/ESP8266_SDK/document/ there are tow directories English an Chinese with document about the SDK fucntion, AT command. Spend some time looking into them.
  2. In the Virtual Box image I've added the moserial application that can be used to see the debug information from ESP.
  3. Launch moserial with: sudo moserial &
  4. If Software Updater is bugging you, do not update. You are just fine.





Wednesday, March 4, 2015

ESP8266 Wireless Wifi Module Develop Board 8266 SDK Development Chip

Other interesting board is this board from Electronic Gadget World, a shop on aliexpress.com.

If you can not find this board you can buy other good development boards like:

1. Development board with ESP8266 module and power supply.
2. Battery operated development board
3. Small form factor development board

The parcel contained one ESP201  an SDK Development board and a DHT11 sensor. No cables or power supply. I've ordered two extra ESP201 so I've replaced the faulty one with a good ESP201.

As you can see in the image there are two USBs. The microUSB located on the top right is just for powering the board. The other usb, a type B USB can be used to power the board, and to write firmware to ESP201 flash. The usb to serial on board is a CH340G chip. My win7 didn't complain about it, I was able to write the flash to ESP201.
The only problem is that the transfer was done at 9600 or less (like 5 minute for 200k), after I've modified in the DeviceManager the speed for the port, the transfer rate was increased. But this happened only once, so I gave up using the CH340G chip for now. I've removed the red jumpers and I used my old Prolific USB/serial.

I'll reinstall the drivers for CH340G chip with this one  later and I'll see if helps.


ESP201 SDK development board

Now let's talk about the connections. As you can see the dev board has:


  • a relay
  • a RGB led
  • a white led ( almost under the RGB led which is above the buzeer)
  • DHT11 
  • buzzer
  • two switched S2 and S3
  • a variable rezistor for ADC ( on the left of relay ) connected to ADC pin.
  • a 5v to 3v3 convertor 
  • a main switch in the right upper corner (this switch is just for ESP201 board I guess, I have the impression that the CH340G is still receiving power even the switch is off).


DIP functionality
On the PCB near the DIP switch there are the values :


  • R - should be the RED led from the RGB connected to the IO15 pin. Putting the R DIP to ON will light RED if the GPIO15 is HIGH.
  • G - GREEN led from RGB led is connected to IO13. Putting the G DIP to ON will light GREEN if the GPIO13 is HIGH.
  • B - BLUE led from RGB led is connected to IO12. Putting the B DIP to ON will light BLUE if the GPIO12 is HIGH
  • W - WHITE led located almost under RGB led is connected to the IO14 pin. Putting HIGH on GPIO14 and DIP switch on ON will light the WHITE led
  • J - relay pin connected to IO16 ( which is always HIGH - I have no idea why . This behavior and the RED led that is not working can be because I have a bad board or the design for all the boards is wrong. Connecting the IO16 to GND (not recommended) will stop the relay, otherwise it will be ON all the time the J DIP pin is ON.
  • B - BUZZER connected to IO5 pin throuch B DIP switch. Having GPIO5 HIGH and B on DIP switch ON will prove that the buzzer is working.
  • K1 - I assume is connected to S2
  • K2 - I assume is connected to S3.


A schematics on a napkin will look like this one:


Napkin schematics :-)

And thanks to Scott Snowden and jwbr from http://www.bpower.nl/ there is a complete schematics of the board.


Wifi Module Develop Board 8266 schematics




On IO4 is connected the DHT11 sensor. I didn't use it because I have a DHT22 which is more accurate.


How to write flash.

1.Power off the board.

2.Keep S2 pressed and power on the board using the switch located in the right top of the board.
3.Now you can write the flash from the ESP201 board.


Conclusions:

It is a very good board, no issues found. If you want a rapid development board you can buy this one.

And the final config will look like in this picture (2 external relays, 2 external LEDs DHT22). Pretty crowded. Breadboard is just for GND.




UPDATE1: See what to do to have access on the GPIO15 ( Red led from RGB) - HERE

UPDATE2: See what to do for controlling the relay connected on the XPD / GPIO16 - HERE

UPDATE3: A IoT plug based on ESP-01 - HERE.   A lawn irrigation IoT based on this board is coming soon.

UPDATE4: Now I have a unix cron functionality on my ESP8266 chips.

UPDATE5: MQTT broker running on ESP8266




Sunday, March 1, 2015

ESP8266 - part one

As I said on the previous post, one device that captured my attention is the ESP8266EX chip that is an wireless SoC and it has GPIO, I2C, ADC (0..1V), SPI, PWM.

It runs at 80MHz and has 32KBytes of instruction RAM, 96KBytes of data RAM and 64KBytes boot ROM.

It has a RISC architecture and the core is a 106micro Diamond Standard core (LX3) made by Tensilica and is produced by Espressif.

Specs from the producer site: 


  • 802.11 b/g/n
  • Wi-Fi Direct (P2P), soft-AP
  • Integrated TCP/IP protocol stack
  • Integrated TR switch, balun, LNA, power amplifier and matching network
  • Integrated PLLs, regulators, DCXO and power management units
  • +19.5dBm output power in 802.11b mode
  • Power down leakage current of <10uA
  • Integrated low power 32-bit CPU could be used as application processor
  • SDIO 1.1/2.0, SPI, UART
  • STBC, 1×1 MIMO, 2×1 MIMO
  • A-MPDU & A-MSDU aggregation & 0.4ms guard interval
  • Wake up and transmit packets in < 2ms
  • Standby power consumption of < 1.0mW (DTIM3)
The chip from the above picture is the old version. The new one is ESP8266EX that is now on all boards that I've seen for sales.

ESP8266Ex is connected on most boards to a SPI flash memory like in the following schematic:





IoT first post

You hear a lot lately about Internet of Things, but what really is it? Until now connections between various devices were so called machine to machine (M2M). They were used to connect devices remotely over Internet usually over GSM networks. Making a network of them and controlling them was not a easy task to do. Internet of Things (IoT) is moving the M2M to a different level where the machines will be closed to the humans and machine to machine will be transformed to humans to machines and machines to humans.

The Internet as we know it today will be transformed in the next years so every device will get Internet access no matter if is your oven, fridge, TV or bathroom scale. You will be able to control them directly over the Internet or a unit that exist in your home will take decisions based on your needs or behavior.

Every device will be in a global network, thanks to the IPv6 protocol. Until the transition to IPv6 is globally you need to stick with the IPv4.

Basically all the devices that now are running from batteries or directly connected to your wall plug will have the ability to be "on the Internet".

According to Wikipedia IoT products can be classified broadly into five different categories: smart wearable, smart home, smart city, smart environment, and smart enterprise.

One device that came the market in 2014 is the ESP8266EX chip. More for this chip in the next posts.