Arduino示例代码讲解:Virtual Color Mixer 虚拟混色器
Virtual Color Mixer 虚拟混色器
这段代码是一个Arduino示例程序,用于读取三个模拟传感器(例如电位器)的值,并通过串行通信将这些值发送出去。这些值可以被Processing或其他程序(如Max/MSP)接收,并用于改变屏幕的背景颜色。
/*
This example reads three analog sensors (potentiometers are easiest)
and sends their values serially. The Processing and Max/MSP programs at the bottom
take those three values and use them to change the background color of the screen.
The circuit:
* potentiometers attached to analog inputs 0, 1, and 2
http://www.arduino.cc/en/Tutorial/VirtualColorMixer
created 2 Dec 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe and Scott Fitzgerald
This example code is in the public domain.
*/
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));
}
功能概述
硬件部分:
- 使用三个电位器分别连接到Arduino的模拟输入引脚A0、A1和A2。
软件部分:
-
读取三个模拟输入引脚的值。
-
将这些值以逗号分隔的字符串形式通过串行通信发送。
代码逐行解释
定义常量
const int redPin = A0; // 用于控制红色的传感器
const int greenPin = A1; // 用于控制绿色的传感器
const int bluePin = A2; // 用于控制蓝色的传感器
redPin
、greenPin
和bluePin
:分别定义连接到模拟输入引脚A0、A1和A2的传感器。
setup()
函数
void setup() {
Serial.begin(9600); // 初始化串行通信,波特率为9600
}
Serial.begin(9600)
:初始化串行通信,设置波特率为9600。
loop()
函数
void loop()