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