serial.Serial 没有newline 参数
时间: 2023-07-28 17:07:58 浏览: 57
很抱歉,我之前的回答有误。在PySerial中,确实没有`newline`参数。 如果你想使用`\r\n`作为行结束符,可以在读取数据时手动处理。以下是一个示例代码:
```python
import serial
ser = serial.Serial('/dev/ttyUSB0', baudrate=9600, bytesize=8, parity='N',
stopbits=1, timeout=1)
while True:
data = ser.read_until(b'\r\n').decode().strip()
if data:
print(data)
```
在上面的代码中,我们使用`read_until()`方法读取数据,以`\r\n`作为结束符。接着,我们使用`decode()`方法将字节数据转换为字符串,并使用`strip()`方法去除字符串首尾的空格。最后,我们判断字符串是否非空,如果非空,则打印出来。
你可以根据实际需求修改这些代码。
相关问题
python3.6 serial.Serial 类的 没有eol 参数
非常抱歉,我的之前的回答有误。在 Python 3.6 中,`serial.Serial` 类确实没有 `eol` 参数。因此,如果您需要指定换行符,可以使用 `io.TextIOWrapper` 类来对串口进行包装。具体做法如下:
```
import serial
import io
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser), newline='\r\n')
while True:
line = sio.readline()
if line:
print(line.strip())
```
在上面的代码中,`serial.Serial` 类被用来打开串口,然后使用 `io.BufferedRWPair` 类将串口对象转换为缓冲读写对象。接着,使用 `io.TextIOWrapper` 类对缓冲读写对象进行包装,设置 `newline` 参数为 `\r\n`,即可指定换行符。最后,使用 `sio.readline()` 方法读取数据,并使用 `strip()` 方法去掉字符串末尾的空格和换行符。
希望我的回答能够帮到您!
Serial.readStringUntil
Serial.readStringUntil() is a function in Arduino programming language that reads characters from the serial port and stores them in a string until a specified character is encountered. The function takes a single argument, which is the delimiter character that indicates the end of the string.
For example, the following code reads a string from the serial port until a newline character is encountered:
```
String inputString = "";
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
char c = Serial.read();
if (c == '\n') {
Serial.print("Input string: ");
Serial.println(inputString);
inputString = "";
} else {
inputString += c;
}
}
}
```
This code declares a string variable called `inputString` and initializes it to an empty string. In the `loop()` function, the code checks if there are any characters available on the serial port using the `Serial.available()` function. If there are, it reads the character using the `Serial.read()` function and checks if it is a newline character (`\n`). If it is, it prints the input string to the serial monitor and resets the string to an empty value. If it is not a newline character, it appends the character to the `inputString` variable using the `+=` operator.