自制舵机

利用最常用的减速电机+电位器,制作了一个舵机模型,这样上课讲解舵机的时候就可以让孩子们很轻松的理解舵机的组成部分了

 

程序源码:


//variables
short int valRead = 0;
short int motorPWM = 110; //amount of power motor (0-255) were 255 is max.

//constants
const short int wireMT_1 = 9; //for wire motor H bridge
const short int wireMT_2 = 10; //for wire motor H bridge
const short int potMT = A0; //motor potentiometer
const short int potIn = A1; //input potentiometer
const short int diff_error = 3; //max error to potentiometer motor
const short int minPot = 400; //minimal position potentiometer motor (0-1023)
const short int maxPot = 1010; //max position potentiometer motor (0-1023)
const short int maxValIn = 1023; //max *input value. For this case 1023, the max of pot.
// *here can use something like degress, where max could be 180

//setup
void setup() {
Serial.begin(9600);
pinMode (wireMT_1, OUTPUT); //wire motor to H bridge
pinMode (wireMT_2, OUTPUT); //wire motor to H bridge
pinMode (potMT, INPUT); //motor potentiometer
pinMode (potIn, INPUT); //input potentiometer
digitalWrite (wireMT_1, LOW);
digitalWrite (wireMT_2, LOW);
}

//run motor function
void runMotor(short int valTarget) {
//proportionality between input and output value
while (valRead <= valTarget && abs(valRead - valTarget) > diff_error) {
valRead = (((float)analogRead(potMT) - minPot) / (maxPot - minPot)) * maxValIn;
//run motor
analogWrite (wireMT_1, motorPWM);
analogWrite (wireMT_2, 0);
}
analogWrite (wireMT_1, 0); //turn off motor

//proportionality between input and output value
while (valRead >= valTarget && abs(valRead - valTarget) > diff_error) {
valRead = (((float)analogRead(potMT) - minPot) / (maxPot - minPot)) * maxValIn;
//run motor
analogWrite (wireMT_2, motorPWM);
analogWrite (wireMT_1, 0);
}
analogWrite (wireMT_2, 0); //turn off motor
}

//loop
void loop() {
short int val = analogRead(potIn); //read input potentiometer
runMotor(val); //run motor for target value
//runMotor(1023-val); //use for invert direction motor
Serial.print("motor: ");
Serial.print(analogRead(A0));
Serial.print(" input: ");
Serial.print(analogRead(A1));
Serial.println();
}