# GPIO script that counts each time a reed switch is activated

My goal is to attach a magnet to a hamster wheel and use a reed switch to determine the distance traveled and speed of my hamster over a long period of time (several weeks/months) and output it as an excel sheet with dates and times.

Currently, I have a raspberry pi model B+ with a reed switch attached to GPIO 22 and ground.

This is my first time using a raspberry pi and one of the first scripts I've written from scratch. Since I am a newbie, I figured that I would first write a script that keeps track of the distance traveled given the circumference of my wheel (I will move on to speed once I have this down).

I am having trouble understanding how I can write a script that tracks each time the magnet passes the reed switch and then sums together each of these events to determine the total distance traveled.

The code below is my first attempt at trying to calculate the total distance traveled. How can I write a script that updates 'previous_feet_traveled' with each rotation so that the circumference of my wheel is added to an accumulated distance, rather than 0 each time?

My thought process:

• Pin 15 starts at high.
• If the magnet attached to the running wheel passes the reed switch, pin 15 changes to low. If this occurs, distance is calculated by adding the circumference of my wheel to the previous feet traveled.
• If the magnet does not pass the reed switch, nothing should happen and pin 15 should stay at high.

I was inspired by this simple script: https://pythonprogramming.net/gpio-example-raspberry-pi/

I would appreciate any feedback and help as I work through this for the first time!

``````import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

prev_feet_traveled = 0
circumference = 2.095

while True:
gpio.output(15, gpio.HIGH)

if gpio.output(15, gpio.LOW):
distance = prev_feet_traveled + circumference

else:
gpio.output(15, gpio.HIGH)
NULL

``````
• You need to read the GPIO to sense the switch. You are writing to the GPIO which is pointless. This seems to be a how do I write a Python program question which is off-topic. Perhaps work through some tutorials?
– joan
Jun 9 at 20:39
• Further to joan's comment, the reed switch will be an input to the Pi - not an output! Jun 9 at 21:56
• you need more than one reed switch ... what if the wheel stops with the magnet at the reed switch and the wheel gets bumped a number of times? Jun 10 at 0:31
• since you are a beginner, your program should be no more than the necessary code to print a message when the magnet passes the reed switch Jun 10 at 0:35
• @joan Why is my question off-topic? I have been looking through python tutorials like the one I linked. What do you mean by reading vs. writing to the GPIO? Jun 10 at 0:55