Servo 2040 board, help to make a servo move

Hi,
I can’t make my servo 2040 board make a servo move, can anyone help?
I’m using circuit python for the code.
My setup is:
*Servo 2040 board connected to computer via USB C/ USB cable (my phone cable).
*I am using an external power supply (Variable power supply set at 5V, 30amps, which can higher or lower the voltage).
*One MG996r servo (to test).
I got AI to write some code (See below:)

import time
import board
import pwmio
from adafruit_motor import servo

# Create a PWMOut object on GP1.
pwm = pwmio.PWMOut(board.GP1, duty_cycle=2 ** 15, frequency=50)

# Create a servo object from the PWMOut object.
my_servo = servo.Servo(pwm)

# Function to sweep the servo from 0 to 180 degrees and back.
def sweep_servo():
    for angle in range(0, 180, 1): # 0-180 degrees, 1 degree step
        my_servo.angle = angle
        time.sleep(0.01)
    for angle in range(180, 0, -1): # 180-0 degrees, 1 degree step
        my_servo.angle = angle
        time.sleep(0.01)

while True:
    sweep_servo()
    time.sleep(1)   # Pause for 1 second between sweeps, 

(I saved it and ran it but it doesn’t work). I’m really frustrated!
Can anyone help?
Thanks in advance.

Hi @Steve2040,

I am unfamiliar with CircuitPython’s servo support so am unsure if there are any obvious issues with that code, other than the pin number you’re using.

Which pin position on Servo 2040 have you plugged your servo into? Even though the pins are numbered 1 to 18 on the board, they are wired GP0 to GP17 on the chip. E.g. to control a servo connected to the pin position marked 1, you need to use GP0.

Is there any reason you are not using our MicroPython build for this board? You will not be able to use the full 18 servos (if that was your intention) with CircuitPython.

Hi Zodius,
Thanks for the reply, I’m happy to use micropython or anything else that works, it’s just the AI I used wrote it in circuit python. Is there a code for micropython or anything else that you use I can load up Thonny and micropython no a problem.

It’s really confusing, so are you saying that because I put the servo on pin one, it’s actually GP0? Thanks for that information, that helps a lot.

If you can show me micropython code that might work, I would be really grateful.

My goal is to build a humanoid robot upper body (2 servo’s for head, 6 servos for each arm meaning 2 shoulder, 2 elbow, 2 wrist.so 14 servo’s and maybe 2 for wheels).

If you can help me get even a couple of servos moving, it would get me off the ground.

Thanks for your support.

Kind regards,
Steve

Maybe this is a lesson in not taking what AI says at face value.

By the way, you never mentioned what error you got when trying to run that code. I just assumed it worked but nothing happened, but checking the CircuitPython build for Servo 2040, it looks like GP1 isn’t a defined pin anyway (instead SERVO_1 to SERVO_18 are), so it shouldn’t have worked, unless you were using a generic Pico build of CircuitPython, rather than the Servo 2040 specific one?

There’s many useful links on the Servo 2040 product page to get you going: Servo 2040 - 18 Channel Servo Controller

Here’s the latest Micropython build that will work with Servo 2040: https://github.com/pimoroni/pimoroni-pico/releases/download/v1.24.0-beta2/pico-v1.24.0-beta2-pimoroni-micropython.uf2

And here’s the latest CircuitPython build, if you wish to continue in that direction: https://adafruit-circuit-python.s3.amazonaws.com/bin/pimoroni_servo2040/en_GB/adafruit-circuitpython-pimoroni_servo2040-en_GB-9.2.4.uf2

For this specific board that is true, but we have another board where Servo 1 starts at GP10, so you should generally avoid using GP numbers unless you have checked the schematic of the product first. Though, for both the Micropython and Circuitpython builds I’ve just linked to, these GP numbers are not defined, so you can happily use SERVO_1 for example, and it will be correct.

Here’s how to drive a single servo: pimoroni-pico/micropython/examples/servo2040/single_servo.py at main · pimoroni/pimoroni-pico · GitHub

And how to drive multiple servos: pimoroni-pico/micropython/examples/servo2040/multiple_servos.py at main · pimoroni/pimoroni-pico · GitHub

Sounds like a cool project! And certainly doable with a Servo 2040 in either CircuitPython or MicroPython.

Hi,
Thanks again, sorry I’m new to all this and where to find stuff. I entered the code from the link you sent(See below) but there was a traceback error
? I’ve pasted the error code below it. It seems not to recognise ‘servo’

import time
import math
from servo import Servo, servo2040

"""
Demonstrates how to create a Servo object and control it.
"""

# Create a servo on pin 0
s = Servo(servo2040.SERVO_1)

# Enable the servo (this puts it at the middle)
s.enable()
time.sleep(2)

# Go to min
s.to_min()
time.sleep(2)

# Go to max
s.to_max()
time.sleep(2)

# Go back to mid
s.to_mid()
time.sleep(2)


SWEEPS = 3              # How many sweeps of the servo to perform
STEPS = 10              # The number of discrete sweep steps
STEPS_INTERVAL = 0.5    # The time in seconds between each step of the sequence
SWEEP_EXTENT = 90.0     # How far from zero to move the servo when sweeping

# Do a sine sweep
for j in range(SWEEPS):
    for i in range(360):
        s.value(math.sin(math.radians(i)) * SWEEP_EXTENT)
        time.sleep(0.02)

# Do a stepped sweep
for j in range(SWEEPS):
    for i in range(0, STEPS):
        s.to_percent(i, 0, STEPS, 0.0 - SWEEP_EXTENT, SWEEP_EXTENT)
        time.sleep(STEPS_INTERVAL)
    for i in range(0, STEPS):
        s.to_percent(i, STEPS, 0, 0.0 - SWEEP_EXTENT, SWEEP_EXTENT)
        time.sleep(STEPS_INTERVAL)

# Disable the servo
s.disable()

#Error Traceback (most recent call last):
File “”, line 3, in
ImportError: no module named ‘servo’

Error says

  File "<stdin>", line 3, in <module>
ImportError: no module named 'servo'

Ah in the REPL i typed each line and when i got to line 3 “from servo import Servo, servo2040” it came up with that traceback error

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ImportError: no module named 'servo'

I also tried leaving off the ‘servo2040’ at the end, same error

Did you flash your board with the MicroPython build I linked to? That includes the servo library that example needs to run.

It could well be that there’s an issue with that build, so you could try and older one like:
https://github.com/pimoroni/pimoroni-pico/releases/download/v1.23.0-1/pico-v1.23.0-1-pimoroni-micropython.uf2, but nobody else has reported a problem (that I’m aware of).

Also, when you post code snippets on the forum, wrap it with ``` so that it gets formatted correctly.
e.g.

example

I’ve gone and edited your posts with them this time.

You can find out what modules you have on your board by typing help("modules") in the REPL.

Edit: Here’s the output of a random board I currently have plugged in:

>>> help("modules")
__main__          breakout_as7343   dht               pimoroni
_asyncio          breakout_bh1745   ds18x20           pimoroni_bus
_boot             breakout_bme280   encoder           pimoroni_i2c
_boot_fat         breakout_bme68x   errno             plasma
_onewire          breakout_bmp280   framebuf          platform
_rp2              breakout_dotmatrix                  gc                pngdec
_thread           breakout_encoder  hashlib           qrcode
_webrepl          breakout_encoder_wheel              heapq             random
adcfft            breakout_icp10125 hub75             re
aioble/__init__   breakout_ioexpander                 io                requests/__init__
aioble/central    breakout_ltr559   jpegdec           rp2
aioble/client     breakout_matrix11x7                 json              select
aioble/core       breakout_mics6814 lwip              servo
aioble/device     breakout_msa301   machine           socket
aioble/l2cap      breakout_paa5100  math              ssl
aioble/peripheral breakout_pmw3901  micropython       struct
aioble/security   breakout_potentiometer              mip/__init__      sys
aioble/server     breakout_rgbmatrix5x5               motor             time
array             breakout_rtc      neopixel          tls
asyncio/__init__  breakout_scd41    network           uasyncio
asyncio/core      breakout_sgp30    ntptime           uctypes
asyncio/event     breakout_trackball                  onewire           urequests
asyncio/funcs     breakout_vl53l5cx os                version
asyncio/lock      builtins          picoexplorer      vfs
asyncio/stream    cmath             picographics      webrepl
binascii          collections       picokeypad        webrepl_setup
bluetooth         cppmem            picoscroll        websocket
boot              cryptolib         picounicorn
breakout_as7262   deflate           picovector
Plus any modules on the filesystem

You can see that servo is in there.

Just on setting it up, in the configure interpreter, I could only get the servo 2040 working when it was set to ‘Micropyhon - Raspberry Pi Pico - Board CDC - COM6’ is that ok?

Yes that is fine. Thonny won’t have knowledge of which exact RP2040 board Servo 2040 is, so using the base Pi Pico option will be fine.

This looks promising!! Ok, I flashed the 2040 with the uf2 that you sent in the link, I ran the code for one servo and it didn’t give an error code!
I saved it as code.py ran it but nothing happened, Should the RGB’s come on at all?
It definitely is connected as it shows up on computer. Variable power supply is on 5v 30amps connected to the external power, nothing happens with the servo, Not sure what im doing wrong.

It feels so close to working!!! :)

False alarm, the code wasn’t saved when i put it back in and saved it it came up with the traceback error.

One thing I noticed is that when I connect it to the computer I have to keep configure the interpreter and resetting it up and have to update it
Is it Micropython (Raspberry Pi Pico) or Micropython (RP2040) that I should configure it to?
Also once it is configured on Thonny ,it seems to disconnect and disappear from the laptop drive info, but I can see it on Thonny, including the code.py program. Is that normal?

You don’t need to save code onto the board to run it. You can run files that are local on your computer, via Thonny, using the run button up in the top left.

You can save code to the board, but it is not required for experimenting.

Now, if you want code to run at board power-up, with MicroPython you should call it main.py rather than code.py.

The RGB LEDs won’t do anything unless you program them to do so. Here’s an example for LED control: pimoroni-pico/micropython/examples/servo2040/led_rainbow.py at main · pimoroni/pimoroni-pico · GitHub

You shouldn’t need to keep doing that. It should just remember.

Either will work, though the latter is technically more correct.

Yes, that is normal. With MicroPython the board does not appear as a USB drive. Instead you access your files via Thonny.

This is in contract to CircuitPython which does present the board as a USB drive with your files accessible from a file browser.

Both approaches have their trade-offs.

Hi again, I typed help(“modules”) and servo wasn’t on there is it hidden as at the bottom it said “Plus any modules on the file system”

In that case it’s not loaded. Could you confirm which UF2 you have on the board? When you were doing the configure interpreter thing with Thonny, it’s possible it put on a default UF2 for the Pi Pico, rather than the one I linked to. It should say what version is running when the REPL first appears.

I removed the UF2 that was in there and dragged and dropped the pico v1.24.0 beta2 pimroni micropython into the 2040.

I typed help(“modules”) and saw all the files including servo in there like you showed.

I tried to run the code again and nothing happened it just highlighted the line 3 for a split second, but it didn’t give the error code this time.

I then typed the first 3 lines in the repl and no error this time, so I pasted the rest of the code in the repl, hit enter, then nothing.

I ran it again and in the REPL it said MPY: soft reboot and took ages for the >>> to come back.in the REPL.
Sorry its taking so long to reply, but there is a message limit and timer saying because i’m on my first day (?) I have to wait , so it may be a while before I reply back :(
Good news is that it doesn’t do the traceback error and I saw servo in the Help modules. So the UF2 you gave me must be copied now.
.