简单示例

亮灯

  1. // 先执行一次 setup
  2. void setup() {
  3. // initialize digital pin LED_BUILTIN as an output.
  4. pinMode(LED_BUILTIN, OUTPUT);
  5. }
  6. // 再无限循环 loop
  7. void loop() {
  8. // HIGH 通电
  9. digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
  10. // 休眠(毫秒)
  11. delay(100); // wait for a second
  12. // LOW 关闭
  13. digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
  14. delay(1000); // wait for a second
  15. }

按钮控制亮灯

  1. // constants won't change. They're used here to set pin numbers:
  2. // 输入
  3. const int buttonPin = 7; // the number of the pushbutton pin
  4. const int ledPin = 12; // the number of the LED pin
  5. // variables will change:
  6. int buttonState = 0; // variable for reading the pushbutton status
  7. void setup() {
  8. // initialize the LED pin as an output:
  9. // 输出初始化
  10. pinMode(ledPin, OUTPUT);
  11. // initialize the pushbutton pin as an input:
  12. // 输入初始化
  13. pinMode(buttonPin, INPUT);
  14. }
  15. void loop() {
  16. // read the state of the pushbutton value:
  17. // 读取脚位信号
  18. buttonState = digitalRead(buttonPin);
  19. // 如果信号为高电平
  20. if (buttonState == HIGH) {
  21. // turn LED on:
  22. // 就设置指定就引脚为高电平
  23. digitalWrite(ledPin, HIGH);
  24. } else {
  25. // turn LED off:
  26. // 否则就降低电平
  27. digitalWrite(ledPin, LOW);
  28. }
  29. }

可变电阻控制灯的亮度

  1. //可变电阻的使用
  2. // 模拟信号接收
  3. int sensor = A0;
  4. // 可变电阻的大小
  5. int sensorRead = 0;
  6. int newdata = 0;
  7. void setup() {
  8. //串口监控初始化
  9. Serial.begin(9600);
  10. }
  11. void loop() {
  12. //读取模拟信号
  13. sensorRead = analogRead(sensor);
  14. // 将 0-1023 中的一个数按照比例转换成 0-100 中的一个数
  15. newdata = map(sensorRead, 0, 1023, 0, 255);
  16. // 打印
  17. Serial.println(newdata);
  18. // 写入模拟信号,将值写入到 3 号引脚
  19. analogWrite(3,newdata);
  20. // delay(200);
  21. }