2017-03-17 59 views
0

我在寫一個簡單的代碼,可以使用模數轉換器MCP3008從模擬傳感器讀取數據。只是一個傳感器的第一個代碼工作好:現在我嘗試使用數組(或列表)這是一塊,如果我的代碼來概括這n個不同的傳感器:Raspberry Pi3上的python代碼:'float'對象沒有屬性'___getitem____'

#Define various arrays (for now only two elements) 
fsr_channel=range(2) 
fsr_level=range(2) 
fsr_volts=range(2) 
previous_fsr_level=range(2) 
previous_fsr_volts=range(2) 
flag=range(2) 

#Initialize to zero each arrays 
for i in range(2): 
    fsr_channel[i]=0 
    previous_fsr_level[i]=0 
    previous_fsr_volts[i]=0 
    flag[i]=0 

#Define delay between readings 
delay = 2 

while True: 
    for i in range(2): 
     #Read FSR value 
     fsr_level[i]=ReadChannel(i) 
     print(fsr_level[i]) 
     fsr_volts=ConvertVolts(fsr_level[i],2) 

     #print out result 
     print"--------------------------" 

     if fsr_volts[i]!=previous_fsr_volts[i]: 
      if (fsr_volts[i] > 0)&(flag[i]==0): 
       print("Object is positioned on the shelf (FSR{})".format(i)) 
      try: 
      curs.execute(""" INSERT INTO Records values(i, CURRENT_DATE(),NOW(),'Object is positioned on the shelf')""") 
      db.commit() 
      except: 
      db.rollback() 
      flag[i]=1 
      print("flag{}".format(flag)) 
      elif (fsr_volts[i]==0)&(flag[i]==1): 
       print("Object has left the shelf (FSR{})".format(i)) 
       try: 
       curs.execute(""" INSERT INTO Records values(2, CURRENT_DATE(),NOW(),'Object has left the shelf')""") 
      db.commit() 
      except: 
      db.rollback() 
      flag[i]=0 
      print("flag{}".format(flag)) 
    print("FSR{} volts: {}".format(i,fsr_volts[i])) 
    print("previous FSR{} volts: {}".format(i,previous_fsr_volts[i])) 
    previous_fsr_volts[i]=fsr_volts[i] 
#Wait before repeting loop 
time.sleep(delay) 

我得到這個錯誤信息:

if fsr_volts[i]!=previous_fsr_volts[i]: 
TypeError: 'float' object has no attribute '___getitem____' 

我不知道爲什麼會發生這種情況。 任何人都可以給我任何指示? 在此先感謝

+0

某處在代碼返回時,你正在做的浮點值(我們稱之爲'foo')和做'foo的[I]'。考慮到這一點,我猜'ConvertVolts()'返回一個浮點值或'previous_fsr_volts'是一個不能被索引的浮點數。 –

+0

謝謝Srdjani,我發現我的錯誤:當我打電話給ConvertsVolts時,我忘記了索引。正確的代碼是fsr_volts [i] == ConvertVolts(fsr_level [i],2) –

回答

0

什麼樣的數據回報來自:

fsr_volts=ConvertVolts(fsr_level[i],2) 

也爲previous_fsr_volts [I]

你可以通過使用類型

print(type(fsr_volts[i]), type(previous_fsr_volts[i])) 

然後將浮點類型轉換爲int:

int(var) 

可能是從功能

+0

謝謝SMFSW,我發現我的錯誤:我忘記索引時,我打電話給ConvertsVolts。正確的代碼是fsr_volts [i] == ConvertVolts(fsr_level [i],2) –

相關問題