我正在处理的气象站项目出现类似错误。错误如下:

Traceback (most recent call last):
  File "wind_direction_byo.py", line 27, in <module>
    print('Unknown value: ' + str(wind) + ' ' + str(volts[wind]))
KeyError: 0.0


这是我尝试执行的源文件代码:

   from gpiozero import MCP3008
import time
import math
adc = MCP3008(channel=0)
count = 0
values = []
volts = {0.4: 0.0,
         1.4: 22.5,
         1.2: 45.0,
         2.8: 67.5,
         2.7: 90.0,
         2.9: 112.5,
         2.2: 135.0,
         2.5: 157.5,
         1.8: 180.0,
         2.0: 202.5,
         0.7: 225.0,
         0.8: 247.5,
         0.1: 270.0,
         0.3: 292.5,
         0.2: 315.0,
         0.6: 337.5}

while True:
    wind = round(adc.value*3.3,1)
    if not wind in volts:
        print('Unknown value: ' + str(wind) + ' ' + str(volts[wind]))
    else:
        print('Found: ' + str(wind) + ' ' + str(volts[wind]))

最佳答案

您要检查wind词典中是否有volts,并且缺少它时,您仍然尝试访问它:

if not wind in volts:
    print('Unknown value: ' + str(wind) + ' ' + str(volts[wind]))


如果不存在,则无法访问。从您的打印品中删除它:

if not wind in volts:
    print('Unknown value: ' + str(wind))

09-26 05:29