Go Down

Topic: analog to PWM (for DC motor control) {need advice}; (Read 1 time) previous topic - next topic

robwar

Hello.
    This is a code I came up with to control a simple dc motor with an ps2 joystick potentiomiter. It works ok, but i would like to know how flawed it is or if there is a better code to use.
       Thanks, Rob.

Code: [Select]

const int analogInPin = A0;
const int motorFwdPin = 9;
const int motorRevPin = 10;

int sensorValue = 0;
int motorFwd = 0;
int motorRev = 0;
int motorOff = 0;

void setup(){}

void loop(){
 
sensorValue = analogRead(analogInPin);
motorFwd = map(sensorValue, 550, 0, 0, 255);
motorRev = map(sensorValue, 480, 1023, 0, 255);
motorOff = map(sensorValue, 480, 550, 0, 0);
   if (sensorValue <= 480)
     {analogWrite(motorFwdPin, motorFwd);}
   else if (sensorValue >= 550)
     {analogWrite(motorRevPin, motorRev);} 
   else {(sensorValue > 485 && sensorValue < 545);
     {analogWrite (motorRevPin, motorOff);
     analogWrite (motorFwdPin, motorOff);}}
    }     


Go Up