3
votes

I wrote a basic code for reading values from analog pin 0(I have a light sensor attached to it and the output is coming at analog pin 0) in python3 using pyfirmata, but it is giving the output as none no matter what. I tried the same code in arduino IDE and that is giving the right answer. Please help.

Code is :

from pyfirmata import Arduino, util
import time
board = Arduino('/dev/cu.usbmodem1411')

it = util.Iterator(board)
it.start()

board.analog[0].enable_reporting()

while True : 
            print (board.analog[0].read())
            time.sleep(1)    

Even when it gives an output after few seconds, it gives 0.29 which isn't actually the sensor value that comes on serial monitor. That value varies between 0 and 1023 and is relatively quite larger than this.

3

3 Answers

2
votes

The analog pins of Arduino linearly translate the input voltages between 0 and +5V to 0 and 1023. However, in pyFirmata , the values between 0 and +5V are linearly translated into the float values of 0 and 1.0. For example, if the voltage at the analog pin is 1V, an Arduino program will measure a value somewhere around 204, but you will receive the float value as 0.2 while using pyFirmata’s read() method in Python.

1
votes

You'll need to start an Iterator thread before reading

board = pyfirmata.Arduino("COM5") # change com port  
board.digital[3].mode = pyfirmata.INPUT  
it = pyfirmata.util.Iterator(board)  
it.start()  
board.digital[3].read()

Most of the time it work, but sometimes None still show up. Sometimes time.sleep can help.

-1
votes

You have to do an if conditional first, something like this (and try running analogfirmata):

while True:
 if board.analog[0].read() == None:
  pass
 else:
  print("board.analog[0].read()")