NodeMCU using Dweet io

Interfacing NodeMCU with Freeboard IOT dashboard using dweet io.

A brief tutorial on posting data to IOT dashboard using NodeMCU using dweet io messaging service.

Requirements:

  1. NodeMCU with micropython firmware (Refer previous post for uploading micropython firmware to nodemcu)

dweet.io is simple publishing and subscribing for machines, sensors, devices, robots, and gadgets (we just call them things). We call published messages ‘dweets’. It’s helpful to think of dweet.io as a Twitter for things, in fact.

We assign each thing a unique thing name (or you can assign your own if it’s available). Then a thing may be subscribed to, which is analogous to following someone in twitter.

Go through https://dweet.io/faq for more…

NodeMCU using Dweet io

The below code snippet connects to the wifi hotspot and post the value read over adc of nodeMCU every 5 seconds to the dweet io dashboard.

I am using a micropython http client library from https://github.com/balloob/micropython-http-client

Git clone the above library.

import network
import machine
import socket
import http_client
import time

#Wifi Config
wlan = network.WLAN(network.STA_IF)        #configure for station interface
wlan.active(True)    #Enable module as station

#Connect
if not wlan.isconnected():
    print('connecting to network...')
    wlan.connect('WIFI-SSID', 'PASSWORD')
    while not wlan.isconnected():
        pass
print('network config:', wlan.ifconfig())

time.sleep(5)
adc = machine.ADC(0)

while(1):
    value = adc.read()
    thing = 'YOUR-THING-NAME'
    url = 'http://dweet.io/dweet/for/'+thing+'?temp='+str(value)
    print(url)
    r=http_client.post(url)
    print(r.json())
    time.sleep(5)

 

In the above code temp =str(value) is a key value pair. You can change the key as you like.

See to that you have change the wifi ssid name and password and your thing name, and save it as main.py so that nodemcu starts running the code after initializing.

Now upload the http_client.py and main.py to nodemcu using adafruit’s ampy.

Refer previous post for procedure

the cmd:

 

ampy -p /dev/ttyUSB0 put http_client.py

ampy -p /dev/ttyUSB0 put main.py

 

Restart NodeMCU and you are done.

The NodeMCU connects to WIFI hotspot and starts publishing values to dweet io, which can been seen via the below url

https://dweet.io/follow/your-thing-name

 

For custom widgets like graphs, guages and string, signup with freeboard and add widgets that suit your purpose.

Add your datasource on the dashboard with type dweet.io and thing name as your-thing-name.

 

 

Now add widgets and select the type of widget to want and the value eg. datasources[“Dweet”][“temp”]

 

You can see the guage changes for every post from NodeMCU.

Note: I am publishing data to dweet io over unsecured connection. The http library i use dont support https. There is a micropython version of urllib that support https.

NodeMCU socket interface

NodeMCU client server communication over WIFI using python socket.

NodeMCU a low cost WIFI module, built with ESP8266 wifi chip is well known for its ease of use and features. The module is available online for about 400INR. The module with AT commands firmware makes useless when it is without CPU to write and read commands to it. It has a Lua firmware and micropython firmware support for easy working without CPU. I go with micropython firmware as i believe python will be more familiar than Lua as an electronic enthusiast. The below example is a client server communication between a PC and NodeMCU socket running micropython.

Requirements:

Git, python, PC, NodeMCU

 

Esptool: Firmware flasher for esp8266 module. Follow the procedure in the below link to install esptool

https://github.com/themadinventor/esptool

Micropython firmware: https://www.dropbox.com/s/pf3wgv7l9vpt3h9/firmware-combined.bin?dl=0

Upon successful installation, connect NodeMCU to PC and run the below command

python esptool.py write_flash --flash_size=8m 0 firmware-combined.bin

Esp8266 flasher

Restart NodeMCU and connect corresponding COM port with 115200 baudrate.

this prompt will show up: >>>

The below python code explains nodeMCU socket programming by transmitting adc value (A0 pin of NodeMCU) periodically every 5 sec with a timer interrupt, to the server and receives data from server.

I am using my PC as server with port 8266 opened, make sure the port you are running the socket is open.

Linux users can do this from sudo ufw allow 8266

Windows user should do it from their firewall program.

 

After flashing firmware the NodeMCU by default runs as access point with ip address 192.168.4.1

We set the module in station mode, so that it can connect to a wifi hotspot and access internet. By the way a remote server can be accessed.

Copy the code and save it to your PC as main.py.

NodeMCU by default runs boot.py at startup followed by main.py

 

import network
import machine
import socket

#Wifi Config
wlan = network.WLAN(network.STA_IF)        #configure for station interface
wlan.active(True)    #Enable module as station

#Connect
if not wlan.isconnected():
    print('connecting to network...')
    wlan.connect('essid', 'password')
    while not wlan.isconnected():
        pass
print('network config:', wlan.ifconfig())

#ADC
adc = machine.ADC(0)

#Socket
s = socket.socket()
addr = socket.getaddrinfo("192.168.0.100", 8266)[0][-1]

#Transmit adc value periodically for every 5 sec
def transmit():
    try:
        value = adc.read()
#        print(str(value))
        s.send(str(value))
        s.send("\r\n")
    except:
        s.close()

#Timer Interrupt
tim = machine.Timer(-1)    #Enable timer interrupt
tim.init(period=5000, mode=machine.Timer.PERIODIC, callback=lambda t:transmit())    #Configures a periodic interrupt for every 5 sec

s.connect(addr)
try:
    while True:
        data = s.recv(5)
        print(data)
except:
    s.close()

 

To upload the file to NodeMCU install this app from adafruit github repo

https://github.com/adafruit/ampy

storing the file to NodeMCU is done by

ampy -p COMPORT put main.py

Upon completion open the port 8266 in PC using below software.

http://www.hw-group.com/products/hercules/index_en.html

set option tcp server and port 8266

 

Restart the nodeMCU and you should find something like this in your nodemcu serial terminal. In this case the ipaddress of NodeMCU is 192.168.0.106

NodeMCU Connected to AP

On the server side the Hercules software will start receiving messages.

and you are done.

I used netcat on server side hercules will be more user friendly.

NEC IR decoder with FPGA

NEC IR decoder with FPGA

This post explains about decoding a commonly known IR protocol, the NEC. The design decodes 8 bit address and 8 bit data standard NEC protocol, using verilog HDL on an FPGA. I am using a de0 nano board, with quartus II running on a windows 10 PC. The code is compatible with any FPGA board.

The protocol

NEC Pulse train

image courtesy www.sbproject.com

The remote sends a continuous 38khz burst which is read as a high level at the ir receiver like tsop1738, which driver an internal transistor and the output at the ir receiver will be inverted as shown below.

 

First a start pulse of 9ms is transmitted.

Then a sync pulse of 4.5ms is transmitted.

After that an 8 bit address and  its inversion is transmitted

Followed by an 8 bit data and a inversion of the data is transmitted.

 

If the sync pulse is of 2.25ms duration then it is a repeat data. (i.e the key is pressed again or hold down continuously)

 

Each 1 bit is transmitted with a 560us burst and a 840us pause

Each 0 bit is transmitted with a 560us burst and a 560us pause

NEC Train under a logic analyzer

Nec pulse train under logic analyzer

 

From the above picture we derive the fsm for the decoder circuit.

step 1: start a counter when ir input goes low and check it is low for 9ms. START PULSE

step 2: similarly check if ir input is high for 4.5ms. SYNC PULSE

step 3: wait for ir input to go high.(i.e first data bit). fetch the ir input level at 1/3 of total pulse duration 800us.(i.e 560+280 us)

step 4: Repeat step 3 32 times.

step 5: Display the received data on the leds.

Since NEC decoding techniques are discussed enough, i’m not going in depth on the decoding technique. You can find a clear picture of it from the verilog source file.

 

Download the source NEC IR decoder

 

Please feel free to ask your doubts you have regarding the decoder fsm.

16×2 lcd interface with FPGA

16×2 lcd interface with FPGA using verilog HDL

 

This post demostrates a 16×2 lcd interface with FPGA. The demo was tested with altera de0 nano board and can be ported to any fpga board by changing the pin configuration. The design was made with finite state machines such that the code understandable, since it is similar to the program flow followed in displaying 16×2 LCD with a microcontroller.

Since most of us are familiar with 16×2 LCD interfacing, i am excluding the explanation part.

 

Driver description.

The 16×2 lcd driver fetches the command/character to be applied to the LCD and the appropriate RS signal and present the LCD pins with an 1ms enable latch pulse, 8 bit data signal and register select signal.

Demo description.

The demo displays Hello world! from the commands and characters stored in the memory. The 16×2 driver can be customized to display characters from external device.

The LCD commands such as clear goto home etc. can be set as parameter instead of storing them in memory for easy access.

module lcd_16x2_8bit (
    input [7:0]data,            
    input clk, rst, start, cd,    
    output [7:0]lcd_data,
    output rs, en,
    output reg done_tick
);

localparam [2:0]    idle    =    3'b000,
                    load    =    3'b001,
                    wait1    =    3'b010,
                    wait2     =     3'b011,
                    done    =    3'b100;

reg [2:0]state_reg,state_next;
reg [15:0]count_reg;
wire [15:0]count_next;
reg [7:0]lcd_data_reg, lcd_data_next;
reg rs_reg, rs_next, en_reg, en_next, c_load_reg, c_load_next;
wire c_1ms, c_h1ms;

always@(posedge clk, negedge rst)
begin
    if(!rst)
    begin
        state_reg <= idle;
        c_load_reg <= 0;
        en_reg <= 0;
        rs_reg <= 0;
        lcd_data_reg <= 0;
        count_reg <= 0;
    end
    else
    begin
        state_reg <= state_next;
        c_load_reg <= c_load_next;
        en_reg <= en_next;
        rs_reg <= rs_next;
        lcd_data_reg <= lcd_data_next;
        count_reg <= count_next;
    end
end

