вторник, 10 декабря 2013 г.

Talking to Arduino in PHP via USB in Linux

I'm really proud of myself. I was able to comeup with the solution for the problem which is being discussed in the internet a lot - how to properly talk to arduino from a PHP script, actually from any kind of script. The problem is that Arduino resets itself when you open a connection, this is not OK and most of people just apply some harware hacking to disable this behaviour. I wanted a software solution.

Also for some reasons I cannot read arduino output using "php_serial.class" code. SO, here is my alternative solution:


  • I've created a deamon which redirects arduino serial output to a log file. This daemon can be started and stopped, on re-start it will re-write the logfile. I've done this for maintenance purposes - the intention is to clean the log file periodically, so that it doesn't grow to Gigabytes which ultimately could affect the performance of the overall solution(so, not because I don't have enough storage - I'm doing this on Netgear STORA after all :)). I've created a daemon script and an init script for this daemon. The code for the daemon script is easy "cat /dev/ttyUSB0 > /home/com_log.txt &" and that's it. Init script is more complex - you have to properly remove the log file and kill the cat process. You can download the code here
  • Once I have a daemon - reading Arduino from any places without resetting it - is super easy. But you have to read last lines if you want latest output. I've created a script which sends to Arduino a command to print the updated information about temperature and humidity sensors, then the script reads new values from the log file and saves them into the MySQL database. Here is the code
  • The script above is added to the crontab to collect temperature/humidity samples every 10 minutes
  • Then I've created a page using Google's Charts JSAPI examples with chart for each counter. Code is here.
This is how it looks like (there is still some work to do with date picker, correct dates on axis, etc.)

Now my Stora is a temperature station :) and since I have relay connected to the Arduino I can adjust temperature by switching heating on or off, but this part is later... stay tuned.

BTW, here is an Arduino scetch - it's a modified version of arduino code from UberFridge project by some awesome guy.

P.S. Please forgive me for code quality - I'm doing this for myself rather than for opensource community :) If someone want to polish the code and make it available on some communities - you are absolutely free to do this, I would appreciate a link to my blog though.


Комментариев нет:

Отправить комментарий