11/*
2- Arduino Servo DC Motor
2+ Arduino Servo DC Motor v1.0
33 PWM proportional
44 Ronaldo Rezende Junior
55 ronaldo.rrj at gmail
88*/
99
1010// variables
11- short int valPot = 0 ;
11+ short int valRead = 0 ;
1212short int motorPWM = 0 ;
1313short int error = 0 ; // difference between target value and input value
1414
@@ -19,10 +19,10 @@ const short int wireMT_1 = 5; //for wire motor H bridge
1919const short int wireMT_2 = 6 ; // for wire motor H bridge
2020const short int potMT = A0; // motor potentiometer
2121const short int potIn = A3; // input potentiometer
22- const short int diff_error = 20 ; // max error to potentiometer motor
22+ const short int diff_error = 10 ; // max error to potentiometer motor
2323const short int minPot = 10 ; // minimal input value
2424const short int maxPot = 1010 ; // max input value
25- const short int maxValIn = 999 ; // max *potentiometer value
25+ const short int maxValIn = 1023 ; // max *input value. For this case 1023, the max of pot.
2626// *here can use something like degress, where max could be 180
2727
2828// setup
@@ -33,16 +33,15 @@ void setup() {
3333 pinMode (potIn, INPUT); // input potentiometer
3434 digitalWrite (wireMT_1, LOW);
3535 digitalWrite (wireMT_2, LOW);
36- valPot = analogRead (potMT);
3736}
3837
3938// run motor function
40- void runMotor (short int valIn ) {
39+ void runMotor (short int valTarget ) {
4140 // proportionality between input and output value
42- while (valPot <= valIn && abs (valPot - valIn ) > diff_error) {
43- valPot = (((float )analogRead (potMT) - minPot) / (maxPot - minPot)) * maxValIn;
41+ while (valRead <= valTarget && abs (valRead - valTarget ) > diff_error) {
42+ valRead = (((float )analogRead (potMT) - minPot) / (maxPot - minPot)) * maxValIn;
4443 // pwm proportional
45- error = valIn - valPot ;
44+ error = valTarget - valRead ;
4645 motorPWM = ((kp * error) / 100 ) + mp;
4746 // run motor
4847 analogWrite (wireMT_1, motorPWM);
@@ -51,10 +50,10 @@ void runMotor(short int valIn) {
5150 analogWrite (wireMT_1, 0 ); // turn off motor
5251
5352 // proportionality between input and output value
54- while (valPot >= valIn && abs (valPot - valIn ) > diff_error) {
55- valPot = (((float )analogRead (potMT) - minPot) / (maxPot - minPot)) * maxValIn;
53+ while (valRead >= valTarget && abs (valRead - valTarget ) > diff_error) {
54+ valRead = (((float )analogRead (potMT) - minPot) / (maxPot - minPot)) * maxValIn;
5655 // pwm proportional
57- error = valPot - valIn ;
56+ error = valRead - valTarget ;
5857 motorPWM = ((kp * error) / 100 ) + mp;
5958 // run motor
6059 analogWrite (wireMT_2, motorPWM);
0 commit comments