环境搭建:
1. Arduino UNO R3开发板,
2. Arduino IDE。
我这里使用的是1.8.5。可以在https://www.arduino.cc/en/Main/Software下载并安装。
安装好之后,桌面会有如下图标。
示例开发:
1.连接设备。
本例中我们以DFR0058 Analog Rotation Sensor结合DFR0021-R为例,基于Arduino Uno R3和Arduino IDE开发。
DFR0021-R的引脚和Arduino Uno开发板的连接方式如下,
DFR0021-R | DFR0058 | Arduino Uno R3 |
VCC | VCC | 3.3V |
GND | GND | GND |
信号引脚 | 信号引脚 | DFR0021接数字引脚8,DFR0058接模拟 引脚A0 |
2. 编码。
连接好之后,用数据线连接Arduino开发板和电脑。同时打开Arduino IDE。输入下述代码。
const int AnalogRotationPin = A0; // Analog Rotation Sensor Pin
const int LedPin = 8; // Digital LED Pin
const int ROTATION_RANGE = 50; // Rotation Sensor Range Value
int sensorValue = 0;
int outputValue = 0;
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
pinMode(LedPin, OUTPUT); // declare LED as output
pinMode(AnalogRotationPin, INPUT); // declare Analog Rotation Sensor as input
}
void loop() {
// read the analog in value:
Serial.print("Reading Analog Rotation Sensor Value: \n");
sensorValue = analogRead(AnalogRotationPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
Serial.print("Analog Rotation Vaule = ");
Serial.print(sensorValue);
Serial.print("\n");
Serial.print("\t Output Value = ");
Serial.println(outputValue);
Serial.print("\n");
if (outputValue > ROTATION_RANGE) // check Analog Rotation Sensor
{
digitalWrite(LedPin, HIGH); // turn LED ON
Serial.print("LED is On...\n");
}
else
{
digitalWrite(LedPin, LOW); // turn LED OFF
Serial.print("LED is OFF...\n");
}
Serial.println();
delay (1000);
}
然后保存文件。
选择Arduino Uno开发板。
编译上传到开发板。
3.运行。
选择COM口信息,
然后选择端口监视工具,查看程序运行信息。
串口监视信息,
备注:上面的数据就是当前Analog Rotation Sensor的值和Red LED 的当前状态(ON表示开,OFF表示关)。此例中,当Analog Rotation Sensor的值大于50时,就打开LED灯光;反之就关闭LED灯。
整体运行界面:
实际效果图: