Arduino串口笔记

Serial笔记

用于控制板和一台计算机或其他设备之间的通信。所有的控制板有至少一个串口(又称作为UART或USART)。它通过0(RX)和1(TX)数字引脚经过串口转换芯片连接计算机USB端口与计算机进行通信。因此,如果你使用这些功能的同时你不能使用引脚0和1作为输入或输出。

Mega2560 有三个额外的串口:Serial 1使用19(RX)和18(TX),Serial 2使用17(RX)和16(TX),Serial3使用15(RX)和14(TX)。

串口、COM口是指的物理接口形式(硬件)。而TTL、RS-232、RS-485是指的电平标准(电信号)

TTL串口设备 TTL标准是低电平为0,高电平为1(+5V电平)

高电平3.6~5V,

低电平0V~2.4V

RS232串口; 标准是正电平为0,负电平为1

-15v ~ -3v 代表1

+3v ~ +15v 代表0

Serial 1通过0(RX)和1(TX)

将TX引脚连接到您的设备的RX引脚,将RX引脚连接到您的设备的TX引脚

内置的串口监视器:点击工具栏上的串口监视器按钮

调用begin()函数(选择相同的波特率)。

函数

if (Serial)

指定的串口是否准备好

available()

获取已经传输到,并存储在串行接收缓冲区(能够存储64个字节)的数据的有效的字节数(字符)。

begin()

设置串行数据传输速率 位/秒(波特)

end()

停用串行通信,使RXTX引脚用于一般输入和输出。要重新使用串行通信, 需要 Serial.begin()语句。

find()

Serial.find(target)从串行缓冲器中读取数据,直到发现给定长度的目标字符串。如果找到目标字符串,该函数返回true,如果超时则返回false

findUntil()

从串行缓冲区读取数据,直到找到一个给定的长度或字符串终止位。

flush()

等待超出的串行数据完成传输。(不再是丢弃所有进入缓存器的串行数据。)

parseFloat()

从串口缓冲区返回第一个有效的浮点数

parseInt()

查找传入的串行数据流中的下一个有效的整数

peek()

返回传入的串行数据的下一个字节(字符),而不是进入内部串行缓冲器调取。也就是说,连续调用 peek()将返回相同的字符,与调用read()方法相同。

print()

以人们可读的ASCII文本形式打印数据到串口输出

println()

输出人们可识别的ASCII码文本并回车 (ASCII 13, 或 '\r') 及换行(ASCII 10, 或 '\n')

read()

读取传入的串口的数据,返回传入的串口数据的第一个字节(或-1,如果没有可用的数据)

readBytes()

从串口读字符到一个缓冲区

readBytesUntil()

将字符从串行缓冲区读取到一个数组,直到检测到终止字符,或预设的读取长度读取完毕,或者时间到了

setTimeout()

设置使用Serial.readBytesUntil() Serial.readBytes()时等待串口数据的最大毫秒值. 默认为1000毫秒

write()

写入二制数据到串口。发送的数据以一个字节或者一系列的字节为单位。如果写入的数字为字符,需使用print()命令进行代替。

SerialEvent()

在数据可用时调用,使用Serial.read()来捕获这些数据。注:目前的serialEvent()不与ATMEGA32U4核心兼容。

示例

文件 示例 \examples\04.Communication

Graph

void setup() {

// initialize the serial communication:

Serial.begin(9600);

}

void loop() {

// send the value of analog input 0:

Serial.println(analogRead(A0));

// wait a bit for the analog-to-digital converter

// to stabilize after the last reading:

delay(2);

}

Physical Pixel

const int ledPin = 13; // the pin that the LED is attached to

int incomingByte; // a variable to read incoming serial data into

void setup() {

// initialize serial communication:

Serial.begin(9600);

// initialize the LED pin as an output:

pinMode(ledPin, OUTPUT);

}

void loop() {

// see if there's incoming serial data:

if (Serial.available() > 0) {

// read the oldest byte in the serial buffer:

incomingByte = Serial.read();

// if it's a capital H (ASCII 72), turn on the LED:

if (incomingByte == 'H') {

digitalWrite(ledPin, HIGH);

}

// if it's an L (ASCII 76) turn off the LED:

if (incomingByte == 'L') {

digitalWrite(ledPin, LOW);

}

}

}

Dimmer

const int ledPin = 9; // the pin that the LED is attached to

void setup() {

// initialize the serial communication:

Serial.begin(9600);

// initialize the ledPin as an output:

pinMode(ledPin, OUTPUT);

}

void loop() {

byte brightness;

// check if data has been sent from the computer:

if (Serial.available()) {

// read the most recent byte (which will be from 0 to 255):

brightness = Serial.read();

// set the brightness of the LED:

analogWrite(ledPin, brightness);

}

}

Virtual Color Mixer

const int redPin = A0;        // sensor to control red color

const int greenPin = A1;    // sensor to control green color

const int bluePin = A2;        // sensor to control blue color

void setup() {

Serial.begin(9600);

}

void loop() {

Serial.print(analogRead(redPin));

Serial.print(",");

Serial.print(analogRead(greenPin));

Serial.print(",");

Serial.println(analogRead(bluePin));

}

ReadASCIIString

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

}

}

}

ASCII Table

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 port only

}

// prints title with ending line break

Serial.println("ASCII Table ~ Character Map");

}

// first visible ASCIIcharacter '!' is number 33:

int thisByte = 33;

// you can also write ASCII characters in single quotes.

// for example. '!' is the same as 33, so you could also use this:

//int thisByte = '!';

void loop() {

// prints value unaltered, i.e. the raw binary version of the

// byte. The serial monitor interprets all bytes as

// ASCII, so 33, the first number, will show up as '!'

Serial.write(thisByte);

Serial.print(", dec: ");

// prints value as string as an ASCII-encoded decimal (base 10).

// Decimal is the default format for Serial.print() and Serial.println(),

// so no modifier is needed:

Serial.print(thisByte);

// But you can declare the modifier for decimal if you want to.

//this also works if you uncomment it:

// Serial.print(thisByte, DEC);

Serial.print(", hex: ");

// prints value as string in hexadecimal (base 16):

Serial.print(thisByte, HEX);

Serial.print(", oct: ");

// prints value as string in octal (base 8);

Serial.print(thisByte, OCT);

Serial.print(", bin: ");

// prints value as string in binary (base 2)

// also prints ending line break:

Serial.println(thisByte, BIN);

// if printed last visible character '~' or 126, stop:

if (thisByte == 126) { // you could also use if (thisByte == '~') {

// This loop loops forever and does nothing

while (true) {

continue;

}

}

// go on to the next character

thisByte++;

}

Serial Call Response

int firstSensor = 0; // first analog sensor

int secondSensor = 0; // second analog sensor

int thirdSensor = 0; // digital sensor

int inByte = 0; // incoming serial byte

void setup() {

// start serial port at 9600 bps:

Serial.begin(9600);

while (!Serial) {

; // wait for serial port to connect. Needed for native USB port only

}

pinMode(2, INPUT); // digital sensor is on digital pin 2

establishContact(); // send a byte to establish contact until receiver responds

}

void loop() {

// if we get a valid byte, read analog ins:

if (Serial.available() > 0) {

// get incoming byte:

inByte = Serial.read();

// read first analog input, divide by 4 to make the range 0-255:

firstSensor = analogRead(A0) / 4;

// delay 10ms to let the ADC recover:

delay(10);

// read second analog input, divide by 4 to make the range 0-255:

secondSensor = analogRead(1) / 4;

// read switch, map it to 0 or 255L

thirdSensor = map(digitalRead(2), 0, 1, 0, 255);

// send sensor values:

Serial.write(firstSensor);

Serial.write(secondSensor);

Serial.write(thirdSensor);

}

}

void establishContact() {

while (Serial.available() <= 0) {

Serial.print('A'); // send a capital A

delay(300);

}

}

Serial Call Response ASCII

int firstSensor = 0; // first analog sensor

int secondSensor = 0; // second analog sensor

int thirdSensor = 0; // digital sensor

int inByte = 0; // incoming serial byte

void setup() {

// start serial port at 9600 bps and wait for port to open:

Serial.begin(9600);

while (!Serial) {

; // wait for serial port to connect. Needed for native USB port only

}

pinMode(2, INPUT); // digital sensor is on digital pin 2

establishContact(); // send a byte to establish contact until receiver responds

}

void loop() {

// if we get a valid byte, read analog ins:

if (Serial.available() > 0) {

// get incoming byte:

inByte = Serial.read();

// read first analog input:

firstSensor = analogRead(A0);

// read second analog input:

secondSensor = analogRead(A1);

// read switch, map it to 0 or 255L

thirdSensor = map(digitalRead(2), 0, 1, 0, 255);

// send sensor values:

Serial.print(firstSensor);

Serial.print(",");

Serial.print(secondSensor);

Serial.print(",");

Serial.println(thirdSensor);

}

}

void establishContact() {

while (Serial.available() <= 0) {

Serial.println("0,0,0"); // send an initial string

delay(300);

}

}

constrain

constrain(x, a, b)

Description

Constrains a number to be within a range.

Parameters

x: the number to constrain, all data types

a: the lower end of the range, all data types

b: the upper end of the range, all data types

Returns

x: if x is between a and b

a: if x is less than a

b: if x is greater than b

weinxin
灵智科教
这是我的微信扫一扫
avatar