- #include <SoftwareSerial.h>
- #include <Servo.h>
- #define MAX_BUF_LEN 32
- #define SERVO_PIN 5
- #define SERVO_RESET 120 // degree
- #define SERVO_STEP_SIZE 2
- #define SERVO_STEP_DELAY 40 // in ms
- static char buf[MAX_BUF_LEN] = {0};
- Servo servo;
- void servo_move(Servo& s, int old_degree, int new_degree, int step_size, int step_delay)
- {
- int i=0;
- if(new_degree<0) new_degree=0;
- else if(new_degree>180) new_degree=180;
-
- if(old_degree>new_degree){
- for(i=old_degree-step_size;i>new_degree;i-=step_size){
- s.write(i);
- delay(step_delay);
- }
- }else if(old_degree<new_degree){
- for(i=old_degree+step_size;i<new_degree;i+=step_size){
- s.write(i);
- delay(step_delay);
- }
- }
-
- if(i!=new_degree) s.write(new_degree);
- delay(step_delay);
- }
- void setup()
- {
- // Open serial communications and wait for port to open:
- Serial.begin(57600);
-
- servo.attach(SERVO_PIN);
- int old_degree=servo.read();
- servo_move(servo,old_degree,SERVO_RESET,SERVO_STEP_SIZE,SERVO_STEP_DELAY);
- }
- void process_command(Servo& s, char* buf, int len)
- {
- int old_degree,new_degree;
- int inc100, inc10,inc,val;
-
- if(len<6 || buf[0]=='+') return;
-
- inc100=buf[3]-'0';
- inc100=100*inc100;
- inc10=buf[4]-'0';
- inc10=10*inc10;
- inc=buf[5]-'0';
-
- val=inc100+inc10+inc;
-
- if(val<0) val=0;
- else if(val>180) val=180;
- old_degree=servo.read();
-
- if(buf[0]=='i' && buf[1]=='n' && buf[2]=='c') {
- new_degree=old_degree+val;
- if(new_degree>180)new_degree=180;
- servo_move(servo, old_degree, old_degree+val, SERVO_STEP_SIZE, SERVO_STEP_DELAY);
- }else if(buf[0]=='d' && buf[1]=='e' && buf[2]=='c'){
- new_degree=old_degree-val;
- if(new_degree<0)new_degree=0;
- servo_move(servo, old_degree, new_degree, SERVO_STEP_SIZE, SERVO_STEP_DELAY);
- }else if(buf[0]=='s' && buf[1]=='e' && buf[2]=='t'){
- servo_move(servo, old_degree, val, SERVO_STEP_SIZE, SERVO_STEP_DELAY);
- }
-
- }
- void loop()
- {
-
- static int i=0;
-
- if (Serial.available()){
- buf[i]=Serial.read();
- if(buf[i]=='\n'){
- buf[i]=0;
- process_command(servo, buf,i);
- i=0;
- } else i++;
- }
- }
阅读(2773) | 评论(0) | 转发(0) |