Turn an LED on and off every second.
This example shows the simplest thing you can do with an Arduino to see physical output: it blinks the on-board LED.
Arduino Board
optional
LED
220 ohm resistor
This example uses the built-in LED that most Arduino boards have. This LED is connected to a digital pin and its number may vary from board type to board type. To make your life easier, we have a constant that is specified in every board descriptor file. This constant is LED_BUILTIN and allows you to control the built-in LED easily. Here is the correspondence between the constant and the digital pin.
If you want to light an external LED with this sketch, you need to build this circuit, where you connect one end of the resistor to the digital pin correspondent to the LED_BUILTIN constant. Connect the long leg of the LED (the positive leg, called the anode) to the other end of the resistor. Connect the short leg of the LED (the negative leg, called the cathode) to the GND. In the diagram below we show an UNO board that has D13 as the LED_BUILTIN value.
The value of the resistor in series with the LED may be of a different value than 220 ohms; the LED will light up also with values up to 1K ohm.
After you build the circuit plug your Arduino board into your computer, start the Arduino Software (IDE) and enter the code below. You may also load it from the menu File/Examples/01.Basics/Blink . The first thing you do is to initialize LED_BUILTIN pin as an output pin with the line
pinMode(LED_BUILTIN, OUTPUT);
In the main loop, you turn the LED on with the line:
digitalWrite(LED_BUILTIN, HIGH);
This supplies 5 volts to the LED anode. That creates a voltage difference across the pins of the LED, and lights it up. Then you turn it off with the line:
digitalWrite(LED_BUILTIN, LOW);
That takes the LED_BUILTIN pin back to 0 volts, and turns the LED off. In between the on and the off, you want enough time for a person to see the change, so the
delay(100) commands tell the board to do nothing for 1000 milliseconds, or one second. When you use the delay(500) command, nothing else happens for that amount of time. Once you've understood the basic examples, check out the BlinkWithoutDelay example to learn how to create a delay while doing other things.
Once you've understood this example, check out the DigitalReadSerial example to learn how read a switch connected to the board
Pushbuttons or switches connect two points in a circuit when you press them. This example turns on the built-in LED on pin 13 when you press the button.
Arduino Board
Momentary button or Switch
10K ohm resistor
hook-up wires
breadboard
Connect three wires to the board. The first two, red and black, connect to the two long vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pull-down resistor (here 10K ohm) to ground. The other leg of the button connects to the 5 volt supply.
When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a LOW. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that we read a HIGH.
You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed. If so, the behavior of the sketch will be reversed, with the LED normally on and turning off when you press the button.
If you disconnect the digital I/O pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's why you need a pull-up or pull-down resistor in the circuit.
/*
Button
Turns on and off a light emitting diode(LED) connected to digital pin 13,
when pressing a pushbutton attached to pin 2.
The circuit:
- LED attached from pin 13 to ground through 220 ohm resistor
- pushbutton attached to pin 2 from +5V
- 10K resistor attached to pin 2 from ground
- Note: on most Arduinos there is already an LED on the board
attached to pin 13.
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
The DHT11 is a basic, ultra low-cost digital temperature and humidity sensor. It uses a capacitive humidity sensor and a thermistor to measure the surrounding air and spits out a digital signal on the data pin (no analog input pins needed). It's fairly simple to use but requires careful timing to grab data.
DHT11 Library install
Details about the code
You need to follow these instructions to make it work:
1. You need to add the library to the Arduino IDE.
2. Upload the code.
3. When the code is uploaded, open the Serial Monitor and set the baud rate to 9600.
4. You will see the humidity and temperature.
Code
#include <dht11.h>
#define DHT11PIN 4
dht11 DHT11;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println();
int chk = DHT11.read(DHT11PIN);
Serial.print("Humidity (%): ");
Serial.println((float)DHT11.humidity, 2);
Serial.print("Temperature (C): ");
Serial.println((float)DHT11.temperature, 2);
delay(2000);
}
Circuit
My sensor has 3 pins and it's fitted on a board. If yours has 4 pins, then you need to build this circuit after the sensor. Use resister 4k ohm.
The DS18B20 is a digital temperature sensor manufactured by Maxim Integrated. It is a small, waterproof, and cost-effective temperature sensing device that can measure temperature in a range of -55°C to +125°C with a high accuracy of ±0.5°C. It uses a 1-Wire interface, which means it requires only one pin for both power and data transfer, making it ideal for use in space-constrained systems like those in an automotive or home automation environment. The DS18B20 communicates over a 1-Wire bus that by definition requires only one data line (and ground) to communicate with a central microprocessor.
#include <OneWire.h>
#include <DallasTemperature.h>
Declare OneWire and DallasTemperature object corresponding to the pin connected to sensor's DATA pin
OneWire oneWire(SENSOR_PIN); // setup a oneWire instance DallasTemperature sensors(&oneWire); // pass oneWire to DallasTemperature library
Initialize the sensor:
sensors.begin(); // initialize the sensor
Send the command to get temperatures:
sensors.requestTemperatures();
Read temperature in Celsius:
tempCelsius = sensors.getTempCByIndex(0);
(Optional) Convert Celsius to Fahrenheit:
tempFahrenheit = tempCelsius * 9 / 5 + 32;
#include <OneWire.h>
#include <DallasTemperature.h>
const int SENSOR_PIN = 13;
// Arduino pin connected to DS18B20 sensor's DQ pin
OneWire oneWire(SENSOR_PIN);
// setup a oneWire instance DallasTemperature tempSensor(&oneWire); // pass oneWire to DallasTemperature library float tempCelsius;
// temperature in Celsius float tempFahrenheit;
// temperature in Fahrenheit
void setup() {
Serial.begin(9600); // initialize serial
tempSensor.begin(); // initialize the sensor
}
void loop() {
tempSensor.requestTemperatures();
// send the command to get temperatures tempCelsius = tempSensor.getTempCByIndex(0);
// read temperature in Celsius tempFahrenheit = tempCelsius * 9 / 5 + 32;
// convert Celsius to Fahrenheit
Serial.print("Temperature: ");
Serial.print(tempCelsius); // print the temperature in Celsius Serial.print("°C");
Serial.print(" ~ "); // separator between Celsius and Fahrenheit Serial.print(tempFahrenheit); // print the temperature in Fahrenheit Serial.println("°F");
delay(500);
}
The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object just like the bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package from 2 cm to 400 cm or 1” to 13 feet.
The operation is not affected by sunlight or black material, although acoustically, soft materials like cloth can be difficult to detect. It comes complete with ultrasonic transmitter and receiver module.
Power Supply − +5V DC
Quiescent Current − <2mA
Working Current − 15mA
Effectual Angle − <15°
Ranging Distance − 2cm – 400 cm/1″ – 13ft
Resolution − 0.3 cm
Measuring Angle − 30 degree
code
const int trigPin = 12;
const int echoPin = 14;
//define sound velocity in cm/uS
#define SOUND_VELOCITY 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
delay(200);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_VELOCITY/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance on the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
delay(1000);
}
Tinkercad's Arduino simulator allows you to create and test Arduino circuits and code without needing any physical hardware. This can be a great way to learn the basics of Arduino programming and electronics, or to prototype new ideas before building them in the real world.