embedded:c
C
VARIABLES
- char - 1 byte - is used to store a single character (ASCII) value
char Temp; // Variable definition or declaration (letting compiler know we will need it in the future) Temp = 25; // Variable initialisation (assigning a value) extern int my_var // Declaration. It tells the compiler that my_var is defined outside this file
Address of the variable
char a1 = 'A'; &a1 // Gives you an address - memory location of the variable temp. Type is char* printf("%p\n", &a1) // %p - is the special format specifier for pointers
Storage Class of the variable defines:
- Scope of the variable
- Visibility of the variable
- Life time of the variable
static - creates global variable but private to the specific function.
void myFunc(void) { static int count = 0; count = count + 1; printf("Function was called %d times\n", count); }
Another use case for static - prevent access to the global variables from another files:
static int internal_global_var; // Won't be accessible outside this file, even with extern
extern - is used to access the global variable, which is defined outside the scope of a file
ASCII
char a1 = 'A'; // Compiler replaces 'A' with 65 and stores it in a1 char a2 = 65; // basically the same as initialising it with 'A' printf("%c\n", a1); // prints 'A' printf("%c\n", a2); // prints also 'A'
PRINTF FORMATTERS
- %u - unsigned
- %lf - double
- %f - float
- %le, %e - real number in the scientific representation
- %#x - hexadecimal with a leading 0x
- %s - string
ASCII
char a1 = 'A'; // Compiler will replace 'A' with 65
If an arithmetic operator has one floating-point operand and one integer operand, however, the integer will be converted to floating point before the operation is done.
PRECEDENCE
- !=
- =
LOGICAL OPERATORS
- && - AND
- || - OR
- ! - NOT
True is anything but 0, e.g.
uint8_t a = 4; uint8_t b = 8; uint8_t c = 0; c = a && b; // c == 1
BITWISE OPERATORS
- & - bitwise AND (usually used to test or clear bits)
- | - bitwise OR (usually used to set bits)
- ~ - bitwise NOT (unary operator, usually used to clear bits)
- ^ - XOR (usually used to toggle bits)
a = ~c; // bitwise unary NOT
BITWISE SHIFT
- » - a value will be divided by 2 for each right shift
- « - a value will be multiplied by 2 for each left shift
Example clearing the 4th bit with a bitwise shift operator and negation:
data = data &~(1<<4);
Example bit extraction for bits [14:9]. The algorithm:
- Shift the portion to the right, until it touches the LSB
- Mask the value to extract only 6 bits [5:0]
data = data >> 9; data &=63;
LOOPING
WHILE
while(expression) // repeat execution of code inside the loop body until expression evaluates to 0 { statemen1; }
embedded/c.txt · Last modified: by v1ctor
