Serial
[Communication]
Description
Used for
communication between the Arduino board and a computer or other devices. All
Arduino boards have at least one serial port (also known as a UART or USART),
and some have several.
On Uno, Nano, Mini, and Mega, pins 0 and 1
are used for communication with the computer. Connecting anything to these pins
can interfere with that communication, including causing failed uploads to the
board.
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.
if(Serial)
Description
Indicates if the
specified Serial port is ready.
On the boards with
native USB, if
(Serial) (or if(SerialUSB) on the Due) indicates
whether or not the USB CDC serial connection is open. For all other boards, and
the non-USB CDC ports, this will always return true.
This was introduced
in Arduino IDE 1.0.1.
Syntax
if
(Serial)
Parameters
Nothing
Returns
bool: returns true if the specified
serial port is available. This will only return false if querying the
Leonardo’s USB CDC serial connection before it is ready.
Example Code
void setup() {
//Initialize serial and wait for port to
open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
Needed for native USB
}
}
void loop() {
//proceed normally
}
Serial.available()
Description
Get the number of bytes (characters)
available for reading from the serial port. This is data that’s already arrived
and stored in the serial receive buffer (which holds 64 bytes).
Serial.available()
inherits
from the Stream utility
class.
Syntax
Serial
.available()
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
Returns
The number of bytes available to read.
Example Code
The following code returns a character
received through the serial port.
int incomingByte =
0;
// for incoming serial data
void
setup() {
Serial.
begin(
9600);
// opens serial port, sets data rate to 9600 bps
}
void
loop() {
// reply only when you receive data:
if (
Serial.
available() >
0) {
// read the incoming byte:
incomingByte =
Serial.
read();
// say what you got:
Serial.
print(
"I received: ");
Serial.
println(incomingByte, DEC);
}
}
Arduino Mega example: This code sends data received in one
serial port of the Arduino Mega to another. This can be used, for example, to
connect a serial device to the computer through the Arduino board.
void
setup() {
Serial.
begin(
9600);
Serial1.
begin(
9600);
}
void
loop() {
// read from port 0, send to port 1:
if (
Serial.
available()) {
int inByte =
Serial.
read();
Serial1.
print(inByte, DEC);
}
// read from port 1, send to port 0:
if (Serial1.
available()) {
int inByte = Serial1.
read();
Serial.
print(inByte, DEC);
}
}
Serial.availableForWrite()
Description
Get the number of bytes (characters)
available for writing in the serial buffer without blocking the write
operation.
Syntax
Serial
.availableForWrite()
Parameters
Serial: serial port object. See the list of available
serial ports for each board on the Serial main page.
Returns
The number of bytes available to write.
Serial.begin()
Description
Sets the data rate in bits per second (baud)
for serial data transmission. For communicating with Serial Monitor, make sure
to use one of the baud rates listed in the menu at the bottom right corner of
its screen. You can, however, specify other rates - for example, to communicate
over pins 0 and 1 with a component that requires a particular baud rate.
An optional second argument configures the
data, parity, and stop bits. The default is 8 data bits, no parity, one stop
bit.
Syntax
Serial
Serial
.begin(speed)
Serial
.begin(speed, config)
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
speed
: in bits per
second (baud) - long
config
: sets data,
parity, and stop bits. Valid values areSERIAL_5N1
SERIAL_6N1
SERIAL_7N1
SERIAL_8N1
(the default)SERIAL_5N2
SERIAL_6N2
SERIAL_7N2
SERIAL_8N2
SERIAL_5E1
SERIAL_6E1
SERIAL_7E1
SERIAL_8E1
SERIAL_5E2
SERIAL_6E2
SERIAL_7E2
SERIAL_8E2
SERIAL_5O1
SERIAL_6O1
SERIAL_7O1
SERIAL_8O1
SERIAL_5O2
SERIAL_6O2
SERIAL_7O2
SERIAL_8O2
Returns
Nothing
Example Code
void
setup() {
Serial.
begin(
9600);
// opens serial port, sets data rate to 9600 bps
}
void
loop() {}
Arduino Mega example:
// Arduino Mega using all four of its Serial ports
// (Serial, Serial1, Serial2, Serial3),
// with different baud rates:
void
setup() {
Serial.
begin(
9600);
Serial1.
begin(
38400);
Serial2.
begin(
19200);
Serial3.
begin(
4800);
Serial.
println(
"Hello Computer");
Serial1.
println(
"Hello Serial 1");
Serial2.
println(
"Hello Serial 2");
Serial3.
println(
"Hello Serial 3");
}
void
loop() {}
Thanks to Jeff Gray for the mega example
Notes and Warnings
For USB CDC serial ports (e.g.
Serial
on the Leonardo), Serial.begin()
is
irrelevant. You can use any baud rate and configuration for serial
communication with these ports. See the list of available serial ports for each
board on the Serial main page.
Serial.end()
Description
Disables serial communication, allowing the
RX and TX pins to be used for general input and output. To re-enable serial
communication, call Serial.begin().
Syntax
Serial
.end()
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
Returns
Nothing
Serial.find()
Description
Serial.find() reads data from the serial
buffer until the target is found. The function returns true if target is found,
false if it times out.
Serial.find() inherits from the stream utility
class.
Syntax
Serial
Serial
.find(target)
Serial
.find(target, length)
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
target
: the
string to search for (char)length
:
length of the target (size_t)
Returns
Bool
Serial.parseFloat()
Description
Serial.parseFloat()
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. The
function terminates if it times out (see Serial.setTimeout()).Serial.parseFloat()
inherits
from the Stream utility
class.
Syntax
Serial
.parseFloat()
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
Returns
Float
Serial.parseInt()
Description
Looks for the next valid integer in the
incoming serial. The function terminates if it times out (see Serial.setTimeout()).
Serial.parseInt()
inherits
from the Stream utility
class.
In particular:
·
Initial
characters that are not digits or a minus sign, are skipped;
·
Parsing stops
when no characters have been read for a configurable time-out value, or a
non-digit is read;
·
If no valid
digits were read when the time-out (see Serial.setTimeout()) occurs, 0 is
returned;
Syntax
Serial
Serial
.parseInt()
Serial
.parseInt(char skipChar)
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
skipChar
: used to
skip the indicated char in the search. Used for example to skip thousands
divider.
Returns
long
: the next
valid integer
Serial.peek()
Description
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()
.Serial.peek()
inherits
from the Stream utility
class.
Syntax
Serial
.peek()
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
Returns
The first byte of incoming serial data
available (or -1 if no data is available) –
int
Serial.print()
Description
Prints data to the serial port as
human-readable ASCII text. This command can take many forms. Numbers are
printed using an ASCII 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. For example-
·
Serial.print(78)
gives
"78"
·
Serial.print(1.23456)
gives
"1.23"
·
Serial.print('N')
gives
"N"
·
Serial.print("Hello world.")
gives "Hello world."
An optional second parameter 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)
. For
floating point numbers, this parameter specifies the number of decimal places
to use. For example-
·
Serial.print(78, BIN)
gives
"1001110"
·
Serial.print(78, OCT)
gives
"116"
·
Serial.print(78, DEC)
gives
"78"
·
Serial.print(78, HEX)
gives
"4E"
·
Serial.print(1.23456, 0)
gives "1"
·
Serial.print(1.23456, 2)
gives "1.23"
·
Serial.print(1.23456, 4)
gives "1.2346"
You can pass flash-memory based strings to
Serial.print() by wrapping them with F(). For
example:
Serial.print(F(“Hello World”))
To send data without conversion to its
representation as characters, use Serial.write().
Syntax
Serial
Serial
.print(val)
Serial
.print(val, format)
Parameters
Serial: serial port object. See the list of available
serial ports for each board on the Serial main page.
val
: the value
to print - any data type
Returns
size_t
: print()
returns
the number of bytes written, though reading that number is optional.
Example Code
/*
Uses a for loop to print numbers in various formats.
*/
void
setup() {
Serial.
begin(
9600);
// open the serial port at 9600 bps:
}
void
loop() {
// print labels
Serial.
print(
"NO FORMAT");
// prints a label
Serial.
print(
"\t");
// prints a tab
Serial.
print(
"DEC");
Serial.
print(
"\t");
Serial.
print(
"HEX");
Serial.
print(
"\t");
Serial.
print(
"OCT");
Serial.
print(
"\t");
Serial.
print(
"BIN");
Serial.
println();
// carriage return after the last label
for (
int x =
0; x <
64; x++) {
// only part of the ASCII chart, change to suit
// print it out in many formats:
Serial.
print(x);
// print as an ASCII-encoded decimal - same as "DEC"
Serial.
print(
"\t\t");
// prints two tabs to accomodate the label lenght
Serial.
print(x, DEC);
// print as an ASCII-encoded decimal
Serial.
print(
"\t");
// prints a tab
Serial.
print(x, HEX);
// print as an ASCII-encoded hexadecimal
Serial.
print(
"\t");
// prints a tab
Serial.
print(x, OCT);
// print as an ASCII-encoded octal
Serial.
print(
"\t");
// prints a tab
Serial.
println(x, BIN);
// print as an ASCII-encoded binary
// then adds the carriage return with "println"
delay(
200);
// delay 200 milliseconds
}
Serial.
println();
// prints another carriage return
}
Notes and Warnings
For information on the asyncronicity
of
Serial.print()
, see the Notes and Warnings section of
the Serial.write() reference page.
Serial.println()
Description
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 command takes the same
forms as Serial.print().
Syntax
Serial
Serial
.println(val)
Serial
.println(val, format)
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
val
: the value
to print - any data typeformat
: specifies
the number base (for integral data types) or number of decimal places (for
floating point types)
Returns
size_t
: println()
returns
the number of bytes written, though reading that number is optional
Example Code
/*
Analog input reads an analog input on analog in 0, prints the value out.
created 24 March 2006
by Tom Igoe
*/
int analogValue =
0;
// variable to hold the analog value
void
setup() {
// open the serial port at 9600 bps:
Serial.
begin(
9600);
}
void
loop() {
// read the analog input on pin 0:
analogValue =
analogRead(
0);
// print it out in many formats:
Serial.
println(analogValue);
// print as an ASCII-encoded decimal
Serial.
println(analogValue, DEC);
// print as an ASCII-encoded decimal
Serial.
println(analogValue, HEX);
// print as an ASCII-encoded hexadecimal
Serial.
println(analogValue, OCT);
// print as an ASCII-encoded octal
Serial.
println(analogValue, BIN);
// print as an ASCII-encoded binary
// delay 10 milliseconds before the next reading:
delay(
10);
}
Notes and Warnings
For information on the asyncronicity
of
Serial.println()
, see the Notes and Warnings section of
the Serial.write() reference page.
Serial.read()
Description
Reads incoming serial data.
Serial.read()
inherits
from the Stream utility
class.
Syntax
Serial
.read()
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
Returns
The first byte of incoming serial data
available (or -1 if no data is available) -
int
.
Example Code
int incomingByte =
0;
// for incoming serial data
void
setup() {
Serial.
begin(
9600);
// opens serial port, sets data rate to 9600 bps
}
void
loop() {
// send data only when you receive data:
if (
Serial.
available() >
0) {
// read the incoming byte:
incomingByte =
Serial.
read();
// say what you got:
Serial.
print(
"I received: ");
Serial.
println(incomingByte, DEC);
}
}
Serial.readBytes()
Description
Serial.readBytes()
reads
characters from the serial port into a buffer. The function terminates if the determined
length has been read, or it times out (see Serial.setTimeout()).Serial.readBytes()
returns
the number of characters placed in the buffer. A 0 means no valid data was
found.Serial.readBytes()
inherits
from the Stream utility
class.
Syntax
Serial
.readBytes(buffer, length)
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
buffer
: the buffer to
store the bytes in (char[]
or byte[]
)length
: the number
of bytes to read (int
)
Returns
The number of bytes placed in the buffer (
size_t
)
Serial.readBytesUntil()
Description
Serial.readBytesUntil() 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
(see Serial.setTimeout()). The function returns the characters up to
the last character before the supplied terminator. The terminator itself is not
returned in the buffer.
Serial.readBytesUntil()
returns the number of characters read
into the buffer. A 0 means no valid data was found.Serial.readBytesUntil()
inherits from the Stream utility
class.
Syntax
Serial
.readBytesUntil(character, buffer, length)
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
character
: the
character to search for (char
)buffer
: the buffer
to store the bytes in (char[]
or byte[]
)length
: the
number of bytes to read (int
)
Returns
size_t
Notes and Warnings
The terminator character is discarded from
the serial buffer.
Serial.readString()
Description
Serial.readString()
reads
characters from the serial buffer into a String. The function terminates if it
times out (see setTimeout()).Serial.readString()
inherits
from the Stream utility
class.
Syntax
Serial
.readString()
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
Returns
A String read from the serial buffer
Serial.readStringUntil()
Description
readStringUntil()
reads
characters from the serial buffer into a String. The function terminates if it
times out (see setTimeout()).Serial.readStringUntil()
inherits from the Stream utility
class.
Syntax
Serial
.readStringUntil(terminator)
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
terminator
: the
character to search for (char
)
Returns
The entire String read from the serial
buffer, up to the terminator character
Notes and Warnings
The terminator character is discarded from
the serial buffer.
Serial.setTimeout()
Description
Serial.setTimeout()
sets
the maximum milliseconds to wait for serial data. It defaults to 1000
milliseconds.Serial.setTimeout()
inherits
from the Stream utility
class.
Syntax
Serial
.setTimeout(time)
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
time
:
timeout duration in milliseconds (long
).
Returns
Nothing
Serial.write()
Description
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
Serial
Serial
.write(val)
Serial
.write(str)
Serial
.write(buf, len)
Parameters
Serial: serial port object. See the list of
available serial ports for each board on the Serial main page.
val
: a value to
send as a single bytestr
: a string to
send as a series of bytesbuf
: an array to
send as a series of byteslen
: the number
of bytes to be sent from the array
Returns
size_t
write()
will
return the number of bytes written, though reading that number is optional
Example Code
void
setup() {
Serial.
begin(
9600);
}
void
loop() {
Serial.
write(
45);
// send a byte with the value 45
int bytesSent =
Serial.
write(“hello”);
//send the string “hello” and return the length of the string.
}
Notes and Warnings
As of Arduino IDE 1.0, serial transmission
is asynchronous. If there is enough empty space in the transmit buffer,
Serial.write()
will
return before any characters are transmitted over serial. If the transmit
buffer is full then Serial.write()
will block until there is enough space
in the buffer. To avoid blocking calls to Serial.write()
, you can
first check the amount of free space in the transmit buffer using availableForWrite().
serialEvent()
Description
Called when data is available. Use
Serial.read()
to
capture this data.
Syntax
void
serialEvent() {
//statements
}
For boards with additional serial ports (see
the list of available serial ports for each board on the Serial main page):
void serialEvent1() {
//statements
}
void serialEvent2() {
//statements
}
void serialEvent3() {
//statements
}
Parameters
statements
: any valid
statements
Returns
Nothing
Notes and Warnings
serialEvent()
doesn’t
work on the Leonardo, Micro, or Yún.serialEvent()
and serialEvent1()
don’t
work on the Arduino SAMD BoardsserialEvent()
, serialEvent1()``serialEvent2()
, and serialEvent3()
don’t
work on the Arduino Due.Example 1:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
while(!Serial)
{
}
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available () > 0 )
{
char gelen = Serial.read();
Serial.println(gelen);
}
}
Example 2:
int sayi;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
while(!Serial)
{
}
}
Example 3:
int sayi1;
int sayi2;
int toplam;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
while(!Serial)
{
}
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0)
{
sayi1 = Serial.read ();
delay(1000);
sayi2 = Serial.read ();
toplam = sayi1 + sayi2;
Serial.println(toplam);
}
delay(1000);
}
Example 3:
int sayi1;
int sayi2;
int toplam;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
while(!Serial)
{
}
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0)
{
sayi1 = Serial.read ();
delay(1000);
sayi2 = Serial.read ();
toplam = (sayi1-48) + (sayi2-48);
Serial.println(toplam);
}
delay(1000);
}
Example 4:
String isim;
int yas;
float boy;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("isminizi giriniz ");
while (Serial.available()==0) {
// döngü boşuna döner
}
isim=Serial.readString();
Serial.println("Merhaba, kaç yaşındasınız?");
while (Serial.available()==0) {
// döngü boşuna döner
}
yas=Serial.parseInt();
Serial.println("Boyunuz kaçtır? ");
while (Serial.available()==0) {
// döngü boşuna döner
}
boy=Serial.parseFloat();
Serial.print("Merhaba ");
Serial.print(isim);
Serial.print(", siz ");
Serial.print(yas);
Serial.println(" yaşındasınız,");
Serial.print("ve boyunuz ");
Serial.print(boy);
Serial.println(" cm.");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0)
{
sayi = Serial.read ();
sayi = sayi - 48;
Serial.println(sayi);
}
delay(1000);
}
int redLEDPin=9; //Declare redLEDPin an
int, and set to pin 9
int yellowLEDPin=10; //Declare
yellowLEDPin an int, and set to pin 10
int redOnTime=250; //Declare redOnTime an
int, and set to 250 mseconds
int redOffTime=250; //Declare redOffTime
an int, and set to 250
int yellowOnTime=250; //Declare
yellowOnTime an int, and set to 250
int yellowOffTime=250; //Declare
yellowOffTime an int, and set to 250
int numYellowBlinks; //Number of times to
blink yellow LED
int numRedBlinks; //Number of
times to blink red LED
String redMessage="The Red LED is
Blinking"; //Declaring a String Variable
String yellowMessage= "The Yellow LED
is Blinking"; //Declaring a String Variable
void setup() {
Serial.begin(115200); //
Turn on the Serial Port
pinMode(redLEDPin, OUTPUT); //
Tell Arduino that redLEDPin is an output pin
pinMode(yellowLEDPin, OUTPUT); //Tell
Arduino that yellowLEDPin is an output pin
Serial.println("How Many
Times Do You Want the Red LED to Blink? "); //Prompt User for Input
while (Serial.available()==0){
} //Wait for User Input
numRedBlinks = Serial.parseInt();
//Read User Input
Serial.println("How Many
Times Do You Want the Yellow LED to Blink? "); //Prompt User for Input
while (Serial.available()==0){
} //Wait for Input
numYellowBlinks = Serial.parseInt();
//Read User Input
}
void loop() {
Serial.println(redMessage);
for (int j=1; j<=numRedBlinks;
j=j+1) { // Start our for loop
Serial.print("
You are on Blink #: ");
Serial.println(j);
digitalWrite(redLEDPin,HIGH);
//Turn red LED on
delay(redOnTime);
//Leave on for redOnTime
digitalWrite(redLEDPin,LOW); //Turn
red LED off
delay(redOffTime); //Leave
off for redOffTime
}
Serial.println(" ");
Serial.println(yellowMessage);
for (int j=1; j<=numYellowBlinks;
j=j+1) { // Start our for loop
Serial.print("
You are on Blink #: ");
Serial.println(j);
digitalWrite(yellowLEDPin,HIGH);
//Turn yellow LED on
delay(yellowOnTime);
//Leave on for yellowOnTime
digitalWrite(yellowLEDPin,LOW); //Turn
yellow LED off
delay(yellowOffTime); //Leave
off for yellowOffTime
}
Serial.println(" ");
}
Hiç yorum yok:
Yorum Gönder