九鼎创展论坛

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

作者: armeasy    时间: 2014-10-25 19:29
标题: arduino ibox项目实战20-AnalogInOutSerial实验
硬件平台:PC机一台,ibox卡片电脑一只,arduino扩展板一个,电位器外设一个,LED灯外设一个
软件平台:WIN7操作系统,android4.0android4.4系统
实验目标:通过电位器旋转改变模拟电压,程序通过模拟电压的变化进而控制LED灯的亮度,并通过调试窗口将模拟电压转换的数字信号和对应的LED亮度值显示出来。
打开arduino的IDE开发工具,依次点击文件->示例-> 03.Analog-> AnalogInOutSerial,AnalogInOutSerial的示例程序将会被打开,其源码如下:
  1. // These constants won't change.  They're used to give names
  2. // to the pins used:
  3. const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
  4. const int analogOutPin = PWM0; // Analog output pin that the LED is attached to

  5. int sensorValue = 0;        // value read from the pot
  6. int outputValue = 0;        // value output to the PWM (analog out)

  7. void setup() {
  8.   // initialize serial communications at 9600 bps:
  9.   Serial.begin(9600);
  10. }

  11. void loop() {
  12.   // read the analog in value:
  13.   sensorValue = analogRead(analogInPin);
  14.   // map it to the range of the analog out:
  15.   outputValue = map(sensorValue, 0, 1023, 0, 255);
  16.   // change the analog out value:
  17.   analogWrite(analogOutPin, outputValue);

  18.   // print the results to the serial monitor:
  19.   Serial.print("sensor = " );
  20.   Serial.print(sensorValue);
  21.   Serial.print("\t output = ");
  22.   Serial.println(outputValue);

  23.   // wait 2 milliseconds before the next loop
  24.   // for the analog-to-digital converter to settle
  25.   // after the last reading:
  26.   delay(2);
  27. }
复制代码
       setup函数中,设置串口波特率为9600,在loop函数中通过analogRead函数读取模拟电压的值,然后通过map函数映射出和读取出来的电压值一一对应的LED亮度值,并通过PWM0输出对应脉宽的波形,从而控制LED灯的亮度。最终通过Serial.print函数将相关的值打印出来。






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