代码之家  ›  专栏  ›  技术社区  ›  JP Silvashy Gautam Rege

用ruby制作动画

  •  1
  • JP Silvashy Gautam Rege  · 技术社区  · 15 年前

    这涉及到在web服务器上运行的物理编程和ruby。我有一个RGB LED阵列,它是5x5,所以总共有25个LED。它们有编号,可单独寻址:

     1   2   3   4   5
     6   7   8   9  10
    11  12  13  14  15
    16  17  18  19  20
    21  22  23  24  25
    

    这是一张照片:

    led matrix

    至于硬件(其实并不重要,因为它工作得很好),系统由25个 BlinkM 一个 Arduino ,以及一些不同的电缆和连接器。

    LED通过串行发送命令,命令如下:

    @sp.write ["\x01", led, "\x04\x00", "c", color]
    

    它使用ruby的 Serialport gem ,变量“led”和“color”被替换为各自的十六进制,因此,例如,如果我想使8号led变为红色,我的输出将为:

    @sp.write ["\x01","\x08", "\x04\x00", "c", "\xff\x00\x00"]
    

    到目前为止,所有这些都是奇迹,我对我所拥有的非常满意,现在我的问题几乎与普通数学和简单编程有关,但不知何故实现超出了我的想象。

    Here is a sample of such animation. 我最感兴趣的是如何在这里使用ruby动画模式。我记得某些“处理”动画脚本,只是循环使用数组作为对象的函数,并影响数组的元素,创建有趣的动画,只是由于输出的数学。

    有人知道我怎么开始做那样的事情吗?我现在可以用我的脚本一次影响一个LED,我可以把它们串在一起 sleep x 在每个命令和手动构建动画之后,我如何才能使用某种程序动画无限期地运行一次呢?


    编辑

    我并没有完整地描述字节码数组,下面是每个部分的功能:

    @sp.write ["\x01", led, "\x04\x00", "c", color]
                 ^      ^      ^   ^     ^    ^
                 a      b      c   d     e    f
    
    a. start byte (not important, tells serial that it is the start of a command)
    b. hex for LED address, ex. `\x07` is led 7
    c. length of command (starting at "e")
    d. bytes to be read (always 0 in our case)
    e. the "fade to color" command
    f. the color we want to fade to in rrggbb hex format.
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   sax    15 年前

    将led映射到2d阵列应该很容易

    @led = []
    led = 1
    5.times do |y|
      5.times do |x|
        @led[x] ||= []
        @led[x][y] = led
        led +=1
      end
    end
    

    我可能会制作一个led类,封装了写出颜色的能力,所以不要这样:

    @led[x][y] = led
    

    它变成

    @led[x][y] = Led.new(:id => led)
    

    然后编写一个方法,这样您就可以轻松地执行以下操作:

    @led[1][5].color(255,255,255)
    

    或者什么。

        2
  •  1
  •   Ronald    15 年前

    如果你只想制作动画,你应该试着把硬件抽象出来,这样它就可以用一些容易操作的数据结构来表示。我不熟悉鲁比,所以我不知道最好的办法。如果你做的是类似于表格的东西,那只是一个网格,我会尝试将led映射到一个2d阵列。

    然后我将创建一个无限循环。这个循环将包含另一组循环,循环遍历数组中的每个像素,并将每个元素中的颜色写入相应的硬件。一旦它写出了所有的像素,它就可以休眠几毫秒,调用一些函数,当它醒来时对动画进行步进,然后再次重复循环。

    一旦你这样做了,你就只需要操作数据结构。这有什么意义吗?

    所以像这样:

    function stepAnimation(){
        //modify 2d array for each step of the animation here
    }
    
    //I'm assuming you have a function that gets
    //Looped forever. In Wiring you do, not sure 
    //about working with Arduino using Ruby, if not
    //just add while(1) in there.. 
    function mainLoop(){ 
        for(var y = 0; y < 5; y++){
         for(var x = 0; x < 5; x++){
             sp.write(2darray[x][y]) //write color from array to hardware
         }
        }
        sleep(60);
        stepAnimation();
    }