简体   繁体   中英

Arduino serial communication issue

I'm trying to write a simple program to read serial data from Arduino. In the Arduino serial monitor window, everything works fine. In the Python console, each number is on a separate line. In Pycharm, it just shows b' ' . I don't know where the problem is.

Arduino Serial Monitor :

1234567890

1234567890

1234567890

1234567890

1234567890

1234567890

1234567890

1234567890

1234567890

1234567890

Python 3 console :

1

2

3

4

5

6

7

8

9

0

Pycharm IDE :

b' '

b' '

b' '

b' '

b' '

b' '

b' '

b' '

b' '

b' '

Here is the Python 3 code I am using:

import serial
from time import sleep

Ser = serial.Serial("COM3", 9600, timeout=0)
Counter = 1

while Counter <= 10:
    data = Ser.readline()
    print(data)
    sleep(1)
    Counter += 1
Ser.close()

Arduino code:

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    Serial.println(1234567890);
    delay(1000);
}

Perhaps a side effect of timeout=0 . I would try this:

import serial

Ser = serial.Serial("COM3", 9600, timeout=1)
data = Ser.readline()
print(data)
Ser.close()

Try using the AMD module !!

Link to the documentation: https://pypi.org/project/AMD/

AMD is a powerful Data-Science module built especially for data extraction and communication with Arduino . This module automatically filters all escape sequence characters and returns you a piece of data or a list of data from the Arduino!

Install via pip: pip install AMD

Documentation for ardata function in the link: https://github.com/SayadPervez/AMD-SEPERATE-DOCUMENTATION/blob/master/ardata().md

Your entire python code can be replaced with the below two lines!!

from AMD import *
data = ardata(3,lines=10)

Alternatively, you can also use the below modified line to get more functionality

data = ardata('COM3',lines=10,squeeze=False,numeric=True)

The first parameter is the COM port . It can either be a string or an Integer. lines represent the number of lines of data to be read from the serial monitor. squeeze parameter specifies if data has to be compressed. numeric specifies if the expected data is of numeric type(integers or floats). However for your requirement the first two lines of code are enough since the rest are set by default!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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