简体   繁体   English

Python readline()

[英]Python readline()

I want to send some parameters from arduino to raspberry pi via serial. 我想通过串口从arduino发送一些参数到raspberry pi。 I must to send every 0.5 seconds this three parameters at the same time which are numbers to raspberry pi. 我必须每隔0.5秒发送这三个参数,这些参数是覆盆子pi的数字。

Arduino code: Arduino代码:

    #include "DHT.h"
    #define echo 7
    #define triger 8
    #define photoresistorPin A0
    int lux; //Variable for photoresistor reading
    DHT dht;


    void setup() {
      Serial.begin(9600);
      dht.setup(2);
      pinMode(7,INPUT);
      pinMode(8,OUTPUT);

    }

    void loop() {
      lux = analogRead(photoresistorPin);
      float temperature = dht.getTemperature();
      long duration, distance;
      digitalWrite(triger, LOW);
      delayMicroseconds(2);
      digitalWrite(triger, HIGH);
      delayMicroseconds(10);
      digitalWrite(triger, LOW);
      duration = pulseIn(echo, HIGH);
      distance = (duration / 2) / 29.1;
      Serial.println(temperature);
      Serial.println(distance);
      Serial.println(lux);
      delay(500);

    }

And i recived with python code: 我收到了python代码:

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

while True:
   line = ser.readline()
   print(line.decode("utf-8"))

Results are: 结果是:

24 #temp
112 #distance
524 #lux

Question is: 问题是:

How to read and put separately each of them in some variable? 如何阅读和分别将它们分别放在一些变量中? Example: I want to read from serial these three parameters and put them separately in some variable for example variable temp =24 for temperature from arduino, after 0.5sec 25, then 24,25,23,25.. and average them. 示例:我想从串行中读取这三个参数并将它们分别放在一些变量中,例如变量temp = 24表示来自arduino的温度,0.5秒25之后,然后是24,25,23,25 ..并将它们平均。 24+25+24+25+23+25/6 and print results. 24 + 25 + 24 + 25 + 23 + 25/6并打印结果。 So the same for distance and lux. 因此距离和勒克斯相同。

Can you read three lines at a time? 你能一次读三行吗?

vars = []

def read_float(ser):
    return float(ser.readline().decode("utf-8"))

while True:
   vars.append([ read_float(ser), read_float(ser), read_float(ser) ])

Regarding "every 5 minutes", look into the sleep function, and probably threading 关于“每5分钟”,看看sleep功能,可能是threading

Why not this? 为什么不呢?

import serial
from collections import defaultdict
ser= serial.Serial('/dev/ttyUSB0',9600)
var = ['temp', 'distance', 'lux']
val_dict = defaultdict(list)

while True:
   line = ser.readline()
   val = zip(var,line.decode("utf-8")))
   for k, v in val:
       val_dict[k].append(float(v))


defaultdict(list, {'distance': [112.0], 'lux': [524.0], 'temp': [24.0]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM