Python Forum
run two tasks concurrently - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: run two tasks concurrently (/thread-4117.html)



run two tasks concurrently - tony1812 - Jul-24-2017

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.


RE: run two tasks concurrently - Larz60+ - Jul-24-2017

A couple of things to look at:
I would suggest three processes, running the timer separately and
notifying the other processes as required.