简单示例
亮灯
// 先执行一次 setupvoid setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT);}// 再无限循环 loopvoid loop() { // HIGH 通电 digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) // 休眠(毫秒) delay(100); // wait for a second // LOW 关闭 digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second}
按钮控制亮灯
// constants won't change. They're used here to set pin numbers:// 输入const int buttonPin = 7; // the number of the pushbutton pinconst int ledPin = 12; // the number of the LED pin// variables will change:int buttonState = 0; // variable for reading the pushbutton statusvoid setup() { // initialize the LED pin as an output: // 输出初始化 pinMode(ledPin, OUTPUT); // initialize the pushbutton pin as an input: // 输入初始化 pinMode(buttonPin, INPUT);}void loop() { // read the state of the pushbutton value: // 读取脚位信号 buttonState = digitalRead(buttonPin); // 如果信号为高电平 if (buttonState == HIGH) { // turn LED on: // 就设置指定就引脚为高电平 digitalWrite(ledPin, HIGH); } else { // turn LED off: // 否则就降低电平 digitalWrite(ledPin, LOW); }}
可变电阻控制灯的亮度
//可变电阻的使用// 模拟信号接收int sensor = A0;// 可变电阻的大小int sensorRead = 0;int newdata = 0;void setup() { //串口监控初始化 Serial.begin(9600);}void loop() { //读取模拟信号 sensorRead = analogRead(sensor); // 将 0-1023 中的一个数按照比例转换成 0-100 中的一个数 newdata = map(sensorRead, 0, 1023, 0, 255); // 打印 Serial.println(newdata); // 写入模拟信号,将值写入到 3 号引脚 analogWrite(3,newdata);// delay(200);}