Giter Club home page Giter Club logo

pyfirmata's Introduction

pyFirmata

pyFirmata is a Python interface for the Firmata protocol. It is fully compatible with Firmata 2.1, and has some functionality of version 2.2. It runs on Python 2.7, 3.6 and 3.7.

Test & coverage status:

https://travis-ci.org/tino/pyFirmata.png?branch=master https://coveralls.io/repos/github/tino/pyFirmata/badge.svg?branch=master

Installation

The preferred way to install is with pip:

pip install pyfirmata

You can also install from source with python setup.py install. You will need to have setuptools installed:

git clone https://github.com/tino/pyFirmata
cd pyFirmata
python setup.py install

Usage

Basic usage:

>>> from pyfirmata import Arduino, util
>>> board = Arduino('/dev/tty.usbserial-A6008rIF')
>>> board.digital[13].write(1)

To use analog ports, it is probably handy to start an iterator thread. Otherwise the board will keep sending data to your serial, until it overflows:

>>> it = util.Iterator(board)
>>> it.start()
>>> board.analog[0].enable_reporting()
>>> board.analog[0].read()
0.661440304938

If you use a pin more often, it can be worth it to use the get_pin method of the board. It let's you specify what pin you need by a string, composed of 'a' or 'd' (depending on wether you need an analog or digital pin), the pin number, and the mode ('i' for input, 'o' for output, 'p' for pwm). All seperated by :. Eg. a:0:i for analog 0 as input or d:3:p for digital pin 3 as pwm.:

>>> analog_0 = board.get_pin('a:0:i')
>>> analog_0.read()
0.661440304938
>>> pin3 = board.get_pin('d:3:p')
>>> pin3.write(0.6)

Board layout

If you want to use a board with a different layout than the standard Arduino or the Arduino Mega (for which there exist the shortcut classes pyfirmata.Arduino and pyfirmata.ArduinoMega), instantiate the Board class with a dictionary as the layout argument. This is the layout dict for the Mega for example:

>>> mega = {
...         'digital' : tuple(x for x in range(54)),
...         'analog' : tuple(x for x in range(16)),
...         'pwm' : tuple(x for x in range(2,14)),
...         'use_ports' : True,
...         'disabled' : (0, 1, 14, 15) # Rx, Tx, Crystal
...         }

Todo

The next things on my list are to implement the new protocol changes in firmata:

pyfirmata's People

Contributors

anner-dejong avatar appultaart avatar curzona avatar fabaff avatar harveyf2801 avatar jochasinga avatar joseu avatar koniarik avatar tino avatar utahdave avatar vido avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyfirmata's Issues

problem with basic usage code

Hello, I am trying to light up a LED using your basic usage code from the Readme (but I use board.digital[13], as it is the built-in LED for the Arduino Leonardo) and nothing happens. I also tried to light up LEDs connected to other digital pins. If I write a value into a digital pin and then read it, I successfully get the same value.

from pyfirmata import Arduino, util
board = Arduino('/dev/tty.usbmodem141101')
board.digital[13].write(1)

Could you give me some advice?

I am using Arduino Leonardo and MacBook (Retina, 12-inch, 2017) with macOS 10.14, pyfirmata 1.0.3 and Python 3.6.5.

Using sysex

I'm using a modified version of StandardFirmata. It has capabilities of measuring distances with a HC-SR04.

How to use pyFirmata's send_sysex (the sysex_cmd = 0x74)?

The HC-SR04 has 4 pins: GND and VCC
And a Trigger-pin connected to an output pin.
And a Echo-pin connected to an input pin.

I have to send a HIGH-command to the Trigger-pin for one second, after that it goes back to LOW.
After that StandardFirmata sends the time the triggered pulse travels.
How to get that output of StandardFirmata?

Python 3 installation

Hi

I've tried installing pyFirmata with both pip and manual setup.py script and both times it failed due to invalid syntax errors.

Your site states that the library is passing python 3 tests but since I'm a python noob I'd like to ask it if is possible to install the library or should I just not bother and revert to Python 2.7.x?

PIP fails in the same part as setup.py execution. What is troubling is that pip actually thinks that the package was installed successfully so I tried running the "Basic usage" script anyway with the following result:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    from pyfirmata import Arduino, util
  File "C:\Python34\lib\site-packages\pyfirmata\__init__.py", line 2, in <module
>
    from boards import BOARDS
ImportError: No module named 'boards'

I'm running on a fresh Python 3.4 install on Windows.

E:\dev\...\pyFirmata>python setup.py install
C:\Python34\lib\distutils\dist.py:260: UserWarning: Unknown distribution option:
 'include_package_data'
  warnings.warn(msg)
C:\Python34\lib\distutils\dist.py:260: UserWarning: Unknown distribution option:
 'install_requires'
  warnings.warn(msg)
C:\Python34\lib\distutils\dist.py:260: UserWarning: Unknown distribution option:
 'zip_safe'
  warnings.warn(msg)
running install
running build
running build_py
creating build
creating build\lib
creating build\lib\pyfirmata
copying pyfirmata\__init__.py -> build\lib\pyfirmata
copying pyfirmata\boards.py -> build\lib\pyfirmata
copying pyfirmata\mockup.py -> build\lib\pyfirmata
copying pyfirmata\pyfirmata.py -> build\lib\pyfirmata
copying pyfirmata\util.py -> build\lib\pyfirmata
running install_lib
copying build\lib\pyfirmata\__init__.py -> C:\Python34\Lib\site-packages\pyfirma
ta
copying build\lib\pyfirmata\boards.py -> C:\Python34\Lib\site-packages\pyfirmata

copying build\lib\pyfirmata\mockup.py -> C:\Python34\Lib\site-packages\pyfirmata

copying build\lib\pyfirmata\pyfirmata.py -> C:\Python34\Lib\site-packages\pyfirm
ata
copying build\lib\pyfirmata\util.py -> C:\Python34\Lib\site-packages\pyfirmata
byte-compiling C:\Python34\Lib\site-packages\pyfirmata\__init__.py to __init__.c
python-34.pyc
byte-compiling C:\Python34\Lib\site-packages\pyfirmata\boards.py to boards.cpyth
on-34.pyc
byte-compiling C:\Python34\Lib\site-packages\pyfirmata\mockup.py to mockup.cpyth
on-34.pyc
  File "C:\Python34\Lib\site-packages\pyfirmata\mockup.py", line 127
    raise IOError, "Cannot read from pin %d" \
                 ^
SyntaxError: invalid syntax

byte-compiling C:\Python34\Lib\site-packages\pyfirmata\pyfirmata.py to pyfirmata
.cpython-34.pyc
  File "C:\Python34\Lib\site-packages\pyfirmata\pyfirmata.py", line 438
    raise IOError, "%s is not an input and can therefore not report" % self
                 ^
SyntaxError: invalid syntax

byte-compiling C:\Python34\Lib\site-packages\pyfirmata\util.py to util.cpython-3
4.pyc
  File "C:\Python34\Lib\site-packages\pyfirmata\util.py", line 27
    raise IOError, "No boards found in %s with identifier %s" % (base_dir, ident
ifier)
                 ^
SyntaxError: invalid syntax

running install_egg_info
removing 'C:\Python34\Lib\site-packages\pyFirmata-0.9.5-py3.4.egg-info' (and eve
rything under it)
Writing C:\Python34\Lib\site-packages\pyFirmata-0.9.5-py3.4.egg-info

pin write and python sleep() issue?

Hi tino,

First I want to say thank you for your work. Really appreciate that. I have a question regarding the Python 3 time sleep() function. My set up is consisted of the Arduino UNO running Firmata firmware and a PC/laptop running python code using pyfirmata library.

What I am trying to do is to analog write to a PWM pin from a list of values (100 values in this case). I also want them to output in every 0.001 second or 1 ms. Therefore, technically, 100 values in 0.001s/each would take ~0.1 sec to complete.

Then the problem happened when I used timer to see how long it would take. It only achieved ~0.1 sec total when Google Chrome was opened on certain websites (I know it seems weird, but it's true 100%). Even when I minimized Google Chrome, the total time would slow down to 1.6s consistently until I opened Chrome again.

Then I tried to take off my time.sleep(0.001) in my loop then it worked fine regardless the appearance of Chrome or not.

I really want to understand why and a solution for this case. Maybe an alternative of time.sleep? Here is my code in python. You can load the firmata sketch from Arduino IDE.

Also note at higher value of time.sleep(), everything works fine with or without Chrome opened.

import pyfirmata
import time
from timeit import default_timer as timer

board = pyfirmata.Arduino("COM4", baudrate = 115200)
pwmPin = board.get_pin('d:5:p') #digital pin 5 pwm mode

my_points = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]

def LoadWaveform():
   rate = 1/1000
   #print (my_points)
   while True:
      start = timer()
      for i in range(len(my_points)):
         pwmPin.write(my_points[i])
         time.sleep(rate)

      end = timer()
      print ("Total time run: ", end - start)
      time.sleep(1)

LoadWaveform()

Analog input already having a reading when nothing is connected to it

Hi Tino,

Thanks for your great work!

I was trying to implement pyFirmata for the first time, but i was reading even when no voltage signal is connected to the assigned analogue input.

Please find my code below:

#!/usr/bin/python

from pyfirmata import Arduino, util
import time

board = Arduino('/dev/ttyACM3')
it = util.Iterator(board)
it.start()
analog_pin = board.get_pin('a:2:i')
analog_pin.enable_reporting()
led = board.get_pin('d:13:o')
while 1:

   reading =  analog_pin.read()
   if reading != None:
             voltage = reading * 5 
             print("Reading = %f\tVoltage = %f" %(reading, voltage))
             led.write(1)
             time.sleep(1)
             led.write(0)
             time.sleep(2)

Looking forward to receiving your possible support

Thanks in advance.

Timing issue with analog reads

Hi,

I could not manage to setup a reliable connection between my pc and arduino (standard firmata sketch). The confusing part is that it all seems to work in the python command line, but when running the example code in a small script, analog reads return 'None'. After inserting a little pause (emulating manual execution in the python shell), analog read does output some values.

Here's my test-script:

#!/usr/bin/env python
import time
from pyfirmata import Arduino, util
board = Arduino('/dev/ttyUSB0')
it = util.Iterator(board)
it.start()
board.analog[0].enable_reporting()
print board.analog[0].read()
print board.analog[0].read()
print board.analog[0].read()
print board.analog[0].read()
time.sleep(1)
print board.analog[0].read()
print board.analog[0].read()
print board.analog[0].read()
print board.analog[0].read()
board.exit()

...and it's output:

None
None
None
None
0.6354
0.6354
0.6354
0.6354

As mentioned, when just typing the statements in the python shell it just seems to work fine:

>>> import time
>>> from pyfirmata import Arduino, util
>>> board = Arduino('/dev/ttyUSB0')
>>> it = util.Iterator(board)
>>> it.start()
>>> board.analog[0].enable_reporting()
>>> print board.analog[0].read()
0.6129
>>> print board.analog[0].read()
0.567
>>> print board.analog[0].read()
0.5787
>>> print board.analog[0].read()
0.607
.... etc

Used hard-/software:
pyFirmata 0.95 in python 2.7.3
Firmata 2.3.5 on an Arduino duemilanova (ATmega328 version)

Any clue?

Bests,

Bram

Read/write I2C

Is there a way to read and write over I2C? I may be totally missing it.

Delays between servo movements in pyfirmata don't work

I'm writing a program in python where moving servos at specific times is a crucial part of the project. To achive this, I am using the pyfirmata library.
I've tried two methods of delays, but none of them seem to work. When I run the code, the servo turns the first time, but after the delay, it doesn't turn and the program just stops, instead of moving the servo to 0 degrees and then stopping.

This is the one with the board.pass_time() built in to the pyfirmata library:

from pyfirmata import Arduino, util
import time
board = Arduino('COM3')
servo = board.get_pin('d:9:s')
servo.write(180)        #This works and turns the servo
time.sleep(1)
servo.write(0)          #This time the servo does not turn, then the program ends

And here's the one with time.sleep():

from pyfirmata import Arduino, util
board = Arduino('COM3')
servo = board.get_pin('d:9:s')
servo.write(180)        #This works and turns the servo
board.pass_time(1)
servo.write(0)          #This time the servo does not turn, then the program ends

I would highly appreciate if someone could help.

Thank you, David

Request socket based serial port connection

I would like to be able to open a socket stream and not be limited to a hardwired serial connection, this is useful for devices that have Wifi shields or are just plain old wifi devices themselves that have some capability. This firmata protocol works great over a wire with no need to craft a protocol that does the same thing. The ask is to add SocketSerial to the code base.

if port is of the form ipaddr:port then a socket is opened instead of a serial connection. see PL #58

read analog pins

I have simple code which reads A0 and i have my DMM next to me which says its 0.002V and pyfirmata gives me None
0.1955
0.1848
0.1848
0.1828
0.1828
0.2991
0.3226
0.3255

when I Multiply with 5v I dont even get the value which is on the DMM. So let me know if you what I should do to fix it. the Values are inconsistent. Basically there is not voltage at that pin but and times I get random values. I know that for 0 to 5v its 0-1 in pyfirmata.

Version bump (0.9.6) and deploy

Looks like there have been a number of changes since 0.9.5. We need to bump and deploy. I don't have access to pypi so you'll have to do it.

LMK if you have any issues with this. If not, I'll tag and bump and you can push.

SyntaxError: invalid Syntax

I am interested in any help that I can get installing on CentOS5 (64 bit). Thanks!

[dradams@MercuryCentOS bin]$ pip-python install pyfirmata
Downloading/unpacking pyfirmata
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/pip/basecommand.py", line 124, in main
self.run(options, args)
File "/usr/lib/python2.4/site-packages/pip/commands/install.py", line 178, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/usr/lib/python2.4/site-packages/pip/req.py", line 890, in prepare_files
location = req_to_install.build_location(self.build_dir, not self.is_download)
File "/usr/lib/python2.4/site-packages/pip/req.py", line 147, in build_location
_make_build_dir(build_dir)
File "/usr/lib/python2.4/site-packages/pip/req.py", line 1125, in _make_build_dir
os.makedirs(build_dir)
File "/usr/lib64/python2.4/os.py", line 159, in makedirs
mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/usr/bin/build'

Storing complete log in /home/dradams/.pip/pip.log
[dradams@MercuryCentOS bin]$ sudo pip-python install pyfirmata
[sudo] password for dradams:
Sorry, try again.
[sudo] password for dradams:
Downloading/unpacking pyfirmata
Downloading pyFirmata-0.9.5.tar.gz
Running setup.py egg_info for package pyfirmata
Traceback (most recent call last):
File "", line 14, in ?
File "/usr/bin/build/pyfirmata/setup.py", line 5
with open('README.rst') as f:
^
SyntaxError: invalid syntax
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

File "", line 14, in ?

File "/usr/bin/build/pyfirmata/setup.py", line 5

with open('README.rst') as f:

        ^

SyntaxError: invalid syntax


Command python setup.py egg_info failed with error code 1
Storing complete log in /home/dradams/.pip/pip.log

[dradams@MercuryCentOS .pip]$ cat pip.log

/usr/bin/pip-python run on Sun Jan 5 12:06:50 2014
Downloading/unpacking pyfirmata
Getting page http://pypi.python.org/simple/pyfirmata
URLs to search for versions for pyfirmata:

SyntaxError: invalid syntax


Command python setup.py egg_info failed with error code 1
Exception information:
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/pip/basecommand.py", line 124, in main
self.run(options, args)
File "/usr/lib/python2.4/site-packages/pip/commands/install.py", line 178, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/usr/lib/python2.4/site-packages/pip/req.py", line 927, in prepare_files
req_to_install.run_egg_info()
File "/usr/lib/python2.4/site-packages/pip/req.py", line 219, in run_egg_info
command_desc='python setup.py egg_info')
File "/usr/lib/python2.4/site-packages/pip/init.py", line 237, in call_subprocess
raise InstallationError(
InstallationError: Command python setup.py egg_info failed with error code 1
[dradams@MercuryCentOS .pip]$

Compatibility and Python 3.6

Hello:

I'm new using firmata protocol, and looking a first steps guide...

pyFirmata was installed well aparantely in Python 3.6... is recommendable to use it on Python 3.6?

This library is compatible with all arduino boards?

Thank you

sending strings with send_sysex

First of all thank you for the library, it's great 👍 :)

I'm trying to send some strings from my python script to my arduino using send_sysex, so the string got displayed on a LCD screen (GLCD lib)

in my .py script, I'm trying

board.send_sysex(0x71, ["test message"])

0x71 being STRING_DATA message

and on my arduino

void lcdDisplayString(char *msg){
  GLCD.CursorTo(0,1);
  GLCD.print(msg);
}

void setup(){
/*
some init code here
*/
Firmata.setFirmwareVersion(0,1);
Firmata.attach(STRING_DATA, lcdDisplayString);
Firmata.begin(57600);
}

However, I'm getting some malformed characters from the display.
I'm wondering if the send_sysex() function from pyFirmata and the Firmata.processInput() in Arduino are sending and accepting the whole string or characters one by one.

TypeError: unorderable types: NoneType() > int()

i'm trying to turn OFF and ON an LED according to the data from a LDR using this code:

from pyfirmata import Arduino, util
board=Arduino('/dev/ttyACM1')
led=board.get_pin('d:13:0')
ldr=board.analog[0]
it = util.Iterator(board)
it.start()
board.analog[0].enable_reporting()
x=board.analog[0].read()
if x>20:
	led.write(0)
else:
	led.write(1)


and it gives me this error
TypeError: unorderable types: NoneType() > int()

whereas using the board.analog[0].read() in a python shell give a float.
What am i doing wrong here?

Code is able to upload but not working with arduino uno

Hello,
I wanted to turn on and off LED connected on digital pin 13 using Pyfirmata from Anaconda, spyder. The problem is no matter which digital pin I give, it is only affecting the RX LED. I have tried same connection with same logic code in arduino IDE to make sure the connection is right. It is working fine with arduino IDE not with python. I am using anaconda spyder 2.7, 64 bit on 64 bit windows 10. I am writing you the code also. Thanks.

code:
from pyfirmata import Arduino , util
import time
board = Arduino ('COM3')
iterator = util.Iterator(board)
iterator.start ()
LED_blink = board.get_pin('d:13:o') // Only RX pin is blinking, tried other pin but same result
LED_blink.write(1)
time.sleep(0.1)
LED_blink.write(0)
time.sleep(0.1)
board.exit()

Add Capability Query

Capability Query (added in version 2.2) These queries are intended to allow GUI-based programs to discover the capabilities and current state of any board running Firmata. The idea is to facilitate displaying highly accurate on-screen representation of the board. The capabilities query provides a list of all modes supported by all pins, and the resolution used by each mode.

/* capabilities query

0 START_SYSEX (0xF0) (MIDI System Exclusive)
1 capabilities query (0x6B)
2 END_SYSEX (0xF7) (MIDI End of SysEx - EOX)
/

capabilities response

0 START_SYSEX (0xF0) (MIDI System Exclusive)
1 capabilities response (0x6C)
2 1st mode supported of pin 0
3 1st mode's resolution of pin 0
4 2nd mode supported of pin 0
5 2nd mode's resolution of pin 0
... additional modes/resolutions, followed by a single 127 to mark the end of the first pin's modes. Each pin follows with its mode and 127, until all pins implemented.

N END_SYSEX (0xF7)
Each pin shall have 2 bytes for each supported mode, and a single 127 to mark the end of that pin's data. The number of pins supported shall be inferred by the message length. The GUI should use this query to discover how many pins exist. The list of supported modes may be used to provide a mode configuration menu that only shows the valid choices when the user configures a pin, or disables/grays choices which do not apply. The resolution information may be used to adapt to future implementations where PWM, Analog and others may have different resolution.

Mockup use is unclear

Hi There!

I love your project, it's been incredibly useful. While actually reading from the board has been working fine, I've been having a hard time setting up the mockup board for testing. I'd love to be able to mockup a board so I don't have to have the arduino physically plugged in to keep developing on my project.

I checked the tests.py file, but the only example just checked that MockupBoard passed the same tests as it's parent class. Documentation for MockupPort/MockupSerial/MockupPin would be absolutely fantastic.

~Earl St Sauver

Blink an LED with DIGITAL_PULSE 0x91

first of all thanks for the nice library.
Im just trying to setup an LED blink function with standardFirmata. But I didnt find the Sysex in Firmata.h.
I did so, but I think it wont work.

#define DIGITAL_PULSE 0x91

void Digitalpulsecallback()
{
digitalWrite(13, LOW);
delayMicroseconds(1000);
digitalWrite(13, HIGH);
delayMicroseconds(1);
digitalWrite(13, LOW);
delayMicroseconds(1000);
}

void setup()
{
Firmata.attach(DIGITAL_PULSE, Digitalpulsecallback);
}

Is there someone, who knows how to make this and what should I in standardFirmata add? Thanks!

Missing example of handlers - migrating to 2.2?

I think I understand the way that handlers are bound to Firmata events (via add_cmd_handler) but I'm flummoxed how to tell what kind of structure my handler function should have so that introspection serves out arguments correctly for a new command binding (beyond the analog and digital bindings you've already provided).

Are there examples or documentation I've missed, for example, detailing how to add a handler for an arbitrary string command, as sent from the Firmata function "sendString" ? If not, would it be possible to create an example or a note about how add_cmd_handler works/might work for the range of possible transmissions listed at...
http://www.firmata.org/wiki/V2.2ProtocolDetails
...or even...
http://www.firmata.org/wiki/V2.3ProtocolDetails

Is it simply about defining a function with a single named/unnamed byte argument per byte expected beyond the command byte, then unmarshalling them in ways which reflect the protocol?

I'm guessing that moving towards 2.2/2.3 is mainly about this kind of binding, but I don't know if there's a structural problem with the current code passing through the newer messages since 2.1. This might be another area which I can get to in coming months.

board.getpin( ).write( ) | ArduinoMega2560 problem

Hi, i'm developer for team school project where we use servo motors, and i found your firmata client as most suitable for us but i'm having problems with sending commands.
As in your example stands

import pyfirmata
board = pyfirmata.ArduinoMega('PORT')

pin = board.get_pin('parameters')

pin.write(value)

im trying to use DIGITAL I/O pins (22 - 54) with parameter 'd:22:s' in get_pin but there is my problem that it won't do anything after passing pin.write
only case where it works for me is when i set servo pins at arduino PWM pins (2-14), parameter 'd:2:s'
but when i tried firmata test software setting servo at digital pins 22 - 54 it work's like expected
im trying to find where is problem but i can't find out if it's known bug or there is something that i doing wrong

and also i noticed at the start the function write() of class Pin is called with value 0 that cause painful flick to servo motors

Pyfirmata, no voltage in Arduino board

I am trying to use to access the pins on my Arduino board, everything seems to be working, i receive no error. I see the RX LED blinks, but can not get any voltage or reading from any pins whatsoever, I use Python 3.7.0.

Also, when you write, 0.8 for example, and then read from the pin, it is going to print the same number, but physically no voltage.

**** Sample code****

import pyfirmata

from pyfirmata import Arduino, util
board = Arduino("COM4")

iterator=util.Iterator(board)
iterator.start()
D11=board.get_pin('d:11:p')
D11.write(0.8)
I copied and ran many codes. One thing in comment, the codes run with no error. but, physically the non of the pins work.

I tested two different boards (one is brand new Aurdino Uno). same issue.

Could you please advise what could be the source of issue?

Thanks

board.digital[pin].write(1) not working?

Hi! I am a Django Developer and new to arduino. I am trying to light up a LED using the basic usage code from the docs

from pyfirmata import Arduino, util
board = ArduinoMega("COM4")
board.digital[8].write(1)

But I just cant make it work. Can you help me with this?
I am using arduino mega 2560 and running on windows 7.

check if port is opened

Hi,
i'd like to control arduino from animation package called Autodesk Maya. I'm also quite new to python, so forgive me stupid questions, please.

Lets say I'm running this script in Maya:

from pyfirmata import ArduinoMega, util
port = "COM3"
board = ArduinoMega(port)

and then some "for loop"

But if i'll run that script again, maya retuns:
SerialException: could not open port 'COM3': WindowsError(5, 'Access is denied.')

So id like to check if COM3 is already connected.I've tried following code, but it's obviously nonsense:

port = "COM3"
if ArduinoMega(None):     # is there some bolean which tells me if i've already assigned board to COM3 or not ? 
     board = ArduinoMega(port)
     print board
else:
     print "already connected"

Is there some way how to do it, please ?

Add Extended Analog

Extended Analog (added in version 2.2) As an alternative to the normal analog message, this extended version allows addressing beyond pin 15, and supports sending analog values with any number of bits. The number of data bits is inferred by the length of the message.

/* extended analog

0 START_SYSEX (0xF0) (MIDI System Exclusive)
1 extended analog message (0x6F)
2 pin (0 to 127)
3 bits 0-6 (least significant byte)
4 bits 7-13
... additional bytes may be sent if more bits needed
N END_SYSEX (0xF7) (MIDI End of SysEx - EOX)
/

pyfirmata in a fast loop

Hello,

I'd like to use pyfirmata to read values from analog port of arduino and display it on a screen using a raspberry pi and pygame. My python code looks like the following :

imports
variables definitions
pygame configuration
board=Arduino('/dev/ttyUSB0',baudrate=9600)
it=util.Iterator(board)
it.start()
board.analog[1].enable_reporting()
board.analog[2].enable_reporting()
sleep(0.5)

while True:
    val1=board.analog[1].read()
    val2=board.analog[2].read()

    computing values from val1 and val2
    displaying values using pygame

it works well on a raspberry pi B+
But on a raspberry pi 2 wich is faster, i can get first analog values then values are not updated, i can see the Arduino Tx light stop blinking after approx 1second.

If i add a sleep(0.1) at the end of the while loop, it works but my animation is not smooth.

Do i stress pyfirmata too much ?

I have tried to read analog values every 10 loops this way (i is iniated at value 0) :

if (i==0):
    val1=board.analog[1].read()
    val2=board.analog[2].read()
i=i+1
if (i>10):
    i=0

but it doesn't works (tx led stays off after 1s)

How can i have updated values without slowing my loop please ? I only want the latest up to date analog value of analog1 and analog2

I hope it's clear, sorry for my poor english.

Regards

Capabilities query parsing

In util.py in function pin_list_to_board_dict there are some assumptions which may not be always true:

  • for digital pin order [0,1,1,1] is assumpted, but Firmata protocol does not specifiy order of modes (so [1,1,0,1] may appear too and it is correct format)
  • for analog, pwm and servo pins resolution is hardcoded and expected as 10, 8 and 14 bytes, but it may varry depending to a hardware

For example I have some board, which returns this byte array of capabilities for some pin: [0, 1, 11, 1, 1, 1, 4, 14]
I think we need to save capabilities for the pins in more general way.

@tino have you any idea how do you want to implement these features? I am ready to implement them and send a pull request (and other pull request to add pin state queries).

Add Analog Mapping Query

Analog messages are numbered 0 to 15, which traditionally refer to the Arduino pins labeled A0, A1, A2, etc. However, these pins are actually configured using "normal" pin numbers in the pin mode message, and when those pins are uses for non-analog functions. The analog mapping query provides the information about which pins (as used with Firmata's pin mode message) correspond to the analog channels.

/* analog mapping query

0 START_SYSEX (0xF0) (MIDI System Exclusive)
1 analog mapping query (0x69)
2 END_SYSEX (0xF7) (MIDI End of SysEx - EOX)
/

/* analog mapping response

0 START_SYSEX (0xF0) (MIDI System Exclusive)
1 analog mapping response (0x6A)
2 analog channel corresponding to pin 0, or 127 if pin 0 does not support analog
3 analog channel corresponding to pin 1, or 127 if pin 1 does not support analog
4 analog channel corresponding to pin 2, or 127 if pin 2 does not support analog ... etc, one byte for each pin
N END_SYSEX (0xF7)
/
The above 2 queries provide static data (should never change for a particular board). Because this information is fixed and should only need to be read once, these messages are designed for a simple implementation in StandardFirmata, rather that bandwidth savings (eg, using packed bit fields).

InvalidPinDefError at the moment of definition the pins

I`m trying to use pyfirmata to send and receive data between Arduino Uno R3 and my python program. At Arduino installed StandartFirmata sketch.

from time import sleep
import serial
import pyfirmata
com_port_number = str(int(input('Введите номер COM-порта ')))
port = 'COM' + com_port_number   # COM port number
print('Выбран порт COM ', port)
try:
        board = pyfirmata.Arduino(port)
except serial.SerialException:
        print('Не удается подключится к выбранному COM-порту')
        com_port_number = str(int(input('Введите номер СОМ-порта')))
        port = 'COM' + com_port_number
        board = pyfirmata.Arduino(port)
sleep(1)
it = pyfirmata.util.Iterator(board)
it.start()
temp_list = []
potentiomentr = board.get_pin('a:0:o')
acid_control = board.get_pin('a:2:o')
stock_control = board.get_pin('a:3:o')
temperature_pin = board.get_pin('d:4:i')    # well, this line is worked fine. Temperature sensor works correctly
in_connection_pc = board.get_pin('d:0:o')   #but now i have InvalidPinDefError
triac = board.get_pin('d:6:o')
level = board.get_pin('d:8:i')
in_engine = board.get_pin('d:5:o')
in_triac = board.get_pin('d:10:o')
in_pump = board.get_pin('d:11:o')
drive_control = board.get_pin('d:12:o')
pump_control = board.get_pin('d:13:o')
while 1:   # бесконечный цикл
    a = temperature_pin.read()
    b = in_connection_pc.write(1)
    print(a)
    list.append(a,b)
    print(list)
    sleep(3)
board.exit()

But i have some strange mistake:

Traceback (most recent call last):
  File "C:/Users/lomil/PycharmProjects/Pyython_and_CSV_love/test_analog.py", line 22, in <module>
    in_connection_pc = board.get_pin('d:0:i')   #but now i have InvalidPinDefError??
  File "C:\Users\lomil\Python_32\lib\site-packages\pyfirmata\pyfirmata.py", line 220, in get_pin
    raise InvalidPinDefError('Invalid pin definition: UNAVAILABLE pin {0} at position on {1}'.format(pin_def, self.name))
pyfirmata.pyfirmata.InvalidPinDefError: Invalid pin definition: UNAVAILABLE pin d:0:i at position on COM1

When I commented all lines except
temperature_pin = board.get_pin('d:4:i')
it worked. But I can`t understand what wrong with other pins. They are totally good and worked fine when I writed test sketch to Arduino.

Add Pin State Query

Pin State Query (added in version 2.2)
The pin state query allows the GUI to read the current configuration of any pin. Normally this is needed when a GUI-based program starts up, so it can populate on-screen controls with an accurate representation of the hardware's configuration. This query can also be used to verify pin mode settings are received properly.

/* pin state query

0 START_SYSEX (0xF0) (MIDI System Exclusive)
1 pin state query (0x6D)
2 pin (0 to 127)
3 END_SYSEX (0xF7) (MIDI End of SysEx - EOX)
/

/* pin state response

0 START_SYSEX (0xF0) (MIDI System Exclusive)
1 pin state response (0x6E)
2 pin (0 to 127)
3 pin mode (the currently configured mode)
4 pin state, bits 0-6
5 (optional) pin state, bits 7-13
6 (optional) pin state, bits 14-20 ... additional optional bytes, as many as needed
N END_SYSEX (0xF7)
/
The pin "state" is any data written to the pin. For output modes (digital output, PWM, and Servo), the state is any value that has been previously written to the pin. A GUI needs this state to properly initialize any on-screen controls, so their initial settings match whatever the pin is actually doing. For input modes, typically the state is zero. However, for digital inputs, the state is the status of the pullup resistor. The pin state query can also be used as a verification after sending pin modes or data messages.

Iterator zombie won't die :)

The Iterator thread doesn't die gracefully on KeyboardInterrupt or SystemExit, or when the Main thread completes.

Additionally, the function _Thread__stop() which does indeed kill the Iterator doesn't appear to be broken out to a nice function call, like Iterator.stop() as seems to be suggested within the Mockup implementation.

I propose setting the Iterator thread's isDaemon() flag to True in the Iterator constructor

        self.setDaemon(True)

If the developer chooses to call Iterator run() in the main thread (preventing the python interpreter from returning) they may need code like the following so it can be killed when foregrounded...

            except(KeyboardInterrupt, SystemExit), e:
                sys.exit()

...and a simple extra method to map the stop function to Thread's stopping function could be nice...

def stop(self):
    self._Thread__stop()

Can't read Arduino pins (returning "None") using Raspberry & TX/RX pins

I'm trying the pyFirmata library with a Raspberry Pi, and an Arduino Mega 2560 board attached to it, using the TX and RX (0 and 1) pins of the Mega board and the TX/RX pins of the Raspberry.

Can this be done with pyFirmata? pyFirmata "connects" to the Arduino Mega without problems, and the board.digital[13].write(1) function works fine, I can turn on/off leds, blink... But the problem comes with the reading functions.

Tried on both digital and analog pins and it doesn't work. No errors are given, but the read function just returns "None". This is an example of the complete instructions I executed:

`>>> import pyfirmata

board=pyfirmata.ArduinoMega("/dev/ttyAMA0")
it = pyfirmata.util.Iterator(board)
it.start()
board.analog[0].enable_reporting()
board.analog[0].read()
print board.analog[0].read()
None
board.digital[2].enable_reporting() #I suppose the "enable_reporting" is for analog reads only?
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/pyfirmata/pyfirmata.py", line 487, in enable_reporting
raise IOError("{0} is not an input and can therefore not report".format(self))
IOError: Digital pin 2 is not an input and can therefore not report
print board.digital[2].read()
None
v=board.digital[2].read()
print v
None
a0=board.get_pin("a:0:i")
a0.read()
print a0.read()
None
pin3=board.get_pin("d:3:i")
pin3.read()
print pin3.read()
None
`

Tried using USB instead of the TX/RX pins and the read functions works fine, so I though if pyFirmata might not be able to use that communication.

Generalise Board class to accommodate alternative bytestreams

I've been looking into the use of pyfirmata as part of an Android controller for a bluetooth-serial-connected Shrimp (equivalent to an Arduino Uno - see http://shrimping.it/blog/shrimp/ ).

I'm wondering whether you would consider refactoring pyFirmata to abstract the serial interface so that the code doesn't have a hard dependency on pyserial.

You can see the example python code from the Instructable I'm following here..
http://pastebin.com/raw.php?i=XEmEsATU
...and the instructable is here...
http://www.instructables.com/id/Androino-Talk-with-an-Arduino-from-your-Android-d/

The key thing to notice is the use of droid.bluetoothConnect() and droid.bluetoothWrite() which I don't see how I can plug in to pyFIrmata without pulling it apart, despite having somewhat the same logic as pyserial.

Nano on pypi

Hi
Thanks for a great package :). In the code here on github you have ArdunioNano in boards and init.py. But when you run pip install pyfirmata you doesn't get ArduinoNano. Would it be possible to publish new code to pypi.org?

What is min_pulse and max_pulse in servo_config

Hi,
I would like to send a 50Hz pulse (1-2ms signals in 20ms intervals) and I'm using servo_config function which has min_pulse and max_pulse parameters but I can't figure out what is the meaning of these parameters.
I tried to figure it out from the code, but so far didn't manage.
Thanks

Newbie Question on Digital Read

I have been able to perform an analog read and have no trouble doing that, but my digital pin reads always return None. If you could look at the code below and let me know what newbie mistake I am making, I would appreciate it. I am using version 0.9.5 of pyfirmata. The indentation is being changed when I save here, but it is correct.

Thanks in advance.

import pyfirmata, pyfirmata.util
import time

board = pyfirmata.Arduino('/dev/ttyACM0', baudrate=57600)

iterator = pyfirmata.util.Iterator(board)
iterator.start()

time.sleep(1)
button = board.get_pin('d:12:i')
time.sleep(1)
button.enable_reporting()
time.sleep(1)

for i in range(10):
value = button.read()
print value
time.sleep(1)

Unresolved import: Arduino

i got error Unresolved import: Arduino, did i need Arduino.py file? where can i get it? thanks
i new in this area, really appreciate your help

Using a Arduino and Arduinomega simultaneously

Hi, I am trying to read data from 2 boards from the same python program using pyFirmata.

import time
import pyfirmata               
from pyfirmata import util  

board = pyfirmata.Arduino
boardMega = pyfirmata.ArduinoMega

#Arduino Pin Defintions
Remote_Setpoint_MFC2_R1C_Pin = 7  #PWM Pin for MFC2
Flow_Signal_MFC2_R1C_Pin = 9  #Analog 0-5V Flow Signal MFC2
Reference_Analog_MFC2_R1C_Pin = 8  #5v Reference Analog MFC2

com = 'COM5' 
com1 = 'COM4'

if (com1,com):
    board = pyfirmata.Arduino(com)
    boardMega=pyfirmata.ArduinoMega(com1)     
    Remote_Setpoint_MFC2_R1C_Pin = boardMega.get_pin('d:7:p')
else :
    print ("Invalid COM PORT")

    
boardMega.analog[Flow_Signal_MFC2_R1C_Pin].enable_reporting()
boardMega.analog[Reference_Analog_MFC2_R1C_Pin].enable_reporting()

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

board.analog[1].enable_reporting()

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

while (1):
    Inlet_Pressure = board.analog[1].read() #Pressure as a float number 0-1 corresponding to 0-5V
    if (Inlet_Pressure != None):
        print("Arduino",Inlet_Pressure)
        time.sleep(1)
    else:
        print("Arduino",Inlet_Pressure)

    Raw_MFC2_R1C_Flow = boardMega.analog[Flow_Signal_MFC2_R1C_Pin].read()
    if (Raw_MFC2_R1C_Flow != None):
        print("Arduinomega", Raw_MFC2_R1C_Flow)
        time.sleep(1)
            
    else:
        print("ArduinoMega",Raw_MFC2_R1C_Flow)
#        time.sleep(1)

The two boards are initialized to 2 variables, board and boardMega.
The issue is this.
board = pyfirmata.Arduino(com)
boardMega=pyfirmata.ArduinoMega(com1)

Here boardMega.analog[].read() gives me a value where as board.analog.read() gives "None".

If these 2 lines are swapped, the one initialized later responds with a value, and the first one returns "None".

Is it possible to read both the boards simultaneously? If not what is the workaround?

Digital Reads Return `None`

When I did this on an Arduino Uno:

>>> board.digital[3].mode = INPUT
>>> board.digltal[3].enable_reporting() # Not sure why this has to be an explicit method call
>>> print(board.digital[3].read())           # Return None most of the time

The last statement return None most of the time. It did work sometime, returning True on an open switch and False on closed. However, I had to explicitly start a thread with

>>> thread = util.Iterator(board)
>>> thread.start()

And with that it still returned None very often.

Connect shields

Hi dear,

I am use basic functions to pyfirmata.

How connectd arduino with shield SIM900, ethernet ?

Setting analog pins to output

Is it possible to set A0-A5 to outputs?
I seem to be able to set the pin mode to OUTPUT (no errors when running my Python script), but am unable to measure 5V on the pin itself.

import pyfirmata
PORT = '/dev/ttyACM0'
board = pyfirmata.Arduino(PORT)
board.analog[0].mode = pyfirmata.OUTPUT
board.analog[0].write(1) #have also tried .write(255)

I will see A0 go to ~0.1 V or ~0.3 V. I measure similar voltages across all of the analog pins once I set board.analog[0].mode = pyfirmata.OUTPUT.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.