# Class for emitting messages in Morse code
class Morse
# Constants defining the morse code
# Morse code from A to Z and 0 to 9
CODE = { "A" => ".-", "B" => "-...", "C" => "-.-.",
"D" => "-..", "E" => ".", "F" => "..-.",
"G" => "--.", "H" => "....", "I" => "..",
"J" => ".---", "K" => "-.-", "L" => ".-..",
"M" => "--", "N" => "-.", "O" => "---",
"P" => ".--.", "Q" => "--.-", "R" => ".-.",
"S" => "...", "T" => "-", "U" => "..-",
"V" => "...-", "W" => ".--", "X" => "-..-",
"Y" => "-.--", "Z" => "--..",
"0" => "-----", "1" => ".----", "2" => "..---",
"3" => "...--", "4" => "....-", "5" => ".....",
"6" => "-....", "7" => "--...", "8" => "---..",
"9" => "----."}
# Morse code durations in dots
DOT = 1
DASH = 3
SPACE = 1 # Space between parts of a same letter
LETTER = 3 # Space between letters of a same word
WORD = 7 # Space between words
# Create a new morse emitter on a given port (pin)
# Params:
# +port+:: the port used for emmitting
# +pwr+:: the emition power
# +dot+:: duration of a dot is seconds
def initialize(port, pwr = 256, dot_s = 0.2)
# @port = AnalogIO.new(port,OUTPUT)
@port = LED.new
@pwr = pwr.to_i
@dot = dot_s.to_f
end
# Emit a morse code including the delay after a letter
# Param:
# +code+:: the code to emit
def emit_morse(code)
code = code.to_s # Ensures code is a string
# Emit each signal
code.each_char do |s|
case (s)
when "." then # Emit a dot
# @port.write(@pwr)
@port.on
sleep(DOT*@dot)
# @port.write(0)
@port.off
when "-" then # Emit a dash
# @port.write(@pwr)
@port.on
sleep(DASH*@dot)
# @port.write(0)
@port.off
when " " then # Emit a space between words
sleep((WORD-SPACE-LETTER)*@dot)
# Note: SPACE and LETTER time are removed since
# they are added afterward
# Invalid signals are skipped
end
# Adds the delay between signals
sleep(SPACE*@dot)
end
# Adds the delay between letters
sleep(LETTER*@dot)
end
# Emit a text in morse code
# Params:
# +text+:: the text to send
def emit(text)
# Ensure text is an uppercase string
text = text.to_s.upcase
# Emit each char
code = ""
text.each_char do |c|
# Get the Morse code corresponding to c
emit_morse(CODE[c])
end
end
end
# Testing the class
# Create a morse emitter on D0
morse = Morse.new(D0)
# Emit text entered from standard input
loop do
morse.emit(gets)
end
print "End of morse\n"