Skip to content

Instantly share code, notes, and snippets.

@yubeneko
Created October 31, 2019 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yubeneko/b940018a5cc3aa3c9a81443f2f54a97c to your computer and use it in GitHub Desktop.
Save yubeneko/b940018a5cc3aa3c9a81443f2f54a97c to your computer and use it in GitHub Desktop.
ラズパイから送られてきたサーボ角度のデータを処理してサーボを制御するコード
#include <Servo.h>
// 受信文字列
String received_data;
// 受信した文字列を変換する
String angles[2];
// ピッチ, ヨー
int angle_pitch;
int angle_yaw;
// サーボオブジェクト
Servo servo_pitch;
Servo servo_yaw;
// 文字列分割関数
// https://algorithm.joho.info/arduino/string-split-delimiter/
int split(String data, char delimiter, String *dst){
int index = 0;
int arraySize = (sizeof(data)/sizeof((data)[0]));
int datalength = data.length();
for (int i = 0; i < datalength; i++) {
char tmp = data.charAt(i);
if ( tmp == delimiter ) {
index++;
if ( index > (arraySize - 1)) return -1;
}
else dst[index] += tmp;
}
return (index + 1);
}
void setup()
{
// Serial Setting
Serial.begin(115200);
Serial.setTimeout(20);
servo_pitch.attach(9);
servo_yaw.attach(10);
servo_pitch.write(90);
servo_yaw.write(90);
}
void loop()
{
}
void serialEvent()
{
received_data = Serial.readStringUntil('\n');
if (received_data == "Init")
{
servo_pitch.write(90);
servo_yaw.write(90);
return;
}
split(received_data, ',', angles);
angle_pitch = angles[0].toInt();
angle_yaw = angles[1].toInt();
servo_pitch.write(angle_pitch);
servo_yaw.write(angle_yaw);
angles[0] = "";
angles[1] = "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment