控制led亮度

来自Microduino Wikipedia
跳转至: 导航搜索
Language English

目的

本教程将教大家如何用Processing来控制LED灯的亮度。

设备

  • 其他硬件设备
    • USB数据连接线 一根
    • LED灯 一个
    • 330欧电阻 一个
    • 面包板 一个
    • 跳线 一盒

原理图

ProcessingControlLEDBrightness原理图.jpg


程序

LEDBrightness

注意:代码里包含图片请不要丢掉

调试

步骤一:按着原理图搭建硬件环境,像这样:

ProcessingControlLEDBrightness连接图.jpg


步骤二:解释一下代码:

此代码可以随着鼠标的x轴的大小改变图片的亮度和控制小灯的亮度。

 void draw() {
   loadPixels();
 
   // We must also call loadPixels() on the PImage since we are going to read its pixels.  img.loadPixels(); 
   for (int x = 0; x < img.width; x++ ) {
     for (int y = 0; y < img.height; y++ ) {
 
       // Calculate the 1D pixel location
       int loc = x + y*img.width;
 
       // Get the R,G,B values from image
       float r = red (img.pixels[loc]);
       float g = green (img.pixels[loc]);
       float b = blue (img.pixels[loc]);
 
       // We calculate a multiplier ranging from 0.0 to 8.0 based on mouseX position. 
       // That multiplier changes the RGB value of each pixel.      
       float adjustBrightness = ((float) mouseX / width) * 8.0; 
       r *= adjustBrightness;
       g *= adjustBrightness;
       b *= adjustBrightness;
 
       // The RGB values are constrained between 0 and 255 before being set as a new color.      
       r = constrain(r,0,255); 
       g = constrain(g,0,255);
       b = constrain(b,0,255);
 
       // Make a new color and set pixel in the window
       color c = color(r,g,b);
       pixels[loc] = c;
     }
   }
   
   updatePixels();  
   
   //output r value to ledpin
   arduino.analogwrite(ledPin, int(r));
 }


步骤三:下载代码并编译通过。


步骤四:运行后鼠标在灯泡上横向移动,看看有什么反应。

结果

鼠标在左边灯泡最暗,在右边最亮,随着从左到右逐渐变化,processing的效果是这样的。

鼠标在左边:

ProcessingOverLEDBrightness1.jpg

鼠标在中间:

ProcessingOverLEDBrightness2.jpg

鼠标在右边:

ProcessingOverLEDBrightness3.jpg


实际中的LED灯也会做相应的明暗变化。

视频