Switch (case) 声明, 附带传感输入

    • 一个if声明允许你选择两个分开的选项,真或假。当有超过2个的选项,你可以用多个if声明,或者你可以用switch声明。switch允许你选择多个选项。这个教程示范怎样用它在四种光电阻的状态下切换开关:全黑,昏暗,中等,明亮。
    • 这个程序首先读取光敏电阻。然后它用map()函数来使它的输出值符合四个值之一:0,1,2,3。最后,用switch()声明来打印对应的信息到电脑里。

    硬件要求

    • Arduino or Genuino开发板
    • 光敏电阻, 或者 其他模拟传感器
    • 10k ohm 电阻
    • 连接线
    • 面包板

    电路
    光敏电阻通过一个分压电路连接到模拟输入pin0。一个10k ohm电阻补充分压器的另一部分,从模拟输入pin0连到地。analogRead()函数从这个电路返回一个0-600的范围值。
    控制结构-Switch Case - 图1
    原理图
    控制结构-Switch Case - 图2
    样例代码

    1. /*
    2. Switch statement
    3. Demonstrates the use of a switch statement. The switch
    4. statement allows you to choose from among a set of discrete values
    5. of a variable. It's like a series of if statements.
    6. To see this sketch in action, but the board and sensor in a well-lit
    7. room, open the serial monitor, and and move your hand gradually
    8. down over the sensor.
    9. The circuit:
    10. * photoresistor from analog in 0 to +5V
    11. * 10K resistor from analog in 0 to ground
    12. created 1 Jul 2009
    13. modified 9 Apr 2012
    14. by Tom Igoe
    15. This example code is in the public domain.
    16. http://www.arduino.cc/en/Tutorial/SwitchCase
    17. */
    18. // these constants won't change. They are the
    19. // lowest and highest readings you get from your sensor:
    20. const int sensorMin = 0; // sensor minimum, discovered through experiment
    21. const int sensorMax = 600; // sensor maximum, discovered through experiment
    22. void setup() {
    23. // initialize serial communication:
    24. Serial.begin(9600);
    25. }
    26. void loop() {
    27. // read the sensor:
    28. int sensorReading = analogRead(A0);
    29. // map the sensor range to a range of four options:
    30. int range = map(sensorReading, sensorMin, sensorMax, 0, 3);
    31. // do something different depending on the
    32. // range value:
    33. switch (range) {
    34. case 0: // your hand is on the sensor
    35. Serial.println("dark");
    36. break;
    37. case 1: // your hand is close to the sensor
    38. Serial.println("dim");
    39. break;
    40. case 2: // your hand is a few inches from the sensor
    41. Serial.println("medium");
    42. break;
    43. case 3: // your hand is nowhere near the sensor
    44. Serial.println("bright");
    45. break;
    46. }
    47. delay(1); // delay in between reads for stability
    48. }

    [Get Code]
    更多

    • serial.begin()
    • analogRead()
    • map()
    • Serial.println()
    • pinMode()
    • digitalWrite()
    • for()
    • delay()
    • 数组:一个在For循环的变量举例了怎样使用一个数组。
    • IfStatementConditional:通过for循环来控制多个LED灯
    • If声明条件:使用一个‘if 声明’,通过改变输入条件来改变输出条件
    • Switch Case:怎样在非连续的数值里选择。
    • Switch Case 2:第二个switch-case的例子,展示怎样根据在串口收到的字符来采取不同的行为
    • While 声明条件:当一个按键被读取,怎样用一个while循环来校准一个传感器。