Advertisement
cisco404

kode program sederhana robot line follower

May 27th, 2024
545
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.24 KB | Source Code | 0 0
  1. // Pin definiton for motor driver
  2. const int motorLeftForward = 3;
  3. const int motorLeftBackward = 5;
  4. const int motorRightForward = 6;
  5. const int motorRightBackward = 9;
  6.  
  7. // -------------------------------------------
  8. // kode program sederhana robot line follower
  9. // www.ardukode.blogspot.com
  10. // -------------------------------------------
  11.  
  12. // Pin definition for line sensor
  13. const int sensorLeft = A0;
  14. const int sensorRight = A1;
  15.  
  16. void setup() {
  17.   // Set motor driver pins as output
  18.   pinMode(motorLeftForward, OUTPUT);
  19.   pinMode(motorLeftBackward, OUTPUT);
  20.   pinMode(motorRightForward, OUTPUT);
  21.   pinMode(motorRightBackward, OUTPUT);
  22.  
  23.   // Set sensor pins as input
  24.   pinMode(sensorLeft, INPUT);
  25.   pinMode(sensorRight, INPUT);
  26.  
  27.   // Start serial communication for debugging
  28.   Serial.begin(9600);
  29. }
  30.  
  31. void loop() {
  32.   // Read sensor values
  33.   int leftSensorValue = analogRead(sensorLeft);
  34.   int rightSensorValue = analogRead(sensorRight);
  35.  
  36.   // Debugging: print sensor values
  37.   Serial.print("Left Sensor: ");
  38.   Serial.print(leftSensorValue);
  39.   Serial.print(" - Right Sensor: ");
  40.   Serial.println(rightSensorValue);
  41.  
  42.   // Line following logic
  43.   if (leftSensorValue > 500 && rightSensorValue < 500) {
  44.     // Turn right
  45.     moveRight();
  46.   } else if (rightSensorValue > 500 && leftSensorValue < 500) {
  47.     // Turn left
  48.     moveLeft();
  49.   } else if (leftSensorValue < 500 && rightSensorValue < 500) {
  50.     // Move forward
  51.     moveForward();
  52.   } else {
  53.     // Stop
  54.     stopMoving();
  55.   }
  56. }
  57.  
  58. void moveForward() {
  59.   digitalWrite(motorLeftForward, HIGH);
  60.   digitalWrite(motorLeftBackward, LOW);
  61.   digitalWrite(motorRightForward, HIGH);
  62.   digitalWrite(motorRightBackward, LOW);
  63. }
  64.  
  65. void moveLeft() {
  66.   digitalWrite(motorLeftForward, LOW);
  67.   digitalWrite(motorLeftBackward, LOW);
  68.   digitalWrite(motorRightForward, HIGH);
  69.   digitalWrite(motorRightBackward, LOW);
  70. }
  71.  
  72. void moveRight() {
  73.   digitalWrite(motorLeftForward, HIGH);
  74.   digitalWrite(motorLeftBackward, LOW);
  75.   digitalWrite(motorRightForward, LOW);
  76.   digitalWrite(motorRightBackward, LOW);
  77. }
  78.  
  79. void stopMoving() {
  80.   digitalWrite(motorLeftForward, LOW);
  81.   digitalWrite(motorLeftBackward, LOW);
  82.   digitalWrite(motorRightForward, LOW);
  83.   digitalWrite(motorRightBackward, LOW);
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement