Skip to content

Instantly share code, notes, and snippets.

@basicxman
Created March 7, 2011 03:46
Show Gist options
  • Save basicxman/858038 to your computer and use it in GitHub Desktop.
Save basicxman/858038 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# PID Simulation
# Andrew Horsman
# 01/19/2011
# Notes:
# Arm range of motion should be a 90 degree arc, 33% of the potentiometer's range of
# motion.
class PID
def GetCurrentPosition
return @current_arm_position
end
def GetSetpoint
@direction_multiplier *= -1 if @setpoint > 66 || @setpoint < 33
@setpoint += @direction_multiplier * 1
end
def CalculateMotorOutput
if @result > 1
return 1
elsif @result < -1
return -1
else
return @result
end
end
def CalculateArmMovement
return @motor_output * 3
end
def SetMotor
temp = 0
temp += @Kp * @current_error
temp += @Ki * @total_error
temp += @Kd * (@current_error - @previous_error)
@result = temp
@motor_output = CalculateMotorOutput()
@current_arm_position += CalculateArmMovement()
end
def WriteFileBegin
File.open(@filename, "w") do |file|
file.puts "Time,Current Position,Setpoint,Multiplier,Previous Error,Error,Total Error,Result,Motor Output"
end
end
def WriteFileLoop
File.open(@filename, "a") do |file|
file.print @current_time.to_s + ","
file.print @current_arm_position.to_s + ","
file.print @setpoint.to_s + ","
file.print @direction_multiplier.to_s + ","
file.print @previous_error.to_s + ","
file.print @current_error.to_s + ","
file.print @total_error.to_s + ","
file.print @result.to_s + ","
file.print @motor_output.to_s
file.puts
end
end
def initialize
@Kp = ARGV[0].to_f
@Ki = ARGV[1].to_f
@Kd = ARGV[2].to_f
puts "#{@Kp} #{@Ki} #{@Kd}"
@period = 60
@current_time = 0
@current_arm_position = 33
@direction_multiplier = 1
@setpoint = 33
@previous_error = 0
@current_error = 0
@total_error = 0
@result = 0
@motor_output = 0
@filename = "simulation#{Time.now.to_i.to_s}_#{@Kp}_#{@Ki}_#{@Kd}.csv"
WriteFileBegin()
1.upto(400) do |loop|
GetSetpoint()
@current_error = @setpoint - GetCurrentPosition()
@total_error += @current_error
WriteFileLoop()
SetMotor()
@previous_error = @current_error
@current_time += @period
end
end
end
test = PID.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment