正如标题所暗示的,我正在尝试使用运行着micropython的raspberry Pi Pico来读取ADC的内部温度(准确地说,是来自德克萨斯仪器的ADS1235 )。
在Pico和ADC之间的SPI通信工作得很好,我使用了示波器来测量和检查。
当我必须处理从ADC接收到的3个数据字节,并将其转化为一个可以用于计算内部温度的数字时,问题就出现了。
图片显示了当我发出"Read命令“时收到的3个数据字节。
数据是在两个补充MSB接收的第一。我尝试过多种方法,从一个24位的双补码二进制字符串到一个负数或正数。
正数计算很好,但当我尝试一个负数(其中最重要的位数是1)时,它不工作。我有一种感觉,必须有一些功能或更容易的方式来进行转换,但我一直未能找到它。
我附加了当前转换器函数的代码和模拟ADC按以下顺序发送3个数据字节的主要部分: 0x81、0x00、0x00以及代码运行时的输出。
import string
def twos_comp_to_decimal(adcreading):
"""compute the int value of 2's complement 24-bit number"""
"""https://www.exploringbinary.com/twos-complement-converter/ look at "implementation" section"""
"""https://note.nkmk.me/en/python-bit-operation/#:~:text=Bitwise%20operations%20in%20Python%20%28AND%2C%20OR%2C%2
0XOR%2C%20NOT%2C,NOT%2C%20invert%3A%20~%206%20Bit%20shifts%3A%20%3C%3C%2C%20%3E%3E"""
signbit = False # Assume adc-reading is positive from the beginning
if adcreading >= 0b100000000000000000000000:
signbit = True
print("negative signbit")
if signbit:
print("inv string")
negativval = bin(~adcreading & 0b011111111111111111111111)
negativval = int(negativval)
negativval += 0b000000000000000000000001
negativval *= -1
return negativval
return adcreading
if __name__ == '__main__':
# tempdata = [0x80, 0xFF, 0x80]
tempdata = [0x81, 0x00, 0x00]
print("Slicing 3 databytes into one 24-bit number")
adc24bit = int.from_bytes(bytearray(tempdata), "big")
print(adc24bit)
print(hex(adc24bit))
print(bin(adc24bit))
print(twos_comp_to_decimal(adc24bit))
# print("Integer value: {}".format(adc24bit))
#temperatureC = ((adc24bit - 122.400) / 420) + 25
#print("Temp in celcius: {}".format(temperatureC))
发布于 2022-06-21 21:54:30
我编写了这个函数来完成从24位的两位补充到十进制的转换,作为示例提供的数字原来是-8323072
,我在这里检查了这个值:https://www.exploringbinary.com/twos-complement-converter/。
下面是我写的代码:
# example data
data = [0x81, 0x00, 0x00]
data_bin = bytearray(data)
def decimal_from_two_comp(bytearr):
string = ''
for byte in bytearr:
string = string + f'{byte:08b}'
# string with the the 24 bits
print(string)
# conversion from two complement to decimal
decimal = -int(string[0]) * 2**23
for i,num in enumerate(string[1:]):
num = int(num)
decimal += num * 2**(23 - (i + 1))
return decimal
您可以检查维基百科页面 for 2的补体,在https://en.wikipedia.org/wiki/Two%27s_complement#Converting_from_two%27s_complement_representation节下,我提供的算法在该节中给出的公式中得到了结果。
https://stackoverflow.com/questions/72507468
复制相似问题