1. Trang chủ
  2. » Giáo Dục - Đào Tạo

Report design a training model of canbased electronic throttle control

126 0 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Design a training model of CAN-based electronic throttle control
Tác giả Phan Hoang Trung Kien
Người hướng dẫn MSc. Pham Tran Dang Quang
Trường học HCM University of Technology
Chuyên ngành Automotive Engineering
Thể loại Capstone project
Năm xuất bản 2025
Thành phố Ho Chi Minh City
Định dạng
Số trang 126
Dung lượng 3,29 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Cấu trúc

  • CHAPTER I. INTRODUCTION (11)
    • 1. Objective (12)
    • 2. Technical Requirements (12)
    • 3. Core problems to be solved & Solving ideas/methods (12)
    • 4. Scope of Thesis (13)
  • CHAPTER II. FUNDAMENTAL KNOWLEDGE (14)
    • 1. Electronic throttle control (14)
      • 1.1. Structure of electronic throttle control (14)
      • 1.2. Throttle position sensor (TPS) (15)
      • 1.3. Acceleration position sensor (APS) (16)
    • 2. H-bridge (18)
    • 3. Controller Area Network (CAN) (18)
      • 3.1. Overview of the structure of CAN (18)
      • 3.2. Frames (20)
      • 3.3. Working principle (21)
    • 4. Universal Asynchronous Receiver/Transmitter Protocol (UART) (22)
    • 5. Pulse Width Modulation (23)
    • 6. PID Control (24)
  • CHAPTER III. CHOOSING DESIGN PLAN (27)
    • 1. Microcontroller ESP32 (27)
    • 2. Can controller MCP2515 (28)
    • 3. H-Bridge MKS H3615NS (30)
    • 4. An operational amplifier (OPA/OPAMP) (31)
  • CHAPTER IV. GENERAL LAYOUT DESIGN (34)
    • 1. General layout block diagram (34)
      • 1.1. Graphical User Interface (window form C#) (34)
      • 1.2. Processor center unit (35)
      • 1.3. Actuators (36)
    • 2. Electronic Throttle Control system path (37)
  • CHAPTER V. TECHNICAL DESIGN (39)
    • 1. Wiring Diagram (39)
      • 1.1. Gateway module (39)
      • 1.2. CAN bus communication (39)
      • 1.3. Processing and actuator modules (41)
    • 2. Work Diagram Over Time (42)
      • 2.1. Timing diagram of ESP32#1 (42)
      • 2.2. Timing diagram of ESP32#2 (43)
    • 3. Algorithmic flowchart of ESP32#1 (44)
      • 3.1. Algorithmic flowchart of Task1_receive_GUI (44)
      • 3.2. Algorithmic flowchart of Task2_CAN_Transmit (46)
      • 3.3. Algorithmic flowchart of Task3_CAN_Receive (47)
      • 3.4. Algorithmic flowchart of Task4_send_GUI (48)
    • 4. Algorithmic flowchart of ESP32#2 (49)
      • 4.1. Algorithmic flowchart of Task1_CAN_receive (49)
      • 4.2. Algorithmic flowchart of Task2_Read_PID (50)
      • 4.3. Algorithmic flowchart of Task3_CAN_send (52)
  • CHAPTER VI. RESULTS AND EVALUATION (53)
    • 1. Determining the output voltage signal parameters of the position sensor (53)
    • 2. Motor controlling via GUI (53)
    • 3. Model 3D via GUI (55)
    • 4. Survey on the influence of Ki, Kp, Kd coefficients on control response via (57)
    • GUI 56 4.1. Kp coefficient (0)
      • 4.2. Ki coefficient (59)
      • 4.3. Kd coefficient (60)
      • 4.4. Summary (62)
  • CHAPTER VII. CONCLUSION (64)
    • APPENDIX 1: GRAPHICAL USER INTERFACE - Windows Forms (C# - Visual Studio) (68)
    • APPENDIX 2: Windows Form C# Program (75)
    • APPENDIX 3: Microcontroller Program of ESP32#1 (96)
    • APPENDIX 4: Microcontroller Program of ESP32#2 (112)

Nội dung

I developed a graphical user interface GUI using C# Windows Forms to send throttle commands, adjust PID parameters, and display sensor feedback such as APS and TPS signals.. Reading and

INTRODUCTION

Objective

Design of a user interface for throttle control, parameter monitoring, and component visualization.

Technical Requirements

To ensure seamless control and monitoring, develop a user interface that provides intuitive and easy access to key parameters Implement microcontroller firmware capable of accurately reading and processing voltage signals, ensuring data consistency across multiple tasks, and precisely calculating PWM signals to control throttle position within acceptable error margins This guarantees the throttle valve maintains the desired opening reliably Additionally, simulate CAN bus communication to facilitate reliable two-way data transmission between microcontrollers, enhancing system stability and performance.

Core problems to be solved & Solving ideas/methods

Core problems to be solved Solving ideas/methods

Graphical user interface (sending data, monitoring parameter charts, and PID parameter affecting the controlling)

Programming using Windows Forms with C# language

Reading and processing input signals such as desired throttle opening, actual

Using the ESP32-Wroom-32E microcontroller, with an Op-amp

12 opening, and PID coefficients potentiometer circuit to process sensor signals for actual throttle position, and interpolation functions for calculations

Simulating the CAN bus communication

Using the MCP2515 CAN module with the SPI protocol.

Scope of Thesis

• Create a user interface to monitor data, control motor and understand about ETC system

• Ensure data can be transmitted and receive both directions

• Ensure the microcontroller to read and solve the data to control throttle

• Can not ensure the system operating under real-time

• Error of data in reading the actual throttle opening

The Thesis assignment is approved by the Department of Automotive Engineering

Date (dd/mm/yyyy) : ……… Date (dd/mm/yyyy) : ………

MSc Pham Tran Dang Quang

FUNDAMENTAL KNOWLEDGE

Electronic throttle control

1.1 Structure of electronic throttle control

The electronic throttle is a crucial component of modern fuel injection engines, responsible for precisely regulating airflow into the combustion chamber It operates by adjusting the throttle plate opening through a DC electric motor, enabling optimal engine performance This electronic control improves fuel efficiency and responsiveness compared to traditional mechanical throttles Proper maintenance of the electronic throttle is essential for smooth engine operation and enhanced vehicle performance.

The main parts of an electronic throttle body are: the throttle control motor, reduction gears, the throttle position sensor, the throttle valve (plate), and the throttle return spring

The motor's torque is transmitted through reduction gears to rotate the throttle valve to a specific angle, controlling engine airflow When the motor's torque balances with the return spring's opposing force, the throttle valve remains stationary, maintaining optimal engine performance Once the motor power is cut off, the return spring closes the throttle valve, ensuring safe engine shutdown and efficient operation.

14 position sensor puts out a voltage signal in response to the change in the throttle valve's position

The engine control unit (ECU) relies on the throttle position sensor (TPS) to measure how much the throttle plate is open, providing crucial data for engine management This information allows the ECU to determine the engine's load, which is essential for regulating idle speed, ignition timing, fuel injection, fuel cut-off, and transmission shifts There are two main types of throttle position sensors used in electronic throttles: linear sensors and Hall effect sensors, both integral to optimal engine performance.

This sensor features two sliders and a resistor, with dedicated connections for IDL and VTA signals at each end When the throttle opens, the sliders move along the resistor, sending a voltage to the VTA terminal that increases proportionally to the throttle opening Conversely, when the throttle is fully closed, the IDL signal connection contacts the IDL and E2 terminals, indicating a closed throttle position.

Hall IC circuits in the throttle position sensor utilize magnets and Hall elements that rotate with the throttle shaft, detecting changes in the magnetic field as the throttle opens The Hall IC generates voltage signals through its VTA1 and VTA2 pins, which vary based on the magnetic field shift caused by the moving magnets These voltage signals are sent to the engine computer (ECU), providing precise information about the throttle's open position The sensor's simple, non-contact design makes it durable and resistant to damage, ensuring reliable performance Additionally, it transmits signals from two independent systems, enhancing its dependability.

The gas pedal position sensor detects how far you press the pedal and converts this input into an electrical signal for engine management It transmits data to the engine's ECU, ensuring precise throttle control To enhance reliability, the sensor sends signals from two independent systems that output the data differently There are two main types of gas pedal position sensors: linear sensors and Hall effect sensors, both designed to provide accurate throttle position information.

The pedal sensor functions similarly to a standard gas pedal position sensor by emitting two voltage signals that indicate pedal position As you press the pedal, the voltage of the VPA signal gradually increases, providing a clear reference for pedal engagement Meanwhile, the VPA2 signal delivers a voltage that generally balances or counteracts the VPA signal, offering additional insights into the pedal's position By analyzing the relationship between these two signals, the sensor accurately determines how the pedal is being pressed, ensuring precise throttle control.

The sensor's construction and operation closely resemble those of a Hall effect throttle position sensor Both systems utilize independent electrical circuits to enhance reliability and ensure precise performance.

H-bridge

Figure 7: Basic schematic diagram of H-bridge

An H-bridge is an essential electronic circuit that enables precise control of DC motor speed and direction by adjusting the voltage across the motor terminals This bidirectional motor driver setup allows DC motors to spin forward or in reverse, making it ideal for various automation and robotics applications By utilizing pulse width modulation (PWM) or a fixed DC voltage, an H-bridge provides efficient and versatile control of motor rotational speed and direction.

Closing switches S1 and S4 while keeping S2 and S3 open directs the DC motor to run in a single direction from left to right, as indicated by the orange line Conversely, opening S1 and S4 and closing S2 and S3 reverse the current flow through the motor, causing it to run in the opposite direction from right to left, as shown by the blue line This switching configuration enables precise control of the motor's rotational direction.

Controller Area Network (CAN)

3.1 Overview of the structure of CAN

The Controller Area Network (CAN) is the most widely used in-vehicle network protocol, ultimately establishing itself as the international standard ISO 11898 Originally developed by Bosch, CAN has been widely adopted by the automotive industry for reliable communication between electronic control units Additionally, higher-level protocols such as DeviceNet and CANopen, both standardized on CAN, are commonly used in industrial automation and communication systems, further demonstrating CAN’s versatility and global significance in vehicular and industrial networking.

Additionally, CAN is accepted expressly for certain vehicle classes, such as agricultural vehicles (ISO11783) and commercial vehicles (J1939)

The CAN bus is a robust and straightforward communication system that allows various electronic components, known as nodes or ECUs, within vehicles and machinery to exchange information seamlessly without relying on a central computer Often described as a multi-lane communication highway, the CAN bus enables all parts to send and receive messages efficiently, ensuring reliable operation across complex systems Its simplicity and durability make it an essential technology in modern automotive and industrial applications, improving data sharing and system performance.

A CAN (Controller Area Network) requires at least two components to be connected for communication It uses two wires—CAN High (CAN H) and CAN Low (CAN L)—which are typically twisted together and have an overall resistance of approximately 120 ohms A 120-ohm resistor is strategically placed at each component connected to the CAN bus, especially at the ends of the network These resistors are essential for maintaining a silent bus when no messages are being transmitted, preventing signal bouncing and ensuring reliable data transfer This setup facilitates fast, dependable communication between vehicle components such as the engine control unit and braking system, enhancing overall vehicle performance and safety.

Figure 8: CAN general structure diagram

Electronic Control Units (ECUs) in vehicles and machinery communicate seamlessly without a host computer through the Controller Area Network (CAN bus) This communication system enables real-time, reliable data sharing between critical components such as the engine and brakes Each node in the CAN bus consists of three primary parts, facilitating efficient and secure data transfer essential for optimal vehicle performance and safety.

The microcontroller (MCU) serves as the ECU's central processing unit, interpreting incoming CAN messages to decide which messages to send The CAN controller, typically integrated within the MCU, ensures all communications adhere to the CAN protocol by managing message encoding, error detection, and arbitration, thereby simplifying the MCU's complexity The CAN transceiver connects the CAN controller to the physical CAN bus, converting controller data into differential signals and providing essential electrical protection for reliable communication.

The CAN protocol begins with the Start of Frame (SoF), a dominant (logic 0) bit that signals the start of a new message on the bus Following SoF is the Arbitration ID, which serves as an identifier indicating the message's content and priority; this ID can be of varying lengths, with shorter IDs used for certain messages to optimize communication efficiency.

(11 bits) called "standard" and a longer one (29 bits) called "extended." The shorter ID is more common

The Identifier Extension bit (IDE) distinguishes between standard and extended message formats by serving as a flag that indicates which ID type is used The Remote Transmission Request bit (RTR) specifies whether the message is a remote frame requesting data (recessive bit "1") or a data frame transmitting data (dominant bit "0") The Data Length Code (DLC) indicates the number of data bytes in the message, ranging from 0 to 8 bytes in standard CAN and up to 64 bytes in newer, higher-speed systems The Data Field contains the actual information being transmitted, such as sensor readings or control commands, and can be empty or hold up to 8 or 64 bytes The Cyclic Redundancy Check (CRC) functions as an error detection mechanism, where the sender computes a 15-bit code based on the message content and appends it, allowing receivers to verify data integrity and detect transmission errors.

"end" bit after the CRC h) Acknowledgement slot (ACK): This is like a "got it" signal After a part on the

In CAN bus communication, a message receiver sends back a unique "ACK" bit to confirm successful receipt The sender monitors this acknowledgment to ensure the message was correctly received; if the "ACK" is not detected, it indicates a transmission error In such cases, the sender may retry sending the message to maintain reliable data exchange.

CAN (Controller Area Network) is a decentralized network where all nodes are equal, and no component has control over the communication sequence Before transmitting data, each node must undergo a message arbitration process to decide who communicates next, ensuring orderly data transmission To determine if the communication bus is available, nodes first perform a listening procedure, checking whether the line is free for transmission.

It begins delivering its message if it is free This causes every other component on the

On the CAN bus, it’s essential to understand that multiple components may transmit messages simultaneously, causing conflicts To handle this, the network employs strategies such as "sending and listening," where a device transmits data while simultaneously monitoring the bus for other signals Additionally, the CAN bus uses priority checks to determine which message should take precedence when multiple devices attempt to communicate at once, ensuring efficient and conflict-free data transfer.

In a multi-part communication system, the device with the highest priority message gains control of the communication bus by performing a priority check at the start of each message During this process, if a higher priority signal is detected, the transmitting device immediately halts its transmission and switches to listening mode, allowing the higher priority message to proceed uninterrupted The device with the most critical message, identified by the lowest priority ID, wins the right to transmit its full message, ensuring essential communications are prioritized Listening devices then filter incoming messages to determine their relevance, processing only the important information and ignoring less critical data This coordinated process enables efficient, priority-based message transmission among different system components.

Universal Asynchronous Receiver/Transmitter Protocol (UART)

UART (Universal Asynchronous Receiver/Transmitter) is a hardware module integrated into microcontrollers, rather than a communication protocol like SPI or I2C It facilitates full-duplex data exchange using just two wires—TX (Transmit) and RX (Receive)—between devices For proper operation, both devices must also share a common ground, enabling reliable asynchronous communication.

UART (Universal Asynchronous Receiver/Transmitter) seamlessly converts parallel data from components like the CPU into serial form for efficient transmission and then back into parallel form at the receiver end This data transfer process minimizes wiring complexity by using just two wires—TX for transmitting data and RX for receiving data—making UART a vital communication protocol for serial communication between electronic devices.

UART operates asynchronously, meaning it does not rely on a shared clock signal Instead, it uses start bits and stop bits to mark the beginning and end of each data frame, ensuring accurate data transmission This method allows the receiving device to accurately identify when to start sampling incoming bits, facilitating effective communication without synchronization through a common clock.

Data is read at a defined baud rate (measured in bits per second), which must be identical on both communicating devices to ensure proper synchronization and accurate data transfer.

Pulse Width Modulation

Pulse Width Modulation (PWM) is a technique that divides an electrical signal into discrete pulses, effectively reducing the average power transmitted Instead of delivering energy continuously as an analog signal, PWM distributes power through a series of rapid on-and-off pulses This method enhances efficiency and control in various electronic applications by modulating the width of the pulses to regulate power delivery.

Figure 11: Parameters in the PWM signal

In a PWM (Pulse Width Modulation) signal, the duty cycle represents the proportion of time the signal remains at its 'high' level within each cycle A timer manages this 'on' duration before the signal switches to 'low,' effectively controlling the duty cycle The percentage of the duty cycle determines the PWM signal's output voltage, making it a crucial parameter for applications requiring precise voltage control.

The output voltage varies with the duty cycle; at a 100% duty cycle, it will be just below 5 V when the operating voltage is around 5 V, ensuring maximum power delivery Conversely, at approximately a 50% duty cycle, the output voltage drops to about 2.5 V, demonstrating the direct relationship between duty cycle and output voltage in PWM systems.

PID Control

Controlling a DC motor using a PWM signal through an H-bridge represents the most basic open-loop control method, where the controller applies a voltage without feedback This technique allows for simple speed regulation by adjusting the duty cycle of the PWM signal Open-loop control is straightforward but lacks the ability to correct motor behavior based on actual speed or position, making it suitable for basic applications requiring minimal precision Using PWM via H-bridge is an efficient way to regulate motor performance, but it is essential to consider its limitations in systems demanding higher accuracy.

A PWM signal alone cannot estimate its impact on motor performance Typically, controllers assume that higher voltage results in faster motor speeds Closed-loop control enhances this by using real-time motor feedback, such as speed or current, to adjust the PWM signal dynamically A PID (Proportional-Integral-Derivative) loop is a widely used algorithm in closed-loop systems, providing precise control by continuously correcting motor behavior based on feedback.

The PID U equation is the sum of three equations: proportional, integral, and differential, based on the difference 𝑒 𝑡 between the desired throttle opening 𝑣 𝑎𝑝𝑠 and the actual throttle position 𝑣 𝑡𝑝𝑠

In which: o Throttle position error: 𝑒 𝑡 = 𝑣 𝑎𝑝𝑠 − 𝑣 𝑡𝑝𝑠 (2) o Control parameters: 𝐾 𝑝 ,𝐾 𝑖 , 𝐾 𝑑

This chapter provides essential technical knowledge for understanding the Electronic Throttle Control (ETC) system, including its structure and working principles It explains key components such as the Throttle Position Sensor (TPS) and Accelerator Pedal Sensor (APS), covering both linear and Hall effect types The H-bridge circuit is introduced as a method for bidirectional DC motor control within the system Additionally, the chapter discusses the Controller Area Network (CAN) protocol, focusing on its architecture, frame formats, and communication principles Core microcontroller interfaces like UART communication and Pulse Width Modulation (PWM) techniques are explained to illustrate their roles in ETC operation Lastly, the chapter introduces the PID control algorithm, detailing how proportional, integral, and derivative components work together to regulate throttle position in a closed-loop system, ensuring precise and responsive control.

CHOOSING DESIGN PLAN

Microcontroller ESP32

Equipped with two Xtensa LX6 processors based on Harvard architecture, the

The ESP32 is a powerful dual-core system, with both cores directly accessible to internal and external memories and peripherals, enabling efficient data processing Positioned on the instruction and data buses, the two cores—referred to as “PRO_CPU” and “APP_CPU”—were initially designed for protocol handling and application logic, respectively, but are largely interchangeable in practical applications With a mirrored address space across both cores, the system allows for identical memory access using the same addresses, enhancing flexibility and performance Additionally, DMA enables fast and efficient memory access by multiple onboard peripherals, further optimizing the ESP32’s overall functionality for IoT and embedded system projects.

Figure 14: ESP32-DevKitC-32E pinout schematic a) Address Space:

• 4GB(32-bit) address space for both data bus and instruction bus

• 1296 KB embedded memory address space

• 19704 KB external memory address space

• Through the data or instruction bus, various sections of embedded and external memory can be reached depending on system requirements

External memory connected via SPI can be integrated into the system’s address space as off-chip memory, expanding overall storage capacity Portions of internal memory can function as a transparent cache layer, automatically optimizing data access and improving system performance This setup allows seamless communication between the processor and external storage, enhancing system flexibility and efficiency.

• Supports up to 16 MB off-Chip SPI Flash

• Supports up to 8 MB off-Chip SPI SRAM d) Peripherals: 41 peripherals e) DMA: 13 modules are capable of DMA operation

Can controller MCP2515

Microchip Technology's MCP2515 is a standalone Controller Area Network (CAN) controller that complies with the CAN 2.0B specification, enabling efficient communication within automotive and industrial networks It supports sending and receiving remote frames, as well as standard and extended data frames, ensuring versatile data transmission The MCP2515 minimizes the processing load on the host microcontroller by employing six acceptance filters and two acceptance masks, which filter out unnecessary messages and improve communication efficiency This advanced CAN controller is ideal for integrating reliable and efficient CAN protocol support into various embedded systems.

MCP2515 communicate over the industry-standard Serial Peripheral Interface (SPI)

The CAN module manages all transmission and reception of CAN bus messages, ensuring reliable communication To send messages, the appropriate message buffer and control registers must be properly loaded, and transmission is initiated via transmit enable pins or control register bits through the SPI interface Monitoring the status and error registers allows for verification of message integrity and detection of faults Incoming messages are scrutinized against user-defined filters after fault examination, determining whether they should be stored in one of the two receive buffers for further processing.

Figure 15: Block diagram of MCP2515

The MCU communicates with the device via the SPI interface, enabling efficient data transfer Standard SPI read and write commands, alongside specialized SPI instructions, are used to access and modify all device registers This communication method ensures reliable data exchange and flexible control over device functions Utilizing the SPI protocol allows for seamless integration and optimized performance in embedded systems.

H-Bridge MKS H3615NS

12A (no heatsink) 15A (basic heatsink) 20A (large heatsink)

Max Output with 5V Supply 500mA

Table 1: Configuration of feature of MKS H3615NS

An operational amplifier (OPA/OPAMP)

An operational amplifier (OPA) with an internal resistor ladder is an effective solution for dynamically scaling input signals to match the full measurement range of an Analog-to-Digital Converter (ADC) This configuration improves ADC resolution and accuracy by optimizing the utilization of the input voltage range In this setup, the OPAMP functions as a precise signal conditioning component, ensuring that input signals are properly adjusted for accurate digital conversion.

Programmable Gain Amplifier (PGA), allowing for fine control over the signal amplification based on system requirements or sensor output levels

The ESP32 operates at a logic level of 3.3V, and its GPIO pins are designed to function within this voltage limit Applying voltages higher than 3.3V directly to GPIO pins can damage the internal circuits of the microcontroller To ensure safe and reliable communication when connecting to external components or sensors with higher voltage levels, it is essential to use voltage level shifting solutions like voltage dividers or dedicated level shifter ICs.

In my application, I used an OPAMP between the throttle position sensor (TPS) output and the ESP32's ADC input to ensure accurate and safe signal reading The OPAMP buffered and scaled the sensor's analog signal, keeping it within the ESP32's safe voltage range By configuring a specific GPIO pin, the OPAMP dynamically scaled down the sensor’s voltage, allowing the ESP32 to sample with improved resolution and accuracy while protecting its hardware This setup optimized analog signal measurement and enhanced overall system reliability.

Figure 18: Structure diagram of OPAMP

To ensure the output signal remains within the 0–3.3V range required by the ESP32's ADC, resistor values such as R₁ = 3400Ω and R₂ = 6600Ω were selected to form a voltage divider or feedback network in the op-amp circuit These resistor choices facilitate accurate scaling of sensor input voltages, allowing the ADC to fully utilize its dynamic range This approach improves the resolution and precision of digital readings by effectively compressing or expanding the input voltage, enabling the sensor signals to be accurately interpreted within the ESP32's voltage limits.

Proper resistor selection is essential to ensure accurate ADC readings and protect the ESP32 Using standard resistor values close to the calculated ones is acceptable, but thorough simulation and testing are necessary to account for tolerances and load effects Incorrect resistor matching can prevent the signal from reaching the full ADC scale, reducing resolution, or cause voltage levels to exceed 3.3V, risking damage to the device.

We used a circuit simulation tool to verify the accuracy and performance of the scaling circuit, ensuring reliable operation The simulation confirmed that the voltage at the OPAMP output correctly tracked the expected range, demonstrating the circuit’s effectiveness This validation ensures that the ESP32 can safely and precisely sample the analog signal across different throttle conditions, enhancing overall system reliability.

Figure 19: Simulation on app LTspice

This chapter highlights the selection of essential hardware components for the ETC system The ESP32 microcontroller was chosen for its powerful dual-core architecture and SPI communication capabilities, enabling efficient interfacing with the MCP2515 standalone CAN controller Additionally, the MKS H3615NS H-bridge driver was employed to effectively control the system's motor operations.

Discover the advantages of DC motors, which provide high current support and flexible PWM control for precise motor management To enhance sensor signal accuracy and protect the microcontroller’s ADC input, an operational amplifier (Op-amp) is implemented to amplify and scale sensor voltage signals This integration ensures safe input levels while improving overall system precision and performance.

GENERAL LAYOUT DESIGN

General layout block diagram

Figure 20: General layout diagram of electrical-electronic ETC System

1.1 Graphical User Interface (window form C#)

The communication module serves as a vital gateway between external devices, such as laptops with GUI software, and the embedded control system in vehicles It ensures reliable and accurate data exchange by bridging the gap between user input/output and real-time embedded processing This module plays a crucial role in maintaining seamless communication, enabling efficient control and monitoring of the vehicle’s systems.

This module is composed of two main parts: a) Graphical User Interface (GUI)

• Transmit to ESP32 #1: o APS value (desired throttle opening) o PID parameters (Kp, Ki, Kd) o Direction (motor rotation direction)

The ESP32 #1 functions as the communication processor, an intermediary microcontroller that manages data exchange between the user interface and the vehicle-side controller It receives critical sensor data such as the TPS value, which indicates the actual throttle opening, along with optional control parameters like PWM values and PID outputs, providing real-time control responses This ensures seamless communication and precise control integration between the GUI and ESP32 #2, optimizing vehicle performance and system responsiveness.

• Transmit: o To ESP32 #2: throttle, PID, and control direction o To GUI: feedback data (TPS, PWM, PID output)

• Receive: o From GUI: user inputs and commands o From ESP32 #2: real-time feedback (TPS, PWM, etc.)

This communication module ensures two-way enabling of closed-loop control and user monitoring It also provides a flexible platform for testing and educational demonstrations of embedded communication systems

The processing module is the heart of the system, responsible for real-time data processing and executing control actions It receives commands from the communication unit, interprets sensor data, performs precise PID calculations, and manages the physical actuator (throttle valve) based on these results This module comprises two main components: ESP32 #2, the control microcontroller that executes control logic and interfaces with the motor driver (H-Bridge), ensuring seamless system operation.

• Receive: Data from ESP32 #1: desired throttle opening, PID parameters, motor direction

• Process: o Read TPS sensor values and determine actual throttle position o Calculate control output using the PID algorithm o Generate an appropriate PWM signal for motor control

• Control: Drive the throttle valve by sending PWM signals to the H-Bridge

• Send: Feedback data (e.g., TPS, PID result, PWM) back to ESP32 #1 b) H-Bridge Motor Driver: Drives the throttle actuator based on control signals

• Uses the PWM signal calculated by ESP32 #2

• Applies the corresponding voltage to the DC motor to open or close the throttle valve as required

This processing module ensures that control decisions are made accurately and executed in real time, maintaining precise throttle positioning with minimal error

The actuation module is the final stage of the system, responsible for physically adjusting the throttle valve based on control signals It converts electrical commands into precise mechanical motion and offers real-time feedback for effective closed-loop control This critical component comprises an electric motor, which transforms electrical signals into mechanical movement, ensuring accurate throttle adjustments for optimal engine performance.

• Receives voltage from the H-bridge motor driver

• Generates torque to rotate the throttle valve b) Throttle Valve: Controls the airflow into the engine based on motor movement

• The valve's opening is determined by the balance between the motor torque and the resistance from the return spring

• Controls the engine's response according to driver input and system regulation

36 c) Throttle Position Sensor (TPS): Provides real-time position feedback to the control system

• Measures the actual throttle opening

• Sends the data as a voltage signal to ESP32 #2

• This value is used in the next PID calculation cycle to maintain precise control

Together, these components ensure accurate physical response to electronic control commands, enabling stable and responsive throttle control in automotive applications.

Electronic Throttle Control system path

Figure 21: Close control path of the Electronic Throttle Control

Based on driver input and real-time feedback, the Electronic Throttle Control

The ETC (Electronic Throttle Control) system precisely manages the throttle valve opening through a sophisticated closed-loop control architecture It begins by processing input signals from the accelerator pedal sensor and various vehicle sensors, which collectively indicate the driver's intended throttle position These inputs enable the system to accurately adjust the throttle opening, ensuring optimal engine performance and driver responsiveness.

An Electronic Control Unit (ECU) utilizes a PID control algorithm to process input signals within its control rules It accurately measures throttle position errors by comparing the desired throttle setting with actual readings from the throttle position sensor The ECU then generates a PWM signal through the PID controller, adjusting the throttle to achieve optimal performance and precise control.

The H-Bridge driver controls the direction and magnitude of voltage supplied to the DC motor by receiving PWM signals, enabling precise motor operation The motor's mechanical torque adjusts the throttle valve opening, which in turn influences engine performance The degree of throttle valve opening determines the amount of intake air (Qair) allowed into the engine, directly impacting engine efficiency and power output.

The Throttle Position Sensor constantly monitors the throttle position and sends real-time data to the ECU, creating an essential feedback loop This closed-loop system ensures accurate and responsive engine control by continuously adjusting the throttle opening to match driving conditions Such precise throttle management is vital for modern vehicle engine systems, providing steady performance and adaptability across diverse situations.

This chapter provides an overview of the system's block diagram and layout, featuring a user-friendly GUI developed in C# Windows Forms The ESP32 microcontroller serves as the central processing unit, coordinating data transfer between the GUI and the actuator module, which includes a motor and throttle valve Data from the GUI is transmitted to ESP32#1, then relayed via the CAN bus to ESP32#2 for processing and control Sensor feedback signals are sent back to the GUI, enabling real-time visualization and establishing a closed-loop control system for efficient operation.

TECHNICAL DESIGN

Wiring Diagram

Figure 22: Wiring diagram between laptop and ESP32

The micro USB port on the ESP32 is responsible for receiving and transmitting data, enabling communication with the GUI (Graphical User Interface) via the COM port

Transmitted signals include the desired throttle value, which the microcontroller uses to calculate the target throttle opening, ensuring precise engine control Additionally, PID parameters such as Ki, Kp, and Kd are sent for tuning the control algorithm to optimize system performance The signals also include a direction value (0 or 1) that determines the motor's rotation direction, facilitating accurate movement control.

• Received signals include: o The actual throttle position is sent back to the GUI for real-time monitoring

Figure 23: Wiring diagram of pair of MCP2515 and ESP32

This project demonstrates how the ESP32 microcontroller effectively communicates with the MCP2515 CAN controller via the SPI protocol to simulate a CAN bus network, similar to those employed in modern vehicles Utilizing the SPI interface ensures efficient data transfer between the ESP32 and MCP2515, enabling realistic CAN bus communication for automotive applications This setup provides a practical solution for developing and testing vehicle communication systems using accessible microcontroller and CAN controller modules.

The wiring configuration follows standard SPI connections:

• MOSI (Master Out Slave In) on ESP32 connects to SI on MCP2515

• MISO (Master In Slave Out) on ESP32 connects to SO on MCP2515

• SCLK (Serial Clock) on ESP32 connects to SCK on MCP2515

• CS (Chip Select) on ESP32 connects to CS (or NSS) on MCP2515

• Additionally, the INT (interrupt) pin from MCP2515 is connected to a GPIO pin on the ESP32 to notify the microcontroller when a CAN message is received or transmitted successfully

The MCP2515 manages all low-level CAN protocol functions, enabling the ESP32 to easily send and receive CAN messages by configuring the SPI interface This integration allows two ESP32 boards to communicate seamlessly over a simulated CAN network, closely mimicking real-world vehicle control systems for robust and efficient communication.

Figure 24: Wiring diagram of ESP32 and H Bridge, actuators

The ESP32 is connected to an H-Bridge driver that manages a DC motor responsible for opening and closing the throttle valve It sends control signals, including direction and PWM, from the ESP32 to the H-Bridge via digital output pins, enabling precise motor control for throttle operation.

The DC motor is controlled via an H-Bridge, which receives voltage signals modulated by the PWM signal generated by the ESP32 This setup allows for precise regulation of the motor's speed and direction, directly impacting throttle movement for accurate performance.

The Throttle Position Sensors (TPS) are connected to the ESP32’s analog input pins, providing voltage signals that indicate the current throttle opening The ESP32 reads these signals and processes them using a PID control algorithm to ensure precise throttle management By continuously adjusting the PWM output based on sensor feedback, the system effectively maintains the desired throttle position This straightforward wiring setup between the ESP32 and the sensors enables accurate and reliable throttle control.

Bridge, motor, and TPS creates a complete and functional closed-loop control system

Work Diagram Over Time

This microcontroller acts as a communication gateway between the GUI on the host computer and the embedded control unit (ESP32#2) It manages bidirectional data exchange through UART and CAN bus protocols, ensuring seamless communication between system components The first task, Task1_receive_GUI, involves receiving data from the GUI to facilitate real-time control and monitoring of the embedded system.

This task handles serial data from the user interface (GUI), including throttle position (apsPercent), PID tuning parameters (Kp, Ki, Kd), and motor direction, ensuring the system receives updated control settings It is vital for maintaining accurate system control by reliably and regularly executing to incorporate user-defined parameters The second task, Task2_CAN_Transmit, is responsible for transmitting the processed data over the CAN bus, facilitating communication between system components and ensuring real-time data exchange for optimal system performance.

• Function: Sends control data received from the GUI to ESP32#2 via CAN bus The data is split across three CAN frames: one for apsPercent + Kp, one for Ki +

Kd, and one for direction

This task is given the highest priority to ensure fast and consistent delivery of control commands to the processing node c) Task3_CAN_Receive:

The Function receives feedback data from ESP32#2, specifically the actual throttle position values (TPS1 and TPS2) encoded within a CAN frame It plays a crucial role in ensuring that ESP32#1 can deliver real-time feedback to the GUI, enabling accurate monitoring and display of throttle status The Task4_send_GUI function facilitates seamless communication between the embedded system and the user interface, providing timely and reliable data for effective system oversight.

• Function: Sends the received throttle position feedback (tps1, tps2) back to the GUI via UART

This task is less time-sensitive and thus assigned the lowest priority

Figure 25: Timing diagram of multi-task in EPS32#1

This microcontroller handles essential control functions by reading sensor data, performing PID calculations, and generating PWM signals to actuate the throttle motor through an H-Bridge One key task is Task 1: CAN reception, which involves receiving and processing CAN messages to ensure accurate and real-time control of the system.

• Function: This high-priority task listens for CAN messages sent from ESP32#1

The system extracts the desired throttle value and PID parameters, updating internal variables to ensure that the control logic operates with the latest user-defined inputs This process is essential for maintaining accurate and responsive control performance Specifically, Task 2, referred to as Task2_Read_PID, is responsible for reading these parameters and updating the system's control variables accordingly By consistently retrieving and applying the most recent PID settings, the control system remains optimized for precise operation.

The system reads analog voltages from the throttle position sensor (TPS), converting them into percentage values for precise control Utilizing the PID algorithm, it calculates the appropriate PWM duty cycle to ensure smooth and accurate actuation Additionally, it determines the correct motor direction based on received signals and drives the H-Bridge accordingly This process plays a crucial role in maintaining closed-loop control stability and responsiveness for optimal performance.

The function transmits the current throttle position values (TPS1 and TPS2) to ESP32#1 using CAN communication Although this data provides essential feedback for system monitoring, it is not time-critical, which is why it is assigned the lowest priority within the task set This ensures efficient processing and reliable data transmission without impacting critical system operations.

Figure 26: Timing diagram of multi-task in ESP32#2

Algorithmic flowchart of ESP32#1

3.1 Algorithmic flowchart of Task1_receive_GUI

Figure 27: Flowchart algorithm of the task1_receive_GUI

The flowchart demonstrates how control data is received from the GUI through UART communication The microcontroller continuously reads incoming bytes and temporarily stores them in the serialBuffer When 25 bytes are received and the packet format is validated—beginning with 'S', 'T', 'A' and ending with '\r', '\n'—the relevant data is then extracted for processing.

• Kp, Ki, Kd: PID coefficients

After parsing, the buffer index is reset to receive the next packet

3.2 Algorithmic flowchart of Task2_CAN_Transmit

Figure 28: Flowchart algorithm of the task2_CAN_Transmit

The flowchart describes the process of sending control data from ESP32#1 to ESP32#2 via CAN communication

The data is divided into three separate frames, each with a unique CAN ID:

• Frame 0x100: includes the desired throttle position apsPercent and the proportional gain Kp

• Frame 0x101: includes the integral and derivative gains Ki and Kd

• Frame 0x102: includes the direction value to determine motor rotation direction

Each frame is constructed with the appropriate data length and payload, and then transmitted using mcp2515.sendMessage()

3.3 Algorithmic flowchart of Task3_CAN_Receive

Figure 29: Flowchart algorithm of the task3_CAN_receivce

The flowchart depicts the process of receiving feedback data from ESP32#2 through CAN communication When the messageAvailable flag is set—triggered by an interrupt from the MCP2515—the microcontroller initiates reading messages from the CAN buffer This sequence ensures efficient handling of incoming data in the system.

If a message with CAN ID 0x200 and 8 bytes of data is detected:

• The first 4 bytes are copied into tps1 representing throttle position from sensor 1

• The next 4 bytes are copied into tps2 representing sensor 2

After successful reading, the messageAvailable flag is reset to false to wait for the next incoming message

3.4 Algorithmic flowchart of Task4_send_GUI

Figure 30: Flowchart algorithm of the task4_send_GUI

The flowchart describes the process of sending feedback data from ESP32#1 to the GUI via UART communication

In each cycle, a 13-byte packet is constructed in the following format:

• Header (3 bytes): 'S', 'T', 'A' to indicate the start of the packet

48 o First 4 bytes contain tps1 (actual throttle position from sensor 1) o Next 4 bytes contain tps2 (from sensor 2)

• Footer (2 bytes): '\r', '\n' mark the end of the packet

Once the packet is fully assembled, it is sent through the Serial port to the GUI application for real-time display and monitoring.

Algorithmic flowchart of ESP32#2

4.1 Algorithmic flowchart of Task1_CAN_receive

Figure 31: Flowchart algorithm of the Task1_CAN_receive

The flowchart depicts the process in which ESP32#2 receives control data from ESP32#1 over the CAN bus During each cycle, the microcontroller assesses incoming messages from the MCP2515 module When a new message is detected, the CAN ID is analyzed to identify the data type, ensuring efficient communication between devices.

• ID 0x100 (8 bytes): contains apsPercent (desired throttle) and Kp

→ These values are stored and passed to the PID controller

• ID 0x101 (8 bytes): contains Ki and Kd

→ Updates the integral and derivative gains for PID

→ Indicates motor rotation direction for throttle valve actuation

All received data is stored in relevant variables to be used in the PID control task in the next cycle

4.2 Algorithmic flowchart of Task2_Read_PID

The flowchart illustrates the process of reading TPS sensor data, calculating the PID output, and controlling the throttle valve using a DC motor

• Analog signals from the two throttle position sensors (VTA1 and VTA2) are read and converted to voltage

• The voltages are then mapped to throttle opening percentages (tps1_percent, tps2_percent) using interpolation and clamping

• Based on the direction value, motor rotation direction is set by writing

HIGH/LOW signals to the H-Bridge control pins

The PID algorithm is configured using the current values of Kp, Ki, and Kd It computes a control output (pid_out) based on the error between tps1_pid and apsPercent_pid This ensures precise control by continuously adjusting based on real-time feedback Proper tuning of these parameters is essential for optimal system performance.

• The output is normalized to a range of 0–1 and scaled to a 12-bit PWM resolution (4095), then written to the motor driver using ledcWrite()

• This results in precise throttle valve positioning based on real-time sensor feedback and control logic

Figure 32: Flowchart algorithm of the Task2_Read_PID

4.3 Algorithmic flowchart of Task3_CAN_send

The flowchart describes the process of sending throttle position feedback (tps1_percent) from ESP32#2 to ESP32#1 via the CAN bus

• The value of tps1_percent is duplicated and stored in both halves of the CAN message payload (4 bytes each, totaling 8 bytes)

• The message is labeled with CAN ID 0x200 to indicate that it contains feedback data

• Once the message is constructed, it is transmitted through the MCP2515 CAN controller to ESP32#1, where the data can be displayed on the GUI

Duplicating tps1_percent may serve as a redundancy check or for consistency verification on the receiving side

Figure 33: Flowchart algorithm of Task3_CAN_send

RESULTS AND EVALUATION

Determining the output voltage signal parameters of the position sensor

The Throttle Position Sensor (TPS) is a vital component in the engine control system that accurately measures the throttle valve's opening position It plays a crucial role in engine performance by providing precise data to the vehicle’s electronic control unit (ECU) The TPS typically includes two signal lines, VTA1 and VTA2, which output voltage signals that correspond to the mechanical position of the throttle Proper functioning of the TPS is essential for optimal engine response, fuel efficiency, and smooth acceleration.

However, in practical operation, only the VTA1 signal reliably reflects the full range of the throttle valve’s movement

The VTA1 signal varies linearly with the throttle opening, providing an accurate measure from fully closed to fully open positions, making it essential for precise throttle position feedback control In contrast, the VTA2 signal does not maintain a linear relationship with throttle position and peaks around 4.98 V before the throttle is fully open, rendering it unsuitable for accurate feedback control applications.

When the throttle is fully closed, the VTA1 signal output is approximately 0.4 V, while fully open throttle results in a maximum voltage of about 2.32 V This linear and precise voltage behavior makes VTA1 the ideal feedback signal for electronic throttle control systems, ensuring accurate and reliable throttle position monitoring.

Motor controlling via GUI

The Graphical User Interface (GUI) is a crucial interface that connects users with the embedded electronic throttle control system, providing an intuitive platform for monitoring and controlling the throttle motor It communicates with the ESP32 microcontroller via a serial COM port (UART interface), enabling seamless two-way data exchange This bidirectional communication allows the GUI to send control parameters while receiving real-time feedback, ensuring precise system operation and user oversight.

Figure 34: GUI for motor controlling

Users can intuitively control the throttle motor through a user-friendly graphical user interface (GUI), which features an interactive slider and input field to set the desired throttle opening percentage Adjusting the throttle setting via the GUI triggers real-time data transmission to the ESP32 microcontroller through the COM port, ensuring precise and seamless motor control This innovative setup simplifies throttle management, making it accessible and efficient for users while optimizing device performance.

The interface features input fields for PID controller parameters (Kp, Ki, and Kd), enabling real-time tuning to optimize system responsiveness and stability across various load and operational conditions It also allows users to set and transmit the motor rotation direction (open or close) as part of the control data, ensuring precise and adaptable motor control.

What makes this system particularly effective is its visual feedback capability

The GUI displays real-time throttle opening percentage readings from the Throttle Position Sensor (TPS), enabling users to compare desired and actual throttle values instantly This closed-loop feedback system ensures that the motor responds correctly to control commands, providing immediate confirmation of proper operation.

To further enhance usability and system transparency, the GUI includes two real- time dynamic charts These plots display voltage signals from the Accelerator Pedal

The Sensor (APS) and Throttle Position Sensor (TPS) are essential for monitoring vehicle throttle performance over time The APS chart displays the driver’s input or throttle demand, while the TPS chart shows the motor’s actual mechanical response Analyzing these synchronized plots helps users assess system performance and ensures that the motor control logic operates correctly, enhancing vehicle efficiency and reliability.

The GUI simplifies complex control operations by providing a visually intuitive environment, allowing users to interact effortlessly without needing in-depth hardware knowledge Featuring real-time graphs, live feedback, and adjustable control parameters, it serves as a powerful tool for experimentation, diagnostics, and system evaluation This direct and visual approach to motor control makes the GUI ideal for development, educational demonstrations, and prototype testing.

Model 3D via GUI

Figure 35: Understand the overview about ETC system

To enhance user understanding of the electronic throttle control system, the GUI features an integrated 3D model visualization that offers an interactive, comprehensive view of the throttle actuator’s physical structure and internal components Users can freely rotate, zoom, and pan the 3D model to explore the entire system or focus on specific parts in detail, providing a clearer and more intuitive understanding of the system's design and functionality.

A 3D representation effectively bridges the gap between software and hardware by providing a clear visual overview of how the control system physically operates This detailed model includes essential mechanical components such as the DC motor, gear transmission assembly, return spring, throttle valve, and throttle position sensor (TPS), all accurately scaled and positioned to mirror real-world assembly By offering this realistic visualization, users can better understand the dynamic interactions between electrical signals and mechanical movements within the system.

The DC motor serves as the primary actuator responsible for adjusting the position of the throttle valve, as clearly depicted in the model It is connected to the gear set, enabling precise control of the throttle system Observing how the motor drives the gear mechanism provides insight into its crucial role in system operation and responsiveness.

The gear transmission system, demonstrated through a moving gear assembly, illustrates how motor torque is accurately converted and transferred to rotate the throttle shaft This process highlights essential functions such as speed reduction and torque amplification, providing a clear understanding of how gear systems optimize power transfer in mechanical applications.

• Return Spring Mechanism: The model includes a visible return spring, which acts to bring the throttle back to its default (closed) position when power is removed, providing fail-safe functionality

The throttle valve is a crucial component that controls the amount of air entering the engine Users can see the throttle valve in action, with animations illustrating its opening and closing movements in response to control inputs from the GUI This visual representation helps users understand how the throttle valve regulates airflow to optimize engine performance.

The Throttle Position Sensor (TPS) plays a crucial role in vehicle performance by monitoring the position of the throttle valve It is mechanically connected to the throttle shaft and accurately transmits the current valve angle to the engine control system This sensor's data is essential for optimizing fuel injection and maintaining efficient engine operation Proper functioning of the TPS ensures smooth acceleration, improved fuel efficiency, and reduced emissions.

Integrating 3D modeling into the GUI transforms the system from a simple control and monitoring tool into an educational platform, enhancing understanding of complex mechanisms This innovative approach is particularly valuable for students, engineers, and researchers seeking to visualize real-time relationships between control signals, mechanical movements, and sensor feedback By offering an interactive and immersive experience, the system promotes better learning and more effective analysis of mechanical and control systems.

The 3D interface enhances system transparency by offering an immersive, interactive learning experience, enabling users to intuitively understand how input signals—such as desired throttle position—are converted into actual mechanical motion.

Survey on the influence of Ki, Kp, Kd coefficients on control response via

Figure 36: System response with different Kp values

If the proportional gain is set too low, the controller will react sluggishly and may fail to respond effectively to changes or disturbances On the other hand, if the

4.1 Kp coefficient

proportional gain is too high, the system may become unstable, leading to oscillations or erratic behavior

The proportional term, also known as the "gain," plays a crucial role in control systems by adjusting the controller’s output proportionally to the current error Governed by the proportional gain constant (Kp), this response aims to reduce the present error effectively By applying a correction scaled to the error value, the proportional term helps improve system accuracy and stability.

A high Kp value means that even a small error results in a large output adjustment, which can make the system overly aggressive and lead to instability Conversely, a low

A small proportional gain (Kp) produces limited output even during significant errors, leading to sluggish system response and subpar tracking performance Consequently, the controller may fail to react effectively to external disturbances, decreasing the system's sensitivity and overall operational effectiveness.

Therefore, careful tuning of the proportional gain is essential to ensure a balanced response one that is both responsive and stable

Figure 37: System response with different Ki values

The integral component, also known as the reset action, plays a crucial role in control systems by generating an output influenced by both the magnitude and duration of the error It operates by calculating the cumulative sum of the error over time, known as the integral of the error, which highlights the accumulated offset not corrected by previous control efforts This integrated error is multiplied by the integral gain constant, Ki, and added to the controller’s output, effectively reducing long-term steady-state error and enhancing system accuracy.

The integral component, when combined with the proportional term, enhances the system's ability to reach the setpoint more effectively and eliminates residual steady-state errors that proportional control alone cannot correct However, because the integral term accumulates past errors, it can cause the system to overshoot the target value, leading to transient deviations in the opposite direction This phenomenon, known as "integral wind-up," underscores the importance of proper PID tuning for optimal control performance.

Ki value to balance correction speed and stability

Figure 38: System response with different Kd values

The rate at which process error changes is determined by calculating the slope of the error over time, known as the first derivative of the error with respect to time This derivative, when multiplied by the derivative gain (Kd), generates the derivative control signal The influence of this derivative action plays a crucial role in providing predictive control to improve system stability and response.

61 as the “rate” or “velocity” term) across all control behavior is governed by the value of

The derivative term in a control system functions by reducing rapid fluctuations in the controller's output, which helps smooth the response as the system approaches the desired setpoint This feature makes it especially effective at minimizing overshoot, a common issue caused by the integral component By dampening sudden changes, the derivative term plays a crucial role in improving the stability and reliability of the entire control loop, ensuring more accurate and consistent system performance.

The derivative component in control systems inherently amplifies high-frequency signals, making it highly sensitive to noise in the error signal Excessively high noise levels or large Kd gains can cause system instability, emphasizing the need for practical mitigation strategies To address this, engineers often implement approximations of pure derivative action using approaches like phase-lead compensators or filtered derivative circuits These techniques help strike a balance between responsiveness and robustness, ensuring stable and effective system performance.

A Proportional-Integral-Derivative (PID) controller optimizes system performance by calculating its output through the combined effect of three key components: proportional, integral, and derivative terms Each term plays a vital role in minimizing control error and ensuring system stability over time The control signal, represented as 𝑢(𝑡), guides the system towards the desired setpoint efficiently The standard PID control law can be expressed mathematically to showcase how these components work together to achieve precise process control.

1 𝑒(𝑡) is the error at time t (the difference between the desired value and the actual system output)

2 Kp is the proportional gain

3 Ki is the integral gain

4 Kd is the derivative gain

Each gain plays a unique role:

Proportional gain (Kp) is a key parameter that produces a control output directly proportional to the current error, influencing the system's responsiveness A higher Kp results in a more aggressive reaction, enabling faster correction of errors, but setting it too high can cause the system to become overly sensitive and oscillate, risking instability Conversely, a low Kp leads to a sluggish response, making the controller less effective at correcting errors promptly Optimizing Kp is essential for achieving a balanced and stable control system performance.

