In this tutorial I’ll cover the core C language used to program Arduinos. We’ll look at ports, the serial monitor, looping, data types, conditionals, setup, loop, static, functions, arrays, strings, numerous math functions, bit manipulation, random, structs, styling text, pointers and much more.
I make multiple little projects here, but the projects will get more advanced as I make more videos. All of the heavily commented code follows below.
If you value videos like this, consider donating $1, or simply turn off Ad Blocking software. I don’t use video, or ads with sounds.
Code from the Video
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 |
PART 1 // This is a global variable meaning it can be accessed by any // code in the whole program (Use as few as possible) // Define an integer that will always have the value of 13 // This is a constant // Integer Values : -32,768 to 32,767 const int ledPin = 13; void setup() { // Opens a serial port and sets how many bits per second // 9600 is 960 characters per second Serial.begin(9600); // Set to use pin 13 for output pinMode(ledPin, OUTPUT); /* 3. // A for loop performs an action multiple times // Each time through the loop we decrement i as long as it is > 0 // You can use > < >= <= for(int i = 3; i > 0; i--){ Serial.print(i); Serial.print(", "); } Serial.println("GO...\n"); */ // 4. Call the function and pass a parameter countDown(5); // 3. You can loop in the same way with while // This is a local variable that can only be accessed in the setup // function int j = 3; while(j > 0){ Serial.print(j); Serial.print(", "); j--; } Serial.println("GO...\n"); // 5. Add floating point numbers Serial.print("3.11111111 + 4.11111111 = "); // You can define how many decimals to print, but precision is // lost after 6 digits Serial.println(addFloats(3.11111111, 4.11111111), 8); // Add doubles (Double & Floats are the same) Serial.print("3.11111111 + 4.11111111 = "); Serial.println(addDoubles(3.11111111, 4.11111111), 8); // Booleans have a value of true or false bool canVote = true; // The ternary operator returns the 1st value if the condition // is true and other wise the 2nd Serial.print("Can I Vote? "); Serial.println(((canVote == true) ? "Yes" : "No")); // chars can hold any of 256 single characters // They must be surrounded by ' and you can't add numbers char letD = 'D'; Serial.println(letD); // Other data types // byte : 0 - 255 // unsigned int : 0 - 65535 // long : -2,147,483,648 - 2,147,483,647 // unsigned long : 0 - 4,294,967,295 // End of 5 } void loop() { // These are local variables // The amount of time to delay between actions // 2. Each time loop executes delayPeriods value would be reset to // 100 unless it is marked as static // static means to only initialize this variable 1 time static int delayPeriod = 100; // Used to increase/decrease the delayPeriod static int countDir = 1; // Turn pin 13 on digitalWrite(ledPin, HIGH); // Wait 1/10th a second delay(delayPeriod); // Turn pin 13 off digitalWrite(ledPin, LOW); // Wait 1/10th a second delay(delayPeriod); // 2. Change direction with a function countDir = checkDirChange(delayPeriod, countDir); /* // Switches the direction of the increment when limits are hit // || means we should execute code if the 1st condition OR the other is true // && is true only if both conditions are true if((delayPeriod == 1000) || (delayPeriod == 0)) { direction *= -1; // You can use > < >= <= ==, or != if(direction < 0){ Serial.println("Going Down"); } else { Serial.println("Going Up"); } } */ // Increase / descrease the delay period depending of current direction delayPeriod += 100 * countDir; // Print to the serial monitor Serial.print("New Wait Time : "); Serial.println(delayPeriod); } // 2. This function receives 2 int parameters and returns 1 int int checkDirChange(int delayPeriod, int countDir){ if((delayPeriod == 1000) || (delayPeriod == 0)) { countDir *= -1; if(countDir < 0){ Serial.println("Going Down"); } else { Serial.println("Going Up"); } } return countDir; } // 4. Receive a parameter and adjust the for loop // void means this function returns no value void countDown(int max){ for(int i = max; i > 0; i--){ Serial.print(i); Serial.print(", "); } Serial.println("GO...\n"); } // 5. Adds and returns floats float addFloats(float num1, float num2){ return num1 + num2; } // 5. Add and return a double double addDoubles(double num1, double num2){ return num1 + num2; } // ————— END PART 1 ————— // ————— PART 2 ————— const int ledPin = 13; // 6. Arrays & Strings // Arrays can contain many values which are accessed using // their index starting at 0 // We'll create an array of numbers that will set how many times // the LED blinks int numOfBlinks[] = {1,2,3,4}; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); } void loop() { int delayPeriod = 1000; // Change a value in the array numOfBlinks[0] = 5; // You can define an array size int array2[10]; // You can store a string of characters or a String // A string ends with a \0 Null char array3[] = "Derek"; // Strings are normally assigned this way and this is // actually a pointer that points to the first chars address // in the char array char *str = "Bananas"; // You can print the string Serial.println(str); // There is also a String object with many functions String myName = "Derek Bananas"; // You can combine strings Serial.println("Name : " + myName); // Get length Serial.println(myName.length()); // Check equality (also equalsIgnoreCase()) Serial.println(myName.equals("Derek")); // Get a character at an index Serial.println(myName.charAt(6)); // Get index of match Serial.println(myName.indexOf('B')); // Remove starting at index and the number of items to remove myName.remove(0, 6); Serial.println(myName); // Replace 1 substring with another myName.replace("nas", "s"); Serial.println(myName); // Get a substring Serial.println(myName.substring(0,3)); // Change to upper and lowercase myName.toUpperCase(); Serial.println(myName); myName.toLowerCase(); Serial.println(myName); // Convert String to int or float with toFloat() String one = "1"; int num1 = one.toInt(); int sum = num1 + num1; Serial.println(sum); // Cycle through array for(int i = 0; i < 5; i++){ Serial.print(array3[i]); } // Cycle through each number of blinks in the array for(int i = 0; i < 4; i++){ blinkLED(numOfBlinks[i]); delay(delayPeriod); } } // Blink lights with a delay a set number of times void blinkLED(int numOfBlinks){ for(int j = 0; j < numOfBlinks; j++){ digitalWrite(ledPin, HIGH); delay(400); digitalWrite(ledPin, LOW); delay(400); } } // ————— END PART 2 ————— // ————— PART 3 ————— void setup() { Serial.begin(9600); // Switch performs different actions based on a limited // number of possible values char grade = 'Z'; switch(grade){ case 'A': Serial.println("Great"); break; case 'B': Serial.println("Good"); break; case 'C': Serial.println("Average"); break; case 'D': Serial.println("Bad"); break; case 'F': Serial.println("Terrible"); break; default: Serial.println("Confused"); break; } // Print all odds until i == 14 then quit int i = 0; while(i < 20){ // If odd print (Modulus returns 0 with evens) if(i % 2){ Serial.println(i); i++; // Skips rest of the while loop continue; } if(i == 14){ // Jump out of while loop break; } i++; } Serial.println(5 + 2); Serial.println(5 - 2); Serial.println(5 * 2); Serial.println(5 / 2); Serial.println(5 % 2); // Absolute value Serial.println(fabs(-2)); // Min & Max Serial.println(fmin(2.5,3)); Serial.println(fmax(2.5,3)); // Rounding Serial.println(round(2.5)); Serial.println(floor(2.5)); Serial.println(ceil(2.5)); // Square Root Serial.println(sqrt(25)); // Square Serial.println(square(3)); // Power Serial.println(pow(5, 2)); // Cube Root Serial.println(cbrt(8)); // Logarithm Serial.println(log(2.718)); Serial.println(log10(1000)); // Constrain a value between a range // If (x, a, b) // Return x if x is between a & b // Return a if x < than a // Return b if x > than b Serial.println(constrain(5, 1, 6)); // Trig Functions Serial.println(sin(1.57)); Serial.println(cos(1.57)); Serial.println(tan(3.14)); Serial.println(sinh(1.57)); Serial.println(cosh(1.57)); Serial.println(tanh(1.57)); Serial.println(asin(1.57)); Serial.println(acos(1.57)); Serial.println(atan(1.57)); // Generate 10 random numbers between 1 to 9 // Initialize the random number generator with // a random seed value using an unconnected pin // which has a floating value randomSeed(analogRead(0)); for(int i = 0; i < 10; i++){ Serial.println(random(1,10)); } // Bit Manipulation // Their are 8 bits in a byte // A bit (Binary Digit) has a value of 0 or 1 // 1111 = 1*2^3 + 1*2^2 + 1*2^1 + 1*2^0 // 15 = 8 + 4 + 2 + 1 // Return 1 if both are 1 with & int bin1 = 0b10101010; // 170 int bin2 = 0b11111111; // 255 Serial.println(bin1 & bin2); // 170 // Return 1 if either are 1 Serial.println(bin1 | bin2); // 255 // XOR returns 1 only if one is 1 and other is 0 Serial.println(bin1 ^ bin2); // 85 // Bitwise not converts each to its opposite Serial.println(~0b0111); // -8 because highest bit // (sign bit) was changed to 1 making it negative // Shift bits right Serial.println(bin2 >> 2); // 00111111 = 63 // Shift bits left Serial.println(bin2 << 2); // 1111111100 = 1020 // Structs allow you to create custom data types struct RGB{ byte red; byte green; byte blue; }; RGB color = {0,255,0}; if(color.red == 0 && color.green == 255 && color.blue == 0){ Serial.println("It's Green"); } // sprintf creates formatted strings printTime(1, 12); // Pointers // A pointer refers to a memory location of a variable // Create a pointer for an int int *ptr; int val1 = 15; // Store the memory location in a pointer ptr = &val1; // Print the value pointed at Serial.println(*ptr); // An array is a pointer int primes[] = {2,3,5,7}; // Print the 1st index Serial.println(*primes); // Print the 2nd index Serial.println(*primes + 1); // Pass an array to a function printArray(primes, 4); } void loop() { // put your main code here, to run repeatedly: } void printTime(int hour, int minute){ // Will store the time in a char array char buffer[6] = ""; // ints with a : between 02 guarantees 2 digits show sprintf(buffer, "%02d:%02d", hour, minute); Serial.println(buffer); } // Prints out the array void printArray(int arr[], int size){ for(int i = 0; i < size; i++){ Serial.println(arr[i]); } } // ————— END PART 3 ————— |
Leave a Reply