Advertisement
Guest User

Motor test

a guest
May 6th, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. //Control pins
  2. #define PWM_PIN 9
  3. #define DIR_PIN 5
  4.  
  5. //Showing dir with Arduino led
  6. #define LED_PIN 13
  7.  
  8. //Dead time insertion in microseconds
  9. #define DTI_US 1000
  10.  
  11. //Change direction every N milliseconds
  12. #define CHANGEDIR_MS 100
  13.  
  14. long lastDTIStart = 0;
  15. long lastDirChange = 0;
  16. boolean changeDir = false;
  17. boolean motorDir = false;
  18.  
  19. void setup() {
  20.   //---------------------------------------------- Set PWM frequency for D9 & D10 ------------------------------
  21.   TCCR1B = TCCR1B & B11111000 | B00000010;    // set timer 1 divisor to     8 for PWM frequency of  3921.16 Hz
  22.  
  23.   timeDirChange();
  24.   pinMode(PWM_PIN, OUTPUT);
  25.   pinMode(DIR_PIN, OUTPUT);
  26.   pinMode(LED_PIN, OUTPUT);
  27.  
  28.   digitalWrite(LED_PIN, motorDir);
  29. }
  30.  
  31. void loop() {
  32.   if(changeDir && !checkDirChange())
  33.   {
  34.     //Sleep in small steps for smaller error
  35.     delayMicroseconds(DTI_US / 100);
  36.     return;
  37.   }
  38.  
  39.   if(millis() - lastDirChange > CHANGEDIR_MS)
  40.   {
  41.     timeDirChange();
  42.     lastDirChange = millis();
  43.   }
  44.  
  45. }
  46.  
  47. void timeDirChange()
  48. {
  49.   //PWM to 0% duty cycle
  50.   analogWrite(PWM_PIN, 0);
  51.   lastDTIStart = micros();
  52.   changeDir = true;
  53. }
  54.  
  55. boolean checkDirChange()
  56. {
  57.   if(changeDir)
  58.   {
  59.     if(micros() - lastDTIStart > DTI_US)
  60.     {
  61.       changeDir = false;
  62.       motorDir = !motorDir;
  63.       digitalWrite(DIR_PIN, motorDir);
  64.       digitalWrite(LED_PIN, motorDir);
  65.       delayMicroseconds(100);      
  66.       //Enable PWM
  67.       analogWrite(PWM_PIN, 128);
  68.      
  69.       return true;
  70.     }
  71.  
  72.     return false;
  73.   }
  74.   return true;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement