我正在尝试从Arduino获取一些数据,而我无法解码来自它的数据。我搜索了一些信息,我找到了这些答案,例如:
Unicode string to String in python
Arduino正在以8位编码(UTF-8)发送数字(数据)。 我尝试了很多不同的代码,我得到的最佳解码是:
我使用SublimeText 2编写代码,这是我使用print
时控制台显示的内容。我需要对数据进行解码,以便稍后使用它来绘制matplotlib图。
我写的最后一段代码给了我上面显示的输出:
class readData(QWidget):
def __init__(self):
super(readData, self).__init__()
self.resize(300, 100)
self.btn = QPushButton("Close", self)
self.btn.setGeometry(150, 50, 100, 30)
self.btn_2 = QPushButton("Search Data", self)
self.btn_2.setGeometry(50, 50, 100, 30)
self.btn.clicked.connect(self.close)
self.btn_2.clicked.connect(self.searchData)
def searchData(self):
arduinoData = serial.Serial('com7', 9600) #We open port com7
while True:
print "Searching for data"
while(arduinoData.inWaiting() == 0): #We wait for the data
print "There is no data"
print "Reading and converting data"
arduinoString = str(arduinoData.readline())
ardString = unicode(arduinoString, errors = "ignore")
print "This is the data: "
print type(arduinoString)
print ""
print arduinoString
print type(ardString)
def close(self):
#WE CLOSE THE WINDOW AND THE PORT
我打开一个简单的QWidget
来显示两个按钮:一个用于开始搜索数据并显示它,另一个用于关闭窗口和端口。这是一个简单的窗口:
我如何解码(或编码,我现在真的不知道)来显示我需要的数字?我究竟做错了什么?我希望你能帮助我。
答案 0 :(得分:1)
String本质上是一系列字符。每个字符都可以用一个或多个字节表示。这种映射来自'字节 - (1或更多)'到了一个' char'是转换格式'。那里有几个公约:
当你从Arduino收到一些字节时,你需要告诉Python你遵循的约定。以下是一些例子:
# Receive data example
rawData = arduino.readLine()
myString = rawData.decode('utf-8')
print(myString)
# Transmit data example
myString = "Hello world"
rawData = myString.encode('utf-8')
arduino.sendLine(rawData)
我希望这有用: - )