Chinaunix首页 | 论坛 | 博客
  • 博客访问: 312173
  • 博文数量: 27
  • 博客积分: 758
  • 博客等级: 军士长
  • 技术积分: 369
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-08 23:10
文章分类

全部博文(27)

文章存档

2014年(1)

2012年(26)

我的朋友

分类: 嵌入式

2012-11-05 08:57:19


  1. #include <SoftwareSerial.h>
  2. #include <Servo.h>

  3. #define MAX_BUF_LEN 32
  4. #define SERVO_PIN 5
  5. #define SERVO_RESET 120 // degree
  6. #define SERVO_STEP_SIZE 2
  7. #define SERVO_STEP_DELAY 40 // in ms

  8. static char buf[MAX_BUF_LEN] = {0};
  9. Servo servo;


  10. void servo_move(Servo& s, int old_degree, int new_degree, int step_size, int step_delay)
  11. {
  12.   int i=0;
  13.   if(new_degree<0) new_degree=0;
  14.   else if(new_degree>180) new_degree=180;
  15.   
  16.   if(old_degree>new_degree){
  17.     for(i=old_degree-step_size;i>new_degree;i-=step_size){
  18.       s.write(i);
  19.       delay(step_delay);
  20.     }
  21.   }else if(old_degree<new_degree){
  22.      for(i=old_degree+step_size;i<new_degree;i+=step_size){
  23.       s.write(i);
  24.       delay(step_delay);
  25.     }
  26.   }
  27.   
  28.   if(i!=new_degree) s.write(new_degree);
  29.   delay(step_delay);
  30. }


  31. void setup()
  32. {
  33.  // Open serial communications and wait for port to open:
  34.   Serial.begin(57600);
  35.   
  36.   servo.attach(SERVO_PIN);

  37.   int old_degree=servo.read();
  38.   servo_move(servo,old_degree,SERVO_RESET,SERVO_STEP_SIZE,SERVO_STEP_DELAY);

  39. }



  40. void process_command(Servo& s, char* buf, int len)
  41. {
  42.   int old_degree,new_degree;
  43.   int inc100, inc10,inc,val;
  44.   
  45.   if(len<6 || buf[0]=='+') return;
  46.   
  47.   inc100=buf[3]-'0';
  48.   inc100=100*inc100;
  49.   inc10=buf[4]-'0';
  50.   inc10=10*inc10;
  51.   inc=buf[5]-'0';
  52.   
  53.   val=inc100+inc10+inc;
  54.   
  55.   if(val<0) val=0;
  56.   else if(val>180) val=180;

  57.   old_degree=servo.read();
  58.       
  59.   if(buf[0]=='i' && buf[1]=='n' && buf[2]=='c') {
  60.     new_degree=old_degree+val;
  61.     if(new_degree>180)new_degree=180;
  62.     servo_move(servo, old_degree, old_degree+val, SERVO_STEP_SIZE, SERVO_STEP_DELAY);
  63.   }else if(buf[0]=='d' && buf[1]=='e' && buf[2]=='c'){
  64.     new_degree=old_degree-val;
  65.     if(new_degree<0)new_degree=0;
  66.     servo_move(servo, old_degree, new_degree, SERVO_STEP_SIZE, SERVO_STEP_DELAY);
  67.   }else if(buf[0]=='s' && buf[1]=='e' && buf[2]=='t'){
  68.     servo_move(servo, old_degree, val, SERVO_STEP_SIZE, SERVO_STEP_DELAY);
  69.   }
  70.   
  71. }

  72. void loop()
  73. {
  74.   
  75.   static int i=0;
  76.   
  77.   if (Serial.available()){
  78.     buf[i]=Serial.read();
  79.     if(buf[i]=='\n'){
  80.       buf[i]=0;
  81.       process_command(servo, buf,i);
  82.       i=0;
  83.     } else i++;
  84.   }

  85. }



阅读(2773) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~