For the following layout, where squares are sensors that send a signal when the train passes and circles are switches.
The train only goes counter clockwise in the big oval.
Last active
December 12, 2020 14:23
-
-
Save elsholz/6fa70b9a5d30360c41bd40fe16725cee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import RPi.GPIO as GPIO | |
from random import randrange | |
from time import sleep | |
import threading | |
# Set the time for the relays to be turned on, before being turned off again | |
SWITCH_TIME = 0.1 | |
GPIO.setmode(GPIO.BCM) | |
# input sensor hill | |
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) | |
# input sensor tunnel | |
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) | |
# switch group A | |
GPIO.setup(13, GPIO.OUT) | |
GPIO.setup(16, GPIO.OUT) | |
# switch b | |
GPIO.setup(19, GPIO.OUT) | |
GPIO.setup(20, GPIO.OUT) | |
# switch c | |
GPIO.setup(26, GPIO.OUT) | |
GPIO.setup(21, GPIO.OUT) | |
# Enable AC Power | |
GPIO.setup(2, GPIO.OUT) | |
GPIO.output(2, GPIO.LOW) | |
switch_lock = threading.Lock() | |
switch_status = { | |
'a': None, | |
'b': None, | |
'c': None | |
} | |
def station_entry(*args): | |
print('Entering the Station!') | |
direction = 13 | |
if randrange(0, 10) < 5: | |
i direction = 16 | |
with switch_lock: | |
if switch_status['a'] != direction: | |
switch_status['a'] = direction | |
GPIO.output(direction, GPIO.HIGH) | |
if switch_status['c'] != 26: | |
switch_status['c'] = 26 | |
GPIO.output(26, GPIO.HIGH) | |
if randrange(0, 10) < 4: | |
switch_status['b'] = 19 | |
else: | |
switch_status['b'] = 20 | |
sleep(SWITCH_TIME) | |
GPIO.output(direction, GPIO.LOW) | |
GPIO.output(26, GPIO.LOW) | |
print(switch_status) | |
def bridge_crossing(*args): | |
print('Crossing the Bridge!') | |
direction = 19 | |
if randrange(0, 10) < 3: | |
direction = 20 | |
with switch_lock: | |
if switch_status['b'] != direction: | |
switch_status['b'] = direction | |
GPIO.output(direction, GPIO.HIGH) | |
if switch_status['c'] != 21: | |
switch_status['c'] = 21 | |
GPIO.output(21, GPIO.HIGH) | |
sleep(SWITCH_TIME) | |
GPIO.output(direction, GPIO.LOW) | |
GPIO.output(21, GPIO.LOW) | |
print(switch_status) | |
print('Setup completed!') | |
print(switch_status) | |
print() | |
GPIO.add_event_detect(27, GPIO.RISING, callback=bridge_crossing, bouncetime=1000) | |
GPIO.add_event_detect(17, GPIO.RISING, callback=station_entry, bouncetime=1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment