Advertisement
Guest User

lab5

a guest
Sep 19th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <RedBot.h>
  2.  
  3. #define SPEED 90
  4.  
  5. // initialize RedBot motors and motor encoders
  6. RedBotMotors motors;
  7. RedBotEncoder encoder = RedBotEncoder(A2, 10);
  8.  
  9. // using counts per rev of 192/rev: 967 revs for 1m
  10. int targetcount = 967;
  11.  
  12. // initialize lCount, rCount, lDiff, rDiff, prevlCount, and prevrCount
  13. int lCount, rCount, lDiff, rDiff;
  14. int prevlCount = 0;
  15. int prevrCount = 0;
  16.  
  17. // set the speeds of left and right motors and speed offset
  18. int lSpeed = SPEED;
  19. int rSpeed = SPEED;
  20. int offset = 3;
  21.  
  22.  
  23. void setup() {
  24.   // begin serial monitoring
  25.   Serial.begin(9600);
  26. }
  27.  
  28. void loop() {
  29.   // starts the loop by getting the number of ticks the encoders have on each motor
  30.   lCount = encoder.getTicks(LEFT);
  31.   rCount = encoder.getTicks(RIGHT);
  32.  
  33.   // stops to turn when the right motor hits the targeted amount of ticks
  34.   if(rCount < targetcount) {
  35.     // get the difference in ticks between 50ms intervals and set previous tick counts
  36.     lDiff = (lCount - prevlCount);
  37.     rDiff = (rCount - prevrCount);
  38.     prevlCount = lCount;
  39.     prevrCount = rCount;
  40.     // if left wheel is ahead, slow down left, speed up right
  41.     if(lDiff > rDiff) {
  42.       lSpeed = lSpeed - offset;
  43.       rSpeed = rSpeed + offset;
  44.     // if right wheel is ahead, slow down right, speed up left
  45.     }else if(lDiff < rDiff) {
  46.       lSpeed = lSpeed + offset;
  47.       rSpeed = rSpeed - offset;
  48.     }else{
  49.       lSpeed = SPEED;
  50.       rSpeed = SPEED;
  51.     }
  52.     // run the motors at the set speeds
  53.     motors.rightMotor(rSpeed);
  54.     motors.leftMotor(-lSpeed);
  55.     delay(50);
  56.   // turn using encoder ticks
  57.   }else{
  58.     // stop and clear encoders and delay for 500ms before pivoting
  59.     motors.brake();
  60.     encoder.clearEnc(BOTH);
  61.     lCount = encoder.getTicks(LEFT);
  62.     rCount = encoder.getTicks(RIGHT);
  63.     delay(500);
  64.     // pivot at 100 speed until the left motor hits 85 ticks
  65.     while(lCount < 88) {
  66.       rightPivot(100);
  67.       lCount = encoder.getTicks(LEFT);
  68.       delay(50);
  69.     }
  70.     // stop and reset speed variables and encoders
  71.     motors.stop();
  72.     lSpeed = SPEED;
  73.     rSpeed = SPEED;
  74.     encoder.clearEnc(BOTH);
  75.     delay(1000);
  76.   }
  77. }
  78.  
  79. void rightPivot(int n) {
  80.   motors.rightMotor(-n);
  81.   motors.leftMotor(-n);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement