Arduino (https://www.amazon.de/gp/product/B01D0OI90U/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&th=1)
In this code I am sending a pulse to a motor driver (lines 8-11). The time between those pulses is determined by line 11 with the variable V
. In order to make the motor move to a certain position I am looping the pulses L
amount of times, and then (in lines 13-17) I am reversing the direction so it returns to origin. So L
is the length the motor drives, while V
is the speed at which it does that.
However, V
(and soon L
) is a value I read from a potentiometer (line 6) - which I should move into the loop so I get instantaneous changing of the speed. Instead of having to wait for it to complete the loop each time before it changes. But when I do that, it doesn't reach the same speed anymore. Instead of having 2.6us (us: microseconds) between pulses. it feels more like 200us - while if its outside the loop it can reach much higher speeds - but I dont know why!
Thanks in advance for all answers/time investments:
I tried moving the code block (the code in line 6) into the loop and it slowed the max speed tremendously.
I then moved the code block both to void setup
, where it just didn't work at all and then before void setup - where it didn't adjust to the speed anymore and just ran at around 222us (us: microseconds).
Since it clearly is capable of reaching the speeds, I think it is somehow connected to some aspect of the code/language that I am unfamiliar with - and since I am a, noob that's basically all of it.
You are effectively blocking the analogRead every time because you are running the entire loop afterwards which also contains a bunch of delays.
Your code reads something like this
decide how far to go (800 * 4) = 3600
check how fast = V
3600 times do the following(
)end of 3600 times repeat
This means that on every move you will at least have 52.6 micros delay (as a minimum and depends on the
V
value).Instead of doing the loop (inside
loop()
) every time you can simply keep the motor running and just change the direction when needed:This will keep running the motor back and forward for the desired distance, if you want to only run it once (for example on a button press) then you can just include another variable that when true will enable the code and when the motor get's back to 0 position will reset itself to false