Advertisement
Helium

AutoClaw 1.4

Jan 16th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.87 KB | None | 0 0
  1. /*  ARDUINO AUTOCLAW V1.3.7
  2.  *  APSC 101 T2
  3.  *  LAST EDITED BY MANSUR HE, 2016-01-16
  4.  */
  5.  
  6. // library
  7. #include <Servo.h>
  8.  
  9. // ---- Pin constants
  10. // Sonar
  11. #define SONAR_ECHO 11
  12. #define SONAR_TRIG 12
  13. #define SONAR_POWER 10
  14. // Servo
  15. #define SERVO_PIN 9
  16.  
  17. // sonar constants
  18. #define MIN_DISTANCE 5
  19. #define SONAR_DELAY 1000
  20.  
  21. // servo constants
  22. #define GRAB_TIME 5000
  23. #define SERVO_MIN 40
  24. #define SERVO_MAX 130
  25.  
  26. // shared variables and instances
  27. bool isActivated;
  28. Servo claw_servo;
  29.  
  30.  
  31. void setup() {
  32.   // Enables Serial Monitoring
  33.   Serial.begin(9600);
  34.  
  35.   // Pin setup
  36.   pinMode(SONAR_ECHO, INPUT);
  37.   pinMode(SONAR_TRIG, OUTPUT);
  38.   pinMode(SONAR_POWER, OUTPUT);
  39.  
  40.   digitalWrite(SONAR_POWER, HIGH);
  41.  
  42.   // Servo setup
  43.   claw_servo.attach(SERVO_PIN);
  44.   claw_servo.write(SERVO_MIN);
  45. }
  46.  
  47.  
  48. void loop() {
  49.  
  50.   // Get sonar distance
  51.   int distance = getDistance();
  52.  
  53.   // Cereal output
  54.   if (! isActivated) {
  55.    
  56.     // --- IN SONAR STATE
  57.     if (distance >= 200 || distance <= 0) {
  58.       Serial.println("Invalid/Range Error");
  59.     } else {
  60.      
  61.       // Activate SERVO state when distance is correct
  62.       if (distance < MIN_DISTANCE) {
  63.         isActivated = true;
  64.       }
  65.  
  66.       // Feedback to serial monitor
  67.       Serial.println(distance);    
  68.     }
  69.   } else {
  70.    
  71.     // --- IN SERVO STATE
  72.     Serial.println("CLAW ACTIVATED...");
  73.  
  74.     // Servo control
  75.     claw_servo.write(SERVO_MAX);
  76.  
  77.     // wait for 5 seconds
  78.     delay(GRAB_TIME);
  79.     isActivated = false;
  80.     claw_servo.write(SERVO_MIN);
  81.   }
  82. }
  83.  
  84.  
  85. float getDistance() {
  86.   int duration;
  87.  
  88.   // activate sonar trigger
  89.   digitalWrite(SONAR_TRIG, HIGH);
  90.  
  91.   // deactivates sonar trigger
  92.   delay(SONAR_DELAY);
  93.   digitalWrite(SONAR_TRIG, LOW);
  94.  
  95.   // reads the pulse duration
  96.   duration = pulseIn(SONAR_ECHO, HIGH);
  97.  
  98.   // converts into distance
  99.   return (duration / 2) /29.1;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement