[go: up one dir, main page]

0% found this document useful (0 votes)
11 views16 pages

W1.2 Embedded C

The document provides an overview of programming in Embedded C, including its structure, conventions, and key components such as pre-processor directives, data types, and coding standards. It emphasizes the importance of comments, variable initialization, and the use of pointers and structs in embedded systems programming. Additionally, it offers tips for efficient coding and low power applications.

Uploaded by

Andrew Koh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views16 pages

W1.2 Embedded C

The document provides an overview of programming in Embedded C, including its structure, conventions, and key components such as pre-processor directives, data types, and coding standards. It emphasizes the importance of comments, variable initialization, and the use of pointers and structs in embedded systems programming. Additionally, it offers tips for efficient coding and low power applications.

Uploaded by

Andrew Koh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Programming in the World of

Embedded Systems
Embedded C language

• C language is a software designed with different keywords, data types, variables,


constants, etc.
• Embedded C is a generic term given to a programming language written in C, which is
associated with a particular hardware architecture.
• Embedded C is an extension to the C language with some additional header files. These
header files may change from controller to controller.

https://www.elprocus.com/basics-and-structure-of-embedded-c-program-with-examples-for-beginners/
Frequently used programming conventions

1. Variables use nouns start with small letters:


radius, averageVelocity, speed;

2. Functions use verbs and start with a small letter:


calculateSpeed( ), toggle_Led( ), change_speed( );

3. Constants use capital letters: LED1, GREEN, BUTTON;

4. Initialize variables when declaring them: int radius=0;

5. Use iterative variables (e.g., for loops) as: i, j, k;

6. Use local variables whenever possible (memory is freed up after use);


7. Avoid meaningless, abbreviated and ambiguous names
variable1, functionA(), abc1, f(), …

8. Avoid global variables whenever possible


Comments and Operators

Comments: Operators:
▪ Source code must have additional information ▪ Separated by blank spaces in order to
provided in the form of comments so it can be significantly improve their readability;
clearly interpreted. ▪ A blank space should be used after
▪ Comments are a very important part of commas, semi-colons, or colons.
documentation to ensure it is easy to maintain. ▪ Examples:
▪ Comment for one line: Double diagonal ( // );
BAD: a=(4+c)*2;
▪ Comments for a larger block of code:
Starts with ( /* ) and ends with ( */ ); GOOD: a = (4 + c) * 2;
▪ Example:
BAD: for(i=7;i>=0;i--){}
/*The source code should be written
in such a way that enough GOOD: for(i = 0; i >= 0; i--
information is provided for the ){}
reader to fully understand the
function of the code*/
Pre-processor directives

• The C pre-processor is a program that transform specific parts of the code before
the actual compilation.
• It is also called a Macro Processor as it allows to define short abbreviations for
frequently used code blocks (i.e., macros).
• It uses special directives which begin with the sharp character (#).
• Important directives are
• #include (e.g., #include <stdio.h>)
lets the pre-processor know that you wish to include a file as part of the source code.
• #define (e.g., #define BIT3 0x04)
substitutes the symbolic name by the corresponding expression every time it is found in the
code.
note that no = or ; are used in contrast to regular value assignment: int bit3 = 0x04;
• #pragma
instructs the compiler to use implementation dependent features.
(e.g., where to place interrupt vectors, as we will see learn later)
General C Program Structure

• Three main components #include <msp430.h>


#define FAKTOR 2; //Preprocessor directive
• Pre-processor directives (optional)
int A, int B; //Global variable
• Global variables (optional)
• Functions (main() is mandatory) int addAndWeight(void)
• Declaration of variables {
int s; //Local variable
• Global variables: declared at the beginning
s = (A + B) * FAKTOR;
of a program and accessible throughout the
entire code; return s;
}
• Local variables: declared within one function
and are only accessible during the execution
of this function; int main(void)
{
• Declaration of functions int result; //Local variable
• Additional functions should be declared A = 5;
before the main() function. B = 7;
• Functions defined above main() do not need result = addAndWeight();
to be declared (as in the example on the printf("%d\n", result);
right). return 0;
}
Value Qualifiers

const int const s = SIZE; //constant that should not be changed


• Declares that the variable cannot be
void main(void)
modified. {
• Variable will be stored in program s++; // compiler complains here!
...
section memory rather than stack. }

int volatile data_rcvd = FALSE; //receive flag


volatile void main(void){
while(!data_rcvd) // compiler thinks while loop
{ // is always true and could
• Declares that an outside event (e.g. ... // remove code after the loop!
ADC) can change the content of a }
}
variable. interrupt void rx_isr(void){
• A statement using this descriptor if (ETX == rx_char)
{
informs the compiler that this data_rcvd = TRUE; // but variable changed here!
variable should not be optimized. }
}
Storage Qualifiers
extern // this is a header file global.h
extern int exec_num;
• Tells the compiler that a global variable is
#include <global.h> // this is file myFile1.c
declared elsewhere (e.g., another void main(void){
compilation unit or source file). exec_num++;
...
• Compiler does not create another instance of
such an extern variable to avoid name #include <global.h> // this is file myFile2.c
collision at linking time. void main(void){
printf(“myFile1 started “%d” times.”, exec_num);
...

int times_called(void);
void main(void){
static int i;
for (i = 0; i < 10; i++){
• A local variable is known “globally” to its result = increment();
}
function }
• Preserves the variable value after one int increment(void)
{
execution of a function or code block. static int i = 0; //only declared once!
i++;
return i;
}
Data types

Size Range values


Type Representation
[bits] Minimum Maximum
signed char 8 ASCII -128 127

char, unsigned char 8 ASCII 0 255

short, signed short 16 2’s complement -32768 32767

unsigned short 16 Binary 0 65535

int, signed int 16 2’s complement -32768 32767

unsigned int 16 Binary 0 65535

long, signed long 32 2’s complement -2147483648 2147483647

unsigned long 32 Binary 0 4294967295

float 32 IEEE 32-bit 1.175495e-38 3.40282346e+38

double 32 IEEE 32-bit 1.175495e-38 3.40282346e+38

long double 32 IEEE 32-bit 1.175495e-38 3.40282346e+38


What is ‘C’ Coding Standard and why should I bother

A ‘C’ coding standard is a set of rules for source code that is adopted by a team of
programmers working together on a project, such as the design of an embedded
system. Programming teams and companies write down their C coding standards for a
variety of reasons but often bicker internally about which rules to follow.

NOTE: MUST be incorporated into all codes submitted in this module


https://barrgroup.com/Embedded-Systems/Books/Embedded-C-Coding-Standard
Mathematic operators
Arithmetic Operators Relational, Logical and Bitwise Operators
Operator Name Syntax Operator Name Syntax
Unary Minus (Negation) -a Less Than a < b
Addition (Sum) a + b Less Than or Equal To a <= b
Subtraction (Difference) a - b Greater Than a > b
Multiplication a * b Greater Than or Equal To a >= b
Division (Dividend) a / b Not Equal To a != b
Modulus (Remainder) a % b Equal To a == b
Postfix Increment a++ Logical Negation !a

Often used in embedded


Postfix Decrement a-- Logical AND a && b
Prefix Decrement --a Logical OR a || b
Good to know

programming
Prefix Increment ++a Bitwise NOT ~a
Assignment by Addition a += b Bitwise AND a & b
Assignment by Subtraction a -= b Bitwise OR a | b
Assignment by Division a /= b Bitwise XOR a ^ b
Assignment by Multiplication a *= b Bitwise left shift a << b
Assignment by Modulus a %= b Bitwise right shift a >> b
Operator priority
Operator priority (from high to low)
Operator Description
() [] -> . Grouping, scope, member access a ? b : c
Size of type cast (most) unary translates to:
! ~ + - & if (a == TRUE){
operations, …
* / % Multiplication, division, modulo b;
Priority increases
+ - Addition, subtraction }
<< >> Bitwise shift left and right else {
< <= > >= Comparisons: less-than, ... c;
}
== != Comparisons: equal and not equal
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive (normal) OR
&& Logical AND
|| Logical OR
?: Ternary Conditional expression
= += -= *= /= %= &=
Assignment operators
|= ^= <<= >>=
, Concatenation
Bitwise shifts
Left-shift Right-shift
▪ Zeros are shifted in from the right ▪ The sign bit is shifted in on the left, thus
▪ The number of places to shift is given as preserving the sign of the operand
the second argument to the shift ▪ The number of places to shift is given as
operators the second argument to the shift
▪ Example: operators;
x = y << 2; ▪ Example:
Assigns x the result of shifting y to the left by two x = y >> 1;
bits (i.e., acts as a multiplication by 4) Assigns x the result of shifting y to the right by
one bit (i.e., acts as a division by 2)
Pointers

▪ When a variable is declared, the Address Value Variable Variable


compiler reserves a location to store of memory in memory name type
200 ‘a’ letter char
the variable in the memory (RAM).
201 66 speed int
▪ Pointers are special variables 202 2454 int
distance
holding the address of a variable 203 ‘b’ char
letter2
and not its content!
204 1.23 radius float
▪ The ampersand or address-of
char *chptr; // declare a char pointer
operator (&) is used to access the char letter = ‘a’; // initialize a char variable
address of a variable. chptr = &letter; // initialize the char pointer

▪ The asterisk or address-at operator printf(“Val: %c”, letter); // output = ‘Val: a’

(*) is used to declare a pointer. printf(“Add: %d”, &letter); // output = ‘Add: 200’
printf(“Add: %d”, chptr); // output = ‘Add: 200’

printf(“Val: %c”, *chptr); // output = ‘Val: a’


printf(“Val: %c”, *(&letter)); // output = ‘Val: a’
Structs
▪ Sometimes it might make sense to struct date
{
group corresponding data char month[9];
int day;
▪ Structs are special data type char *weekday;
declarations that define a grouped };
list of different variables. struct date birthday; // initialization
▪ The variables are placed as one block strcpy(birthday.month, “December”); // string copy
in memory such that they can be birthday.day = 15;
birthday.weekday = “Wednesday”;
accessed via a single pointer.
printf(“Month: %s”, birthday.month); // output = ‘Month: December’
printf(“Day: %d”, birthday.day); // output = ‘Day: 15’
printf(“Weekday: %s”, birthday.weekday); // output = ‘Weekday: Wednesday’

struct date *ptr = &birthday;

printf(“Day: %d”, ptr->day); // output = ‘Day: 15’


printf(“Add: %d”, &(ptr->day)); // output = ‘Add: [address of day]’
printf(“Add: %d”, &(ptr->weekday)); // output = ‘Add: [address of day + 2]’
Some final tips

• General tips • Principles for low power applications


• Use local variable as much as possible • Maximize the time in standby
(local variables use CPU registers • Use interrupts to control program flow
whereas global variables use RAM)
• Replace software functions with
• Use unsigned data types where possible peripheral hardware (e.g., timers,
• Use pointers to access structures and comparators, hardware multiplier)
unions • Manage the power of internal
• Use static const qualifier to avoid run- peripherals
time copying of structures, unions, and • Manage the power of external devices
arrays
• Code effecively: every unnecessary
• Count down for loops, since comparisons instruction executed is a portion of the
with 0 are faster battery wasted that will never return

https://www.tutorialspoint.com/cprogramming/index.htm

You might also like