Friday 29 July 2016

Hello World with NodeMcu using Lua

I recently come across a another Prototyping Board named as NodeMCU.
From its Official Website Node MCU is
An open-source firmware and development kit that helps you to prototype your IOT product within a few Lua script lines

It runs on Low Cost ESP8266 SoC from Espressif.. and Open Source NodeMCU firmware. We can Program this module using lua,micropython and c. 

First thing to do after you gets your hands on your nodeMCU hardware is to flash new firmware to it..  there are still people working on it.. so it is best to keep it updated.

To flash firmware you need(I am assuming you have nodeMCU Dev Kit with you not generic esp8266 Module)

1.  cp2102 usb to Serial Bridge Drivers  : Download from https://www.pololu.com/docs/0J7/all
2.  Node MCU firmware :  Go to https://github.com/nodemcu/nodemcu-firmware/releases
and Download the nodemcu_float or nodemcu_int

3. NodeMCU Flasher : Download it from https://github.com/nodemcu/nodemcu-flasher
 
 Download the win32 or win64 depending on your system

4.ESPlorer IDE to Program Node Mcu : download it from  http://esp8266.ru/esplorer/ and make sure you have java installed in your system


step 1: Install the cp2102 Driver
step 2: Connect the your nodeMCU board to your PC and note down the COM port
step 3: open the NodeMCU flasher Downloaded earlier
ans select the nodeMCU COM port under operation Menu

step 4: under the config tab select the downloaded nodeMCU firmware by clicking little gear as shown in the image
step 5: go back to the Operation Menu and Click on the Flash Button.. 
You can see the Progress below or go to the log for Messages..

You can see the green tick mark in the NODEMCU TEAM when it us successfully updated the firmware.

step 6: close the flasher application and remove and reinsert power to nodeMCU

Now.. your nodeMCU is ready to accept commands from you

Simple LED On and Off using lua
there are many loaders available for nodeMCU.. i am using ESPlorer which runs on Java

Open the ESPlorar.jar executable program in previously downloaded package

 
 Select the COM port and click Open You can now see that Lower send Button is Activated..

You can send the commands to the nodeMCU using send followed by Command.

The command used are 
1. gpio.mode(pin,mode) : used to set the mode for GPIO pin

mode can be specified as input or output using gpio.INPUT or gpio.OUTPUT

2.gpio.write(pin,value) : used to send low or high value to the pin

value can be specified as gpio.LOW or gpio.HIGH for low or HIGH values

I will use pin 7 (D7), Connect the Anode to D7 and cathode to ground with help of breadboard 

and send the following commands to the nodeMCU one by one (anything followed by " -- " is Comment )

gpio.mode(7,gpio.OUTPUT)
gpio.write(7,gpio.HIGH) -- LED is ON 
gpio.write(7,gpio.LOW) -- LED is OFF

That's it for Now...

Saturday 2 July 2016

RasPi Local Web Server, Database and Posting Data From Arduino To Server

In this Post I will Show How to Setup Local Server , Data Base,Phpmyadmin to Receive the Data from Arduino Master Which is Receiving Data From Other 3 Slave Arduino's
Basic Setup :


First Work On the Arduino Part:
I used I2C Protocol To establish Master Slave Communication Between Arduinos.
Master Arduino Sends the request to the slave for Data For three Arduinos 
newMillis = millis();
if(newMillis - prevMillis >= interval*1000){
prevMillis = newMillis;
requestSlaveA();
delay(100);
requestSlaveB();
delay(100);
requestSlaveC();
}

On Slave Side Upon Receiving Request
void requestCallback(){
int input = analogRead(AnalogInputPin);
// To send multiple bytes from the slave,
// you have to fill your own buffer and send it all at once.
uint8_t buffer[2];
buffer[0] = input >> 8;
buffer[1] = input & 0xff;
Wire.write(buffer, 2);
}


Slave Reads the Value from Analog 0 Pin and Convert the Int into byte with Shifting and "Logical AND" Operation ans Send the value to the Master.
On Master Side The Request Function is Like this:
void requestSlaveA(){
if(Wire.requestFrom(slaveA,byteLength)){
Serial.print('A');
Serial.println(getData());
}else{
Serial.println("EA");
}
}

From Nick Fammon Site : Wire.requestFrom does not return until the data is available (or if it fails to become available). Thus it is not necessary to do a loop waiting for Wire.available after doing Wire.requestFrom.

Upon receiving the Data we call the getData() Function to Parse the Data
int getData(){
int receivedValue = Wire.read() << 8;
receivedValue |= Wire.read();
return receivedValue;
}

we Sent the Parsed data Via Serially To the Raspberry Pi.
On Raspberry Pi Side I Used Python to Receive the Data Serially and Regular Expressions with Python for
Parsing Data

ser = serial.Serial('/dev/ttyACM0') #open the serial Connection between pi and Arduino
while True:
if(ser.inWaiting() > 3) : #If Serial Buffer has More than 3 Bytes
data = ser.readline() # read a Line of Data from Serial Buffer
processData(data) # Call the Function to Read the Data

This Code Receives the Data Serially and call function processData() to Process the Received Data and Pass the Data as Argument.

So we Received the Data. We need to Setup Raspberry pi as Server and Setup Database in to it.
For that Follow these Steps :

1.To Install Apache2 in Raspberry Pi use the Command ;
sudo apt-get install apache2 php5 libapache2-mod-php5
2.After Finished Installing Use the Following Command to Restart the apache2 Server
sudo service apache2 restart
3.After Restarting Check your Pi Ip Configuration with Command
ifconfig
4.Enter the ipNumber in the Web browser in locla lan. you can see Sample Webpage as
It Works
You can Edit the source file Location using
sudo nano /var/www/html/index.html note : You need to Change the Above file before Using It

5.Installing Php5 In Raspberry Pi : use the following command to install the Php
sudo apt-get install php5 libapache2-mod-php5 -y
6.Installing My Sql on Raspberry Pi : Use the Following Command to Install The mySql
sudo apt-get install mysql-server python-mysqldb This will install the mysql server and Python MySQLdb Module Also

7.Installing Php My Admin : use the following Command to Install the Phpmyadmin
sudo apt-get install phpmyadmin
8.Configure Apache2 to Work with Php My Admin
nano /etc/apache2/apache2.conf
naviagate to the Bottom of the File and add the Following Line
Include /etc/phpmyadmin/apache.conf

9.restart the apache2
/etc/init.d/apache2 restart
Before Running the Code create a Database in the SQL using Terminal
To enter in to the mysql shell enter

mysql -u root -p where root is the username
use the Command
                        a.CREATE DATABASE database_name to Create a Database
                        b.USE database_name to change the current database
                        c.CREATE TABLE table_name To Create a table in the Current Database

I used Python MySQLdb Module to Write the values Into MySQL data base
To Store the Values into the DataBase Use 
db = MySQLdb.connect("localhost","root","raspberry","sensorData") #Connect to the DataBase 
curs = db.cursor() # open Cursor which is used to pass MySQLdb Queries
curs.execute(""" INSERT INTO sensorData.sensorDataTable values(%s,%s,%s,%s)""",(deviceId,timeStamp,1,sensorValue)) #Commit the Data db.commit()

Which stores the Values in the DataBase



To Read the Values from mySQL Database to WebPage I used Php
$conn = new mysqli($serverName,$userName,$password,$db); 
if($conn ->connect_error){ 
die("Connection Failed: ".$conn->connect_error);
 } 
echo "Connected successfully";
 $retval = mysqli_query($conn,"SELECT * FROM sensorDataTable");
 if(!$retval){ 
die('Could not get Data : '.mysqli_error());
 }
 while($row = mysqli_fetch_assoc($retval))
echo "Device id :{$row['Device Id']}<br>"
          . "Time Stamp :{$row['Time Stamp']}<br>"
            ."Sensor Type :{$row['Sensor Type']}<br>"
            "Sensor Value.{$row['Sensor Value']}<br>"
            ."--------------------------------------<br>"; 
   }
Which Displays the Values From Webpage





You Can Get All the Source Code From My GitHub Repositories

Output :