📣ความรู้ไปประยุกต์ใช้อุปกรณ์อิเล็กทรอนิกส์เพื่อสร้างสรรค์เป็นโครงงานตามที่โจทย์กำหนดได้ คำสั่งเขียน
#include <Servo.h>
Servo servoMotor; //ตัวแปรมอเตอร์ servo
Servo servoWheel;
int servoPin = 9; //OUTPUT Pin มอเดอร์ servo
int servoWheelPin = 3;
int angle=0; //องศาของมอเดตอร์
void setup()
{
Serial.begin(9600);
pinMode(5, OUTPUT);
servoMotor.attach(servoPin);//มอเตอร์ servo
servoMotor.write(0); //ปรับองศาของมอเตอร์ servo ไปที่ 0 องศา
//servoWheel.attach(servoWheelPin);
//servoWheel.write(0);
}
void loop()
{
// Send an ultrasonic pulse
pinMode(7, OUTPUT); // signal pin (trigger) - digital output
digitalWrite(7, LOW); // Initialize pulse as LOW
delayMicroseconds(2);
digitalWrite(7, HIGH); // Send out ultrasonic waves
delayMicroseconds(10);
digitalWrite(7, LOW); // Stops sending out ultrasonic waves
// Receive the reflected ultrasonic pulse
pinMode(7, INPUT); // signal pin (echo) - digital input
long duration = pulseIn(7, HIGH); // Allows us to determine the time it takes for the reflected signals to go back by the echo pin
// Recall distance = (velocity*time)/2
// Convert velocity to cm per microsecond from m/s: ((340)*(100)/(1000000)) = 0.034 cm/ms
long distance = 0.034*duration/2;
// convert to inches
long inches = distance/2.54;
// Print the results
// Has an error of +- 5%
// When object is out of range, the program provides the highest possible (332 cm)
Serial.print("Distance in cm: ");
Serial.println(distance);
Serial.print("Distance in in: ");
Serial.println(inches);
delay(1000);
if(distance<=160){
digitalWrite(5,HIGH);
servoWheel.attach(servoWheelPin);
servoWheel.write(180);
delay(1000);
servoWheel.detach();
servoMotor.write(180);
delay(1000);
servoMotor.write(0);
}
else{
digitalWrite(5,LOW);
servoMotor.write(0);
}
}
ไม่มีความคิดเห็น:
แสดงความคิดเห็น
ครูเต้ง เทคโนฯ