问题
I have two BBC Micro Bit and using Radio function to transfer data from one slave to the master Micro Bit. When the data is transferred I am getting random carriage returns, I am not sure what is the problem, I have tried to strip any random CR etc, but still getting the same problem.
a=1,On,
12
=2,
Off, 77
=3,
On, 88
===================================================
Gateway code
from microbit import *
import radio
radio.config(group=0)
radio.on()
while True:
incoming = radio.receive()
if incoming:
uart.write(incoming)
==============================================
Slave code
from microbit import *
import radio
radio.config(group=0)
radio.on()
while True:
if button_a.was_pressed():
radio.send('Matt,A=On,Off' + '\n') # a-ha
display.scroll("A")
if button_b.was_pressed():
radio.send('Matt,B=On,Off' + '\n') # a-ha
display.scroll("B")
=========================================================
PySerial code
import sys
import glob
import serial
def serial_ports():
ports = ['COM%s' % (i + 1) for i in range(256)]
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
if __name__ == '__main__':
print(serial_ports())
try:
ser = serial.Serial('COM5', 115200, timeout = 0)
print("connected to: " + (ser.portstr))
except serial.SerialException:
pass
while True:
line = ser.readline().decode('utf-8')
# Read a line and convert it from b'xxx\r\n' to xxx
if line: # If it isn't a blank line
f = open('output.csv', 'a+')
f.write(line + '\n')
print(line)
f.close()
ser.close()
回答1:
I found your scripts worked without sending extra carriage returns. I tested using two microbits. I used the REPL in mu and also CoolTerm, set to 115200 baud. I am using Linux Mint as my OS. CoolTerm output: Matt,B=On,Off Matt,A=On,Off
Added after the pyserial code was posted: The code below works for me to produce the expected output without extra blank lines. The newline is removed by using the end='' in the print statement. Finding the microbit using the pid and vid enables you to have other serial devices attached. Credit to microbit-playground for posting example code on how to use pid and vid to find the microbit.
I tested this on Linux using the jupyter notebook. It should work on Windows without modification.
import serial
import serial.tools.list_ports as list_ports
def find_microbit_comport():
ports = list(list_ports.comports())
for p in ports:
if (p.pid == 516) and (p.vid == 3368):
return str(p.device)
if __name__ == '__main__':
ser = serial.Serial()
ser.baudrate = 115200
ser.port = find_microbit_comport()
ser.open()
while True:
line = ser.readline().decode('utf-8')
if line: # If it isn't a blank line
f = open('output.csv', 'a+')
f.write(line)
print(line, end='')
f.close()
ser.close()
来源:https://stackoverflow.com/questions/44205403/bbc-microbit-radio-string-transfer-random-carriage-returns