Sei sulla pagina 1di 35

UNIT 3 Analog Signal and Serial Monitor

UNIT OBJECTIVE
When you have completed this unit, you will be able to explain the operating
principle of various analog input and output devices and Arduino Serial Monitor, and
write programs to control these devices.

DISCUSSION
Potentiometers and joysticks are practical analog input devices. A potentiometer
either rotary type or slide type, has three terminals: the wiper terminal at the middle
and two end terminals. If connecting one end terminal to a positive voltage +5V and
the other to ground, the wiper voltage will vary from 0V to +5V when you change the
position of the wiper.

A joystick is a hand switch actuated by a lever free to move in more than one axis of
motion. Joystick switches are often used to control video games, and also used for
controlling machines such as wheelchairs, cranes, and robots. The joystick installed
on the MTS-100 consists of two rotary potentiometers and a tact switch.

PWM output levels are low (0) and high (1), same as a digital signal, the average of
PWM output is considered as a dc voltage, which is proportional to the pulse width of
PWM wave. PWM outputs are well suited to light a LED at varying brightnesses or
drive a motor at various speeds.

Like the HyperTerminal in Windows XP, Arduino Serial Monitor allows you to
manipulate the Arduino board under Windows environment. The Serial Monitor
connects to your Arduino Uno over the serial port (com).

EQUIPMENT REQUIRED
1 Personal Computer
2 MTS-100 Tutor for Arduino
3 USB Cable
4 Jumper Wires
5 AC Power Cord

3-1
Exercise 3-1 Analog Input and Output

EXERCISE OBJECTIVE

After completing this exercise, you should be able to:


1. State the construction and operation of 1W LED, potentiometer and joystick.
2. Write sketches to control the LED brightness using potentiometer and joystick.

DISCUSSION

Potentiometer

Digital signal is low (0) or high (1). Digital signal is used in microcomputers or digital
circuits for computing and storage. However, analog devices and analog signals are
found everywhere in real world. Therefore, how to handle analog signal is an
important task of Arduino boards. Potentiometers and joysticks are practical analog
input devices. The potentiometer (POT) also called the Variable Resistor (VR) is the
most common analog device. Potentiometers can be divided into rotary type and
slide type, as shown in Fig. 3-1.

(a) Rotary type (b) Slide type

Fig. 3-1 Potentiometers

The MTS-100 is equipped with two slide potentiometers arranged in horizontal and
vertical placement for X- and Y-axis operations, respectively, as shown in Fig. 3-2.
The potentiometer placed in horizontal is called the horizontal potentiometer (H pot),
and the voltage on the P7-1 header pin increases as the wiper moves from left to
right. The potentiometer placed in vertical is called the vertical potentiometer (V pot),
and the voltage on the P7-2 header pin increases as the wiper moves from bottom to
top.

3-2
Fig. 3-2 Interface circuit of slide potentiometers

A joystick is a hand switch actuated by a lever free to move in more than one axis of
motion. One or more of several switch contact mechanisms are actuated depending
on which way the lever is pushed, and sometimes by how far it is pushed. Joystick
switches are often used to control video games, and also used for controlling
machines such as wheelchairs, cranes, and robots. Joysticks usually have one or
more pushbuttons and potentiometers whose state can also be read by the
computer. Fig. 3-3 shows the mushroom-shaped joystick installed on the MTS-100.
It contains two rotary potentiometers (variable resistors) and a tact switch (center
pushbutton switch).

Fig. 3-3 Appearance and internal circuit of mushroom-shaped joystick

The joystick is connected to the P24A header in factory. The header P24 is used to
connect the joystick terminals to Arduino board: P24-1 pin connected to the center
pushbutton (actually a tact switch), P24-2 pin connected to the wiper (middle
terminal) of horizontal potentiometer (H pot), and P24-3 pin connected to the wiper
(middle terminal) of vertical potentiometer (V pot).

3-3
The voltage on the P24-2 pin increases as the wiper of H pot moves from middle to
left, while the voltage decreases as the wiper moves from middle to right. The
voltage on the P24-3 pin increases as the wiper of V pot moves from middle to top,
while the voltage decreases as the wiper moves from middle to bottom. The tact
switch (center pushbutton) is connected through a pullup resistor to +5V. When the
tact switch is open, the voltage on the P24-1 header pin is high. When the tact
switch is closed, the voltage on the P24-1 pin will be low. In normal case, the
joystick’s stick is in the center position due to an internal spring mechanism, so the
tact switch is open and the wipers of V and H pots are at the middle position.

Analog Input/Output Functions

In Unit 2, digital input and output functions digitalRead() and digitalWrite() were used
for the input and output of digital signals. To handle the input and output of analog
signals, analog input and output functions analogRead() and analogWrite() are
available.

Analog Input Function

The Arduino Uno contains a 6-channel 10-bit Analog-to-Digital Converter (ADC),


whose channel inputs are connected to analog input pins A0~A5, respectively. Each
of the ADC channels will map input voltages between 0 and 5 volts into integer
values between 0 and 1023. This yields a resolution between readings of 5
volts/1024 units or, 0.0049 volts (4.9 mV) per unit. It takes about 100 microseconds
(0.0001 seconds) to read an analog input, so the maximum reading rate is about
10,000 times a second.

analogRead() function

Description:
The analogRead() function reads the value from the specified analog pin.
Syntax:

val = analogRead(pin);

Parameters:
1. pin: the number of the analog input pin to read from.
2. val: variable is the integer value (0 to 1023) returned.

3-4
For example, the statement

myVoltage=analogRead(2);

reads the analog voltage on analog pin A2 and stores it in the variable myVoltage.

Analog pins A0~A5 not only can be used for analog input, but also used for digital
I/O. For digital I/O, these pins (A0~A5) can be read or written using digitalRead() or
digitalWrite(). For analog input, these pins (0~5) can be read using analogRead()
function.

Analog Output Fuction

Arduino Uno board has no Digital-to-Analog Converter (DAC), but with an 8-bit Pulse
Width Modulation (PWM) output, the average of a PWM output is considered as an
analog signal.

analogWrite() function

Description:
The analogWrite() function writes an analog value (PWM wave) to a pin.

Syntax:

analogWrite(pin, analogValue);

Parameters:
1. pin: the pin to write to.
2. analogValue: the duty cycle between 0 (always off) and 255 (always on).

The following statement outputs a PWM wave with a duty cycle of 127 to pin 5:

analogWrite(5,127);

On the Arduino Uno, analogWrite() function (PWM output) works on pins 3, 5, 6, 9,


10, and 11. The frequency of the PWM signal on pins 3, 9, 10, 11 is about 490 Hz,
whereas pins 5 and 6 have PWM signals with a frequency of 980 Hz approximately.

3-5
PWM Output

A PWM wave consists of low and high levels in a fixed period. The time of high level
is called the pulse width. The ratio of high level time to the period time is called the
duty cycle. For example, the output of the built-in 8-bit PWM on Arduino Uno is
evenly divided into 28-1 divisions (255) in a fixed period. If a PWM wave consists of
5-division high (the pulse width) and 250-division low, the average value of output
voltage Vo is calculated by VCC×(5/255), where 5/255 is the duty cycle of PWM
wave. When VCC=5V, then Vo=0.098V. If a PWM wave consists of 125-division high
and 130-division low, the average output voltage Vo is calculated by VCC×(125/255).
When VCC=5V, then Vo=2.45V. The average value of a PWM output wave is
proportional to the pulse width or the duty cycle.

Essentially PWM output levels are low (0) and high (1), same as a digital signal, so
the output driver will operate in saturation and cutoff. PWM outputs are well suited to
light a LED at varying brightnesses or drive a motor at various speeds.

1W LED

In this exercise, we will design an LED dimmer whose power dissipation is 1 watt.
The operating principle of 1W LED is identical to common LEDs. Fig. 3-4 shows the
1W LED driver circuit. The anode of the LED is connected to the drain of a PMOS
FET transistor whose gate is tied to the P8 header pin. The PMOS FET acts as a
driver and a switch. A low to the gate turns on the switch to drive the 1W LED on. A
high to the gate turns off the switch so that the LED is off.

Fig. 3-4 1W LED driver circuit

3-6
Potentiometer/Joystick Controlled LED Dimmer

In this exercise, you’ll employ the potentiometer of slide potentiometer and joystick to
control the brightness of 1W LED using PWM output. To set the output to the LED
proportional to the value read from the potentiometer, an ADC channel and a PWM
output must be used. Since the PWM output on Arduino Uno is 8-bit output (0 to 255)
and the ADC channel is 10-bit output (0 to 1023), it is required to re-map the
measured value of 10-bit ADC output to 8-bit PWM output. In this case, dividing the
10-bit ADC output by 4 re-maps the value from 10-bit to 8-bit range. However,
Arduino provides a map() function to re-map a number from one range to another.

map() function

Description:
Arduino map() function re-maps a number from one range to another. That is, a
value of fromLow would get mapped to toLow, a value of fromHigh to toHigh,
values in-between to values in-between, etc.

Syntax:
newValue = map(value, fromLow, fromHigh, toLow, toHigh);

Parameters:
1. value: the number to map
2. fromLow: the lower bound of the value's current range
3. fromHigh: the upper bound of the value's current range
4. toLow: the lower bound of the value's target range
5. toHigh: the upper bound of the value's target range
6. newValue: the previously-declared variable for storing the mapped value

The following example,

newValue=map(30, 0, 99, 24, 511);

re-maps a 30 from range 0 to 99 to range 24 to 511, and stores the result in the
newValue variable.

3-7
PROCEDURE A

Potentiometer Controlled LED Dimmer

In this procedure, you will use the vertical potentiometer (V pot) to light the 1W LED
at varying brightnesses.

Circuit Connections

Perform the following steps and refer to the wiring diagram in Fig. 3-5 to complete
the connections for potentiometer controlled LED dimmer.

Fig. 3-5 Wiring diagram of potentiometer controlled LED dimmer

1. Connect the Arduino Uno board to your computer using the USB cable.

3-8
2. Connect a correct AC voltage from a wall outlet to your MTS-100 using the AC
power cord, and then turn on the power.

3. Connect the Arduino pin A2 to the header pin P7-2 (SLIDE POTENTIOMETER).
This makes the vertical potentiometer (V pot) available.

4. Connect the Arduino pin 3 to the header pin P8 (1W LED). This makes the 1W
LED available.

Program Design

5. Open the Arduino IDE window. In the text editor, write your sketch as shown
below and save it as “ex3-1-1.ino”. Note: You can omit the program comments to
save time for the actual study of the sketch.

//========== ex3-1-1.ino ============


//========== Global Declaration ============
// pin A2 connected to V pot’s wiper, pin 3 connected to 1W LED
#define potV 2 // V pot’s wiper connected to analog pin A2
#define LED 3 // 1W LED connected to digital pin 3
//========== Initialization ============
void setup()
{ pinMode(potV, INPUT); // configure analog pin A2 as an input
pinMode(LED, OUTPUT); // configure digital pin 3 as an output
digitalWrite(LED, 1); // turn off LED
}
//========== Main Code ============
void loop()
{ int analogIn=0,pwm; //declare integer variables analogIn, pwm
analogIn = analogRead(potV); // read the value of vertical pot, range 0 to
1023
pwm=~map(analogIn,0,1023,0,255); // scale it to use it with the PWM, range 0 to
255
analogWrite(LED,pwm); // PWM output according to the scaled value
}

Compiling and Uploading

6. Once the editing is completed, press + keys to compile your sketch.


If “Error compiling” appears in the console, the message area will show the error
message with line number. If “Done compiling” appears in the console, the
message area will display memory usage for code and variables as follows:

3-9
Sketch uses 1,590 bytes (4%) of program storage space. Maximum is 32,256
bytes.

Global variables use 15 bytes (0%) of dynamic memory, leaving 2,033 bytes
for local variables. Maximum is 2,048 bytes.

7. Press + keys to upload the code to the Arduino board.

8. Never look steadily at the 1W LED to protect your eyes from a strong light.

9. Move the wiper of V pot from bottom to top, the 1W LED should light at varying
brightnesses from minimum to maximum.

10. Move the wiper of V pot from top to bottom, the 1W LED should light at varying
brightnesses from maximum to minimum.

PROCEDURE B

Joystick Controlled LED Dimmer

In this procedure, you will use the joystick instead of the potentiometer to light the
1W LED at varying brightnesses. In addition, when the center pushbutton of joystick
is pressed, the 1W LED will light at maximum brightness for 0.5 seconds, and then
return to the original state.

Circuit Connections

Perform the following steps and refer to the wiring diagram in Fig. 3-6 to complete
the connections for joystick controlled LED dimmer.

1. Connect the Arduino Uno board to your computer using the USB cable.

2. Connect a correct AC voltage from a wall outlet to your MTS-100 using the AC
power cord, and then turn on the power.

3. Connect the Arduino pin A0 to the header pin P24-1 (JOYSTICK). This makes
the joystick button (the tact switch of joystick) available.

3-10
4. Connect the Arduino pin A2 to the header pin P24-3 (JOYSTICK). This makes
the vertical potentiometer of joystick available.

5. Connect the Arduino pin 3 to the header pin P8 (1W LED). This makes the 1W
LED available.

Fig. 3-6 Wiring diagram of joystick controlled LED dimmer

Program Design

6. Open the Arduino IDE window. In the text editor, write your sketch as shown
below and save it as “ex3-1-2.ino”. Note: You can omit the program comments to
save time for the actual study of the sketch.

3-11
//========== ex3-1-2.ino ============
//========== Global Declaration ============
// pin A0 connected to joystick’s tact switch, pin A2 connected to joystick’s V pot
// pin 3 connected to 1W LED
#define PB A0 // joystick’s tact switch connected to analog pin A0
#define potV 2 // V pot’s wiper connected to analog pin A2
#define LED 3 // 1W LED connected to digital pin 3
//========== Initialization ============
void setup()
{ pinMode(PB, INPUT); // configure analog pin A0 as an input
pinMode(potV, INPUT); // configure analog pin A2 as an input
pinMode(LED, OUTPUT); // configure digital pin 3 as an output
digitalWrite(LED, 1); // turn off LED
}
//========== Main Code ============
void loop()
{ int pb=1,analogIn=0,pwm; // declare variables pb,analogIn,pwm
pb = digitalRead(PB); // read tact switch’s state
if (!pb) // if the tact switch is pressed,
{ digitalWrite(LED,0); // 1W LED on, max brightness
delay(500); // a delay of 0.5 seconds
digitalWrite(LED,1); // turn off 1W LED
}
analogIn = analogRead(potV); // read the value of vertical pot, range 0 to
1023
pwm=map(analogIn,0,1023,0,255); // scale it to use it with the pwm, range 0 to
255
analogWrite(LED,pwm); // PWM output according to the scaled value
}

Compiling and Uploading

7. Once the editing is completed, press + keys to compile your sketch.


If “Error compiling” appears in the console, the message area will show the error
message with line number. If “Done compiling” appears in the console, the
message area will display memory usage for code and variables as follows:

Sketch uses 1,876 bytes (5%) of program storage space. Maximum is 32,256
bytes.

Global variables use 15 bytes (0%) of dynamic memory, leaving 2,033 bytes
for local variables. Maximum is 2,048 bytes.

3-12
8. Press + keys to upload the code to the Arduino board.

9. Never look steadily at the 1W LED to protect your eyes from a strong light.

10. Initially the joystick is in the center position and the 1W LED lights at half
brightness.

11. Push the joystick from center to top, the 1W LED should light at varying
brightnesses from half to maximum. Release the joystick, it returns to the center
position and the 1W LED light at half brightness.

12. Pull the joystick from the center to bottom, the 1W LED should light at varying
brightnesses from half to minimum. Release the joystick, it returns to the center
position and the 1W LED light at half brightness.

13. Press the joystick’s center pushbutton, the 1W LED should light at maximum
brightness for 0.5 seconds.

3-13
Exercise 3-2 Serial Monitor

EXERCISE OBJECTIVE

After completing this exercise, you should be able to:


1. State the function and operation of Arduino Serial Monitor.
2. Write sketches to control the LED brightness, microphone noise detector, and
CdS light detector and digital voltmeter in the Serial Monitor window.

DISCUSSION

Serial Monitor
Like the HyperTerminal in Windows XP, Arduino Serial Monitor allows you to
manipulate the Arduino board under Windows environment. During sketch uploading,
the Arduino Uno is connected to your computer using a Universal Asynchronous
Receiver/Transmitter (UART) and a UART to USB bridge chip. In addition, the Serial
Monitor connects to your Arduino Uno over the same serial port (com).

When Arduino Uno board is connected to your PC using the USB cable, you can
click the Serial Monitor button on the toolbar in the Arduino IDE or press
+ + keys to open the Serial Monitor window as show in Fig. 3-7.

Fig. 3-7 Serial Monitor window


Look at the Serial Monitor window:

3-14
1. COM port: The COM port used to connect to the Arduino Uno is displayed in the
upper left corner of serial monitor window.

2. The small upper box is where you can type in characters to be sent, and then
click the button. The characters will be sent to the Arduino board.

3. The larger area is where characters sent from Arduino board will be displayed. If
the Autoscroll is checked, the displayed characters will automatically scroll up.

4. Line end settings: Specifies how the string is terminated that you send to your
Arduino board after clicking the button.
(1) No line ending: no character is appended to the string being sent.
(2) Newline: a newline aka Line Feed character ('LF'=0x0a or '\n') is appended.
(3) Carriage return: a Carriage Return character ('CR'=0x0d or '\r') is appended.
(4) Both NL and CR: both a CR and a newline (LF) character are appended.

5. Baud Rate Settings: Specifies the transmission speed or so-called "baud rate"
that Serial Monitor and your Arduino board use. This setting must match the
setting your sketch uses in the Serial.begin() function.

Serial Library

Arduino Serial library includes many functions used for communicating Arduino
board with PC. Serial library functions are as follows:

Serial.available() function

Description:
The Serial.available() function gets the number of bytes (characters) available
for reading from the serial port. This is data that is already arrived and stored in
the serial receive buffer (which holds 64 bytes).

Syntax:

receivedBytes = Serial.availabe();

The receivedBytes variable is the return of the number of bytes available to read.

3-15
This function is usually used to check whether data is received or not. In the
example,

if(Serial.availabe()>0)
{ statement block
}

the statements in the statement block will be executed if the characters is read from
the serial port.

Serial.begin() function

Description:
The Serial.begin() function sets the data rate in bits per second (baud) for serial
data transmission. You can, however, specify other rates - for example, to
communicate over pins 0 and 1 with a component that requires a particular
baud rate. Once the serial port is initialized by the Serial.begin() function, the
Arduino Uno board can receive the data from PC via pin 0 (RX), and can send
data to PC via pin 1 (TX).

Syntax:
Serial.begin(baudrate);

Parameters:
1. baudrate: in bits per second (baud) – long. For communicating with the
computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400,
19200, 28800, 38400, 57600, or 115200. The default baudrate of most
devices is 9600bps.

For example, to set data rate of 9600bps for serial data transmission, use this
statement:
Serial.begin(9600);

Serial.end() function

Description:
The Serial.end() function disables serial communication, allowing the RX and
TX pins to be used for general input and output.

Syntax:

Serial.end();

3-16
Serial.find() function

Description:
The Serial.find() function reads data from the serial buffer until the target string
of given length is found. The function returns true if target string is found, false if
it times out.

Syntax:

trueFalse=Serial.find(targetChar);

Parameters:
1. targetChar: the string to search for (char)
2. trueFalse: true if target string is found, false if it times out (Boolean)

Serial.findUntil() function

Description:
The Serial.findUntil() function reads data from the serial buffer until a target
string of given length or terminator string is found.

Syntax:

trueFalse=Serial.findUntil(targetChar, terminal);

Parameters:
1. targetChar: the string to search for (char)
2. terminal: the terminal string in the search (char)
3. trueFalse: true if the target string is found, false if it times out. (Boolean)

Serial.flush() function

Description:
The Serial.flush() function waits for the transmission of outgoing serial data to
complete.

Syntax:

Serial.flush();

Serial.parseFloat() function

Description:
The Serial.parseFloat() function returns the first valid floating-point number from
the Serial buffer. Characters that are not digits (or the minus sign) are skipped.
parseFloat() is terminated by the first character that is not a floating-point number.

3-17
Syntax:

dataFloat=Serial.parseFloat();

Parameters:
1. dataFloat: the previously-declared variable stores the first valid float found in
the incoming serial stream.

Serial.parseInt() function

Description:
The Serial.parseInt() function looks for the next valid integer in the incoming
serial stream.

Syntax:

dataInt=Serial.parseInt();

Parameters:
1. dataInt: the previously-declared variable stores the next valid integer found
in the incoming serial stream.

Serial.peek() function

Description:
The Serial.peek() function returns the next byte (character) of incoming serial
data without removing it from the internal serial buffer. That is, successive calls
to peek() will return the same character, as will the next call to read().

Syntax:

recData=Serial.peek();

Parameters:
1. recData: variable stores the first byte of incoming serial data available (or -1
if no data is available) – int.

Serial.print() function

Description:
The Serial.print() function prints data to the serial port as human-readable
ASCII text. This command can take many forms:
1. Numbers are printed using an ASCII character for each digit.

3-18
2. Floats are similarly printed as ASCII digits, defaulting to two decimal places.
3. Bytes are sent as a single character. Characters and strings are sent as is.

Syntax:

numberOfData=Serial.print(val, format);

Parameters:
1. Val: the value to print – any data type
2. format: The optional argument specifies the base (format) to use; permitted
values are BIN (binary, or base 2), OCT (octal, or base 8), DEC (decimal, or
base 10), HEX (hexadecimal, or base 16).
(1) BIN: binary format, e.g. Serial.print(65, BIN) gives “1000001”.
(2) OCT: octal format, e.g. Serial.print(65, OCT) gives “101”.
(3) DEC: decimal format, e.g. Serial.print(65, DEC) gives “65”.
(4) HEX: hexadecimal format, e.g. Serial.print(65, HEX) gives “41”.
For floating-point numbers, this parameter specifies the number of decimal
places to use.
3. numberOfData: the variable is the number of bytes written returned by the
print() function.

The following sketch opens the serial port at 9600 bps and dsplays the numbers
100-109 on the Serial Monitor in various formats.

void setup()
{ Serial.begin(9600); // open the serial port at 9600 bps
}
void loop()
{// display titile
Serial.print(“NO FORMAT”); // print a label
Serial.print(“\t”); // print a tab
//=========================
Serial.print(“DEC”); // print a label
Serial.print(“\t”); // print a tab
//=========================
Serial.print(“HEX”); // print a label
Serial.print(“\t”); // print a tab
//=========================
Serial.print(“OCT”); // print a label
Serial.print(“\t”); // print a tab
//=========================

3-19
Serial.print(“BIN”); // print a label
Serial.print(“\t”); // print a tab
//=========================
for(int x=100; x<110; x++) // print 100~109 out in many formats:
{Serial.print(x); // print as an ASCII-encoded decimal – same as “DEC”
Serial.print(“\t”); // print a tab
Serial.print(x, DEC); // print as an ASCII-encoded decimal
Serial.print(“\t”); // print a tab
Serial.print(x, HEX); // print as an ASCII-encoded hexadecimal
Serial.print(“\t”); // print a tab
Serial.print(x, OCT); // print as an ASCII-encoded octal
Serial.print(“\t”); // print a tab
Serial.println(x, BIN); // print as an ASCII-encoded binary, followed by a carriage
return
delay(200); // a delay of 200 ms
}
Serial.println(“”); // print another carriage return
}

When the sketch above is executed, you’ll see the numbers 100-109 are displayed
in Serial Monitor window in various formats as follows:

NO FORMAT DEC HEX OCT BIN


100 100 64 144 1100100
101 101 65 145 1100101
102 102 66 146 1100110
103 103 67 147 1100111
104 104 68 150 1101000
105 105 69 151 1101001
106 106 6A 152 1101010
107 107 6B 153 1101011
108 108 6C 154 1101100
109 109 6D 155 1101101

Serial.println() function

Description:
The Serial.println() function prints data to the serial port as human-readable
ASCII text followed by a carriage return character (ASCII 13, or '\r') and a
newline character (ASCII 10, or '\n'). This function takes the same forms as
Serial.print().

3-20
Serial.read() function

Description:
The Serial.read() function reads incoming serial data.

Syntax:

recData=Serial.read();

Parameter:
1. recData: variable is the first byte of incoming serial data available (or -1 if no
data is available) – int .

Serial.readBytes() function

Description:
The Serial.readBytes() function reads characters from the serial port into a
buffer. The function terminates if the determined length has been read, or it
times out.

Syntax:

rdBytes=Serial.readBytes(buffer, length);

Parameters:
1. buffer: the buffer to store the bytes in (char[] or byte[])
2. length: the number of bytes to read (int)
3. rdBytes: the number of characters placed in the buffer. A 0 means no valid
data was found.

Serial.readBytesUntil() function

Description:
The Serial.readBytesUntil() function reads characters from the serial buffer into
an array. The function terminates if the terminator character is detected, the
determined length has been read, or it times out.

Syntax:

rdBytes=Serial.readBytesUntil(character, buffer, length);

Parameters:
1. character: the character to search for (char)
2. buffer: the buffer to store the bytes in (char[] or byte[]) array.

3-21
3. length: the number of bytes to read (int)
4. rdBytes: the number of characters read into the buffer. A 0 means no valid
data was found.

Serial.setTimeout() function

Description:
The Serial.setTimeout() function sets the maximum milliseconds to wait for
serial data.

Syntax:

Serial.setTimeout(time);

Parameters:
1. time: the timeout duration in milliseconds (long), 1000 by default.

Serial.write() function

Description:
The Serial.write() function 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 of a
number use the print() function instead.

Syntax:

Serial.write(oneByte);
Serial.write(multiBytes);
Serial.write(buffer, length);

Parameters:
1. oneByte: a value to send as a single byte
2. multiByte: a string to send as a series of bytes
3. buffer: an array to send as a series of bytes
4. length: the length of the buffer

3-22
PROCEDURE A

LED Brightness Controller 1

In this procedure, you’ll design an LED controller to control the brightness of 1W


LED in the Serial Monitor window. In the Serial Monitor window, the specified LED
brightness (range 0 to 9) will be sent to the Arduino Uno to control the LED at soft
variation of LED brightness.

Circuit Connections

Peform the following steps and refer to the wiring diagram in Fig. 3-8 to complete the
connections of high-power LED dimmer:

1. Connect the Arduino Uno board to your computer using the USB cable.

2. Connect a correct AC voltage from a wall outlet to your MTS-100 using the AC
power cord, and then turn on the power.

3. Connect the Arduino pin 3 to the header pin P8 (1W LED) as shown in Fig. 3-8.
This makes the 1W LED available.

Fig. 3-8 Wiring diagram of high-power LED dimmer

3-23
Program Design

4. Open the Arduino IDE window. In the text editor, write your sketch as shown
below and save it as “ex3-2-1.ino”. Note: You can omit the program comments to
save time for the actual study of the sketch.

//========== ex3-2-1.ino ============


//========== Global Declaration ============
// pin 3 connected to 1W LED
#define LED 3 // LED connected to digital pin 3
//========== Initialization ============
void setup()
{ Serial.begin(9600); // open the serial port at 9600 bps
pinMode(LED, OUTPUT); // configure digital pin 3 as an output
digitalWrite(LED, 1); // turn off LED
}
//========== Main Code ============
void loop()
{ int PC; // declare the variable PC
if (Serial.available()>0) // if incoming data on serial port is ready to read,
{ PC = Serial.read()-48; // read brightness setting and convert ASCII to
number
// range 0 to 9 (ASCII char 0 = 48 in decimal)
PC = map(PC,0,9,0,255); // scale it for the dimmer use, range 0 to 255
Serial.println(PC); // set LED’s brightness according to the scaled
value
for (int x=0;x<PC;x++) // increase brightness gradually
{ analogWrite(LED,255-x); // drive LED
delay(25); // a delay of 25 ms
}
for (int x=255-PC;x<=255;x++) // decrease brightness gradually
{ analogWrite(LED,x); // drive LED
delay(25); // a delay of 25 ms
}
}
}

Compiling and Uploading

5. Once the editing is completed, press + keys to compile your sketch.


If “Error compiling” appears in the console, the message area will show the error
message with line number. If “Done compiling” appears in the console, the
message area will display memory usage for code and variables as follows:

3-24
Sketch uses 3,396 bytes (10%) of program storage space. Maximum is 32,256
bytes.

Global variables use 186 bytes (9%) of dynamic memory, leaving 1,862 bytes
for local variables. Maximum is 2,048 bytes.

6. Press + keys to upload the code to the Arduino board.

7. Click the Serial Monitor button on the toolbar or press + +


keys to open the Serial Monitor window.

8. In the upper box of the Serial Monitor window, enter 12345678987654321, and
then click button or press . The 1W LED should light at varying
brightnesses from minimum to maximum, and then from maximum to minimum.

PROCEDURE B

LED Brightness Controller 2

In procedure A, the Serial.read() function was used to continuously read serial port
data for LED brightness control. In this procedure, the Serial.readBytesUntil()
function will be used to read the brightness setting (2 bytes once) from the serial
buffer into an array. The brightness setting between 0 and 99 is specified in the
Serial Monitor window. For example, you enter 1234 in the upper box of the Serial
Monitor window, and then click button or press , the specified
brightness is 12, and then 34. The range of brightness is 0 to 99: 0=minimum
brightness (off), 99=maximum brightness.

Circuit Connections

1. Remain the connections used in Procedure A unchanged.

Program Design

2. Open the Arduino IDE window. In the text editor, write your sketch as shown
below and save it as “ex3-2-2.ino”. Note: You can omit the program comments to
save time for the actual study of the sketch.

3-25
//========== ex3-2-2.ino ============
//========== Global Declaration ============
//pin 3 connected to 1W LED
#define LED 3 // LED connected to digital pin 3
char rec[6]; // declare a character array named rec
//========== Initialization ============
void setup()
{ Serial.begin(9600); // open the serial port at 9600 bps
pinMode(LED, OUTPUT); // configure digital pin 3 as an output
digitalWrite(LED, 1); // turn off LED
}
//========== Main Code ============
void loop()
{ int i,CNT; // declare integer variables i and CNT
byte PC; // declare a byte variable named PC
if (Serial.available()>0) // if valid data on the serial port,
{ for(i=0;i<2;i++) rec[i]=0; // clear rec array
CNT=Serial.readBytesUntil(13,rec,2); // read serial port data (2 bytes)
// and store in rec array (13=enter key)
if (CNT==1) PC= rec[0]-48; // if only one byte is read,
// convert ASCII char to number
else PC= (rec[0]-48)*10+rec[1]-48; // if the input value > one byte, convert
// two ASCII chars to two-digit number
if (PC>=0 && PC<100) // if the input value is valid, 0 to 99
{ map(PC,0,99,0,255); // scale it for the controller use, range 0
to 255
analogWrite(LED,255-PC); // set the LED brightness using the
scaled value
}
}
delay(1000); //delay 1 second
}

Compiling and Uploading

3. Once the editing is completed, press + keys to compile your sketch.


If “Error compiling” appears in the console, the message area will show the error
message with line number. If “Done compiling” appears in the console, the
message area will display memory usage for code and variables as follows:

3-26
Sketch uses 3,124 bytes (9%) of program storage space. Maximum is 32,256
bytes.

Global variables use 198 bytes (9%) of dynamic memory, leaving 1,850 bytes
for local variables. Maximum is 2,048 bytes.

4. Press + keys to upload the code to the Arduino board.

5. Click the Serial Monitor button on the toolbar or press + +


keys to open the Serial Monitor window. In the upper box of the Serial Monitor
window, do the following steps.

6. Type 1 and click button, the 1W LED should light at minimum


brightness.

7. Type 2 and click button, the brightness of 1W LED should increase from
1 to 2.

8. Type 9 and click button, the brightness of 1W LED should increase from
2 to 9.

9. Type 50 and click button, the brightness of 1W LED should increase


from 9 to 50.

10. Type 85 and click button, the brightness of 1W LED should increase
from 50 to 85.

11. Type 90 and click button, the brightness of 1W LED should increase
from 85 to 90.

12. Type 125 and click button, the brightness of 1W LED should decrease
from 90 to 12, and then to 5.

13. Type 0 and click button, the 1W LED should be off.

3-27
PROCEDURE C

Light Detector

In this procedure, you’ll design a light detector to sense the brightness of ambient
light, and show the measured brightness level in mV in the Serial Monitor window.

Circuit Connections

Peform the following steps and refer to the wiring diagram in Fig. 3-9 to complete the
connections for light detector:

1. Connect the Arduino Uno board to your computer using the USB cable.

2. Connect a correct AC voltage from a wall outlet to your MTS-100 using the AC
power cord, and then turn on the power.

3. Connect the Arduino pin A2 to the header pin P20-1 (CDS & MICROPHONE).
This makes the CdS available.

Fig. 3-9 Wiring diagram of light detector

3-28
Program Design

4. Open the Arduino IDE window. In the text editor, write your sketch as shown
below and save it as “ex3-2-3.ino”. Note: You can omit the program comments to
save time for the actual study of the sketch.

//========== ex3-2-3.ino ============


//========== Global Declaration ============
#define CDS A2 // CdS connected to analog pin A2
int cds,cds0; // declare integer variables cds,cds0
//========== Initialization ============
void setup()
{ Serial.begin(9600); // open the serial port at 9600 bps
pinMode(CDS, INPUT); // configure analog pin A2 as an input
}
//========== Main Code ============
void loop()
{ cds = analogRead(CDS); // read CDS output voltage, range 0 to 1023
if (cds!=cds0) // if the voltage is changed,
{ cds0=cds; // store the voltage value in cds0
cds=map(cds,0,1023,0,5000); // scale it for the detector use, range 0 to 5000
Serial.print(cds); // display the scaled value on Serial Monitor
Serial.println(" mV"); // display the “mV” string followed by a CR
and an LF
}
delay(1000); // a delay of 1 second
}

Compiling and Uploading

5. Once the editing is completed, press + keys to compile your sketch.


If “Error compiling” appears in the console, the message area will show the error
message with line number. If “Done compiling” appears in the console, the
message area will display memory usage for code and variables as follows:

Sketch uses 3,002 bytes (9%) of program storage space. Maximum is 32,256
bytes.

Global variables use 196 bytes (9%) of dynamic memory, leaving 1,852 bytes
for local variables. Maximum is 2,048 bytes.

6. Press + keys to upload the code to the Arduino board.

3-29
7. Click the Serial Monitor button on the toolbar or press + +
keys to open the Serial Monitor window.

8. The brightness of ambient light sensed by the CdS photocell will be displayed in
the large area of the serial monitor, in mV.

9. Wave your hand over the CdS photocell, the displayed value should be changed.

PROCEDURE D

Noise Detector

Noise is a kind of pollution. In this procedure, you’ll design a noise detector to sense
the noise from the microphone output, and show the noise level in mV in the Serial
Monitor window.

Circuit Connections

Peform the following steps and refer to the wiring diagram in Fig. 3-10 to complete
the connections for noise detector:

1. Connect the Arduino Uno board to your computer using the USB cable.

2. Connect a correct AC voltage from a wall outlet to your MTS-100 using the AC
power cord, and then turn on the power.

3. Connect the Arduino pin A2 to the header pin P20 (CDS & MICROPHONE). This
makes the microphone available.

3-30
Fig. 3-10 Wiring diagram of noise detector

Program Design

4. Open the Arduino IDE window. In the text editor, write your sketch as shown
below and save it as “ex3-2-4.ino”. Note: You can omit the program comments to
save time for the actual study of the sketch.

//========== ex3-2-4.ino ============


//========== Global Declaration ============
#define MIC A2 // MIC connected to analog pin A2
int mic0=0,mic1=0,mic2=0; // declare integer variables mic0,mic1,mic2
//========== Initialization ============
void setup()
{ Serial.begin(9600); // open the serial port at 9600 bps
pinMode(MIC, INPUT); // configure analog pin A2 as an input
}
//========== Main Code ============
void loop()
{ for(int i=0;i<10;i++) // repeat 10 times
{ mic2 = analogRead(MIC); // read MIC output voltage, range 0 to 1023
mic1 += mic2; // accumulate the voltages

3-31
}
if (mic0!=mic1) // if the value is changed,
{ mic0=mic1; // store the value in mic0
mic1=map(mic1,0,1023,0,5000);// scale it for the detector use, range 0 to 5000
Serial.print(mic1); // display the scaled value in Serial Monitor
window
Serial.println(" mV"); // display the “mV” string followed by a CR
and an LF
mic1=0; // reset mic1 to zero, for next detection
}
delay(500); // a delay of 0.5 seconds
}

Compiling and Uploading

5. Once the editing is completed, press + keys to compile your sketch.


If “Error compiling” appears in the console, the message area will show the error
message with line number. If “Done compiling” appears in the console, the
message area will display memory usage for code and variables as follows:

Sketch uses 3,044 bytes (9%) of program storage space. Maximum is 32,256
bytes.

Global variables use 198 bytes (9%) of dynamic memory, leaving 1,850 bytes
for local variables. Maximum is 2,048 bytes.

6. Press + keys to upload the code to the Arduino board.

7. Click the Serial Monitor button on the toolbar or press + +


keys to open the Serial Monitor window.

8. The volume of ambient noise sensed by the microphone should be displayed in


the large area of the serial monitor, in mV.

9. Speak to the microphone. The voltage displayed in the serial monitor window
should be proportional to the volume.

3-32
PROCEDURE E

Digital Voltmeter

In this procedure, you’ll design a digital voltmeter to measure the input voltage from
the wiper of vertical potentiometer (V pot) and show the measured voltage in the
Serial Monitor window.

Circuit Connections

Peform the following steps and refer to the wiring diagram in Fig. 3-11 to complete
the connections for the digital voltmeter:

1. Connect the Arduino Uno board to your computer using the USB cable.

2. Connect a correct AC voltage from a wall outlet to your MTS-100 using the AC
power cord, and then turn on the power.

3. Connect the Arduino pin A2 to the header pin P7-2 (SLIDE POTENTIOMETER).
This makes the vertical potentiometer (V pot) available.

Fig. 3-11 Wiring diagram of digital voltmeter

3-33
Program Design

4. Open the Arduino IDE window. In the text editor, write your sketch as shown
below and save it as “ex3-2-5.ino”. Note: You can omit the program comments to
save time for the actual study of the sketch.

//========== ex3-2-5.ino ============


//========== Global Declaration ============
#define potV A2 // V pot’s wiper connected to analog pin A2
int pot0=0,pot1=0,pot2=0; // declare integer variables pot0, pot1, pot2
//========== Initialization ============
void setup()
{ Serial.begin(9600); // open the serial port at 9600 bps
pinMode(potV, INPUT); // configure analog pin A2 as an input
}
//========== Main Code ============
void loop()
{ for(int i=0;i<10;i++) // read 10 times
{ pot2 = analogRead(potV); // read V pot’s voltage, range 0 to 1023
pot1 += pot2; // accumulate the voltages read
}
pot1 /=10; // pot1 divided by 10, ignore units digit
if (pot0!=pot1) // if the value is changed (new),
{ pot0=pot1; // store the value in pot0
pot1=map(pot1,0,1023,0,5000); // scale it for the voltmeter use, range 0 to
5000
Serial.print(pot1); // display the scaled value on Serial Monitor
window
Serial.println(" mV"); // display the “mV” string followed by a CR
and an LF
pot1=0; // reset pot1 to zero, for next measurement
}
delay(1000); // a delay of 1 second
}

Compiling and Uploading

5. Once the editing is completed, press + keys to compile your sketch.


If “Error compiling” appears in the console, the message area will show the error
message with line number. If “Done compiling” appears in the console, the
message area will display memory usage for code and variables as follows:

3-34
Sketch uses 3,142 bytes (9%) of program storage space. Maximum is 32,256
bytes.

Global variables use 198 bytes (9%) of dynamic memory, leaving 1,850 bytes
for local variables. Maximum is 2,048 bytes.

6. Press + keys to upload the code to the Arduino board.

7. Click the Serial Monitor button on the toolbar or press + +


keys to open the Serial Monitor window.

8. The wiper voltage of V pot (the measured voltage of the voltmeter) should be
displayed in the large area of the serial monitor, in mV. The measured voltages
displayed should vary from minimum to maximum as the V pot moves from
bottom to top.

3-35

Potrebbero piacerti anche