python - 获取数据并解码它给出稀有字符

标签 python matplotlib unicode decode

我正在尝试从 Arduino 获取一些数据,但无法解码来自 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 或更多)”到“字符”的映射是“转换格式”。有几个约定:

  • 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)

我希望这对你有帮助:-)

关于python - 获取数据并解码它给出稀有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722179/

相关文章:

python - 难以在同一绘图上绘制函数、其一阶导数及其不定积分

python - 使用 Matplotlib 绘制正态分布

php - 在 MYSQL 数据库中存储多语言/unicode 字符(泰语、印地语、菲律宾语)

c# - 试图让 libmecab.dll (MeCab) 与 C# 一起工作

python - Matplotlib - 停止动画

WIndows MAPI unicode 问题

python - Tensorflow 和 cifar 10,测试单个图像

python - 我可以嵌套 virtualenvs 吗?

python - 以编程方式将模块/函数集转换为 Python 类

svg - 如何将刻度中的文本的原始字符串从 matplotlib 导出到 svg?