Python Forum

Full Version: Python Serial: How to read the complete line to insert to MySQL?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello. Sorry for my bad English, it's not my first language.
I have created a python code to insert data from a DHT11 sensor into a mysql table. Everything works, well almost. I have noticed that in the first rows the data does not appear as it should. At first the lines come out irregularly. Then they come out as they should be.
Here is a picture of what I'm talking about:
https://i.vgy.me/Yc4lGp.png

Here is my Arduino code:
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE); 
void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  // Leemos la humedad relativa
  float h = dht.readHumidity();
  // Leemos la temperatura en grados centígrados (por defecto)
  float t = dht.readTemperature();
  // Calcular el índice de calor en grados centígrados
  float hic = dht.computeHeatIndex(t, h);

  // Comprobamos si ha habido algún error en la lectura
  if (isnan(h) || isnan(t)) {
    Serial.print("Error obteniendo los datos del sensor DHT11");
    return;
  }else{
  Serial.print("Temperatura: ");
  Serial.print(t);
  Serial.print(" *C\t");
  Serial.print("Humedad: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Indice de calor: ");
  Serial.print(hic);
  Serial.println(" *C");
  delay(3000);
  }
}
Here is my python code:
import mysql.connector
import serial

mibd = mysql.connector.connect(
  host="localhost",
  user="root",
  password="N12345",
  database="sensor_humedad"
)

ser = serial.Serial(
    port='/dev/ttyACM0',
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

def programa():

   while True:
    medida=ser.readline() 
    micursor = mibd.cursor()
    sql = "INSERT INTO medidas (dht11) VALUES (%s)"
    valores = [(medida)]
    micursor.execute(sql, valores)
    mibd.commit()
    print(f"{micursor.rowcount}, se ha insertado una linea del sensor.")
programa()
I have tried looking for solutions but I can't solve my problem. I think I would have to use "in_waiting" or "flush()" but I don't know where in my code I should put it. I am new to python.
ser.readline() returns bytes, not a str.
# Instead of this
medida=ser.readline() 

# do this
medida=ser.readline().decode('utf-8')