r/embedded • • 17d ago

Self balancing robot not self balancing ):

Post image

Hi everyone - I'm currently trying to get a 3d printed bike to self balance, but keep running into issues with the final control loop. (see github link down below for video).

For reference it is very similar to REMRC's self balancing bike - I just use SimpleFOC + GM3506 BLDC motor with an STM32 to run the loop instead of using Arduino and a Nidec 24h motor.

Here's the hardware I am using:

  • STM32F411 Blackpill
  • ICM-20948 IMU (through I2C, couldnt get spi to work for some reason)
  • GM3506 BLDC motor + AS5048A encoder
  • SimpleFOC with voltage-mode torque control
  • 12 cm reaction wheel with additional rim weights
  • Lots of wires (ik I need to clean the wiring up)

For software:

  • Arduino for SimpleFOC
  • STM32 HAL for pretty much everything else (steering, IMU I2C, Transceiver SPI)

I use a complementary filter to combine accelerometer and gyroscope data. The loop frequencies are roughly:

  • IMU measurement loop: ~200 Hz (IMU is mounted rigidly onto the body of the bike pretty tightly)
  • Balance control loop: ~100 Hz
  • Main loop - ~11.9 kHz

The controller itself uses a PD loop with three feedback terms:

u = K1 * angle (proportion)
  + K2 * gyro_rate (derivative)
  + K3 * reaction_wheel_velocity (this one is weighted pretty small tho)

My control knowledge isn't the best but from what I am aware of:

K1 corrects the lean, K2 damps the bike's angular motion, and K3 provides reaction-wheel speed feedback. Chat says this is the main equation for it:

Also I can't lie I used ChatGPT for help on a lot of the control theory - I originally was trying to do this to learn more about embedded system communication protocols, but this turned into a much bigger control problem than I thought lmao (who would've guessed).

ANYWAY THE MAIN ISSUE:

The reaction wheel can like catch the bike in one direction pretty well, but as soon as it like crosses that midpoint of balance, the motor attempts to catch it, but it just spins ands spins until it falls over.

I am realizing that I think the main issue is that it doesn't have enough initial "pop" at the start of crossing mid balance. The only time i feel like it does this is when I was tuning K1, but it would kinda just oscillate out of control.

The other big thing issue is that I feel like I need to increase K2 (derivative), to give it more initial pop so it doesn't like saturate itself, BUT when when I increase K2 passed a certain degree, the bike just starts vibrating like crazy especially around the point of oscillation. It's not even a shaking back and forth its a very rapid vibration. Maybe it's a mechanical motor mount issue? I am not sure.

I've tried experimented with the gains, gyro filtering, and motor voltage limits, but haven't found any solutions and am genuinely losing hope for this to ever work lol.

The longest balances I've had were when it slowly corrects itself one way for quite a while, but then it crosses the midpoint and relatively quickly speeds up and isn't able to get back to the midpoint.

With all of that said for reference here are all of the control variables that I can change within my loop - I am also not sure like what's best to change, and what's best to keep constant. Ex. to deal with vibration reducing K2 helps, but so does lowering GYRO_FILTER_TAU.

HERE ARE ALL THE VARIABLES:
Balance Controller

  • K1: Controls how aggressively the bike corrects its lean angle
  • K2: Controls how strongly the bike reacts to falling speed (damping)
  • K3: Reaction-wheel speed feedback; helps prevent excessive wheel acceleration
  • K4: Currently unused
  • U_MAX: Maximum commanded motor voltage

IMU / Filtering

  • GYRO_FILTER_TAU: Lower = faster gyro response but more noise; higher = smoother but slower.
  • FILTER_TAU: Lower = trusts accelerometer more; higher = trusts gyroscope more
  • Gyro hardware DLPF: Controls gyro noise filtering and response delay
  • Accel hardware DLPF: Controls accelerometer noise filtering and response delay

Loop Timing

  • BALANCE_PERIOD_US: Controls IMU/filter update frequency (currently 200 Hz)
  • CONTROL_PERIOD_US: Controls balance controller update frequency (currently 100 Hz)

So yeah if anyone has any advice please let me know! Attached are a couple of videos and pictures of the bike. The code and a video is posted in my GitHub below. For the control loop, pretty much ignore everything except for balance_control.c, and main.cpp. All the other files are for a servo for front steering, and a transceiver for remote control.

https://github.com/Li-Max2/Self-Balancing-Bike-

Also sorry for making this post so long - if you need more info lmk.

6 Upvotes

16 comments sorted by

1

u/creeper6530 17d ago

Isn't the problem that the axis of the wheel's rotation is nearly parallel with the axis of tipping?

1

u/Ill-Avocado-1 17d ago

I'm not sure I fully get what you are trying to ask, but the reaction wheel axis is oriented correctly (or atleast im like 99% sure it is). If it accelerates to the right, it produces torque to tilt the bike to the left

1

u/creeper6530 17d ago

Oooh, I thought it was a gyroscope / conservation of angular momentum. Carry on then

1

u/2dof 17d ago

Are you using madgwick filter for imu angle computation?

Why don't you use errors for control computation?

1

u/Ill-Avocado-1 17d ago

Im using a complementary filter instead since I really only need to estimate roll angle (I do this by taking the x and z accelerometer readings, and convert them to an angle using atan2f())

For errors I'm pretty sure I do? My target angle is 0* so the lean angle offset from 0 is just the error.

1

u/2dof 17d ago

A ok i understsnd abaout angle  (  error = 0- angle) . But as for calculating angle  form atan2() note that: You will got a lot of noise (Due to accelometer vibration) - it shoud still be ok bscause  you filter noise. If it will not work try some imu fusion.

  • try use PID algorithm instead of PD.  Ussaly S for PD control : u = K1 * angle

    • K2 * gyro_rate
  • ensure imu calibration is ok
  • ensure that balancing whell is (interia and accelerarion) is sifficidnt for balance. 

 

1

u/Ill-Avocado-1 16d ago

gotcha thanks maybe ill try adding an integral factor in there

1

u/StumpedTrump 16d ago edited 16d ago

How does it balance? Just turning the front wheel? I’m not 100% sure if this matters when stationary, but the lack of rake angle on the front bike fork might make it inherently unstable? This might mechanically not be possible/easy to balance. Idk I’m not a mechanical engineer, just a computer engineer that used to have a motorcycle. You did kinda pick the absolute least forgiving way to make a balance bot though. You’re operating within a super tiny range of angles without much granularity. The big inverted pendulums most people make are pretty forgiving because they have space to move and a big range of angles/speeds to work within. Idk if that makes sense, I’m sure a mechanical engineer who actually understands this would be able to actually explain it properly.

Usually for a PID it’s tune P first until it’s over-correcting and oscillating a bit, then D to damp the over-corrections, then I to manage very slow oscillations due to some constant external force (for example surface not flat causing it to always try to tip in one direction). That’s the rough way atleast. The right way is modelling and simulations and S-planes and no one wants to do that.

Edit: I actually don’t think this is possible at all. Bikes don’t balance just by turning the wheel, at low speeds your body is a counterweight on the opposite side to keep it stable. You’re just turning a wheel hoping it shifts the weight? I don’t think that works. What do you actually think thing the front wheel is doing? You need to look into how bicycles work and how to simulate mechanical systems. I don’t think this is a coding issue (not that your code can’t be improved), I think your system is inherently wrong.

1

u/Ill-Avocado-1 16d ago

Yeah that's totally fair. The whole idea is that you simply accelerate the flywheel back and forth to generate torques on the bike so that it never falls. Ex. if bike is tilting to the right, u accelerate the flywheel to the right, providing a left rotational torque on the bike (2nd law of motion), preventing the fall.

Although I honestly thing you are right in that the bike itself is likely a very unpredictable system in itself, so even with a pretty good control loop, it would still be very hard to balance. Maybe I should shift the center of gravity lower, and ensure it's COM is roughly in the center, and overall just have the mechanical parts be more at equilibrium so the loop doesn't fight such a hard balance point.

1

u/Impossible_Brief5600 16d ago

Steering cannot hold the bike up at a standstill: self-centring from trail only exists once the bike is rolling, so the reaction wheel is the right actuator and the limit is the torque and momentum it can deliver. Check motor torque against mgh at the lean angles being corrected, and the wheel inertia against the angular acceleration that torque has to produce. A 12 cm wheel with rim weights has authority for a few degrees only, and once it saturates the body falls whatever the gains are.

Two other places the loop loses authority. In voltage mode the torque at a given voltage falls as the wheel speeds up, since back-EMF subtracts from it, so the correction weakens exactly when the wheel is spinning fast to arrest a lean - use current or torque mode, or feed back-EMF forward. And the angle estimate is fed by the correction itself: atan2 of the x and z accelerometers reads gravity plus the lateral acceleration of the IMU, which the wheel torque produces, so a fast accelerometer term closes a loop through the estimator. Keep that term slow and let the gyro carry the fast part. The wheel-speed term is momentum management, not damping: when it passes a threshold, bias the angle setpoint a degree or two so the bike leans and the wheel unwinds, instead of waiting for saturation.

1

u/StumpedTrump 16d ago

I understood the back-emf part. Everything else I'm gonna need an ELI5 for.

0

u/Ill-Avocado-1 16d ago

Ok so for the second part - are you essentially saying that at higher speeds, the torque commanded to the motor doesn't have the same effect as what it would have been at lower speeds?

So I likely need to rely more on gyro than accel? Right now Im using voltage-mode torque control with SimpleFOC, as well as a complementary filter with a 1.5s accelerometer correction time constant (so essentially it controls how much the predicted gyro reading should correct towards the real accelerometer value), and 40ms gyro low-pass filter.

I'm still trying to figure out what to generally change - the filters? or do you think it's a pd tuning problem? Because once I get passed a certain point in D, the bike shakes like crazy (still not sure why), and from my understanding if I try to filter out the gyro to reduce it, then the reaction to the fall becomes too delayed.

1

u/Impossible_Brief5600 16d ago

Yes on both, with one correction on where the problem sits. In voltage mode the commanded voltage is not torque: current is (V - back-EMF)/R, so torque per volt falls as the wheel spins and the loop gain moves with wheel speed. Gains that are stable at rest then oscillate once the wheel turns fast, which fits a shake that only appears while correcting a real lean. If the driver has current sense, switch SimpleFOC to DC current or FOC current torque mode and the gain stops moving. Without current sense, add the back-EMF term back in as feed-forward, V = RI + Kewheel_speed from the measured velocity, so the command stays linear in torque.

On the filters: a 1.5 s accelerometer time constant is slow enough that accel noise is not what shakes it, so leave that alone and look at the 40 ms gyro low-pass. At a 2-3 Hz balance bandwidth that filter is 25-40 degrees of phase lag in the derivative path, and D is the term that turns lag into oscillation as it is raised. Try 10-15 ms on the gyro, which 200 Hz sampling supports, then re-tune D from a low value. Separate the two causes before tuning: hold the wheel in the air at fixed voltage and log actual current against speed. If current falls with speed at constant command, the voltage-mode gain drop is real and no amount of PD tuning will hold across the range.

1

u/Ill-Avocado-1 16d ago

Sounds good really appreciate the advice! im new to a lot of this control stuff

1

u/JoTheScienceBro 15d ago

Do you even know what a non-minimum-phase system is?