3

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
ButterCup
  • 71
  • 1
  • 4

3 Answers3

2

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.

  • Nice info! Your answer explains the (seemingly) strange values (e.g., 0.29). Any idea why the OP was seeing `None` as an output value sometimes, though? – evadeflow Dec 27 '17 at 18:13
  • For that you have to define the pin as an input pin. By defining the pin as an input you will be able to read values. Also you can cross check by using firmata GUI. – ABHI PANCHAL Dec 29 '17 at 01:54
1

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.

Hoppo
  • 1,130
  • 1
  • 13
  • 32
TUNAPRO1234
  • 106
  • 5
-1

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()")
ale
  • 6,369
  • 7
  • 55
  • 65