In different blog posts, I’ve already explained how to receive data from Arduino using a .Net application or a server-side script. Today I’m going to show you how it’s possible, using JavaScript, to receive and show data using only a Web browser.
Logical architecture
The project has two main elements:
- Arduino, connected to an AM2302 sensor to get temperature and humidity values
- an HTML page, with some external resources (JavaScript and CSS files) opened in a browser
the JavaScript code in the HTML page sends JSONP requests to Arduino, which responds with a JSON message that contains the values obtained from the sensor. With the help of two opensource libraries, received data will is displayed on a chart and with a gauge.
Resources
All the files for this project (HTML page, JavaScript libraries, Arduino sketch…) are available in my GitHub’s repository:
JavaScript
When you open the ambientMonitor.html page in your browser, the different JavaScript libraries are loaded and executed.
The code requests data from Arduino using a JSONP call with the help of the jQuery library, as explained in a previous post. To make the sketch simpler, I decided to use a static name for the callback function (myCB):
var jqxhr = $.ajax({ url: 'http://192.168.1.1/?callback=?', dataType: 'jsonp', jsonpCallback:'myCB'}) |
Data is displayed using two JavaScript libraries:
and the update function runs every 30 seconds:
setInterval(updateValues, 30000); |
All the code was commented to make it easy to understand it: of course for doubts and questions leave a message at the end of this post!
Arduino
The Arduino sketch is similar to other examples in my tutorial about the enc28j60 controller.
The sensor (connected to PIN 3) is read using the Adafruit library:
#define DHTPIN 3 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); [...] dht.begin(); [...] float h = dht.readHumidity(); float t = dht.readTemperature(); |
When the browser requests data, a response is prepared and sent in JSONP format:
BufferFiller bfill = ether.tcpOffset(); bfill.emit_p(PSTR("HTTP/1.0 200 OK\r\n" "Content-Type: text/html\r\n\r\n" "myCB({'temperature':$S,'humidity':$S})"), t_string, h_string); |
The response body is: myCB({‘temperature’:tt.tt,’humidity’:hh.hh})
Conclusions
Using only client-side code (running in the browser) it’s possible to write a complete dashboard for requesting and displaying data from Arduino, without the need of a web server.
Salve, bellissimo blog, complimenti!
Articolo molto interessante, ho una piccola curiosità, come fanno i servizi ad esempio di google play che una volta registrato il proprio cellulare, una volta cliccata l’icona per scaricare un app dal proprio pc , automaticamente lo scarica al cellulare.
Funziona allo stesso modo? ma IP non cambia mai della connessione al cellulare? scusami, ho un pò di confusione
Ciao Michele,
in quel caso il cellulare (un “servizio” che è in esecuzione anche se non lo vedi) periodicamente controlla se vi sono delle APP da installare chiedendo ai server di Google Play e – in caso affermativo – le scarica e le installa sul tuo cellulare.
NIcely done! im going to make a blog post for this on my blog!
Thanks Philip!
A great project. Is it posible to use the Arduino WiFi shield instead of the Ethernet shield? I suppose the question I’m asking is does the WiFi library have enough similarity to the Ethernet library to transpose the code. I’m relatively new to the Arduino but have a specific interest in using the WiFi shield. Could you advise me.
Hi Ed
I’m working on a code for the “official” ethernet shield, you should be able to adapt it for the wifi shield too!
Ciao, in attesa che tu riesca a modificare il tutto per lo shield ethernet ufficiale, ho acquistato un enc28j60. Premesso che il tutto funziona da rete interna, anche tramite il collegamento con TL-WR702N, ho due dubbi:
– quando apro la pagina ambient monitor i valori, inizialmente sono a zero, per poi aggiornarsi dopo trenta secondi. Se digito ip arduino sono in tempo reale. Posso ovviare al problema solo riducendo il tempo della richiesta dati ad arduino?
– da rete esterna visualizzo la mia bella pagina, ma i valori non si aggiornano. Mi sa che devo aprire le porte del router per ip arduino vero?
In futuro sarebbe bello ristrutturare la pagina includendo la pressione atmosferica e più sensori di temp e umidità…..assorbimento elettrico abitazione….mi sto allargando scusa.
Grazie mille.
Ciao Massimo
puoi cambiare la frequenza di “refresh” dei dati via AJAX modificando la pagina (cerca “setInterval” e cambia il valore 30000).
per utilizzarlo via internet devi configurare il router per girare la porta 80 sull’IP di Arduino e, sempre nella pagina, inserire il tuo IP pubblico invece che quello della rete locale.
Bellissimo articolo. Bel sistema. Io ho creato un progettino con Arduino, dht22 e un barometro. Il problema che avevo era l’interfaccia web. Devo creare una pagina semplicissima in html perché Arduino fa da server e non supporta pagine troppo complesse. In questo caso invece Arduino funge da client. Appena sono a casa provo il tuo progetto. Potrei ampliarlo usando anche i dati del barometro.
Grazie davvero per i contenuti che condividi.
grazie mille Giovanni e fammi sapere come va il tuo progetto!
Buongiorno Luca, apprezzo molto i tuoi progetti molto interessanti. Avrei una domanda da farti. Avendo a disposizione una sheda Ethernet Shield W5100 al posto della enc28j60 quali adattamenti al codice devo fare? GRAZIE!!!
Ciao Fabrizio,
purtroppo è molto diversa e il codice Arduino va rifatto quasi completamente… ci sto lavorando!
Hi Luca, Excellent project and tutorials you have on the enc28j60
Hi Luca, Excellent project and tutorials you have on the enc28j60, any plans on creating one which would allow monitoring a DHT and switching on/off ports via a web page ?
Ola Chede.. Lucas , Excelente Projeto, Parabéns !
Aguardo ansioso pela adaptação que ira fazer para o Shield Ethernet W5100 ..
Abraços Sucesso !
Hello Luca.
Congratulations because your work. I have test all your projects and they work ok. I have one question to do. Is there any library to work with an UDP client under IPv6 for arduino?
Thank you very much.
Hi Graciano! Thanks… unfortunately as far as I know no ipv6 libraries for Arduino exist at the moment
Nice job. I will look at it in more detail, as I would prefer to use RS422 for multiple Arduinos, in a boat. This is to show twin engine stats, as well as fuel levels in 6 tanks.
I am very much NOT a programmer, but can usually adapt programs to mee my needs.
Thanks for sharing your work.
Thanks Shane! I’m using RS485 too for multi-node wired network… let me know the progress of your project!
Hi Luca,
amazing tutorial. You are doing really gret job. You wrote that you would be doing this to work with official ethernet shiled. I just want to ask if you are still planning to do it because Im using eth shield and I dont know how to respond to a jsonp request. Thx for answer
Hi Matej
thanks for your comment: at the moment I don’t own an original shield; however it’s well supported on the official forum, try asking there your request, I’m sure they will help you!
Ciao Luca, i tuoi lavori sono molto interessanti…. complimenti. Ti volevo chiedere se sei riuscito a convertire lo sketch per la shield ethernet W5100.
Ciao Franco, grazie ad un amico del blog lo sketch per W5100 è disponibile:
http://www.lucadentella.it/2015/02/14/ambientmonitor-client-w5100/
Hi luca, this is amazing project. Thanks for this tutorial.
If I want place the html file to SD card on Ethernet so we can access via IP address. Can you help me?
Hi, give a look to my SDWebServer example, it does exactly what you need (with some restrictions)
Hi,
Your project is very nice reference for WIZnet solution.
I’m an engineer worked at WIZnet provide W5100 to Arduino Ethernet Shield.
Can I introduce your project on the WIZnet museum site(http://wiznetmuseum.com/)?
Thanks in advace.
Of course! Thanks
Ciao, ottimo lavoro, due sole domande:
mi da errore nella compilazione in queste due prime righe:
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
idee???
l’indirizzo ip;
se metto uno ip fisso ovviamente posso tramite cellulare collegarmi da qualsiasi parte del mondo?
giusto?
grazie
A.
Ciao, hai caricato la libreria DHT? Per quanto riguarda l’IP, per poter raggiungere la scheda da Internet dovrai configurare il NAT sul tuo router
ciao, le ho provate tutte cmq, alla fine sono riuscito cmanbiando nel tuo codice questa riga:
da:
ether.printIp(“Netmask:\t”, ether.mymask);
a:
ether.printIp(“Netmask:\t”, ether.netmask);
saluti
A.
Hi,
I want to show 3 more sensor data, Pressure, Ph and Electric Conductivity in to this graph. I have Arduino program ready, i am stuck with html program, can you pls guide me how to do this.
Thank you.
Regards,
Irfan
hello sir.,.just wanna ask if how to save the data of the sensor to a database? and what database should i use?
Hi! It’s not so easy to directly interface Arduino with a database, you’d better to add an external piece of software (php…) and use a simpler protocol (HTTP, MQTT) to send data to that software.
okay sir.,.in this project of yours.,.can i use ESP 8266 instead of ethernet shield? do u have a tutorial how to do it?
thank you for the response sir! much appreciated
very helpful to my thesis project
well if you use the W5100 tutorial you should be able to run the sketch also on ESP8266