1. Trang chủ
  2. » Luận Văn - Báo Cáo

Development And Realization Of A Distributed Control Algorithm For An Inverted Rotary Pendulum Using Freertos With Ttcan Communication.pdf

103 6 0

Đ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 đề Development and realization of a distributed control algorithm for an inverted rotary pendulum using FreeRTOS with TTCAN communication
Tác giả Bui, Hoang Dung
Người hướng dẫn Prof. Dr. Roman Obermaisser, Dr.-Ing. Walter Lang
Trường học Universität Siegen
Chuyên ngành Embedded Systems
Thể loại Thesis
Năm xuất bản 2014
Thành phố Siegen
Định dạng
Số trang 103
Dung lượng 3,85 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

  • 1.1 Overview (6)
  • 1.2 Master thesis objectives (7)
  • 1.3 Report’s structure (8)
  • 2.1 Related Work (10)
    • 2.1.1 The mechanical design (10)
    • 2.1.2 The results from the student work (12)
  • 2.2 Embedded C (14)
    • 2.2.1 Basic concepts in Embedded C (15)
    • 2.2.2 Control Statements (16)
    • 2.2.3 Pointer, Arrays and Structures (18)
  • 2.3 FreeRTOS (19)
    • 2.3.1 Introduction (19)
    • 2.3.2 Used FreeRTOS Library Classes (23)
  • 2.4 CAN and Time Trigger CAN (25)
    • 2.4.1 Controller Area Network – CAN (26)
    • 2.4.2 Time Trigger CAN – TTCAN (27)
  • 2.5 AT90CAN128 Microcontroller (31)
    • 2.5.1 The specific knowledge about AT90CAN128 (31)
    • 2.5.2 CAN Controller in AT90CAN128 (33)
  • 3.1 The nonlinear IRP Model (38)
  • 3.2 Microcontroller Structures (42)
    • 3.2.1 TTCAN Scheduler (43)
    • 3.2.2 Time Trigger Matrices (45)
    • 3.2.3 TTCAN_Scheduler Task and CAN ISR (48)
    • 3.2.4 Microcontroller Tasks (50)
  • 4.1 Nonlinear IRP model (57)
  • 4.2 The common parts (59)
    • 4.2.1 CAN Tasks (59)
    • 4.2.2 CAN ISR (64)
  • 4.3 SEN-uC (66)
    • 4.3.1 Specific External Interrupt Service Routines (66)
    • 4.3.2 Data_Preparation() Task (67)
  • 4.4 LCD-uC (68)
  • 4.5 PUSB-uC (70)
  • 4.6 MOTO-uC (73)
    • 4.6.1 Timer/Counter 3 Compare Match Interrupts (74)
    • 4.6.2 DC-motor Control Tasks (75)
  • 4.7 Parameters Estimation (79)
    • 4.7.1 The IRP parameters (79)
    • 4.7.2 LQR parameters (81)
    • 4.7.3 PWM and Sampling frequencies (82)
  • 5.1 Results (83)
    • 5.1.1 The nonlinear IRP model behavior (83)
    • 5.1.2 The IRP machine Operation (85)
  • 5.2 Discussion (91)
    • 5.2.1 Sampling and PWM frequency (91)
    • 5.2.2 Mechanical Structures (92)

Nội dung

UNIVERSITÄT SIEGEN Institut für Embedded Systems Master Thesis Development and Realization of a distributed control algorithm for an inverted rotary pendulum using FreeRTOS with TTCAN communication Su[.]

Overview

This master thesis project builds upon the previous student work, "Modeling and Simulation of an Inverted Rotary Pendulum" [Bui, 2013], which established an approximate linear model and utilized the State Space method for control theory While the Simulink model demonstrated stability and maintained an upright position, discrepancies arose due to the inherent nonlinear components of the actual machine This thesis aims to address these differences and delve deeper into the control challenges associated with the Inverted Rotary Pendulum (IRP), as illustrated in Figure 1.1.

Figure 1.1 illustrates the key components of the Inverted Pendulum Robot (IRP), including the pendulum/mass M, gearbox, DC motor, belt transmission, frame, two sensors, and foundation The movement of the IRP is initiated by the DC motor, which transfers motion to the frame through the gearbox and belt transmission As the frame rotates, it causes the mass/pendulum to swing upward into an upright position The system measures the angle positions of both the frame and the mass M using two encoders, referred to as the Arm angle and Pendulum angle, respectively.

Signals from encoders processed by Circuit 1 are transmitted to Integrated Circuit 2, which features four AT90CAN128 microcontrollers and various components, including an LCD DOGS102-6, a push-button matrix, LEDs, signal ports, four PCA82C250s, and an L6205D The microcontrollers manage data for DC motor control, while the push-button matrix and LCD serve as the Human Machine Interface (HMI), displaying information about the IRP system User commands are received via the button matrix, influencing the IRP system's state The PCA82C250s act as a bridge between the CAN controller and the CAN Bus, and the L6205D amplifies PWM signals from the microcontroller's I/O port to directly control the DC motor.

The IRP is controlled by four microcontrollers, each serving a specific function The first microcontroller detects and transmits the arm and pendulum angles to the second microcontroller, which displays all IRP information on an LCD The third microcontroller manages the button matrix signals to control the operation of the IRP, while the fourth microcontroller regulates the rotation of the DC motor, facilitating the movement of the IRP.

Master thesis objectives

This thesis builds upon previous student work, focusing on the essential task of coding for four microcontrollers to ensure the IRP machine operates stably in an upright position To achieve this, certain minimum objectives must be met.

- Build nonlinear model of IRP

- Define constraint times which can keep the system working stable

- Handle with the sensor signal and the backlash

- Check capacity of Microcontrollers to meet the IRP control requirements

- Write the program to control the IRP working at upright position with the stability time about 5 seconds

As the primary objectives of the master thesis are achieved, the goals are expanded to enhance system usability Additional features will be integrated to improve user-friendliness.

- Establish two separate programs to control IRP in two phases: Swing up phase and Upright phase

- Human – Machine Interface (HMI): show IRP information on LCD, and some buttons to control IRP

- Be able to change the reference input of arm angle

- Be able to transmit the signal of IRP angles to computer, and shown it graphically

That is the objectives of this master thesis project Subsequently, the report structure would be introduced.

Report’s structure

The report is structured into six chapters, designed to guide the reader through the implementation of the student's work in a step-by-step manner Each chapter presents relevant knowledge and demonstrates its application to the specific Independent Research Project (IRP).

Chapter 1 presents general knowledge about IRP, objectives and report’s structure

Chapter 2 describes the related works and basic concepts which would be used to control the IRP machine

Chapter 3 outlines the designed functionalities for each microcontroller, beginning with an overview of their general structures, including the Scheduler, CAN message, TTCAN_Scheduler task, and CAN ISR It then delves into the specific tasks tailored for each microcontroller, emphasizing their unique roles and operations.

Chapter 4 focuses on implementing the design using a programming language, specifically converting microcontroller structures into Embedded C and FreeRTOS code to control the IRP machine Additionally, this chapter outlines the parameter estimation process essential for the system's functionality.

Chapter 5 would present the results from chapter 4 The response in the nonlinear model and the IRP machine will be shown and discussed The learned knowledge is also discussed here

Chapter 6 concludes about the master thesis project The achieved goals were reached in this work

In the end of the work, the declaration, reference and appendix – the program codes in detail of the former chapters are presented

This article provides essential insights into the master thesis, offering readers a comprehensive overview The subsequent chapter introduces fundamental concepts and relevant research related to the IRP.

2 Basic concepts and Related Works

This chapter lays the groundwork for developing the IRP operation, beginning with a review of existing related works and their findings that will inform this master's thesis It then introduces essential concepts for programming the IRP control code, including Embedded C, FreeRTOS, TTCAN, and the AT90CAN128 microcontroller, focusing solely on the specific knowledge pertinent to these areas.

Related Work

The mechanical design

This section presents the engineering draws of IRP machine’s structure The overview of the IRP in design phase is shown in the figure below

The blue item in the drawing represents the DC motor, while the belt transmission and bearing are not included The 3-D view is projected from the front and top directions, resulting in detailed top and front views of the Integrated Robotics Platform (IRP) The front view indicates that the IRP has a height of 400 mm, a length of 350 mm, and a width of 200 mm.

Figure 2.2 Front view of the IRP

Figure 2.3 Top view of the IRP

The front and top views provide a dimensional representation of the IRP, illustrating the distances between components and offering a visual overview of the machine's mechanical structure This dimensional information is crucial for procuring essential components like the DC motor, gearbox, and belt transmission to fulfill specific requirements Subsequently, the engineering drawings are forwarded to the mechanical shop, responsible for the production and assembly of the foundation and other components.

The results from the student work

This section revisits the accomplishments from the student work, which involved the development of a linear IRP model and the application of State Space Control theory In this approach, the system equations were reformulated into a first-order equation system, with system states and inputs represented as vectors A crucial aspect of the state space method is ensuring that system states approach zero as time progresses towards infinity, which is essential for maintaining a steady state Since the open IRP cannot remain upright on its own, a feedback controller was incorporated to stabilize its position This controller measures the output, applies feedback parameters, and compares the result with the reference input If a discrepancy exists, it converts the difference into a voltage signal to adjust the DC motor towards the desired position; if there is no difference, the IRP remains stationary The accompanying figures illustrate the Simulink model of the IRP.

Figure 2.4 Plant with feedback signal

The IRP model depicted above operates without a reference input, effectively treating it as zero The system comprises four states, which are gathered by the Feedback component This feedback signal is then relayed back to the PLANT to fine-tune the movement of the DC motor The configuration of both the PLANT and the Feedback component is illustrated in the figure below.

The feedback parameters are essential for the effective functioning of the IRP system Various methods exist to calculate these parameters, but the student utilized the linear quadratic regulator (LQR) method, which successfully balances system effort with output response The parameters were processed using the lqr() function in Matlab software.

The formula to calculate the feedback signal is:

And the controlled signal is equal to Feedback signal but with opposite sign:

To enhance the capabilities of the Integrated Robotic Platform (IRP), a crucial component was introduced alongside the feedback system This addition allows the IRP to operate effectively at any position within the arm's working range while maintaining the mass in an

Figure 2.7: The full IRP model The new component produces an added signal by formula:

Ki dt t Cons Position Arm

Where dt is the time period between to two times taken the sensor signal which is equal to 3 milliseconds

In this content, the controlled signal is different to the feedback signal, and the controlled signal is calculated by the formula:

In addition, the moment of inertia of IRP was calculated, and would be used in this master thesis work.

Embedded C

Basic concepts in Embedded C

In this part, it is started by introducing the symbol conventions in Embedded C The next one is kinds of variables, constant, I/O operation and bitwise operator

Just as C language, there are some symbol conventions to compile the program in Embedded C They are listed in the table below:

; A semicolon is used to indicate the end of an expression An expression in its simplest form is a semicolon alone

Braces are essential in programming as they define the start and end of a function's contents They also group multiple statements together, allowing them to be treated as a single block.

“text” Double quotes are used to mark the beginning and the end of a text string

// or /* … */ Slash-slash or slash-star/star-slash are used as comment delimiters

#include Add external library to the program

Due to the memory limitations in microcontrollers, it is essential to utilize memory efficiently Consequently, the creator of Embedded C developed various types of variables designed to optimize memory usage.

In programming, data types are defined by their size in bits and the range of values they can represent A bit can hold a value of 0 or 1, while a char, which is 8 bits, ranges from -128 to 127 An unsigned char also has 8 bits but ranges from 0 to 255 The int and short int types, both 16 bits, can represent values from -32,768 to 32,767 The long int, which is 32 bits, has a broader range from -2,147,483,648 to 2,147,483,647, while its unsigned variant can represent values from 0 to 4,294,967,295 Additionally, the signed long int shares the same range as the long int For floating-point numbers, both float and double types, each 32 bits, can represent values from approximately ±1.175e-38 to ±3.402e38.

CONSTANTS: are fixed values – they are not allowed to be modified as the program executes Constant can be described by some kind of numeric form:

- Decimal form without a prefix (such as 1234)

- Binary form with 0b prefix (such as 0b101001)

- Hexadecimal form with 0x prefix (such as 0xff)

- Octal form with 0 prefix (such as 0777)

TYPE CASTING: The cast, called out in parentheses, convert the followed expression becoming the declared type which is in the cast when the operation is been performed

I/O OPERATIONS: Embedded microcontrollers must interact directly with other hardware Therefore, any of their input and output operations are accomplished using the built-in parallel ports of the microcontroller

Bitwise operators manipulate operands at the bit level and are applicable to non-floating point data types such as char, int, and long The following table presents the bitwise operators arranged by their precedence.

Control Statements

The specific control statements will be introduced in this section It contains some common loops which are used many times in the project

WHILE LOOP: is one of the most basic control elements, the format of this statement is as follows: while (expression)

The expression is evaluated for its truthfulness; if true, the statements within the while loop are executed, while a false result leads to no action being taken.

A do/while loop is akin to a while loop, but with the key difference that the condition is evaluated at the end of the loop This ensures that the instructions within a do/while loop are executed at least once Like a while loop, if the condition evaluates to true, the loop will continue to execute The basic syntax of a do/while statement is as follows: do.

A for loop is utilized to execute a block of statements a specific number of times, as determined by the user It consists of an initialization, a test condition, and an action that modifies the loop variable, all encapsulated within the for-condition braces The standard format of a for loop is: for (expr1; expr2; expr3).

IF/ELSE statements: they are used to steer or branch the operation of the program based on the evaluation of a conditional statement

The SWITCH/CASE statement functions similarly to an if/else statement but allows for multiple values of the expression to be evaluated Each case includes a "break" command at the end to exit the switch/case structure The syntax of this statement is as follows: switch (expression).

{ case const1: statement1; statement2; break; case const2: Statement3;

; Statement x; break; case const-x: statement5; statement6; break; default: statement7; statement8; break;

Pointer, Arrays and Structures

This section describes some kinds of compound variables, which are derived from the basic variables types They are pointers, Arrays and Structures

Pointers are variables that store the address of other variables, constants, functions, or data objects They are declared using the dereferencing operator (*), such as in the examples: `char *p;` which indicates that `p` is a pointer to a character, and `int *fp;` which signifies that `fp` is a pointer to an integer.

The pointer holds the address of another item And in typical microcontroller the address of a memory is a 16-bit value data type, therefore the pointer will be a 16-bit value

An array is a structured data set of a specific type, organized in a sequential manner To declare an array, one must specify its name and the total number of elements it will contain The elements within an array can be accessed using the syntax: name[0], name[1], … name[x-1] For example, the declaration `int digits[10];` creates an array designed to hold 10 integer values.

Multidimensional arrays are essentially arrays of arrays, capable of having two, three, four, or more dimensions In such arrays, adjacent memory locations are accessed using the right-most index in the declaration For example, a standard declaration of a two-dimensional array of integers is represented as int two_d[5][10].

STRUCTURES: A structure is a compound subject created from one or more variables The variables within a structure are called members Members can be different types of variables

A structure declaration has the following form: struct structure_tag_name

The member can be invoked by the syntax: structure_var_name.member_1 The structure is a useful tool, which can manage a subject with compound features

The specific knowledge about Embedded C which is used in the project is introduced concisely They provide the foundation to understand the sections latter.

FreeRTOS

Introduction

In order to manage the microcontroller cores, the FreeRTOS built Application Programmable Interface – API functions, which assigned specific duties Those API functions are grouped to five main sets [Barry, 2009]

The system is organized into five essential sets: the first set manages Task entities, the second oversees Queue entities, the third handles Interrupt management, the fourth is responsible for Resource Management, and the final set manages Memory This article will provide a detailed description of the structure and functions of the first four sets.

In FreeRTOS, the fundamental component is the task, which is defined as a C function that returns void and accepts no parameters Tasks must run indefinitely and cannot return any values Multiple tasks can coexist within a project, but at any given time, the microcontroller core can execute only one task, while all others remain in a "Not Running" state This indicates that a task can either be in the "Running" state, where its code is actively executed, or in the "Not Running" state, where it is dormant and its status is preserved for future execution.

Figure 2.8 Task states in FreeRTOS

In the Not Running state, it can be separated into three sub-states: Suspended, Ready and Blocked [Barry,

In a multitasking environment, a task enters the Blocked State when it awaits an event, which may be either temporal or for synchronization A task is considered to be in the Suspended State when it is not available for scheduling, typically achieved by invoking the vTaskSuspend() API function To resume execution, tasks can utilize either the vTaskResume() or xTaskResumeFromISR() API functions Additionally, a task may be in the "Not Running" state without being in the Suspended State.

Blocked states, it would be in Ready State

In FreeRTOS, a task transitions from the Not Running state to the Running state is referred to as "switch in" or "swapped in," while the reverse process is known as "switch out" or "swapped out." The FreeRTOS scheduler is solely responsible for managing these task switches.

FreeRTOS offers several API functions for managing tasks and their states, including xTaskCreate() for task creation and vTaskDelete() for task deletion To introduce delays in a main task, developers can utilize vTaskDelay() and vTaskDelayUntil() Additionally, tasks can be suspended or resumed using vTaskSuspend() and vTaskResume(), respectively A comprehensive list of all API functions used in this master thesis project is provided in the following table.

The API functions provide essential task management capabilities: xTaskCreate() is used to create a new task and add it to the ready-to-run list, while vTaskDelete() allows for the deletion of a task To manage task execution timing, vTaskDelay() delays a task for a specified number of ticks, placing it in the 'Blocked' state, whereas vTaskDelayUntil() keeps a task in the 'Blocked' state for an exact number of ticks based on absolute time Additionally, vTaskSuspend() can suspend any task, moving it to the 'Suspended' state, and vTaskResume() is used to resume a suspended task, transitioning it back to the 'Ready' state.

Those API functions above are described in primitive way In reality, they contain more parameters which affect to the task performance

Applications built on FreeRTOS typically consist of multiple independent tasks, each responsible for its own specific function These autonomous tasks must communicate and synchronize with one another to ensure the overall system operates effectively One effective method for facilitating this communication and synchronization is through the use of queues.

A queue is a data structure that stores data items and is designed for access by multiple tasks, allowing for simultaneous reads and writes The capacity of a queue, known as its length, determines how many data items it can hold, while the size of the data can vary based on the type of information stored Both the data size and queue length are established at the time of the queue's creation When tasks attempt to read from or write to the queue, they may be blocked if the queue is empty or full, ensuring efficient management of data flow.

FreeRTOS offers a collection of API functions to facilitate the creation and management of queues, enabling data transmission and retrieval The following table highlights a selection of these functions utilized in the project.

The API provides several functions for queue management: xQueueCreate() is used to create a queue, while vQueueDelete() allows for the deletion of a queue To post an item onto a queue, xQueueSend() is utilized, and xQueueSendToFront() enables posting an item at the front of the queue For receiving items, xQueueReceive() retrieves an item from the queue, and xQueuePeek() allows for viewing an item without removal, though it should not be used in an interrupt service routine For interrupt service routines, xQueueSendFromISR() safely posts an item to the back of a queue, and xQueueReceiveFromISR() allows for receiving an item from a queue.

Those API functions above are described in primitive way In reality, they contain more parameters which affect to the task performance

Embedded real-time systems must respond to various events, which can be categorized as temporal/synchronization events or those originating from the environment For temporal events, API functions and specific tasks are designed to address them effectively In contrast, environmental events present a more complex challenge, requiring the use of interrupts for their detection.

In 2009, the question arose regarding whether the entire process should be handled within an Interrupt Service Routine (ISR) To minimize the ISR duration, it is advisable to divide the process into smaller segments Additionally, establishing effective communication between the ISR and the main code is crucial Strategies to address these challenges will be discussed in the following sections.

To synchronize a task with an interrupt during an event, a binary semaphore is utilized to unblock the task whenever the interrupt occurs This structure ensures that most of the code is executed in the main task, while only critical code resides in the Interrupt Service Routine (ISR) When the event occurs, the ISR performs a “give” operation on the semaphore to unblock the corresponding task, allowing the necessary event processing to continue Once the task completes its process using a “take” operation, it transitions to a Blocked state, awaiting the next event.

The API functions for semaphore operations, including creating a semaphore and performing "give" and "take" actions, are listed in the table below A semaphore can be viewed as a queue that holds only one item, with the functions xSemaphoreTake() and xSemaphoreGive() used to empty or fill the semaphore, respectively The relevant API functions utilized in this project are detailed in the table below.

API Function Description vSemaphoreCreateBinary() Function that creates a binary semaphore xSemaphoreTake() Macro to obtain a semaphore xSemaphoreGive() Macro to release a semaphore

FreeRTOS effectively manages microcontroller resources, which is crucial in multitasking systems to prevent conflicts, as highlighted by Barry (2009) When one task accesses a resource and is then pre-empted by another, it can leave the resource in an inconsistent state, leading to potential data corruption or errors To mitigate these issues, FreeRTOS offers API functions that can disable all interrupts, the scheduler, or both, ensuring that critical functions can execute without interruption.

Used FreeRTOS Library Classes

This project includes five code files: heap_1.c, list.c, port.c, queue.c, and tasks.c, along with eleven header files: compiler.h, list.h, FreeRTOS.h, FreeRTOSConfig.h, io.h, portable.h, portmacro.h, projdefs.h, queue.h, task.h, StackMacros.h, semphr.h, and global.h These files primarily consist of the FreeRTOS base, which is essential for managing real-time system operations The subsequent sections will provide a detailed introduction to the function of each class.

This header file introduces new variable types, macros, and constants utilized throughout FreeRTOS, enhancing user comprehension by simplifying the declaration of new variables.

This file serves as the interface that identifies the type of microcontroller connected to the port, allowing Atmel Studio to upload the code correctly based on the detected microcontroller.

This class is simply to manage microcontroller memory The file would setup the correct byte alignment mask for the defined byte alignment and allocate the memory for the heap

The scheduler relies on two key files to manage its implementation list, which, while specifically designed for its needs, can also be utilized by application code These files include tasks that initialize a list for storing pointers or items, as well as functions to add or remove items from this list.

Those files contain some macro and tasks which manage the switch task duties and the time tick of FreeRTOS time

This header file is responsible for verifying the definitions of essential application-specific macros If any definitions are absent, it will define the missing elements to ensure the system operates smoothly.

This header file configures the application specific definition which keeps the FreeRTOS working as desired These definitions are able to adjust for particular hardware and application requirements

This class defines the prototype to which task functions must conform

The classes in this project manage queues that are essential for creating, storing, sending, and receiving data Notably, items are queued by copy rather than by reference.

This header file invokes the stack overflow hook function when the stack of the task being swapped out is either currently overflowing or appears to have overflowed in the past.

The defined classes outline the essential functions and features needed to manage tasks effectively They include tasks or macros for creating and deleting tasks, initiating context switches, disabling maskable interrupts, and marking critical code regions It's important to note that preemptive context switches are not permitted within these critical regions.

This header file declares Port specific definitions (new kind of variables or macro) The setting in this file configures FreeRTOS correctly for the given hardware and compiler

The article outlines the functions utilized by other classes, specifically heap_1.c and port.c, emphasizing that each function must be defined for its respective port Notably, some functions in this class facilitate the setup of a new task's stack or hardware/ISR, preparing it for scheduler control, while also mapping to the necessary memory management routines for the port.

The Semaphore.h class includes functions and macros for managing semaphores, allowing users to create, delete, and modify data within them This tool is essential for effectively managing the timing triggers of a scheduler.

This class stands apart from others as it is not part of the FreeRTOS library; rather, it is designed to manage global variables utilized throughout the project For instance, in the SEN-uC, certain variables like Pendulum_axis and Arm_axis are declared within this file and are shared across multiple classes While each microcontroller includes this global class, the global variables contained within are unique to each one.

CAN and Time Trigger CAN

Controller Area Network – CAN

The Controller Area Network (CAN) protocol, established by BOSCH in 1980 and standardized as ISO 11898, facilitates real-time, secure serial bus communication It encompasses both the data link layer and physical layer of the ISO/OSI Reference Model, allowing for the transmission of four frame types: Data Frame, Remote Frame, Error Frame, and Overload Frame, achieving a bitrate of 1 Mbit/s Each frame is assigned a unique identifier that determines message priority, with lower binary numbers indicating higher priority In cases of simultaneous transmission, bit-wise arbitration resolves conflicts, where the dominant state prevails, and the node with the lower priority identifier becomes a receiver of the higher priority message, which will be retransmitted when the bus is free This mechanism underscores the importance of frames in enabling microcontroller communication.

The CAN Bus transmits data using units known as CAN frames, which adhere to two message formats distinguished by the length of their identifiers The "CAN base frame" features an eleven-bit identifier, while the "CAN extended frame" accommodates a twenty-nine-bit identifier, allowing for greater flexibility in message identification.

Figure 2.9 CAN message frame structure

A CAN base frame message starts with the first bit called “Start of Frame (SOF)” The next is the

The arbitration field includes an identifier and the Remote Transmission Request (RTR) bit, which differentiates between Data frames and Remote frames The Control field features the Identifier Extension (IDE) bit for distinguishing between CAN base and extended frames, along with the Data Length Code (DLC) that indicates the length of the data byte field In Remote frames, the DLC specifies the requested data byte length The Data Field can contain up to 8 bytes of data, while the 16-bit Cyclic Redundant Check ensures frame integrity The Acknowledge (ACK) field includes an ACK slot and delimiter, where the ACK bit is initially recessive but becomes dominant when receivers confirm correct data reception Finally, the End of Frame (EOF) marks the conclusion of the frame, and the Intermission frame Space defines the minimum number of bits between consecutive messages.

The CAN extended frame message incorporates an additional 18-bit extension identifier to the existing 11-bit base identifier, resulting in a total of 29 bits for the new identifier This distinction is the primary difference between the extended frame format and the base frame format The Identifier Extension (IDE) bit serves to differentiate between the two formats; it is dominant for the 11-bit identifier frame and recessive for the 29-bit frame In a bus system that supports both frame formats, the 11-bit message consistently holds priority over the 29-bit message.

The extended format has several drawbacks, including increased bus latency time, which can be at least 20 bit-times longer Additionally, it requires approximately 20% more bandwidth for messages and exhibits lower error detection performance.

Time Trigger CAN – TTCAN

The CAN protocol's arbitration mechanism prioritizes message transmission, ensuring that higher priority messages are transmitted without interference, while lower priority messages experience increased latency jitter To address these latency issues and achieve deterministic communication under maximum bus load, the Time Triggered CAN (TTCAN) protocol was developed TTCAN operates on a time-based communication model, where events are initiated by the passage of time segments This protocol is defined under ISO 11898-4 and consists of two levels: Level 1 guarantees time-triggered operations through a reference message from a time master, while Level 2 utilizes globally synchronized time for enhanced accuracy and drift correction This project implements TTCAN Level 1 using the AT90CAN128 controller, which supports this protocol extension, and subsequent sections will detail the specifications of the TTCAN Level 1 protocol.

The TTCAN operation relies on time-triggered and periodic communication initiated by a reference message from the time master This reference message, identifiable by its unique identifier, is transmitted during time slot "0" of the basic cycle and includes the timestamp of its transmission Upon arrival at other nodes, this reference message is utilized to adjust any time drift between the time master and the other nodes, ensuring synchronized communication within the network.

 The basic cycle and its time windows

The period between two consecutive reference messages is known as the basic cycle, which comprises several time slots, also referred to as time windows Each time window varies in size and provides adequate space for message transmission.

Figure 2.10 Basic cycle and Time Window

The time window for messages can represent either periodic or spontaneous states, events, or data, adhering to the CAN message standard There are three types of time windows within a basic cycle, with the exclusive time window being the first This window stores periodic messages, with predetermined transmission time points and predefined sending nodes Designed offline, multiple exclusive time windows can exist within a single basic cycle; however, they do not support automatic re-transmission of CAN messages.

To enhance design flexibility, the arbitrating time window was introduced for spontaneous messages This innovative time window allows for online CAN message design, enabling multiple messages to be prepared during the design phase The selection of the specific message to be transmitted on the bus is determined through bitwise arbitration Additionally, this time window prevents the automatic retransmission of CAN messages, ensuring efficient communication.

Figure 2.11Basic cycle with three kind of time window

The free time window serves to accommodate future network expansions within the CAN system This time window can be transformed into either an exclusive or arbitrating time window as new nodes are integrated The figure above illustrates the three types of time windows alongside the reference message.

 The nodes in TTCAN network

In a TTCAN network, nodes are designed to receive only the essential information needed for time-triggered operations, such as sending and receiving messages This approach optimizes memory usage in hardware implementations while still providing sufficient data for effective network management.

In sophisticated systems, a single basic cycle may not provide sufficient space for communication among nodes To address this limitation, the TTCAN specification permits the use of multiple basic cycles to construct the communication or system matrix The accompanying figure illustrates a system matrix comprising four basic cycles.

The system matrix is constructed from four interconnected basic cycles, allowing for the transmission of a CAN message either in every basic cycle, every third basic cycle, or just once throughout the entire system matrix.

 Cycle Time and Time marks

In a CAN basic cycle, communication occurs over a defined Cycle Time in TTCAN, which resets upon receiving reference messages The system matrix is associated with this cycle time through Time Marks, which indicate the beginning of each time window Transmitted Trigger (Tx Trigger) is used for sending messages, while Receiving Trigger (Rx Trigger) facilitates message reception.

In a system matrix with multiple basic cycles, the time mark includes both a base mark and a repeat count The base mark identifies the initial basic cycle for message transmission or reception following the start of the matrix cycle Meanwhile, the repeat count specifies the number of basic cycles that occur between consecutive message transmissions or receptions within the same system matrix.

AT90CAN128 Microcontroller

The specific knowledge about AT90CAN128

The AT90CAN128 microcontroller from Atmel Corporation is an advanced 8-bit device based on enhanced RISC architecture, capable of achieving nearly 1 MIPS per MHz with a CPU clock frequency of 16MHz It supports a variety of applications thanks to its large memory and 32 general-purpose working registers, along with ISP and USART communication capabilities This project incorporates aspects of the AT90CAN128, as illustrated in the accompanying figure.

Parallel I/O ports serve as versatile general-purpose I/O devices, featuring three key registers The Data Direction Register (DDRx) determines whether the pins of the I/O ports function as inputs or outputs The Port Driver Register (PORTx) is responsible for controlling the voltage levels of these pins Lastly, the PINx register stores the current states of each pin within the ports.

The AT90CAN128 features 7 I/O ports with a total of 53 general-purpose I/O lines, each supporting true Read-Modify-Write functionality This allows for the direction of individual port pins to be altered without affecting others, ensuring that changes to drive values or pull-up resistor settings are equally isolated Additionally, these I/O ports can function as communication interfaces (including SPI, USART, and CAN), serve as ADC ports, or receive external clock signals.

An interrupt is a signal that prompts the CPU to halt its current operation and execute a designated piece of code known as the interrupt service routine (ISR) This signal can originate from either external events or internal hardware sources Once the ISR is completed, the program flow resumes from the point of interruption Utilizing interrupts enhances the efficiency and responsiveness of embedded systems to critical events.

When an interrupt occurs, the CPU first saves the program counter and relevant status information before executing the Interrupt Service Routine (ISR) Upon completion of the ISR, a return-from-interrupt instruction restores the saved status information and program counter Each microcontroller organizes its interrupts into a list of fixed addresses known as vectors If interrupt D is active, its fixed vector address, referred to as address AD, is stored in the microcontroller To handle the interrupt, an ISR is written and placed in memory starting at address AISR Consequently, the vector for interrupt D, located at address AD, will either contain a jump instruction to AISR or simply point to address AISR.

An Interrupt Service Routine (ISR) typically takes precedence over regular tasks, as it can complete its operation by executing a return-from-interrupt instruction In contrast, ordinary tasks are designed to run indefinitely, entering a blocked state when there is no data to process.

The AT90CAN128 microcontroller supports various interrupts that are essential for practical applications, including external interrupts for detecting signal changes on pins, Timer/Counter Compare Match Interrupts for PWM manipulation and peripheral device control, and Tx/Rx Complete Interrupts for ensuring complete data transmission In this IRP project, the external ISR, Timer/Counter ISR, and CAN Transfer Complete ISR play crucial roles in achieving the project objectives.

The timer/counter is a versatile tool that measures elapsed time using either the CPU timer or an external timer It can determine time periods, pulse width, speed, frequency, and generate output signals The AT90CAN128 features four timers/counters: Timer/Counter0, Timer/Counter1, Timer/Counter2, and Timer/Counter3 Notably, Timer/Counter0 and Timer/Counter2 are 8-bit counters with single-channel capabilities, primarily used for controlling PWM, although they are not utilized in this project.

The 16-bit Timer/Counter provides precise timing for program execution, wave generation, and signal measurement, controlled by the 8-bit Timer/Counter Control Registers (TCCR1/3) that configure the Prescaler and Waveform Generation Mode The TCNT1/3 register can be clocked internally through the prescaler, while the Input Capture Unit (ICR1/3) and Output Compare Unit (OCR1/3) allow for event capturing and time-stamping Interrupts are managed individually through the Timer Interrupt Mask Register (TIMSK1/3) and monitored in the Timer Interrupt Flag Register (TIFR1/3) The combination of the Waveform Generation Mode and Compare Output mode bits defines the Timer/Counter's operational behavior, particularly in Pulse Width Modulation applications.

PWM (Pulse Width Modulation) is a technique used to convert digital signals into analog signals by adjusting the duty cycle of square wave outputs from microcontroller pins, resulting in varying DC voltage outputs The effective output voltage is the average value, achieved through a combination of Waveform Generation Mode and Compare Output mode bits, which defines the operation mode and allows for variations in output energy and frequency Depending on specific application needs, users can select from various operation modes, including Normal Mode, Clear Timer on Compare Match Mode, Fast PWM Mode, Phase Correct PWM Mode, or Phase and Frequency Correct PWM Mode.

CAN Controller in AT90CAN128

The AT90CAN128 features a V2.0B Active CAN controller equipped with a Message Object (MOb) that manages message information, facilitating acceptance filtering and message management During peripheral initialization, the application specifies which messages to send and receive, allowing the CAN controller to accept only those messages whose identifiers match the programmed receive message objects Once a message is accepted, it is stored, and the application is notified via an interrupt Additionally, the CAN controller can automatically respond to incoming remote frames with the appropriate data frame.

To facilitate communication with the physical bus, a CAN controller requires a CAN controller interface, which in this project is provided by the PCA82C250 device This interface effectively converts the RxCAN or TxCAN signals from the CAN controller into CANH or CANL signals for the physical bus, and also performs the reverse conversion.

The CAN Controller Structure consists of two key components: the CAN channel and the Message Object (MOb) The CAN channel manages the communication parameters of the CAN Controller with the physical bus through the PCA82C250, while the MObs are tasked with processing all CAN messages MObs are configured to operate in specific modes based on the operational requirements.

The CAN Channel serves as the interface between the MObs and the physical bus, operating in three distinct modes The first is Enable Mode, where both the internal TxCAN and RxCAN are activated along with the input clock The second is Standby Mode, in which the transmitter maintains a recessive level while the receiver is disabled; however, the input clock remains active, allowing access to the register and pages Lastly, Listening Mode operates transparently for the CAN Channel, facilitating communication without interfering with the data flow.

To enable effective communication, the Finite State Machine of the CAN channel must synchronize with the time quantum, followed by setting the baud rate to select the optimal sampling point.

The MOb serves as a CAN frame descriptor, encapsulating all necessary information for handling CAN frames, with 15 independent MObs available In cases of multiple matches, priority is given to the lower MOb The operation modes include disabled mode, transmit mode, receive mode, automatic reply, and frame buffer receive mode To ensure the reception of only relevant messages, the Acceptance Filter is utilized, configured through the registers CANID1/2/3/4 and CANIDM1/2/3/4 The AT90CAN128 microcontroller employs the CANPAGE register to navigate among the 15 MObs, allowing the CAN controller to identify the active MOb based on the first four bits of the CANPAGE value Once the appropriate MOb is selected, the data is stored in the CAN Data Message register, CANMSG.

CAN Timer is a programmable 16-bit timer is used for message stamping and time trigger communication

As shown on the figure above, CANTCON is responsible to configure the CAN Timer prescaler The clkCANTIM is calculated by the following formula:

The CANTIM is a 16-bit register that counts from 0x0000 to 0xFFFF and resets to “0” once it exceeds 0xFFFF, starting when the CAN controller is enabled In Time Trigger Communication mode, the CANTTC register captures the CANTIM value upon message arrival or transmission, with the capture time being recorded in the MOb responsible for sending or receiving the frame.

To ensure that messages are fully sent or received, interrupts are utilized to notify the CAN controller Additionally, interrupts play a crucial role in detecting transmission faults, monitoring the availability of message objects (MOb), and assessing the bus state The structure of CAN interrupts is illustrated in the accompanying figure.

On the structure, there are some kinds of interrupts:

- Interrupt on receive completed OK,

- Interrupt on transmit completed OK,

- Interrupt on error (bit error, stuff error, CRC error, form error, acknowledge error),

- Interrupt on the frame buffer full,

- Interrupt on “Bus Off” setting,

- Interrupt on overrun of CAN timer

The general interrupt enable is provided by ENIT bit and the specific interrupt enable for CAN timer overrun is provided by ENORVT bit

This chapter outlines the Nonlinear Model of the IRP and the structural design of four microcontrollers dedicated to IRP control Section 3.1 details the real model of the IRP developed during my student work The subsequent section focuses on establishing the microcontroller structures, beginning with the assignment of responsibilities for each microcontroller and the configuration of the TTCAN communication channel The TTCAN scheduler is then established to define the basic cycle and time window The design process further elaborates on specific actions triggered by individual microcontrollers, detailing which tasks become active upon receiving messages and their respective functions.

Let’s start the interesting works by the nonlinear IRP model.

The nonlinear IRP Model

The IRP model, as presented in Bui (2013), is initially linear; however, it fails to capture all aspects of the IRP due to its nonlinear nature To gain a comprehensive understanding of the IRP, developing a nonlinear model is essential In this nonlinear framework, only the PLANT component will be modified, while the Feedback and Integral components will maintain their original structure.

IRP model is built basing on the original equation system [Bui, 2013]:

) sin ( ) cos sin 2 ( ) cos ( sin

In order to ease the modelling job the equation system (3.2) is rewritten:

M tot input tot tot input

2 sin( cos cos sin cos sin cos sin sin )

The nonlinear Simulink model of the IRP is shown on the figure below

Figure 3.1: The Nonlinear Simulink IRP model with no reference input

The PLANT component undergoes significant structural changes due to the complexity of the IRP machine, resulting in its division into three distinct subsystems: Nominator1, Nominator2, and Denominator.

The equation system (3.2) involves Nominator1, Nominator2, and Denominator, representing the two nominators and the denominator Below, the structural details of the three subsystems are illustrated in the accompanying figures.

In order to reduce the complexity of the Simulink model, some IRP’s parameter such as inertia momentum

Jtot, gravity constants g, the mass m, the rod length L, the arm length r are used more than one time in the subsystems as inputted parameters

The article discusses the DC-motor equation within two nominator subsystems, highlighting its compound structure that categorizes it as a separate subsystem known as DC-motor Torque In the Simulink model, key motor parameters include Kt and Km, while ng, nb, and nm represent the efficiencies of the gearbox, belt transmission, and DC-motor, respectively Additionally, Kg and Kb denote the gear and belt ratios.

Figure 3.6 DC-motor torque subsystem

Because there is no change on the Feedback component, their structures are the same from the section 2.1.2

To enhance the flexibility of the Integrated Robotic Platform (IRP), an integral component has been incorporated into the system, allowing it to operate at any arm angle This addition increases the state vector of the IRP, expanding it to five states.

Figure 3.7: The Nonlinear Simulink IRP model with no reference input

Microcontroller Structures

TTCAN Scheduler

The IRP operates effectively through the coordination of four microcontrollers, which must communicate and share data seamlessly As detailed in section 2.4, this project utilizes TTCAN, with the TTCAN Scheduler being a crucial component The scheduler outlines essential parameters such as the basic cycle duration, the number of time windows and message frames, their transmission timing, and their source and destination All relevant information is illustrated in the accompanying figure.

Effective management of the IRP system relies on critical time response requirements, as the system must promptly detect changes in the pendulum angle to ensure stability The TTCAN scheduler operates on a basic cycle lasting 3 milliseconds, divided into six equal time windows of 0.5 milliseconds each Communication among microcontrollers occurs through three message frames: the Reference message (MasTim) with ID 0x0000, the Angle/Sensor Message (Sensor) with ID 0x0001, and the Push button message (Pusb_uC) with ID 0x0002 The MasTim message, sent by the LCD-uC in Time Window "0," provides the timestamp of the last reference message to correct time drift among microcontrollers The Sensor message, transmitted by SEN-uC in Time Slot 1, conveys the angles of the IRP, while the Pusb_uC message, processed by PUSB-uC and sent in Time Slot 3, includes the PWM value and controlled buttons To manage this data effectively, a compatible structure object, such as struct CAN_message, must be created to store the message contents as outlined in section 2.4.1.

The structure defines an unsigned integer `id` for storing the message identifier, an unsigned char `length` for indicating the data length, and an array `data[8]` to hold the message data, all essential for efficient message handling in communication protocols.

 Data length of three CAN message

The MasTim reference message includes a 16-bit value representing the transmitted time of the last message This information is stored in two bytes within the data array, specifically in data[0] and data[1].

The sensor system utilizes encoders with a resolution of 2000 values per revolution, necessitating the use of integer variables to effectively manage the angles of both the Arm and the Pendulum To transition the pendulum from a downward to an upright position, two distinct pendulum angles are required: one for the swing-up phase, referred to as the Pendulum angle with a zero value at the down position, and another for maintaining the upright position, known as the Pendulum up angle at the exact upright coordinate Consequently, three integer variables are established—one for the arm angle and two for the pendulum angles—resulting in a total of six bytes allocated for these angle variables within the Sensor message, specifically in Sensor.data[0].

Sensor.data[1], Sensor.data[2], Sensor.data[3], Sensor.data[4], Sensor.data[5] The data length on this message is 6 bytes

The Push Button microcontroller message, referred to as Pusb_uC, utilizes an integer PWM value that requires two data bytes for storage Additionally, this message includes the controlled signal from the pressed button, with the data bytes organized in a specific arrangement.

- The first byte Pusb_uC.data[0] stores the started button signal (Button 1 on the button matrix)

- the second byte Pusb_uC.data[1] stores the stopped button signal (button 2),

- the third byte Pusb_uC.data[2] stores the changed reference input button signal (button 3),

- the fourth byte Pusb_uC.data[3] stores the value of reference input data (button 6),

- the fifth byte Pusb_uC.data[4] and the sixth bytes Pusb_uC.data[5] store the PWM data

The three bytes Pusb_uC.data[0], Pusb_uC.data[1], and Pusb_uC.data[2] are designed to store binary values, where a value of "1" indicates that the corresponding button is pressed, while a value of "0" signifies that it is not pressed.

Time Trigger Matrices

The TTCAN Scheduler facilitates the creation of Time Trigger Matrices that govern the operations of microcontrollers Each matrix dictates the timing and actions of specific microcontrollers Initially, an overview of each microcontroller's functions is provided The SEN-uC monitors encoder changes using Interrupt Service Routine (ISR), recording new angles every 3 milliseconds during time slot “0” and transmitting this data in time slot “1.” The LCD-uC receives messages from both the Sensor and Pusb_uC in time slots “2” and “4,” respectively, displaying the information on the LCD screen Similarly, the MOTO-uC processes data like the LCD-uC but uses it to control a DC motor Lastly, the PUSB-uC receives the Sensor message in time slot “2,” processes the sensor data along with button signals, and sends the Pusb_uC message in time slot “3.”

In order to synchronize the four time trigger matrices, they are designed with the same structure and define values The define value meanings are explained as following:

NONE: means there is nothing happened at the respective time slot, and its value is zero “0”

RX_ANGLE: the microcontroller receives the Sensor/Angle message in the current time slot Its value is “1”

RX_PUSB: the microcontroller receives the Pusb_uC message in current time slot Its value is “2”

PR_DATA: the microcontroller prepares sensor data to send on the next time slot Its value is “3”

The Time Trigger Matrices consist of two-dimensional arrays featuring 7 columns and 6 rows, where the rows correspond to six time slots ranging from 0 to 5 The first three columns represent the Time-mark, Base-mark, and Repeat index, with the Time-mark managing the schedule's time windows Each matrix contains a single basic cycle, resulting in Base-mark and Repeat values of "0" and "1," respectively The fourth column, labeled Type, specifies the actions for the TTCAN Scheduler; for instance, if the Type value is 'S' or 's', a CAN message will be transmitted.

If the type is ‘A’ or ‘a’, that time slot is for the arbitrary slot, which will be used in future If the type is ‘T’ or

In a microcontroller system, specific tasks are activated to prepare data based on their designated time slots When the microcontroller communicates by sending or receiving messages, the fifth column indicates the message ID The sixth and seventh columns serve to insert items into semaphores or queues, triggering specific tasks The sixth column is responsible for waking up a task to process incoming data, while the seventh column activates a task to prepare data for transmission.

When the general features are defined, four time trigger matrices will be constructed in subsequently

 SEN-uC const unsigned char Trigger[TIMEMARKS][TRIGGER_INDEX] PROGMEM =

{0, 0, 1, ‘t’, 0x00, NONE, PR_DATA}, // Prepare the Sensor Data

PROGMEN: indicate that the time trigger matrix will be stored in flash memory, make more room for SRAM TIMEMARKS: is defined as “6”

TRIGGER_INDEX: is defined as “7”

Using TIMEMARKS and TRIGGER_INDEX is a convenient way to manage the time trigger matrices during coding phase

This microcontroller gets sensor data from the sensors, save them on Sensor message then transmits them to other microcontroller The detail of this matrix was explained below

- Time slot 0: sends a semaphore to active Data_Preparation task to prepare sensor data

- Time slot 1: Transmit sensor data via CAN BUS

- From time slot 2 to time slot 5: do nothing

 PUSB-uC const unsigned char Trigger[TIMEMARKS][TRIGGER_INDEX] PROGMEM =

{2, 0, 1, ‘r’, 0x11, RX_ANGLE, NONE}, // Receive Angles

{3, 0, 1, ‘s’, 0x12, NONE, NONE}, // Send PUSB_uC

The PUSB-uC calculates the PWM from Sensor message and transmits to LCD-uC and MOTO-uC The action of TTCAN Scheduler is explained following:

- Time slot 2: receives Sensor message

- Time slot 3: Send Pusb_uC message

- Time slot 4 and 5: do nothing

 MOTO-uC const unsigned char Trigger[TIMEMARKS][TRIGGER_INDEX] PROGMEM =

{2, 0, 1, ‘r’, 0x11, RX_ANGLE, NONE}, // receive Angles

{4, 0, 1, ‘r’, 0x12, RX_PUSB, NONE}, // receive Pusb_uC

MOTO-uC receives the Sensor and Pusb_uC messages then uses those data to control DC – motor

- Time slot 0: receive reference message and manipulate the TCNT1 and OCR1A

- Time slot 2: Receive Sensor/Angle message from sensor microcontroller

- Time slot 4: receive Pusb_uC message from Pusb microcontroller to adjust PWM

 LCD-uC const unsigned char Trigger[TIMEMARKS][TRIGGER_INDEX] PROGMEM =

{2, 0, 1, ‘r’, 0x11, RX_ANGLE, NONE}, // Receive Angles

{4, 0, 1, ‘r’, 0x12, RX_PUSB, NONE}, // receive PUSB_uC

The LCD-uC receives data from SEN-uC and PUSB-uC then shows the data on the LCD

- Time slot 2: Receive angle message from sensor microcontroller

- Time slot 4: receives Pusb_uC message and displays the involved information on LCD

The foundations of CAN communication are established, leading to the introduction of the TTCAN_Scheduler Task and the design of the CAN Interrupt Service Routine (ISR) These components are essential for managing the basic cycle and correcting time drift among microcontrollers in relation to the time master.

TTCAN_Scheduler Task and CAN ISR

The TTCAN_Scheduler task and CAN ISR play crucial roles in managing time synchronization, time cycles, and time slot durations across four microcontrollers To ensure consistency, their structures must be analogous in each microcontroller The TTCAN_Scheduler is responsible for overseeing the time cycle, determining time slot durations, and coordinating message transmission and reception, while the CAN ISR focuses on maintaining accurate time synchronization.

To maintain the pendulum in an upright position, the time cycle is set to a brief duration of 3 milliseconds, divided into time slots of 0.5 milliseconds each These time slots, which range from 0 to 5, repeat continuously and are designated for specific actions, including reception and transmission In the system, the TTCAN_Scheduler assigns different tasks that correspond to these specific actions within each time slot.

On time slot 0, the master time microcontroller which is assigned for LCD-uC transmits a reference message

In the upcoming time slots, the SEN-uC transmits a Sensor message, which is subsequently received by another microcontroller in time slot 2 During the third time slot, the PUSB-uC sends a Pusb_uC message, which is then received by both the MOTO-uC and LCD-uC in the following time slot Notably, time slot 5 remains inactive with no system actions taking place.

The CAN Interrupt Service Routine (ISR) is triggered by message transmission, reception, or errors on the CAN Bus, although this discussion assumes error-free communication When a message is successfully sent, the CAN ISR resets the CAN control Data MOb register in preparation for the next transmission Conversely, upon receiving a message without errors, the message is stored in the appropriate struct variable, such as Angles or Pusb_uC, based on its identifier Additionally, if the message is a reference, the incoming data is utilized to adjust the time drift between the received microcontroller and the time master microcontroller.

Each node in the TTCAN protocol operates on its own local time, which must be synchronized with the master node's global time At the completion of each basic cycle, the master node sends a reference message that includes the sending time of the last reference message, stored as Ref_Time Upon receiving this reference message, each node records the time of receipt in a variable called Rx_Time Additionally, the last sending and receiving time points are tracked in the Last_Ref and Last_Rx variables, respectively The time drift parameter is then calculated using a specific formula.

Rf Last Time drift Rf

Then the local interrupt time of OCR1A register is manipulated:

Where Compare is nominated interrupt time value for make a clock tick of FreeRTOS

With the completion of the TTCAN_Scheduler task and CAN ISR design for four microcontrollers, the following section will focus on the specific tasks within each microcontroller that are responsible for processing data to control the DC motor.

Microcontroller Tasks

Each microcontroller in the IRP system has specific responsibilities to ensure optimal functionality The SEN-uC detects changes in two angles, stores this data in global variables, and transmits it to other microcontrollers The LCD-uC receives this information and displays it on the LCD screen Meanwhile, the PUSB-uC processes sensor messages, calculates the PWM, and sends it to the MOTO-uC Finally, the MOTO-uC receives both the sensor frame and the PUSB-uC frame to perform its tasks.

Pendulum angle, which derives from sensor frame, the MOTO-uC chooses which task would be invoked After that, the chosen task manipulates the PWM then control the DC-motor

Microcontrollers operate with multiple tasks that collaborate to perform functions efficiently To determine the execution order of these tasks, implementing a prioritized preemptive scheduling system is essential.

In the synchronized priorities system of the four microcontrollers, there are four levels of priority ranging from 0 to 3, with priority 0 being the lowest and priority 3 the highest The configuration for these priorities is managed in the FreeRTOSConfig.h header file, where priority 0 is designated for the idle task, while priority 3 is reserved for the most critical tasks.

TTCAN_Scheduler task in all 4 microcontrollers Other priorities of each task in each microcontroller would be described in the respective section

This section will introduce the task structures in microcontrollers Before delving into the details, the table below presents various symbols and their meanings that will be referenced in the subsequent sections.

Message frame Queue or semaphore Global variable

Task or ISR (the first index is priority, the second is the task name)

This microcontroller has two primary functions: first, it detects changes in the Pendulum and Arm angles and updates the corresponding global variables, Pen_Ang and Arm_Ang Second, it prepares sensor data based on these global variables during time slot “0” and transmits this information to another microcontroller in time slot “1.” To accomplish the first function, four external interrupt service routines (ISRs) are implemented due to the bidirectional nature of the angle measurements, as detailed in section 2.2.3.

In the time slot “0” of every basic cycle, global variables Pen_Ang, Arm_Ang are saved to four data bytes of

In section 3.2.2, the Sensor/Angle message is introduced, which requires the transfer of Pen_Ang and Arm_Ang values to the Angle message To facilitate this transfer, a task called Data_Preparation is created, which is triggered every three milliseconds by a semaphore signal [Richard Barry, 2004].

The TTCAN_Scheduler task is responsible for managing the transmission of the Angle message Once the Angle message is prepared, it awaits transmission by the TTCAN_Scheduler When the designated time slot “1” arrives, the Angle message is sent to another microcontroller.

CAN bus The whole process is presented in the figure below

Figure 3.10 Time Trigger Plan of SEN-uC

As the IRP operates, its two angles undergo changes that are monitored by an external ISR, which subsequently stores the updated angle values in designated global variables When the time slot "0" arrives, these new values are utilized for further processing.

The TTCAN_Scheduler activates the Data_Reception() task using the WakeTaskSe semaphore, which then stores the updated Pen_Angle and Arm_Angle values in the Angle message Subsequently, during the next time slot, the TTCAN_Scheduler will transmit the Angle message.

In SEN-uC, there are two primary tasks: "Data_Preparation" and "uC_Check." The "Data_Preparation" task, previously detailed, is assigned a higher priority of "2," while the "uC_Check," which monitors the microcontroller's state, holds a lower priority of "1."

This microcontroller receives two messages Sensor and Pusb_uC then display the needed data on the LCD

To manage separate duties, two distinct tasks are established: Data_Reception() for receiving messages and LCD_Display() for displaying information on the LCD Struct variables are created to handle the two messages, along with two global integer variables to store the angles The tasks and TTCAN_Scheduler are illustrated in the accompanying figure.

Figure 3.11 Time Trigger Plan of LCD-uC

The TTCAN_Scheduler task triggers the Data_Reception() task by sending an item to the queue when a message arrives at a designated time slot This task processes the message data and updates two global variables, Pen_Ang and Arm_Ang, which are then displayed on the LCD by the LCD_Display() task Notably, the Data_Reception() task operates with a priority level of "2," while the LCD_Display() task holds a higher priority of "1."

On the LCD, some information should be shown:

- The greeting to the program: Welcome to IRP

- The states of IRP: (Power on, Change input, swing up, Steady State, Stop)

- Two angles of IRP: P_Ang, A_Ang

- Started/Stopped Button: display which to start, which to stop the IRP

- Change the ref input button: display which button to increase, which button to decrease Ref Input

- Finish changing ref Input button: display which button finish the changing process

- Button to start or stop oscillation

To effectively display all necessary information, a minimum of eleven rows is required on the LCD However, due to the LCD's limitation of only showing eight rows, the information is divided across two screens The first screen presents the data as illustrated in the accompanying figure.

States: Power on/Swing up/Steady State/Stop

Push B1 to start/ Push B2 to stop Push B3 to change the ref input /

The second screen displays the following information:

Push B4 to increase ref Input Push B5 to decrease ref Input Push B6 to finish Button 7: Oscillation

The structure design of LCD is completed There are two implemented tasks in this microcontroller, they are

Data_Reception() and LCD_Display() All the information of the IRP is shown on two screens, which were described above The next part will discuss about the MOTO-uC

The microcontroller processes the Angles/Sensor message during time slot 2 and stores the results in the Pusb_uC message Additionally, it detects button presses that control the IRP operation, allowing users to modify the global variable NomInput for reference input or to save new values in specific bytes of the Pusb_uC message.

The Pusb_uC message is transmitted over the CAN bus through the TTCAN_Scheduler task, allowing for the separation of duties that can be executed by two parallel tasks One of these tasks is responsible for calculating the PWM.

The common parts

SEN-uC

MOTO-uC

Parameters Estimation

Results

Discussion

Ngày đăng: 11/10/2023, 19:59

TỪ KHÓA LIÊN QUAN

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

TÀI LIỆU LIÊN QUAN

w