logo
mbot2 line follower code
This is the
OLD website...


NEW website
available
Top forecasts
Forecast maps
Click-Map forecast
Username:

Password:


Register! (free) Why?

Mbot2 Line Follower Code 💯 Trusted

""" MBot2 Line Follower Feature =========================== Uses the 5-channel line follower sensor to follow a black line on a white surface. Supports PID control for smooth tracking, speed adjustment, and emergency stop. """ import mbot2 import time import sys

choice = input("\nSelect option: ").strip() mbot2 line follower code

def pid_control(self, error, dt): """ PID control algorithm Returns: turn speed (-MAX_TURN to +MAX_TURN) """ # Proportional term p_term = self.KP * error # Integral term (with anti-windup) self.integral += error * dt # Limit integral to prevent excessive accumulation integral_limit = 100 self.integral = max(-integral_limit, min(integral_limit, self.integral)) i_term = self.KI * self.integral # Derivative term derivative = (error - self.previous_error) / dt if dt > 0 else 0 d_term = self.KD * derivative # Calculate total turn speed turn_speed = p_term + i_term + d_term # Limit turn speed turn_speed = max(-self.MAX_TURN, min(self.MAX_TURN, turn_speed)) # Store values for next iteration self.previous_error = error return turn_speed 0.0 = center

def calculate_line_position(self, sensors): """ Calculate the line position as a weighted average Returns: position from -2.0 (far left) to +2.0 (far right), 0.0 = center, None if no line detected """ weighted_sum = 0 total_weight = 0 for i, reading in enumerate(sensors): if reading: # Line detected # Convert index to position: 0=-2, 1=-1, 2=0, 3=1, 4=2 position = i - 2 weighted_sum += position total_weight += 1 if total_weight > 0: return weighted_sum / total_weight else: return None # No line detected mbot2 line follower code