PID in MMBasic


Author Message
PhenixRising
Guru

Joined: 07/11/2023
Location: United Kingdom
Posts: 1893
Posted: 12:58pm 17 Sep 2024      

Pete,

When someone recommended being very specific when asking a question of ChatGPT, I asked it for Galil Motion Control's notch filter in Basic code.

Apparently, it can be used if one encounters a resonant frequency on a machine axis that the PID can't eliminate.
Never experienced the problem, myself so I can't vouch for its efficacy.


' BASIC-style pseudocode for a notch filter
' Initialize parameters
center_freq = 50         ' Center frequency in Hz (f_0)
sampling_rate = 1000      ' Sampling rate in Hz
bandwidth = 5             ' Bandwidth in Hz
attenuation = -20         ' Attenuation in dB

' Derived constants
omega_0 = 2 * PI * center_freq / sampling_rate    ' Digital radian frequency
bw = bandwidth / sampling_rate                    ' Bandwidth in terms of the sampling rate
d = -attenuation / 20                             ' Attenuation factor
alpha = sin(omega_0) / (2 * bw)                   ' Filter sharpness

' Filter coefficients
b0 =  1
b1 = -2 * cos(omega_0)
b2 =  1
a0 =  1 + alpha
a1 = -2 * cos(omega_0)
a2 =  1 - alpha

' Normalize coefficients
b0 = b0 / a0
b1 = b1 / a0
b2 = b2 / a0
a1 = a1 / a0
a2 = a2 / a0

' Variables for storing past input/output values
x_1 = 0
x_2 = 0
y_1 = 0
y_2 = 0

'Main loop (input is the signal you want to filter)
DO WHILE (true)

   'Assume input_signal is the current sample of the input signal
   input_signal = GET_INPUT()  ' Get input signal value
   
   'Apply the notch filter difference equation
   output_signal = b0 * input_signal + b1 * x_1 + b2 * x_2 - a1 * y_1 - a2 * y_2
       
   'Update past values
   x_2 = x_1
   x_1 = input_signal
   y_2 = y_1
   y_1 = output_signal
   
   print input_signal
   print output_signal
   'Output the filtered signal
   SEND_OUTPUT(output_signal)
   
LOOP