12 Arduino Projects for Beginners — With Code

license

Introduction: 12 Arduino Projects for Beginners — With Code

12 Arduino Projects for Beginners — With Code

Have you ever wanted to learn how to write code for the Arduino board by working on fun Arduino projects, but never really knew where or how to start?

Well, I believe that every Maker has already been there. That’s the reason why I have create a collection of Arduino projects with increasing level of difficulty for anyone to start getting more familiar with programming the Arduino board. The projects will allow you to learn the basics of the Arduino in a very efficient manner, and take you step by step to building more complex projects.

Step 1: Arduino Projects

This collection of Arduino projects from very basic to more advanced includes:

  • LED brightness
  • Traffic Light Controller
  • Servomotor Control
  • Smart Night Lamp
  • Voice control
  • and much more…

These Arduino projects can inspire you for your own projects. If you want to learn more, you can take our complete Udemy online course: Arduino and Robotics .

The projects source code can be found on Github . Without further due, let’s start!

Step 2: LED Blink

The “LED Blink” is for the Arduino the equivalent of the “Hello world” in computer programming, where you will need to write a code to have the sentence “Hello world” displayed in the console of a computer. Not really exciting, but it gives a hint on the inner workings of the Arduino board. Each Arduino board comes with an on-board LED that can be used for this purpose. The project toggles the default LED of the Arduino board located on the pin 12 (ledPin) ON and then OFF every 2 seconds (delayTime, note: 2s=2000ms).

Arduino LED blink code

int ledPin = 12;
int delayTime = 2000;
voidsetup() {
pinMode(ledPin,OUTPUT);
}
voidloop() {
digitalWrite(ledPin, HIGH);
delay(delayTime);
digitalWrite(ledPin, LOW);
delay(delayTime);
}

Step 3: LED Button Control

Once more comfortable with the “LED Blink” project, the more natural way to move forward is to add more control on our LED. We can use a push button for this purpose and only switch the state of the LED when the button is pressed down. The “if” statement in line 14 is used to check for a change of state of the button, in this case state transition “button up” to “button down”. The code only toggles the state of the button 200 ms after the button is pressed in order to filter the input. This process is called denouncing.

arduino_led_button_toggle.ino

int inputPin = 0;
int ledPin = 12;
int buttonState = 0;
int buttonStateTm1 = 0;
int ledState = LOW;
voidsetup() {
pinMode(inputPin, INPUT);
pinMode(ledPin, OUTPUT);
}
voidloop() {
buttonState = digitalRead(inputPin);
if(buttonState > buttonStateTm1){
delay(200);
ledState = !ledState;
}
digitalWrite(ledPin, ledState);
buttonStateTm1 = buttonState;
}

Step 4: LED Brightness Control

The Arduino projects are starting to get more interesting as we move forward in this post. So far, we have only controlled the LED in a binary form. ON or OFF depending on various events and inputs. But wouldn’t it be nice to control the brightness of our LED? Well that’s exactly what we will do in this project!

Controlling the brightness of an LED is equivalent to controlling the voltage on the pins of the LED. To do that, we will use the PWM output of the Arduino board. With the LED connected to pin 3 and a potentiometer connected to the analog input A0, the code bellow changes the brightness of our LED by rotating the potentiometer.

led_brightness_control.ino

int ledPin = 3;
int valPot = 0;
voidsetup() {
}
voidloop() {
valPot = analogRead(A0);
valPot = map(valPot, 0, 1023, 0, 255);
analogWrite(ledPin, valPot);
}

Step 5: Traffic Light

To continue and end our Arduino projects on LEDs, let’s build a traffic light controller with 3 LEDs (Red, Yellow, Green). Each LED should light up one after the other after a specified amount of time to emulate a traffic light. For further improvements, a button can also be connected to the Arduino to emulate, a “Pedestrian crossing” button that makes the traffic light turn to Red on demand.

traffic_light_controller.ino

//Declare the pins on which the LEDs are connected
int ledPinRed = 2;
int ledPinYellow = 1;
int ledPinGreen = 0;
voidsetup() {
// Set the pins 0, 1, 2 as output
pinMode(ledPinRed, OUTPUT);
pinMode(ledPinYellow, OUTPUT);
pinMode(ledPinGreen, OUTPUT);
//Turn OFF all the LEDs
digitalWrite(ledPinRed, LOW);
digitalWrite(ledPinYellow, LOW);
digitalWrite(ledPinGreen, LOW);
}
voidloop() {
// Successively Turn on each LED
changeLedState(ledPinRed, 3000);
changeLedState(ledPinYellow, 1000);
changeLedState(ledPinGreen, 3000);
}
voidchangeLedState(int ledPin, int duration){
//Turn ON the selected LED and turn off
//all the other ones
if(ledPin == ledPinRed){
digitalWrite(ledPinRed, HIGH);
digitalWrite(ledPinYellow, LOW);
digitalWrite(ledPinGreen, LOW);
}
elseif(ledPin == ledPinYellow){
digitalWrite(ledPinRed, LOW);
digitalWrite(ledPinYellow, HIGH);
digitalWrite(ledPinGreen, LOW);
}
elseif(ledPin == ledPinGreen){
digitalWrite(ledPinRed, LOW);
digitalWrite(ledPinYellow, LOW);
digitalWrite(ledPinGreen, HIGH);
}
else{
digitalWrite(ledPinRed, LOW);
digitalWrite(ledPinYellow, LOW);
digitalWrite(ledPinGreen, LOW);
}
delay(duration);
}

Step 6: Servomotor Control

Hoora!!! It is great to have been able to explore small but interesting projects with LEDs. But wouldn’t it be great to see something physically moving and controlled by the Arduino?

We can use a servomotor for this. A servomotor is controlled almost in the same way as the LED is controlled in the “LED brightness control” project, but there is more to it than just setting the PWM output of the Arduino to a specific value. This is when libraries comes very handy, we can use the “Servo.h” library provided with the Arduino development environment to make it very simple to control a servomotor. We include the library in our project and use the functions “attach()” and “write()” to respectively configure the PWM output port to be used with a Servomotor and set the position of the servomotor. The position of the servomotor will oscillate between -180° to +180°.

servomotor.ino

#include
int servoPin = 3;
Servo myservo;
voidsetup() {
myservo.attach(servoPin);
}
voidloop() {
for( int pos = 0 ; pos ; pos++){
myservo.write(pos);
delay(15);
}
for( int pos = 180; pos>= 0; pos--){
myservo.write(pos);
delay(15);
}
}

Step 7: Smart Night Lamp

Let’s now put everything together into a single project. The Smart Night Lamp will use all the knowledge that we have acquired so far. We will change the brightness of 3 LEDs by using a potentiometer, and set the angle of a servomotor to it’s current value to indicate the brightness level. Note that a single multi-color LED can also be used instead of the 3 LEDs, this will result in effectively having different colors. A multi-color LED has 3 pins and allows to control it’s Red, Green and Blue value to create any color in the visible spectrum. For simplicity, we will stick here to what we have already learned so far, but for more advanced learners, I would recommend to give a go and use the multi-color LED instead.

smart_night_lamp.ino

#include
int buttonState = 0;
int buttonState_tm1 = 0;
constint buttonPin = 0;
constint ledPinRed = 6;
constint ledPinBlue = 5;
constint ledPinGreen = 3;
constint servoMotorPin = 9;
int valLedRed = 0;
int valLedGreen = 0;
int valLedBlue = 0;
int pwmRed = 0;
int pwmGreen = 0;
int pwmBlue = 0;
int valPotentiometer = 0;
int cmdPosServo = 0;
int _max_pwm_val = 100;
Servo myservo;
voidsetup() {
pinMode(buttonPin, INPUT);
myservo.attach(servoMotorPin);
}
voidloop() {
buttonState = digitalRead(buttonPin);
valPotentiometer = analogRead(A0);
if(buttonState > buttonState_tm1){
delay(200);
valLedRed = random(_max_pwm_val);
valLedGreen = random(_max_pwm_val);
valLedBlue = random(_max_pwm_val);
}
cmdPosServo = map(valPotentiometer, 0, 1023, 0, 180);
valPotentiometer = map(valPotentiometer, 0, 1023, 0, _max_pwm_val);
pwmRed = (int) constrain(valLedRed + (valPotentiometer - _max_pwm_val/2.0), 0.0, _max_pwm_val);
pwmGreen = (int) constrain(valLedGreen + (valPotentiometer - _max_pwm_val/2.0), 0, _max_pwm_val);
pwmBlue = (int) constrain(valLedBlue + (valPotentiometer - _max_pwm_val/2.0), 0, _max_pwm_val);
changeColor(pwmRed, pwmGreen, pwmBlue);
myservo.write(cmdPosServo);
buttonState_tm1 = buttonState;
delay(15);
}
voidchangeColor(int red, int green, int blue){
analogWrite(ledPinRed, red);
analogWrite(ledPinGreen, green);
analogWrite(ledPinBlue, blue);
}

Step 8: Play Tunes

That’s an exciting Arduino project, being able to play various tunes with the Arduino board. Although this may seam daunting at first and seems to require a deep knowledge of the musical language, it is fairly easy to produce sound using the Arduino board. By connecting a buzzer on a PWM output of the Arduino board and using the built-in function “tone(pin, frequency, duration)” it is possible to generate a tone of any frequency for a specific duration. A melody is just a succession of those tones. In this example the frequency and the duration of each tone is stored in arrays and are later on played by reading each value in the arrays.

Play tunes using the Arduino board and a piezzo-electric buzzer

#defineNUM_NOTES8
int buzzerPin = 3;
int melody[NUM_NOTES] = {
262, 196, 196, 220, 196, 0, 247, 262
};
int noteDurations[NUM_NOTES] = {
4, 8, 8, 4, 4, 4, 4, 4
};
voidsetup() {
}
voidloop() {
for(int noteId = 0; noteId
int noteDuration = 1000/ noteDurations[noteId];
tone(buzzerPin, melody[noteId], noteDuration);
int pauseBetweenNotes = noteDuration* 1.3;
delay(pauseBetweenNotes);
noTone(buzzerPin);
}
}

Step 9: Voice Control

Who has never dreamed of interacting with an advanced artificial intelligence such as Jarvis first seen in the movie Iron Man? Well it would be even better to build one by yourself :)!

Connecting a microphone to the Arduino board will allow us to just do that. Voice is just another analog signal that we can capture by using an analog input. By connecting a microphone on the analog pin A0, we can capture our voice as a signal that changes over time. The simplest way to integrating voice control in any application is to just use the amplitude of the vocal signal to generate an action once this amplitude is above a specific value. In this project, we will turn on an LED by speaking into a microphone. We detect the amplitude of the vocal signal (how loud the signal is) and turn on an LED if the signal is above a threshold. Any loud sound can change the state of the LED in this project, this can serve as the basis to implementing more complex behaviours.

voice_control.ino

int soundLevel = 0;
int ledPin = 12;
bool toggle = false;
voidtoggleLEDState(){
digitalWrite(ledPin, toggle);
toggle = !toggle;
}
voidsetup() {
pinMode(ledPin, OUTPUT);
}
voidloop(){
soundLevel = analogRead(A0);
if(soundLevel >= 650) {
delay(100);
toggleLEDState();
}
delay(1);
}

Step 10: Conclusion

Congratulations, if you have reached so far in this post, they are even more exciting projects in the github repository that involves using the Arduino 101 board and create cool project with functionalities only available on this board such as accelerometers, timers, Bluetooth, etc…

Below are some useful links:

Udemy course: Arduino and Design : Make Your First Robot

Github: Projects Code

Hope you enjoyed this post, it will be updated as more projects are added to the github repository, so stay tuned and keep coding awesome projects.

Recommendations

Lenticular Clock

Water Contest

Water Contest

Outdoor Life Contest

Outdoor Life Contest

Farm to Table Contest

Farm to Table Contest

Arduino programming and syntax : A definitive guide for beginners

Once you have set up your Arduino IDE , it is time to begin writing the code. Coding for the Arduino platform is effortless. There are a ton of libraries to make things easier. The syntax is fairly simple too. In this post, we will cover almost all the essential language elements of an Arduino sketch (program). After this, you should be able to read, write and undertake any Arduino coding project.

What is an Arduino program?

The Arduino program is usually written in the Arduino IDE. The program is a set of instructions in embedded C. It has some special header files as zip files that are available online to provide specialised functions. An Arduino program is known as a sketch.

The Arduino code should contain two functions as void setup() and void loop(). These two are the main elements of any Arduino code. They are known as functions. We will take a closer look at them soon.

What language is used for writing an Arduino program?

Embedded C is used to write the Arduino programs. It is used for applications that very near to the hardware. That directly communicates with the hardware. It is very similar to C and C++. But it has some built-in functions other than normal functions used in ordinary C.

What is a sketch?

What are the general syntax elements in arduino programming.

The general syntax for writing the Arduino program is almost similar to that of ordinary C and C++. Those who are familiar with basic C and C++ can do it easily. If you would like a quick recap of your C knowledge, we have a free C programming course for beginners that you can check out.

Parameters: variable is the name, that has to be assigned to the value. Constant is the value that is used in the program.

#include<>

It is one of the best features of the Arduino IDE. There are several libraries available online. They are specially written for Arduino’s purpose. Each library gives you some additional access to the sensors and modules.

Akin to the #define command, there is no semicolon needed at the end of the #include statement. Otherwise, it will show a cryptic error.

Parameters: The library file is the additional header to be added. Here’s how you can include a library file in your Arduino IDE .

This example includes the SoftwareSerial library so that its functions may be used to control a GPS.

All the commands like ss.read in the above sketch are courtesy of the library file we included in the beginning. Without that library file, it would become incredibly difficult to implement GPS functionality.

Block comments /* */

The starting of the comment block is marked by /*, and the ending is marked by */.

Block comments can have multiple lines. When you wish to have a single line comment you can use // and then write the comment. Similar to/**/, these comment lines are also ignored by the compiler. It doesn’t take any space in the microcontroller’s memory. Moreover, it helps you to understand how the program works.

curly braces {}

Unbalanced braces tend to cryptic error. The code within the braces is said to be a block that may be a function.

Semicolons ;

What is the general structure of a sketch, void setup().

The setup() function should be the first one that is called when a sketch starts to run or compile. This function block is used to initialize the pin-modes, variables and also the baud rate. It will only run once when the Arduino is powered or tends to reset.

void loop()

It is the block that contains the code which has the instruction that has to be performed infinitely by the microcontroller from when the Arduino board is powered on till when it’s powered off.

What are the different types of variables in an Arduino program?

What is int.

Integers are the data type that can store numbers. In Arduino Uno, an int can store a 16- byte value that is 2-byte. Here, int has the range of -32,768 to 32,767. That is -2^15 to 2^15. In some boards like Arduino Due, an int can store a 32-bit value that is 4- byte.

What is char?

Characters are also stored as numbers. These standard numbers that are allocated for all characters are called ASCII numbers. For example, the ASCII value of ‘B’ is 66.

What is float?

It helps to store decimal numbers. Floating-point numbers are used to approximate the analog and continuous values due to their greater resolution when compared to integers. Range of float data type is from     -3.4028235E+38 to 3.4028235E+38. It has 32-bit storage.

What is bool?

What is the local variable.

Local variables are variables with local scope. We can use it only within the code block where we declare it.

What is a global variable?

What are the different arithmetic functions that can be performed in an arduino, what is multiplication operation.

Operator: *

Syntax: value1 *value2;

What is the remainder operation?

It helps us to find the remainder when one integer is divided by another integer. It works only for int datatype, not for float datatype

What is the division operation?

Operator: /

What is the addition operation?

What is the subtraction operation.

Operator: –

What is the assignment operation?

It can assign the numbers on the right side to the variable on the left side of the operator.

What are the different comparison functions in an Arduino program?

What is equal to operation, what is not equal to operation.

It checks whether the two numbers on the left and right sides are not the same or not. And returns true or false.

What is less than operation?

Operator: <

What is less than or equal to operation?

What is greater than operation.

Operator :>

It checks whether the numbers on the left is greater than the number on the right side and returns true or false.

Syntax: value1 > value2;

What is greater than equal to operation?

Syntax: value1 >= value2;

What is pin mode declaration?

Function: pin mode(pin, mode).

We use the pinMode command to define the function of pins on the Arduino board . It helps to declare the PIN and the mode on which the pin is performed. It initializes the pins of the Arduino board which are to be used as input pins or output pins.

Pin- The PIN may be a digital or analog pin of the Arduino board where the hardware is connected.

Digital pins control

Digitalread(pin).

You can use it to get the digital input from the devices such as sensors and Arduino shields in the form of 0’s and 1’s.

digitalWrite(Pin, Mode)

It is useful in giving digital output to devices such as modules, shields, LED, motor and other electronic devices. In the form of 0’s and 1’s. That pin can give up to 3.3V when the output is 1.

Analog pins control

There are five analog I/O pins present in the Arduino Uno board. It can send and receive analog signals. It is useful in PWM control and also helps to get accurate readings of the sensor.

AnlogRead(Pin)

You can use it to get the analog input from the devices such as sensors and shields in the form of 0’s and 1’s.

AnalogWrite(Pin, Value)

You can use this function to give the analog output to the devices such as modules, shields, LED, motor and other electronic devices. It also helps in PWM control.

What are branch or redirect statements?

What is the break statement.

Syntax: break

What is the return statement?

It returns the value to the variable. Usually, functions use this return statement.

What is the continue statement?

Syntax: continue

What is the goto statement?

Syntax : goto

What are the control statements?

Control statements allow you to add a condition to a loop. If you want to control the number of times a loop executes with some parameters, then control statements are the right tools for you.

