九鼎创展论坛

标题: arduino ibox项目实战23-Calibration实验 [打印本页]

作者: armeasy    时间: 2014-10-28 14:07
标题: arduino ibox项目实战23-Calibration实验
硬件平台:PC机一台,ibox卡片电脑一只,arduino扩展板一个,电位器一个,LED灯一个
软件平台:WIN7操作系统,android4.0android4.4系统
实验目标:通过ADC从电位器读取ADC的值,然后通过得到的值控制LED灯的亮度。
打开arduino的IDE开发工具,依次点击文件->示例-> 03.Analog->AnalogWriteMega,AnalogWriteMega的示例程序将会被打开,其源码如下:
  1. const int sensorPin = A0;    // pin that the sensor is attached to
  2. const int ledPin = PWM0;        // pin that the LED is attached to

  3. // variables:
  4. int sensorValue = 0;         // the sensor value
  5. int sensorMin = 1023;        // minimum sensor value
  6. int sensorMax = 0;           // maximum sensor value


  7. void setup() {
  8.   // turn on LED to signal the start of the calibration period:
  9.   pinMode(LED1, OUTPUT);
  10.   digitalWrite(LED1, HIGH);

  11.   // calibrate during the first five seconds
  12.   while (millis() < 5000) {
  13.     sensorValue = analogRead(sensorPin);

  14.     // record the maximum sensor value
  15.     if (sensorValue > sensorMax) {
  16.       sensorMax = sensorValue;
  17.     }

  18.     // record the minimum sensor value
  19.     if (sensorValue < sensorMin) {
  20.       sensorMin = sensorValue;
  21.     }
  22.   }

  23.   // signal the end of the calibration period
  24.   digitalWrite(LED1, LOW);
  25. }

  26. void loop() {
  27.   // read the sensor:
  28.   sensorValue = analogRead(sensorPin);

  29.   // apply the calibration to the sensor reading
  30.   sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

  31.   // in case the sensor value is outside the range seen during calibration
  32.   sensorValue = constrain(sensorValue, 0, 255);

  33.   // fade the LED using the calibrated value:
  34.   analogWrite(ledPin, sensorValue);
  35. }
复制代码
       将电位器的两端接GND5V,中间的脚接A0PWM0LED,运行程序,通过反复修改程序中的参数,观察LED灯的亮暗程度。






欢迎光临 九鼎创展论坛 (http://bbs.9tripod.com/) Powered by Discuz! X3.2