Python - Firmata and Arduino - problem with running script

90 Views Asked by At

I use nodemcu (esp8266) with servo motor (SG90), I have tried to write simple code in python that I confirm I can run servo motor. When I run script, all I get is waiting and it never ends. I ran Standard format script in arduino and uploaded code to MCU. Does anyone has some suggestion what could be the problem here. Thanks.

import pyfirmata
import time

# Specify the port where your Arduino is connected.
# For Windows, it may be something like "COM3." For macOS or Linux, it may be "/dev/ttyACM0" or "/dev/ttyUSB0."
port = 'COM3'  # Update with your specific port

# Create a new board object and connect to the Arduino.
board = pyfirmata.Arduino(port)

# Define the pin to which the servo is connected (e.g., digital pin 9).
servo_pin = board.get_pin('d:9:s')  # Pin 9 as a servo

try:
    while True:
        # Sweep the servo from 0 to 180 degrees
        for angle in range(0, 181, 1):
            servo_pin.write(angle)
            time.sleep(0.01)  # Adjust the delay for smoother motion

        # Sweep the servo from 180 to 0 degrees
        for angle in range(180, -1, -1):
            servo_pin.write(angle)
            time.sleep(0.01)  # Adjust the delay for smoother motion

except KeyboardInterrupt:
    board.exit()  # Cleanly exit when Ctrl+C is pressed

Kind regards

1

There are 1 best solutions below

0
Volodimir Kopey On

You run not "Standard format script" but StandardFirmata sketch. Check in the sketch the line:

Firmata.begin(57600);

Then in the Python module use:

board = pyfirmata.Arduino(port, baudrate=57600)
print(board)