Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- """
- PI Controller for BeagleBone Black
- """
- __author__ = "Joe Moquin"
- __copyright__ = "Copyright 2015, Smart Green Power Node"
- __credits__="""
- Brett Beauregard:
- http://brettbeauregard.com/blog/2011/04/improving-the-beginners-pid-introduction/
- """
- __email__ = "sjmoquin@gmail.com"
- __maintainer__ = "Joe Moquin"
- __status__ = "Alpha"
- __version__ = "0.1"
- from time import clock
- #import Adafruit_BBIO.ADC as ADC
- #import Adafruit_BBIO.PWM as PWM
- import signal
- class PI_Controller:
- """
- Handles storage and calculation of PWM output from ADC input.
- Derivative values removed.
- """
- def __init__(self):
- self.ADC_input = 0.0
- self.errSum = 0.0
- self.kp = 0.0
- self.ki = 0.0
- self.lastTime = 0
- self.lastErr = 0.0
- self.PWM_output = 0.0
- self.sample_time = 1000
- self.setpoint = 0.0
- def Compute(self, ADC_input):
- #For reporting
- self.ADC_input = ADC_input
- #How long since we last calculated, in miliseconds
- now = int(1000*clock())
- dt = now - self.lastTime
- if dt >= self.sample_time
- """
- #boost_voltage = Black_Magic * ADC_input
- #Compute all the working error variables for PI
- error = self.setpoint - boost_voltage
- self.errSum = self.errSum + error
- #Compute PID Output
- boost_feedback_voltage = self.kp * error + self.ki * self.errSum
- PWM_output = Devil_Magic * boost_feedback_voltage
- #For reporting
- self.PWM_output = PWM_output
- """
- PWM_output = 90.0
- self.PWM_output
- #Remember some variables for next time
- #self.lastErr = error
- self.lastTime = now
- return PWM_output
- else:
- return self.PWM_output
- def print_handler(self, signum, frame):
- """
- Prints ADC input and PWM output upon USR1 signal from environment.
- In Terminal, type:
- ps -C python
- You'll get something like
- debian@beaglebone:~$ ps -C python
- PID TTY TIME CMD
- 2276 pts/0 00:04:16 python
- in reply.
- Type in the following, using the PID from the ps command:
- sudo kill -s USR1 2276
- In the PI_Controller.py's terminal, the following will print.
- """
- print "ADC_input:\t{}".format(self.ADC_input)
- print "boost_PWM:\t{}".format(self.PWM_output)
- def set_kp(self, kp):
- self.kp = kp
- def set_ki(self, ki):
- self.ki = ki * self.sample_time/1000
- def set_setpoint(self, setpoint):
- self.setpoint = setpoint
- if __name__ == "__main__":
- #ADC.setup()
- #PWM.start(channel, duty, freq=2000, polarity=0)
- #PWM.start("P9_14", 100, 10000, 0)
- pi = PI_Controller()
- signal.signal(signal.SIGUSR1, pi.print_handler)
- while True:
- #Pesky ADC read gives faulty values for first few reads.
- #So, just read a few times, saving the last read.
- ADC_input = 0.5
- #for __ in range(5):
- # ADC_input = ADC.read("P9_40")
- boost_PWM = pi.Compute(ADC_input)
- #PWM.set_frequency(boost_PWM)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement