Purpose of this experiment is to demonstrate real time aspect of the web to pull data from an Arduino.
Arduino can be clubbed together with several sensor to receive data of surroundings and do anything with data. Once you have data with you, imagination is the limit like sending surrounding temperature to Twitter as tweet, check mail when you come close to your computer, turn off volume when an ad comes on TV etc.
Following POC shows use of Arduino with LDR sensor to plot real time graph of Light around you.
You will need following things for our project :
- Arduino UNO or Freeduino
- LDR or photo-resistor
- 10k ohm resistor (Voltage divider)
- Computer
Let connect things
Connect your LDR and resistor as shown in figure.,
Now coding part,
The idea here is to read sensor reading using Arduino and send them to computer for further processing, so we will read sensor data and send it serial port of computer where Arduino is connected.
filename: LDR.ino
int LDR = 0;
void setup(){
Serial.begin(9600);
}
void loop(){
int Reading = analogRead(LDR);
Serial.println(Reading);
delay(250);
}
Code is pretty self-explanatory. Now the web part here we will use websocket for reading values and plotting real time graph out of read values. We will not discuss websocket and its implementation as this is out of scope of this project (which itself is big topic for discussion).
In order to run the code you need to install Python with following modules
- geventwebsocket.handler
- gevent
- serial
Here websocket server written in Python,
filename: LDRreader.py
from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi
import gevent
import serial
# PORT used for websocket client
PORT = 8090
import os
import random
def handle(ws):
""" This is the websocket handler function. Note that we
can dispatch based on path in here, too."""
serial_read = serial.Serial('COM31', 9600)
if ws.path == '/data':
for i in xrange(10000):
signal = serial_read.readline()
ws.send("0 %s %s\n" % (i, signal))
print "0 %s %s\n" % (i, signal)
gevent.sleep(0.1)
def app(environ, start_response):
if environ['PATH_INFO'] == '/test':
start_response("200 OK", [('Content-Type', 'text/plain')])
return ["blah blah"]
elif environ['PATH_INFO'] in ("/data"):
handle(environ['wsgi.websocket'])
else:
start_response("404 Not Found", [])
return []
def main():
print "In main, Starting WSGIServer"
server = pywsgi.WSGIServer(('0.0.0.0', PORT), app,
handler_class=WebSocketHandler)
try:
server.serve_forever()
except:
pass
if __name__ == "__main__":
main()
Now websocket client which will actual receive data and plot it on web browser, you need this library for plotting graph. Download and keep in same directory where LDR.html is present.
filename: LDR.html
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="jquery.flot.js"></script>
<script>
var iets = "";
window.onload = function() {
var data = {};
try {
var s = new WebSocket("ws://localhost:8090/data");
}
catch (e) {
var s = new MozWebSocket("ws://localhost:8090/data");
}
s.onopen = function() {
console.log('Websocket Open');
s.send('hi');
};
s.onmessage = function(e) {
console.log('got ' + e.data);
var lines = e.data.split('\n');
for (var i = 0; i < lines.length - 1; i++) {
var parts = lines[i].split(' ');
var d = parts[0], x = parseFloat(parts[1]), y = parseFloat(parts[2]);
if (!(d in data)) data[d] = [];
data[d].push([x,y]);
}
var plots = [];
for (var d in data) plots.push( { data: data[d].slice(data[d].length - 200) } );
$.plot( $("#holder"), plots,
{
series: {
lines: { show: true, fill: true },
},
yaxis: { min: 0 },
} );
s.send('');
};
};
</script>
</head>
<body>
<h3>LDR Plot</h3>
<div id="holder" style="width:800px;height:350px"></div>
</body>
</html>
Now start our websocket server using
# python LDRreader.py
now go to browser and type http://localhost:8090 and bam !!!
You will see plotting graph.


This comment has been removed by the author.
ReplyDeleteHello, is very interesting, you can explain the part of load the library, I mean how python Known the path of library
ReplyDeletewhich OS you use? Work on Windows or Ubuntu?
ReplyDeleteKeyError: 'wsgi.websocket' I'm getting this error.What is wrong?
ReplyDeleteSame Here
DeleteThanks for sharing such a good information...
ReplyDeleteNetwork Solutions Review
Your blog is very informative and gracefully. Your guideline is very good. Thank you | Atmosphere Company in Bangalore
ReplyDeleteHii, Written well and thanks for sharing. I improves my knowledege.
ReplyDeleteI have seen lot of projects based on Arduino Microcontroller on Engineers Garage website. There are lot of websites from where you can find latest invention news, articles in the electronics engineering field, It is a community of Electronics and Electrical Engineers where they can take ideas for there projects or submit there tutorials also. This website works on the electric circuit diagram, micro controllers, DIY projects, Innovation Stories and More. Undertakings are a piece of any designing educational modules. Final year projects for Electronics Engineering help understudies to execute what they realized in their four years designing examinations. They likewise help the workforce to comprehend their understudies' execution. Very Helpful website for Final year engineering students.
You can visit Engineers Garage
Thanks for this!
ReplyDeleteI haven't touched any microcontroller since college so I'm slightly rusty but this was helpful
Melbourne Web Developer
Really it was an awesome article… very interesting to read…
ReplyDeleteThanks for sharing.........
Best Web Development company in India
Salesforce Developer Course
ReplyDeleteA Salesforce developer course is ideal for building technical expertise. This salesforce developer course details explains the modules clearly. It includes real-time applications. Learning looks practical. Good for career growth.
SFDC Admin Training
ReplyDeleteSFDC admin training helps build strong CRM skills. This sfdc training page looks good. Easy explanations. Practical approach. Worth exploring.
Great overview! A devops full course
ReplyDeletefocuses on continuous integration and delivery, ensuring faster time-to-market and improved application performance.
Great article! With our devops training
ReplyDelete, learners gain hands-on experience in automation, infrastructure management, and collaborative workflows for career growth.
service now training online is explained in a simple and practical way.service now training online
ReplyDeleteMCD Level 1 certification is a valuable credential for MuleSoft professionals. It validates your ability to design and build basic integration solutions.mcd level 1 certification
ReplyDeleteMCD Level 1 certification is a great step for MuleSoft developers. Thanks for sharing preparation tips.mcd level 1 certification
ReplyDeleteInsightful article! Our boomi course
ReplyDeleteprovides practical experience in AtomSphere, connectors, and workflow automation, empowering learners to implement real-world cloud integrations.
MuleSoft developer training helps in understanding integration patterns and API design. It’s a must-have skill for modern developers.mulesoft certification training
ReplyDeleteGreat read! Learn data modeling class
ReplyDeletewith practical experience and build strong skills in database design and analytics.
This ServiceNow admin course is a great option for beginners aiming to enter the IT service management field.
ReplyDeleteservice now admin course
These ServiceNow classes provide hands-on exposure to real-time scenarios.servicenow classes
ReplyDeleteFlexible ServiceNow online training with real-time projects and certification support.servicenow online training
ReplyDeleteservicenow classes – ServiceNow classes offer structured learning and help in understanding platform administration and ITSM modules.
ReplyDeleteservicenow classes
Mule software training is essential for integration developers, and this post is helpful.mule software training
ReplyDeleteSalesforce Developer Course
ReplyDeleteWhat should I check before enrolling in a Salesforce developer course? I came across this salesforce developer course. Is curriculum enough?
A professional certification program designed to validate MuleSoft integration and development skills for better job opportunities.A professional certification program designed to validate MuleSoft integration and development skills for better job opportunities.
ReplyDeleteA professional certification program designed to validate MuleSoft integration and development skills for better job opportunities.mule soft certification
ReplyDeleteSFDC admin course covers all essential concepts needed to become a certified admin.sfdc admin course
ReplyDeleteWell explained. Salesforce developer classes provide hands-on experience in building real-world applications.
ReplyDeletesalesforce developer classes
Salesforce admin course helps learners understand CRM management, user configuration, data handling, and automation tools used in Salesforce platforms.salesforce admin course
ReplyDeleteA salesforce development course teaches Apex, Lightning Web Components, and CRM customization skills needed for developer roles.salesforce development course
ReplyDeleteVery detailed explanation about sfdc admin training. The blog clearly describes how training can improve practical Salesforce administration skills.sfdc admin training
ReplyDeleteExcellent explanation about the SFDC Admin course. The blog covers important administration concepts and gives a clear learning path for beginners.sfdc admin course
ReplyDeleteThis blog shared valuable insights about tableau course online and data analytics learning. Real-time projects and dashboard creation are very useful for beginners.tableau course online
ReplyDeleteTableau online training helps students understand data storytelling concepts and develop strong business intelligence expertise.tableau online training
ReplyDeleteAn excellent Salesforce development course for learners who want to build expertise in Apex, Lightning Components, and Salesforce application development. The practical coding exercises are very useful for real-world projects.
ReplyDeletesalesforce development course
Sales force developer training helps aspiring developers learn Apex, Visualforce, and Lightning technologies. The course focuses on creating customized business applications on Salesforce.sales force developer training
ReplyDeleteVery useful information about the Salesforce admin course online. Flexible learning schedules and real-time project experience make online training a great option.salesforce admin course online
ReplyDeleteThe SFDC Admin course is well-structured and easy to understand. It includes real-time scenarios, hands-on practice, and interview preparation, making learners job-ready.sfdc admin training
ReplyDeleteGreat post. Many learners searching for interactive practical sessions prefer linux administration classes to understand real-world Linux server management and system maintenance concepts effectively
ReplyDeleteTableau developer training helps learners create powerful dashboards, reports, and visual analytics using real-world data, improving business intelligence skills.tableau developer training
ReplyDeleteAn SFDC Admin Course teaches the fundamentals of Salesforce administration, including security settings, reports, dashboards, and process automation. It is suitable for beginners who want to enter the growing CRM technology field.sfdc admin course
ReplyDeleteBecome job-ready with Salesforce Developer Training focused on practical development skills. Work on real-time projects involving Apex programming, triggers, Lightning components, and Salesforce platform customization.salesforce developer course
ReplyDeleteThanks for sharing this valuable content. Power BI classes online are a convenient option for working professionals who want to upgrade their visualization skills.power bi classes online
ReplyDelete