Advertisement
bitwise_gamgee

Untitled

Jul 5th, 2023
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. Idea:
  2.  
  3. Use direct port/pin control:
  4.  
  5. #define MOTOR1_PIN1 9
  6. #define MOTOR1_PIN2 10
  7. #define MOTOR2_PIN1 11
  8. #define MOTOR2_PIN2 12
  9.  
  10. void setup() {
  11. // Other stuff
  12.   pinMode(MOTOR1_PIN1, OUTPUT);
  13.   pinMode(MOTOR1_PIN2, OUTPUT);
  14.   pinMode(MOTOR2_PIN1, OUTPUT);
  15.   pinMode(MOTOR2_PIN2, OUTPUT);
  16. // More stuff
  17. }
  18.  
  19. void loop() {
  20.  
  21.   int motor1Speed = // data
  22.   int motor2Speed = // data
  23.  
  24.   controlMotor1(motor1Speed);
  25.   controlMotor2(motor2Speed);
  26.  
  27.   delay(40);
  28. }
  29.  
  30. // Create two new functions to handle motor control
  31.  
  32. void controlMotor1(int speed) {
  33.   // Set the direction of motor 1 based on the speed
  34.   if (speed >= 0) {
  35.     digitalWrite(MOTOR1_PIN1, HIGH);
  36.     digitalWrite(MOTOR1_PIN2, LOW);
  37.   } else {
  38.     digitalWrite(MOTOR1_PIN1, LOW);
  39.     digitalWrite(MOTOR1_PIN2, HIGH);
  40.     speed = -speed; // Make the speed positive for analogWrite
  41.   }
  42.  
  43.   analogWrite(MOTOR1_PIN2, speed);
  44. }
  45.  
  46. void controlMotor2(int speed) {
  47.  
  48.   if (speed >= 0) {
  49.     digitalWrite(MOTOR2_PIN1, HIGH);
  50.     digitalWrite(MOTOR2_PIN2, LOW);
  51.   } else {
  52.     digitalWrite(MOTOR2_PIN1, LOW);
  53.     digitalWrite(MOTOR2_PIN2, HIGH);
  54.     speed = -speed; // Make the speed positive for analogWrite
  55.   }
  56.  
  57.   analogWrite(MOTOR2_PIN2, speed);
  58. }
  59.  
  60. // Rest of program
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement