URM37AndServo.ino 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <Servo.h>
  2. #include <Metro.h>
  3. Metro measureDistance = Metro(50);
  4. Metro sweepServo = Metro(20);
  5. unsigned long actualDistance = 0;
  6. Servo myservo; // create servo object to control a servo
  7. int pos = 60;
  8. int sweepFlag = 1;
  9. int URPWM = 3; // PWM Output 0-25000US,Every 50US represent 1cm
  10. int URTRIG= 10; // PWM trigger pin
  11. uint8_t EnPwmCmd[4]={0x44,0x02,0xbb,0x01}; // distance measure command
  12. void setup(){ // Serial initialization
  13. myservo.attach(9);
  14. Serial.begin(9600); // Sets the baud rate to 9600
  15. SensorSetup();
  16. }
  17. void loop(){
  18. if(measureDistance.check() == 1){
  19. actualDistance = MeasureDistance();
  20. // Serial.println(actualDistance);
  21. // delay(100);
  22. }
  23. if(sweepServo.check() == 1){
  24. servoSweep();
  25. }
  26. }
  27. void SensorSetup(){
  28. pinMode(URTRIG,OUTPUT); // A low pull on pin COMP/TRIG
  29. digitalWrite(URTRIG,HIGH); // Set to HIGH
  30. pinMode(URPWM, INPUT); // Sending Enable PWM mode command
  31. for(int i=0;i<4;i++){
  32. Serial.write(EnPwmCmd[i]);
  33. }
  34. }
  35. int MeasureDistance(){ // a low pull on pin COMP/TRIG triggering a sensor reading
  36. digitalWrite(URTRIG, LOW);
  37. digitalWrite(URTRIG, HIGH); // reading Pin PWM will output pulses
  38. unsigned long distance=pulseIn(URPWM,LOW);
  39. if(distance==50000){ // the reading is invalid.
  40. Serial.print("Invalid");
  41. }else{
  42. distance=distance/50; // every 50us low level stands for 1cm
  43. }
  44. return distance;
  45. }
  46. void servoSweep(){
  47. if(sweepFlag ){
  48. if(pos>=60 && pos<=120){
  49. pos=pos+1; // in steps of 1 degree
  50. myservo.write(pos); // tell servo to go to position in variable 'pos'
  51. }
  52. if(pos>119) sweepFlag = false; // assign the variable again
  53. }else {
  54. if(pos>=60 && pos<=120){
  55. pos=pos-1;
  56. myservo.write(pos);
  57. }
  58. if(pos<61) sweepFlag = true;
  59. }
  60. }