Optical lens focal length adjusting method based on STM32 and PID algorithm
By combining an STM32 microcontroller with an improved PID algorithm, the accuracy and adaptability issues in traditional optical lens focal length adjustment methods are solved, achieving efficient focal length adjustment and improving response speed and positioning accuracy.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- GUILIN UNIV OF TECH AT NANNING
- Filing Date
- 2026-03-31
- Publication Date
- 2026-06-23
AI Technical Summary
Traditional optical lens focal length adjustment methods suffer from low precision, slow response, and susceptibility to interference, especially in nonlinear mapping, temperature drift compensation, and suppression of integral saturation.
Using an STM32 microcontroller combined with an improved PID algorithm, high-precision mapping is achieved through table lookup and linear interpolation. Integral separation and anti-integral saturation mechanisms are introduced, and a multi-rate interrupt scheduling architecture and temperature compensation are adopted to construct cascade PID control for position and velocity loops.
It achieves fast, accurate, smooth, and stable automatic adjustment of the optical lens focal length, improving response speed, positioning accuracy, robustness, and adaptability.
Smart Images

Figure CN122260600A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of optical imaging and automatic control technology, and in particular to an optical lens focal length adjustment method based on STM32 and PID algorithm. Background Technology
[0002] In precision optical systems such as security monitoring, industrial vision inspection, and microscopic imaging, rapid, precise, and stable adjustment of lens focal length is crucial for achieving clear imaging and accurate target acquisition. Traditional focal length adjustment methods often employ open-loop stepper motors, controlling lens movement through preset pulse counts. This method cannot sense the actual physical position of the lens and is prone to focal length inaccuracies due to mechanical transmission errors, temperature drift, load variations, and other factors. Furthermore, it lacks dynamic optimization of the motion process, making it susceptible to shocks and vibrations, which can affect system lifespan and image quality.
[0003] While some existing technologies employ closed-loop control, most rely on complex dedicated controllers and high-cost position sensors, such as high-resolution encoders, resulting in high system complexity and cost. Although some solutions introduce PID control, they typically use a single PID loop with fixed parameters, making it difficult to simultaneously meet the requirements of fast response, high steady-state accuracy, and strong anti-interference capabilities. Traditional methods are particularly inadequate when dealing with problems such as nonlinear focal-position mapping, temperature drift compensation, and suppression of integral saturation. Summary of the Invention
[0004] This invention provides an optical lens focal length adjustment method based on STM32 and PID algorithm. Its main purpose is to solve the problems of low focal length adjustment accuracy, slow response and susceptibility to interference in traditional open-loop and simple closed-loop control, and to achieve high-performance servo control of optical lens focal length.
[0005] To achieve the above objectives, this invention provides an optical lens focal length adjustment method based on STM32 and PID algorithm, characterized in that: STM32 microcontroller unit; The motor drive module is electrically connected to the STM32 microcontroller unit; An optical lens assembly includes a zoom motor for adjusting the focal length and a focusing motor for assisting focusing, wherein the zoom motor and the focusing motor are driven by the motor drive module. The position sensing module is used to detect the position of the lens group of the optical lens assembly in real time and feed the position signal back to the STM32 microcontroller unit; The STM32 microcontroller unit is configured to execute the following control flow: S1: Receive target focal length value; S2: Based on the pre-stored focal length-position correspondence table, the target focal length value is converted into the corresponding motor target position code value using a lookup table and linear interpolation algorithm; S3: Obtain the real-time position feedback value from the position sensing module and calculate its position error with the target position encoding value; S4: An improved position loop PID control algorithm is used to process the position error. The improved PID algorithm includes integral separation and anti-integral saturation mechanism, and outputs speed control command. S5: Based on the speed control command and the real-time speed feedback value calculated by the position difference, a speed loop PID control algorithm is used to generate a motor drive command; S6: The motor drive module executes the motor drive command to control the movement of the zoom motor and the focus motor, and repeats steps S3 to S6 until the actual focal length reaches the target focal length.
[0006] Optionally, the table lookup and linear interpolation algorithm in step S2 specifically includes: In the focal length-position correspondence table, a binary search algorithm is used to determine the two reference points that are closest to the target focal length value; Based on the proportional relationship between the target focal length value and the focal lengths corresponding to the two reference points, the target position code value of the motor is calculated using a linear interpolation formula.
[0007] Optionally, the integral separation and anti-integral saturation mechanism in step S4 specifically includes: A first error threshold and a second error threshold are set, wherein the second error threshold is greater than the first error threshold; When the absolute value of the position error is less than the first error threshold, it is determined to be in the steady-state fine-tuning stage, and the PID integral term is cleared to avoid critical oscillation. When the absolute value of the position error is greater than or equal to the first error threshold and less than the second error threshold, it is determined to be in the normal adjustment stage, the PID integral accumulation function is enabled, and the integral accumulation value is limited to prevent integral saturation. When the absolute value of the position error is greater than or equal to the second error threshold, it is determined to be in the rapid adjustment stage. The PID integral term is cleared to zero and the integral function is disabled, and rapid proportional adjustment is performed first.
[0008] Understandably, in the PID control algorithm of steps S4 and S5, the proportional term, the processed integral term, the derivative term, and the control output are respectively represented as follows: Among them, U p [n] is the proportional term, U i [n] is the processed integral term, U d[n] is the differential term, U[n] is the control output value, and K p It is the proportional parameter in the PID gain parameters, K i K is the integral parameter in the PID gain parameters. d This is the differential parameter in the PID gain parameters, where n represents the index value of the current control cycle, e[n] is the position or velocity error value in the nth cycle, and e[n-1] is the position or velocity error value in the (n-1)th cycle. This represents the cumulative sum of errors, and k is the discrete-time index.
[0009] Optionally, the system further includes a temperature sensor, and the STM32 microcontroller unit is further configured as follows: Obtain the ambient temperature value collected by the temperature sensor; Based on the pre-stored temperature-compensation correspondence table, query the focal length compensation amount corresponding to the ambient temperature value; The focal length compensation is superimposed on the motor target position encoding value to correct focal length drift caused by temperature changes.
[0010] Optionally, the STM32 microcontroller unit employs a multi-rate interrupt scheduling architecture to execute control tasks, including: The first timer interrupt service routine is periodically triggered at a first frequency to perform analog-to-digital converter sampling, acquire the analog signal of the position sensing module, and update the real-time position feedback value and the real-time speed feedback value. The second timer interrupt service routine is periodically triggered at a second frequency lower than the first frequency to execute the speed loop PID control algorithm and update the motor drive command; The third timer interrupt service routine is periodically triggered at a third frequency lower than the second frequency to execute the position loop PID control algorithm and focus adjustment logic judgment. The main loop program is used to perform target focal length reception, focal length-position conversion, system status monitoring, and non-real-time communication tasks.
[0011] Optionally, the position sensing module is a linear potentiometer, whose sliding arm is mechanically coupled to the mirror assembly, converting the linear displacement of the mirror assembly into a change in resistance, and then outputting a voltage signal proportional to the position to the analog-to-digital converter interface of the STM32 microcontroller unit.
[0012] Optionally, the STM32 microcontroller unit is further configured to execute dual-threshold steady-state judgment logic, including: When the position error is less than a first preset threshold, the steady state counter is activated. If the position error is less than the more stringent second set threshold in multiple consecutive control cycles, it is determined that the focus adjustment is in place, and the control motor enters the position holding state. If the duration from the start of adjustment to the current moment exceeds the preset timeout threshold, the adjustment process is deemed abnormal, and a motor stop or fault alarm operation is executed.
[0013] To achieve the above objectives, the present invention also provides an STM32 readable storage medium storing at least one instruction, which is executed by an STM32 microcontroller to implement the optical lens focal length adjustment method based on STM32 and PID algorithm described above.
[0014] To address the problems described in the background section, this invention firstly achieves high-precision, fast, nonlinear mapping from the target focal length to the motor position code value by constructing and querying a pre-stored focal length-position relationship table, combined with binary search and linear interpolation algorithms, thus ensuring the accuracy of the control target from the source. Secondly, it introduces an integral separation and anti-saturation mechanism based on error magnitude into the position loop PID algorithm, dividing the control process into three stages: rapid adjustment, normal adjustment, and steady-state fine-tuning. Different integral strategies are adopted for each stage, effectively solving the overshoot and oscillation problems of traditional PID under startup, shutdown, and large disturbances, significantly improving dynamic performance and steady-state accuracy. Furthermore, through a multi-rate interrupt scheduling architecture, high-real-time data sampling, mid-frequency speed loop control, and low-frequency position loop calculation are processed in layers, rationally allocating the computing resources of the STM32 microcontroller and ensuring the real-time performance and stability of the control system. In addition, the system integrates temperature compensation and dual-threshold steady-state judgment logic, further enhancing environmental adaptability and control reliability. Ultimately, through cascaded PID control—namely, the position loop and the velocity loop—and the synergistic effect of the aforementioned integral separation and anti-saturation mechanism, rapid, precise, smooth, and stable automatic adjustment of the optical lens focal length is achieved. Therefore, this invention significantly improves the response speed, positioning accuracy, and overall robustness of optical lens focal length adjustment. Attached Figure Description
[0015] Figure 1 This is a flowchart of an optical lens focal length adjustment method based on STM32 and PID algorithm according to the present invention. Detailed Implementation
[0016] The technical solutions of the present invention will be clearly and completely described below with reference to the accompanying drawings of the embodiments of the present invention. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments.
[0017] This application provides a method for adjusting the focal length of an optical lens based on STM32 and a PID algorithm. The subject of this invention is an embedded electronic device, specifically an optical device control board equipped with an STM32 series microcontroller. The method is applicable to precision optical devices requiring automatic zoom functions, such as security surveillance cameras, industrial vision inspection equipment, microscopic imaging systems, and infrared imaging systems.
[0018] In this invention, the system includes: an STM32F407 microcontroller, a motor drive circuit, an optical lens assembly comprising a zoom motor and a focus motor, a potentiometer-type position sensor, a temperature sensor, and a communication interface. The STM32 microcontroller controls the motor drive circuit through multiple PWM outputs, acquires the position sensor voltage through an ADC interface, implements multi-task scheduling through timer interrupts, and communicates with a host computer through a UART interface.
[0019] Reference Figure 1 The diagram shown is a flowchart illustrating an optical lens focal length adjustment method based on STM32 and a PID algorithm according to an embodiment of the present invention. In this embodiment, the method is executed in an STM32 microcontroller according to the following steps: S1. Receive the target focal length command and initialize system parameters.
[0020] Understandably, the target focal length command can be received from the host computer via a serial port. After the system is powered on, the STM32 first reads the pre-stored parameter tables from the internal Flash, including the focal length-position correspondence table paraTable and the temperature compensation table TemCompenTable. The focal length-position correspondence table is a two-dimensional array, such as paraTable
[41]
[15] , where the second column stores the focal length value and the fourth column stores the corresponding position code value (LSB). In the initialization function main(), these tables are read into RAM through STMFLASH_Read_OneWord().
[0021] S2. Based on the pre-stored focal length-position correspondence table, the target focal length value is converted into the corresponding motor target position code value using a lookup table and linear interpolation algorithm.
[0022] It is clear that, due to the non-linear relationship between lens focal length and motor position, this invention employs a "table lookup + linear interpolation" method to achieve high-precision conversion. Specifically, this is executed by the function transTargetLsb(float refFocal). First, a binary search algorithm is used to locate the reference row index closest to the target focal length value in the pre-constructed focal length-position correspondence table. If the index value is less than or equal to zero, it indicates that the target focal length is less than or equal to the minimum focal length value in the table, and the position code value stored in the first row of the table is directly taken as the target position code value. If the index value is greater than forty, it indicates that the target focal length is greater than or equal to the maximum focal length value in the table, and the position code value stored in the fortieth row of the table is directly taken as the target position code value. If the index value is between zero and forty, further determination is made: if the focal length value recorded in the index row of the table is exactly equal to the target focal length value, the position code value corresponding to that row is directly taken; if the focal length value recorded in the index row of the table is greater than the target focal length value, linear interpolation is performed between the current index row and the previous row; if the focal length value recorded in the index row of the table is less than the target focal length value, linear interpolation is performed between the current index row and the next row. The specific steps of the linear interpolation are as follows: first, calculate the ratio of the change in position code to the change in focal length between two adjacent reference points to obtain the position code change rate corresponding to a unit change in focal length; then, based on this change rate, add the product of the difference between the target focal length value and the focal length value of the reference point multiplied by the change rate, with the position code value of the previous reference point as the reference, to finally obtain the accurate target position code value.
[0023] S3. Obtain the real-time position feedback value from the position sensing module and calculate its position error with the target position encoding value.
[0024] The real-time position feedback employs a layered interrupt design to achieve real-time data acquisition and control. High-resolution ADC sampling is implemented using STM32's Timer TIM2. The function AD7682_Read() reads the 16-bit ADC chip via the SPI interface, sampling four channels and performing moving average filtering. Timer TIM6 is used to execute an interrupt service routine when an update interrupt is triggered. Internally, a static counter is first incremented. When the counter reaches a preset threshold of five, indicating five interrupt cycles have elapsed, the counter is reset to zero, and the first set of control tasks is executed: first, the focus error control function is called, which uses dual-threshold judgment logic to intelligently adjust the focus motor; then, the brushless DC motor position loop PID calculation function is called to complete the position control loop calculation and output update. Regardless of whether the counter reaches the threshold, the second set of control tasks continues to execute in each TIM6 interrupt: when the zoom motor enable flag is valid, the zoom motor control output function is called to perform speed loop calculation and update the PWM drive signal; when the focus motor enable flag is valid, the focus motor control output function is called to achieve real-time closed-loop control of the focus motor. Through this nested scheduling mechanism, the first group of control tasks is executed at one-fifth of the frequency of the TIM6 timer interrupt, forming a low-frequency control layer; the second group of control tasks is executed at the full frequency of the TIM6 timer interrupt, forming a high-frequency control layer, thereby realizing hierarchical, time-division, and efficient scheduling of multi-motor collaborative control tasks in the optical lens system.
[0025] S4. An improved position loop PID control algorithm is used to process the position error. The improved PID algorithm includes integral separation and anti-integral saturation mechanism, and outputs speed control command.
[0026] The improved PID algorithm is implemented in the function PID_Calc(PID_TypeDef * pPID_Structure), and its key feature is the introduction of integral separation and anti-integral saturation mechanisms: First, the absolute value of the current control error is determined. If the absolute value of the error is less than a first preset threshold, for example, 10 units, the system is determined to be in the steady-state fine-tuning stage. At this time, the cumulative integral value is forcibly cleared to avoid system oscillation caused by the continuous integration of small errors near the target value. If the absolute value of the error is between the first preset threshold and the second preset threshold, which is defined by the integral separation threshold parameter in the structure, the system is determined to be in the normal adjustment stage. At this time, the integral function is enabled, and the current error is accumulated into the integral term to eliminate the steady-state error of the system. Simultaneously, anti-saturation limiting processing is implemented on the cumulative integral value. When it exceeds the maximum integral limit value defined in the structure, it is forcibly limited within the limit value, thereby preventing integral saturation caused by long-term error accumulation. If the absolute value of the error is greater than or equal to the second preset threshold, the system is determined to be in a rapid adjustment or startup phase. At this time, the integral cumulative value is cleared to zero and the integral function is paused, allowing the controller to prioritize the proportional term for rapid response under larger errors, thus avoiding adverse effects from the integral term during the rapid adjustment phase. Through this mechanism, this invention achieves an adaptive integral strategy for the PID controller within different error ranges, balancing the system's speed, stability, and anti-saturation capability. The position loop PID output serves as the setpoint for the speed loop, forming a cascade control structure. The PID calculation function is called to process the position loop controller. The input of this function is the setpoint stored in the position loop control structure and the feedback value from the position sensor; the output is the control quantity after proportional, integral, and derivative operations. Subsequently, the output control quantity calculated by the position loop is used as the setpoint for the speed loop controller, updating the corresponding field in the speed loop control structure. Next, the PID calculation function is called to process the speed loop controller. The input of this function is the aforementioned setpoint and the speed feedback value obtained through position differential or speed measurement devices; the output is the final control command. Finally, the control commands output from the speed loop are converted into corresponding pulse width modulation duty cycles and applied to the target motor through the motor drive interface, thereby achieving precise positioning of the motor and smooth speed control. Through this cascade structure, the inner speed loop responds quickly to speed commands and suppresses disturbances, while the outer position loop ensures the final positioning accuracy, forming a dual-loop collaborative control system.
[0027] S5. Based on the speed control command and the real-time speed feedback value calculated by the position difference, a speed loop PID control algorithm is used to generate a motor drive command.
[0028] The velocity feedback value is obtained in real time through the position difference calculation method: that is, the position encoded values obtained from two consecutive sampling periods are differentially calculated, and the difference is divided by the sampling time interval to obtain an approximate instantaneous velocity. Let the current sampling time be t. k The corresponding position code value is P k The previous sampling time t k-1 The position code is P k-1 The sampling period is T s The real-time speed feedback value is V. fb The calculation formula is as follows: The position code value is obtained by sampling the potentiometer voltage through the analog-to-digital converter. The differential calculation is completed synchronously in each sampling interrupt TIM2. The resulting speed value is stored in the speed feedback buffer for the control loop to read.
[0029] Furthermore, the speed error is calculated and preprocessed by reading the speed loop setpoint V. ref And compared with the real-time speed feedback value V obtained from the above steps. fb By subtracting the values, we obtain the speed error e. v =V ref -V fb Regarding the speed error e v Preprocessing: First, perform amplitude limiting; if |e v | Greater than the maximum permissible speed error threshold e v_max Then let e v =e v_max First, to prevent abnormal disturbances from causing sudden changes in the control quantity; second, to perform low-pass filtering on the error signal to suppress high-frequency measurement noise.
[0030] In detail, based on the speed error e v The size of |e| determines the integral separation and anti-saturation strategy; if |e| v | Less than the minimum error threshold ε 1, This indicates a steady-state fine-tuning phase approaching the target velocity, at which point the velocity integral term I... v Zero out to avoid slow crawling; if ε1 < |e v If |<ε2, where ε2 is the maximum error threshold, then it is judged as the normal adjustment stage, and the current speed error e is set to... v Added to the integral term I v =I v +e v and to I v To implement anti-saturation limiting, i.e., limiting to -I max and I max Between, I max This is the preset integral limit value; if |e v |>ε2, indicating a rapid adjustment phase, the integral term Iv The system is reset to zero and the integral accumulation is paused, allowing the controller to rely primarily on the proportional element for a rapid response when the speed error is large.
[0031] Furthermore, according to the aforementioned speed error e v Calculate the proportional term P v Integral term I out and differential term D v Proportional term P v =K p_v ×e v , where K p_v The speed loop proportionality coefficient; integral term I out =K i_v ×I v , where =K i_v The integral coefficients of the velocity loop; the differential term D v =K d_v ×(e v -e v_prev ) / T s , where e v_prev It is the speed error of the previous sampling period, K d_v For the velocity ring differential coefficients.
[0032] This invention employs intelligent state management to improve control accuracy. First, it determines whether the system meets the conditions for entering steady-state evaluation: when the absolute value of the difference between the current position and the target position is less than a preset sensitive error threshold, or when the control system has exceeded a preset adjustment time limit, the steady-state processing flow is triggered. If the conditions are met, the steady-state duration counter is further checked: if the cumulative value of the counter has reached or exceeded a preset number of stable cycles, such as 20 control cycles, the system is determined to be sufficiently stable. At this point, the currently used error threshold is switched to a more precise gear meshing threshold, and the motor control output is set to zero, allowing the system to enter a position-holding state, avoiding unnecessary micro-motion and energy consumption. If the steady-state duration counter has not yet reached the set value, the counter is incremented, and the PID control algorithm continues to be called to calculate the motor control output, enabling the system to perform fine-tuning within a small error range, while accumulating the duration of the stable state. This mechanism, through two-level threshold switching and continuous stable cycle counting, effectively distinguishes between the three states of the system: "approaching the target," "fine-tuning," and "completely locked," avoiding critical oscillations and ensuring a fast, smooth positioning process with no jitter in the final steady state.
[0033] The compensation value at the current temperature is obtained by looking up the TemCompenTable, and the target position or feedback position is corrected.
[0034] S6. The motor drive module executes the motor drive command to control the movement of the zoom motor and the focus motor, and repeats steps S3 to S6 until the actual focal length reaches the target focal length.
[0035] The STM32 main loop selects the operating mode based on the motorMode variable: In the system's main loop, the serial port data receiving and processing function is continuously called first to parse instructions from the host computer in real time and update the corresponding control parameters and status flags. Next, the current motor operating mode variable is checked: if the system is in automatic zoom mode, the focal length-position conversion function is called sequentially to calculate the target position code value for the zoom motor and the compensation motor, respectively, providing a setting benchmark for closed-loop control. Further, when the system enables the automatic zoom loop function and reaches the 50-millisecond task trigger flag, the automatic zoom loop logic is executed: based on the zoom direction flag, the current focal length value is incremented or decremented according to a preset proportional coefficient to generate a new target focal length value, achieving smooth and continuous focal length change. Steps S3 and S6 are repeated until the actual focal length reaches the target focal length. The main loop runs continuously in a non-blocking manner, ensuring that communication response, mode judgment, and automatic control logic are executed periodically, while providing execution opportunities for other background tasks, forming the event-driven and state management core of the entire control system.
[0036] To address the problems described in the background section, this invention first achieves high-precision nonlinear mapping from focal length to position using a lookup table interpolation algorithm, thus resolving the error issues arising from the traditional linear assumption. Secondly, it employs a position-velocity dual-loop cascade PID control, with a fast response inner loop and a precision-ensuring outer loop. Thirdly, it introduces integral separation and anti-saturation mechanisms, dynamically adjusting the integral strategy based on the error magnitude to effectively prevent overshoot and oscillation. Fourthly, it utilizes a multi-rate interrupt architecture, rationally layering 5kHz sampling, 666Hz control calculation, and 133Hz logic judgment to ensure real-time performance. Fifthly, it integrates temperature compensation and dual-threshold steady-state judgment, significantly improving environmental adaptability and control robustness. Experiments show that the system of this invention exhibits a zoom positioning error of less than ±0.05mm, an adjustment time of less than 0.5 seconds, and an overshoot of less than 2% in environments ranging from -20°C to 60°C, demonstrating a significant performance improvement compared to traditional solutions.
[0037] In the embodiments provided by this invention, it should be understood that the disclosed devices, systems, and methods can be implemented in other ways. For example, the system can use other STM32 series microcontrollers, the position sensor can be an encoder or other types of sensors, and the PID algorithm parameters can be adjusted according to the specific lens characteristics.
[0038] It will be apparent to those skilled in the art that the present invention is not limited to the details of the exemplary embodiments described above, and that the present invention can be implemented in other specific forms without departing from the spirit or essential characteristics of the present invention.
[0039] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention and are not intended to limit it. Although the present invention has been described in detail with reference to preferred embodiments, those skilled in the art should understand that modifications or equivalent substitutions can be made to the technical solutions of the present invention without departing from the spirit and scope of the technical solutions of the present invention.
Claims
1. A method for adjusting the focal length of an optical lens based on STM32 and PID algorithm, characterized in that, include: The STM32 microcontroller unit serves as the core processor of the system. An optical lens assembly, including at least a zoom motor for adjusting the focal length and a focusing motor for assisting focusing; The motor drive module is electrically connected to the STM32 microcontroller unit and the optical lens assembly, and is used to drive the zoom motor and the focus motor; The position sensing module is used to detect the actual physical position of the lens or lens group in the optical lens assembly in real time and feed the position signal back to the STM32 microcontroller unit. The STM32 microcontroller unit is configured to execute a control program stored therein, which implements a multi-loop PID control algorithm to control the motor drive module to drive the optical lens assembly to move to the target position according to the input target focal length value, thereby realizing closed-loop automatic adjustment of the focal length.
2. The system according to claim 1, characterized in that, The STM32 microcontroller unit includes: The focal length-position conversion module is used to convert the received target focal length value into the corresponding target position encoded value; The system includes a multi-loop PID controller, comprising at least one position loop PID controller and one speed loop PID controller. The position loop PID controller is used to calculate the deviation between the target position encoded value and the actual position feedback value from the position sensing module, and its output is used as the target speed setpoint of the speed loop PID controller. The output of the speed loop PID controller is used to control the motor drive module.
3. The system according to claim 2, characterized in that, The focal length-position conversion module achieves the conversion from focal length to position code value through a combination of table lookup and interpolation, specifically including: A pre-stored focal length-position lookup table, which stores multiple discrete focal length values and their corresponding standard position codes; A lookup unit is used to find at least two reference points in the lookup table that are closest to the target focal length value; An interpolation calculation unit is used to calculate, based on the focal length and position code values of the at least two reference points, a target position code value that precisely corresponds to the target focal length value using a linear interpolation algorithm.
4. The system according to claim 3, characterized in that, The search unit uses a binary search algorithm to quickly locate the information in the search table.
5. The system according to any one of claims 2 to 4, characterized in that, The position loop PID controller and the velocity loop PID controller employ an improved PID algorithm with integral separation and anti-integral saturation mechanisms. The improved PID algorithm includes the following steps: Load the pre-stored PID gain parameters, which are scaled and stored, including proportional, integral, and derivative parameters. Calculate the error value within the current control cycle, where the position loop PID corresponds to the position error value and the speed loop PID corresponds to the speed error value; If the absolute value of the error is less than the first preset threshold, the integral term is cleared to zero. If the absolute value of the error value is greater than the first preset threshold but less than the second preset threshold, then the error value is integrated and accumulated, and the integrated accumulated value is limited. If the absolute value of the error is greater than or equal to the second preset threshold, the integration term is cleared to zero and the integration process is stopped. The final control output value is calculated based on the proportional term, the processed integral term, and the derivative term. The proportional term, the processed integral term, the derivative term, and the control output are respectively represented as follows: , among which, U p [n] is the proportional term, U i [n] is the processed integral term, U d [n] is the differential term, U[n] is the control output value, and K p It is the proportional parameter in the PID gain parameters, K i K is the integral parameter in the PID gain parameters. d This is the differential parameter in the PID gain parameters, where n represents the index value of the current control cycle, e[n] is the position or velocity error value in the nth cycle, and e[n-1] is the position or velocity error value in the (n-1)th cycle. This represents the cumulative sum of errors, and k is the discrete-time index.
6. The system according to claim 5, characterized in that, The STM32 microcontroller unit executes the multi-loop PID controller through different timer interrupt frequencies, wherein the speed loop PID controller has a higher execution frequency and the position loop PID controller has the lowest execution frequency.
7. A method for adjusting the focal length of an optical lens based on STM32 and PID algorithm, characterized in that, Applied to the system according to any one of claims 1 to 6, the method comprises the following steps: Receive target focal length input command; The target focal length input command is converted into a target position encoded value through focal length-position conversion; Obtain the actual position feedback value from the position sensing module; A position loop PID control algorithm is adopted to quickly adjust the focal length position according to the deviation between the target position encoding value and the actual position feedback value, so as to achieve the target focal length. The speed loop PID control algorithm is used to adjust the PWM duty cycle based on the deviation between the target speed and the actual speed feedback value. Based on the PWM duty cycle, the motor drive module is controlled to drive the motor in the optical lens assembly to move, thereby adjusting the focal length; The system detects the actual position in real time and provides feedback to form a closed-loop control until the actual focal length reaches the target focal length.
8. The method according to claim 7, characterized in that, The step of "converting the target focal length input command into a target position encoded value through focal length-position conversion" specifically includes: In the pre-stored lookup table, a binary search algorithm is used to locate the reference row index that is closest to the target focal length value; Determine the relationship between the target focal length value and the focal length value corresponding to the reference row index; If the target focal length value is equal to the reference point focal length value, then the corresponding position code value is directly taken as the target value; If the target focal length value is between the focal length values of two reference points, then the target position code value is calculated based on the data of these two reference points using a linear interpolation formula. If the target focal length value exceeds the range of the lookup table, the boundary position code value is taken as the target value.