Advertisement
MrLunk

Pygame USB-serial control - Arduino receiver end

Jan 27th, 2018
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None | 0 0
  1. // MrLunk's Autonomous Vehikel 2017 - Serial motion control
  2.  
  3. #include <Servo.h>
  4. #include <Wire.h>
  5.  
  6. Servo myservo;
  7.  
  8. // const int led = 13;
  9. int usbRead =0;
  10.  
  11. Servo SteeringServo;
  12. int MaxSteerAngle = 30;
  13. int Speed = 100;
  14. int MaxSpeed = 60;
  15.  
  16. int RPWM_Output = 5; // Arduino PWM output pin 5; connect to IBT-2 pin 1 (RPWM)
  17. int LPWM_Output = 6; // Arduino PWM output pin 6; connect to IBT-2 pin 2 (LPWM)
  18.  
  19. // --------------------------------------------------------------
  20.  
  21. void setup() {
  22.  
  23.   Serial.begin(9600);
  24.   // pinMode(led, OUTPUT);
  25.   // digitalWrite(led, LOW);
  26.  
  27.   pinMode(RPWM_Output, OUTPUT);
  28.   pinMode(LPWM_Output, OUTPUT);
  29.  
  30.   SteeringServo.attach(7);
  31. }
  32.  
  33. // --------------------------------------------------------------
  34.  
  35. void loop() {
  36.   if(Serial.available()) {
  37.  
  38.     usbRead = Serial.read() - '0';
  39.     Serial.println(usbRead);
  40.  
  41.     if(usbRead == 8) {
  42.       Forwards();
  43.       usbRead = 0;
  44.     }
  45.  
  46.     if(usbRead == 7) {
  47.       StopEngine();
  48.       usbRead = 0;
  49.     }
  50.  
  51.     if(usbRead == 5) {
  52.       SteerStraight();
  53.       usbRead = 0;
  54.     }
  55.  
  56.     if(usbRead == 2) {
  57.       Backwards();
  58.       usbRead = 0;
  59.     }
  60.  
  61.     if(usbRead == 4) {
  62.       SteerRight();
  63.       usbRead = 0;
  64.     }
  65.  
  66.     if(usbRead == 6) {
  67.       SteerLeft();
  68.       usbRead = 0;
  69.     }
  70.  
  71.  
  72.   }
  73. }
  74.  
  75. // --------------Routine definitions------------------------------
  76.  
  77. void Forwards(){
  78.   analogWrite(LPWM_Output, 0);
  79.   analogWrite(RPWM_Output, MaxSpeed);
  80.   // delay(200);
  81.  
  82. }
  83.  
  84. void SteerStraight(){
  85.   SteeringServo.write(90);              
  86. }
  87.  
  88. void StopEngine(){
  89.   analogWrite(LPWM_Output, 0);
  90.   analogWrite(RPWM_Output, 0);
  91. }
  92.  
  93. void Backwards(){
  94.   analogWrite(LPWM_Output, MaxSpeed);          // Backwards
  95.   analogWrite(RPWM_Output, 0);
  96.   // delay(200);
  97. }
  98.  
  99. void SteerRight(){
  100.   SteeringServo.write(90 - MaxSteerAngle);              
  101.  
  102. }
  103.  
  104. void SteerLeft(){
  105.   SteeringServo.write(90 + MaxSteerAngle);
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement