arduino判断是否连接串口_arduino串口是什么_arduino串口_arduino串口连接不上

这篇博客介绍了Arduino中串口通信的实现,通过HardwareSerial类的成员函数进行操作。示例程序演示了如何通过串口接收数据控制LED亮度。文章详细解析了`Serial.begin(9600)`设置波特率的函数,并讨论了如何判断串口是否已连接。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值