Advertisement
Robert_l

rc pwm

Dec 9th, 2022
869
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #define pulseInPin A0    // select the input pin for the potentiometer
  2. #define PWMOutPin 3  //PWM pin
  3. #define dirR 4
  4. #define dirL 5
  5.  
  6. int timeIn = 0;  // variable to store the value coming from the sensor
  7. int timeMid = 1500;
  8. int offset = 50;
  9. int PWMval;
  10.  
  11. void setup() {
  12.   // declare the ledPin as an OUTPUT:
  13.  
  14.   pinMode(pulseInPin, INPUT);
  15.   pinMode(PWMOutPin, OUTPUT);
  16.   pinMode(dirL, OUTPUT);
  17.   pinMode(dirR, OUTPUT);
  18.   Serial.begin(9600);
  19. }
  20.  
  21. void loop() {
  22.   // read the value from the sensor:
  23.   timeIn = pulseIn(pulseInPin, HIGH);
  24.   if(timeIn > 2500) {timeIn = timeMid;}
  25.   if(timeIn < 500) {timeIn = timeMid;}
  26.  
  27.   Serial.println(timeIn);
  28.   if(timeIn > timeMid + offset)
  29.   {
  30.     fwd();
  31.   }else if(timeIn < timeMid - offset)
  32.   {
  33.     rwd();
  34.   }
  35.   else {
  36.     neutral();
  37.   }
  38. }
  39.  
  40. void fwd()
  41. {
  42.   int timeCalc;
  43.   digitalWrite(dirR, HIGH);
  44.   digitalWrite(dirL, LOW);
  45.   timeCalc = abs(timeIn - timeMid);
  46.   PWMval = map(timeCalc, 0, 500, 0, 255);
  47.   analogWrite(PWMOutPin, PWMval);
  48. }
  49. void rwd()
  50. {
  51.   int timeCalc;
  52.   digitalWrite(dirR, LOW);
  53.   digitalWrite(dirL, HIGH);
  54.   timeCalc = abs(timeIn - timeMid);
  55.   PWMval = map(timeCalc, 0, 500, 0, 255);
  56.   analogWrite(PWMOutPin, PWMval);
  57. }
  58. void neutral()
  59. {
  60.   digitalWrite(dirR, LOW);
  61.   digitalWrite(dirL, LOW);
  62.   analogWrite(PWMOutPin, 0);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement