串口通信是arduino和PC机通信最简单的方式之一。以前的PC带有真正的串口,但是和arduino的电平标准不一样。后来,随着USB端口的出现,基本PC端就没有串口了。但是我们一般都可以通过USB模拟PC端的串口,因此现在依然可以让arduino和PC通过这个“串口”通信。
如果使用无线蓝牙模块和PC端通信也是可行的。其实我们的arduino下载程序的过程就是通过USB接口模拟串口实现的。
![](https://img.kancloud.cn/12/60/1260ee4e89b7844e38a3bbcfe25d797f_621x722.png)
这个程序实现的功能描述如下:硬件包含一个四位拨码开关,通过数字输入端口将拨码信息输入arduino。拨码开关可以输入四位二进制数字,比如 1101,0101等等。而这个数字将被由串口从arduino传递给PC端;同时在串口监视器,PC端输入“1,2,3,4”控制显示的格式。1对应二进制格式,2对应16进制格式,3对应10进制格式,4对应8进制格式。这样我们实现两个设备(,arduino和PC端)的通信,这个通信上叫做双工通信。
```
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
int dip=0;
bool keyPressed=true;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int incomingByte = 49;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("1:BIN 2: HEX 3:DEC 4:OCT");
Serial.println("move the dip to change the data");
Serial.println("input 1,or 2,or 3,or 4 in the serial send window");
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
if(keyPressed==true)
{
dip=digitalRead(9);
dip=dip*2+digitalRead(8);
dip=dip*2+digitalRead(7);
dip=dip*2+digitalRead(6);
//Serial.println("1:BIN 2: HEX 3:DEC 4:OCT");
if(incomingByte==49)
{
Serial.println(dip,BIN);
}
else if(incomingByte==50)
{
Serial.println(dip,HEX);
}
else if(incomingByte==51)
{
Serial.println(dip,DEC);
}
else if(incomingByte==52)
{
Serial.println(dip,OCT);
}
keyPressed=false;
}
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
keyPressed=true;
}
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
//Serial.println("1:BIN 2: HEX 3:DEC 4:OCT");
Serial.println("I received your choiece.");
}
}
```
- 序言
- 第一章 arduino简介和学习
- 第一节 arduino介绍
- 第二节 学习方法概述
- 第三节 计算机的智能
- 第二章 开始学习之旅
- 第一节 安装环境和购买硬件的说明
- 第二节 介绍一个具体的范例
- 第三章 分类官网教程讲解
- 第一节 Basics类的示例项目
- 第二节 数字端口的示例
- 第三节 模拟端口的示例
- 第四节 串口通信的示例
- 第五节 LED显示的示例
- 第六节 arduino处理矩阵键盘
- 第七节 LCD显示范例
- 第四章 综合实践项目制作教程
- 第一节 简单的计算器
- 第五章 复习题
- 单选题
- 编程题目
- 单选题答案
- 编程题答案
- 第1题
- 第2题
- 第3题
- 第4题
- 第5题
- 第6题
- 第7题
- 第8题
- 第9题
- 第10题
- 第11题
- 第12题
- 第13题
- 第14题
- 第15题
- 第16题
- 第17题
- 复习题包含翻译
- 第六章 快速复习
- 第一节 英文解说