Python Forum

Full Version: run two tasks concurrently
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I just got a Pi, that what motivated me to learn Python. I am a absolute newbies when it come to python programming,  I joint this forum.

I am making an app I have a script to read data to Pi with serial from sensors in Aduino,
It is a very simple script:
import serial, time

ser = serial.Serial('/dev/ttyUSB0', 9600)

while True :
   data = ser.readline()
   print str(data)
   time.sleep(1)
ser.close()
now besides reading data. the Pi also control the a timed relay relay to turn things on and off, so I made a timer script:
import RPi.GPIO as GPIO
import time
#GPIO.setmode(GPIO.BCM)
GPIO.setmode(GPIO.BOARD)

GPIO.setwarnings(False)
while True: 
   GPIO.setup(40,GPIO.OUT)
   print ("LED on")
   GPIO.output(40,GPIO.HIGH)
   time.sleep(1) # Insert here?
   print ("LED off")
   GPIO.output(40,GPIO.LOW)
   time.sleep(1) # Insert here?
   

GPIO.cleanup() 
Now my trouble is (conciliate the two scripts into one) keeping the timer running while reading data concurrently. How does python do that? Do I need to create a a dedicated thread to run them or is there a sinpler way to do it. Thanks.
A couple of things to look at:
I would suggest three processes, running the timer separately and
notifying the other processes as required.