通信接口

[2016.05.04]Arduino串口从基础到高级最全面教程

字号+ 作者:duino123.com 来源:未知 2016-05-05 14:14 我要评论( )

串口通信是学习arduino最重要的一部分,不管是与计算机还是与ESP8266,蓝牙,GPS,GSM等设备,都离不开串口。

PLCLIVE.COM注:
本文译自arduino官网,从基础到高级用法,最全面的介绍了arduino串口。后续会全文翻译,敬请期待。。。



Arduino通过串口可以方便的与计算机及其他外部设备进行通讯,所有的Arduino控制板都配置至少一个串口(UART/USART),利用数字管脚0(RX)和管脚1(TX)与计算机的USB口进行连接。当使用串口功能的时候,这两个管脚将不能用作数字量输入输出。

官方IDE已经内置串口监控,使用的时候要将波特率与begin()中的波特率修改一致。

Arduino Mega比UNO多配置了3个串口:Serial1(管脚19-RX,管脚18-TX),Serial2(管脚17-RX,管脚16-TX),Serial3(管脚15-RX,管脚14-TX),使用这些管脚与计算机进行串口通讯的时候,需要额外配置USB转串口模块;与外部TTL设备进行通讯的时候只需将TX连接设备RX管脚,RX连接设备TX管脚,GND与设备GND连接即共地。由于RS232的工作电压为+/-12V,切勿将这些管脚与RS232串口直接连接!切勿将这些管脚与RS232串口直接连接!切勿将这些管脚与RS232串口直接连接!否则将烧毁Arduino控制板。重要的事情说三遍!

 


if (Serial)

Description

Indicates if the specified Serial port is ready.

On 32u4 based boards (Leonardo, Yùn, ecc) , if (Serial) indicates wether or not the USB CDC serial connection is open. For all other instances, including if (Serial1) on the Leonardo, this will always returns true.

This was introduced in Arduino 1.0.1.

Syntax

All boards:
if (Serial)

Arduino Leonardo specific: 
if (Serial1) 
Arduino Mega specific: 
if (Serial1) 
if (Serial2) 
if (Serial3)

Parameters

none

Returns

boolean : 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:

 


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
}

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). available() inherits from the Stream utility class.

Syntax

Serial.available()

Arduino Mega only: 
Serial1.available() 
Serial2.available() 
Serial3.available()

Parameters

none

Returns

the number of bytes available to read

Example

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);
        }
}

availableForWrite()

Description

Get the number of bytes (characters) available for writing in the serial buffer without blocking the write operation.

Syntax

Serial.availableForWrite()

Arduino Mega only: 
Serial1.availableForWrite() 
Serial2.availableForWrite() 
Serial3.availableForWrite()

Parameters

none

Returns

the number of bytes available to write
 


begin()

Description

Sets the data rate in bits per second (baud) for serial data transmission. For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200. 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.begin(speed)
Serial.begin(speed, config)

Arduino Mega only: 
Serial1.begin(speed) 
Serial2.begin(speed) 
Serial3.begin(speed) 
Serial1.begin(speed, config) 
Serial2.begin(speed, config) 
Serial3.begin(speed, config)

Parameters

speed: in bits per second (baud) - long
config: sets data, parity, and stop bits. Valid values are :

  • SERIAL_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:

 

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() {}


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(). peek() inherits from theStream utility class.

Syntax

Serial.peek()

Arduino Mega only: 
Serial1.peek() 
Serial2.peek() 
Serial3.peek()

Parameters

None

Returns

the first byte of incoming serial data available (or -1 if no data is available) - int


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.println(1.23456, 0) gives "1"
  • Serial.println(1.23456, 2) gives "1.23"
  • Serial.println(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 a single byte, use Serial.write().

Syntax

Serial.print(val) 
Serial.print(val, format)

Parameters

val: the value to print - any data type

format: specifies the number base (for integral data types) or number of decimal places (for floating point types)

Returns

size_t (long): print() returns the number of bytes written, though reading that number is optional

Example:

 

/*
Uses a FOR loop for data and prints a number in various formats.
*/

int x = 0;    // variable

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.print("\t"); 

  for(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");    // prints a tab

    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
}

 

Programming Tips

As of version 1.0, serial transmission is asynchronous; Serial.print() will return before any characters are transmitted.


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.println(val) 
Serial.println(val, format)

Parameters

val: the value to print - any data type

format: specifies the number base (for integral data types) or number of decimal places (for floating point types)

Returns

size_t (long): println() returns the number of bytes written, though reading that number is optional

Example:

 


/*
  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);
}

 


read()

Description

Reads incoming serial data. read() inherits from the Stream utility class.

Syntax

Serial.read()

Arduino Mega only: 
Serial1.read() 
Serial2.read() 
Serial3.read()

Parameters

None

Returns

the first byte of incoming serial data available (or -1 if no data is available) - int

Example

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

buffer: the buffer to store the bytes in (char[] or byte[])
length : the number of bytes to read (int)

Returns

byte


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()).

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(characterbufferlength)

Parameters

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

byte


readString()

Description

Serial.readString() reads characters from the serial buffer into a string. The function terminates if it times out (seesetTimeout()).

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See theStream class main page for more information.

Syntax

Serial.readString()

Parameters

none

Returns

A string read from the serial buffer
 


readStringUntil()

Description

readStringUntil() reads characters from the serial buffer into a string. The function terminates if the terminator character is detected or it times out (see setTimeout()).

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See theStream class main page for more information.

Syntax

Serial.readStringUntil(terminator)

Parameters

terminator : the character to search for (char)

Returns

The entire string read from the serial buffer, until the terminator character is detected
 


 


 

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.write(val) 
Serial.write(str) 
Serial.write(buf, len)

Arduino Mega also supports: Serial1, Serial2, Serial3 (in place of Serial)

Parameters

val: a value to send as a single byte

str: a string to send as a series of bytes

buf: an array to send as a series of bytes

len: the length of the buffer

Returns

byte
write() will return the number of bytes written, though reading that number is optional

Example

 

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.
}

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()

Arduino Mega only: 
Serial1.end() 
Serial2.end() 
Serial3.end()

Parameters

none

Returns

nothing
 


Serial.find()

Description

Serial.find() 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.

Serial.find() inherits from the Stream utility class.

Syntax

Serial.find(target)

Parameters

target : the string to search for (char)

Returns

boolean
 


Serial.findUntil()

Description

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

The function returns true if the target string is found, false if it times out.

Serial.findUntil() inherits from the Stream utility class.

Syntax

Serial.findUntil(targetterminal)

Parameters

target : the string to search for (char)
terminal : the terminal string in the search (char)

Returns

boolean
 


flush()

Description

Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)

flush() inherits from the Stream utility class.

Syntax

Serial.flush()

Arduino Mega only: 
Serial1.flush() 
Serial2.flush() 
Serial3.flush()

Parameters

none

Returns

nothing
 


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.

Serial.parseFloat() inherits from the Stream utility class.

Syntax

Serial.parseFloat()

Parameters

none

Returns

float
 


parseInt()

Description

Looks for the next valid integer in the incoming serial stream. 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.parseInt()

Serial.parseInt(char skipChar)

Arduino Mega only: 
Serial1.parseInt() 
Serial2.parseInt() 
Serial3.parseInt()

Parameters

skipChar: used to skip the indicated char in the search. Used for example to skip thousands divider.

Returns

long : the next valid integer
 


serialEvent()

Description

Called when data is available. Use Serial.read() to capture this data.

NB : Currently, serialEvent() is not compatible with the Esplora, Leonardo, or Micro

Syntax

 


void serialEvent(){
//statements
}

 

Arduino Mega only:

void serialEvent1(){
//statements
}

void serialEvent2(){
//statements
}

void serialEvent3(){
//statements
}

 

Parameters

statements: any valid statements
 


Serial.setTimeout()

Description

Serial.setTimeout() sets the maximum milliseconds to wait for serial data when using Serial.readBytesUntil(),Serial.readBytes(), Serial.parseInt() or Serial.parseFloat(). It defaults to 1000 milliseconds.

Serial.setTimeout() inherits from the Stream utility class.

Syntax

Serial.setTimeout(time)

Parameters

time : timeout duration in milliseconds (long).

Parameters

None

 


应用举例:Read ASCII String

This sketch uses the Serial.parseInt() function to locate values separated by a non-alphanumeric character. Often people use a comma to indicate different pieces of information (this format is commonly referred to as comma-separated-values or CSV), but other characters like a space or a period will work too. The values are parsed into integers and used to determine the color of a RGB LED. You'll use the Arduino Software (IDE) serial monitor to send strings like "5,220,70" to the board to change the light color.

Hardware Required

  • Arduino or Genuino Board
  • common anode RGB LED
  • 3 220 ohm resistors
  • hook-up wires
  • breadboard

Circuit

Schematic

You'll need four wires to make the circuit above. A wire connects the 5V from the POWER connector of the board to the longest pin of the RGB LED. You should turn the LED so that the longest pin is the second from the left..

Place the RGB LED on your breadboard with the longest pin as the second from the top. Check the datasheet for your specific LED to verify the pins, but they should be R, V+, G and B. The wire from 5V should therefore connect that second pin from top, as in the connection scheme above.

With your remaining wires, connect your red cathode to pin 3, green cathode to pin 5, and blue cathode to pin 6 in series with the resistors.

RGB LEDs with a common anode share a common power pin. Instead of turning a pin HIGH to illuminate the LED, you need to turn the pin LOW, to create a voltage difference across the diode. So sending 255 via analogWrite() turns the LED off, while a value of 0 turns it on at full brightness. In the code below, you'll use a little bit of math on the sketch side, so you can send values which correspond to the expected brightness. Essentially, instead of using analogWrite(pin, brightness), you'll be calling analogWrite(pin, 255-brightness).

Code

You'll first set up some global variables for the pins your LED will connect to. This will make it easier to differentiate which one is red, green, and blue in the main part of your program:

const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;

In your setup(), begin serial communication at 9600 bits of data per second between the board and your computer with the line:

Serial.begin(9600);

Also in the setup, you'll want to configure the pins as outputs:

pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);

In the loop(), check to see if there is any data in the serial buffer. By making this a while() statement, it will run as long as there is information waiting to be read :

while (Serial.available() > 0) {

Next, declare some local variables for storing the serial information. This will be the brightness of the LEDs. UsingSerial.parseInt() to separate the data by commas, read the information into your variables:

int red = Serial.parseInt();
int green = Serial.parseInt();
int blue = Serial.parseInt();

Once you've read the data into your variables, check for the newline character to proceed:

 if (Serial.read() == '\n') {

Using constrain(), you can keep the values in an acceptable range for PWM control. This way, if the value was outside the range of what PWM can send, it will be limited to a valid number. By subtracting this value from 255 you will be formatting the value to use with a common anode LED. As explained above, these LEDs will illuminate when there is a voltage difference between the anode and the pin connected to the board:

red = 255 - constrain(red, 0, 255);
green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255);

Now that you have formatted the values for PWM, use analogWrite() to change the color of the LED. Because you subtracted your value from 255 in the step above:

analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);

Send the value of each LED back to the serial monitor in one string as HEX values :

Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);

Finally, close up your brackets from the if statement, while statement, and main loop :

    }
  }
}

Once you have programmed the board, open your Arduino Software (IDE) serial monitor. Make sure you have chosen to send a newline character when sending a message. Enter values between 0-255 for the lights in the following format : Red,Green,Blue. Once you have sent the values to the board, the attached LED will turn into the color you specified and you will receive back the HEX values in the serial monitor.

 

/*
  Reading a serial ASCII-encoded string.

 This sketch demonstrates the Serial parseInt() function.
 It looks for an ASCII string of comma-separated values.
 It parses them into ints, and uses those to fade an RGB LED.

 Circuit: Common-Cathode RGB LED wired like so:
 * Red anode: digital pin 3
 * Green anode: digital pin 5
 * Blue anode: digital pin 6
 * Cathode : GND

 created 13 Apr 2012
 by Tom Igoe
 
 modified 14 Mar 2016
 by Arturo Guadalupi

 This example code is in the public domain.
 */


// pins for the LEDs:
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // make the pins outputs:
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);

}

void loop() {
  // if there's any serial available, read it:
  while (Serial.available() > 0) {

    // look for the next valid integer in the incoming serial stream:
    int red = Serial.parseInt();
    // do it again:
    int green = Serial.parseInt();
    // do it again:
    int blue = Serial.parseInt();

    // look for the newline. That's the end of your
    // sentence:
    if (Serial.read() == '\n') {
      // constrain the values to 0 - 255 and invert
      // if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
      red = 255 - constrain(red, 0, 255);
      green = 255 - constrain(green, 0, 255);
      blue = 255 - constrain(blue, 0, 255);

      // fade the red, green, and blue legs of the LED:
      analogWrite(redPin, red);
      analogWrite(greenPin, green);
      analogWrite(bluePin, blue);

      // print the three numbers in one string as hexadecimal:
      Serial.print(red, HEX);
      Serial.print(green, HEX);
      Serial.println(blue, HEX);
    }
  }
}






如需更详细资料,如有好资源分享,请加入QQ交流群:214461008

欢迎阅读,欢迎转载,不用注明出处!本站只提供入门和进阶资料,做您学习的小伙伴!

老司机也欢迎光临指导!有好内容请加群:214461008 不要看声明了,看内容吧!

相关文章
  • Arduino软串口的使用

    Arduino软串口的使用

    2016-05-04 15:27

  • 手机APP通过蓝牙控制Arduino上的通讯实验及完整例程

    手机APP通过蓝牙控制Arduino上的通讯实验及完整例程

    2016-05-02 22:13

  • Arduino串口高级用法

    Arduino串口高级用法

    2016-05-17 09:24

  • FT232RL编程器与Arduino ATMEGA328的连接和程序上传

    FT232RL编程器与Arduino ATMEGA328的连接和程序上传

    2016-04-28 17:13

网友点评
Arduino