气象站项目中的KeyError

时间:2018-11-15 10:18:07

标签: python raspberry-pi

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

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]))

1 个答案:

答案 0 :(得分:2)

您要检查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))