To make it a hitcounter for your website, we need two small code pieces. One two create and take care of the counter and a second to fetch the value of the counter and to send it to the Arduino.
Note: If you are not familliar with Python or PHP, the scripts can be easily ported to your favorite programming language.
Here is a small PHP script, that reads a value from a file (hitcounter.txt), increments it and writes it back to the file. That is all, that is needed. This file can be saved as counter.php on your server for example. You can then trigger a count with you webbrowser pointing to http : //www.youdomain.com/counter.php. I included this snippet in my wordpress blog.
$hits = file($count_my_page);
$hit = trim($hits);
$fp = fopen($count_my_page , "w");
fputs($fp , "$hit");
The glue code
This next code snippet is used to fetch the counter. I used Python but anything should work. It opens an HTTP connection and fetches the hitcounter.txt. If the value has changed since the last fetching, the diff is calculated and pushed to the Arduino. This is done every ten seconds until you interrupt the script with crtl-c.
Adapt the myUrl and the serial connection below to your needs.
# fetch counter
# usb serial connection to arduino
ser = serial.Serial('/dev/tty.usbserial-A4001JAh', 9600)
myUrl = 'http://tinkerlog.com/hitcounter.txt'
last_counter = urllib.urlopen(myUrl).read()
_ counter = urllib.urlopen(myUrl).read()
_ delta = int(counter) - int(last_counter)
_ print "counter: %s, delta: %s" % (counter, delta)
_ last_counter = counter
I could not upload files with php extension, so you have to rename the counterphp.txt to counter.php.
If your Arduino is still attached to your PC, then start the Python script to fetch your hitcounter.
and you should see the output of the counter. If you point your browser to the URL of your counter.php and hit reload, you should hear your hitcounter ringing.
Yes, now we are done. Time to lean back and enjoy our work.
It is the first time, that I built something, that has moving parts. That is the first step to bridge the gap between the virtual and the real world. And it was really easy, the code is straight forward. Also most of the parts were in my trash bin, except the bell. Putting everything together and waiting for someone to hit my blog was fun.
Hope you enjoyed it.
This project is made by alex_weber.