Saturday, June 06, 2015

Scala on the Raspberry PI

As Scala compiles its files as Java class-files, they run on a regular JVM, with a few Scala-specific jar-files in the classpath.
Even if it is not the most productive way to get work done, it is possible to compile Java files on the Raspberry PI, as well as Scala files. Personally, I prefer to develop in an IDE, and use FTP to push the classes to the Raspberry PI, it's much faster, and the IDE is much more productive than vi.
The explanations I found here got me started.
And again, as Scala runs on a Java Virtual Machine (JVM), all the work done with PI4J is fully available from Scala.
The following code (available on github) shows how to read a BMP180 from Scala:
 import adafruiti2c.sensor.AdafruitBMP180

 object Scala_101 {
   def main(args: Array[String]) {
     println("Hello, Scala world!")
     val bmp180 = new AdafruitBMP180
     try
     {
       val temp  = bmp180.readTemperature
       val press = bmp180.readPressure / 100
       println(s"CPU Temperature   :  ${SystemInfo.getCpuTemperature}\272C")
       println(s"Temp:${temp}\272C, Press:${press} hPa")
     }
     catch
     {
       case ex: Exception => {
         println(ex.toString())
       }
     }
   }
 }
  
To run it, I used a script like this:
 #!/bin/bash
 # 
 SCALA_HOME=/home/pi/.sbt/boot/scala-2.10.3
 PI4J_HOME=/opt/pi4j
 #
 CP=$SCALA_HOME/lib/scala-library.jar
 # 
 CP=$CP:$PI4J_HOME/lib/pi4j-core.jar
 CP=$CP:../AdafruitI2C/classes
 CP=$CP:./out/production/Scala.101
 # 
 sudo java -classpath "$CP" Scala_101
  
And all is good, the output is
 Hello,Scala world!
 CPU Temperature  :40.6°C
 Temp:22.5°C, Press:1010.73 hPa

No comments:

Post a Comment