หุ่นยนต์เดินตามเส้น 2 เซ็นเซอร์ Arduino
อุปกรณ์ที่ต้องใช้ก็คือ
12. แผ่นอะคริลิค
ตัวอย่างโค้ด Arduino
/*-------definning Inputs------*/
int LS = 2; // left sensor
int RS = 3; // right sensor
/*-------definning Outputs------*/
int LM1 = 4; // left motor
int LM2 = 5; // left motor
int RM1 = 6; // right motor
int RM2 = 7; // right motor
/*-------PWM ควบคุมความเร็วมอเตอร์-----*/
int PWM1 = 10; // PWM left motor
int PWM2 = 11; // PWM right motor
int SPEED = 90; // Speed PWM สามารถปรับความเร็วได้ถึง 255
void setup()
{
pinMode(LS, INPUT);
pinMode(RS, INPUT);
pinMode(LM1, OUTPUT);
pinMode(LM2, OUTPUT);
pinMode(RM1, OUTPUT);
pinMode(RM2, OUTPUT);
pinMode(PWM1, OUTPUT);
pinMode(PWM2, OUTPUT);
}
void loop()
{
if (!(digitalRead(LS)) && !(digitalRead(RS))) // Move Forward
{
analogWrite(PWM1, SPEED);
digitalWrite(LM1, HIGH);
digitalWrite(LM2, LOW);
analogWrite(PWM2, SPEED);
digitalWrite(RM1, HIGH);
digitalWrite(RM2, LOW);
}
if (!(digitalRead(LS)) && digitalRead(RS)) // Turn right
{
digitalWrite(LM1, LOW);
digitalWrite(LM2, LOW);
analogWrite(PWM2, SPEED);
digitalWrite(RM1, HIGH);
digitalWrite(RM2, LOW);
}
if (digitalRead(LS) && !(digitalRead(RS))) // turn left
{
analogWrite(PWM1, SPEED);
digitalWrite(LM1, HIGH);
digitalWrite(LM2, LOW);
digitalWrite(RM1, LOW);
digitalWrite(RM2, LOW);
}
if (digitalRead(LS) && digitalRead(RS)) // stop
{
digitalWrite(LM1, LOW);
digitalWrite(LM2, LOW);
digitalWrite(RM1, LOW);
digitalWrite(RM2, LOW);
}
}
int LS = 2; // left sensor
int RS = 3; // right sensor
/*-------definning Outputs------*/
int LM1 = 4; // left motor
int LM2 = 5; // left motor
int RM1 = 6; // right motor
int RM2 = 7; // right motor
/*-------PWM ควบคุมความเร็วมอเตอร์-----*/
int PWM1 = 10; // PWM left motor
int PWM2 = 11; // PWM right motor
int SPEED = 90; // Speed PWM สามารถปรับความเร็วได้ถึง 255
void setup()
{
pinMode(LS, INPUT);
pinMode(RS, INPUT);
pinMode(LM1, OUTPUT);
pinMode(LM2, OUTPUT);
pinMode(RM1, OUTPUT);
pinMode(RM2, OUTPUT);
pinMode(PWM1, OUTPUT);
pinMode(PWM2, OUTPUT);
}
void loop()
{
if (!(digitalRead(LS)) && !(digitalRead(RS))) // Move Forward
{
analogWrite(PWM1, SPEED);
digitalWrite(LM1, HIGH);
digitalWrite(LM2, LOW);
analogWrite(PWM2, SPEED);
digitalWrite(RM1, HIGH);
digitalWrite(RM2, LOW);
}
if (!(digitalRead(LS)) && digitalRead(RS)) // Turn right
{
digitalWrite(LM1, LOW);
digitalWrite(LM2, LOW);
analogWrite(PWM2, SPEED);
digitalWrite(RM1, HIGH);
digitalWrite(RM2, LOW);
}
if (digitalRead(LS) && !(digitalRead(RS))) // turn left
{
analogWrite(PWM1, SPEED);
digitalWrite(LM1, HIGH);
digitalWrite(LM2, LOW);
digitalWrite(RM1, LOW);
digitalWrite(RM2, LOW);
}
if (digitalRead(LS) && digitalRead(RS)) // stop
{
digitalWrite(LM1, LOW);
digitalWrite(LM2, LOW);
digitalWrite(RM1, LOW);
digitalWrite(RM2, LOW);
}
}
ไม่มีความคิดเห็น:
แสดงความคิดเห็น