Guest User

Untitled

a guest
Jan 16th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #include "Servo.h"
  2. #define M1 9
  3. #define M2 10
  4. #define M3 11
  5. #define TOTAL_MOTORS 2
  6. Servo motor[TOTAL_MOTORS];
  7. Servo base;
  8. int mmax[TOTAL_MOTORS] = {180, 180};
  9. int mmin[TOTAL_MOTORS] = {0, 0};
  10. int current_degree[TOTAL_MOTORS] = {90, 90};
  11.  
  12. void setup() {
  13. Serial.begin(9600);
  14. pinMode(2, INPUT);
  15. pinMode(3, INPUT);
  16. motor[0].attach(M2);
  17. motor[1].attach(M3);
  18. base.attach(M1);
  19. base.write(90);
  20. delay(300);
  21. for(int i=0; i<TOTAL_MOTORS; i++) {
  22. motor[i].write(90); delay(200);
  23. current_degree[i] = 90;
  24. }
  25. }
  26. // 此函數用來一次把3個伺服馬達調整到指定的角度(degree陣列)
  27. void arm_move_all_to(int degree[]) {
  28. int diff[TOTAL_MOTORS];
  29. int max_diff_degree=0; // 最大的差異角度數
  30. int max_index=0; // 最大差異角度的那個伺服馬達
  31. int remap[TOTAL_MOTORS][180]; // 重新對應角度用的陣列
  32. // 以下的迴圈用來找出哪一個伺服器的差異角度最多
  33. for(int i=0; i<TOTAL_MOTORS; i++) {
  34. diff[i] = degree[i] - current_degree[i] ;
  35. if(abs(diff[i])>max_diff_degree) {
  36. max_index = i;
  37. max_diff_degree = abs(diff[i]);
  38. }
  39. }
  40. // 以下重新對應要調整的角度陣列
  41. for(int i=0; i<=max_diff_degree; i++) {
  42. for(int motor_no=0; motor_no<TOTAL_MOTORS; motor_no++) {
  43. remap[motor_no][i] = current_degree[motor_no] +
  44. (int) (((float)diff[motor_no]/(float)max_diff_degree)*i);
  45. //disp_var(remap[motor_no][i]);
  46. }
  47. }
  48. // 以下開始讓伺服馬達調整角度
  49. for(int i=0; i<=max_diff_degree; i++) {
  50. for(int motor_no=0; motor_no<TOTAL_MOTORS; motor_no++) {
  51. current_degree[motor_no] = remap[motor_no][i];
  52. motor[motor_no].write(remap[motor_no][i]);
  53. }
  54. delay(20);
  55. //disp_current_degree();
  56. }
  57. //delay(1000);
  58. }
  59. int count=0;
  60. void loop() {
  61. int pin2, pin3;
  62. int d[2];
  63. d[0]=170; d[1]=20;
  64. arm_move_all_to(d);
  65. d[0]=60; d[1]=180;
  66. arm_move_all_to(d);
  67. pin2 = digitalRead(2);
  68. pin3 = digitalRead(3);
  69. if(++count<5) {
  70. base.write(80);
  71. delay(300);
  72. } else {
  73. base.write(100);
  74. delay(300);
  75. if(count>10) count=0;
  76. }
  77. base.write(90);
  78. delay(300);
  79. }
Add Comment
Please, Sign In to add comment