import socket
// open TCP client socket:
IPADDR = '192.168.99.9'
PORTNUM = 2101
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IPADDR, PORTNUM))
// send command to read A/D value: two hex bytes
tdata = bytes.fromhex('FEA4')
s.send(tdata)
// receive 2-byte (hex) reply
rdata=s.recv(256)
// close socket
s.close()
// convert reply to a voltage reference (unsigned short)
vRef = (rdata[0] * 256)+(rdata[1])
// convert vref to float as degrees Farenheit
degF = vRef * 4930 / 1024
degF = degF / 10
degF = degF - 273.15
degF = degF * 9 / 5 + 32
// open text file
fo = open("\mnt\stuff\temp.txt", "w")
// write formatted string as number only e.g., 32.6
fo.write("{:+.1f}.format(degF)\n")
// Close file
fo.close()
我不确定是否访问收到的数据并创建无符号短值。我将收到类似/ x02 / x55的内容,即(2 * 256)+85 = 597.
浮点数学,这里也不确定,但这就是我如何将597的读数转换为57.6的度数-F值
最后,我需要将字符串“57.6”写入文件。
最后,而不是在此代码中,我需要一种方法让RasPi每分钟运行一次此代码来更新文件。我有一个Web服务器,它读取文件并从中创建HTML文本。
感谢任何人的帮助......
答案 0 :(得分:1)
我假设您的套接字代码是正确的,我将修复注释:
import socket
# open TCP client socket:
IPADDR = '192.168.99.9'
PORTNUM = 2101
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IPADDR, PORTNUM))
# send command to read A/D value: two hex bytes
tdata = bytes.fromhex('FEA4')
s.send(tdata)
# receive 2-byte (hex) reply
rdata=s.recv(256)
# close socket
s.close()
我假设你的数学大多是正确的,但是如果你使用Python 2,如果rdata[0]
是一个整数(类int
),你可能会进行分层划分。
# convert reply to a voltage reference (unsigned short)
vRef = (rdata[0] * 256)+(rdata[1])
为安全起见,首先在其他计算之前将vRef转换为float:
vRef = float(rdata[0] * 256)+(rdata[1])
然后继续:
# convert vref to float as degrees Farenheit
degF = vRef * 4930 / 1024
degF = degF / 10
degF = degF - 273.15
degF = degF * 9 / 5 + 32
此:
# open text file
fo = open("\mnt\stuff\temp.txt", "w")
# write formatted string as number only e.g., 32.6
fo.write("{:+.1f}.format(degF)\n")
# Close file
fo.close()
可以替换为:
with open("\mnt\stuff\temp.txt", "w") as file:
file.write("{:+.1f}.format(degF)\n")
with
关键字将文件作为上下文管理器打开,并自动为您关闭文件,即使您的代码引发异常也是如此。 Sockets don't work as context managers in Python 2, unless you create a wrapper for it yourself.