将温度从3个字节2的补充中转换
我正在尝试使用Raspberry Pi Pico运行Micropython读取ADC的内部温度(Texas仪器的ADS1235)。 Raspberry Pi Pico和ADC工作之间的SPI通信(我使用示波器检查)。 3个数据字节收到的表格ADC我必须变成一个数字:
数据在两者的补充中,首先是MSB。我试图从24位两位的补充二进制字符串变成负数或正数。一个正数计算可行,但对于负数(最重要的位是1),则没有。转换有一些功能吗?转换器函数的代码在其中模拟ADC发送3个字节以[0x81,0x00,0x00]的顺序发送3个字节:
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))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我编写了此功能,以进行从两者补充中写入的24位到小数的转换,您提供的示例提供的数字是
-8323072
,我在此处检查了此值: https://www.expleloringbinary.com/twos-complent-complent-complent-componment-componverter/ 。这是我写的代码:
您可以在 我在该节中呈现的公式中提供的算法提供了结果。
I wrote this function to do the conversion from 24 bit written in two's complement to decimal, the number you provided as an example turned out to be
-8323072
, I checked this value here: https://www.exploringbinary.com/twos-complement-converter/.Here is the code I wrote:
You can check on the wikipedia page for Two's Complement under the section Converting from two's complement representation that the algorithm I provided results in the formula they present in that section.