I am working on a project in which I need to control a brushless motor with a microcontroller. I have chosen the Pico as I already have some on hand and there is a high chance of it being completely destroyed, so the low price is nice.
To control the motor, I have connected one of the Pico's GPIO pins to the input of a dshot brushless ESC. I am using micropython as I do not have any experience with C or C++. I am able to get the motor to spin, but I am having some trouble changing the speed. Dshot uses a 16 bit digital frame for communication. More information on dshot can be found here: https://brushlesswhoop.com/dshot-and-bidirectional-dshot/.
When I set the frame variable to 1000001011000110 (and frameinverse to the inverse) inside of the square() function, the motor spins as expected. However, when I try to pull that variable from outside of the function as shown below, I get the error NameError: name 'frame' isn't defined.
Is there something I'm doing wrong, or should I try to find another way of achieving this goal? (I know the code has too much repetition, I want to get this working before I try to optimize anything)
from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
frame = "1000001011000110"
frameinverse = ''.join('0' if c=='1' else ('1' if c=='0' else c) for c in frame)
@asm_pio(set_init=PIO.OUT_LOW)
def square():
global frame
global frameinverse
wrap_target()
set(pins, 1) [int(str(frame)[0], 2)]
set(pins, 0) [int(str(frameinverse)[0], 2)]
set(pins, 1) [int(str(frame)[1], 2)]
set(pins, 0) [int(str(frameinverse)[1], 2)]
set(pins, 1) [int(str(frame)[2], 2)]
set(pins, 0) [int(str(frameinverse)[2], 2)]
set(pins, 1) [int(str(frame)[3], 2)]
set(pins, 0) [int(str(frameinverse)[3], 2)]
set(pins, 1) [int(str(frame)[4], 2)]
set(pins, 0) [int(str(frameinverse)[4], 2)]
set(pins, 1) [int(str(frame)[5], 2)]
set(pins, 0) [int(str(frameinverse)[5], 2)]
set(pins, 1) [int(str(frame)[6], 2)]
set(pins, 0) [int(str(frameinverse)[6], 2)]
set(pins, 1) [int(str(frame)[7], 2)]
set(pins, 0) [int(str(frameinverse)[7], 2)]
set(pins, 1) [int(str(frame)[8], 2)]
set(pins, 0) [int(str(frameinverse)[8], 2)]
set(pins, 1) [int(str(frame)[9], 2)]
set(pins, 0) [int(str(frameinverse)[9], 2)]
set(pins, 1) [int(str(frame)[10], 2)]
set(pins, 0) [int(str(frameinverse)[10], 2)]
set(pins, 1) [int(str(frame)[11], 2)]
set(pins, 0) [int(str(frameinverse)[11], 2)]
set(pins, 1) [int(str(frame)[12], 2)]
set(pins, 0) [int(str(frameinverse)[12], 2)]
set(pins, 1) [int(str(frame)[13], 2)]
set(pins, 0) [int(str(frameinverse)[13], 2)]
set(pins, 1) [int(str(frame)[14], 2)]
set(pins, 0) [int(str(frameinverse)[14], 2)]
set(pins, 1) [int(str(frame)[15], 2)]
set(pins, 0) [int(str(frameinverse)[15], 2)]
wrap()
sm = rp2.StateMachine(0, square, freq=200000, set_base=Pin(0))
sm.active(1)