用Ruby动画

时间:2010-02-27 03:38:06

标签: ruby animation

这与物理编程以及在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 BlinkMArduino和一些不同的布线和连接器组成。

通过串口使用命令发送命令:

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

使用ruby的Serialport gem将字节数组写入串行,变量“led”和“color”用每个的十六进制代替,例如,如果我想让8号编号转为红色,我的输出会显示为:

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

到目前为止,所有这些都是奇迹,我对我所拥有的东西感到非常满意,现在我的问题几乎与普通数学和简单的编程有关,但不知何故,实现仍然在我的脑海中。

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

有没有人知道如何开始这样的事情?我目前能够用我的脚本一次影响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 个答案:

答案 0 :(得分:2)

将你的LED映射到二维阵列应该很容易

@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)

或其他什么。

答案 1 :(得分:1)

如果你只想制作动画,你应该尝试抽象出硬件,以便它可以用一些易于使用的数据结构来表示。我不熟悉Ruby,所以我不知道最好的方法。如果您正在制作类似于该网格的表格,我会尝试将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();
}