Starting with C++ concepts will provide you with a deeper understanding of the underlying principles of programming and memory management, which are crucial for efficient resource utilisation in embedded systems. This knowledge will translate into more efficient and maintainable Arduino C code, enabling you to create more sophisticated projects and troubleshoot issues more effectively.
To make it easier for us we will start with Arduino C and the Serial Monitor but you may want to work through a course in C++ first, such as the C++ Tutorial for Beginners from Simplilearn or C++ Introduction by Codefinity.
"I consider these skills essential because, often, students tend to copy and paste code from the internet without a thorough understanding of its functionality. This results in challenges when it comes to integrating different code segments and troubleshooting issues.
By imparting coding skills to students, we can ensure they establish a robust foundation, particularly if they wish to pursue further studies in Electronics, especially embedded systems.
Additionally, it provides them with the opportunity to explore the Programming standard, typically executed using Python. " - Katana Dunn, Electronics Teacher
Embedded programming is used to create software for specialised hardware, often with limited resources. It is often used in devices like smartphones, wearables, and industrial automation systems. Embedded programming requires a strong understanding of programming concepts and low-level programming languages like C and C++.
Desktop programming is used to create software for personal computers or workstations. It encompasses a wide range of applications, including web browsers, office suites, games, and media players. Desktop programming requires a strong understanding of programming concepts and higher-level programming languages like Python, Java, and C#.
Choosing between embedded and desktop programming depends on the student's interests and career goals. Embedded programming is a good choice for students who enjoy working with hardware and creating real-time systems. Desktop programming is a good choice for students who are interested in developing user-facing applications and web-based solutions.
Both embedded and desktop programming offer valuable skills and knowledge for high school students interested in electronics and computer science. By understanding the differences and exploring both paths, students can make informed decisions about their future endeavors in the exciting world of electronics and software development.
Understanding Programming Concepts: Programming forms the foundation for interacting with Arduino boards and electronics. Without a grasp of basic programming concepts like variables, data types, operators, control flow statements, and functions, it becomes challenging to effectively control and manipulate hardware components.
Problem-Solving and Algorithmic Thinking: Programming instills problem-solving and algorithmic thinking skills, which are essential for designing and implementing successful Arduino projects. Learners develop the ability to break down complex problems into smaller, manageable steps, formulate algorithms to solve those steps, and translate those algorithms into code.
Code Reusability and Error Correction: Prior programming knowledge enables learners to leverage existing code libraries and examples, reducing the need to reinvent the wheel for every project. Additionally, it facilitates debugging and troubleshooting, as learners can identify and fix errors more effectively.
Adaptability to Different Programming Languages: Once familiar with the fundamentals of programming, learners can more easily adapt to different programming languages, including Arduino C, Python, and other languages used in electronics and robotics.
Enhanced Creativity and Innovation: Programming empowers individuals to express their creativity and innovative ideas through electronics projects. With a solid programming foundation, learners can bring their ideas to life by controlling hardware components and creating interactive devices.
In summary, learning programming before diving into Arduino C and electronics projects provides a strong foundation for understanding programming concepts, developing problem-solving skills, adapting to different programming languages, and unleashing creativity in electronics and robotics. It is also essential for optimising code for the limited storage space available in the Arduino.
Arduino is an open-source electronics platform that provides a flexible and easy-to-use hardware and software environment for creating interactive projects. Arduino boards are based on microcontrollers, and the Arduino programming language, often referred to as "Arduino C" or simply "Arduino language," is a simplified version of C/C++.
While the syntax is similar to C/C++, Arduino programming is designed to be more beginner-friendly, making it accessible to those without extensive programming experience. The Arduino IDE (Integrated Development Environment) simplifies the process of writing code for Arduino boards. It includes a set of libraries and functions that abstract low-level details, making it easier to work with sensors, actuators, and other hardware components.
In summary, Arduino C is a variant of the C programming language adapted for use with Arduino boards, offering a simpler and more user-friendly approach for hobbyists, students, and makers.
Always add an appropriate, descriptive filename so it is easy to find the code. Using the Arduino App locally installed means it provides the opportunity to develop file and folder management skills.
In this program, all code in the setup() function only run once while the loop() function repeats. If using Tinkercad Circuits or the Arduino App you must have an Arduino on the canvas or attached to your computer to run the code.
Docstrings and comments are essential elements in programming for documentation purposes. While they serve different purposes, both contribute to the clarity, maintainability, and understanding of code.
In programming, data types are a fundamental concept that defines the type of data that a variable can hold. Data types specify the nature of the data and the operations that can be performed on it. Different programming languages offer various data types to accommodate different kinds of information.
Importance of Data Types in Programming:
Memory Allocation: Different data types require different amounts of memory. Understanding and specifying data types help in efficient memory usage, optimizing program performance.
Operation Compatibility: Data types determine what operations can be performed on the data. For example, you can perform arithmetic operations on numerical data types, but not on strings without conversion.
Error Prevention: Using appropriate data types helps prevent errors and ensures that variables are used in a way that is consistent with the intended purpose. It helps catch potential issues during the compilation or runtime.
Code Clarity: Explicitly specifying data types makes code more readable and understandable. It provides clear information about the kind of data a variable holds, making the code more maintainable.
Interoperability: In some cases, when interacting with external systems or libraries, specifying data types ensures compatibility and seamless communication between different components of a program.
In summary, understanding and using data types appropriately is crucial in programming to enhance code efficiency, prevent errors, and facilitate better communication between different parts of a program or between different programs.
Arrays
An array is a data structure in programming that allows you to store a collection of elements, all of the same data type, under a single variable name. Each element in the array is accessed by its index or position within the array, starting from zero.
String Manipulation
In Arduino programming, string manipulation is often performed using C-style character arrays. Here are some common string operations in Arduino C:
Concatenate Strings
char str1[] = "Hello";
char str2[] = "World";
char result[20];
strcpy(result, str1);
strcat(result, " ");
strcat(result, str2);
strcpy(): Replace the destination with the source string.
strcat(): Append the source string to the destination string.
Access Individual Characters
char firstChar = str1[0];
Get Length of a String
int length = strlen(str1);
Substring Extraction
char sub[4];
strncpy(sub, str1 + 1, 3);
sub[3] = '\0'; // Null-terminate the substring
Find a Character or substring
char* found = strstr(str1, "ll");
if (found != nullptr) {
int position = found - str1;
}
Compare Strings
if (strcmp(str1, str2) == 0) {
// Strings are equal
}
Append to String
String str= "Hello";
str.concat(" Arduino");
or str += " Arduino";
or str1 + str2;
Why arrays are important:
In Arduino programming, which is typically done using a simplified version of C or C++, arrays play a crucial role due to the specific needs and constraints of embedded systems like those on Arduino boards. Here's why arrays are useful in Arduino C:
Memory Efficiency: Arduino boards often have limited memory, and using arrays allows for efficient storage of multiple values in a contiguous block of memory. This is particularly important when dealing with sensor readings, data logging, or other applications where memory usage is a concern.
Data Storage: Arrays are useful for storing sensor readings, historical data, or any set of values that need to be processed or displayed. They provide a structured way to organize and access data.
For Loops and Iteration: Many Arduino programs involve repetitive tasks, and arrays are well-suited for use with for loops. This is helpful when working with multiple sensors or when you need to perform a series of similar operations on a set of data.
Sensor Readings: Arduino projects often involve interfacing with sensors. Arrays can be used to store readings from multiple sensors, making it easier to manage and process data from various sources.
LEDs and Displays: When working with arrays of LEDs or segments on an LED display, arrays simplify the control and manipulation of individual elements. For instance, you might use an array to represent the state of each LED in a matrix.
String Handling: In Arduino programming, strings are often represented as character arrays. Arrays make it convenient to manipulate and process strings, especially when dealing with input/output or communication with other devices.
Multi-Dimensional Arrays: Arduino applications sometimes require multi-dimensional arrays, which are arrays of arrays. These are useful for representing grids, matrices, or two-dimensional sensor data.
Efficient Code: Arduino programs often run on microcontrollers with limited processing power. Efficient data structures, like arrays, contribute to writing code that consumes fewer resources and executes more quickly.
Communication Protocols: Arrays are frequently used when working with communication protocols such as I2C or SPI. Sensor readings or configuration data can be organized in arrays for efficient data exchange.
In summary, arrays are essential in Arduino programming as they provide an efficient and organized way to handle data, making it easier to manage, manipulate, and process information in the resource-constrained environment of embedded systems.
The Serial Monitor in Arduino is a tool provided by the Arduino IDE (Integrated Development Environment) that allows you to communicate with your Arduino board and monitor the data being sent or received through the serial port. It is particularly useful for debugging and testing purposes.
We use the Serial library which include a series of functions for communicating with the serial port on the Arduino boards.
Serial.begin(baudrate) start the Serial communications. The baud rate is the speed at which data is transmitted over the serial connection. The baud rate you choose must be the same as the Serial Monitor.
Serial.println(Add here what you want to print) print stuff on the Serial Monitor and moves to the next line. Serial,print() add now new line.
Serial.available() and Serial.read(): These functions are used for receiving data from the serial port. Serial.available() returns the number of bytes available to read, and Serial.read() reads the next byte of incoming serial data.
Serial.write(data): This function is used to send raw binary data to the serial port.
The Serial Monitor is access via the Tools menu or Ctrl+Shift+M.
Task
Create the code, "Helloworld.ino" from above using the Arduino App or Tinkercad Circuit.
Open the Serial Monitor and observe output.
Add the delay function to write the words slower.
Change the output to anything you like.
Only move on when you happy with results. Remember coding conventions such as indents, doc string, comments.
We can read either an integer or a string from the serial monitor using the commands Serial.available() and Serial.read(). These functions are used for receiving data from the serial port. Serial.available() returns the number of bytes available to read, and Serial.read() reads the next byte of incoming serial data.
Task
Create the above code. Start with any of the two pieces of code.
Read various numbers or string in an make sure they display appropriately in the serial monitor. If the number is too big you may find you have to change the data type as the numbers will not be the same.
See if you can read a float reliably using the "Serial.parseFloat" command.
Loop Statements
In Arduino C/C++, you can use several loop statements to control the flow of your program and execute a block of code repeatedly. The primary loop statements in Arduino are:
for Loop: The for loop is used to execute a block of code a specified number of times. It typically consists of three parts: initialization, condition, and increment.
for (initialization; condition; increment) {
// Code to be executed repeatedly
}
while Loop: The while loop is used to execute a block of code as long as a specified condition is true. It's suitable when you want to repeat a task until a certain condition is met.
while (condition) {
// Code to be executed repeatedly as long as the condition is true
}
do...while Loop: The do...while loop is similar to the while loop but guarantees that the block of code is executed at least once, as the condition is checked after the code block.
do {
// Code to be executed at least once
} while (condition);
loop() Function (Arduino-specific): Arduino sketches often have a special loop() function, which is the main entry point for program execution. The code inside the loop() function is executed continuously, allowing you to create programs that run indefinitely.
void loop() {
// Code to be execute
These loop statements are essential for creating iterative and repetitive behaviour in Arduino programs. You can use them to control the execution of code within your projects and handle tasks that need to be repeated multiple times, such as reading sensors, controlling actuators, or running animations.
Task 3: The purpose of task 3 is to practice the for loop
Add the following code and follow the instructions
In this task, we will look at the basics of the For Loop. The For loop is one of the programming structures that allows you to execute a block of code repeatedly as long as a certain condition is met. The format for the For statement is:
---- for(initialisation/start value/begin; condition to end value; iteration / update/ step) ----
The task is to write 1 to 10 and 10 to 1 in the Serial Monitor. The instructions are for Tinkercad Circuits but can easily be modify for the Arduino App.
1) Click on the Code button and select Text.
2) Add a Docstring at the top: /*Add description here */
3) Under Variable Declarations, add an int variable called value.
4) In the setup function add the line to start the serial communication between the Arduino and the computer. "Serial.begin(9600);"
5) Test the first For statement to see what it does. Basically just run the code and look at the Serial Monitor output.
6) Obviously, the code is not doing what was asked. Fix it so it writes from 1 to 10. Test
7) Then add the code to output 10 to 1. Test
Task 4: Modify the code to output odd numbers from 1 to 100. Use the same idea to output only even numbers. Hint: Use the modulo operation and you will need the selection statements
Functions are like mini-programs within your main program. They help you break down your code into smaller, more manageable pieces, making it easier to understand, write, and fix errors. Think of it like dividing a big task into smaller steps.
Functions also make your code more reusable. Once you've written a function to do something, you can use it again and again, saving you time and effort. It's like having a tool kit full of useful tools to build your program.
In short, functions are essential for writing clear, efficient, and maintainable Arduino C programs. They are like the building blocks of good programming practices.
There are three ways, we use functions.
Function with No Argument or Return Value:
In this example, the greetUser() function takes no arguments (void in the parentheses) and does not return any value (void before the function name). It simply prints a greeting message to the Serial Monitor.
Function with an Argument:
In this example, the squareNumber(int num) function takes one argument (int num) and has no return value. It calculates the square of the input number and prints the result to the Serial Monitor.
Function with a Return Value:
In this example, the addNumbers(int a, int b) function takes two arguments (int a and int b) and returns an integer value (int). It calculates the sum of the two input numbers and returns the result. The setup() function calls this function, captures the return value, and prints the sum to the Serial Monitor.
Using all the skills from above to create various programs. Make sure you name them appropriately, use conventions such as appropriate variable names, indents, docstring and comments. For all code make sure you make it as efficient as you can. Use functions where appropriate. You can use the starting code on the right.
Sequence: Create code that write the number 1 to 5 and back on the serial monitor. Add each number on a new line.
Sum of Numbers: Implement a program that takes a series of numbers from the Serial Monitor, adds them up, and prints the total.
Create a function that ask for your name. Return the value to the main loop and display. Use the function String getName(){}.
Create code adding all the numbers in an array:
int numbers[] = {3, 7, 1, 5, 9};
First display the numbers before you display the answer. Make sure it is user friendly.
Create code to add the numbers to the array in 3 from the Serial Monitor (Input by user).
Number guessing game: Create a number guessing game. The code create a random number that the user has to guess. Make sure it is user friendly. Also add hints to the user. There are two functions you can use: random(max) or rand(min, max), randomSeed() can be used to initialise the random number generator.
String Reversal: Take a string as input through the Serial Monitor and print its reverse.
Multiplication Table: Print the multiplication table of a given number, allowing the user to input the number through the Serial Monitor.
Palindrome Checker: Write a program that checks if a given word or phrase entered through the Serial Monitor is a palindrome.
Factorial Calculator: Create a program that calculates the factorial of a given number entered through the Serial Monitor.
Create a menu for the functions above. Ask the users name and for them to choose one of the options. The user follow the instructions online. Make sure it repeats until the user Quits. And example of how to start a menu are shown to the right.
Challenges
ASCII Art Generator: Allow the user to input a character through the Serial Monitor and print its ASCII art representation.
Simple Timer: Implement a timer that counts down from a specified time (entered through the Serial Monitor) and prints the remaining time.
Password Checker: Create a password checker function for a four digit number entered via the serial port. Display suitable message if it is correct or not. Develop the code iteratively and add a limit to the number off guesses.
void setup() {
Serial.begin(9600);
}
void printMenu() {
Serial.println("Menu:");
Serial.println("1. Option 1");
Serial.println("2. Option 2");
Serial.println("3. Option 3");
Serial.println("4. Exit");
}
void handleOption(int option) {
switch (option) {
case 1:
Serial.println("You selected Option 1");
// Add code for Option 1
break;
case 2:
Serial.println("You selected Option 2");
// Add code for Option 2
break;
case 3:
Serial.println("You selected Option 3");
// Add code for Option 3
break;
case 4:
Serial.println("Exiting menu");
break;
default:
Serial.println("Invalid option");
}
}
void loop() {
printMenu();
Serial.print("Enter your choice: ");
while (!Serial.available()) {
// Wait for user input
}
int userChoice = Serial.parseInt();
Serial.println(userChoice);
handleOption(userChoice);
delay(1000); // Delay for readability
}