This document provides an overview of C programming for embedded microcontroller systems. It discusses program structure, data types, variables, operators, control structures, functions, interrupts, and memory mapping. Specific topics covered include basic C program components and layout, microcontroller memory maps, header files, data types and sizes, constant values, variable scopes (automatic and static), arithmetic and logical operators, and basic C statement types. The intended audience is those with experience in assembly language programming who want to learn C for embedded applications.
C was created in the early 1970s at Bell Labs by Dennis Ritchie. It is commonly used for systems programming like operating systems and compilers. C code is compiled into efficient, portable machine code. A C program structure includes preprocessor commands, functions, variables, statements/expressions, and comments. Key C language elements are keywords, identifiers, constants, comments, and symbols. C supports various data types like int, char, float, and double that determine memory usage and value representation. Variables must be declared with a specific data type before use.
1. Embedded C requires compilers to create files that can be downloaded and run on microcontrollers, while C compilers typically generate OS-dependent executables for desktop computers.
2. Embedded systems often have real-time constraints and limited memory/power that are usually not concerns for desktop applications.
3. Programming for embedded systems requires optimally using limited resources and satisfying real-time constraints, which is done using the basic C syntax and function libraries but with an embedded/hardware-oriented mindset.
1. Embedded C requires compilers to create executable files that can be downloaded and run on microcontrollers, while C compilers typically generate code for operating systems on desktop computers.
2. Embedded systems often have real-time constraints and limited memory and other resources that require more optimization, unlike most desktop applications.
3. Programming for embedded systems focuses on optimally using limited resources and satisfying timing requirements using basic C constructs and function libraries.
The document discusses microprocessors, their architecture, instructions, operations, interfacing and the 8085 and 8086 microprocessors. It provides details on the functional blocks, registers, addressing modes, procedures, calling conventions, and stack usage of the 8086 microprocessor. It also describes various assembler directives, operators, and concepts like logical segments, procedures, and passing parameters in registers vs memory for procedures.
Static scheduling machines like VLIW move instruction scheduling from hardware to compiler by packing multiple operations into single instructions. This simplifies hardware but requires compilers to explicitly represent dependencies. The Intel Itanium ISA follows the VLIW philosophy, using instruction bundles containing up to 3 operations. Itanium 2 improved on the original design with an 8-stage pipeline and register renaming to boost performance. Itanium supports both control and data speculation via techniques like speculative loads and the Advanced Load Address Table.
Fundamentals of Programming Constructs.pptxvijayapraba1
The algorithm involves taking Celsius temperature as input, multiplying it by 1.8 and adding 32 to convert it to Fahrenheit. This is implemented in a C program that takes Celsius input, performs the conversion calculation and prints the Fahrenheit output.
Embedded C is a subset of the C programming language used for embedded systems that excludes large features and focuses on efficiency; it uses preprocessor directives, handles variables in local and global scopes, and can pass parameters by value or reference. Embedded C++ further restricts C++ for embedded use by removing features like multiple inheritance and runtime type identification. The document discusses optimizing embedded C and C++ code, common patterns like super loop architectures, and guidelines for writing embedded C code.
This document provides information about integer and floating point files in Allen-Bradley SLC-500 and LogixPro PLCs. It discusses:
- Default and user-defined file types for integers (N7) and floating point (F8) data.
- The integer file can store 256 16-bit words of integer data. The floating point file stores non-extended 32-bit numbers in two 16-bit words each.
- Examples of addressing integers (N7:0) and floating point (F8:4) values in these files.
C was created in the early 1970s at Bell Labs by Dennis Ritchie. It is commonly used for systems programming like operating systems and compilers. C code is compiled into efficient, portable machine code. A C program structure includes preprocessor commands, functions, variables, statements/expressions, and comments. Key C language elements are keywords, identifiers, constants, comments, and symbols. C supports various data types like int, char, float, and double that determine memory usage and value representation. Variables must be declared with a specific data type before use.
1. Embedded C requires compilers to create files that can be downloaded and run on microcontrollers, while C compilers typically generate OS-dependent executables for desktop computers.
2. Embedded systems often have real-time constraints and limited memory/power that are usually not concerns for desktop applications.
3. Programming for embedded systems requires optimally using limited resources and satisfying real-time constraints, which is done using the basic C syntax and function libraries but with an embedded/hardware-oriented mindset.
1. Embedded C requires compilers to create executable files that can be downloaded and run on microcontrollers, while C compilers typically generate code for operating systems on desktop computers.
2. Embedded systems often have real-time constraints and limited memory and other resources that require more optimization, unlike most desktop applications.
3. Programming for embedded systems focuses on optimally using limited resources and satisfying timing requirements using basic C constructs and function libraries.
The document discusses microprocessors, their architecture, instructions, operations, interfacing and the 8085 and 8086 microprocessors. It provides details on the functional blocks, registers, addressing modes, procedures, calling conventions, and stack usage of the 8086 microprocessor. It also describes various assembler directives, operators, and concepts like logical segments, procedures, and passing parameters in registers vs memory for procedures.
Static scheduling machines like VLIW move instruction scheduling from hardware to compiler by packing multiple operations into single instructions. This simplifies hardware but requires compilers to explicitly represent dependencies. The Intel Itanium ISA follows the VLIW philosophy, using instruction bundles containing up to 3 operations. Itanium 2 improved on the original design with an 8-stage pipeline and register renaming to boost performance. Itanium supports both control and data speculation via techniques like speculative loads and the Advanced Load Address Table.
Fundamentals of Programming Constructs.pptxvijayapraba1
The algorithm involves taking Celsius temperature as input, multiplying it by 1.8 and adding 32 to convert it to Fahrenheit. This is implemented in a C program that takes Celsius input, performs the conversion calculation and prints the Fahrenheit output.
Embedded C is a subset of the C programming language used for embedded systems that excludes large features and focuses on efficiency; it uses preprocessor directives, handles variables in local and global scopes, and can pass parameters by value or reference. Embedded C++ further restricts C++ for embedded use by removing features like multiple inheritance and runtime type identification. The document discusses optimizing embedded C and C++ code, common patterns like super loop architectures, and guidelines for writing embedded C code.
This document provides information about integer and floating point files in Allen-Bradley SLC-500 and LogixPro PLCs. It discusses:
- Default and user-defined file types for integers (N7) and floating point (F8) data.
- The integer file can store 256 16-bit words of integer data. The floating point file stores non-extended 32-bit numbers in two 16-bit words each.
- Examples of addressing integers (N7:0) and floating point (F8:4) values in these files.
The document provides an introduction to the 8085 microprocessor. It discusses the basic components of a microcomputer including the CPU, memory (RAM and ROM), and I/O unit. It then describes the internal structure of the 8085 CPU including its registers, flag bits, program counter, and stack pointer. The document outlines the 8085 bus structure including its address bus, data bus, and control signals. It provides timing diagrams for opcode fetch, memory read, and memory write operations. Finally, it discusses addressing modes, instruction size, and includes a table of the 8085 instruction set.
The document provides an overview of computer organization and architecture. It discusses the basic components of a computer including the CPU, memory, and registers. It then describes the specific architecture of a basic computer model, including its instruction set, addressing modes, and register set. The basic computer uses a 16-bit word size and has instructions for memory access, register operations, and input/output. It connects its registers through a common 16-bit bus controlled by three lines.
This presentation discusses an embedded system project to control a fan based on temperature. It includes:
- An overview of Skyphi Technologies, an organization that provides training in embedded systems and other domains.
- A definition of embedded systems and examples like ATMs, aircraft systems, and more.
- An introduction to the AVR microcontroller and its features like the ATmega8, programming tools, and pin diagram.
- Explanations of embedded C programming structure, I/O ports, registers, and programming the AVR microcontroller.
- Details of the temperature controlled fan project including components, working principle, circuit diagram, and code overview.
- Applications of the temperature controlled fan
Function pointers allow a function to be passed as an argument to another function. The document discusses different types of function pointers in C like near pointers, far pointers, and huge pointers. It also discusses how function pointers allow implementing operations like search and sort using callbacks rather than switch statements. Passing functions as arguments provides flexibility and replaces long repetitive code with jump tables.
A microprocessor is the main component of a microcomputer system and is also ...jeronimored
The document describes the curriculum for a course on microprocessors and their applications. It contains 5 modules: 1) Introduction, 2) 8085 pins, 3) 8085 architecture and programming, 4) interfacing techniques, and 5) other 8-bit microprocessors. Module 1 introduces basic microcomputer concepts like CPU, memory, I/O, hardware, and software. Module 2 describes the various pin categories and functions of the 8085 microprocessor. Module 3 discusses the 8085 architecture including registers, ALU, programming, and instruction set. Module 4 covers interfacing memories and I/O devices to the 8085. Module 5 provides an introduction to other 8-bit microprocessors like the Z80 and MC6800
This document discusses the architecture and programming of the 8051 microcontroller. It begins by outlining the objectives and outcomes of studying the 8051. It then provides details on the basics of the 8051 architecture, including its internal blocks like RAM, registers, timers, ports, and memory organization. It also compares microcontrollers to general purpose microprocessors. Finally, it discusses the internal registers of the 8051 like the program counter, stack pointer, and special function registers in detail.
The document discusses digital signal processors and digital signal controllers. It begins with an overview of microprocessors and microcontrollers before explaining that digital signal processors have additional hardware units that allow them to perform mathematical operations more efficiently compared to general purpose microprocessors. Digital signal controllers combine the computational power of a digital signal processor with integrated memory and peripherals on a single chip for embedded real-time control applications involving intensive math operations. Texas Instruments is a major manufacturer of digital signal processors and produces the C2000 family of digital signal controllers.
This document provides information about the 8-bit microprocessor unit REE602, including its instruction format, pin diagram, internal architecture, instruction types, and examples of instruction classification. It discusses the instruction format, one-byte, two-byte, and three-byte instructions. It also summarizes the pin diagram, internal architecture, timing diagrams, and provides examples of different types of instructions including data transfer, arithmetic, logical, and branching instructions.
Introduction in Security given by Bart Van Bos at Nalys.
Topics:
- Buffer overflows in C
- Counter measures
- Life demo of 2 attacks
- Shellcode generation
Lecture slides that I used in Advanced Information Security Summer School (AIS3, 2016 & 2018) in Taiwan. https://ais3.org/
台湾の高度セキュリティ人材育成プログラム(AIS3, 2016/2018)の講義で利用した講義資料です。
The document describes the internal architecture of the 8086 microprocessor. It has two main blocks: the Bus Interface Unit (BIU) and Execution Unit (EU). The BIU handles fetching instructions and data from memory and I/O, while the EU decodes and executes instructions. The 8086 uses general purpose registers like AX, BX, CX, DX as well as segment registers, pointers, and a flag register to control operations and store temporary data as it executes instructions.
Embedded Application : An Autonomous Robot or Line Follower BotEr. Raju Bhardwaj
This document discusses a line follower robot and embedded systems. It provides details about:
1. A line follower robot is a machine that follows a black or white line on a surface using infrared sensors to detect the line.
2. An embedded system combines hardware and software and is used in applications like personal computers, phones, home automation, and more. It requires inputs, processing, and outputs.
3. Microcontrollers like the ATmega8 are commonly used as the "brain" of embedded systems and robots to control inputs, outputs, and processing. The document discusses registers used to configure ports on the microcontroller.
The document contains questions and explanations about C programming keywords and concepts like pointers, arrays, structures, unions, and bit manipulation. It provides definitions and examples for keywords like #define, #include, #pragma, #asm, #ifdef, and #endif. It also gives solutions to questions about pointers, counting bits to access specific bits or bytes of memory at a particular address, and explaining differences between array parameters and pointers in function definitions in C.
The document describes the architecture of the Pentium family processor. It discusses the Pentium processor's architecture including its 64-bit data bus, separate code and data caches, pipeline sequence, and superscalar execution using two pipelines. It also describes the Pentium's registers including the general purpose, segment, debug, and EFlags registers. Finally, it discusses the Pentium's bus description including the address bus, data bus, control bus, byte enables, and bus cycles.
Assemblers take assembly code written in symbolic mnemonics and convert it into machine-readable object code. They evaluate the operation field of each instruction to find the corresponding machine code value. Assemblers also generate location counter values and other information needed by the loader. Assembly programs contain labels, opcodes, operands, and comments. Assembler directives provide instructions to the assembler itself rather than generating machine codes. Common directives include START and END to specify the beginning and end of a program. VAX, Pentium Pro, and other architectures have different data formats, instruction formats, addressing modes, instruction sets, and I/O methods.
This document summarizes four problems completed in a lab using a Tiva C Series microcontroller. Problem 1 introduced the microcontroller and Code Composer Studio software. Problem 2 described header files used in the code. Problem 3 explored adjusting clock speeds. Problem 4 provided an overview of the microcontroller platform, peripheral drivers library, and GPIO module. The code caused three LEDs to blink by writing pin values using delays timed based on clock speed.
The document discusses writing C code for the 8051 microcontroller using the Keil compiler. It describes the Keil compiler's limitations in the evaluation version, modifications made to the C language to support microcontrollers, and provides examples of writing C code that interfaces with hardware registers and uses interrupts. The purpose is to explain how to develop software for the 8051 microcontroller using the Keil compiler and its C extensions.
The document discusses several topics related to computer architecture and assembly language programming:
1. It describes the von Neumann architecture model and key components like the ALU, control unit, and memory.
2. It summarizes Moore's Law and how increasing transistor density has allowed for higher performance chips over time.
3. It provides an overview of some early Intel processors like the 8086 and techniques used to increase processor speed like pipelining.
4. It includes brief explanations of common assembly language concepts like registers, memory addressing, and arithmetic and logical instructions.
हिंदी वर्णमाला पीपीटी, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, हिंदी स्वर, हिंदी व्यंजन, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
The document provides an introduction to the 8085 microprocessor. It discusses the basic components of a microcomputer including the CPU, memory (RAM and ROM), and I/O unit. It then describes the internal structure of the 8085 CPU including its registers, flag bits, program counter, and stack pointer. The document outlines the 8085 bus structure including its address bus, data bus, and control signals. It provides timing diagrams for opcode fetch, memory read, and memory write operations. Finally, it discusses addressing modes, instruction size, and includes a table of the 8085 instruction set.
The document provides an overview of computer organization and architecture. It discusses the basic components of a computer including the CPU, memory, and registers. It then describes the specific architecture of a basic computer model, including its instruction set, addressing modes, and register set. The basic computer uses a 16-bit word size and has instructions for memory access, register operations, and input/output. It connects its registers through a common 16-bit bus controlled by three lines.
This presentation discusses an embedded system project to control a fan based on temperature. It includes:
- An overview of Skyphi Technologies, an organization that provides training in embedded systems and other domains.
- A definition of embedded systems and examples like ATMs, aircraft systems, and more.
- An introduction to the AVR microcontroller and its features like the ATmega8, programming tools, and pin diagram.
- Explanations of embedded C programming structure, I/O ports, registers, and programming the AVR microcontroller.
- Details of the temperature controlled fan project including components, working principle, circuit diagram, and code overview.
- Applications of the temperature controlled fan
Function pointers allow a function to be passed as an argument to another function. The document discusses different types of function pointers in C like near pointers, far pointers, and huge pointers. It also discusses how function pointers allow implementing operations like search and sort using callbacks rather than switch statements. Passing functions as arguments provides flexibility and replaces long repetitive code with jump tables.
A microprocessor is the main component of a microcomputer system and is also ...jeronimored
The document describes the curriculum for a course on microprocessors and their applications. It contains 5 modules: 1) Introduction, 2) 8085 pins, 3) 8085 architecture and programming, 4) interfacing techniques, and 5) other 8-bit microprocessors. Module 1 introduces basic microcomputer concepts like CPU, memory, I/O, hardware, and software. Module 2 describes the various pin categories and functions of the 8085 microprocessor. Module 3 discusses the 8085 architecture including registers, ALU, programming, and instruction set. Module 4 covers interfacing memories and I/O devices to the 8085. Module 5 provides an introduction to other 8-bit microprocessors like the Z80 and MC6800
This document discusses the architecture and programming of the 8051 microcontroller. It begins by outlining the objectives and outcomes of studying the 8051. It then provides details on the basics of the 8051 architecture, including its internal blocks like RAM, registers, timers, ports, and memory organization. It also compares microcontrollers to general purpose microprocessors. Finally, it discusses the internal registers of the 8051 like the program counter, stack pointer, and special function registers in detail.
The document discusses digital signal processors and digital signal controllers. It begins with an overview of microprocessors and microcontrollers before explaining that digital signal processors have additional hardware units that allow them to perform mathematical operations more efficiently compared to general purpose microprocessors. Digital signal controllers combine the computational power of a digital signal processor with integrated memory and peripherals on a single chip for embedded real-time control applications involving intensive math operations. Texas Instruments is a major manufacturer of digital signal processors and produces the C2000 family of digital signal controllers.
This document provides information about the 8-bit microprocessor unit REE602, including its instruction format, pin diagram, internal architecture, instruction types, and examples of instruction classification. It discusses the instruction format, one-byte, two-byte, and three-byte instructions. It also summarizes the pin diagram, internal architecture, timing diagrams, and provides examples of different types of instructions including data transfer, arithmetic, logical, and branching instructions.
Introduction in Security given by Bart Van Bos at Nalys.
Topics:
- Buffer overflows in C
- Counter measures
- Life demo of 2 attacks
- Shellcode generation
Lecture slides that I used in Advanced Information Security Summer School (AIS3, 2016 & 2018) in Taiwan. https://ais3.org/
台湾の高度セキュリティ人材育成プログラム(AIS3, 2016/2018)の講義で利用した講義資料です。
The document describes the internal architecture of the 8086 microprocessor. It has two main blocks: the Bus Interface Unit (BIU) and Execution Unit (EU). The BIU handles fetching instructions and data from memory and I/O, while the EU decodes and executes instructions. The 8086 uses general purpose registers like AX, BX, CX, DX as well as segment registers, pointers, and a flag register to control operations and store temporary data as it executes instructions.
Embedded Application : An Autonomous Robot or Line Follower BotEr. Raju Bhardwaj
This document discusses a line follower robot and embedded systems. It provides details about:
1. A line follower robot is a machine that follows a black or white line on a surface using infrared sensors to detect the line.
2. An embedded system combines hardware and software and is used in applications like personal computers, phones, home automation, and more. It requires inputs, processing, and outputs.
3. Microcontrollers like the ATmega8 are commonly used as the "brain" of embedded systems and robots to control inputs, outputs, and processing. The document discusses registers used to configure ports on the microcontroller.
The document contains questions and explanations about C programming keywords and concepts like pointers, arrays, structures, unions, and bit manipulation. It provides definitions and examples for keywords like #define, #include, #pragma, #asm, #ifdef, and #endif. It also gives solutions to questions about pointers, counting bits to access specific bits or bytes of memory at a particular address, and explaining differences between array parameters and pointers in function definitions in C.
The document describes the architecture of the Pentium family processor. It discusses the Pentium processor's architecture including its 64-bit data bus, separate code and data caches, pipeline sequence, and superscalar execution using two pipelines. It also describes the Pentium's registers including the general purpose, segment, debug, and EFlags registers. Finally, it discusses the Pentium's bus description including the address bus, data bus, control bus, byte enables, and bus cycles.
Assemblers take assembly code written in symbolic mnemonics and convert it into machine-readable object code. They evaluate the operation field of each instruction to find the corresponding machine code value. Assemblers also generate location counter values and other information needed by the loader. Assembly programs contain labels, opcodes, operands, and comments. Assembler directives provide instructions to the assembler itself rather than generating machine codes. Common directives include START and END to specify the beginning and end of a program. VAX, Pentium Pro, and other architectures have different data formats, instruction formats, addressing modes, instruction sets, and I/O methods.
This document summarizes four problems completed in a lab using a Tiva C Series microcontroller. Problem 1 introduced the microcontroller and Code Composer Studio software. Problem 2 described header files used in the code. Problem 3 explored adjusting clock speeds. Problem 4 provided an overview of the microcontroller platform, peripheral drivers library, and GPIO module. The code caused three LEDs to blink by writing pin values using delays timed based on clock speed.
The document discusses writing C code for the 8051 microcontroller using the Keil compiler. It describes the Keil compiler's limitations in the evaluation version, modifications made to the C language to support microcontrollers, and provides examples of writing C code that interfaces with hardware registers and uses interrupts. The purpose is to explain how to develop software for the 8051 microcontroller using the Keil compiler and its C extensions.
The document discusses several topics related to computer architecture and assembly language programming:
1. It describes the von Neumann architecture model and key components like the ALU, control unit, and memory.
2. It summarizes Moore's Law and how increasing transistor density has allowed for higher performance chips over time.
3. It provides an overview of some early Intel processors like the 8086 and techniques used to increase processor speed like pipelining.
4. It includes brief explanations of common assembly language concepts like registers, memory addressing, and arithmetic and logical instructions.
Similar to C programming for embedded system applications.pptx (20)
हिंदी वर्णमाला पीपीटी, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, हिंदी स्वर, हिंदी व्यंजन, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
Assessment and Planning in Educational technology.pptxKavitha Krishnan
In an education system, it is understood that assessment is only for the students, but on the other hand, the Assessment of teachers is also an important aspect of the education system that ensures teachers are providing high-quality instruction to students. The assessment process can be used to provide feedback and support for professional development, to inform decisions about teacher retention or promotion, or to evaluate teacher effectiveness for accountability purposes.
it describes the bony anatomy including the femoral head , acetabulum, labrum . also discusses the capsule , ligaments . muscle that act on the hip joint and the range of motion are outlined. factors affecting hip joint stability and weight transmission through the joint are summarized.
How to Build a Module in Odoo 17 Using the Scaffold MethodCeline George
Odoo provides an option for creating a module by using a single line command. By using this command the user can make a whole structure of a module. It is very easy for a beginner to make a module. There is no need to make each file manually. This slide will show how to create a module using the scaffold method.
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
This presentation was provided by Steph Pollock of The American Psychological Association’s Journals Program, and Damita Snow, of The American Society of Civil Engineers (ASCE), for the initial session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session One: 'Setting Expectations: a DEIA Primer,' was held June 6, 2024.
Thinking of getting a dog? Be aware that breeds like Pit Bulls, Rottweilers, and German Shepherds can be loyal and dangerous. Proper training and socialization are crucial to preventing aggressive behaviors. Ensure safety by understanding their needs and always supervising interactions. Stay safe, and enjoy your furry friends!
C programming for embedded system applications.pptx
1. C programming for embedded
microcontroller systems.
Assumes experience with
assembly language programming.
V. P. Nelson
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
2. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Outline
• Program organization and microcontroller
memory
• Data types, constants, variables
• Microcontroller register/port addresses
• Operators: arithmetic, logical, shift
• Control structures: if, while, for
• Functions
• Interrupt routines
3. Basic C program structure
#include "STM32L1xx.h" /* I/O port/register names/addresses for the STM32L1xx microcontrollers */
/* Global variables – accessible by all functions */
int count, bob; //global (static) variables – placed in RAM
/* Function definitions*/
int function1(char x) { //parameter x passed to the function, function returns an integer value
int i,j; //local (automatic) variables – allocated to stack or registers
-- instructions to implement the function
}
/* Main program */
void main(void) {
unsigned char sw1;
int k;
//local (automatic) variable (stack or registers)
//local (automatic) variable (stack or registers)
/* Initialization section */
-- instructions to initialize variables, I/O ports, devices, function registers
/* Endless loop */
while (1) { //Can also use: for(;;) {
-- instructions to be repeated
} /* repeat forever */
}
Declare local variables
Initialize variables/devices
Body of the program
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
4. STM32L100RC µC memory map
0xE00F FFFF
0xE000 0000
0x4002 67FF
0x4000 0000
0x2000 3FFF
0x2000 0000
0x0803 FFFF
Control/data registers: Cortex-M3 CPU functions
(NVIC, SysTick Timer, etc.)
Control/data registers: microcontroller peripherals
(timers, ADCs, UARTs, etc.)
256K byte Flash memory:
program code & constant data storage
Reset & interrupt vectors: in 1st words of flash memory
0x0800 0000
16K byte RAM: variable & stack storage
Address
Vacant
Cortex
registers
Vacant
Peripheral
registers
Vacant
16KB RAM
Vacant
256KB Flash
Memory
Vacant
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
0xFFFF FFFF
5. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Microcontroller “header file”
• Keil MDK-ARM provides a derivative-specific “header
file” for each microcontroller, which defines memory
addresses and symbolic labels for CPU and peripheral
function register addresses.
#include "STM32L1xx.h“ /* target uC information */
// GPIOA configuration/data register addresses are defined in STM32L1xx.h
void main(void) {
uint16_t PAval;
GPIOA->MODER &= ~(0x00000003);
PAval = GPIOA->IDR;
//16-bit unsigned variable
// Set GPIOA pin PA0 as input
// Set PAval to 16-bits from GPIOA
for(;;) {} /* execute forever */
}
6. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
C compiler data types
• Always match data type to data characteristics!
• Variable type indicates how data is represented
• #bits determines range of numeric values
• signed/unsigned determines which arithmetic/relational
operators are to be used by the compiler
• non-numeric data should be “unsigned”
• Header file “stdint.h” defines alternate type names
for standard C data types
• Eliminates ambiguity regarding #bits
• Eliminates ambiguity regarding signed/unsigned
(Types defined on next page)
7. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
C compiler data types
Data type declaration * Number of bits Range of values
char k;
unsigned char k;
uint8_t k;
8 0..255
signed char k;
int8_t k;
8 -128..+127
short k;
signed short k;
int16_t k;
16 -32768..+32767
unsigned short k;
uint16_t k;
16 0..65535
int k;
signed int k;
int32_t k;
32 -2147483648..
+2147483647
unsigned int k;
uint32_t k;
32 0..4294967295
* intx_t and uintx_t defined in stdint.h
8. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Data type examples
• Read bits from GPIOA (16 bits, non-numeric)
– uint16_t n; n = GPIOA->IDR; //or: unsigned short n;
• Write TIM2 prescale value (16-bit unsigned)
– uint16_t t; TIM2->PSC = t; //or: unsigned short t;
• Read 32-bit value from ADC (unsigned)
– uint32_t a; a = ADC; //or: unsigned int a;
• System control value range [-1000…+1000]
– int32_t ctrl; ctrl = (x + y)*z; //or: int ctrl;
• Loop counter for 100 program loops (unsigned)
– uint8_t cnt; //or: unsigned char cnt;
– for (cnt = 0; cnt < 20; cnt++) {
9. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Constant/literal values
• Decimal is the default number format
int m,n; //16-bit signed numbers
m = 453; n = -25;
• Hexadecimal: preface value with 0x or 0X
m = 0xF312; n = -0x12E4;
• Octal: preface value with zero (0)
m = 0453; n = -023;
Don’t use leading zeros on “decimal” values. They will be interpreted as octal.
• Character: character in single quotes, or ASCII value following “slash”
m = ‘a’;
n = ‘13’;
//ASCII value 0x61
//ASCII value 13 is the “return” character
• String (array) of characters:
unsigned char k[7];
strcpy(m,“hellon”); //k[0]=‘h’, k[1]=‘e’, k[2]=‘l’, k[3]=‘l’, k[4]=‘o’,
//k[5]=13 or ‘n’ (ASCII new line character),
//k[6]=0 or ‘0’ (null character – end of string)
10. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Program variables
• A variable is an addressable storage location
to information to be used by the program
– Each variable must be declared to indicate size
and type of information to be stored, plus name
to be used to reference the information
int x,y,z;
char a,b;
//declares 3 variables of type “int”
//declares 2 variables of type “char”
– Space for variables may be allocated in registers,
RAM, or ROM/Flash (for constants)
– Variables can be automatic or static
11. Variable arrays
• An array is a set of data, stored in consecutive
memory locations, beginning at a named address
– Declare array name and number of data elements, N
– Elements are “indexed”, with indices [0 .. N-1]
int n[5];
n[3] = 5;
//declare array of 5 “int” values
//set value of 4th array element
n[0]
n[1]
n[2]
n[3]
n[4]
Address:
n
n+4
n+8
n+12
n+16
Note: Index of first element is always 0.
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
12. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Automatic variables
• Declare within a function/procedure
• Variable is visible (has scope) only within that
function
– Space for the variable is allocated on the system
stack when the procedure is entered
• Deallocated, to be re-used, when the procedure is exited
– If only 1 or 2 variables, the compiler may allocate
them to registers within that procedure, instead of
allocating memory.
– Values are not retained between procedure calls
13. Automatic variable example
void delay () {
int i,j; //automatic variables – visible only within delay()
//outer loop
//inner loop
//do nothing
for (i=0; i<100; i++) {
for (j=0; j<20000; j++) {
}
}
} Variables must be initialized each
time the procedure is entered since
values are not retained when the
procedure is exited.
MDK-ARM (in my example): allocated registers r0,r2 for variables i,j
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
14. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Static variables
• Retained for use throughout the program in RAM
locations that are not reallocated during program
execution.
• Declare either within or outside of a function
– If declared outside a function, the variable is global in scope,
i.e. known to all functions of the program
• Use “normal” declarations. Example: int count;
– If declared within a function, insert key word static before
the variable definition. The variable is local in scope, i.e.
known only within this function.
static unsigned char bob;
static int pressure[10];
15. Static variable example
unsigned char count; //global variable is static – allocated a fixed RAM location
//count can be referenced by any function
void math_op () {
int i;
static int j;
if (count == 0)
j = 0;
i = count;
j = j + i;
//automatic variable – allocated space on stack when function entered
//static variable – allocated a fixed RAM location to maintain the value
//test value of global variable count
//initialize static variable j first time math_op() entered
//initialize automatic variable i each time math_op() entered
//change static variable j – value kept for next function call
//return & deallocate space used by automatic variable i
}
void main(void) {
count = 0;
while (1) {
math_op();
count++;
}
}
Fall 2014 - ARM Version
//initialize global variable count
//increment global variable count
ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
16. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
C statement types
• Simple variable assignments
– Includes input/output data transfers
• Arithmetic operations
• Logical/shift operations
• Control structures
– IF, WHEN, FOR, SELECT
• Function calls
– User-defined and/or library functions
17. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Arithmetic operations
• C examples – with standard arithmetic operators
int i, j, k;
uint8_t m,n,p;
i = j + k;
m = n - 5;
j = i * k;
m = n / p;
m = n % p;
// 32-bit signed integers
// 8-bit unsigned numbers
// add 32-bit integers
// subtract 8-bit numbers
// multiply 32-bit integers
// quotient of 8-bit divide
// remainder of 8-bit divide
i = (j + k) * (i – 2); //arithmetic expression
*, /, % are higher in precedence than +, - (higher precedence applied 1st)
Example: j * k + m / n = (j * k) + (m / n)
Floating-point formats are not directly supported by Cortex-M3 CPUs.
18. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Bit-parallel logical operators
Bit-parallel (bitwise) logical operators produce n-bit results of the
corresponding logical operation:
& (AND) | (OR) ^ (XOR) ~ (Complement)
C = A & B; A 0 1 1 0 0 1 1 0
(AND) B 1 0 1 1 0 0 1 1
C 0 0 1 0 0 0 1 0
C = A | B; A 0 1 1 0 0 1 0 0
(OR) B 0 0 0 1 0 0 0 0
C 0 1 1 1 0 1 0 0
C = A ^ B; A 0 1 1 0 0 1 0 0
(XOR) B 1 0 1 1 0 0 1 1
C 1 1 0 1 0 1 1 1
B = ~A; A 0 1 1 0 0 1 0 0
(COMPLEMENT) B 1 0 0 1 1 0 1 1
19. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Bit set/reset/complement/test
• Use a “mask” to select bit(s) to be altered
C = A & 0xFE; A a b c d e f g h
0xFE 1 1 1 1 1 1 1 0
C a b c d e f g 0
C = A & 0x01; A a b c d e f g h
0xFE 0 0 0 0 0 0 0 1
C 0 0 0 0 0 0 0 h
C = A | 0x01; A a b c d e f g h
0x01
C
0 0 0 0 0 0 0
a b c d e f g
1
1
C = A ^ 0x01; A a b c d e f g h
0x01 0 0 0 0 0 0 0 1
C a b c d e f g h’
Clear selected bit of A
Set selected bit of A
Complement selected bit of A
Clear all but the selected bit of A
20. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Bit examples for input/output
• Create a “pulse” on bit 0 of PORTA (assume bit
is initially 0)
PORTA = PORTA | 0x01; //Force bit 0 to 1
PORTA = PORTA & 0xFE; //Force bit 0 to 0
• Examples:
if ( (PORTA & 0x80) != 0 ) //Or: ((PORTA & 0x80) == 0x80)
bob();
c = PORTB & 0x04;
if ((PORTA & 0x01) == 0)
PORTA = c | 0x01;
// call bob() if bit 7 of PORTA is 1
// mask all but bit 2 of PORTB value
// test bit 0 of PORTA
// write c to PORTA with bit 0 set to 1
21. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Example of µC register address definitions in STM32Lxx.h
(read this header file to view other peripheral functions)
#define PERIPH_BASE ((uint32_t)0x40000000) //Peripheral base address in memory
#define AHBPERIPH_BASE (PERIPH_BASE + 0x20000) //AHB peripherals
/* Base addresses of blocks of GPIO control/data registers */
#define GPIOA_BASE (AHBPERIPH_BASE + 0x0000) //Registers for GPIOA
#define GPIOB_BASE (AHBPERIPH_BASE + 0x0400) //Registers for GPIOB
#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) //Pointer to GPIOA register block
#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) //Pointer to GPIOB register block
/* Address offsets from GPIO base address – block of registers defined as a “structure” */
typedef struct
{
Address offset: 0x00
Address offset: 0x04
0x06
Address offset: 0x08
Address offset: 0x0C
Address offset: 0x10
0x12
Address offset: 0x14
0x16
Address offset: 0x18
Address offset: 0x1A
Address offset: 0x1C
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
/*!< GPIO port mode register,
/*!< GPIO port output type register,
/*!< Reserved,
/*!< GPIO port output speed register,
/*!< GPIO port pull-up/pull-down register,
/*!< GPIO port input data register,
/*!< Reserved,
/*!< GPIO port output data register,
/*!< Reserved,
/*!< GPIO port bit set/reset low registerBSRR,
/*!< GPIO port bit set/reset high registerBSRR,
/*!< GPIO port configuration lock register,
/*!< GPIO alternate function low register, Address offset: 0x20-0x24 */
IO uint32_t MODER;
IO uint16_t OTYPER;
uint16_t RESERVED0;
IO uint32_t OSPEEDR;
IO uint32_t PUPDR;
IO uint16_t IDR;
uint16_t RESERVED1;
IO uint16_t ODR;
uint16_t RESERVED2;
IO uint16_t BSRRL;
IO uint16_t BSRRH;
IO uint32_t LCKR;
IO uint32_t AFR[2];
} GPIO_TypeDef;
22. Example: I/O port bits
(using bottom half of GPIOB)
7 6 5 4 3 2 1
uint16_t sw;
sw = GPIOB->IDR;
sw = GPIOB->IDR & 0x0010;
if (sw == 0x01)
if (sw == 0x10)
if (sw == 0)
if (sw != 0)
GPIOB->ODR = 0x005a;
GPIOB->ODR |= 0x10;
GPIOB->ODR &= ~0x10;
if ((GPIOB->IDR & 0x10) == 1)
0
h g f e d c b a
GPIOB
Switch connected to bit 4 (PB4) of GPIOB
//16-bit unsigned type since GPIOB IDR and ODR = 16 bits
// sw = xxxxxxxxhgfedcba (upper 8 bits from PB15-PB8)
// sw = 000e0000 (mask all but bit 4)
// Result is sw = 00000000 or 00010000
// NEVER TRUE for above sw, which is 000e0000
// TRUE if e=1 (bit 4 in result of PORTB & 0x10)
// TRUE if e=0 in PORTB & 0x10 (sw=00000000)
// TRUE if e=1 in PORTB & 0x10 (sw=00010000)
// Write to 16 bits of GPIOB; result is 01011010
// Sets only bit e to 1 in GPIOB (GPIOB now hgf1dcba)
// Resets only bit e to 0 in GPIOB (GPIOB now hgf0dcba)
// TRUE if e=1 (bit 4 of GPIOB)
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
23. Shift operators
Shift operators:
x >> y (right shift operand x by y bit positions)
x << y (left shift operand x by y bit positions)
Vacated bits are filled with 0’s.
Shift right/left fast way to multiply/divide by power of 2
B = A << 3;
(Left shift 3 bits)
A 1 0 1 0 1 1 0 1
B 0 1 1 0 1 0 0 0
B = A >> 2;
(Right shift 2 bits)
A 1 0 1 1 0 1 0 1
B 0 0 1 0 1 1 0 1
B = ‘1’;
C = ‘5’;
B = 0 0 1 1 0 0 0 1 (ASCII 0x31)
C = 0 0 1 1 0 1 0 1 (ASCII 0x35)
D = (B << 4) | (C & 0x0F);
(B << 4) = 0 0 0 1 0 0 0 0
(C & 0x0F) = 0 0 0 0 0 1 0 1
D = 0 0 0 1 0 1 0 1 (Packed BCD 0x15)
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
24. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
C control structures
• Control order in which instructions are executed
(program flow)
• Conditional execution
– Execute a set of statements if some condition is met
– Select one set of statements to be executed from
several options, depending on one or more conditions
• Iterative execution
– Repeated execution of a set of statements
• A specified number of times, or
• Until some condition is met, or
• While some condition is true
25. IF-THEN structure
if (a < b)
{
statement s1;
statement s2;
….
}
a < b
?
Yes
No
S1;
S2;
…
• Execute a set of statements if and only if some
condition is met
TRUE/FALSE condition
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
26. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Relational Operators
Test TRUE condition Notes
(m == b) m equal to b Double =
(m != b) m not equal to b
(m < b) m less than b 1
(m <= b) m less than or equal to b 1
(m > b) m greater than b 1
(m >= b) m greater than or equal to b 1
(m) m non-zero
(1) always TRUE
(0) always FALSE
• Test relationship between two variables/expressions
1. Compiler uses
signed or unsigned
comparison, in
accordance with
data types
Example:
unsigned char a,b;
int j,k;
if (a < b) – unsigned
if (j > k) - signed
27. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Boolean operators
• Boolean operators && (AND) and || (OR) produce
TRUE/FALSE results when testing multiple TRUE/FALSE
conditions
if ((n > 1) && (n < 5)) //test for n between 1 and 5
if ((c = ‘q’) || (c = ‘Q’)) //test c = lower or upper case Q
• Note the difference between Boolean operators &&, ||
and bitwise logical operators &, |
if ( k && m)
if ( k & m)
//test if k and m both TRUE (non-zero values)
//compute bitwise AND between m and n,
//then test whether the result is non-zero (TRUE)
28. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Common error
• Note that == is a relational operator,
whereas = is an assignment operator.
if ( m == n) //tests equality of values of variables m and n
if (m = n) //assigns value of n to variable m, and then
//tests whether that value is TRUE (non-zero)
The second form is a common error (omitting the second equal sign), and
usually produces unexpected results, namely a TRUE condition if n is 0 and
FALSE if n is non-zero.
29. IF-THEN-ELSE structure
• Execute one set of statements if a condition is met and an
alternate set if the condition is not met.
if (a == 0)
{
statement s1;
statement s2;
}
else
{
statement s3;
statement s4:
}
a == 0
?
Yes No
S3;
S4;
S1;
S2;
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
30. IF-THEN-ELSE HCS12 assembly language vs C example
AD_PORT: EQU $91 ; A/D Data Port
MAX_TEMP: EQU 128 ; Maximum temperature
VALVE_OFF: EQU 0 ; Bits for valve off
VALVE_ON: EQU 1 ; Bits for valve on
EQU $258 ; Port P for the valve
VALVE_PORT:
. . .
; Get the temperature
ldaa AD_PORT
; IF Temperature > Allowed Maximum
cmpa #MAX_TEMP
bls ELSE_PART
; THEN Turn the water valve off
ldaa VALVE_OFF
staa VALVE_PORT
bra END_IF
; ELSE Turn the water valve on
ELSE_PART:
ldaa VALVE_ON
staa VALVE_PORT
END_IF:
; END IF temperature > Allowed Maximum
C version:
#define MAX_TEMP 128
#define VALVE_OFF 0
#define VALVE_ON 1
if (AD_PORT <= MAX_TEMP)
VALVE_PORT = VALVE_OFF;
else
VALVE_PORT = VALVE_ON;
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
31. Ambiguous ELSE association
if (n > 0)
if (a > b)
z = a;
else
z = b;
//else goes with nearest previous “if” (a > b)
if (n > 0) {
if (a > b)
z = a;
} else {
z = b;
}
//else goes with first “if” (n > 0)
Braces force proper association
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
32. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Multiple ELSE-IF structure
• Multi-way decision, with expressions
evaluated in a specified order
if (n == 1)
statement1;
else if (n == 2)
statement2;
else if (n == 3)
statement3;
else
//do if n == 1
//do if n == 2
//do if n == 3
statement4; //do if any other value of n (none of the above)
Any “statement” above can be replaced with a set of
statements: {s1; s2; s3; …}
33. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
SWITCH statement
• Compact alternative to ELSE-IF structure, for multi-
way decision that tests one variable or expression
for a number of constant values
/* example equivalent to that on preceding slide */
switch ( n) { //n is the variable to be tested
case 0: statement1; //do if n == 0
case 1: statement2; // do if n == 1
case 2: statement3; // do if n == 2
default: statement4; //if for any other n value
}
Any “statement” above can be replaced with a set of
statements: {s1; s2; s3; …}
34. WHILE loop structure
• Repeat a set of statements (a “loop”) as long
as some condition is met
while (a < b)
{
statement s1;
statement s2;
….
}
a < b
? Yes
No
S1;
S2;
…
“loop” through these
statements while a < b
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Something must eventually cause a >= b, to exit the loop
35. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
AD_PORT: EQU $91 ; A/D Data port
MAX_ALLOWED:EQU 128 ; Maximum Temp
LIGHT_ON: EQU 1
LIGHT_OFF: EQU 0
LIGHT_PORT: EQU $258 ; Port P
; - - -
; Get the temperature from the A/D
ldaa AD_PORT
; WHILE the temperature > maximum allowed
WHILE_START:
cmpa MAX_ALLOWED
bls END_WHILE
; DO - Flash light 0.5 sec on, 0.5 sec off
ldaa LIGHT_ON
staa LIGHT_PORT ; Turn the light
jsr delay ; 0.5 sec delay
ldaa LIGHT_OFF
staa LIGHT_PORT ; Turn the light off
jsr delay
; End flashing the light, Get temperature from the A/D
ldaa AD_PORT
; END_DO
bra WHILE_START
END_WHILE:
C version:
#define MAX_ALLOWED 128
#define LIGHT_ON 1
#define LIGHT_OFF 0
while (AD_PORT <= MAX_ALLOWED)
{
LIGHT_PORT = LIGHT_ON;
delay();
LIGHT_PORT = LIGHT_OFF;
delay();
}
WHILE loop example:
C vs. HCS12 Assembly
Language
36. DO-WHILE loop structure
do
{
statement s1;
statement s2;
….
}
while (a < b);
a < b
?
Yes
No
S1;
S2;
…
“loop” through
these statements
until a < b
• Repeat a set of statements (one “loop”)
until some condition is met
The condition is tested after executing the set of
statements, so the statements are guaranteed to
execute at least once.
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
37. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
DO-WHILE example
;HCS12 Assembly Language Version
;
;
DO
Flash light 0.5 sec on, 0.5 sec off
ldaa LIGHT_ON
staa LIGHT_PORT ; Turn light on
jsr
ldaa
staa
jsr
delay
LIGHT_OFF
LIGHT_PORT
delay
;
;
0.5 sec delay
Turn light off
; END_DO
; END_WHILE:
; End flashing the light
; Get the temperature from the A/D
ldaa AD_PORT
bra WHILE_START
; END_WHILE temperature > maximum allowed
; Dummy subroutine
delay: rts
C version:
#define MAX_ALLOWED 128
#define LIGHT_ON 1
#define LIGHT_OFF 0
do {
LIGHT_PORT = LIGHT_ON;
delay();
LIGHT_PORT = LIGHT_OFF;
delay();
} while (AD_PORT <= MAX_ALLOWED);
38. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
WHILE examples
/* Add two 200-element arrays. */
int M[200],N[200],P[200];
int k;
/* Method 1 – using DO-WHILE */
//initialize counter/index
k = 0;
do {
M[k] = N[k] + P[k];
k = k + 1;
} while (k < 200);
//add k-th array elements
//increment counter/index
//repeat if k less than 200
/* Method 2 – using WHILE loop
//initialize counter/index
//execute the loop if k less than 200
//add k-th array elements
//increment counter/index
k = 0;
while (k < 200} {
M[k] = N[k] + P[k];
k = k + 1;
}
39. WHILE example
while ( (GPIOA->IDR & 0x0001) == 0) // test bit 0 of GPIOA
{}
c = GPIOB->IDR;
// do nothing & repeat if bit is 0
// read GPIOB after above bit = 1
PORTA
bit0 0
1
No
operation
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Wait for a 1 to be applied
to bit 0 of GPIOA
and then read GPIOB
Read
PORTB
40. FOR loop structure
• Repeat a set of statements (one “loop”) while
some condition is met
– often a given # of iterations
for (m = 0; m < 200; m++)
{
statement s1;
statement s2;
}
Initialization(s)
Condition for
execution
Operation(s) at end
of each loop
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
41. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
FOR loop structure
for (m = 0; m < 200; m++)
{
statement s1;
statement s2;
}
• FOR loop is a more compact form of the
WHILE loop structure
/* execute loop 200 times */ /* equivalent WHILE loop */
m = 0; //initial action(s)
while (m < 200) //condition test
{
statement s1;
statement s2;
m = m + 1; //end of loop action
}
42. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
FOR structure example
/* Read 100 16-bit values from GPIOB into array C */
/* Bit 0 of GPIOA (PA0) is 1 if data is ready, and 0 otherwise */
uint16_t c[100];
uint16_t k;
for (k = 0; k < 200; k++) {
while ((GPIOA->IDR & 0x01) == 0) //repeat until PA0 = 1
{}
c[k] = GPIOB->IDR;
//do nothing if PA0 = 0
//read data from PB[15:0]
}
43. FOR structure example
/* Nested FOR loops to create a time delay */
for (i = 0; i < 100; i++) { //do outer loop 100 times
for (j = 0; j < 1000; j++) { //do inner loop 1000 times
} //do “nothing” in inner loop
}
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
44. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
C functions
• Functions partition large programs into a set
of smaller tasks
– Helps manage program complexity
– Smaller tasks are easier to design and debug
– Functions can often be reused instead of starting
over
– Can use of “libraries” of functions developed by
3rd parties, instead of designing your own
45. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
C functions
• A function is “called” by another program to
perform a task
– The function may return a result to the caller
– One or more arguments may be passed to the
function/procedure
46. Function definition
int math_func (int k; int n)
{
int j;
j = n + k - 5;
return(j);
//local variable
//function body
//return the result
}
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Parameters passed to
Type of value to be
returned to the caller*
Parameters passed
by the caller
* If no return value, specify “void”
47. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Function arguments
• Calling program can pass information to a
function in two ways
– By value: pass a constant or a variable value
• function can use, but not modify the value
– By reference: pass the address of the variable
• function can both read and update the variable
– Values/addresses are typically passed to the
function by pushing them onto the system stack
• Function retrieves the information from the stack
48. Example – pass by value
/* Function to calculate x2 */
//passed value is type int, return an int value
//local variable – scope limited to square
//use the passed value
//return the result
int square ( int x ) {
int y;
y = x * x;
return(x);
}
void main {
int k,n;
n = 5;
k = square(n);
n = square(5);
}
//local variables – scope limited to main
//pass value of n, assign n-squared to k
// pass value 5, assign 5-squared to n
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
49. Example – pass by reference
/* Function to calculate x2 */
void square ( int x, int *y ) { //value of x, address of y
*y = x * x; //write result to location whose address is y
}
//local variables – scope limited to main
//calculate n-squared and put result in k
// calculate 5-squared and put result in n
void main {
int k,n;
n = 5;
square(n, &k);
square(5, &n);
}
In the above, main tells square the location of its local variable,
so that square can write the result to that variable.
Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
50. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Example – receive serial data bytes
/* Put string of received SCI bytes into an array */
Int rcv_data[10];
Int rcv_count;
//global variable array for received data
//global variable for #received bytes
void SCI_receive ( ) {
while ( (SCISR1 & 0x20) == 0) {}
rcv_data[rcv_count] = SCIDRL;
rcv_count++;
}
//wait for new data (RDRF = 1)
//byte to array from SCI data reg.
//update index for next byte
Other functions can access the received data from the global variable
array rcv_data[].
51. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Some on-line C tutorials
• http://www.cprogramming.com/tutorial/c-
tutorial.html
• http://www.physics.drexel.edu/courses/Comp
_Phys/General/C_basics/
• http://www.iu.hio.no/~mark/CTutorial/CTutor
ial.html
• http://www2.its.strath.ac.uk/courses/c/
52. Fall 2014 - ARM Version ELEC 3040/3050 Embedded Systems Lab (V. P. Nelson)
Tutorial to be continued …..