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;
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?