Arduino – Joystick-LINK
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
#include <Servo.h> #define joystickX A4 #define joystickY A5 #define joystickSw A0 #define motorA 6 #define motorB 9 #define buttonPower 2 #define buttonAuto 3 #define buttonSpeed1 4 #define buttonSpeed2 5 Servo myservo; int powers=0; int speeds=150; int positions=90; int rotations=0; int states=1; unsigned long cnt=0; unsigned long cnt2=0; void setup() { Serial.begin(9600); myservo.attach(10); pinMode(buttonPower, INPUT); pinMode(buttonAuto, INPUT); pinMode(buttonSpeed1, INPUT); pinMode(buttonSpeed2, INPUT); } void buttonStates() { if (digitalRead(buttonPower) && cnt==0) { powers=!powers; cnt=millis(); } else if (digitalRead(buttonAuto) && cnt==0) { rotations=!rotations; cnt=millis(); } else if (millis() > cnt+300) { cnt=0; } if (digitalRead(buttonSpeed1)) { speeds=150; } else if (digitalRead(buttonSpeed2)) { speeds=255; } } void autoRotations() { if (millis() > cnt2+15) { if (rotations) { positions+=states; if (positions >= 180) { states=-1; } else if (positions <= 0) { states=1; } } else { if (analogRead(joystickX) > 1024/2+30) { positions++; } else if (analogRead(joystickX) < 1024/2-30) { positions--; } positions=constrain(positions, 0, 180); } myservo.write(positions); cnt2=millis(); } } void loop() { buttonStates(); if (powers) { analogWrite(motorB, 0); analogWrite(motorA, speeds); autoRotations(); } else { analogWrite(motorB, 0); analogWrite(motorA, 0); } Serial.print("powers : "); Serial.print(powers); Serial.print(", speeds : "); Serial.print(speeds); Serial.print(", positions : "); Serial.print(positions); Serial.print(", rotations : "); Serial.print(rotations); Serial.print(", states : "); Serial.println(states); } |