Arduino中串口通信是通过HardwareSerial类来实现的,在头文件HardwareSerial.h中定义了一个HardwareSerial类的对象Serial,直接使用类的成员函数就可简单地实现串口通信。对象和类的概念与应用可参阅6.1节内容。下面以一个串口调光器的程序为例介绍HardwareSerial类几个较常用的公有成员函数,程序清单如下:
/*
Dimmer(调光器)
通过计算机发送数据控制LED灯的亮度,单字节数据发送,数据范围0~255
使用具有pwm功能的9号引脚
created 2006
by David A. Mellis
modified 14 Apr 2009
by Tom Igoe and Scott Fitzgerald
This example code is in the public domain.
*/
const int ledPin = 9; // the pin that the LED is attached to
void setup()
{
// 设置串口波特率:
Serial.begin(9600);//1
// 设置LED控制引脚:
pinMode(ledPin, OUTPUT);
}
void loop()
{
byte brightness;
// 查询串口是否收到数据:
if (Serial.available()) //2
{
// 获取数据
brightness = Serial.read();//3
//控制LED亮度
ogWrite(ledPin, brightness);
}
}
串口通信相关语句分析解释。arduino串口
1. Serial.begin(9600);
该语句的功能是设置串口通信波特率为9600bps,其函数原型如下:
void HardwareSerial::begin(long baud)
{
uint16_t baud_setting;
bool use_u2x;
// U2X mode is needed for baud rates higher than (CPU Hz / 16)
if (baud > F_CPU / 16)
{
use_u2x = true;
}
else
{
// figure out if U2X mode would allow for a better connection
// calculate the percent difference between the baud-rate specified and
// the real baud rate for both U2X and non-U2X mode
uint8_t nonu2x_baud_error = abs((int)(255-
((F_CPU/(16*(((F_CPU/8/baud-1)/2)+1))*255)/baud)));
uint8_t u2x_baud_error = abs((int)(255-
((F_CPU/(8*(((F_CPU/4/baud-1)/2)+1))*255)/baud)));
// prefer non-U2X mode because it handles clock skew better
use_u2x = (nonu2x_baud_error > u2x_baud_error);
}
if (use_u2x)
{
*_ucsra = 1 << _u2x;
baud_setting = (F_CPU / 4 / baud - 1) / 2;
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-30283-1.html