miklik

Arduino set servo from console

Sep 29th, 2025 (edited)
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | Source Code | 0 0
  1. #include <Servo.h>
  2.  
  3. //Servo connection PINs
  4. int spin[4] = {2,3,4,5};
  5. int sangle[4] = {0,90,180,90};
  6. Servo myservo[4];  // create Servo object to control a servo
  7.  
  8. char c;     //character
  9. bool d = false;     //are new data
  10.  
  11. void readChar() {
  12.     if (Serial.available() > 0) {
  13.         c = Serial.read();
  14.         d = true;
  15.         Serial.print("pushed: ");
  16.         Serial.println(c);
  17.     }
  18. }
  19.  
  20. void setservos(int a){
  21.   for (int s = 0;s < 4;s++) {
  22.     Serial.print("servo: ");
  23.     Serial.print(s);
  24.     Serial.print(" Angle: ");
  25.     Serial.println(a);
  26.     myservo[s].write(a);        // sets the servo position
  27.     delay(250);
  28.   }
  29. }
  30.  
  31. void stest() {
  32.   for (int i = 0; i < 4; i++){
  33.     setservos(sangle[i]);
  34.     delay(500);
  35.   }
  36. }
  37.  
  38. void setup() {
  39.   Serial.begin(9600);
  40.   Serial.println("Arduino is ready");
  41.   Serial.println("Write leater t-est, r-ight, m-idle, l-eft");
  42.   for (int s = 0;s < 4;s++) {
  43.     myservo[s].attach(spin[s]);  // attaches the servos on pins
  44.     myservo[s].write(90);        // sets the servo position to midle
  45.   }
  46. }
  47.  
  48. void loop() {
  49.   readChar();
  50.   if (d == true) {
  51.     if (c == 't') {
  52.       Serial.println("Servo test");
  53.       stest();
  54.     }
  55.     if (c == 'r') {
  56.       Serial.println("Servo to right");
  57.       setservos(0);
  58.     }
  59.     if (c == 'm') {
  60.       Serial.println("Servo to midle");
  61.       setservos(90);
  62.     }
  63.     if (c == 'l') {
  64.       Serial.println("Servo to left");
  65.       setservos(180);
  66.     }
  67.     d = false;
  68.   }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment