Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.32 KB | None | 0 0
  1. #include <SoftwareSerial.h>
  2. #include <Wire.h>
  3. #include <NewPing.h> //include 超音波標頭檔
  4. #define MAX_DISTANCE 50 //超音波最遠接收到50cm
  5. NewPing sonar(13, 12, MAX_DISTANCE); //設定超音波腳位(trig為Pin 13, echo為Pin 12)
  6. int cm; //cm為存取超音波數值的變數
  7. SoftwareSerial BT(0,1); ////設定軟體串列通訊給藍芽用腳位設定(trig為Pin 10, echo為Pin 11)
  8. int strsize;
  9. int k=15;
  10. ////////////////////////////////////motor設定//////////////////////////////////////////////////////////
  11. /*
  12. 直流馬達 的 AIN1 連接至 Arduino 之 的 pin 2
  13. 直流馬達 的 PWM1 連接至 Arduino 之 的 pin 3
  14. 直流馬達 的 BIN1 連接至 Arduino 之 的 pin 4
  15. 直流馬達 的 PWM2 連接至 Arduino 之 的 pin 5
  16. */
  17. const int DC_DIR_1 = 7;
  18. const int DC_Motor_1 = 6;
  19. const int DC_DIR_2 = 4;
  20. const int DC_Motor_2 = 5;
  21. ////////////////////////////////////motor設定//////////////////////////////////////////////////////////
  22. void setup() {
  23. pinMode(4, OUTPUT);
  24. pinMode(5, OUTPUT);
  25. pinMode(6, OUTPUT);
  26. pinMode(7, OUTPUT); // sets the motor pin as output
  27. BT.begin(9600);
  28. Serial.begin(9600);
  29. }
  30.  
  31. void loop() {
  32.  
  33. while(true){
  34. if ((strsize=(BT.available()))>0){
  35. k=char(BT.read());
  36. if(k==77)
  37. {
  38. cm = sonar.ping_cm(); //接收超音波數值,單位cm
  39. Serial.print(" urtrasonic detect= ");
  40. Serial.print(cm);
  41. Serial.println(" cm");
  42. Serial.print(" cmd= ");
  43. Serial.println(k);
  44. BT.write(cm);
  45. // Serial.print(" test ");
  46. //Serial.println(cm);
  47. }
  48. else
  49. {
  50. Serial.print(" urtrasonic detect= ");
  51. Serial.print(cm);
  52. Serial.println(" cm");
  53. Serial.print(" cmd= ");
  54. Serial.println(k);
  55. }
  56. if(k==61) //a
  57. {
  58. digitalWrite(DC_DIR_1,LOW);
  59. digitalWrite(DC_DIR_2,LOW);
  60. analogWrite(DC_Motor_1, 150);
  61. analogWrite(DC_Motor_2, 150);
  62. delay(50); 延遲
  63. }
  64. else if(k==62) //b
  65. {
  66. digitalWrite(DC_DIR_1,HIGH);
  67. digitalWrite(DC_DIR_2,HIGH);
  68. analogWrite(DC_Motor_1, 150);
  69. analogWrite(DC_Motor_2, 150);
  70. delay(50); 延遲
  71. }
  72. else if(k==63) //c
  73. {
  74. digitalWrite(DC_DIR_1,LOW);
  75. digitalWrite(DC_DIR_2,HIGH);
  76. analogWrite(DC_Motor_1, 150);
  77. analogWrite(DC_Motor_2, 150);
  78. delay(50); 延遲
  79. }
  80. else if(k==64) //d
  81. {
  82. digitalWrite(DC_DIR_1,HIGH);
  83. digitalWrite(DC_DIR_2,LOW);
  84. analogWrite(DC_Motor_1, 150); 馬達轉速150
  85. analogWrite(DC_Motor_2, 150); 馬達轉速150
  86. delay(50); 延遲
  87. }
  88. else if(k==65) //e 感應到65
  89. {
  90. analogWrite(DC_Motor_1, 0); 馬達轉速零
  91. analogWrite(DC_Motor_2, 0); 馬達轉速零
  92. delay(50); 延遲
  93. }
  94.  
  95.  
  96. }
  97.  
  98.  
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement