Example for analog input controlling velocity?

Hello all,

Im not the most talented coder and was wondering if someone could share their code.

Looking to use a potentiometer to control direction.

Thanks all

Hi Simracer,

You can get an analog value just by calling

int val = analogRead(pin);

Where pin is the number of the analog input pin you’re using. This will give you an integer value between 0 and 1024, depending on how you’ve configured your potentiometer. You can’t use this and current sensing at the same time, so if you’re trying to use SimpleFOC’s current sensing, don’t try to use the analog in at the same time.

Given your raw analog input value, a simple way to turn this into a speed is to map it in a linear way:

float speed = val / 1024.0f * max_speed;

Where max_speed is the maximum speed you want to support in radians per second. 1024.0f is writing the number 1024 as an explicitly declared float value.
Then you can set this speed to the motor:

motor.move(speed);

Putting this into the main loop, it’s probably a good idea not to do it each time through the loop. You don’t want to change the speed at a rate of several kHz, so slowing this down saves MCU cycles and prevents noise on the ADC from influencing the control loop each iteration:

float max_speed = 100.0f;
float speed = 0.0f;
long timestamp = millis();

void loop() {
   motor.loopFOC();
   motor.move(speed);
   long now = millis();
   if (now - 250 > timestamp) { // 4x per second
      timestamp = now;
      int val = analogRead(pin);
      speed = val / 1024.0f * max_speed;
   }
}

Something like that. I did’t compile this, I just typed it in this message so there may be some typos, but I hope the idea is clear.

That is great,

how would that look if I wanted 1.75v to be centered? to control 2 directions?

could i use something like this?

int mappedVal = map(analogRead(0),0,4096,-100,100);

1 Like

That looks good to me :+1:t2: