Skip to content

Instantly share code, notes, and snippets.

@dolphin2410
Created May 1, 2024 06:15
Show Gist options
  • Save dolphin2410/dc29430a36067b04ddc091bd7f59f178 to your computer and use it in GitHub Desktop.
Save dolphin2410/dc29430a36067b04ddc091bd7f59f178 to your computer and use it in GitHub Desktop.
Wheel control using serial
#define LWheel 0
#define RWheel 1
// 0: not running, 1: only left is running, 2: only right is running, 3: both is running
int runningState = 0;
int priorRunningState = -1;
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
String s = "";
char c;
while((c = Serial.read()) != -1) {
s += c;
delay(10);
}
if (s.startsWith("lr")) {
runningState = 3;
Serial.println("runningState: 3");
} else if (s.startsWith("r")) {
runningState = 2;
Serial.println("runningState: 2");
} else if (s.startsWith("l")) {
runningState = 1;
Serial.println("runningState: 1");
} else if (s.startsWith("s")) {
runningState = 0;
Serial.println("runningState: 0");
}
}
if (runningState == priorRunningState) {
return;
}
switch(runningState) {
case 0:
analogWrite(LWheel, 0);
analogWrite(RWheel, 0);
priorRunningState = 0;
break;
case 1:
analogWrite(LWheel, 255);
analogWrite(RWheel, 0);
priorRunningState = 1;
break;
case 2:
analogWrite(LWheel, 0);
analogWrite(RWheel, 255);
priorRunningState = 2;
break;
case 3:
analogWrite(LWheel, 255);
analogWrite(RWheel, 255);
priorRunningState = 3;
break;
}
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment