Advertisement
Guest User

Robot Controller

a guest
Apr 15th, 2021
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.25 KB | None | 0 0
  1. from controller import Robot, Keyboard, Supervisor,Emitter,Receiver,PositionSensor
  2. from math import atan, pi, acos, sqrt, sin, cos
  3. import numpy as np
  4.  
  5. robot = Robot()
  6. TIMESTEP = int(robot.getBasicTimeStep())
  7. timestep = TIMESTEP
  8.  
  9. X,Y,Z = 0,0,0
  10. angle = 0
  11. maxSpeed = 15 #30
  12. theta = [0,0,0]
  13. otheta = [0,0,0]
  14. para = [0,0,0]
  15.  
  16. #90,3,180 works
  17. para[0] = 50
  18. para[1] = 1 #1.5 #35*maxSpeed/3600
  19. para[2] = 10#4
  20.  
  21. def setSpeed(l,r):
  22.     motor[0].setVelocity(l)
  23.     motor[1].setVelocity(r)
  24.  
  25.  
  26. def getSpeed(ang, ang_dot):
  27.  
  28.     target = 0
  29.     theta[0] = ang
  30.     theta[1] += ang
  31.     theta[2] = ang_dot
  32.  
  33.     if abs(theta[0])<0.05:
  34.         theta[1] = 0
  35.        
  36.     speed = theta[0]*para[0]+theta[1]*para[1]+theta[2]*para[2]
  37.    
  38.     otheta[0] = theta[0]
  39.     otheta[1] = theta[1]
  40.     otheta[2] = theta[2]
  41.    
  42.     if abs(speed)>maxSpeed:
  43.         speed = maxSpeed*(speed/abs(speed))
  44.        
  45.     return speed
  46.  
  47. state = [0, 0, 0, 0]
  48. K = [10, -1.7, 150, 600]
  49. #K = [6, -0.8, 200, 350]  
  50. #K = [7.5, -0.85, 75, 200]  
  51. #K = [10, 0, 100, 300]  # is stable to some extent. Tested for 15 minutes
  52.  
  53. def lqrSpeed(phi, dphi,theta, theta_dot):
  54.     state[0] = phi
  55.     state[1] = dphi
  56.     state[2] = theta
  57.     state[3] = theta_dot
  58.    
  59.     d = [ K[i]*state[i] for i in range(len(K))]
  60.     s = sum(d)
  61.    
  62.     if abs(s)>maxSpeed:
  63.         s = maxSpeed*(s/abs(s))
  64.     return s
  65.  
  66.  
  67. def reset_param():
  68.     global gAng,aAng,angle,lDisRef,rDisRef,lEnc,rEnc,oldxD,speed,oT,xD
  69.     gAng = 0
  70.     aAng = 0
  71.     angle = 0
  72.    
  73.     for i in range(len(motorNames)):
  74.         motor.append(robot.getDevice(motorNames[i]))
  75.         motor[i].setPosition(float('inf'))
  76.         motor[i].setVelocity(0)
  77.        
  78.        
  79.     lDisRef = lEnc.getValue()
  80.     rDisRef = rEnc.getValue()    
  81.     oldxD = (lDisRef+rDisRef)*90/pi
  82.     speed = 0
  83.     oT = robot.getTime()
  84.     xD = 0
  85.    
  86. #Setup motors
  87. motorNames = ['leftMotor', 'rightMotor']
  88. motor = []
  89.    
  90. for i in range(len(motorNames)):
  91.     motor.append(robot.getDevice(motorNames[i]))
  92.     motor[i].setPosition(float('inf'))
  93.     motor[i].setVelocity(0)
  94.  
  95. #Setup Accelerometer and Gyroscope
  96. accMeter = robot.getDevice('accel')
  97. accMeter.enable(TIMESTEP)
  98. gyro = robot.getDevice('gyro')
  99. gyro.enable(TIMESTEP)
  100.  
  101. #Setup Encoders
  102. lEnc = robot.getDevice("leftEncoder")
  103. lEnc.enable(TIMESTEP)
  104. rEnc = robot.getDevice("rightEncoder")
  105. rEnc.enable(TIMESTEP)
  106. robot.step(timestep)
  107.  
  108. #Initiate keyboard
  109. keyb = Keyboard()
  110. keyb.enable(TIMESTEP)
  111.  
  112. #Initialize Emitter and Receiver
  113. emitter = robot.getDevice("emitter")
  114. emitter.setChannel(2)
  115.  
  116. reciever = robot.getDevice("receiver")
  117. reciever.enable(timestep)
  118. reciever.setChannel(1)
  119.  
  120. #Establish Proper Sync Between Emitter And Reciever
  121.  
  122.  
  123. oT = robot.getTime()
  124. gAng = 0
  125. oldxD = 0
  126. oldT = oT
  127.  
  128. # uses PID or else LQR
  129. pid = False
  130.  
  131. fitness = 0
  132.  
  133. # Get reference value of encoder
  134. lDisRef = lEnc.getValue()
  135. rDisRef = rEnc.getValue()
  136.  
  137. stop = False
  138. oldG = np.array([0,0,0])
  139. xD = 0
  140. previous_msg = ""
  141. while robot.step(timestep) != -1:
  142.     # Data Transmission
  143.         # 1.Get LQR Parameters and Run
  144.         # 2.Send Back Fitness when requested
  145.  
  146.     if reciever.getQueueLength()>0:
  147.         message = reciever.getData().decode('utf-8')
  148.         if message=="return_fitness":
  149.             emitter.send(str(fitness).encode('utf-8'))
  150.             speed = 0
  151.             for i in range(len(motorNames)):
  152.                 motor[i].setPosition(float('inf'))
  153.                 motor[i].setVelocity(0)
  154.  
  155.             reset_param()
  156.             stop = True
  157.             print("Robot: Fitness for ",K," is ",fitness)
  158.            
  159.         else:
  160.            
  161.             message_ = [float(param) for param in message.split(',') ]
  162.             K = message_
  163.             fitness = 0
  164.             #print(K)
  165.             stop = False
  166.         reciever.nextPacket()
  167.        
  168.  
  169.     # Run Controll Algorithm  
  170.  
  171.     [x,y,z] = accMeter.getValues()
  172.     [gx,gy,gz] = np.array(gyro.getValues())
  173.     gAng += (gx*(robot.getTime()-oT))*180/pi
  174.     oT = robot.getTime()
  175.     if gy!=0:
  176.         aAng = -atan(gz/gy)*180/pi
  177.     else:
  178.         aAng = 0
  179.     if aAng>0:
  180.         aAng = 90-aAng
  181.     else:
  182.         aAng = -1*(90+aAng)
  183.     angle = 0.99*gAng + 0.01*aAng
  184.  
  185.     # Controller
  186.    
  187.     if pid:
  188.         #print('%.2f'%gAng," vs ",'%.2f'%aAng, " VS ", '%.2f'%angle)
  189.         speed = getSpeed(angle,gx)
  190.    
  191.     elif not(stop) :
  192.        
  193.         lDis = lEnc.getValue() - lDisRef
  194.         rDis = rEnc.getValue() - rDisRef
  195.         xD = (lDis+rDis)*90/pi
  196.        
  197.         if (robot.getTime()-oldT)>0:
  198.             speed = lqrSpeed(xD,(oldxD-xD)/(robot.getTime()-oldT),angle, gx)
  199.         else:
  200.             speed = lqrSpeed(xD,0,angle, gx)
  201.         oldxD = xD
  202.         oldT = robot.getTime()
  203.         """
  204.        print('Theta %.3f'%angle, "\tSpeed : ",'%.3f'%speed,
  205.        "\tIntegral : ",'%.3f'%theta[1],  "\tDerivative : ",'%.3f'%theta[2],
  206.        "\tPhi : ",'%.3f'%xD)
  207.        """
  208.        
  209.     elif stop:
  210.         speed = 0
  211.        
  212.     if  abs(angle)<5:
  213.         fitness += angle/5  
  214.    
  215.    
  216.     # Penalize when the SBR falls and favour oscillations
  217.     if abs(angle)>50:
  218.         fitness += (150)
  219.     #print(speed)
  220.     setSpeed(speed,speed)
  221.  
  222.    
  223.  
  224.      
  225.  
  226. print("Got Out")
  227.        
  228.    
  229.    
  230.    
  231.    
  232.    
  233.    
  234.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement