Data from Arduino

Hello

First of all, I am aware a similar question has been posted here before.(pH Data from Arduino to Pi (Mycodo)) However it didn’t really work in my case. I have three soil moisture sensors connected to my arduino. I managed to read serial data from the Arduino using a Raspberry Pi. But for some reason it doesent return any values in live measurements.

I used the following code as the python 3 v2 imput:

import serial

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    ser.reset_input_buffer()
    while True:
         if ser.in_waiting > 0:
            line = ser.readline).decode('utf-8').rstrip()
            moistlist123 = list(map(float, line.split()))
            moistlist1 = float(sum(moistlist1))
 return{0: moist1}

Obviously I am very new to python so please feel free to correct. If anything else could be the problem, some fixing-ideas would be great. Thanks!

sorry the formating is all f-ed up

5 things I immediately see wrong:

  1. Remove the first if statement. That is only used when running Python code from a terminal.

  2. Your spacing is incorrect. You need to use 4 spaces per indent. You also have a single space before return.

  3. You never define moist1.

  4. Your code will never exit the while loop.

  5. “ser.readline)” is incorrect.

This code cannot run in this state. Where did you get it?

Thank you. I honestly just mixed and matched. Which was probably a bad idea lol, since I have no experience with python. I am still struggling though. I tried editing the code based on your advice but got stuck on 4. Do you mind giving me an example of how the code could work?

Can you provide the code you used to do this? The more info the better. You’ll get more and better responses if you give us something to work with.

Sure!

#!/usr/bin/env python3
import serial

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    ser.reset_input_buffer()

    while True:
        if ser.in_waiting > 0:
            line = ser.readline().decode('utf-8').rstrip()
            print(line)

Be sure to encase all code in backtics to properly format it. It’s impossible to read unformatted code that’s not monospaced.

This is properly formatted and uses the example code correctly. Whether it works is another matter.

import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
ser.reset_input_buffer()

timeout = time.time() + 5
while time.time() < timeout:  # exit if no measurement in 5 seconds
    if ser.in_waiting > 0:
        line = ser.readline().decode('utf-8').rstrip()
        self.logger.debug(f"line = {line}")
        return {0: line}