🔗소프트웨어 링크바로가기

핵심 기능

사용 방법

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

    image.png

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

    image.png

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

    image.png

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

    image.png

전체 코드

#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);
    }
  }
}

주요 코드 설명

서모모터 연결

데이터 수신 규약

// 파이썬에서 값이 들어왔을 때만 실행
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();

확장 아이디어