So I have made a pid code that runs pid in c++ but there is a syntax error and it wont let me run. I have been to worlds before and I am going again and last time out autons didnt work and I have a pid code and i need help could some one help me fix it please!!! Here is the pid code.
#include "vex.h"
// 3 motors per side
vex::motor leftFront1 = vex::motor(vex::PORT1, vex::gearSetting::ratio18_1, false);
vex::motor leftMid2 = vex::motor(vex::PORT2, vex::gearSetting::ratio18_1, false);
vex::motor leftBack3 = vex::motor(vex::PORT3, vex::gearSetting::ratio18_1, false);
vex::motor rightFront1 = vex::motor(vex::PORT4, vex::gearSetting::ratio18_1, true);
vex::motor rightMid2 = vex::motor(vex::PORT5, vex::gearSetting::ratio18_1, true);
vex::motor rightBack3 = vex::motor(vex::PORT6, vex::gearSetting::ratio18_1, true);
vex::controller Controller1 = vex::controller(vex::controllerType::primary);
vex::competition Competition; // Competition instance
// PID constants
double kP = 0.5;
double kI = 0.001;
double kD = 0.1;
// Function to set all drivetrain motors
void setDriveSpeed(double leftSpeed, double rightSpeed) {
leftFront1.spin(vex::directionType::fwd, leftSpeed, vex::velocityUnits::rpm);
leftMid2.spin(vex::directionType::fwd, leftSpeed, vex::velocityUnits::rpm);
leftBack3.spin(vex::directionType::fwd, leftSpeed, vex::velocityUnits::rpm);
rightFront1.spin(vex::directionType::fwd, rightSpeed, vex::velocityUnits::rpm);
rightMid2.spin(vex::directionType::fwd, rightSpeed, vex::velocityUnits::rpm);
rightBack3.spin(vex::directionType::fwd, rightSpeed, vex::velocityUnits::rpm);
}
// PID control function for speed
void drivePIDSpeed(double targetSpeed, double duration) {
double error, lastError = 0, totalError = 0;
double power;
double currentSpeed = 0;
// Timer to stop after duration
vex::timer driveTimer;
driveTimer.reset();
while (driveTimer.time(vex::timeUnits::sec) < duration) { // Run for set time
// Get current speed (average of left & right motors)
currentSpeed = (leftFront1.velocity(vex::velocityUnits::rpm) + rightFront1.velocity(vex::velocityUnits::rpm)) / 2.0;
error = targetSpeed - currentSpeed;
totalError += error; // Integral
double derivative = error - lastError; // Derivative
power = (kP * error) + (kI * totalError) + (kD * derivative);
setDriveSpeed(power, power); // Adjust speed using PID
lastError = error;
vex::wait(20, vex::timeUnits::msec); // Small delay to prevent CPU overload
}
setDriveSpeed(0, 0); // Stop motors after time ends
}
// Autonomous function
void autonomous() {
drivePIDSpeed(100, 3); // Drive at 100 RPM for 3 seconds
}
// Driver control function
void userControl() {
while (true) {
// Get joystick values
double forwardPower = Controller1.Axis3.position(); // Left joystick Y-axis
double turnPower = Controller1.Axis1.position(); // Right joystick X-axis
// Convert joystick input to motor speed (RPM)
double maxRPM = 200; // Adjust if needed (200 RPM max for motors)
double leftSpeed = (forwardPower + turnPower) * maxRPM / 100.0;
double rightSpeed = (forwardPower - turnPower) * maxRPM / 100.0;
setDriveSpeed(leftSpeed, rightSpeed);
vex::wait(20, vex::timeUnits::msec); // Prevent excessive CPU usage
}
}
// Main function
int main() {
// No need for codeInit() here if you're using VEXcode, as the VEX library handles initialization.
// Attach autonomous and driver control functions
Competition.autonomous(autonomous);
Competition.drivercontrol(userControl);
while (true) {
vex::wait(100, vex::timeUnits::msec); // Prevents CPU overload
}
return 0;
}
the syntax error is between lines 3 and 4.
Thanks you
post the error you are seeing, it compiled ok for me.
2 Likes
it says a project run time has occurred. Please check error panel for more details
you can’t use C++ code in a Python project.
1 Like
OH thank you so much i did not realise that.
import vex # Assuming VEX library
# Define motors (replace with your actual motor ports)
left_front1 = vex.Motor(vex.Ports.PORT1, vex.GearSetting.RATIO18_1, False)
right_front1 = vex.Motor(vex.Ports.PORT6, vex.GearSetting.RATIO18_1, True) # Reversed for proper forward motion
# PID gains (tune these values)
kP_drive = 1.0
kI_drive = 0.01
kD_drive = 0.1
kP_turn = 1.5
kI_turn = 0.02
kD_turn = 0.2
def set_drive_speed(left_power, right_power):
left_front1.spin(vex.DirectionType.FWD, left_power, vex.VelocityUnits.PERCENT)
right_front1.spin(vex.DirectionType.FWD, right_power, vex.VelocityUnits.PERCENT)
def drive_pid_distance(target_distance, duration):
error = 0
last_error = 0
total_error = 0
power = 0
current_distance = 0
drive_timer = vex.Timer()
drive_timer.reset()
# Assuming encoders are attached to motors and provide distance in cm
left_front1.reset_position()
right_front1.reset_position()
while drive_timer.time(vex.TimeUnits.SECONDS) < duration:
current_distance = (left_front1.position(vex.RotationUnits.CM) + right_front1.position(vex.RotationUnits.CM)) / 2.0
error = target_distance - current_distance
total_error += error
derivative = error - last_error
power = (kP_drive * error) + (kI_drive * total_error) + (kD_drive * derivative)
set_drive_speed(power, power)
last_error = error
vex.wait(20, vex.TimeUnits.MSEC)
set_drive_speed(0, 0)
def turn_pid_angle(target_angle, duration):
error = 0
last_error = 0
total_error = 0
power = 0
current_angle = 0
turn_timer = vex.Timer()
turn_timer.reset()
# Assuming gyro sensor is used for angle measurement
gyro = vex.Gyro(vex.Ports.PORT9) # Replace with your gyro port
gyro.calibrate()
vex.wait(2000, vex.TimeUnits.MSEC) # Allow gyro to calibrate
while turn_timer.time(vex.TimeUnits.SECONDS) < duration:
current_angle = gyro.heading()
error = target_angle - current_angle
if error > 180:
error -= 360
elif error < -180:
error += 360 #shortest turn.
total_error += error
derivative = error - last_error
power = (kP_turn * error) + (kI_turn * total_error) + (kD_turn * derivative)
set_drive_speed(-power, power) # Opposite motor directions for turning
last_error = error
vex.wait(20, vex.TimeUnits.MSEC)
set_drive_speed(0, 0)
def main():
# Drive forward for 50 cm in 3 seconds
drive_pid_distance(50, 3)
vex.wait(500, vex.TimeUnits.MSEC) # small pause
# Turn 90 degrees clockwise in 2 seconds
turn_pid_angle(90, 2)
vex.wait(500, vex.TimeUnits.MSEC) # small pause
# Drive forward again for 30 cm in 2 seconds
drive_pid_distance(30, 2)
vex.wait(500, vex.TimeUnits.MSEC)
if __name__ == "__main__":
main()
can some one see what wrong with this code its supposed to driveforward and turn using pid
Are you still using VexCode? If you are pushing into PID, I would probably suggest switching to Visual Studio Code and using the VEX Extension if thats the case, that way you have access to the different pages.
#region VEXcode Generated Robot Configuration
import math
import random
from vexcode_vrc import *
from vexcode_vrc.events import get_Task_func
# Brain should be defined by default
brain=Brain()
arm_motor = Motor("ArmMotor", 3)
pusher_motor = Motor("PusherMotor", 8)
front_distance = Distance("FrontDistance", 6)
distance = front_distance
front_optical = Optical("FrontOptical", 5)
gps = GPS("GPS", 17)
drivetrain = Drivetrain("drivetrain", 0)
pusher_rotation = Rotation("PusherRotation", 19)
ai_vision = AiVision("aiVision", 7)
# 'Enum' class for AI Vision GameElements
class GameElements:
MOBILE_GOAL = 0
RED_RING = 1
BLUE_RING = 2
#endregion VEXcode Generated Robot Configuration
# PID driving functions (using VEXcode VR's Drivetrain and GPS)
kP_drive = 1.0
kI_drive = 0.01
kD_drive = 0.1
kP_turn = 1.5
kI_turn = 0.02
kD_turn = 0.2
def drive_pid_distance(target_distance):
error = 0
last_error = 0
total_error = 0
power = 0
current_distance = 0
drivetrain.set_drive_velocity(0, PERCENT)
drivetrain.set_turn_velocity(0, PERCENT)
drivetrain.drive_for(FORWARD, 0, MM)
while True:
current_distance = drivetrain.drive_distance(MM) / 10
error = target_distance - current_distance
total_error += error
derivative = error - last_error
power = (kP_drive * error) + (kI_drive * total_error) + (kD_drive * derivative)
drivetrain.set_drive_velocity(power, PERCENT)
drivetrain.drive(FORWARD)
if abs(error) < 1:
drivetrain.stop()
break
last_error = error
wait(20, MSEC)
drivetrain.stop()
def turn_pid_angle(target_angle):
error = 0
last_error = 0
total_error = 0
power = 0
current_angle = 0
gps.calibrate()
wait(2, SECONDS)
while True:
current_angle = gps.heading(DEGREES)
error = target_angle - current_angle
if error > 180:
error -= 360
elif error < -180:
error += 360
total_error += error
derivative = error - last_error
power = (kP_turn * error) + (kI_turn * total_error) + (kD_turn * derivative)
drivetrain.set_turn_velocity(power, PERCENT)
# Ensure a minimum turn velocity to avoid issues
if abs(power) > 2:
drivetrain.turn()
else:
drivetrain.stop()
if abs(error) < 1:
break
last_error = error
wait(20, MSEC)
drivetrain.stop()
# Main Function
def main():
drive_pid_distance(50)
wait(500, MSEC)
turn_pid_angle(90)
wait(500, MSEC)
# VR threads — Do not delete
vr_thread(main)
here is my code in python all it does is moves forward and turns 90 degrees but i am having aturibue problem and its on line 50
edit: code tags added by mods, please remember to use them
Do not post all your code if you want help with an issue, its lazy. Single out your problem first, then formulate an intelligent question.