Connecting Arduino Mega 2560 to Python with PyFirmata

572 Views Asked by At

I am currently controlling two servos using the Arduino IDE, but now need to integrate my Arduino code into a Python script. However, having followed the exact procedure of translating Arduino code to Python and downloading/using the correct pyfirmata package, the board simply does not react.

I read about how to use PyFirmata and went through the process of uploading StandardFirmata to my Arduino Mega 2560 board after changing the samplingInterval value to 99, instead of the default 19. I tested the board, the individual servos, power, etc. and have even used the ArduinoMega module in pyfirmata, but there is absolutely no reaction when using the Python code. I have looked through multiple online forums and it seems that this is a recurring issue, but no one has posted a solution (as per my knowledge) to the problem and it would be of great help if someone could help me fix this. I have the following simple code, which I got by following a simple tutorial on youtube:

from pyfirmata import ArduinoMega, SERVO, util, Arduino
from time import sleep

port = "/dev/cu.usbmodem143301"
joint_pin = 9
base_pin = 10
board = ArduinoMega(port)
board.digital[base_pin].mode=SERVO

def rotateServo(pin, angle):
    board.digital[pin].write(180)
    sleep(0.015)

def main():

    #for i in range(0, 90):
        #rotateServo(base_pin, i, board)
    # rotate joint servo
    for j in range(0, 90):
        rotateServo(base_pin, j)

if __name__ == '__main__':
    main()

I would appreciate any help that can be given with this. Thank you in advance!

1

There are 1 best solutions below

0
On

Try this and your code will run absolutely fine.

#!/usr/bin/env python3
import pyfirmata
import time
if __name__ == '__main__':
    board = pyfirmata.ArduinoMega('/dev/ttyACM0')
    print("Communication Successfully started")
    M1=board.digital[2]
    M1.mode=pyfirmata.PWM
    M2=board.digital[3]
    M2.mode=pyfirmata.PWM
    while True:
        M1.write(.1)
        M2.write(0)
        #time.sleep(.001)