작업 공간의 언어 설정이 Arduino(C++)로 설정돼 있는지 확인 합니다.

코드를 작성한뒤 컴파일 버튼을 클릭합니다.

컴파일이 완료됐다면 업로드 버튼을 클릭한뒤 연결된 보드를 선택합니다.

정상적으로 업로드가 됐는지 확인합니다.

#include <Servo.h>
Servo armLeft; // 왼쪽 어깨 서보모터
Servo armRight; // 오른쪽 어깨 서보모터
int leftAngle = 90; // 왼쪽 팔 각도 저장 변수
int rightAngle = 90; // 오른쪽 팔 각도 저장 변수
String data = "";
void setup() {
armLeft.attach(6); // 왼쪽 서보: 6번 핀
armRight.attach(7); // 오른쪽 서보: 7번 핀
armLeft.write(90); // 왼쪽 서보 초기값 설정
armRight.write(90); // 오른쪽 서보 초기값 설정
Serial.begin(9600);
}
void loop() {
// 파이썬에서 값이 들어왔을 때만 실행
if (Serial.available() > 0) {
data = Serial.readStringUntil('\\n');
data.trim();
int commaIndex = data.indexOf(',');
if (commaIndex >= 0 && commaIndex < (int)data.length() - 1) {
// 첫 번째 숫자(왼쪽 팔 각도)
leftAngle = data.substring(0, commaIndex).toInt();
// 두 번째 숫자(오른쪽 팔 각도)
rightAngle = data.substring(commaIndex + 1).toInt();
// 범위 제한
if (leftAngle < 0) leftAngle = 0;
if (leftAngle > 180) leftAngle = 180;
if (rightAngle < 0) rightAngle = 0;
if (rightAngle > 180) rightAngle = 180;
// 서보모터 움직이기(오른쪽은 기구 방향 때문에 180에서 뺌)
armLeft.write(leftAngle);
armRight.write(180 - rightAngle);
}
}
}
Servo 객체를 만들고, 각 서보모터가 연결된 핀 번호를 설정합니다.왼쪽각도,오른쪽각도 형식으로 데이터를 보내고, 마지막에 \\n을 붙입니다.readStringUntil('\\n')으로 데이터 한 줄을 읽고, 쉼표 ,를 기준으로 왼쪽 값과 오른쪽 값을 나눕니다.// 파이썬에서 값이 들어왔을 때만 실행
if (Serial.available() > 0) {
data = Serial.readStringUntil('\\n');
data.trim();
int commaIndex = data.indexOf(',');
if (commaIndex >= 0 && commaIndex < (int)data.length() - 1) {
// 첫 번째 숫자(왼쪽 팔 각도)
leftAngle = data.substring(0, commaIndex).toInt();
// 두 번째 숫자(오른쪽 팔 각도)
rightAngle = data.substring(commaIndex + 1).toInt();