Created
July 1, 2025 05:18
-
-
Save tomoyanonymous/19a91c7bb0b81914fa2307caffa1c599 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Servo.h> | |
constexpr int instrument_pins[] = { 3, 5, 6, 9, 10, 11 }; // Expected to be used in Uno R3/R4 | |
constexpr int numbers = sizeof(instrument_pins) / sizeof(int); | |
Servo instruments[numbers]; | |
void setup() { | |
for (int i = 0; i < numbers; i++) { | |
instruments[i].attach(instrument_pins[i]); | |
} | |
Serial.begin(115200); | |
while (!Serial) | |
; // Wait for Serial (needed on some boards) | |
Serial.println("connected"); | |
} | |
void loop() { | |
if (Serial.available()) { | |
auto msg = Serial.readStringUntil('\n'); | |
processMessage(msg); | |
delay(20);//need adjustment | |
for (int i = 0; i < numbers; i++) { | |
//flush all pins to ensure sending only single pulse | |
instruments[instrument_pins[i]].writeMicroseconds(0); | |
} | |
} | |
} | |
char buffer[512]; | |
int find_pins(int pin) { | |
int res = -1; | |
for (int i = 0; i < numbers; i++) { | |
if (pin == instrument_pins[i]) { | |
res = i; | |
} | |
} | |
return res; | |
} | |
void processMessage(String msg) { | |
// msg format: <pin1>,<dur1> <pin2>,<dur2> ... \n | |
strcpy(buffer, msg.c_str()); | |
char* msg_head = &buffer[0]; | |
while (true) { | |
auto pin = atoi(strtok(msg_head, ",")); | |
auto dur = atoi(strtok(NULL, " ")); //read w/ continue | |
auto pin_count = find_pins(pin); | |
if (pin_count >= 0) { | |
instruments[pin_count].writeMicroseconds(dur); | |
char msg[30]; | |
sprintf(msg,"write %d to pin %d", dur,pin); | |
Serial.println(msg); | |
}else{ | |
memset(buffer, '\0', sizeof(buffer)); | |
return; | |
} | |
msg_head = NULL; // to continue reading with strtok | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment