4. Intro to the Arduino (1)
4. Intro to the Arduino (1)
https://www.arduino.cc/en/Products/Compare
https://www.arrow.com/en/research-and-
events/articles/choose-the-perfect-arduino-board-for-your-
next-project
Getting Started
• Check out: http://arduino.cc/en/Guide/HomePage
• Arduino microcontrollers are programmed using the Arduino
IDE (Integrated Development Environment)
• Can be downloaded for free from
http://arduino.cc/en/Main/Software
1. Download & install the Arduino environment (IDE)
2. Connect the Arduino board to your computer via the USB cable
3. If needed, install the drivers
4. Launch the Arduino IDE
5. Select your board
6. Select your serial port
7. Open the sketch (program)
8. Upload the program
Select Serial Port and Board
Parts of the IDE main screen
Name of current sketch
Main menus
Action buttons/icons
1
• Digital IO is binary valued—
it’s either on or off, 1 or 0
• Internally, all 0
www.mikroe.com/chapters/view/1
pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT
digitalRead(pin)
Reads HIGH or LOW from a pin
digitalWrite(pin, value)
Writes HIGH or LOW to a pin
Electronic stuff
Output pins can provide 40 mA of current
Writing HIGH to an input pin installs a 20KΩ pullup
PinMode
• A pin on arduino can be set as input or output by using pinMode
function.
pin
5V source
10kΩ
560Ω
10kΩ
Pulldown resistor
Controlling LED by pushbutton
• void setup()
• {
• pinMode(12, OUTPUT);
• pinMode(7,INPUT);
• }
• void loop()
• {
/*When the BUTTON is pressed, x will
• int x=digitalRead(7); //read pin 7 as HIGH or LOW
have a value 1; and when not pressed
•
value will be 0. */
• if(x==HIGH)
• digitalWrite(12,HIGH); /*When x is 1, pin 12 will be given 5V.
• else When x is 0, pin 12 will be given 0V.
• digitalWrite(12,LOW); */
• }
Controlling LED by pushbutton (Alternative)
• int ButtonState; //When the LED is ON its state will be 1 otherwise 0.
• void setup()
• {
• pinMode(12, OUTPUT);
/*When a BUTTON is pressed, the LED will
• pinMode(7,INPUT); be turned on. When another press is
• ButtonState=0; //initialize state to be 0 detected it will be turned off.
• }
• void loop()
• {
• int x=digitalRead(7); //read pin 7 as HIGH or LOW
•
• if(x==HIGH && ButtonState==0 ) // If the button is pressed and it is at OFF position turn it ON
• { digitalWrite(12,HIGH); delay(100); ButtonState=1; }
• else if (x==HIGH && ButtonState==1)
• {digitalWrite(12,LOW); delay(100); ButtonState=0; }
• }
Controlling Multiple LEDs
Controlling Multiple LEDs (pushbutton to start)
int x; void loop()
int ledArray[]={10,11,12,13};//keep led pin names in an array {
x=digitalRead(8);
void setup()
{ if(x==HIGH)
pinMode(8, INPUT); {
pinMode(ledArray[0], OUTPUT); while(1)
pinMode(ledArray[1], OUTPUT); {
pinMode(ledArray[2], OUTPUT); for(int i=0;i<4;i++)
pinMode(ledArray[3], OUTPUT); {
x=0; digitalWrite(ledArray[i], HIGH);
} delay(100);
}
for(int i=3;i>=0;i--)
{
digitalWrite(ledArray[i], LOW);
delay(100);
}
}
}
}
Controlling Multiple LEDs (pushbutton to start and stop)
int LEDarray[]={9, 10, 11, 12}; void loop()
int i; {
int Bstate=0; int x=digitalRead(8);
void setup() if(x==HIGH && Bstate==0)
{ {
Bstate=1;
while(1)
pinMode(8, INPUT); {
for( i=0;i<4;i++) for(i=0;i<4;i++)
{ { digitalWrite(LEDarray[i], HIGH); delay(100); }
pinMode(LEDarray[i], OUTPUT); for(i=3;i>=0;i--)
} { digitalWrite(LEDarray[i], LOW); delay(100); }
if(digitalRead(8)==HIGH )
} {
Bstate=0;delay(100);break;
}
}
}
}
Arduino Interrupts
• In some cases like the example shown on the previous slide, because
of the delays, information that should be received from some sensors
are missed on real time events.
• In order to prevent this (missing real time sensory information),
Arduino boards can give priority to some pins. This is called
interruption, which pauses all other operations when information
comes to the prioritized pins, and continues to the paused process
after completing the prioritized action.
Arduino Interrupts
• Instead of just watching that pin all the time (by reading the pin at
each iteration), Arduino can farm the work of monitoring that pin to
an Interrupt, and free up loop() to do whatever is necessary to be
done in the meantime!
• The function attachInterrupt() employs the interruption process on
Arduino with three arguments:
• 1. The interrupt number,
• 2. The function name of the interrupt service routine,
• 3. The interrupt mode
Arduino Interrupts
attachInterrupt(The interrupt number, The function name , The interrupt mode)
• 1. The interrupt number, determines what pin can generate an interrupt. This isn't the number of the pin itself, but it's
actually a reference to where in memory the Arduino processor has to look to see if an interrupt occurs. A given space in
that vector corresponds to a specific external pin, and not all pins can generate an interrupt! On the Arduino Uno, pins 2
and 3 are capable of generating interrupts, and they correspond to interrupt vectors 0 and 1, respectively. You can see a
list of what pins are available as interrupt pins, on different Arduino boards.
BOARD DIGITAL PINS USABLE FOR INTERRUPTS
Uno, Nano, Mini, other 328-based 2, 3
Uno WiFi Rev.2, Nano Every all digital pins
Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based 0, 1, 2, 3, 7
Zero all digital pins, except 4
MKR Family boards 0, 1, 4, 5, 6, 7, 8, 9, A1, A2
Nano 33 IoT 2, 3, 9, 10, 11, 13, 15, A5, A7
Nano 33 BLE, Nano 33 BLE Sense all pins
Due all digital pins
all digital pins (Only pins 2, 5, 7, 8, 10,
101
11, 12, 13 work with CHANGE)
Arduino Interrupts
attachInterrupt(The interrupt number, The function name , The interrupt mode)
void ChangeState() {
Bstate = !Bstate;
}
What is analog ?
It is continuous range of voltage values (not just 0 or 5V)
This reads the voltage on pin A0 and puts it into a variable called val.
val can range from 0 to 1023. If you need a different value, like for an LED
(which takes values from 0 to 255.):
map takes the value of val and converts to the new range of values from 0
to 255.
Pulse-Width Modulation (PWM)
• The Fading example demonstrates the use of analog output (PWM) to fade
an LED. It is available in the File->Sketchbook->Examples->Analog menu of
the Arduino software.
• Pulse Width Modulation, or PWM, is a technique for getting analog results
with digital means.
• Digital control is used to create a square wave, a signal switched between on
and off. This on-off pattern can simulate voltages in between full on (5 Volts)
and off (0 Volts) by changing the portion of the time the signal spends on
versus the time that the signal spends off.
Pulse-Width Modulation (PWM)(Cont.)
• The duration of "on time" is called the pulse width. To get varying
analog values, you change, or modulate, that pulse width. If you
repeat this on-off pattern fast enough with an LED for example, the
result is as if the signal is a steady voltage between 0 and 5v
controlling the brightness of the LED.
Pulse-Width Modulation (PWM)(Cont.)
• In the graphic in next slide, the green lines represent a regular time
period. This duration or period is the inverse of the PWM frequency.
In other words, with Arduino's PWM frequency at about 500Hz, the
green lines would measure 2 milliseconds each.
• A call to analogWrite() is on a scale of 0 - 255, such that
analogWrite(255) requests a 100% duty cycle (always on), and
analogWrite(127) is a 50% duty cycle (on half the time) for example.
Pulse-Width Modulation (PWM)(Cont.)
PWM instruction example
Sets the output to the LED proportional to the value read
from the potentiometer.
void setup()
{
pinMode(ledPin,OUTPUT);
pinMode(analogPin,INPUT);
}
BOARD USB CDC NAME SERIAL PINS SERIAL1 PINS SERIAL2 PINS SERIAL3 PINS
Leonardo, Micro,
Serial 0(RX), 1(TX)
Yún
SerialUSB (Native
Due 0(RX), 1(TX) 19(RX), 18(TX) 17(RX), 16(TX) 15(RX), 14(TX)
USB Port only)
• You can use the Arduino environment’s built-in serial monitor to communicate with an Arduino board. Click
the serial monitor button in the toolbar and select the same baud rate used in the call to begin().
• Serial communication on pins TX/RX uses TTL logic levels (5V or 3.3V depending on the board). Don’t
connect these pins directly to an RS232 serial port; they operate at +/- 12V and can damage your Arduino
board.
• To use these extra serial ports to communicate with your personal computer, you will need an additional
USB-to-serial adaptor, as they are not connected to the Mega’s USB-to-serial adaptor. To use them to
communicate with an external TTL serial device, connect the TX pin to your device’s RX pin, the RX to your
device’s TX pin, and the ground of your Mega to your device’s ground.
Some of the Serial Functions (Serial.function_name)
• if(Serial): • findUntil(): • println():
• Indicates if the specified Serial port is ready. • Reads data from the serial buffer until a • Prints data to the serial port as human-readable ASCII text
target string of given length or followed by a carriage return character and a newline character
• available(): terminator string is found. The function
returns true if the target string is found, • read():
• Get the number of bytes (characters) available false if it times out. • Reads incoming serial data.
for reading from the serial port. This is data
that’s already arrived and stored in the serial • flush(): • readBytes():
receive buffer (which holds 64 bytes). • Waits for the transmission of • Returns the number of characters placed in the buffer. A 0
means no valid data was found.
outgoing serial data to
• begin(): complete. • Syntax: Serial.readBytes(buffer, length)
• Sets the data rate in bits per second (baud) for • readBytesUntil():
serial data transmission. • parseFloat(): • Reads characters from the serial buffer into an array.
• Returns the first valid floating • Syntax: Serial.readBytesUntil(character, buffer, length)
• end(): point number from the Serial
• Disables serial communication, allowing the RX and buffer. • readString():
TX pins to be used for general input and output. • Reads characters from the serial buffer into a String.
• parseInt():
• find(): • Looks for the next valid integer • setTimeout():
in the incoming serial. • Sets the maximum milliseconds to wait for serial data. It
• Serial.find() reads data from the serial buffer until defaults to 1000 milliseconds.
the target is found. The function returns true if target
is found, false if it times out.
• print(): • Syntax: Serial.setTimeout(time)
• Prints data to the serial port as • write():
• Syntax: human-readable ASCII text. This
• Serial.find(target) OR command can take many forms. • Writes binary data to the serial port. This data is sent as a byte
or series of bytes; to send the characters representing the digits
• Serial.find(target, length) Numbers are printed using an ASCII of a number use the print() function instead.
character for each digit. Floats are
similarly printed as ASCII digits,
defaulting to two decimal places.
Bytes are sent as a single character.
Characters and strings are sent as is.
Serial Monitoring Example
(Brightness of the LED is entered by user)
const int ledPin = 3; // the pin that the LED is attached to
void setup() {
// initialize the serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
}
int brightness=0;
void loop() {
for(int i=0;i<4;i++)
pinMode(dataPin[i], OUTPUT);
Note that the servo has a plug attached to its ribbon cable. This is so that we can more
easily extend the cable using plugs and more ribbon cable. It also allows it to plug into
specific plugs built into some shields. Several companies make a few different Motor
Shields, which are shields specifically designed to drive servos, motors, and stepper
motors. These usually support 2 to 4 motors, although Adafruit has one that will
control 16. They generally have plugs built into the shield for the motors and often
drive them through some sort of a serial connection (I2C or SPI is common).