Skip to content

Instantly share code, notes, and snippets.

@Bluebie
Created September 20, 2010 03:17
Show Gist options
  • Save Bluebie/587393 to your computer and use it in GitHub Desktop.
Save Bluebie/587393 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'ruby-audio'
# Info at http://www.horrorseek.com/home/halloween/wolfstone/Motors/svoint_RCServos.html
class ServoAnimation
SampleRate = 48000 # samples per second
RePulse = 200 # hertz
CentreWidth = 1.5 # mSec
ScaleWidth = 0.9 # mSec
PulseEvery = SampleRate / RePulse
DefaultWait = 0.5
def self.polarity= polarity
@polarity = polarity
end
def self.inherited stay_classy; stay_classy.begin; end
def self.begin;
@file = "#{self.name}.wav"
@info = RubyAudio::SoundInfo.new :channels => 1, :samplerate => SampleRate, :format => RubyAudio::FORMAT_WAV|RubyAudio::FORMAT_PCM_16
@snd = RubyAudio::Sound.open(@file, 'w', @info)
@angle = 0
@polarity = +1.0
end
# Stop sending commands, letting the servo go limp, for a duration
def self.limp seconds = DefaultWait
@angle = nil
buffer = RubyAudio::Buffer.new('float', PulseEvery)
buffer.size.times { |i| buffer[i] = 0.0 }
(seconds * RePulse.to_f).round.times do
@snd.write buffer
end
end
# Wait for a duration, holding the servo at the current angle (or limp if no angle set yet)
def self.wait seconds = DefaultWait
return self.limp(seconds) unless @angle
buffer = RubyAudio::Buffer.new('float', PulseEvery)
threshold = (CentreWidth + (ScaleWidth * @angle)) * 0.001 * SampleRate
buffer.size.times do |i|
buffer[i] = ((i < threshold) && @polarity) || 0.0
end
(seconds * RePulse.to_f).round.times do
@snd.write buffer
end
end
def self.set angle
@angle = angle
end
end
# Should make servo go all the way left, then all the way right, then go limp for one second!
class Wiggle < ServoAnimation
set -1.0
wait 2.0
set +1.0
wait 2.0
limp 1.0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment