获取数据并解码它会产生罕见的字符

时间:2016-04-19 14:59:52

标签: python matplotlib unicode decode

我正在尝试从Arduino获取一些数据,而我无法解码来自它的数据。我搜索了一些信息,我找到了这些答案,例如:

Introduction to Unicode

Unicode string to String in python

Arduino正在以8位编码(UTF-8)发送数字(数据)。 我尝试了很多不同的代码,我得到的最佳解码是:

The data that I have got from decoding

我使用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来显示两个按钮:一个用于开始搜索数据并显示它,另一个用于关闭窗口和端口。这是一个简单的窗口:

enter image description here

我如何解码(或编码,我现在真的不知道)来显示我需要的数字?我究竟做错了什么?我希望你能帮助我。

1 个答案:

答案 0 :(得分:1)

String本质上是一系列字符。每个字符都可以用一个或多个字节表示。这种映射来自'字节 - (1或更多)'到了一个' char'是转换格式'。那里有几个公约:

  • UTF-8
  • UTF-16
  • ASCII

当你从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)

我希望这有用: - )

相关问题