Step 5Make it a hitcounter
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.
| « Previous Step | Download PDFView All Steps | Next Step » |
1
comment
|
Add Comment
|
![]() |
Add Comment
|










