What is ‘for’ statement?

Arguments: There are three arguments inside the for statement.

Next, third is the changing condition that states how to increment or decrement the variable for upcoming iterations.

What is the while statement?

We have covered the working of the while loop in-depth here .

What is the do-while statement?

Syntax: do{

We have covered the working of the do-while loop in-depth here .

What is the Serial begin function?

Syntax: Serial.begin(value)

What is the Serial print function?

Format- It is not necessary, but it helps you to print the data in a specified format such as binary, octal, decimal.

What is the Serial print ln function?

What is the serial parse int function.

It looks for the next valid integer if the current input is not an integer.

What is the Serial parse Float function?

It returns the first valid integer from the serial buffer.

What is String()?

It creates a string class. That is, a sequence of characters. There are many types to construct strings from different datatypes that format them as a sequence of characters. It returns an instance of string class

Gives the string “13”

What is an Array?

It has only four elements, but the size is five, so a[4] provides garbage value. And a[6] has an invalid address.

And also, you can get the value by,

What is a Function?

Other than built-in functions, you can also write your functions. Using this, we can divide the large program into basic building blocks.

We have covered the working of the functions in C in-depth here .

There’s a lot more that you can do with an Arduino, and we will cover the next stage of programming an Arduino at a later stage in this Arduino course . However, what we have seen in this post should be more than enough to get you up and running with most projects. If there is any query that you have, we are always happy to help. Let us know in the comments, and we’ll get back to you. Feel free to bookmark this page for all future reference.

Related courses to Arduino programming and syntax : A definitive guide for beginners

8085 Microprocessors Course

A free course on Microprocessors. Start from the basic concepts related to the working of general microprocessors and work upto coding the 8085 and 8086.

Design For Testability Course

Digital electronics course.

i love your work easy to understand I give you AA++ for your work . im 60 year olde ime just sarting to worke on pc and Arduino

Leave a Reply Cancel reply

Assignment 3 - Step Counting on an Arduino

You will recreate your step counter from Assignment 1 on an Arduino. Your algorithm can be the exact same as it was before (assuming it worked well), or you can completely change the algorithm. Like before, you can assume that the Arduino is in a fixed position in your hand. The step count should be displayed in binary using the 5 NeoPixel LEDs along the left side of the board. Although only 4 LEDs are needed, using 5 LEDs allows your board to clearly show if your step counter is over-counting. LED #0 should be the least significant bit, LED #1 the second least significant bit, etc.

Deliverables:

Source code (.zip, .tar, or GitHub link): link In-class demo

Experimenting With Arduino

Arduino programming: conditional statements, objectives and overview.

This lesson introduces control flow and conditional statements. Additionally, this lesson includes examples of basic conditional statements and the role of assignment and comparison operators in programming.

Lesson Objectives

  • Understand and explain how conditional statements help programs make decisions.
  • Explain the purpose of  assignment operators  and  comparison operators  in conditional statements.

Control Flow in Arduino Programming

The term  control flow  may seem daunting at first but at its core its essentially a group of statements and structures that govern the interactivity and processes of programs. You’ve already worked with one type of control flow in your Arduino experimentation-  functions .

The Block Statement

The first, and most basic, control flow statement is the  block statement . You’ve actually already integrated these into your code when you’ve worked with  functions . Consider this code contained within the  void loop()  function (you’re going to have this code memorized by the end of the course!):

With regard to the above example, you can think of the block statement as containing, or controlling, the code within the function. In this particular example, this would be the code that controls the on/off messages of the LED as well as the delays.

Code contained within  { }  is intentionally chunked together.

Conditional Statements

Conditional statements  are one of the core pillars of programming, whether it be for the web, video games or other applications. Developing a practical and functional understanding of working with conditional statements will greatly enhance the level of interactivity that you’re able to develop and include in your code.

Let’s take a look at two examples. The first demonstrates a concept, and the second is a snippet of functional Arduino code.

Example One :

In this example, the if statement evaluates a condition that is contained with the  ( )  following the  if . The statement that is within the  ( )  needs to be able to be evaluated as a Boolean value, meaning it must either evaluate to  true  or  false .

In the above example, the statement would evaluate as true  if the value of the variable x is greater than 10 . If this returns true, then the code within the first set of  { }  is executed.

This particular form includes an else { } block statement as well. This is the code that executes if the condition is false. Since the statement contained within the ( ) is Boolean, meaning it is either true  or  false, only one block statement of code will execute.

Example Two :

This is a snippet of code using a concept that you’ll integrate into an upcoming project.

This example is checking to the state of a button to determine whether it is on or off. The setup is similar to the first example, as it is checking an expression inside the  ( ) .

The if statement checks the  buttonState  variable to see if it is in a HIGH (on) state, and if that condition evaluates as true, then a  digitalWrite  message is sent to the board to turn on the LED.

In the else  { }  statement, which will execute when  buttonState  is NOT equal to HIGH , then sends a message to turn the LED off.

Notice the inclusion of  variables  in the above examples. Variables and conditional statements are commonly used together to execute commands that are determined by checking a particular state.

Now that you have an understanding of the structure of conditional statements, it’s time to introduce another key concept,  operators .

Basic Operators

This section includes some of the basic operators that you’ll use in your Arduino projects. There are lots of resources available online, particularly on the  Arduino Reference Page  for a more in-depth list if you’re wanting to develop a deeper understanding of this tool.

Assignment Operators

You’ve already worked with the first type of operator, which is the  assignment operator . These are operators that assign a value to something on the left based on the evaluation of what’s on the right. Here are some examples:

  • char placeholderName = 'Dave';
  • int result = x + y;

Comparison Operators

Another type of operator is the  comparison operator . This was used in the example above where the value of a “name” variable is checked to see if it is empty. These are commonly used in  if…else statements  because they return true or false based on the evaluation. Many of these are the same as what you’ve likely used in math classes. Here are some examples:

  • Equal ( == ): This returns true if the values are equal.
  • Not equal ( != ): This returns true if the values aren’t equal.
  • Greater than ( > ): This returns true if the value on the left is larger than the value on the right.
  • Greater than or equal to ( >= ): This returns true if the value on the left is larger or equal to the value on the right.
  • Less than ( < ): This returns true if the left value is less than the right value.
  • Less than or equal to ( <= ): This returns true if the value on the left is less than or equal to the value on the right.

One thing that you should remember is that when evaluating equality within conditional statements, you want to use the (==) operator. If you use only a single (=), Arduino thinks that you’re attempting to assign value and it can become confused about how to handle the statement.

You’ll encounter other operator types. Focus on developing an understanding of  how  operators are used with conditional statements.

Username or Email Address

Remember Me

  • Português (Brasil)
  • IoT Cloud API

The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License .

Find anything that can be improved? Suggest corrections and new documentation via GitHub.

Doubts on how to use Github? Learn everything you need to know in this tutorial .

Last Revision: Searching...

Last Build: 2024/07/30

Description

The single equal sign = in the C++ programming language is called the assignment operator. It has a different meaning than in algebra class where it indicated an equation or equality. The assignment operator tells the microcontroller to evaluate whatever value or expression is on the right side of the equal sign, and store it in the variable to the left of the equal sign.

Example Code

Notes and warnings.

The variable on the left side of the assignment operator ( = sign ) needs to be able to hold the value stored in it. If it is not large enough to hold a value, the value stored in the variable will be incorrect.

Don’t confuse the assignment operator [ = ] (single equal sign) with the comparison operator [ == ] (double equal signs), which evaluates whether two expressions are equal.

LANGUAGE if (conditional operators)

LANGUAGE char

LANGUAGE int

LANGUAGE long

Assignment 3

Arduino programming.

In groups of two, write your first name by switching 9 LEDs on/off and push buttons such that: With press of one push button, the letters of the name blink every 1000 ms 2) With press of another push button, all LEDs blink ON and then OFF with a delay of 1000 ms five times. 3) Extra credit: Also, print the letter typed on the Serial Monitor using the 9 LEDs

This entire process has to be documented and a video has to be uploaded on your assignment webpage which shows the assignment deliverables. Please provide a link to the arduino code used.

Components Required

Components Description Number
LEDs Output Display 9
Arduino Uno For Microcontroller Programming 1
Jumper Wires For making connections 20
Breadboard Base for connections 2
Push Buttons For code activation 2
Resistors For current limiting 9
Laptop Code Compilation and transfer 1

Basic Circuit Connections

Initially we tried to test the basic circuit using one LED and push button so that we will get a clear idea how to proceed.

assignment 3 arduino code

Connections were made according to the Diagrams shown below

assignment 3 arduino code

Credits: Edited the images from 'Elegoo Starter Kit for Uno'

This experiment was done successfully and we got the desired result. Output Video :

Arduino Code for the basic LED Blinking programming is here:

Arduino Code - LED Blinking

Performing the task

Initially arduino code was compiled and found to be error free.

Connections were made according to the below picture and tested it by uploading the code from arduino IDE

assignment 3 arduino code

Problems Faced

Initially for the Serial input program, we used IF-ELSE statement and it didn't work as expected. So on further exploration we came to know about the 'Switch-case' statement and used it for this program. It worked and also helped us in making the code very short and precise.

Switch statement is case sensitive and as of now we have only used Capital letters to reduce the code content. Cases for small letters can also be included to overcome the problem of case sensitivity.

Final Output

Output video for the assignment is recorded and edited using Kdenlive Video Editor (More details regarding the software is explained in Assignment 1 ) and uploaded in my Youtube Channel Amalkrishna P S

Video for first part of the assignment, ie 1) Name display with 9 LEDs using push buttons and 2) LED Blinking for 5 times is here:

Letter display with LEDs on Serial Input is uploaded here :

Here is the arduino code used for the program:

Arduino Code

© 2017 Free HTML5 Template. All Rights Reserved. Designed by FreeHTML5.co Demo Images: Unsplash

  • HARDWARE & TOOLS

Control Structure

  • switch...case

Further Syntax

  • /* */ (block comment)
  • {} (curly braces)
  • #define (define)
  • #include (include)
  • ; (semicolon)
  • // (single line comment)
  • unsigned char
  • unsigned int
  • unsigned long
  • Floating Point Constants
  • Integer Constants

Variable Scope & Qualifiers

  • digitalRead()
  • digitalWrite()
  • analogRead()
  • analogReference()
  • analogWrite()

Advanced IO

  • pulseInLong()
  • Serial.available()
  • Serial.availableForWrite()
  • Serial.begin()
  • Serial.end()
  • Serial.find()
  • Serial.findUntil()
  • Serial.flush()
  • Serial.getTimeout()
  • Serial.parseFloat()
  • Serial.parseInt()
  • Serial.peek()
  • Serial.print()
  • Serial.println()
  • Serial.read()
  • Serial.readBytes()
  • Serial.readBytesUntil()
  • Serial.readString()
  • Serial.readStringUntil()
  • serialEvent()
  • Serial.setTimeout()
  • Serial.write()
  • Stream.available()
  • Stream.find()
  • Stream.findUntil()
  • Stream.flush()
  • Stream.getTimeout()
  • Stream.parseFloat()
  • Stream.parseInt()
  • Stream.peek()
  • Stream.read()
  • Stream.readBytes()
  • Stream.readBytesUntil()
  • Stream.readString()
  • Stream.readStringUntil()
  • Stream.setTimeout()

String Functions

  • String.c_str()
  • String.charAt()
  • String.compareTo()
  • String.concat()
  • String.endsWith()
  • String.equals()
  • String.equalsIgnoreCase()
  • String.getBytes()
  • String.indexOf()
  • String.lastIndexOf()
  • String.length()
  • String.remove()
  • String.replace()
  • String.reserve()
  • String.setCharAt()
  • String.startsWith()
  • String.substring()
  • String.toCharArray()
  • String.toDouble()
  • String.toFloat()
  • String.toInt()
  • String.toLowerCase()
  • String.toUpperCase()
  • String.trim()

String Operators

  • String += (append)
  • String == (comparison)
  • String + (concatenation)
  • String != (different from)
  • String [] (element access)
  • String > (greater than)
  • String >= (greater than or equal to)
  • String < (less than)
  • String <= (less than or equal to)
  • Keyboard.begin()
  • Keyboard.end()
  • Keyboard Modifiers
  • Keyboard.press()
  • Keyboard.print()
  • Keyboard.println()
  • Keyboard.release()
  • Keyboard.releaseAll()
  • Keyboard.write()
  • Mouse.begin()
  • Mouse.click()
  • Mouse.end()
  • Mouse.isPressed()
  • Mouse.move()
  • Mouse.press()
  • Mouse.release()
  • delayMicroseconds()
  • constrain()
  • isAlphaNumeric()
  • isControl()
  • isHexadecimalDigit()
  • isLowerCase()
  • isPrintable()
  • isUpperCase()
  • isWhitespace()

Bits and Bytes

Arithmetic Operators

  • + (addition)
  • = (assignment operator)
  • / (division)
  • * (multiplication)
  • % (remainder)
  • - (subtraction)

Bitwise Operators

  • << (bitshift left)
  • >> (bitshift right)
  • & (bitwise and)
  • ~ (bitwise not)
  • | (bitwise or)
  • ^ (bitwise xor)

Boolean Operators

  • && (logical and)
  • ! (logical not)
  • || (logical or)

Comparison Operators

  • == (equal to)
  • > (greater than)
  • >= (greater than or equal to)
  • < (less than)
  • <= (less than or equal to)
  • != (not equal to)

Compound Operators

  • += (compound addition)
  • &= (compound bitwise and)
  • |= (compound bitwise or)
  • ^= (compound bitwise xor)
  • /= (compound division)
  • *= (compound multiplication)
  • %= (compound remainder)
  • -= (compound subtraction)
  • -- (decrement)
  • ++ (increment)
  • (unsigned int)
  • (unsigned long)

Random Numbers

  • randomSeed()

Trigonometry

External Interrupts

  • attachInterrupt()
  • detachInterrupt()
  • interrupts()
  • noInterrupts()

Pointer Access Operators

  • * (dereference operator)
  • & (reference operator)

Zero, Due, MKR Family

  • analogReadResolution()
  • analogWriteResolution()

assignment 3 arduino code

Description

The single equal sign = in the C++ programming language is called the assignment operator. It has a different meaning than in algebra class where it indicated an equation or equality. The assignment operator tells the microcontroller to evaluate whatever value or expression is on the right side of the equal sign, and store it in the variable to the left of the equal sign.

Example Code

※ NOTES AND WARNINGS:

  • The variable on the left side of the assignment operator ( = sign ) needs to be able to hold the value stored in it. If it is not large enough to hold a value, the value stored in the variable will be incorrect.
  • Don't confuse the assignment operator = (single equal sign) with the "equal to" comparison operator == (double equal signs):
  • = stores value to a variable.
  • == evaluates whether two expressions are equal or not.
  • Language : + (addition)
  • Language : / (division)
  • Language : * (multiplication)
  • Language : % (remainder)
  • Language : - (subtraction)
  • Language : if (conditional operators)
  • Language : char
  • Language : int
  • Language : long

※ ARDUINO BUY RECOMMENDATION

※ OUR MESSAGES

  • We are AVAILABLE for HIRE. See how to hire us to build your project

assignment 3 arduino code

  • Arduino-Overview
  • Arduino-Board-Description
  • Installation
  • Tinkar Simulation
  • Program Structure
  • Variables and Constants
  • Control Statements
  • Blinking LED
  • Reading Analog Voltage
  • Temperature Sensor
  • RC circuit data log
  • Reading Analog Voltage More than 5V
  • 7 Segment Display
  • Ultrasonic Sensor
  • LCD Display
  • LEDs control with Ultrasonic sensor
  • Circuit we cooked during class
  • Questions and Answers
  • Edit on GitHub
  • Arithmetic Operators
  • Comparison Operators
  • Boolean Operators
  • Bitwise Operators

Operators ¶

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators −

  • Compound Operators

Arithmetic Operators ¶

Operator name Operator simple Description Example
assignment operator = Stores the value to the right of the equal sign in the variable to the left of the equal sign. A = B
addition + Adds two operands A + B will give 30
subtraction - Subtracts second operand from the first A - B will give -10
multiplication * Multiply both operands A * B will give 200
division / Divide numerator by denominator B / A will give 2
modulo % Modulus Operator and remainder of after an integer division B % A will give 0

Example ¶

Result ¶, comparison operators ¶.

Assume variable A holds 10 and variable B holds 20 then

Operator name Operator simple Description Example
equal to == Checks if the value of two operands is equal or not, if yes then condition becomes true. (A == B) is not true
not equal to != Checks if the value of two operands is equal or not, if values are not equal then condition becomes true. (A != B) is true
less than < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true
greater than > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true
less than or equal to <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true
greater than or equal to >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true

Boolean Operators ¶

Assume variable A holds 10 and variable B holds 20 then −

Operator name Operator simple Description Example
and && Called Logical AND operator. If both the operands are non-zero then then condition becomes true. (A && B) is true
or || Called Logical OR Operator. If any of the two operands is non-zero then then condition becomes true. (A || B) is true
not ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false

Bitwise Operators ¶

Assume variable A holds 60 and variable B holds 13 then −

Operator name Operator simple Description Example
and & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
or | Binary OR Operator copies a bit if it exists in either operand (A | B) will give 61 which is 0011 1101
xor ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
not ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -60 which is 1100 0011
shift left << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
shift right >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111

Compound Operators ¶

Operator name Operator simple Description Example
increment ++ Increment operator, increases integer value by one A++ will give 11
decrement -- Decrement operator, decreases integer value by one A-- will give 9
compound addition += Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand B += A is equivalent to B = B+ A
compound subtraction -= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand B -= A is equivalent to B = B - A
compound multiplication *= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand B A
compound division /= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand B /= A is equivalent to B = B / A
compound modulo %= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand B %= A is equivalent to B = B % A
compound bitwise or |= bitwise inclusive OR and assignment operator A |= 2 is same as A = A | 2
compound bitwise and &= Bitwise AND assignment operator A &= 2 is same as A = A & 2

From here you can search these documents. Enter your search terms below.

Keyboard Shortcuts

Keys Action
Open this help
Next page
Previous page
Search

Arduino Tutorial

  • Arduino Tutorial
  • Arduino - Home
  • Arduino - Overview
  • Arduino - Board Description
  • Arduino - Installation
  • Arduino - Program Structure
  • Arduino - Data Types
  • Arduino - Variables & Constants
  • Arduino - Operators
  • Arduino - Control Statements
  • Arduino - Loops
  • Arduino - Functions
  • Arduino - Strings
  • Arduino - String Object
  • Arduino - Time
  • Arduino - Arrays
  • Arduino Function Libraries
  • Arduino - I/O Functions
  • Arduino - Advanced I/O Function
  • Arduino - Character Functions
  • Arduino - Math Library
  • Arduino - Trigonometric Functions
  • Arduino Advanced
  • Arduino - Due & Zero
  • Arduino - Pulse Width Modulation
  • Arduino - Random Numbers
  • Arduino - Interrupts
  • Arduino - Communication
  • Arduino - Inter Integrated Circuit
  • Arduino - Serial Peripheral Interface
  • Arduino Projects
  • Arduino - Blinking LED
  • Arduino - Fading LED
  • Arduino - Reading Analog Voltage
  • Arduino - LED Bar Graph
  • Arduino - Keyboard Logout
  • Arduino - Keyboard Message
  • Arduino - Mouse Button Control
  • Arduino - Keyboard Serial
  • Arduino Sensors
  • Arduino - Humidity Sensor
  • Arduino - Temperature Sensor
  • Arduino - Water Detector / Sensor
  • Arduino - PIR Sensor
  • Arduino - Ultrasonic Sensor
  • Arduino - Connecting Switch
  • Motor Control
  • Arduino - DC Motor
  • Arduino - Servo Motor
  • Arduino - Stepper Motor
  • Arduino And Sound
  • Arduino - Tone Library
  • Arduino - Wireless Communication
  • Arduino - Network Communication
  • Arduino Useful Resources
  • Arduino - Quick Guide
  • Arduino - Useful Resources
  • Arduino - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Arduino - Compound Operators

Assume variable A holds 10 and variable B holds 20 then −

Operator name Operator simple Description Example
increment ++ Increment operator, increases integer value by one A++ will give 11
decrement -- Decrement operator, decreases integer value by one A-- will give 9
compound addition += Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand B += A is equivalent to B = B+ A
compound subtraction -= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand B -= A is equivalent to B = B - A
compound multiplication *= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand B*= A is equivalent to B = B* A
compound division /= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand B /= A is equivalent to B = B / A
compound modulo %= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand B %= A is equivalent to B = B % A
compound bitwise or |= bitwise inclusive OR and assignment operator A |= 2 is same as A = A | 2
compound bitwise and &= Bitwise AND assignment operator A &= 2 is same as A = A & 2

pin assignments in code

I'm confused on pin assignments on the Nano.

There's the pins on the board itself and pins on the chip. The schematic shows board pin #'s that are the same, because there are two jacks.

There are examples of code that call out a pin by # and others that call it out by name.

myservo.attach(9) - is this pin 9 on the board (D6) or pin 9 on the chip (D5)? If I call out pin 9, how do I determine if it's the D6 pin or the A3 pin on the other header?

val=analogRead(A0) - does this indicate that the compiler knows that A0 is attached to the chip pin 23, and the board pin 12,

Would it be better to call out pins by name per the analog command, and let the compiler figure out what the pin# is or should I go by pin #'s on the chip, since there are duplicated pin #'s on the nano board itself?

This helped me. http://www.pighixxx.com/test/pinoutspg/boards/

Yes, it's almost always better to use the predefined constants, for portability between boards, as well as convenience. If you do that, all the mental machinations above will mostly disappear.

All references to the pin number in code are refer to the logical/arduino pin numbers. So 9 means the pin marked D9, physical pin 15 on the DIP version of the ATMega328p, physical pin 13 on the TQFP version.

The digital pin number, or the D# constant can be used interchangibly (they're just #defines - D9 is #defined to be 9, so the preprocessor searches for D9 and replaces them all with 9).

With analog pins, you use either the A# define, or you keep counting up from the last digital pin* (eg, on nano, last digital pin is 13; A0 is 14). For analogRead(), you can also use the number of the channel (eg, analogRead(0), analogRead(A0), and analogRead(14) do the same thing (though the last one will confuse a lot of the people who read it, so it's not good practice).

Physical pin numbers are never used when writing code, and frankly, almost never used when talking about the pins on microcontrollers period. As I noted above, for example, the physical pin numbers between the same chip in different packages are often different.

Sometimes pins are refered to like Pxn (where X is a letter and N is a number from 0~7, ex, arduino pin 9 is PB1) - these refer to the "port" and pin number within that port - this is relevant if doing direct port manipulation, or talking to people who don't use the Arduino IDE.

  • This is how it's done on all the official AVR-based cores (haven't looked at the SAM/ARM boards), and every third party AVR core I've seen, but an idiot could create a core where that convention wasn't followed.

Related Topics

Topic Replies Views Activity
Project Guidance 6 7232 May 5, 2021
Microcontrollers 6 4866 September 24, 2021
Programming Questions 16 12065 May 6, 2021
Programming Questions 2 23 July 25, 2024
Nano Every 4 2705 October 23, 2021

IMAGES

  1. Arduino code for assignment 3

    assignment 3 arduino code

  2. Schematic for assignment 3

    assignment 3 arduino code

  3. Assignment 3.2

    assignment 3 arduino code

  4. WEEK 5

    assignment 3 arduino code

  5. How to write Arduino code ?

    assignment 3 arduino code

  6. How to Code Arduinos Part 2 : 4 Steps

    assignment 3 arduino code

VIDEO

  1. Arduino PART3

  2. Уроки Arduino #1

  3. Arduino Uno R3 : Microcontroller programming Arduino projects #arduino #technology #viral

  4. 2024 Arduino LCD Assignment Description

  5. Arduino Nightlight Assignment Enes100

  6. Interfacing With Arduino: Week 2 Peer Assignment

COMMENTS

  1. Coursera-Interfacing-with-the-Arduino/Assignment 3.ino at master

    For example, if the user types "read 3" then the contents of EEPROM address 3 should be printed to the serial monitor. If the user types "write 3 10" then the value 10 should be written into address 3 of the EEPROM.

  2. Assignment #3

    Plug your arduino into the computer with the USB cable; Select Arduino/Genuino from the ports list; Copy and paste in your code from Assignment 1, Exercise 5 ("Hello World" + Timer in seconds) ... we want to reproduce Exercise 3 from Assignment #2. The circuit will be the same, but now run your code from Exercise 3.

  3. 12 Arduino Projects for Beginners

    Step 2: LED Blink. The "LED Blink" is for the Arduino the equivalent of the "Hello world" in computer programming, where you will need to write a code to have the sentence "Hello world" displayed in the console of a computer. Not really exciting, but it gives a hint on the inner workings of the Arduino board.

  4. Arduino Reference

    Arduino programming language can be divided in three main parts: functions, values (variables and constants), and structure. ... The elements of Arduino (C++) code. Sketch loop() setup() Control Structure break ... (assignment operator) Comparison Operators ...

  5. Arduino programming and syntax : A definitive guide for beginners

    What is the assignment operation? Operator: = It can assign the numbers on the right side to the variable on the left side of the operator. Syntax: variable = value2; Example. int a=5; int b=analogRead(3) //b has the sensor reading What are the different comparison functions in an Arduino program?

  6. Assignment 3

    Assignment 3 - Step Counting on an Arduino. You will recreate your step counter from Assignment 1 on an Arduino. Your algorithm can be the exact same as it was before (assuming it worked well), or you can completely change the algorithm. ... (50 points) We will briefly examine your code to ensure that you are using some form of signal ...

  7. DIY-Lab-Assignment-3-codes/Arduino code of Assignment3 Q1 at ...

    Saved searches Use saved searches to filter your results more quickly

  8. PDF 1 Introduction 2 Basic Variable Operations: De ne, Assign, and Recall

    The rst line in the preceding code declares sensorPin and sensorReading to be int variables. ... 2.1 The Assignment Operator The statement: x = 3; assigns the value 3 to the variable named x. The equals sign is the assignment operator. When the ... Arduino Due, int variables are 32 bit, meaning that their range

  9. Arduino Programming: Conditional Statements

    Experimenting With Arduino Arduino Programming: Conditional Statements Objectives and Overview This lesson introduces control flow and conditional statements. Additionally, this lesson includes examples of basic conditional statements and the role of assignment and comparison operators in programming. Lesson Objectives Understand and explain how conditional statements help programs make ...

  10. Arduino Reference

    The Arduino Reference text is licensed under a Creative Commons ... The assignment operator tells the microcontroller to evaluate whatever value or expression is on the right side of the equal sign, and store it in the variable to the left of the equal sign. Example Code. int sensVal; // declare an integer variable named sensVal sensVal ...

  11. Assignment 3

    3) Extra credit: Also, print the letter typed on the Serial Monitor using the 9 LEDs. This entire process has to be documented and a video has to be uploaded on your assignment webpage which shows the assignment deliverables. Please provide a link to the arduino code used. Components Required

  12. Arduino Assignment 3

    Arduino Assignment 3 - ardu3. University: University of California San Diego. Course: Experimental Techniques (MAE 170) 8 Documents. Students shared 8 documents in this course. AI Chat. Info More info. Download. AI Quiz. Save. 1 of 2 . Arduino Assignment 3 . Items marked with * are extra credit.

  13. Digital pin

    Well, I don't actually ever do it that way (or use assignment using = ) I just mentioned using decltype(A0) as it is portable vs pin_size_t which is not portable. For all the Arduino code I do, I use int for the Arduino pin const/constants and uint8_t for variable storage within the class to store Arduino pin numbers.

  14. = assignment operator

    The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License. The content is modified based on Official Arduino References by: adding more example codes and output, adding more notes and warning, rewriting some parts, and re-formating

  15. Operators

    Operators. An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators −. Arithmetic Operators. Comparison Operators. Boolean Operators. Bitwise Operators. Compound Operators.

  16. Arduino

    Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand. B*= A is equivalent to B = B* A. compound division. /=. Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand. B /= A is equivalent to B = B / A.

  17. pin assignments in code

    DrAzzy February 27, 2016, 2:04am 3. All references to the pin number in code are refer to the logical/arduino pin numbers. So 9 means the pin marked D9, physical pin 15 on the DIP version of the ATMega328p, physical pin 13 on the TQFP version. The digital pin number, or the D# constant can be used interchangibly (they're just #defines - D9 is # ...

  18. Assignment 3: Arduino Code In this assignment, you

    Question: Assignment 3: Arduino Code In this assignment, you get to practice writing applied C code against your Arduino. A note on collaboration -- it's totally fine (and encouraged) for you to work together with classmates /roommates /pets on the assignment. There is nothing wrong with sharing knowledge.

  19. Arduino code for assignment 3

    Download scientific diagram | Arduino code for assignment 3 from publication: Promoting Continuous Professional Development Among Academics from A Vocational College by Using A Practical Workshop ...

  20. = (assignment operator)

    The assignment operator tells the microcontroller to evaluate whatever value or expression is on the right side of the equal sign, and store it in the variable to the left of the equal sign. Example Code. Copy. 1 int sensVal; // declare an integer variable named sensVal. 2 ... The Arduino documentation is licensed under the Creative Commons ...