|
| 1 | +# 1. Core C Basics for Embedded Systems |
| 2 | + |
| 3 | +``` |
| 4 | +Your Foundation for Embedded Programming |
| 5 | +``` |
| 6 | +**Topics Covered:** |
| 7 | + |
| 8 | +- Variables & Data Types |
| 9 | +- Operators & Control Flow |
| 10 | +- Functions |
| 11 | +- Arrays & Strings |
| 12 | +- Basic Input/Output |
| 13 | +- Practice Problems |
| 14 | + |
| 15 | +## 1.1 Variables & Data Types |
| 16 | + |
| 17 | +**What is a Variable?** |
| 18 | + |
| 19 | +A variable is a named location in memory that stores data. Think of it as a labeled box |
| 20 | +where you can put values and retrieve them later. |
| 21 | + |
| 22 | +**Note:** In embedded systems, understanding how much memory each data type uses is |
| 23 | +CRITICAL because microcontrollers have limited RAM. |
| 24 | + |
| 25 | +**Common Data Types in C** |
| 26 | + |
| 27 | +| Data Type | Size (Typical) | Range | Use Case | |
| 28 | +|-----------------|---------------|------------------------------------|-----------------------------------| |
| 29 | +| char | 1 byte | -128 to 127 | Single characters, small integers | |
| 30 | +| unsigned char | 1 byte | 0 to 255 | Sensor readings, register values | |
| 31 | +| int (16-bit) | 2 bytes | -32,768 to 32,767 | Counters, calculations | |
| 32 | +| unsigned int | 2 bytes | 0 to 65,535 (16-bit) | Always positive values | |
| 33 | +| long | 4 bytes | -2,147,483,648 to 2,147,483,647 | Large numbers, timestamps | |
| 34 | +| float | 4 bytes | ±3.4e±38 (~6–7 digits precision) | Decimal numbers (avoid in embedded!) | |
| 35 | + |
| 36 | +**Example Code:** |
| 37 | +```c |
| 38 | +// Declaring variables |
| 39 | +int sensorValue = 0; // 16 or 32-bit integer |
| 40 | +unsigned char ledState = 1; // 8-bit (0-255) |
| 41 | +float temperature = 25.5; // Floating point |
| 42 | +char deviceStatus = 'A'; // Single character |
| 43 | + |
| 44 | +// Why size matters in embedded: |
| 45 | +unsigned char counter = 0; // Uses only 1 byte of RAM |
| 46 | +int bigCounter = 0; // Uses 2 or 4 bytes of RAM |
| 47 | +``` |
| 48 | + |
| 49 | +<br> |
| 50 | + |
| 51 | +## 1.2. Operators & Control Flow |
| 52 | + |
| 53 | +**Arithmetic Operators** |
| 54 | + |
| 55 | +Used for mathematical calculations: + (add), - (subtract), * (multiply), / (divide), % |
| 56 | +(modulus/remainder) |
| 57 | +```c |
| 58 | +int a = 10, b = 3; |
| 59 | +int sum = a + b; // 13 |
| 60 | +int diff = a - b; // 7 |
| 61 | +int product = a * b; // 30 |
| 62 | +int quotient = a / b; // 3 (integer division!) |
| 63 | +int remainder = a % b; // 1 |
| 64 | +``` |
| 65 | + |
| 66 | +**Comparison Operators** |
| 67 | + |
| 68 | +Compare values and return true (1) or false (0): |
| 69 | +```c |
| 70 | +== (equal), |
| 71 | +!= (not equal), |
| 72 | +> (greater), |
| 73 | +< (less), |
| 74 | +>=, <= |
| 75 | +``` |
| 76 | + |
| 77 | +**Logical Operators** |
| 78 | + |
| 79 | +Combine multiple conditions: && (AND), || (OR),! (NOT) |
| 80 | + |
| 81 | +```c |
| 82 | +int temperature = 75; |
| 83 | +int humidity = 60; |
| 84 | + |
| 85 | +// AND operator - both conditions must be true |
| 86 | +if (temperature > 70 && humidity > 50) { |
| 87 | + printf("Hot and humid!\n"); |
| 88 | +} |
| 89 | +``` |
| 90 | + |
| 91 | +**Control Flow: if/else** |
| 92 | + |
| 93 | +Makes decisions in your program based on conditions. |
| 94 | + |
| 95 | +```c |
| 96 | +int temperature = 75; |
| 97 | +if (temperature > 80) { |
| 98 | + // Turn on cooling fan |
| 99 | + fanState = 1; |
| 100 | +} else if (temperature < 60) { |
| 101 | + // Turn on heater |
| 102 | + heaterState = 1; |
| 103 | +} else { |
| 104 | + // Temperature is fine |
| 105 | + fanState = 0; |
| 106 | + heaterState = 0; |
| 107 | +} |
| 108 | +``` |
| 109 | + |
| 110 | +**Loops: for and while** |
| 111 | + |
| 112 | +Repeat code multiple times. Essential for embedded systems! |
| 113 | +```c |
| 114 | +// for loop - when you know how many times to repeat |
| 115 | +for (int i = 0; i < 10; i++) { |
| 116 | + printf("%d ", i); // Prints: 0 1 2 3 4 5 6 7 8 9 |
| 117 | +} |
| 118 | + |
| 119 | +// while loop - repeat while condition is true |
| 120 | +int count = 0; |
| 121 | +while (count < 5) { |
| 122 | + printf("Count: %d\n", count); |
| 123 | + count++; |
| 124 | +} |
| 125 | +``` |
| 126 | + |
| 127 | +> **Embedded Tip:** In embedded systems, you'll often use infinite loops: while(1) { } to |
| 128 | +keep the microcontroller running continuously! |
| 129 | + |
| 130 | +## 1.3. Functions |
| 131 | + |
| 132 | +**What are Functions?** |
| 133 | + |
| 134 | +Functions are reusable blocks of code that perform a specific task. They help you |
| 135 | +organize code and avoid repetition. |
| 136 | + |
| 137 | +**Function Structure** |
| 138 | + |
| 139 | +```c |
| 140 | +return_type function_name(parameters) { |
| 141 | + // code to execute |
| 142 | + return value; // optional |
| 143 | +} |
| 144 | +``` |
| 145 | +
|
| 146 | +**Example: Simple Functions** |
| 147 | +
|
| 148 | +```c |
| 149 | +// Function that returns sum of two numbers |
| 150 | +int add(int a, int b) { |
| 151 | + return a + b; |
| 152 | +} |
| 153 | +
|
| 154 | +// Function that doesn't return anything (void) |
| 155 | +void blinkLED(int times) { |
| 156 | + for (int i = 0; i < times; i++) { |
| 157 | + // Turn LED on |
| 158 | + // Delay |
| 159 | + // Turn LED off |
| 160 | + // Delay |
| 161 | + } |
| 162 | +} |
| 163 | +
|
| 164 | +// Using the functions |
| 165 | +int main() { |
| 166 | + int result = add(5, 3); // result = 8 |
| 167 | + blinkLED(5); // Blink LED 5 times |
| 168 | + return 0; |
| 169 | +} |
| 170 | +``` |
| 171 | + |
| 172 | +> **Why Functions Matter in Embedded:** Real embedded projects have functions like |
| 173 | +readSensor(), updateDisplay(), checkButton() - breaking complex tasks into simple, |
| 174 | +manageable pieces. |
| 175 | + |
| 176 | +## 1.4. Arrays & Strings |
| 177 | + |
| 178 | +**What is an Array?** |
| 179 | + |
| 180 | +An array is a collection of elements of the same type stored in consecutive memory |
| 181 | +locations. Think of it as a row of boxes, each holding a value. |
| 182 | + |
| 183 | +**Declaring and Using Arrays** |
| 184 | + |
| 185 | +```c |
| 186 | +// Declare an array of 5 integers |
| 187 | +int sensorReadings[5]; |
| 188 | + |
| 189 | +// Initialize array with values |
| 190 | +int ledPins[4] = {2, 3, 4, 5}; |
| 191 | + |
| 192 | +// Access array elements (index starts at 0!) |
| 193 | +sensorReadings[0] = 100; // First element |
| 194 | +sensorReadings[1] = 105; // Second element |
| 195 | +sensorReadings[4] = 120; // Fifth element |
| 196 | + |
| 197 | +// Loop through array |
| 198 | +for (int i = 0; i < 5; i++) { |
| 199 | + printf("%d ", sensorReadings[i]); |
| 200 | +} |
| 201 | +``` |
| 202 | + |
| 203 | +**Strings in C** |
| 204 | + |
| 205 | +In C, strings are arrays of characters ending with a null terminator ('\0'). This is different |
| 206 | +from other languages! |
| 207 | + |
| 208 | +```c |
| 209 | +// Declaring strings |
| 210 | +char deviceName[] = "Arduino"; // Automatically adds \ |
| 211 | +char message[20] = "Hello World"; // Reserve 20 chars |
| 212 | + |
| 213 | +// Character array vs string |
| 214 | +char name[6] = {'C', 'l', 'a', 'u', 'd', '\0'}; // Must add \ |
| 215 | + |
| 216 | +// Common string operations (need string.h) |
| 217 | +#include <string.h> |
| 218 | +char str1[50] = "Hello"; |
| 219 | +char str2[50] = "World"; |
| 220 | +strcat(str1, str2); // Concatenate: str1 becomes "HelloWorld" |
| 221 | +int len = strlen(str1); // Get length: 10 |
| 222 | +strcpy(str1, "New"); // Copy: str1 becomes "New" |
| 223 | +``` |
| 224 | +
|
| 225 | +> **Important:** In embedded systems, you'll often use character arrays to store sensor |
| 226 | +data, messages for displays, or communication buffers. |
| 227 | +
|
| 228 | +## 1.5. Basic Input/Output |
| 229 | +
|
| 230 | +**Console Output: printf()** |
| 231 | +
|
| 232 | +`printf()` is used to print formatted output to the console. Essential for debugging |
| 233 | +embedded systems! |
| 234 | +
|
| 235 | +```c |
| 236 | +#include <stdio.h> |
| 237 | +
|
| 238 | +int temperature = 25; |
| 239 | +float voltage = 3.3; |
| 240 | +char status = 'A'; |
| 241 | +
|
| 242 | +// Format specifiers: |
| 243 | +printf("Temperature: %d°C\n", temperature); // %d for integers |
| 244 | +printf("Voltage: %.2f V\n", voltage); // %f for floats (.2 = 2 decimals) |
| 245 | +printf("Status: %c\n", status); // %c for characters |
| 246 | +printf("Hex value: 0x%X\n", 255); // %X for hexadecimal |
| 247 | +
|
| 248 | +// Multiple values: |
| 249 | +printf("Temp: %d, Voltage: %.1f\n", temperature, voltage); |
| 250 | +``` |
| 251 | + |
| 252 | +**Console Input: scanf()** |
| 253 | + |
| 254 | +`scanf()` reads formatted input from the console. |
| 255 | + |
| 256 | +```c |
| 257 | +int age; |
| 258 | +char name[50]; |
| 259 | + |
| 260 | +printf("Enter your age: "); |
| 261 | +scanf("%d", &age); // Note the & symbol! |
| 262 | + |
| 263 | +printf("Enter your name: "); |
| 264 | +scanf("%s", name); // No & for arrays |
| 265 | + |
| 266 | +printf("Hello %s, you are %d years old!\n", name, age); |
| 267 | +``` |
| 268 | +
|
| 269 | +**Common Format Specifiers** |
| 270 | +
|
| 271 | +| Specifier | Data Type | Example | |
| 272 | +|---------------|----------------|------------------------------| |
| 273 | +| %d or %i | int | printf("%d", 42); | |
| 274 | +| %u | unsigned int | printf("%u", 255); | |
| 275 | +| %f | float/double | printf("%.2f", 3.14); | |
| 276 | +| %c | char | printf("%c", 'A'); | |
| 277 | +| %s | string | printf("%s", "Hello"); | |
| 278 | +| %x or %X | hexadecimal | printf("0x%X", 255); | |
| 279 | +| %p | pointer | printf("%p", &var); | |
| 280 | +
|
| 281 | +
|
| 282 | +## 1.6. Practice Problems |
| 283 | +
|
| 284 | +Here are some hands-on exercises to solidify your understanding. Try to solve these |
| 285 | +without looking at solutions first! |
| 286 | +
|
| 287 | +**Problem 1: Temperature Converter** |
| 288 | +
|
| 289 | +Write a program that converts temperature from Celsius to Fahrenheit using the |
| 290 | +formula: F = (C × 9/5) + 32 |
| 291 | +
|
| 292 | +// Your code here: |
| 293 | +// 1. Declare a float variable for celsius |
| 294 | +// 2. Use scanf to get input |
| 295 | +// 3. Calculate fahrenheit |
| 296 | +// 4. Print the result |
| 297 | +
|
| 298 | +
|
| 299 | +**Problem 2: Even or Odd Checker** |
| 300 | +
|
| 301 | +Write a program that takes a number and prints whether it's even or odd. (Hint: Use the |
| 302 | +modulus operator %) |
| 303 | +
|
| 304 | +**Problem 3: Sum Calculator with Loop** |
| 305 | +
|
| 306 | +Write a program that takes a number N and calculates the sum of all numbers from 1 to |
| 307 | +N using a for loop. |
| 308 | +Example: If N = 5, sum = 1+2+3+4+5 = 15 |
| 309 | +
|
| 310 | +**Problem 4: Array Average** |
| 311 | +
|
| 312 | +Create an array of 5 sensor readings. Write a function that calculates and returns the |
| 313 | +average value. |
| 314 | +
|
| 315 | +**Problem 5: LED Blink Function** |
| 316 | +
|
| 317 | +Write a function void blinkPattern(int count, int delayMs) that simulates blinking an LED. |
| 318 | +Use printf to show LED ON/OFF states. |
| 319 | +
|
| 320 | +**Problem 5: Write a program that** |
| 321 | +- Takes 5 temperature readings into an array |
| 322 | +- Calculates the average temperature |
| 323 | +- If average > 75°F, print "COOLING NEEDED" |
| 324 | +- If average < 65°F, print "HEATING NEEDED" |
| 325 | +- Otherwise, print "TEMPERATURE OK" |
0 commit comments