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 :



No comments:

Post a Comment