메카트로닉스 진로 교육 (중3)
제공 코드2차시, 초음파 거리 측정과 시리얼 출력
| 언어 | Arduino C++ |
|---|---|
| 설명 | HC-SR04 예제를 측정표 실습용으로 정리한 코드 |
const int TRIG = 9;
const int ECHO = 10;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH); // 10us pulse
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long duration = pulseIn(ECHO, HIGH); // round-trip time (us)
float cm = duration * 0.034 / 2; // sound 0.034 cm/us, halve for one way
Serial.print("distance(cm): ");
Serial.println(cm);
delay(500);
}메카트로닉스 진로 교육 (중3)
제공 코드3차시, 자동문: 20cm 이내면 1초 뒤 열기
| 언어 | Arduino C++ |
|---|---|
| 설명 | 기획안 예시(20cm 이내면 1초 뒤 180°, 없으면 2초 뒤 0°)를 코드로 옮김 |
#include <Servo.h>
const int TRIG = 9;
const int ECHO = 10;
Servo door;
float readCm() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
return pulseIn(ECHO, HIGH) * 0.034 / 2;
}
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
door.attach(6);
door.write(0);
Serial.begin(9600);
}
void loop() {
float cm = readCm();
Serial.print(cm);
if (cm < 20) {
Serial.println(" -> OPEN");
delay(1000);
door.write(180);
} else {
Serial.println(" -> CLOSE");
delay(2000);
door.write(0);
}
}메카트로닉스 진로 교육 (중3)
제공 코드6차시, 로봇팔 동작 각도 표 재생
| 언어 | Arduino C++ |
|---|---|
| 설명 | 2025 로봇팔 제공 코드(Potentiometer_control.ino, 키트 제조사 예제)의 핀 배치 9, 6, 5, 3, 11을 따름. 각도 값은 팀이 측정해 채운다 |
#include <Servo.h>
Servo s[5];
const int PINS[5] = {9, 6, 5, 3, 11}; // base, shoulder, elbow, wrist, gripper
// steps: home -> pick -> move -> place -> home (fill with measured angles)
const int STEPS = 5;
int pose[STEPS][5] = {
{ 90, 90, 90, 90, 90}, // home
{ 60, 120, 60, 90, 40}, // pick (gripper closes)
{120, 100, 80, 90, 40}, // move
{120, 120, 60, 90, 90}, // place (gripper opens)
{ 90, 90, 90, 90, 90}, // home
};
void setup() {
for (int j = 0; j < 5; j++) {
s[j].attach(PINS[j]);
s[j].write(pose[0][j]);
}
delay(1000);
}
void loop() {
for (int i = 0; i < STEPS; i++) {
for (int j = 0; j < 5; j++) s[j].write(pose[i][j]);
delay(800); // tune: too short -> missed grip
}
delay(3000);
}