In this video lesson we show how you can control a PIO State Machine on the Raspberry Pi Pico W inside of a micropython class. We demonstrate with the practical example of controlling servos with a servo Class which we create. The objective is to ‘hide’ all the complex code in the class, allowing less adept users to interact with the servo with simple python commands. For your convenience the code developed in this video is included below. Enjoy!
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# ==================================================================== # DISCLAIMER: # This code is provided as-is for educational and experimental # purposes only. The author makes no representations or warranties of # any kind concerning the safety, suitability, or accuracy of this # code. Use at your own risk. The author assumes no liability for any # damages, system failures, security breaches, or network issues # resulting from the use or implementation of this script. # ==================================================================== import time from machine import Pin import rp2 class servoState: counter=0 @rp2.asm_pio(set_init=rp2.PIO.OUT_LOW,out_shiftdir=rp2.PIO.SHIFT_RIGHT) def servoSet(): wrap_target() mov(x,osr) mov(y,isr) set(pins,0) label('timeLoop') jmp(x_not_y,'nxt') set(pins,1) label('nxt') jmp(y_dec,'timeLoop') wrap() def __init__(self,servoPin): self.sm = rp2.StateMachine(servoState.counter,servoState.servoSet, freq=2000000, set_base=Pin(servoPin)) self.sm.active(1) self.sm.put(20000) self.sm.exec("pull()") self.sm.exec("mov(isr,osr)") print("State Machine: "+str(servoState.counter)+" created") servoState.counter=servoState.counter+1 def servoAngle(self,angle): pw=int(500+angle*2000/180) self.sm.put(pw) self.sm.exec("pull()") myServo1=servoState(20) myServo2=servoState(21) myServo3=servoState(22) myServo4=servoState(23) myServo5=servoState(24) myServo6=servoState(25) myServo7=servoState(26) myServo8=servoState(27) ts=5 while True: for angle in range(0,180,1): myServo1.servoAngle(angle) myServo7.servoAngle(180-angle) time.sleep(ts) for angle in range(180,0,-1): myServo1.servoAngle(angle) myServo7.servoAngle(180-angle) time.sleep(ts) |
