MrGorG
MrGorG

Reputation: 23

How to send and receive data from python to arduino at the same time

I currently have an arduino code, which is connected to three sensors: temperature, pressure and humidity. I would like to make a code in python that of an order (by int or strg), this sends the type of sensor that I want to read, example: if I enter by keyboard 1, it constantly sends me temperature data; if income 2, send me pressure data; and thus be able to enter any digit at any time. Pd: Sorry my bad english,I don't know if i could explain my problem

I have a similar code in arduino with switch case, and it works perfectly. but I can not make it work in python since when I put raw_input (), the program stops waiting for input and stops reading the sensor data.

Python

import serial
import time

ser=serial.Serial('/dev/ttyUSB0',baudrate=115200)
while 1:
 ser.setDRT(False)
 #c=raw_input()
 #ser.write(c)
 med=a.readline()
 print med

this just works fine to read data from one sensor type assigned by default

Upvotes: 2

Views: 1201

Answers (1)

Uli Sotschok
Uli Sotschok

Reputation: 1236

If you have tasks, that needs to run in parallel, you can use threads. One thread gets the sensor data and the other waits for input.

Python has a very easy to use builtin module for threading.

A very simple implementation example might look like this:

import threading 


def wait_input():
    while True:
        user_input = input()
        # do something with user_input 

def get_sonsordata()
    while True:
        med=a.readline()
        print(med)

input_thread = threading.Thread(target=wait_input)
input_thread.start()
sensor_thread = threading.Thread(target=get_sonsordata)
sensor_thread.start()

Upvotes: 1

Related Questions