Integral gain (Ki) is responsible for addressing accumulated error over time by integrating the error signal and applying corrections based on the total historical error This feature enables the controller to eliminate steady-state error and ensure the system output eventually aligns with the setpoint However, setting Ki too high can lead to excessive overshoot and sustained oscillations, as the controller continues to apply correction even after the error changes sign Proper tuning of Ki is essential to balance responsiveness and stability in the control system.

Derivative gain (Kd) anticipates future trends by reacting to the rate of change of the error, providing a damping effect that reduces overshoot and improves system stability However, a high derivative gain can amplify measurement noise, causing erratic control actions To mitigate this, the derivative term is often filtered using low-pass techniques or approximated with phase-lead compensation, ensuring more stable and reliable control performance.

A PID controller combines proportional, integral, and derivative terms to provide a powerful and flexible solution for closed-loop control systems Proper tuning of Kp, Ki, and Kd is essential for achieving optimal performance, balancing quick response, minimal overshoot, and long-term accuracy When correctly adjusted, a PID controller can adapt to diverse dynamic systems, ensuring smooth and reliable control behavior.

CONCLUSION

GRAPHICAL USER INTERFACE - Windows Forms (C# - Visual Studio)

The user interface, developed using Windows Forms in C# with Visual Studio, is organized into several main sections The first section is the COM port module, which facilitates serial communication with ESP32 #1 by allowing users to select the appropriate port and manage the connection for seamless data exchange.

The second section is the parameter control panel, where users can input and send values such as desired throttle, PID coefficients (Kp, Ki, Kd), and motor direction

To the right, two real-time charts visualize the relationship between APS

(Accelerator Pedal Sensor) and TPS (Throttle Position Sensor) voltages over time, helping users monitor and analyze the system's performance

1 UART Communication Module via COM Port

This module allows the user to establish a serial connection between the GUI and ESP32

#1 using the UART protocol It includes several essential features for flexible and reliable communication:

• A COM port selection dropdown to choose the appropriate serial port detected on the system

• A baud rate selector to match the communication speed with the ESP32 (e.g.,

• A Reload button to refresh and detect newly available COM ports without restarting the application

• Connect and Disconnect buttons to initiate or terminate the UART communication as needed

This section ensures stable and user-controlled data transmission between the PC and the embedded system, forming the foundation for real-time interaction

2 Control Parameter Adjustment and Update Panel

Figure 41: Parameter Adjustment and Update Panel

The Control Parameter Adjustment and Update Panel offers a user-friendly interface for configuring and updating the system's main control inputs Users can easily set the desired throttle opening percentage, fine-tune PID controller coefficients (Kp, Ki, Kd), and select the motor rotation direction according to the current operating mode This panel facilitates precise control and optimal system performance through intuitive parameter adjustments.

After adjusting the values, the panel transmits the updated data via UART to ESP32#1, which relays the parameters through the CAN bus to the processing controller Meanwhile, the panel updates the APS (Accelerator Pedal Sensor) chart in real time, enabling users to monitor throttle input changes over time and observe their impact on the control system's performance.

This section plays a critical role in PID tuning and in observing the system’s response to various control inputs

3 Real-Time Chart Visualization Module

Figure 42: APS and TPS chat with respect to time

The Real-Time Chart Visualization Module enables users to monitor system performance dynamically by displaying two essential signals: the desired throttle position from the Accelerator Pedal Sensor (APS) and the actual throttle position measured by the Throttle Position Sensor (TPS) These signals are shown simultaneously on two separate, continuously updating line charts, providing real-time insights into system behavior over time This module is vital for diagnosing system performance and ensuring optimal operation in automotive applications.

By analyzing these charts, users can visually monitor how the throttle valve responds to user input and evaluate the system’s accuracy in reaching the target position The direct comparison between APS and TPS signals offers an intuitive understanding of the system’s responsiveness and consistency, making it especially useful for testing and demonstrations This overview helps ensure optimal throttle control performance and system reliability.

The 3D Model Display Module provides an interactive, detailed visualization of the Electronic Throttle Control (ETC) system’s internal structure, allowing users to gain a comprehensive understanding of its operation This module features a dynamic 3D view of key components, including a complete model of the throttle system that highlights major parts for better insights Designed to enhance technical knowledge, the 3D visualization helps users explore the ETC system's internal mechanisms effectively.

• Throttle Body: The main enclosure that houses the internal components

• Throttle Valve: The adjustable element that regulates airflow into the engine

• DC Motor: The electric motor responsible for actuating the throttle valve

• Transmission Mechanism: The linkage or drive system that connects the motor to the throttle valve, ensuring precise movement

• Return Spring: The spring mechanism that helps bring the throttle valve back to its default position when not actively driven

Users can rotate, zoom, and pan around the model to explore components from multiple angles, enhancing understanding of the mechanical layout and system interactions This interactive visual tool bridges the gap between theoretical design and practical implementation, aiding engineers, students, and researchers in comprehending the complex interplay of ETC system elements.

5 PID Coefficient Influence Monitoring Section

This section offers an intuitive, visual explanation of how each PID coefficient—proportional (Kp), integral (Ki), and derivative (Kd)—influences the throttle control system’s behavior Understanding the role of Kp helps optimize responsiveness, while Ki corrects steady-state errors over time Kd predicts system behavior, preventing overshoot and improving stability By analyzing these effects, users can fine-tune PID settings for precise and stable throttle control performance.

This module enables users to evaluate critical performance metrics like response speed, overshoot, steady-state error, and system stability by continuously displaying the differences between APS (Accelerator Pedal Sensor) and TPS (Throttle Position Sensor) over time Users can adjust PID parameters in real time via the GUI and instantly observe how these modifications influence the system’s accuracy in following the desired throttle position, enhancing calibration precision and overall control performance.

This section is essential for tuning, testing, and educational purposes, as it visualizes the control loop in action and demonstrates the impact of each gain component It enhances understanding of control theory and aids in achieving optimal system performance.

Windows Form C# Program

This article introduces a comprehensive GUI multi-task application developed using C# and various NET libraries The program leverages essential namespaces such as System, System.Collections.Generic, and System.Drawing for core functionalities, along with System.IO.Ports for serial port communication, and System.Windows.Forms for creating user-friendly interfaces It integrates data visualization features utilizing System.Windows.Forms.DataVisualization.Charting to display dynamic charts, and employs HelixToolkit.Wpf for advanced 3D graphics rendering within WPF applications The application's modular design emphasizes efficient multitasking capabilities, seamlessly combining 2D and 3D visualization components to enhance user interaction and data analysis.

{ public partial class FormETC : Form

This article discusses the implementation of a serial communication system using a SerialPort object, with a Timer set to a 50-millisecond interval to handle data processing It emphasizes the importance of buffering incoming serial data efficiently using a byte list to ensure accurate packet reception, specifically with a packet size of 13 bytes The system tracks operational metrics such as start time, connection status, and whether a chart has begun, to facilitate real-time data visualization Key control parameters like desired throttle, PID controller coefficients (_kp, _ki, _kd), and directional controls are configured to optimize performance Additionally, sensors and voltage readings—including TPS (Throttle Position Sensor), APS (Aircraft Position Sensor), and related voltage measurements—play a critical role in monitoring the vehicle's state and ensuring precise control.

PID performance metrics are essential for evaluating control system effectiveness, including parameters such as error, maximum overshoot, settling time, and steady-state error Monitoring these metrics ensures the system maintains desired performance, with variables like error history and last desired throttle providing insights into control stability Key thresholds, such as the settling threshold of 5.0 and a settling window of 2.0 seconds, are used to determine when the system has stabilized, enhancing overall control accuracy and responsiveness.

FormClosing += FormETC_FormClosing; parameters_tableLayout.Enabled = false; actual_tableLayout.Enabled = false; pid_tableLayoutPanel1.Enabled = false;

{ combox.Items.Clear(); string[] ports = SerialPort.GetPortNames(); combox.DataSource = ports.Length > 0 ? ports : new[] { "No COM ports found" };

{ var viewer = new MyDrawings(); var host = new ElementHost { Dock = DockStyle.Fill, Child = viewer }; tab3D.Controls.Add(host);

{ var component = new ComponentViewer(); var host = new ElementHost { Dock = DockStyle.Fill, Child = component }; tab_component.Controls.Add(host);

} private void conbut_Click(object sender, EventArgs e)

{ if (_serialPort.IsOpen) return; try

_serialPort.PortName = combox.SelectedItem.ToString();

_serialPort.BaudRate = int.Parse(comboxBaurate.Text);

_serialPort.Open(); if (_serialPort.IsOpen)

MessageBox.Show($"Connected to {_serialPort.PortName} successfully!",

"Connected", MessageBoxButtons.OK, MessageBoxIcon.Information); parameters_tableLayout.Enabled = true; actual_tableLayout.Enabled = true; pid_tableLayoutPanel1.Enabled = true;

MessageBox.Show($"Connection failed: {ex.Message}", "Error",

} private void enterbut_Click(object sender, EventArgs e)

MessageBox.Show("Please connect to a COM port first.", "Warning",

MessageBoxButtons.OK, MessageBoxIcon.Warning); return;

The article demonstrates how to parse user input from text boxes for configurable parameters such as desired throttle, PID controller gains (KP, KI, KD), and direction using the `float.TryParse` method in C# It highlights the process of checking if the setpoint has changed by comparing the new throttle value with the previous one, as well as determining if any PID controller parameters have been modified by comparing the new values with existing settings Implementing these parsing and comparison steps ensures accurate updates to control parameters, which is essential for maintaining optimal system performance in applications like motor control or automation systems Properly handling user input and change detection enhances the robustness and responsiveness of automated control processes.

_serialPort.Write(BuildPacket(), 0, ReceivePacketSize + 12); if (setpointChanged || pidChanged)

_lastSetpointChangeTime = (DateTime.Now - _startTime).TotalSeconds; _lastDesiredThrottle = _desiredThrottle;

UpdateCharts(); if (!_timer.Enabled) _timer.Start();

MessageBox.Show($"Error sending data: {ex.Message}", "Error",

{ var packet = new List

The code snippet demonstrates how to construct a data packet by adding serialized values of parameters such as _desiredThrottle, _kp, _ki, _kd, and _direction using BitConverter.GetBytes() It appends carriage return and newline characters to the packet to denote the end of the data stream, ensuring proper formatting for transmission This process is essential for preparing control data in robotics or embedded systems, emphasizing the importance of accurate data serialization and protocol adherence Proper packet assembly facilitates reliable communication between devices, highlighting best practices for data transmission in networked systems.

} private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)

{ byte[] tempBuffer = new byte[_serialPort.BytesToRead];

_serialPort.Read(tempBuffer, 0, tempBuffer.Length); if (IsHandleCreated && !IsDisposed)

MessageBox.Show($"Error receiving data: {ex.Message}", "Error",

{ int startIdx = _serialBuffer.FindIndex(x => x == 'S'); if (startIdx < 0 || _serialBuffer.Count < startIdx + ReceivePacketSize) break; if (_serialBuffer[startIdx] == 'S' && _serialBuffer[startIdx + 1] == 'T' &&

{ byte[] packet _serialBuffer.Skip(startIdx).Take(ReceivePacketSize).ToArray();

_errorHistory.Add(Math.Abs(_error)); if (_tps1 > _desiredThrottle)

_maxOvershoot = Math.Max(currentOvershoot, _maxOvershoot);

} double currentTime = (DateTime.Now - _startTime).TotalSeconds; if (!_isSettled && currentTime - _lastSetpointChangeTime > 0.5)

{ if (Math.Abs(_error) (Error: err, Time: (i + 1) * 0.2))

All(x => x.Error new { Error = err, Time = currentTime - (i + 1) * 0.2 }) Where(x => x.Time >= windowStartTime)

_steadyStateError = recentErrors.Any() ? (float)recentErrors.Average() : 0; } errorBox.Text = $"{_error:F2}%"; overshootBox.Text = $"{_maxOvershoot:F2}%"; settlingTimeBox.Text = $"{_settlingTime:F2}s"; steadyStateErrorBox.Text = $"{_steadyStateError:F2}%";

This article highlights key parameters in a control system, including desired throttle, direction, and PID controller gains, such as Kp, Ki, and Kd It emphasizes the importance of monitoring throttle positions via TPS1 and TPS2 sensors, along with actual throttle status and desired APS values The system's error percentage, maximum overshoot, settling time, and steady-state error are essential metrics for evaluating performance and stability, ensuring optimal operation in drone or vehicle control applications Properly displaying these parameters helps optimize system responsiveness and accuracy.

} private void StopCommunication(bool resetUI = true)

_isChartStarted = false; if (_serialPort.IsOpen)

Console.WriteLine($"Error closing port: {ex.Message}");

{ parameters_tableLayout.Enabled = false; actual_tableLayout.Enabled = false; pid_tableLayoutPanel1.Enabled = false;

LoadComPorts(); combox.SelectedIndex = -1; comboxBaurate.SelectedItem = "115200"; track_aps.Value = 0;

} private void reloadbut_Click(object sender, EventArgs e) => FullReset(); private void disconbut_Click(object sender, EventArgs e) => FullReset(); private void FormETC_FormClosing(object sender, FormClosingEventArgs e) { if (_serialPort.IsOpen || _timer.Enabled)

MessageBox.Show("Please disconnect before closing the form!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); e.Cancel = true;

{ track_aps.Minimum = 0; track_aps.Maximum = 1000; track_aps.TickFrequency = 50; track_aps.TickStyle = TickStyle.BottomRight; track_aps.Scroll += track_aps_Scroll; desirebox.KeyDown += textboxforAPS_KeyDown;

} private void track_aps_Scroll(object sender, EventArgs e)

{ double trackValue = track_aps.Value / 10.0; desirebox.Text = trackValue.ToString("F2");

} private void textboxforAPS_KeyDown(object sender, KeyEventArgs e)

{ if (e.KeyCode != Keys.Enter) return; e.SuppressKeyPress = true; if (float.TryParse(desirebox.Text, out float desiredValue) && desiredValue >= 0

{ track_aps.Value = (int)(desiredValue * 10);

UpdateCharts(); if (!_timer.Enabled) _timer.Start();

MessageBox.Show("Value must be a number between 0 and 100%", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);

} private float MapTrackbarToVoltageAPS1(float value) => 0.33f + (value / 100.0f) * (2.13f - 0.33f); private float MapTrackbarToVoltageAPS2(float value) => 0.7f + (value / 100.0f) * (4.22f - 0.7f);

87 private float MapPercentageToVoltageTPS1(float percentage) => 0.7f +

(percentage / 100.0f) * (4.315f - 0.7f); private float MapPercentageToVoltageTPS2(float percentage) => 2.44f +

} double elapsedSeconds = (DateTime.Now - _startTime).TotalSeconds;

This code snippet maps the TPS1 percentage to voltage for TPS2, enabling accurate data visualization It plots real-time voltage readings for APS1 and APS2 on Chart 1, while Chart 2 displays throttle voltages for TPS1 and TPS2, providing a comprehensive view of engine response The PID chart visualizes both desired and actual throttle openings over time, helping monitor throttle control precision Additionally, the code includes a condition to maintain chart performance by limiting the number of data points to 3,000 This approach ensures efficient real-time graph updates for automotive throttle and sensor data analysis.

{ chart1.Series["APS1"].Points.RemoveAt(0); chart1.Series["APS2"].Points.RemoveAt(0);

88 chart2.Series["TPS1"].Points.RemoveAt(0); chart2.Series["TPS2"].Points.RemoveAt(0); pid_chart.Series["Desired Throttle Opening"].Points.RemoveAt(0); pid_chart.Series["Actual Throttle Opening"].Points.RemoveAt(0);

} chart1.Invalidate(); chart2.Invalidate(); pid_chart.Invalidate();

Clear all data points from the "APS1" and "APS2" series in Chart1, as well as from the "TPS1" and "TPS2" series in Chart2, to ensure accurate and updated visualization Additionally, reset the "Desired Throttle Opening" and "Actual Throttle Opening" series in the PID chart for precise control analysis Regularly clearing chart series helps maintain data accuracy and improves the clarity of performance monitoring.

} private void Timer_Tick(object sender, EventArgs e) => UpdateCharts(); private void ResetPidMetrics()

89 chart1.Series.Clear(); chart1.ChartAreas.Clear(); chart1.Titles.Clear(); var area = new ChartArea("MainArea")

AxisX = { Title = "Time (s)", LabelStyle = { Format = "0.0", Angle = 0 }, MajorGrid = { LineColor = Color.LightGray } },

AxisY = { Title = "Voltage (V)", Minimum = 0, Maximum = 5, MajorGrid = { LineColor = Color.LightGray } }

}; chart1.ChartAreas.Add(area); chart1.Titles.Add(new Title("APS value w.r.t time", Docking.Top, new

To create an informative line chart, add multiple data series such as "APS1" and "APS2" with distinct colors—red and blue—for clear differentiation Setting the chart type to Line and customizing attributes like border width enhance visual clarity Inputting specific data points, such as (0, 0.33) for APS1 and (0, 0.7) for APS2, ensures accurate data representation Using these techniques optimizes your chart's readability and SEO relevance for data visualization content.

{ chart2.Series.Clear(); chart2.ChartAreas.Clear(); chart2.Titles.Clear(); var area = new ChartArea("MainArea")

AxisX = { Title = "Time (s)", LabelStyle = { Format = "0.0", Angle = 0 }, MajorGrid = { LineColor = Color.LightGray } },

AxisY = { Title = "Voltage (V)", Minimum = 0, Maximum = 5, MajorGrid = { LineColor = Color.LightGray } }

}; chart2.ChartAreas.Add(area); chart2.Titles.Add(new Title("TPS value w.r.t time", Docking.Top, new

Create a line chart using the Arial font with a size of 14 and bold style, set to black color for clarity Add two data series named "TPS1" and "TPS2" with distinct colors—red and blue respectively—and a border width of 2 for visual emphasis Populate the chart with initial data points at coordinates (0, 0.7) for TPS1 and (0, 2.44) for TPS2 to effectively display comparative performance trends.

{ pid_chart.Series.Clear(); pid_chart.ChartAreas.Clear(); pid_chart.Titles.Clear(); var area = new ChartArea("PIDArea")

AxisX = { Title = "Time (s)", LabelStyle = { Format = "0.0" }, MajorGrid = { LineColor = Color.LightGray } },

AxisY = { Title = "Throttle Opening (%)", Minimum = 0, Maximum = 100, MajorGrid = { LineColor = Color.LightGray } }

The article discusses how to visualize the comparison between desired and actual throttle openings using a chart It explains that a chart area is added to the plot and titled "Desired vs Actual Throttle" to clearly indicate the chart's purpose The visualization includes two line series: one representing the "Desired Throttle Opening" in blue and the other showing the "Actual Throttle Opening" in red, both with a border width of 3 for enhanced clarity This approach helps in analyzing throttle performance effectively, making it a valuable tool for monitoring and optimizing engine control systems.

91 pid_chart.Series["Desired Throttle Opening"].Points.AddXY(0, 0); pid_chart.Series["Actual Throttle Opening"].Points.AddXY(0, 0);

• Defines the FormETC class, a Windows Forms application for controlling and monitoring a system via serial communication

• Declares a SerialPort object for communication, a Timer for periodic updates, and a buffer for incoming serial data

• Includes variables for throttle (_desiredThrottle, _tps1, _tps2), PID parameters (_kp, _ki, _kd), direction, voltages, and PID metrics (error, overshoot, settling time, steady-state error)

• Uses constants for packet size and PID thresholds

• Initializes the form, loads available COM ports, sets up charts, configures trackbar and textbox, and loads 3D model and component viewer

• Disables UI controls (parameters_tableLayout, actual_tableLayout, pid_tableLayoutPanel1) until connected

• Attaches event handlers for form closing and timer ticks

• Clears and populates the COM port dropdown with available ports

• Sets baud rate options and defaults to 115200

• Calls functions to set up APS, TPS, and PID charts, resets parameters, and clears chart-start flag

• Adds a 3D model viewer (MyDrawings) to the tab3D control using ElementHost

• Adds a component viewer (ComponentViewer) to the tab_component control using ElementHost

• Creates a component viewer (ComponentViewer) and embeds it in the tab_component control using an ElementHost for full docking, displaying additional visual components

The application attempts to open the selected COM port at the specified baud rate, establishing a reliable serial communication link Upon successful connection, it attaches a data-received event handler to handle incoming data efficiently and enables UI controls to allow user interaction If the connection fails, the system displays clear error messages to inform users of the issue, ensuring a smooth troubleshooting process.

The system parses user input from textboxes to configure throttle, PID parameters, and direction settings If a serial connection is established, it sends a control packet accordingly When PID parameters are updated, the system resets the PID metrics to ensure accurate control Additionally, it updates the real-time charts to reflect current data and initiates a timer to manage ongoing processes, ensuring smooth and responsive operation.

• Constructs a 25-byte packet starting with "STA", followed by throttle, PID parameters, direction, and ending with "\r\n" for serial transmission

• Reads incoming serial data into a temporary buffer, adds it to _serialBuffer, and invokes ParseSerialData on the UI thread to process the data safely

• Searches for valid 13-byte packets starting with "STA" and ending with "\r\n" Extracts tps1 and tps2, updates textboxes, calculates PID metrics, and removes processed data from the buffer

The system calculates the error between the desired and actual throttle positions, monitors overshoot behavior, and determines the settling time once the error stabilizes within a specified threshold Additionally, it computes the steady-state error by averaging recent error values, providing accurate performance insights The results, including error metrics, overshoot, and settling time, are then displayed in user interface textboxes for real-time monitoring and analysis.

• Resets throttle, PID parameters, direction, voltages, and PID metrics to default values, clears error history, and updates textboxes

• Updates textboxes with current values of throttle, direction, PID parameters, TPS values, and PID metrics, formatted for readability

• Stops the chart, closes the serial port, and optionally disables UI controls to halt communication

• Closes the serial port, stops the timer, clears charts and buffer, resets parameters, reinitializes charts, reloads COM ports, and resets UI controls

17 Reloadbut_Click and disconbut_Click

• Both buttons trigger FullReset to reset the application to its initial state

• Prevents form closure if the serial port or timer is active, showing a warning Calls FullReset if closure is allowed

• Configures the trackbar with a 0–1000 range and attaches event handlers for trackbar scrolling and textbox key presses to handle user input

• Updates the throttle textbox with the trackbar value, scaled to 0–100 with two decimal places

• Handles Enter key presses in the throttle textbox, validates input (0–100), updates the trackbar and throttle value, and triggers chart updates

• Converts throttle percentages to voltage values for APS1, APS2, TPS1, and TPS2 using linear mapping formulas for chart plotting

• Records elapsed time, maps throttle/TPS values to voltages, adds data points to APS, TPS, and PID charts, removes old points if exceeding 3000, and refreshes charts

• Clears all data points from APS, TPS, and PID charts to reset their display

• Calls UpdateCharts every 50ms to refresh the charts with new data

• Resets PID metrics (error, overshoot, settling time, steady-state error), clears error history, and updates textboxes

• Sets up the APS chart with time (X-axis) and voltage (Y-axis, 0–5V), adds APS1 and APS2 series, and initializes with starting points

• Sets up the TPS chart with time (X-axis) and voltage (Y-axis, 0–5V), adds TPS1 and TPS2 series, and initializes with starting points

• Sets up the PID chart with time (X-axis) and throttle opening (Y-axis, 0–100%), adds Desired and Actual Throttle series, and initializes with starting points

Microcontroller Program of ESP32#1

// Pin definitions const int CAN_INT_PIN = 4; const int CAN_CS_PIN = 5;

The system operates with specific timing intervals to ensure efficient communication: TASK1, responsible for receiving data from the GUI, runs every 40 milliseconds; TASK2, handling CAN transmission, executes every 20 milliseconds; TASK3, dedicated to CAN reception, also occurs every 20 milliseconds; and TASK4, which sends data back to the GUI, is scheduled every 40 milliseconds These carefully defined intervals optimize data exchange and maintain synchronization within the embedded system.

The code initializes the MCP2515 CAN controller with `MCP2515 mcp2515(CAN_CS_PIN);` and sets up CAN message structures `canMsgTx` and `canMsgRx` for transmitting and receiving data A `serialBuffer` array of 25 bytes is used for serial communication The variables `apsPercent`, `Kp`, `Ki`, and `Kd` are defined for sensor readings and PID control parameters, while `direction`, `tps1`, and `tps2` manage motor control and throttle position sensing A `volatile` boolean `messageAvailable` signals the presence of new CAN messages The code also tracks timing for multiple tasks with `previousTask1Millis` through `previousTask4Millis` to manage task intervals efficiently, ensuring smooth real-time operation of the system.

// Interrupt handler for CAN messages void IRAM_ATTR onCANMessage() {

// Initialize hardware and communication void setup() {

SPI.begin(); mcp2515.reset(); mcp2515.setBitrate(CAN_500KBPS, MCP_8MHZ); mcp2515.setNormalMode(); pinMode(CAN_INT_PIN, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(CAN_INT_PIN), onCANMessage, FALLING); }

// Task 1: Receive data from GUI over Serial void taskReceiveGUI() { static uint8_t index = 0; while (Serial.available()) { uint8_t byteIn = Serial.read(); if (index < sizeof(serialBuffer)) { serialBuffer[index++] = byteIn;

} if (index == sizeof(serialBuffer)) { if (serialBuffer[0] == 'S' && serialBuffer[1] == 'T' && serialBuffer[2] == 'A'

&& serialBuffer[23] == '\r' && serialBuffer[24] == '\n') { memcpy(&apsPercent, &serialBuffer[3], sizeof(float)); memcpy(&Kp, &serialBuffer[7], sizeof(float)); memcpy(&Ki, &serialBuffer[11], sizeof(float)); memcpy(&Kd, &serialBuffer[15], sizeof(float)); memcpy(&direction, &serialBuffer[19], sizeof(int));

// Task 2: Transmit CAN messages void taskCANTransmit() {

// Frame 0x100: Throttle + Kp canMsgTx.can_id = 0x100; canMsgTx.can_dlc = 8; memcpy(canMsgTx.data, &apsPercent, sizeof(float)); memcpy(&canMsgTx.data[4], &Kp, sizeof(float)); mcp2515.sendMessage(&canMsgTx);

// Frame 0x101: Ki + Kd canMsgTx.can_id = 0x101; canMsgTx.can_dlc = 8; memcpy(canMsgTx.data, &Ki, sizeof(float)); memcpy(&canMsgTx.data[4], &Kd, sizeof(float)); mcp2515.sendMessage(&canMsgTx);

// Frame 0x102: Direction canMsgTx.can_id = 0x102; canMsgTx.can_dlc = 4; memcpy(canMsgTx.data, &direction, sizeof(int)); mcp2515.sendMessage(&canMsgTx);

// Task 3: Receive CAN messages void taskCANReceive() { if (messageAvailable) {

98 while (mcp2515.readMessage(&canMsgRx) == MCP2515::ERROR_OK) { if (canMsgRx.can_id == 0x200 && canMsgRx.can_dlc == 8) { memcpy(&tps1, canMsgRx.data, sizeof(float)); memcpy(&tps2, &canMsgRx.data[4], sizeof(float));

// Task 4: Send data to GUI over Serial void taskSendGUI() { uint8_t packet[13];

// Data memcpy(&packet[3], &tps1, sizeof(float)); memcpy(&packet[7], &tps2, sizeof(float));

Serial.write(packet, sizeof(packet));

// Main loop with non-blocking task scheduling void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousTask1Millis >= TASK1_INTERVAL) {

} if (currentMillis - previousTask2Millis >= TASK2_INTERVAL) { previousTask2Millis = currentMillis; taskCANTransmit();

} if (currentMillis - previousTask3Millis >= TASK3_INTERVAL) { previousTask3Millis = currentMillis; taskCANReceive();

} if (currentMillis - previousTask4Millis >= TASK4_INTERVAL) { previousTask4Millis = currentMillis; taskSendGUI();

• Purpose: Includes necessary libraries for communication

• SPI.h: Enables Serial Peripheral Interface (SPI) communication, used to interface with the MCP2515 CAN controller

• mcp2515.h: Provides functions to control the MCP2515 CAN module for sending and receiving CAN bus messages

• Explanation: These libraries are essential for enabling the Arduino to communicate with external devices via SPI and manage CAN bus

100 communication, which is critical for interfacing with automotive or industrial systems

2.2 Pin Definitions const int CAN_INT_PIN = 4; const int CAN_CS_PIN = 5;

• Purpose: Defines the pins used for the MCP2515 CAN module

• CAN_INT_PIN: Pin 4 is configured as an interrupt pin to detect incoming CAN messages

• CAN_CS_PIN: Pin 5 is the Chip Select pin for SPI communication with the MCP2515

These constants enhance code readability and maintainability by clearly defining hardware connections The interrupt pin enables the system to respond instantly to new CAN messages, thereby improving overall efficiency.

2.3 Timing Intervals const unsigned long TASK1_INTERVAL = 40; // Receive from GUI const unsigned long TASK2_INTERVAL = 20; // CAN transmit const unsigned long TASK3_INTERVAL = 20; // CAN receive const unsigned long TASK4_INTERVAL = 40; // Send to GUI

• Purpose: Defines the execution intervals (in milliseconds) for four main tasks in the program

• Task Intervals: o Task 1 (GUI receive): 40ms o Task 2 (CAN transmit): 20ms

101 o Task 3 (CAN receive): 20ms o Task 4 (GUI send): 40ms

These intervals are designed to ensure each task executes at a specific frequency, preventing system overloads and enabling real-time operation They balance the timing requirements of serial and CAN communication, maintaining efficient and reliable system performance.

The MCP2515 module is initialized with the CAN_CS_PIN, facilitating Controller Area Network communication The program defines can_frame structures for transmitting and receiving CAN messages, along with a serial buffer for data handling Key variables such as APS percentage, PID constants (Kp, Ki, Kd), and direction are declared to manage control parameters Sensor inputs like TPS1 and TPS2 are used for system monitoring, with a volatile boolean indicating the availability of new messages Multiple timestamp variables track task execution intervals to ensure precise timing in real-time operations, optimizing communication and control responsiveness.

• Purpose: Declares variables used throughout the program

• mcp2515: Object to control the MCP2515 CAN module

• canMsgTx, canMsgRx: Structures to store CAN messages for transmission and reception

• serialBuffer: Array to store incoming serial data from the GUI (25 bytes)

• apsPercent, Kp, Ki, Kd: Floating-point variables for throttle percentage and PID control parameters

• direction: Integer for motor or actuator direction

• tps1, tps2: Floating-point variables for throttle position sensor values

• messageAvailable: Volatile boolean to flag new CAN messages (used in interrupts)

• previousTaskXMillis: Timestamps to track the last execution time of each task

These variables store essential data for effective communication and control within the system The `volatile` keyword used for `messageAvailable` ensures safe handling in interrupt contexts, preventing compiler optimization issues Additionally, the timestamps facilitate non-blocking task scheduling, enhancing overall system efficiency and responsiveness.

2.5 Interrupt Handler void IRAM_ATTR onCANMessage() { messageAvailable = true;

• Purpose: Interrupt service routine (ISR) triggered when a new CAN message is received

• IRAM_ATTR: Ensures the function runs from RAM for faster execution (critical for interrupts)

• Functionality: Sets the messageAvailable flag to true, signaling the main loop to process incoming CAN messages

• Explanation: This interrupt handler allows the system to detect new CAN messages instantly, improving responsiveness The IRAM_ATTR attribute optimizes performance for time-sensitive operations

SPI.begin(); mcp2515.reset(); mcp2515.setBitrate(CAN_500KBPS, MCP_8MHZ); mcp2515.setNormalMode(); pinMode(CAN_INT_PIN, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(CAN_INT_PIN), onCANMessage, FALLING);

• Purpose: Initializes the system during startup

• Serial.begin(115200): Starts serial communication at 115200 baud rate for GUI interaction

• SPI.begin(): Initializes the SPI interface for communication with the MCP2515

• mcp2515.reset(): Resets the MCP2515 CAN controller

• mcp2515.setBitrate(CAN_500KBPS, MCP_8MHZ): Configures the CAN bus for 500 kbps speed with an 8 MHz clock

• mcp2515.setNormalMode(): Sets the MCP2515 to normal operation mode for sending/receiving CAN messages

• pinMode and attachInterrupt: Configures the CAN interrupt pin and attaches the interrupt handler

The setup function initializes the hardware and communication interfaces, ensuring the Arduino is prepared to interact seamlessly with the GUI and CAN bus The CAN bus is configured for high-speed communication, making it ideal for automotive applications where rapid data transfer is essential.

2.7.1 Task 1: Receive Data from GUI (taskReceiveGUI) void taskReceiveGUI() { static uint8_t index = 0; while (Serial.available()) { uint8_t byteIn = Serial.read(); if (index < sizeof(serialBuffer)) { serialBuffer[index++] = byteIn;

} if (index == sizeof(serialBuffer)) { if (serialBuffer[0] == 'S' && serialBuffer[1] == 'T' && serialBuffer[2] == 'A'

&& serialBuffer[23] == '\r' && serialBuffer[24] == '\n') { memcpy(&apsPercent, &serialBuffer[3], sizeof(float)); memcpy(&Kp, &serialBuffer[7], sizeof(float)); memcpy(&Ki, &serialBuffer[11], sizeof(float)); memcpy(&Kd, &serialBuffer[15], sizeof(float)); memcpy(&direction, &serialBuffer[19], sizeof(int));

• Purpose: Receives and processes data sent from the GUI over the serial port

This function efficiently reads incoming serial bytes into a buffer, continuously monitoring for a specific 25-byte packet format that begins with "STA" and ends with "\r\n" Once a valid packet is detected, it extracts critical parameters such as apsPercent, Kp, Ki, Kd, and direction using memcpy, ensuring precise data retrieval After successfully processing each valid packet, the buffer index is reset to prepare for the next set of serial data, maintaining seamless communication and data integrity.

This function allows the Arduino to receive control parameters from a GUI, including throttle percentage and PID constants, ensuring seamless communication The carefully designed packet format guarantees reliable data transfer between devices Additionally, the use of memcpy facilitates safe handling of binary data conversion, enhancing data integrity during transmission.

2.7.2 Task 2: Transmit CAN Messages (taskCANTransmit) void taskCANTransmit() {

// Frame 0x100: Throttle + Kp canMsgTx.can_id = 0x100; canMsgTx.can_dlc = 8; memcpy(canMsgTx.data, &apsPercent, sizeof(float)); memcpy(&canMsgTx.data[4], &Kp, sizeof(float)); mcp2515.sendMessage(&canMsgTx);

// Frame 0x101: Ki + Kd canMsgTx.can_id = 0x101; canMsgTx.can_dlc = 8; memcpy(canMsgTx.data, &Ki, sizeof(float));

106 memcpy(&canMsgTx.data[4], &Kd, sizeof(float)); mcp2515.sendMessage(&canMsgTx);

// Frame 0x102: Direction canMsgTx.can_id = 0x102; canMsgTx.can_dlc = 4; memcpy(canMsgTx.data, &direction, sizeof(int)); mcp2515.sendMessage(&canMsgTx);

• Purpose: Sends control data to external devices via the CAN bus

• Functionality: o Sends three CAN frames:

▪ ID 0x100: Contains apsPercent and Kp (8 bytes)

▪ ID 0x101: Contains Ki and Kd (8 bytes)

▪ ID 0x102: Contains direction (4 bytes) o Uses memcpy to copy data into the CAN frame's data field

This task transmits essential control parameters to devices such as ECUs or motor controllers via the CAN bus, ensuring efficient communication Utilizing multiple CAN IDs organizes data effectively, while a 500 kbps bitrate provides rapid data transfer, supporting real-time control.

2.7.3 Task 3: Receive CAN Messages (taskCANReceive) void taskCANReceive() { if (messageAvailable) { while (mcp2515.readMessage(&canMsgRx) == MCP2515::ERROR_OK) {

107 if (canMsgRx.can_id == 0x200 && canMsgRx.can_dlc == 8) { memcpy(&tps1, canMsgRx.data, sizeof(float)); memcpy(&tps2, &canMsgRx.data[4], sizeof(float));

• Purpose: Processes incoming CAN messages containing throttle position sensor data

The functionality includes checking the messageAvailable flag set by the interrupt handler, reading CAN messages, and specifically detecting messages with ID 0x200 that contain an 8-byte payload It extracts throttle position sensor values, tps1 and tps2, using memcpy for accurate data handling After processing the message, the system clears the messageAvailable flag to prepare for subsequent messages, ensuring efficient and reliable CAN communication.

This task involves receiving feedback data from external devices such as throttle position sensors through the CAN bus, facilitating seamless data exchange An interrupt-driven approach is employed to ensure the prompt processing of incoming messages, which is essential for maintaining real-time control system performance.

2.7.4 Task 4: Send Data to GUI (taskSendGUI) void taskSendGUI() { uint8_t packet[13];

// Data memcpy(&packet[3], &tps1, sizeof(float)); memcpy(&packet[7], &tps2, sizeof(float));

Serial.write(packet, sizeof(packet));

• Purpose: Sends throttle position sensor data to the GUI over the serial port

• Functionality: o Creates a 13-byte packet with a "STA" header, tps1, tps2, and "\r\n" footer o Uses memcpy to copy sensor data into the packet o Transmits the packet using Serial.write

• Explanation: This task provides feedback to the GUI, allowing users to monitor throttle position data in real-time The structured packet format ensures reliable communication with the GUI application

2.8 Main Loop (loop) void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousTask1Millis >= TASK1_INTERVAL) {

} if (currentMillis - previousTask2Millis >= TASK2_INTERVAL) { previousTask2Millis = currentMillis; taskCANTransmit();

} if (currentMillis - previousTask3Millis >= TASK3_INTERVAL) { previousTask3Millis = currentMillis; taskCANReceive();

} if (currentMillis - previousTask4Millis >= TASK4_INTERVAL) { previousTask4Millis = currentMillis; taskSendGUI();

• Purpose: Schedules and executes the four tasks in a non-blocking manner

• Functionality: o Uses millis() to track elapsed time o Executes each task when its interval has elapsed, updating the corresponding timestamp o Ensures tasks run independently without blocking each other

The main loop features a non-blocking scheduler that enables the system to manage multiple tasks simultaneously, including GUI communication, CAN transmission, and reception This design ensures real-time performance and optimal resource utilization, enhancing the efficiency and responsiveness of the system.

Microcontroller Program of ESP32#2

// Pin definitions const int INT_PIN = 4; const int VTA1_PIN = 32; const int VTA2_PIN = 33; const int PWM_PIN = 27; const int IN1_PIN = 25; const int IN2_PIN = 26;

// PWM configuration const int PWM_CHANNEL = 0; const int PWM_FREQ = 16000; const int PWM_RESOLUTION = 12;

// Task intervals (milliseconds) const unsigned long TASK1_INTERVAL = 10; // CAN receive const unsigned long TASK2_INTERVAL = 20; // PID and sensor read const unsigned long TASK3_INTERVAL = 40; // CAN send

MCP2515 mcp2515(5); struct can_frame canMsgRx, canMsgTx; volatile bool messageAvailable = false; unsigned long previousTask1Millis = 0; unsigned long previousTask2Millis = 0;

502 Bad GatewayUnable to reach the origin service The service may be down or it may not be responding to traffic from cloudflared

PID myPID(&tps1_pid, &pid_out, &apsPercent_pid, Kp_pid, Ki_pid, Kd_pid,

// Interrupt handler for CAN messages void IRAM_ATTR onCANMessage() { messageAvailable = true;

// Convert analog signal to voltage float analogToVoltage(int analogValue) { return analogValue * 3.3 / 4095.0;

// Map input value to a new range float mapValue(float input, float fromLow, float fromHigh, float toLow, float toHigh) { return toLow + ((input - fromLow) * (toHigh - toLow)) / (fromHigh - fromLow); }

// Clamp value within a range float clamp(float value, float minVal, float maxVal) { return max(min(value, maxVal), minVal);

// Initialize hardware and communication void setup() {

502 Bad GatewayUnable to reach the origin service The service may be down or it may not be responding to traffic from cloudflared

502 Bad GatewayUnable to reach the origin service The service may be down or it may not be responding to traffic from cloudflared

} break; case 0x101: if (canMsgRx.can_dlc == 8) {

114 memcpy(&Ki, canMsgRx.data, sizeof(float)); memcpy(&Kd, &canMsgRx.data[4], sizeof(float));

} break; case 0x102: if (canMsgRx.can_dlc == 4) { memcpy(&direction, canMsgRx.data, sizeof(float));

// Task 2: Read sensors and compute PID void taskReadPID() {

The throttle position sensor (TPS) readings are obtained by converting analog signals to voltage values using the analogToVoltage function These raw voltage values from VTA1 and VTA2 sensors are then mapped to percentage values, with TPS1 ranging from 0% to 100% based on a voltage span of 0.4V to 2.32V, and TPS2 also mapping from 0% to 100% within a 1.182V to 3.2V range To ensure accurate and bounded readings, the mapped values are clamped between 0% and 100% Finally, the TPS1 percentage is assigned to the PID control variable for further processing.

// Set motor direction digitalWrite(IN1_PIN, direction == 0 ? LOW : HIGH); digitalWrite(IN2_PIN, direction == 0 ? HIGH : LOW);

115 myPID.SetMode(AUTOMATIC); myPID.SetTunings(Kp_pid, Ki_pid, Kd_pid); myPID.SetControllerDirection(DIRECT); myPID.SetOutputLimits(out_min, out_max); myPID.SetSampleTime(20); myPID.Compute();

// Calculate PWM output pwm = (pid_out < out_min) ? 0.0 : (pid_out > out_max) ? 0.99 : pid_out / 100.0; ledcWrite(PWM_CHANNEL, pwm * (1 = TASK1_INTERVAL) { previousTask1Millis = currentMillis; taskCANReceive();

} if (currentMillis - previousTask2Millis >= TASK2_INTERVAL) { previousTask2Millis = currentMillis; taskReadPID();

} if (currentMillis - previousTask3Millis >= TASK3_INTERVAL) { previousTask3Millis = currentMillis; taskCANSend();

2.1 Header Files and Libraries & Pin Definitions

#include const int INT_PIN = 4; const int VTA1_PIN = 32; const int VTA2_PIN = 33; const int PWM_PIN = 27; const int IN1_PIN = 25; const int IN2_PIN = 26;

The code integrates three essential libraries: SPI.h for establishing serial communication with the MCP2515 CAN controller, mcp2515.h which offers functions for managing CAN bus operations such as message transmission and reception, and PID_v1.h that enables the implementation of the PID control algorithm to accurately regulate throttle position based on sensor feedback and user input, ensuring smooth and precise control of the system.

The system utilizes specific hardware pins, including pin 4 designated for CAN interrupt (currently not used for interrupts in this version), pins 32 and 33 for reading throttle position sensors (VTA1 and VTA2), pin 27 for PWM output to control the motor, and pin 25 for additional functionalities Understanding these hardware pin configurations is essential for effective system integration and performance.

26 for controlling motor direction via an H-bridge or similar circuit

2.2 PWM Configuration const int PWM_CHANNEL = 0; const int PWM_FREQ = 16000; const int PWM_RESOLUTION = 12;

• Configures PWM settings for motor control, using channel 0 with a frequency of

16 kHz to ensure smooth operation and a 12-bit resolution (0-4095) for precise control of the PWM signal duty cycle

118 const unsigned long TASK1_INTERVAL = 10; // CAN receive const unsigned long TASK2_INTERVAL = 20; // PID and sensor read const unsigned long TASK3_INTERVAL = 40; // CAN send

The system is configured with specific timing intervals to ensure optimal performance: CAN message reception occurs every 10 milliseconds for frequent data checks; PID computation and sensor readings are scheduled every 20 milliseconds to maintain a balance between responsiveness and stability; and CAN message transmission is set every 40 milliseconds to reliably send sensor data to external devices.

This article involves the MCP2515 CAN bus controller, with variables for CAN message handling (`canMsgRx`, `canMsgTx`), and timing control (`previousTask1Millis`, `previousTask2Millis`, `previousTask3Millis`) It defines key parameters for a PID control system, including proportional (`Kp`), integral (`Ki`), and derivative (`Kd`) gains, along with sensor readings for throttle position sensors (`tps1_percent`, `tps2_percent`) and air pressure sensors (`apsPercent`) The control outputs, such as PWM signals and PID calculations (`pwm`, `pid_out`), are constrained within specified limits (`out_min`, `out_max`) The system uses tuned PID constants (`Kp_pid = 0.6`, `Ki_pid = 0.5`, `Kd_pid = 0.001`) to ensure precise and responsive control of mechanical or automotive systems, integrating CAN communication and real-time data processing for optimal performance.

PID myPID(&tps1_pid, &pid_out, &apsPercent_pid, Kp_pid, Ki_pid, Kd_pid,

The system initializes key variables for seamless operation, including MCP2515 to control the CAN module on pin 5, while canMsgRx and canMsgTx store CAN messages for communication Task timers are implemented to monitor execution timing, and control parameters such as apsPercent, Kp, Ki, Kd, and direction facilitate input management and PID tuning Sensor variables like tps1_percent and tps2_percent record throttle positions, whereas PID-related variables (pwm, pid_out, apsPercent_pid, tps1_pid) are used for control calculations Additionally, the myPID object is initialized with default tuning values to ensure proper PID controller functionality.

2.5 Analog to Voltage Conversion float analogToVoltage(int analogValue) { return analogValue * 3.3 / 4095.0;

• Converts 12-bit analog readings (0-4095) from the throttle position sensors into a voltage value (0-3.3V) based on the microcontroller’s ADC range, providing a standardized input for further processing

2.6 Map Value Function & Clamp Function float mapValue(float input, float fromLow, float fromHigh, float toLow, float toHigh) { return toLow + ((input - fromLow) * (toHigh - toLow)) / (fromHigh - fromLow); } float clamp(float value, float minVal, float maxVal) { return max(min(value, maxVal), minVal);

• Scales an input value from one range (e.g., sensor voltage) to another (e.g., 0- 100% throttle position), using linear interpolation to ensure accurate representation of sensor data in the desired units

• Restricts a value to a specified range (e.g., 0-100%) by returning the minimum if below the range or the maximum if above, ensuring sensor readings and control outputs stay within valid limits

SPI.begin(); mcp2515.reset(); mcp2515.setBitrate(CAN_500KBPS, MCP_8MHZ);

To initialize the MCP2515 in normal mode, use the command `mcp2515.setNormalMode()` Set up the interrupt pin with `pinMode(INT_PIN, INPUT_PULLUP)` to ensure proper input reading Configure the motor control pins by setting `IN1_PIN` and `IN2_PIN` as outputs using `pinMode`, and also set the `PWM_PIN` as an output for PWM control To generate PWM signals, initialize the PWM channel with `ledcSetup(PWM_CHANNEL, PWM_FREQ, PWM_RESOLUTION)` and attach the PWM pin to the channel using `ledcAttachPin(PWM_PIN, PWM_CHANNEL)` These configurations collectively enable efficient control of the motor and communication with the MCP2515 module.

The system initializes serial communication at 115200 baud for debugging purposes and sets up SPI for communication with the CAN module It then resets the MCP2515 CAN controller, configures it to operate at a baud rate of 500 kbps with an 8 MHz clock, and enables normal CAN operation mode to ensure reliable data transmission.

Configures pins for CAN interrupt (unused in this version), motor direction (IN1, IN2), and PWM output, and sets up the PWM channel for motor control

2.8.1 Task 1: Receive CAN void taskCANReceive() { while (mcp2515.readMessage(&canMsgRx) == MCP2515::ERROR_OK) { switch (canMsgRx.can_id) { case 0x100: if (canMsgRx.can_dlc == 8) { memcpy(&apsPercent, canMsgRx.data, sizeof(float)); memcpy(&Kp, &canMsgRx.data[4], sizeof(float)); apsPercent_pid = apsPercent;

121 if (canMsgRx.can_dlc == 8) { memcpy(&Ki, canMsgRx.data, sizeof(float)); memcpy(&Kd, &canMsgRx.data[4], sizeof(float));

} break; case 0x102: if (canMsgRx.can_dlc == 4) { memcpy(&direction, canMsgRx.data, sizeof(float));

The system continuously monitors incoming CAN messages, processing each based on its ID to ensure accurate vehicle control For messages with ID 0x100 (8 bytes), it extracts the desired throttle (apsPercent) and proportional gain (Kp), updating the PID controller parameters accordingly Messages with ID 0x101 (8 bytes) provide the integral (Ki) and derivative (Kd) gains, allowing precise PID tuning adjustments Additionally, messages with ID 0x102 (4 bytes) convey the motor rotation direction, enabling proper control of motor operation for optimal performance.

2.8.2 Task 2: Read Sensors and Compute PID void taskReadPID() { float raw_vta1 = analogToVoltage(analogRead(VTA1_PIN)); float raw_vta2 = analogToVoltage(analogRead(VTA2_PIN)); tps1_percent = clamp(mapValue(raw_vta1, 0.4, 2.32, 0.0, 100.0), 0.0, 100.0); tps2_percent = clamp(mapValue(raw_vta2, 1.182, 3.2, 0.0, 100.0), 0.0, 100.0); tps1_pid = tps1_percent;

Ngày đăng: 02/09/2025, 18:40

Nguồn tham khảo

Tài liệu tham khảo Loại Chi tiết
2. Espressif Systems, ESP32 Technical Reference Manual, Version 4.9, 2023. [Online]. Available:https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf Sách, tạp chí
Tiêu đề: ESP32 Technical Reference Manual
Tác giả: Espressif Systems
Nhà XB: Espressif Systems
Năm: 2023
3. Microchip Technology Inc., MCP2515: Stand-Alone CAN Controller with SPI Interface, Data Sheet, DS21801E, 2016. [Online]. Available:https://ww1.microchip.com/downloads/en/DeviceDoc/MCP2515-Stand-Alone-CAN-Controller-with-SPI-20001801J.pdf Sách, tạp chí
Tiêu đề: MCP2515: Stand-Alone CAN Controller with SPI Interface
4. D. Dhananjayan, “Working With Automotive CAN Protocol,” Blogspot.com, Jan Sách, tạp chí
Tiêu đề: Working With Automotive CAN Protocol
Tác giả: D. Dhananjayan
Nhà XB: Blogspot.com
30, 2018. [Online]. Available: https://dhananjayansblog.blogspot.com/2018/01/working-with-automotive-can-protocol.html Link
1. Khai quát - Hệ thống điều khiển điện tử, Tài liệu nội bộ Khác

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w