1.Basic_Programing
1.Basic_Programing
By turning the shaft of the potentiometer, you change the amount of resistance on either
side of the wiper, which is connected to the center pin of the potentiometer. This changes
the voltage at the center pin. When the resistance between the center and the side connected
to 5 volts is close to zero (and the resistance on the other side is close to 10k ohm), the
voltage at the center pin nears 5 volts. When the resistances are reversed, the voltage at the
center pin nears 0 volts, or ground. This voltage is the analog voltage that you're reading as
an input.
The Arduino boards have a circuit inside called an analog-to-digital converter or ADC that
reads this changing voltage and converts it to a number between 0 and 1023. When the
shaft is turned all the way in one direction, there are 0 volts going to the pin, and the input
value is 0. When the shaft is turned all the way in the opposite direction, there are 5 volts
going to the pin and the input value is 1023. In between, analogRead() returns a number
between 0 and 1023 that is proportional to the amount of voltage being applied to the pin.
Schematic
Code
In the sketch below, the only thing that you do in the setup function is to begin serial
communications, at 9600 bits of data per second, between your board and your computer
with the command:
Serial.begin(9600);
Next, in the main loop of your code, you need to establish a variable to store the resistance
value (which will be between 0 and 1023, perfect for an Int datatype) coming in from your
potentiometer:
int sensorValue = analogRead(A0);
Finally, you need to print this information to your serial monitor window. You can do this
with the command Serial.println() in your last line of code:
Serial.println(sensorValue);
Now, when you open your Serial Monitor in the Arduino Software (IDE) (by clicking the
icon that looks like a lens, on the right, in the green top bar or using the keyboard shortcut
Ctrl+Shift+M), you should see a steady stream of numbers ranging from 0-1023,
correlating to the position of the pot. As you turn your potentiometer, these numbers will
respond almost instantly.
/*
AnalogReadSerial
Reads an analog input on pin 0, prints the result to the Serial Monitor.
Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and
ground.
This example code is in the public domain.
https://www.arduino.cc/en/Tutorial/BuiltInExamples/AnalogReadSerial
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
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 5V supply.
Pushbuttons or switches connect two points in a circuit when you press them. 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 reads as
LOW, or 0. When the button is closed (pressed), it makes a connection between its two
legs, connecting the pin to 5 volts, so that the pin reads as HIGH, or 1.
If you disconnect the digital i/o pin from everything, its reading may change erratically.
This is because the input is "floating" - that is, it doesn't have a solid connection to voltage
or ground, and it will randomly return either HIGH or LOW. That's why you need a pull-
down resistor in the circuit.
Schematic
Code
In the program below, the very first thing that you do will in the setup function is to begin
serial communications, at 9600 bits of data per second, between your board and your
computer with the line:
Serial.begin(9600);
Next, initialize digital pin 2, the pin that will read the output from your button, as an input:
pinMode(2,INPUT);
Now that your setup has been completed, move into the main loop of your code. When your
button is pressed, 5 volts will freely flow through your circuit, and when it is not pressed,
the input pin will be connected to ground through the 10k ohm resistor. This is a digital
input, meaning that the switch can only be in either an on state (seen by your Arduino as a
"1", or HIGH) or an off state (seen by your Arduino as a "0", or LOW), with nothing in
between.
The first thing you need to do in the main loop of your program is to establish a variable to
hold the information coming in from your switch. Since the information coming in from the
switch will be either a "1" or a "0", you can use an
int
datatype. Call this variable
sensorValue
, and set it to equal whatever is being read on digital pin 2. You can accomplish all this with
just one line of code:
int sensorValue = digitalRead(2);
Once the board has read the input, make it print this information back to the computer as a
decimal value. You can do this with the command Serial.println() in our last line of code:
Serial.println(sensorValue);
Now, when you open your Serial Monitor in the Arduino Software (IDE), you will see a
stream of "0"s if your switch is open, or "1"s if your switch is closed.
B. DigitalReadSerial
Reads a digital input on pin 2, prints the result to the Serial Monitor
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
Schematic
Code
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()
commands tell the board to do nothing for 1000 milliseconds, or one second. When you use
the
delay()
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.
B. Turns an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO it is
attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to the correct LED
pin independent of which board is used. If you want to know what pin the on-board LED is
connected to on your Arduino model, check the Technical Specs of your board at:
https://www.arduino.cc/en/Main/Products
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
Schematic
Code
After declaring pin 9 to be your ledPin, there is nothing to do in the setup() function of your
code.
The analogWrite() function that you will be using in the main loop of your code requires
two arguments: One telling the function which pin to write to, and one indicating what
PWM value to write.
In order to fade your LED off and on, gradually increase your PWM value from 0 (all the
way off) to 255 (all the way on), and then back to 0 once again to complete the cycle. In the
sketch below, the PWM value is set using a variable called brightness. Each time through
the loop, it increases by the value of the variable fadeAmount.
If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed
to its negative. In other words, if fadeAmount is 5, then it is set to -5. If it's -5, then it's set
to 5. The next time through the loop, this change causes brightness to change direction as
well.
analogWrite() can change the PWM value very fast, so the delay at the end of the sketch
controls the speed of the fade. Try changing the value of the delay and see how it changes
the fading effect.
This example shows how to fade an LED on pin 9 using the analogWrite() function.
The analogWrite() function uses PWM, so if you want to change the pin you're using, be
sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with
a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
READ ANALOG VOLTAGE
This example shows you how to read an analog input on analog pin 0, convert the values
from analogRead() into voltage, and print it out to the serial monitor of the Arduino
Software (IDE).
Hardware Required
Arduino Board
10k ohm potentiometer
Circuit
Connect the three wires from the potentiometer to your board. The first goes to ground
from one of the outer pins of the potentiometer. The second goes to 5 volts from the other
outer pin of the potentiometer. The third goes from the middle pin of the potentiometer to
analog input 0.
By turning the shaft of the potentiometer, you change the amount of resistance on either
side of the wiper which is connected to the center pin of the potentiometer. This changes
the voltage at the center pin. When the resistance between the center and the side connected
to 5 volts is close to zero (and the resistance on the other side is close to 10 kilohms), the
voltage at the center pin nears 5 volts. When the resistances are reversed, the voltage at the
center pin nears 0 volts, or ground. This voltage is the analog voltage that you're reading as
an input.
The microcontroller of the board has a circuit inside called an analog-to-digital
converter or ADC that reads this changing voltage and converts it to a number between 0
and 1023. When the shaft is turned all the way in one direction, there are 0 volts going to
the pin, and the input value is 0. When the shaft is turned all the way in the opposite
direction, there are 5 volts going to the pin and the input value is 1023. In
between, analogRead() returns a number between 0 and 1023 that is proportional to the
amount of voltage being applied to the pin.
Schematic
Code
In the program below, the very first thing you'll do will be in the setup function, to begin
serial communication at 9600 bits of data per second, between your board and your
computer with the line:
Serial.begin(9600);
Next, in the main loop of your code, you need to establish a variable to store the resistance
value (which will be between 0 and 1023, perfect for an intdatatype) coming in from your
potentiometer:
int sensorValue = analogRead(A0);
To change the values from 0-1023 to a range that corresponds to the voltage the pin is
reading, you'll need to create another variable, a float, and do a little math. To scale the
numbers between 0.0 and 5.0, divide 5.0 by 1023.0 and multiply that by sensorValue :
float voltage= sensorValue * (5.0 / 1023.0);
Finally, you need to print this information to your serial monitor. You can do this with the
command Serial.println() in your last line of code:
Serial.println(voltage)
Now, when you open your Serial Monitor in the Arduino IDE (by clicking on the icon on
the right side of the top green bar or pressing Ctrl+Shift+M), you should see a steady
stream of numbers ranging from 0.0 - 5.0. As you turn the pot, the values will change,
corresponding to the voltage coming into pin A0.
/ ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result to the
Serial Monitor.
Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and
ground.
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
HOW TO WIRE AND PROGRAM A BUTTON
Learn how to wire and program a pushbutton to control an LED.
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.
Hardware
Arduino Board
Momentary button or Switch
10K ohm resistor
hook-up wires
breadboard
Circuit
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.
Schematic
Code
/*
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
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
Connect one pin from your pot to 5V, the center pin to analog pin 0 and the remaining pin
to ground. Next, connect a 220 ohm current limiting resistor to digital pin 9, with an LED
in series. The long, positive leg (the anode) of the LED should be connected to the output
from the resistor, with the shorter, negative leg (the cathode) connected to ground.
Schematic
Code
In the sketch below, after declaring two pin assignments (analog 0 for our potentiometer
and digital 9 for your LED) and two variables, sensorValue and outputValue, the only
things that you do in the setup() function is to begin serial communication.
Next, in the main loop, sensorValue is assigned to store the raw analog value read from the
potentiometer. Arduino has an analogRead range from 0 to 1023, and an analogWrite range
only from 0 to 255, therefore the data from the potentiometer needs to be converted to fit
into the smaller range before using it to dim the LED.
// These constants won't change. They're used to give names to the pins used:
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to
int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
// change the analog out value:
analogWrite(analogOutPin, outputValue);
// print the results to the Serial Monitor:
Serial.print("sensor = ");
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
// wait 2 milliseconds before the next loop for the analog-to-digital
// converter to settle after the last reading:
delay(2);
}