Arduino XMAS hitcounter

Step 5Make it a hitcounter

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.

The counter

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[0]);
$hit++;
$fp = fopen($count_my_page , "w");
fputs($fp , "$hit");
fclose($fp);
echo $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
#
import time
import urllib
import serial

# 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()
while (True):
_ counter = urllib.urlopen(myUrl).read()
_ delta = int(counter) - int(last_counter)
_ print "counter: %s, delta: %s" % (counter, delta)
_ ser.write(chr(ord(chr(delta))))
_ last_counter = counter
_ time.sleep(10)

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.

..>python counter.py

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.

counter.py484 bytes
« Previous StepDownload PDFView All StepsNext Step »
1 comment
Oct 14, 2010. 2:19 PMmoogbeatz99 says:
how would i set up this hit counter thing with a google site? would it work at all? im not planning on actually doing this instructable, i might when i get spare time and money, but i would like to actually know if it would work.....

Pro

Get More Out of Instructables

Already have an Account?

close

All Steps Viewing
View all steps of an Instructable on the same page when you're a Pro Member.

Upgrade to Pro today!
41
Followers
4
Author:alex_weber