0% found this document useful (0 votes)
19 views28 pages

Arduino E1

Uploaded by

Janek Pawlak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views28 pages

Arduino E1

Uploaded by

Janek Pawlak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Prototyping Methods for HCI

------------------------------------------------------------------
Designing and implementing prototypes using
software and microprocessor platforms.
Task_0:
Load example Blink.

1)Programming basics - I/O ports

LED

The most basic feedback information (output signal) that we can


receive from an Arduino board is a change in the state of an LED.
LEDs and most peripherals (such as buzzers or vibrating motors)
should be connected to a resistor in series to limit the current
flowing through them. The value of the resistor should be selected
according to the technical documentation of the chosen model and
color of the LED, based on Ohm's law and the voltage distribution
in a series connection.

However, it is not necessary to perform calculations every time.


When using standard LEDs in practical applications, it is possible
to use resistors in the range of 100Ω - 330Ω. This is due to the
tolerance of each electronic component (usually 5-10%) - both the
resistor and the LED. It should be remembered that connecting
without a resistor or using smaller values can cause the LED to
burn out, while larger values can cause the brightness of the
light to dim.
The above example shows a static connection of an LED to the power
supply (Arduino output 5V and GND). In order to be able to control
the condition or frequency of LED lighting, a digital pin must be
used.

Output signal - LED control

To inform Arduino that a connected element is to be treated as an


output, it is necessary to use the pinMode function to assign one
of the 3 modes (INPUT, OUTPUT, INPUT_PULLUP) to the selected pin.
If we are using a pin to control an output, we should use the
OUTPUT mode, which allows us to change the logical state using the
digitalWrite function, which sets the selected pin to either a
high or low state (HIGH or LOW).

To enable control of the LED state, we need to use a digital pin


(there are 14 available on the Arduino board). In this case, we
will use pin 9, connecting the LED according to the following
diagram.
When writing code, we can use the Blink example and modify it to
use our selected pin number (as shown in the code below) to
control the LED connected to that pin.

Code_1:
void setup() {
pinMode(9, OUTPUT); // Configure pin 9 as an output
}

void loop() {
digitalWrite(9, HIGH); // Turn on the LED
delay(1000); // Wait for 1 second
digitalWrite(9, LOW); // Turn off the LED
delay(1000); // Wait for 1 second
}

The code above uses the delay function to introduce a delay. This
function takes a single argument, which specifies the number of
milliseconds to wait before continuing.

In the example code above, delay(1000) is used to pause the


program for 1 second between turning the LED on and off. This
delay is necessary to ensure that the blinking effect is visible
to the human eye.

It's worth noting that the use of the delay function can sometimes
cause problems in more complex programs. This is because delay
pauses the entire program, preventing it from doing anything else
during the pause.

Task_1:
You need to connect the LED and test different delays between
state changes.

Buzzer - sound generator

https://wiki.dfrobot.com/Digital_Buzzer_Module__SKU__DFR0032_

Another option for using the output signal is for an audio signal.
The simplest solution is to use a buzzer from a ready-made
solution such as DFrobot (on the left) or by connecting a generic
buzzer in series with a resistor (on the right).

Task_2:
Test code_1 in the variant with a buzzer connected.
If a sound output signal is used, it is possible to play music
notes by modulating the signal accordingly. However, creating a
library containing all the notes would be very time-consuming.
Built-in examples come to the rescue in this case.

To play a melody, go to File ⟶ Examples ⟶ 02.Digital ⟶ toneMelody.

We can see that in this case, the code consists of two files: the
main one - toneMelody and a library created specifically for this
code - pitches.h.
The main code contains the
➔ implementation of two arrays:
◆ melody[] containing the corresponding notes (note
positions on a staff) and
◆ noteDurations[] containing the duration values of the
notes (note types).
➔ A for loop is executed only once (to hear the melody again,
the code must be uploaded again or the reset button on the
Arduino board must be pressed directly) by converting the
length of the note into values in seconds and retrieving the
notes from the library using the command melody[thisNote].

To play the melody in a loop, move the for loop from void setup()
to void loop().

Task_3:
Test the example and prepare a melody in the way that suits you
(also check the code with a melody from the internet, e.g.
https://github.com/robsoncouto/arduino-songs/blob/master/supermari
obros/supermariobros.ino). However, pay attention to the pin
number assigned to the buzzer.

Input signal - obtaining information from a button

The codes presented above unconditionally sent an output signal,


but often we want the programmed circuit to react to an external
signal. The simplest information we can send is a high or low
state generated by pressing a button.

To do this, follow the example below. One side of the button is


connected to ground (negative), the other to pin 7.

To use the pin connected to the button, we want to assign the


INPUT type. However, if we want to use the button without
connecting it to a voltage, but only by detecting the circuit
closing, we use INPUT_PULLUP, which means turning on the internal
pull-up resistor.

void setup() {
pinMode(8, OUTPUT); //LED as output
pinMode(5, INPUT_PULLUP); //Button as input with internal pull-up resistor
digitalWrite(8, LOW); //Turn off the LED
}

void loop()
{
if (digitalRead(5) == LOW) { //If the button is pressed
digitalWrite(8, HIGH); //Turn on the LED
} else { //If the condition is not met (button is not pressed)
digitalWrite(8, LOW); //Turn off the LED
}
}

Task_4:
Testing the above connection along with the code.
2)UART

What is UART? It is a type of communication that is based on the


serial transmission of a sequence of bits, which are then
assembled into information.

UART communication uses two pins: pin 1 - Tx (Transmit) and pin 2


- Rx (Receive). Due to the lack of a synchronizing pin in both
devices, the same baud rate must be set, which is defined as the
number of bits transmitted per second.

This type of transmission is also used to establish a connection


between a microcontroller and a computer for programming, and
later for sending and receiving data or commands. Thanks to the
built-in converter on the Arduino UNO board, connectivity through
USB is possible without using pins 0 and 1.

As previously mentioned, UART is used not only to transmit the


program but also to interact with the controller during the code
execution. To do this, you need to open the serial port monitor
(which can be done in two ways).

Display in Serial Monitor

void setup(){
Serial.begin(9600); //Ustawienie prędkości transmisji
Serial.println("Start programu"); //Jednorazowe wysłanie tekstu
}
void loop() {
delay(1000);
Serial.println("minęła sekunda"); //Wysyłanie w pętli
}
Receiving data in the Serial Monitor

String odebraneDane = ""; //Pusty ciąg odebranych danych

void setup() {
Serial.begin(9600); //Uruchomienie komunikacji
}

void loop() {
if(Serial.available() > 0) { //Czy Arduino odebrało dane
odebraneDane = Serial.readStringUntil('\n'); //Jeśli tak, to odczytaj je do znaku
końca linii i zapisz w zmiennej odebraneDane
Serial.println("Witaj " + odebraneDane + "!"); //Wyświetl komunikat
}
}

Task_5:
Write code that on "start" will start incrementing the variable,
while on "stop" it will display it, and then reset it to be ready
for the repeated operation.

Displaying Data in Serial Plotter

Multiple plots in Serial Plotter

Serial.print(Wartosc1);
Serial.print("\t"); // Znak tabulatora
Serial.print(Wartosc2);
Serial.print("\t"); // Znak tabulatora
Serial.print(Wartosc3);
Serial.print("\t"); // Znak tabulatora
Serial.print(Wartosc4);
Serial.println(""); // Przejście do nowej linii
#define

#define ledPin 8

void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}

3)Analog values

Arduino pins signals can be divided into two types - digital and
analog. This means that the data transmitted and received can be
in the form of low and high states (0 - 0V or 1 - 5V) or
intermediate values ranging from 0 - 5V.

Voltage measurement, i.e. the conversion of an analog signal, is


performed by a 10-bit ADC (Analog-Digital Converter). This means
that we can read values from 0 to 1023 for a voltage range of 0 to
5V.

Among the available sensors and elements that use analog pins, we
can distinguish two types - elements based on resistance change
that require the use of a voltage divider (such as a
photoresistor), and ready-made modules that properly process the
signal and provide an analog value (such as a microphone).
Reading analog values from a voltage divider can also serve as
user input in the form of changes in the position of a
potentiometer.

Below are two possible connection options. Of course, there are


more possibilities, and you do not have to limit yourself to the
presented connections. The most important thing is the beginning
and end of the circuit, which may also depend on other elements on
the board.

To read the current value from the potentiometer, the following


code should be used, which translates the voltage value available
in the Arduino (0V - 5V) into numerical values ​consistent with the
ADC resolution on the microcontroller (0-1023).

int potPin = A0; // analog pin used to connect the potentiometer


int potVal = 0; // variable to store the value read from the potentiometer

void setup() {
Serial.begin(9600); // initialize serial communication at 9600 bits per second
}

void loop() {
potVal = analogRead(potPin); // read the value from the potentiometer
Serial.println(potVal); // print the potentiometer value to the serial monitor
delay(100); // wait for 100ms before reading the potentiometer again
}

Task_6:
Knowing how the values are mapped, write a code that allows you to
display the value of the read voltage (a simple voltmeter). You
can do it by writing a linear function that converts the values,
or you can familiarize yourself with the operation of the map
function.
(https://reference.arduino.cc/reference/en/language/functions/math
/map/)

Knowing how analog value reading works, we will now move on to


using it with a voltage divider.

When using a voltage divider, it is important to remember that


there are two resistors involved, one of which (called the fixed
resistor) should have a constant value, while the other (called
the variable resistor) will be adjustable, such as a
photoresistor.

The voltage divider should be connected in such a way that one end
is connected to the power supply voltage, and the other end to
ground. Between them, two resistors should be connected, with the
fixed resistor connected to the power supply voltage, and the
variable resistor connected to ground. The voltage at the junction
of the resistors will be proportional to the amount of light
hitting the photoresistor.

The first configuration shown below demonstrates the use of a


resistor matched to the changes occurring in the sensor. The
second option is to connect half of a potentiometer in series with
the sensor, which will allow the values to be adjusted on the fly,
and thus calibrate the readings obtained.

To adjust the value of the resistor in conjunction with a


photoresistor in a voltage divider and obtain the best reading
signal using Arduino, you can follow these steps:

1. Determine the value of the voltage that will be applied to


the voltage divider.
2. Select the value of the fixed resistor such that, at the
voltage value determined in step 1, the voltage value at the
point where the resistors are connected corresponds to the
range of the ADC measurement in Arduino. For example, if the
ADC has a 10-bit resolution (1024 levels) and you want to
measure voltages from 0 to 5V, then the voltage value at the
point where the resistors are connected should be 5V, and the
value of the fixed resistor should be 4.7 kΩ (for a voltage
divider of 1:1) or 10 kΩ (for a voltage divider of 2:1).
3. Choose the value of the variable resistor based on the range
of variability of the photoresistor and the preferred
measurement sensitivity. The smaller the value of the
variable resistor, the greater the sensitivity, but the lower
the measurement accuracy
4. Connect the voltage divider to Arduino and use the
analogRead() function to read the voltage value from the
point where the resistors are connected. Test the voltage
divider's operation and adjust the value of the variable
resistor to obtain the desired sensitivity and measurement
accuracy.
5. Calibrate the voltage divider, if necessary, by comparing the
ADC readings with the actual voltage values at the point
where the resistors are connected and adjusting the value of
the variable resistor to obtain more accurate measurements.
Task_7:
Writing a code that allows to determine 3 states of illumination
of the photoresistor - uncovered, partially covered, and
completely covered. The information should be displayed in the
serial monitor.

4)Sensors with digital read

Task_8:
Choose at least two of the sensors below and test their
functioning.

Capacitive Touch Sensor


https://wiki.dfrobot.com/DFRobot_Capacitive_Touch_Sensor_SKU_DFR00
30

int ledPin = 13; // Connect LED on pin 13, or use the onboard one
int KEY = 2; // Connect Touch sensor on Digital Pin 2

void setup(){
pinMode(ledPin, OUTPUT); // Set ledPin to output mode
pinMode(KEY, INPUT); //Set touch sensor pin to input mode
}

void loop(){
if(digitalRead(KEY)==HIGH) { //Read Touch sensor signal
digitalWrite(ledPin, HIGH); // if Touch sensor is HIGH, then turn on LED
}
else{
digitalWrite(ledPin, LOW); // if Touch sensor is LOW, then turn off LED
}
}

Joystick
https://wiki.dfrobot.com/Joystick_Module_For_Arduino_SKU_DFR0061

int JoyStick_X = 0; //x


int JoyStick_Y = 1; //y
int JoyStick_Z = 3; //key

void setup()
{
pinMode(JoyStick_Z, INPUT);
Serial.begin(9600); // 9600 bps
}
void loop()
{
int x,y,z;
x=analogRead(JoyStick_X);
y=analogRead(JoyStick_Y);
z=digitalRead(JoyStick_Z);
Serial.print(x ,DEC);
Serial.print(",");
Serial.print(y ,DEC);
Serial.print(",");
Serial.println(z ,DEC);
delay(100);
}
Vibration Sensor

https://wiki.dfrobot.com/DFRobot_Digital_Vibration_Sensor_V2_SKU_D
FR0027

#define SensorLED 13
//Connect the sensor to digital Pin 3 which is Interrupts 1.
#define SensorINPUT 3
unsigned char state = 0;

void setup() {
pinMode(SensorLED, OUTPUT);
pinMode(SensorINPUT, INPUT);
//Trigger the blink function when the falling edge is detected
attachInterrupt(1, blink, FALLING);
}

void loop() {
if (state != 0) {
state = 0;
digitalWrite(SensorLED, HIGH);
delay(500);
}
else
digitalWrite(SensorLED, LOW);
}

//Interrupts function
void blink() {
state++;
}
Tilt Sensor

int ledPin = 13; // Connect LED to pin 13


int switcher = 3; // Connect Tilt sensor to Pin3

void setup()
{
pinMode(ledPin, OUTPUT); // Set digital pin 13 to output mode
pinMode(switcher, INPUT); // Set digital pin 3 to input mode
}
void loop()
{

if(digitalRead(switcher)==HIGH) //Read sensor value


{
digitalWrite(ledPin, HIGH); // Turn on LED when the sensor is tilted
}
else
{
digitalWrite(ledPin, LOW); // Turn off LED when the sensor is not triggered
}
}
Digital Infrared Motion Sensor

https://wiki.dfrobot.com/Digital_Infrared_motion_sensor__SKU_SEN00
18_

const int buttonPin = 2;


const int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop()
{
if (digitalRead(buttonPin) == HIGH)
{
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin, LOW);
}
}
5)Sensors with analog read

Steam Sensor

https://wiki.dfrobot.com/Steam_Sensor__SKU_SEN0121_

/*******************************
Connection:
VCC-5V
GND-GND
S-Analog pin 0

You can put the sensor on your palm,


it may sense the humidity of your palm
********************************/

void setup()
{
Serial.begin(9600);// open serial port, set the baud rate to 9600 bps
}
void loop()
{
int sensorValue;
sensorValue = analogRead(0); //connect Steam sensors to Analog 0
Serial.println(sensorValue); //print the value to serial
delay(200);
}
Soil Moisture Sensor

https://wiki.dfrobot.com/Moisture_Sensor__SKU_SEN0114_

/*
# Example code for the moisture sensor
# Editor : Lauren
# Date : 13.01.2012
# Version : 1.0
# Connect the sensor to the A0(Analog 0) pin on the Arduino board
# the sensor value description
# 0 ~300 dry soil
# 300~700 humid soil
# 700~950 in water
*/
void setup(){

Serial.begin(57600);
}

void loop(){

Serial.print("Moisture Sensor Value:");


Serial.println(analogRead(A0));
delay(100);
}
Triple Axis Accelerometer

https://wiki.dfrobot.com/Triple_Axis_Accelerometer_MMA7361_SKU_DFR
0143

// # Editor :Holiday from DFRobot


// # Data 09.10.2013

// # Product name:Triple Axis Accelerometer MMA7361


// # Product SKU:SEN0143
// # Version : 2.0

// # Description:
// # This sample shows how to measure the angle value using two axis value

#include<math.h>
#include<stdio.h>

#define A_X 5
#define A_Y 4
#define A_Z 3

int val_x,val_y,val_z;
double b;
void setup()
{
pinMode(A_X,INPUT);
pinMode(A_Y,INPUT);
pinMode(A_Z,INPUT);
Serial.begin(9600);
}
void loop()
{
float a;
for (int i=0;i<10;i++)
{
val_x+=analogRead(A_X);delay(2);
val_y+=analogRead(A_Y);delay(2);
val_z+=analogRead(A_Z);delay(2);
}
val_x=val_x/10;
val_y=val_y/10;
val_z=val_z/10;
delay(300);
Serial.print(" X_Axis: ");
Serial.print(val_x);
Serial.print(" Z_Axis: ");
Serial.print(val_z);
Serial.print(" ");
b=(double) (abs(val_x-320))/(abs(val_z-320));
Serial.print(" B: ");
Serial.print(b);
Serial.print(" ");
a=atan(b);
Serial.print(" A: ");
Serial.println(a/3.14*180); //the value of Angle
val_x=0;
val_y=0;
val_z=0;

}
Flame Sensor

https://wiki.dfrobot.com/Flame_sensor_SKU__DFR0076

/*
# Product: Flame sensor
# SKU : DFR0076
# Description:
# When flame sensor detected flame, the data will be read by the serial.
*/

void setup() {
Serial.begin(9600);
}

void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
}
Sound Sensor

https://wiki.dfrobot.com/Analog_Sound_Sensor_SKU__DFR0034

void setup()
{
Serial.begin(9600); // open serial port, set the baud rate to 9600 bps
}
void loop()
{
int val;
val=analogRead(0); //connect mic sensor to Analog 0
Serial.println(val,DEC);//print the sound value to serial
delay(100);
}

6)PWM & servomechanism

PWM (Pulse Width Modulation) is a technique for modulating the


width of pulses, used to control the power delivered to electrical
devices. It involves cyclically turning on and off the power
supply within a specified time period, where the ratio of the
on-time duration to the total cycle time is adjustable.

In practice, PWM involves generating a signal with a constant


frequency, where the duration of the on-state (high state) is
varied while the duration of the off-state (low state) remains
unchanged. The ratio of these two durations creates a percentage
value that determines the power delivered to the device.

PWM allows for the simulation of average power by rapidly


switching the power supply on and off. For an observer or
receiving device, the result is a lower average power while
maintaining control over its time distribution.
PWM is widely used in electronics and device control, such as
servo motors, DC motors, fan controllers, LED brightness
controllers, and many others. It enables precise control of power
and regulation of parameters such as speed, position, brightness,
or other electrical device properties.

To control an LED with PWM using Arduino, you will need an Arduino
board with at least one PWM-enabled pin. Here's a step-by-step
guide:

1. Connect the LED to Arduino:


- Connect the anode (longer pin) of the LED to a digital pin on
Arduino. For example, you can use pin 9.
- Connect the cathode (shorter pin) of the LED to the GND
(ground) pin on Arduino.

2. Write the Arduino code:


Open the Arduino IDE and write code to control the brightness
of the LED using PWM. Here's an example code:

int ledPin = 9; // Selected PWM pin

void setup() {
pinMode(ledPin, OUTPUT); // Set the pin as output
}

void loop() {
analogWrite(ledPin, 128); // Set brightness to half (value 0-255)
delay(1000); // Wait for 1 second
analogWrite(ledPin, 255); // Set full brightness
delay(1000); // Wait for 1 second
}

In this code, we use the `analogWrite()` function, which


generates PWM signal on the selected pin. We pass the brightness
value ranging from 0 to 255, where 0 represents the LED completely
off, and 255 represents full brightness.

3. Upload the code to Arduino:


Connect Arduino to your computer using a USB cable, select the
appropriate serial port in the Arduino IDE, and then upload the
code to Arduino by clicking the "Upload" button (upward arrow) on
the toolbar.

After uploading the code to Arduino, the LED should start


blinking, changing its brightness between half and full
brightness, with a 1-second delay between changes.
With PWM, you can smoothly and precisely control the brightness of
the LED by adjusting the value passed to the `analogWrite()`
function. You can modify the values and delays in the code to
achieve the desired LED brightness control effects.

To control a servo using PWM, you will need an Arduino board with
at least one PWM-enabled pin. Here are the steps you need to
follow:

1. Connect the servo to Arduino:


- Connect the power wires of the servo to the power supply: red
wire to the servo's power pin (VCC), black wire to the GND
(ground) pin.
- Connect the control wire of the servo: orange wire to a
digital pin on Arduino. For example, you can use pin 9.

2. Write the Arduino code:


Open the Arduino IDE and write code that will control the servo
using PWM. Here's an example code:

#include <Servo.h>

Servo myservo; // Servo object

void setup() {
myservo.attach(9); // Assign PWM pin to the servo
}

void loop() {
myservo.write(90); // Set angle to 90 degrees
delay(1000); // Wait for 1 second
myservo.write(180); // Set angle to 180 degrees
delay(1000); // Wait for 1 second
}

In this code, we use the `Servo` library, which simplifies


servo control. We create a servo object `myservo` and attach it to
the selected PWM pin using the `attach()` function. Then, we use
the `write()` function of the servo object to set the desired
angle of rotation for the servo.

3. Upload the code to Arduino:


Connect Arduino to your computer using a USB cable, select the
appropriate serial port in the Arduino IDE, and then upload the
code to Arduino by clicking the "Upload" button (upward arrow) on
the toolbar.
After uploading the code to Arduino, the servo should start
rotating, changing the angle between 90 and 180 degrees, with a
1-second delay between changes.

By manipulating the values passed to the `write()` function, you


can precisely control the angle of rotation for the servo and thus
control its movement. You can adjust the values and delays in the
code to achieve the desired servo control effects.

Task_9:
Program the LED brightness control and servo position depending on
the selected analog sensor.
Exercise 1.1 (grade 3)

Program the traffic light switching system to respond to a button. After


the first click, the lights should change from green to yellow, and then to
red. After the second click, the change should be reversed.

Remember to take into account that before turning on the red light, the
yellow light should stay on longer than before switching to green.

Exercise 1.2 (grade 4)

Program a smart bulb to light up when the system detects a sunset.

Exercise 1.3 (grade 5)

Program the control of 3 LEDs through text commands entered in the Serial
Port Monitor. The command has two values - led color and lighting duration.

You might also like