export class PidController { private sumError : number ; private lastError : number ; private lastTime : number ; private dT : number ; private iMax : number ; private currentValue : number ; constructor ( private kP , private kI , private kD , private target ) { this . kP = kP || 1 ; this . kI = kI || 0 ; this . kD = kD || 0 ; this . target = target ; this . dT = 0 ; this . iMax = 0 ; this . sumError = 0 ; this . lastError = 0 ; this . lastTime = 0 ; this . target = 0 ; } public update ( currentValue ) { this . currentValue = currentValue ; let dt = this . dT ; if ( ! dt ) { const currentTime = Date . now ( ) ; if ( this . lastTime === 0 ) { dt = 0 ; } else { dt = ( currentTime - this . lastTime ) / 1000 ; } this . lastTime = currentTime ; } if ( typeof dt !== 'number' || dt === 0 ) { dt = 1 ; } const error = ( this . target - this . currentValue ) ; this . sumError = this . sumError + error * dt ; if ( this . iMax > 0 && Math . abs ( this . sumError ) > this . iMax ) { const sumSign = ( this . sumError > 0 ) ? 1 : - 1 ; this . sumError = sumSign * this . iMax ; } const dError = ( error - this . lastError ) / dt ; this . lastError = error ; return ( this . kP * error ) + ( this . kI * this . sumError ) + ( this . kD * dError ) ; } public reset ( ) { this . sumError = 0 ; this . lastError = 0 ; this . lastTime = 0 ; } }