Search code examples
pythonarduinopyfirmata

cannot communicate Arduino with python


I am getting an error while trying to communicate Arduino with python, I am using Arduino module and I'm getting cannot open port error and I can communicate my Arduino from Arduino IDE.

from Arduino import Arduino
import time

board = Arduino(port="/dev/cu.usbmodem14201") # plugged in via USB, serial com at rate 115200
board.pinMode(13, "OUTPUT")

while True:
    board.digitalWrite(13, "LOW")
    time.sleep(1)
    board.digitalWrite(13, "HIGH")
    time.sleep(1)

This is my error

serial.serialutil.SerialException: [Errno 2] could not open port /dev/cu.usbmodem14201: [Errno 2] No such file or directory: '/dev/cu.usbmodem14201'

when I tried with pyfirmata I am getting an error

This is my code:

import pyfirmata
import time

board = pyfirmata.Arduino('/dev/cu.usbmodem14201')
led = board.get_pin('d:13:o')

while True:
    led.write(1)
    time.time(1)
    led.write(0)
    time.time(1)

my error for pyfirmata:

AttributeError: partially initialized module 'pyfirmata' has no attribute 'Arduino' (most likely due to a circular import)

Solution

  • To preface, I have done some Serial communication with Arduino, but have not worked with the Arduino library too extensively.

    I suggest if you haven't done so already, considering the PySerial library. This may help with your initial issue with serial connection between your Mac and board. This does not entirely fix your need of directly writing to the LEDs, but can serve as a substitute in the meantime. You can use the incoming serial communication from your Mac to direct certain operations on your Arduino.

    A great tutorial I have used can be found here: https://create.arduino.cc/projecthub/ansh2919/serial-communication-between-python-and-arduino-e7cce0

    Another issue may be that your Serial Monitor may be active which is blocking serial communication between devices over Python.