assign count_next = (c_load_reg)?(count_reg + 1'b1):16'd0;

assign c_1ms = (count_reg == 16'd50000);
assign c_h1ms = (count_reg == 16'd25000);

always@*
begin
    state_next = state_reg;
    rs_next = rs_reg;
    en_next = en_reg;
    lcd_data_next = lcd_data_reg;
    done_tick = 0;
    c_load_next = c_load_reg;
    case(state_reg)
        idle:
        begin
            if(start)
                state_next = load;
        end
        load:
        begin
            state_next = wait1;
            lcd_data_next = data;
            rs_next = cd;
        end
        wait1:
        begin
            c_load_next = 1;
            en_next = 1;
            if(c_1ms)
            begin
                state_next = wait2;
                en_next = 0;
                c_load_next = 0;
            end
        end
        wait2:
        begin
            c_load_next= 1;
            if(c_h1ms)
            begin
                state_next = done;
                c_load_next = 0;
            end
        end
        done:
        begin
            done_tick = 1;
            state_next = idle;
        end
endcase
end
assign lcd_data = lcd_data_reg;
assign en = en_reg;
assign rs = rs_reg;
endmodule

 

16x2 lcd interface FPGA

Download the source files from the below link.

16×2 LCD Hello world Example

Leon3 blink led example on a de0 nano board

Blink LED with Leon3 on DE0 nano board

In this tutorial we will see how to access terasic de0 nano board LEDs (Leon3 blink led example).

Configure the fpga with the default leon3 system

cd grlib-gpl-x.x.x-xxxxx/designs/leon3-terasic-de0-nano

make quartus-prog-fpga

Accessing the LEDs from address maps

grlib-gpl-1.4.1-b4156/designs/leon3-terasic-de0-nano/README.txt

The design has four GRGPIO ports.

GRGPIO0 is connected to board signal GPIO_0[31:0]
GRGPIO1 is connected to board signal GPIO_1[31:0]
GRGPIO2 is connected as follows:

GRGPIO2 line(s)  Direction   Board signal
12:0              <->       GPIO_2[12:0]
15:13            <-         GPIO_2_IN[2:0]
17:16            <->       GPIO_0[33:32]
19:18            <-         GPIO_0_IN[1:0]
21:20            <->       GPIO_1[33:32]
23:22            <-         GPIO_1_IN[1:0]
29:24             ->        LED[5:0]
30                <-         g_sensor_int

grlib-gpl-1.4.1-b4156/doc/grip.pdf

The LED base address can be got from info sys command at the grmon

grmon -altjtag -u

grmon2>info sys

Leon3 blink led example

#define LIM 1000000000

#include <stdio.h>

char* gpio_base = (char*) 0x80000B00;

int main()
{

    int i;
    
    //set direction to all out
    *(gpio_base+0x00000008) = 0x0000003f;
 
    while(1){
      //turn off all
      *(gpio_base+0x00000004) = 0x0000003f;
      printf("Leds are off\n");
      for(i=0;i<LIM;i++);
      //turn on all
      *(gpio_base+0x00000004) = 0x00000000;
      printf("Leds are on\n");
      for(i=0;i<LIM;i++);
      }
}

 

compile the code blink_led.c

sparc-elf-gcc-4.4.2 -O2 -msoft-float blink_led.c -o blink_led.exe

Run the code

open grmon with

grmon -altjtag -u

lo blink_led.exe

run

 

You can see the leds blinking.

Getting started with Leon3 on DE0 nano board

Leon3 on DE0 nano board

This post will help you getting started with Leon3 on DE0 nano board. DE0 nano is a low cost altera board from, which can be bought for around $80 Leon3 was originally designed by the European Space Research and Technology Centre. We can start by downloading source code.

I am using a ubuntu machine with quartus II installed.

Download the source code:

http://www.gaisler.com/index.php/downloads/leongrlib

cd your/working/directory

cp path/to/grlib-gpl-x.x.x-xxxxx.tar.gz ./

Configuring the FPGA:

Open a terminal session and extract the compressed file and browse to path grlib-gpl-x.x.x-xxxxx/designs/leon3-terasic-de0-nano

tar -xzvf grlib-gpl-x.x.x-xxxxx.tar.gz

cd grlib-gpl-x.x.x-xxxxx/designs/leon3-terasic-de0-nano

make quartus

make quartus-prog-fpga

make sure you have altera/quartus/bin in the path with

echo $PATH

Debugger setup

Download grmon2 debugger evaluation version from http://www.gaisler.com/index.php/downloads/debug-tools

cd your/working/directory

cp path/to/grmon-eval-2.x.xx.tar.gz ./

Extract tar -xzvf grmon-eval-2.x.xx-tar.gz

Add grmon-eval folder to the path

export $PATH:/path/to/grmon-eval/linux/bin

Run the debugger with the command

grmon -altjtag -u

 

you will see a prompt

grmon2>

type ‘info sys’ to get detailed report of attached cores

grmon2>info sys

If you get an error libjtag_client.so: cannot open shared object file: No such file or directory.

add altera/quartus/linux to the LD_LIBRARY_PATH

export LD_LIBRARY_PATH="/path/to/altera/quartus/linux"

Compiler setup

Download Bare c compiler from http://www.gaisler.com/anonftp/bcc/bin/linux/

cd your/working/directory

cp path/to/sparc-elf-x.x.x-x.x.xxx.tar.bz2 ./

tar xvjf sparc-elf-x.x.x-x.xxxx.tar.bz2

Save the below code as a hello.c file

#include <stdio.h>

main()
{
printf("Hello World\n");
}

Add compiler to path with

export $PATH:/path/to/sparc-elf-x.x.x/bin

Compile the program with

sparc-elf-gcc-4.4.2 -O2 -msoft-float hello.c -o hello.exe

Running hello world from grmon2

open grmon2

grmon -altjtag -u

 

lo hello.exe

run