Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.9 kB
13
Indexable
Never
import time

class SelfBalancingSkateboard:
    def __init__(self, target_angle, kp, ki, kd):
        self.target_angle = target_angle
        self.kp = kp
        self.ki = ki
        self.kd = kd

        # Initial values
        self.current_angle = 0.0
        self.prev_error = 0.0
        self.integral = 0.0

    def read_sensor_data(self):
        # Simulated sensor data
        # You would replace this with actual sensor readings from accelerometer, gyroscope, and encoder
        accelerometer_data = 0.0  # Replace with actual accelerometer data
        gyroscope_data = 0.0  # Replace with actual gyroscope data
        encoder_data = 0.0  # Replace with actual encoder data
        return accelerometer_data, gyroscope_data, encoder_data

    def calculate_pid(self, error):
        # PID controller
        self.integral += error
        output = self.kp * error + self.ki * self.integral + self.kd * (error - self.prev_error)
        self.prev_error = error
        return output

    def adjust_motor_power(self, pid_output):
        # Simulated motor adjustment
        # You would replace this with actual motor control code
        motor_power = pid_output
        print(f"Adjusting motor power: {motor_power}")

    def detect_hill(self, accelerometer_data):
        # Simple hill detection based on accelerometer reading
        # You would need to calibrate these thresholds based on your setup
        hill_threshold = 0.2
        return accelerometer_data > hill_threshold

    def run(self):
        while True:
            # Read sensor data
            accelerometer_data, gyroscope_data, encoder_data = self.read_sensor_data()

            # Detect hill
            is_uphill = self.detect_hill(accelerometer_data)

            # Calculate the current tilt angle (replace this calculation with your actual sensor fusion logic)
            self.current_angle = 0.5 * accelerometer_data + 0.5 * gyroscope_data

            # Calculate the error
            error = self.target_angle - self.current_angle

            # Adjust motor power based on PID output
            pid_output = self.calculate_pid(error)

            # Simulate additional actions based on hill detection
            if is_uphill:
                print("Going uphill!")
                # Implement logic for going uphill
            else:
                print("Going downhill!")
                # Implement logic for going downhill

            # Adjust motor power based on PID output
            self.adjust_motor_power(pid_output)

            # Simulate a loop delay (replace this with your actual loop timing mechanism)
            time.sleep(0.01)

# Example usage:
target_angle = 0.0
kp = 1.0
ki = 0.1
kd = 0.01

skateboard = SelfBalancingSkateboard(target_angle, kp, ki, kd)
skateboard.run()
Leave a Comment