A good idea to take your project to a next level is to communicate with it online, instead of having the data displayed on a screen, you can check all the data on your phone or computer and interact with your PI from anywhere.
The process is easy, it is a small python code, with a PHP script, and a server to host the communication.
A brief description:
we will start by writing the python code on the pi, let’s say we want to send a distance measured by an Ultrasonic sensor, we will write our normal code to measure the distance, and and then we will use a ‘socket’ to send the data to our server. A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.
The data will be concatenated with an HTTP address linked to the server, where this is the way our PHP script can read the data as an input.
You can also check the code on Github.
Here is the python code:
[sourcecode language="python"][/sourcecode ]
import RPi.GPIO as GPIO import socket //importing socket library import time import math GPIO.setmode(GPIO.BCM) host = "alawiya51.mypressonline.com" //hostname goes here port = 80 //setting the ultrasonic sensor pins TRIG = 23 ECHO = 24 print "Distance Measuremnet In Progress" GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) GPIO.output(TRIG, False) print "Waiting for Sensor to Settle" //Create a method to send the data def sendData(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) //initiating a socket s.connect((host , port)) // connecting to the server time.sleep(2) GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO)==0: pulse_start = time.time() while GPIO.input(ECHO)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start //measuring the time between both pulses distance = pulse_duration * 171.50 distance = round(distance,2) //calculating the distance request = "GET /insert.php?x=" + str(distance) + \ " HTTP/1.1\r\nHost: " + host + "\r\n\r\n" //writing the request s.send(request) //sending the request to the server request = "" print "Distance : ",distance, "m\n" while True: sendData(); time.sleep(60) //send the data to the server every minute done; GPIO.cleanup()
The PHP script will only read the data embedded in the link when called, and it will be stored in a database we previously created.
Here is the PHP code:
[sourcecode language="php"] echo "Executing: insert.php"; $con= mysqli_connect('hostname', 'database_name', 'your_username', 'your_password'); $x = $_GET["x"]; echo " x = " .$x. ""; $sql ="INSERT INTO ultraValue (ultvalue) VALUES ('$x')"; mysqli_query($con, $sql); mysqli_close($con); echo " done"; ?>[/sourcecode ]
I hope this was helpful, don’t hesitate to leave any question if you had any problem.
Stay creative and talk to you in the next tutorial.