#include #include #include #include // Self Made Lib #include // Verbindung Adafruit_PWMServoDriver board0 = Adafruit_PWMServoDriver(0x40); Adafruit_PWMServoDriver board1 = Adafruit_PWMServoDriver(0x41); SoftwareSerial BTSerial(11, 10); // RX | TX // Konstanten #define SERVOMIN 125 // this is the 'minimum' pulse length count (out of 4096) #define SERVOMAX 625 // this is the 'maximum' pulse length count (out of 4096) #define BUFFERSIZE 128 // Variablen const int numRows = 6; const int numCols = 3; int legarray[numRows][numCols]; char legBuffer[BUFFERSIZE]; int bufIndex = 0; boolean reading = false; JackBotEmotes face; void setup() { // USB //Serial.begin(9600); // Bluetooth BTSerial.begin(38400); board0.begin(); board0.setPWMFreq(50); board1.begin(); board1.setPWMFreq(50); pinMode(3, OUTPUT); //Define TX Pin as output pinMode(2, INPUT); //Define RX Pin as input // Initialiesieren der Start Position for (int i = 0; i < 6; i++) { for (int j = 0; j < 3; j++) { legarray[i][j] = 90; } } ServoControll(legarray); face.begin(); face.showText("Hello JackBot!", 1, 0); } void loop() { face.update(); while (BTSerial.available()) { char c = BTSerial.read(); if (c == '<') { // reset buffer for new frame bufIndex = 0; reading = true; } else if (c == '>') { // end of frame if (reading) { legBuffer[bufIndex] = '\0'; // null-terminate string if (stringToArray(String(legBuffer))) { ServoControll(legarray); face.smile(); face.showText("Moving!", 4, 1); } else { face.showText("Data Err!", 3, 1); } } reading = false; } else if (reading) { if (bufIndex < BUFFERSIZE - 1) { legBuffer[bufIndex++] = c; } else { // buffer overflow → discard this frame reading = false; } } } } // Funktion: Ansteuern der Servos void ServoControll(int leg[6][3]) { for (int i = 0; i < 6; i++) { for (int j = 0; j < 3; j++) { if (i < 3) { board0.setPWM(i * 3 + j, 0, angleToPulse(leg[i][j])); } else { board1.setPWM((i - 3) * 3 + j, 0, angleToPulse(leg[i][j])); } } } } // Funktion: Konvertiert den Winkel in PWM int angleToPulse(int ang) { return map(ang, 0, 180, SERVOMIN, SERVOMAX); } // Funktion: Konvertiert den String in das Array bool stringToArray(String input) { input.replace("\n", ","); char buffer[input.length() + 1]; input.toCharArray(buffer, sizeof(buffer)); char *token = strtok(buffer, ","); int row = 0, col = 0; int count = 0; while (token != NULL && row < numRows) { legarray[row][col] = atoi(token); count++; col++; if (col >= numCols) { col = 0; row++; } token = strtok(NULL, ","); } return count == (numRows * numCols); }