There are basically two approaches to this problem: You can solve it mechanically or through sensors/programming, or some combination of both.
jsotola's response offers several good mechanical approaches - clamping to the beam, lowering the center of gravity below the beam, etc. Exploit loopholes if you can; does the robot have to balance on top of the beam, or can it hang from underneath? But depending on the situation, purely mechanical options such as these might not be viable. Consider a Segway, or the Cubli in jsotola's answer. Neither of these have purely mechanical solutions to stay upright and balanced. How do they do it?
The answer is something called a PID Controller. For a balancing robot it basically works like this:
- The balancing robot gets a sensor reading from a gyroscope/accelerometer sensor to "feel" if it is falling.
- Based on how much the robot has tilted and how quickly it is falling, the PID formula figures out how forcefully the robot should respond. If the robot doesn't respond quickly enough it will fall, but it also can't respond too quickly or it may over-correct and fall the other way. By adjusting the constants in the PID formula you can make it output the proper amount of response for whatever amount of disturbance the robot detects.
- Using the value from the PID, the robot adjusts its motors to arrest any unwanted tilting/falling.
- The Cubli uses spinning weights to apply torque and balance on a corner.
- A Segway makes very small adjustments to its speed to keep the wheels under the center of mass.
- This process repeats tens or even hundreds of times per second so it can quickly respond to disturbances.
How does this apply to you?
It's impossible to say without knowing more about your specific situation, but I can think of a few scenarios in which you could employ this.
- How does the robot respond to a tilting beam? The robot could employ a heavy balance bar (like a tightrope walker), or simply put a heavy weight on a pivot (maybe its own battery pack). But how fast do you have to tilt the weight to stay balanced on the beam? Gyro/accelerometer sensor and a PID controller.
- How does the robot avoid driving off the side of the narrow beam? Use a sensor to detect how close it is to the edge of the beam, use a PID to adjust the steering to correct for it.