In this task, we will review a fun example that enables a person to be physically active every 60 minutes.
This example is based on the Twisted framework discussed in the previous project. It would be great to have two Raspberry Pi boards (set up with the SD card images and powered up) or an Arduino Ethernet board. A laptop that is connected to the same network as the Raspberry Pi is just as sufficient.
If you missed installing the Twisted framework in the previous project, the Twisted framework can be installed as follows:
sudo apt-get install python-twisted
This enables a person to get some physical activity by walking back and forth between the two devices (assuming the Raspberry Pi devices are installed far away from the person in the interest of gaining some physical activity).
simpleserver
(http://twistedmatrix.com/documents/current/_downloads/simpleserv.py).#Declare inputs and outputs. GPIO.setmode(GPIO.BCM) GPIO.setup(18,GPIO.IN) GPIO.setup(25,GPIO.OUT) GPIO.setwarnings(False) class AsyncTask: def __init__(self): self.run_state = True #avoiding the channel argument throws an error def terminate(self,channel): self.run_state = False def add_callback(self): GPIO.add_event_detect(18,GPIO.FALLING, callback=self.terminate) def run(self): while self.run_state == True: GPIO.output(25,GPIO.HIGH) time.sleep(1) GPIO.output(25,GPIO.LOW) time.sleep(1) GPIO.remove_event_detect(18)
AsyncTask
class, the buzzer can be set off by triggering a separate thread to call the run
function. This sets off the buzzer with a one-second interval.add_callback
method is used to turn off the buzzer when the button is pressed. The add_event_detect
method waits for the state of GPIO #18 to change from high to low. This turns off the buzzer by setting run_state
to False
. While exiting the infinite loop, we remove the callback functions using the remove_event_detect
method.async_task = AsyncTask() async_task.add_callback() thread = Thread(target=async_task.run, args=()) thread.start()
simpleclient.py
example after modifying the code to change the server address to that of the Raspberry Pi (https://twistedmatrix.com/documents/14.0.1/_downloads/simpleclient.py).EthernetClient
has to be initialized and connected to the Raspberry Pi to send a test message. This can be repeated in a 60-minute cycle:Serial.println("connecting..."); if (client.connect(server, 8000)) { Serial.println("connected"); client.println("Hello, World!"); client.println(); //Lets wait for the client to read and //echo the message //Note: A second's delay is a bit excessive delay(1000); //If there is a response from the server //echo back the message Serial.println("Server says:"); while(client.available()) { char c = client.read(); Serial.print(c); } client.stop(); Serial.println("Client Disconnected"); } else { Serial.println("connection failed"); }
3.15.168.2