我是python的新手,我正在尝试使用LibMPSSE库从霍尼韦尔差压传感器读取压力数据。我是从Adafruit FT232H芯片上读到的,我在ubuntu Linux上使用的是python 2.7.6。
#!/usr/bin/env python
from mpsse import *
SIZE = 2 # 2 bytes MSB first
WCMD = "\x50" # Write start address command
RCMD = "\x51" # Read command
FOUT = "eeprom.txt" # Output file
try:
eeprom = MPSSE(I2C)
# print "%s initialized at %dHz (I2C)" % (eeprom.GetDescription(), eeprom.GetClock())
eeprom.Start()
eeprom.Write(WCMD)
# Send Start condition to i2c-slave (Pressure Sensor)
if eeprom.GetAck() == ACK:
# ACK received,resend START condition and set R/W bit to 1 for read
eeprom.Start()
eeprom.Write(RCMD)
if eeprom.GetAck() == ACK:
# ACK recieved, continue supply the clock to slave
data = eeprom.Read(SIZE)
eeprom.SendNacks()
eeprom.Read(1)
else:
raise Exception("Received read command NACK2!")
else:
raise Exception("Received write command NACK1!")
eeprom.Stop()
print(data)
eeprom.Close()
except Exception, e:
print "MPSSE failure:", e
根据库,Read返回一个大小字节的字符串,每当我想打印数据时,我看到的唯一输出是 2 T_`ʋ Q} * / eE 。我尝试用utf-8进行编码但仍然没有运气。
答案 0 :(得分:0)
当字符串中的字节/字符(在您的情况下为data
)包含不可打印的字符时,Python可能会打印“怪异”输出。要“查看”各个字节的内容(如整数或十六进制),请执行以下操作:
print(','.join(['{:d}'.format(x) for x in map(ord, data)])) # decimal
或
print(','.join(['{:02X}'.format(x) for x in map(ord, data)]))
由于data
缓冲区的长度由SIZE=2
设置,要从整个缓冲区中提取每个字节作为整数,您可以执行以下操作:
hi, lo = map(ord, data)
# or:
hi = ord(data[0])
lo = ord(data[1])
要详细了解ord
及其作用,请参阅https://docs.python.org/2/library/functions.html#ord