## **串口控制LED**
> 本例向你展示如何在Arduino或Genuino板从电脑接收消息。在接收到字母H时,就把LED打开。在接收到字母L时就关闭LED。
数据可以从Arduino IDE的串口监视器发送,也可以从Processing(下面有代码)或Flash(通过serial-net代理),PD或者Max/MSP等其他软件发送。
### **所需硬件**
Arduino板Genuino板
LED (可选)
220Ω电阻(可选)
连接线
### **所需软件**
Processing或Max/MSP 5.x版本
很多Arduino和Genuino 板都在13引脚有板载LED;如果你的板子没有内置LED,请将外部LED连接到13引脚。阳极(长脚)通过220Ω电阻连接到13引脚。阴极(短脚)连接到GND。
### **电路**
![图片来自官网](http://img.blog.csdn.net/20160516134207669)
### **原理图**
![图片来自官网](http://img.blog.csdn.net/20160516134222476)
### **代码**
~~~
/*
串口控制LED
用Arduino从电脑上接收数据。Arduino在接收到字母H时打开LED,在接收到L时关闭LED。
数据可以从Arduino IDE的串口监视器发送,也可以从Processing(下面有代码)或Flash(通过serial-net代理),PD或者Max/MSP等其他软件发送。
电路搭建:
* LED从13引脚连接到GND
* 代码是公开的
*/
const int ledPin = 13; // LED引脚
int incomingByte; // 串口数据存储
void setup() {
// 初始化串口连接:
Serial.begin(9600);
// 以OUTPUT模式初始化LED:
pinMode(ledPin, OUTPUT);
}
void loop() {
// 检查是否有数据:
if (Serial.available() > 0) {
//读取数据流中最后一个字符:
incomingByte = Serial.read();
// 如果时字母H(ASCII码72), 打开LED:
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
}
// 如果时字母L(ASCII码76), 关闭LED:
if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
}
}
}
~~~
#### **Processing代码**
将下面代码复制到Processing。当你的鼠标经过中间方块时,13引脚的LED应该会打开。Processing Applet的界面是这样的:
![图片来自官网](http://img.blog.csdn.net/20160516134237638)
~~~
// 串口控制LED
// 展示如何向Arduino板发送数据
// 如果鼠标在方形区域,就把LED打开,如果不在就关闭
// 代码是公开的。
import processing.serial.*;
float boxX;
float boxY;
int boxSize = 20;
boolean mouseOverBox = false;
Serial port;
void setup() {
size(200, 200);
boxX = width/2.0;
boxY = height/2.0;
rectMode(RADIUS);
// 列举所有可用串口。
//(若用了2.1或之前版本,请用Serial.printArray())
Serial.printArray()
println(Serial.list());
// 打开第一个串口(假设Arduino连上的是这个)
// 确保和Arduino设置的波特率相同(这里是9600)
port = new Serial(this, Serial.list()[0], 9600);
}
void draw()
{
background(0);
// 检查光标是否在方块上方
if (mouseX > boxX-boxSize && mouseX < boxX+boxSize &&
mouseY > boxY-boxSize && mouseY < boxY+boxSize) {
mouseOverBox = true;
// 改变方块颜色:
stroke(255);
fill(153);
// 鼠标在方块内,发送H:
port.write('H');
}
else {
// 改变方块颜色到未选中状态:
stroke(153);
fill(153);
// 鼠标在方块内,发送L:
port.write('L');
mouseOverBox = false;
}
// 画方块
rect(boxX, boxY, boxSize, boxSize);
}
~~~
#### **Max 补丁**
Max/MSP补丁生效后如图所示。请将代码复制下来并且粘贴到**新建补丁**(**new patch**) 窗口。
~~~
----------begin_max5_patcher----------
1672.3oc2ZszaaiCD9ryuBBebQVCQRYao8xhf1cQCPVfBzh8RRQ.sDsM2HSZ
HQmlzh9eu7gjsjsEk7y0oWjiHoHm4aluYHGlueUmtiDuPy5B9Cv8fNc99Uc5
XZR2Pm726zcF4knDRlYXciDylQ4xtWa6SReQZZ+iSeMiEQR.ej8BM4A9C7OO
kkAlSjQSAYTdbFfvA27o2c6sfO.Doqd6NfXgDHmRUCKkolg4hT06BfbQJGH3
5Qd2e8d.QJIQSow5tzebZ7BFW.FIHow8.2JAQpVIIYByxo9KIMkSjL9D0BRT
sbGHZJIkDoZOSMuQT.8YZ5qpgGI3locF4IpQRzq2nDF+odZMIJkRjpEF44M3
A9nWAum7LKFbSOv+PSRXYOvmIhYiYpg.8A2LOUOxPyH+TjPJA+MS9sIzTRRr
QP9rXF31IBZAHpVHkHrfaPRHLuUCzoj9GSoQRqIB52y6Z.tu8o4EX+fddfuj
+MrXiwPL5+9cXwrOVvkbxLpomazHbQO7EyX7D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75U+1JXxFUY.xEEBcRCqhOEkz2bENEWnh4pbh0wY25EefbD6EmW
UA6Ip8wFLyuFXx+Wrp8m6iff1B86W7bqJO9+mx8er4E3.abCLrYdA16sBuHx
vKT6BlpIGQIhL55W7oicf3ayv3ixQCm4aQuY1HZUPQWY+cASx2WZ3f1fICuz
vj5R5ZbM1y8gXYN4dIXaYGq4NhQvS5MmcDADy+S.j8CQ78vk7Q7gtPDX3kFh
3NGaAsYBUAO.8N1U4WKycxbQdrWxJdXd10gNIO+hkUMmm.CZwknu7JbNUYUq
0sOsTsI1QudDtjw0t+xZ85wWZd80tMCiiMADNX4UzrcSeK23su87IANqmA7j
tiRzoXi2YRh67ldAk79gPmTe3YKuoY0qdEDV3X8xylCJMTN45JIakB7uY8XW
uVr3PO8wWwEoTW8lsfraX7ZqzZDDXCRqNkztHsGCYpIDDAOqxDpMVUMKcOrp
942acPvx2NPocMC1wQZ8glRn3myTykVaEUNLoEeJjVaAevA4EAZnsNgkeyO+
3rEZB7f0DTazDcQTNmdt8aACGi1QOWnMmd+.6YjMHH19OB5gKsMF877x8wsJ
hN97JSnSfLUXGUoj6ujWXd6Pk1SAC+Pkogm.tZ.1lX1qL.pe6PE11DPeMMZ2
.P0K+3peBt3NskC
-----------end_max5_patcher-----------
~~~
### **相关资料**
[serial.read()](https://www.arduino.cc/en/Serial/Read)
[serial.available()](https://www.arduino.cc/en/Serial/Available)
[if statement](https://www.arduino.cc/en/Tutorial/IfStatement)
- 说明
- 系统示例文件目录结构及说明
- 01.Basics
- AnalogReadSerial
- BareMinimum
- Blink
- DigitalReadSerial
- Fade
- ReadAnalogVoltage
- 02.Digital
- BlinkWithoutDelay
- Button
- Debounce
- DigitalInputPullup
- StateChangeDetection
- toneKeyboard
- toneMelody
- toneMultiple
- tonePitchFollower
- 03.Analog
- AnalogInOutSerial
- AnalogInput
- AnalogWriteMega
- Calibration
- Fading
- Smoothing
- 04.Communication
- ASCIITable
- Dimmer
- Graph
- Midi
- MultiSerial
- PhysicalPixel
- ReadASCIIString
- SerialCallResponse
- SerialCallResponseASCII
- SerialEvent
- SerialPassthrough
- VirtualColorMixer
- 05.Control
- Arrays
- ForLoopIteration
- IfStatementConditional
- switchCase
- switchCase2
- WhileStatementConditional
- 06.Sensors
- ADXL3xx
- Knock
- Memsic2125
- Ping
- 07.Display
- barGraph
- RowColumnScanning
- 08.Strings
- CharacterAnalysis
- StringAdditionOperator
- StringAppendOperator
- StringCaseChanges
- StringCharacters
- StringComparisonOperators
- StringConstructors
- StringIndexOf
- StringLength
- StringLengthTrim
- StringReplace
- StringStartsWithEndsWith
- StringSubstring
- StringToInt
- 09.USB
- Keyboard
- KeyboardLogout
- KeyboardMessage
- KeyboardReprogram
- KeyboardSerial
- KeyboardAndMouseControl
- Mouse
- ButtonMouseControl
- JoystickMouseControl
- 10.StarterKit_BasicKit (与特定硬件相关,暂无)
- p02_SpaceshipInterface
- p03_LoveOMeter
- p04_ColorMixingLamp
- p05_ServoMoodIndicator
- p06_LightTheremin
- p07_Keyboard
- p08_DigitalHourglass
- p09_MotorizedPinwheel
- p10_Zoetrope
- p11_CrystalBall
- p12_KnockLock
- p13_TouchSensorLamp
- p14_TweakTheArduinoLogo
- p15_HackingButtons
- 11.ArduinoISP(暂无)
- ArduinoISP