Sunday, December 31, 2017

Raspberry Pi & Groovy : Morse Code Translator

I got a Raspberry Pi and the first thing I wanted to get working is Groovy programming of the GPIO. Took some fiddling but the eventual code was easy.

I ended up building a simple Mores code generator that outputs text to a led light.

First the wiring for the Pi and Breadboard
First gotcha is that to access the GPIO you need to run the Groovy script as ROOT. So changed to root

sudo su


Install SDKMan to install Groovy.

curl -s "https://get.sdkman.io" | bash


Then I just installed Groovy with

sdk install groovy


The next was to use Pi4j and groovy to do the code. The code is pretty rough, but it works.


@Grapes(
        @Grab(group='com.pi4j', module='pi4j-core', version='1.1')
)

import com.pi4j.io.gpio.*

    println('getting gpio controller')

    GpioController gpio = GpioFactory.getInstance()
    GpioPinDigitalOutput outputPin = gpio.provisionDigitalOutputPin(RaspiPin.getPinByAddress(1))

    def alpha = ["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", "1", "2", "3", "4", "5", "6", "7", "8",
    "9", "0", " " ]

    def morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
    "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
    "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
    "-.--", "--..", ".----", "..---", "...--", "....-", ".....",
    "-....", "--...", "---..", "----.", "-----", "|"]

    def say = "SOS SOS SOS SOS"
    
    def dotTime = 250
    def dashTime = 750
    def between = 500
    def space = 1000

    def outputLed = {time->
        println("dot")
        outputPin.setState(true)
        sleep(time)
        outputPin.setState(false)
        sleep(between)
    }

    def doLetter = {letter-> 
        def index = alpha.findIndexOf {it.equalsIgnoreCase(letter)}
        def morseCode = morse.get(index)
        println "letter: ${letter} = ${morseCode}"
        
        morseCode.each {bit->
            println("bit ${bit}")
            if (bit.equals('.')) {
                outputLed(dotTime)
            } else if (bit.equals('-')) {
                outputLed(dashTime)
            } else if (bit.equals('|')) {
                sleep(space)
            }
        }
    }

println "Saying: ${say}"
outputPin.setState(false)
say.each {letter->
    doLetter(letter)
}
outputPin.setState(false)
println 'done'

gpio.shutdown()


Then just run the above script with
groovy [file].groovy


But wait, you probably will get this error.
Unable to determine hardware version. I see: Hardware : BCM2835


This I had to fix by reverting my kernel, information was in this thread
But this was the script that reverted the Kernel
sudo rpi-update 52241088c1da59a359110d39c1875cda56496764 

Here is a video of it doing SOS SOS SOS.




No comments:

Post a Comment