Updates from admin RSS

  • Enable GPIO:s in Codesys

    Ellen 17:17 on December 8, 2015 | 0 Permalink | Reply
    Tags: , PLC,

    Once you have set up Raspberry Pi and Codesys it is time to start reading and writing the values of the Raspberry Pis GPIO:s. When using the Raspberry Pi examples from Codesys you will see that the GPIOs are listed in the tree of objects. Make sure to select the version of your Raspberry Pi as you configure the GPIOs. Right-click the GPIOs object and select Plug Device. Here you can choose between “GPIOs A/B” for models A and B or for models B+ and 2 choose “GPIOs B+/Pi2″. Click “Plug device” and then “Close” to close the window.

    In order to choose what pins will be used for what click on “GPIOs Parameters” and double click in the column “Value” for any pin to select “not uses”, “Output” or “Input”.


    In order to access your pins you will need to give them variable names. Notice that you need to set variables names for both inputs and outputs separately:

    To access these inputs and outputs in code use the varaible names and the pin number of your choice:

    gpioInput:BOOL; // Boolean value for input

    gpioInput := gpioIn.17; // Sets variable for input to read later
    gpioOut.18 := TRUE;

    Happy coding!

  • Read UDP stream in Codesys

    Ellen 17:53 on December 3, 2015 | 0 Permalink | Reply
    Tags: , , udp

    How to read a UDP stream in Codesys. To start off you will need to import the following libraries:

    Click on “Add library” and “Advanced..”. Search for “CAA Net..” and “CAA Types” to add
    CAA Net Base Services
    CAA Types Extern

    The code below listens to a UDP stream that broadcasts to the IP adress of the device running Codesys. In my case it is a Raspberry Pi. First some variable declarations:


            eState: INT:= 0;
            IPAddress               : NBS.IP_ADDR; (* IP Address *)
            uiPort                  : UINT; (* Port No. *)
            sReceived               : STRING; (* Holds the received message *)

            ctRecAnswers    : CAA.COUNT; (* No. of received messages *)

            UDPPeer                 : NBS.UDP_Peer; (* FB UDP Peer *)
            XUDPPeer                : NBS.UDP_Peer; (* FB UDP Peer *)
            UDPSend                 : NBS.UDP_Send; (* FB UDP Send *)
            UDPReceive              : NBS.UDP_Receive; (* FB UDP Receive *)
            Peer                    : CAA.HANDLE; (* Handle to the peer connection *)
            xEnable                 : BOOL;
            udpData :STRING;

    Then the code that listens to the UDP stream:

    UDPPeer(xEnable:= xEnable, ipAddr:= IPAddress, uiPort:= uiPort, hPeer=> Peer);

    CASE eState OF
            0: // Init
                    IPAddress.sAddr:= ‘′; // IP Adress where Codesys application is running
                    uiPort:= 3000;
                    xEnable:= TRUE;
                    eSTATE := 10;
            10: // Start listening
                    IF UDPPeer.xActive THEN
                    UDPReceive(xEnable:= TRUE,  hPeer:= Peer, szSize:= SIZEOF(sReceived), pData:= ADR(sReceived));
                    IF UDPReceive.xReady THEN
                            udpData := sReceived; // Data from UDP-stream
                            ctRecAnswers := ctRecAnswers + 1; // Number of UDP calls
                    ELSIF UDPReceive.xError THEN
                            eState:= 20;
                    eState:= 20;
                    // Error

  • Configure Yun and install Node

    Ellen 17:21 on November 4, 2014 | 0 Permalink | Reply
    Tags: , , , yun

    Turn your Arduino on by connecting the micro-usb cable. It will get it’s own access point that you connect to. When connected type in http://arduino.local into your browser and you will get into the page of the Arduino Yun. Password comes preconfiguired as “arduino”.

    If http://arduino.local doesn’t work. Check the IP adress of your network ie and type it in but replace the last digit with 1 so it becomes

    Type in the details of your wifi network so that the Arduino can connect to internet. Configure and restart. No connect to your wifi network that has internet connection.

    Now open the Terminal and type:

    ssh root@arduino.local

    You will be required to type in the password you set earlier.

    Upgrade OpenWrt
    Download the upgrade for OpenWrt to the SD card via the Terminal.

    cd /mnt/sda1/
    wget http://downloads.arduino.cc/openwrtyun/1/YunSysupgradeImage_v1.5.0.zip

    Install unzip and unzip the package

    opkg update
    opkg install unzip
    unzip YunSysupgradeImage_v1.5.0.zip

    Install upgrade

    run-sysupgrade /mnt/sda1/openwrt-ar71xx-generic-yun-16M-squashfs-sysupgrade.bin

    The output will look like this:

    run-sysupgrade /mnt/sda1/openwrt-ar71xx-generic-yun-16M-squashfs-sysupgrade.bin
    Sending TERM to remaining processes … uhttpd dbus-daemon dnsmasq avahi-daemon thd ntpd uSDaemon sleep syslogd klogd hotplug2 procd ubusd netifd
    Sending KILL to remaining processes …
    Switching to ramdisk…
    Performing system upgrade…
    Unlocking firmware …
    Writing from  to firmware …
    Upgrade completed
    Rebooting system…

    When the process is done you see “Rebooting system…”.

    The Arduino Yun has now gone back to its original settnings. Connect to it with its access point and hook it up to your wifi again. Make it a habit to change name and password for future security.

    Format SD card
    To format the SD card and assign more disk space to OpenWrt follow these steps. All is copied from

    Upload YunDiskSpaceExpander sketch to your Arduino Yun via USB (not over wifi). Make sure that your Arduino Yun is connected to the wifi for this procedure though.

    If you experienced problems uploading the sketch make sure that the Arduino Yun is listed as a known host on your computer with

    Click on the Serial Monitor-button to get started. Write yes to proceed. Make sure that you have “Newline” selected.

    When bridge started write yes to proceed:

    Proceed to partitioning micro SD card and write yes. Then enter the number of MB for data partition.

    The instructions invites you to press the Yun RST button when it is done. The Yun RST button reboots the Arduino Yun and is placed close to the LEDs.

    When the Arduino Yun restarts you can ssh into it and confirm the partition with:

    df -h / /mnt/sda1

    It should look something like:

    Install node
    To install node on your Arduino Yun, enter:

    opkg update
    opkg install node

    To talk to the Arduino part from OpenWrt install the node package serial-port.

    opkg update
    opkg install node-serialport

    Open the serial port for Node so communication between Arduino and OpenWrt can be done:

    vi /etc/inittab

    Add # in front of the last line to comment it out. In the vi editor press i to insert text.

    #ttyATH0::askfirst:/bin/ash –login

    Press Esc and write “:w!” to save and “:q!” to quit editor.

    Now reboot your Arduino Yun and we will get some code going!

    Example code of calling an Arduino sketch from node:

    var SerialPort = require("serialport").SerialPort
    var serialPort = new SerialPort("/dev/ttyATH0", {
        baudrate: 9600,
        dataBits: 8,
        parity: ‘none’,
        stopBits: 1,
        flowControl: false
    }, false);

    serialPort.on("open", function () {
    var data_with_newline = "mydata/n";
         serialPort.write(data_with_newline, function(err, results) {      
          log("send data");
          if(err != undefined) {            
            log(‘err ‘ + err);      

        serialPort.on(‘data’, function(data) {
            log(‘data received: ‘ + data);

      serialPort.on(‘error’, function(err) {
          log(‘error: ‘+err);

    The Arduino sketch receving the data:

    char incomingChar;
    bool incomingCodeReceived = true;

    void setup() {
     while (Serial1.available() > 0 && !incomingCodeReceived) {
       incomingChar = Serial1.read();
       if (incomingChar == \n) {
          incomingCodeReceived = true;
        } else {
        if ((incomingStrLength + 1) < INCOMING_STR_SIZE) {
            incomingStr[incomingStrLength] = incomingChar;
            incomingStrLength += 1;
          } else {
            incomingStrLength = 0;

    void loop() {

    Install forever on Yun

    The Yun doesn’t have enough memory to install this module on its own so the version I use can be downloaded here: Forever.zip

    Make sure your forever module is executable:

    chmod u+x /root/node_modules/forever/bin/forever

    Try it out by typing:


    Crontab on the Yun
    You might want to run a Cron job on your Yun. This can be done by typing:

    /etc/init.d/cron start
    /etc/init.d/cron enable

    Edit your Crontab as you normally do with:

    crontab -e

    Setting static IP of an Arduino Yun
    Soon to be published

  • Servo festival with node.js on Raspberry Pi

    Ellen 17:51 on October 25, 2014 | 0 Permalink | Reply
    Tags: , , servo

    pi-blaster.js was used in the ballon project with 2 servos controlling the flow of helium and cutting the cord to the ballon.

    Running several servo motors on Raspberry Pi with pi-blaster.js works like a charm. Install node.js on your Raspberry to run the pi-blaster.js package.

    Install pi-blaster

    git clone https://github.com/mwilliams03/pi-blaster.git
    cd pi-blaster
    make pi-blaster

    Start pi-blaster deamon

    sudo ./pi-blaster

    Defines outputs to use. In this case I use 2 but you can use up to 8 pins.

    sudo ./pi-blaster 22 24

    Try it out from the command line setting channel 0(GPIO 22) to 0.2.

    echo "0=0.2" > /dev/pi-blaster

    Install pi-plaster.js

    npm install pi-blaster.js

    In your node.js script you can now control your servos like this:

    var piblaster = require(‘pi-blaster.js’); // Import package

    piblaster.setPwm(0, 0.2); // Sets servo on pin 22 to 20 %
    piblaster.setPwm(1, 0.4); // Sets servo on pin 24 to 40%

    To set the pi-blaster setting on reboot, create this shell script and call on reboot crontab:

    sudo /path_to/pi-blaster/pi-blaster 22 24

    To connect a servo motor to Raspberry Pi:

  • Raspberry Pi with Node.js and Alamode

    Ellen 15:52 on July 1, 2014 | 0 Permalink | Reply
    Tags: alamode, , , , serial port


    For this tutorial I use the latest Raspbian version from http://www.raspberrypi.org/downloads.

    Setup Alamode
    Install the arduino IDE on the Raspberry

    sudo apt-get update
    sudo apt-get install arduino

    Get the Alamode setup files and install them by following these steps:

    git clone git://github.com/wyolum/alamode.git
    cd /alamode/alamode-setup
    sudo ./setup

    In order for these setting to take effect, please reboot your Raspberry PI:

    sudo reboot

    Load an Alamode sketch
    If you don’t have your Raspberry Pi connected to screen, keyboard and mouse you can access the GUI from your computer. I have a Mac and use XQuartz.

    As you start XQuartx open the Terminal in this application with Command + N and log into your Raspberry Pi like this:

    ssh -X user@ipaddress

    When you are logged in, just type:


    and the Arduino IDE will start up on your computer.

    The Alamode setup added the Alamode board to your Arduino IDE. Select it by
    Tools > Board > Alamode
    Tools > Serial Port > /dev/ttyAMA0

    Copy the following code and paste it (Ctrl+V) into a new sketch. Put an LED into ground and pin 13 on your Alamode.

    void setup()
      pinMode(13, OUTPUT);

    void loop()
      char inSerial[5];  
      int i=0;
      if (Serial.available() > 0)
           while (Serial.available() > 0) {
             inSerial[i]=Serial.read(); //read data  
           if(!strcmp(inSerial,"high")) {
            digitalWrite(13, HIGH);
          if(!strcmp(inSerial,"low")) {
            digitalWrite(13, LOW);

    To send data from Alamode to Arduino, just write to the serial port with:


    Install node.js

    wget http://nodejs.org/dist/v0.10.12/node-v0.10.12-linux-arm-pi.tar.gz
    tar xvfz node-v0.10.12-linux-arm-pi.tar.gz
    sudo mv node-v0.10.12-linux-arm-pi /opt/node/

    Set the path to node.js:

    echo‘export PATH="$PATH:/opt/node/bin"’ >> ~/.bashrc
    source ~/.bashrc

    Install serialport
    To communicate between the Alamode and node.js we need the serialport package for node.js:

    npm install serialport

    More information on: https://github.com/voodootikigod/node-serialport
    Node.js coding

    var SerialPort = require("serialport").SerialPort
    var serialPort = new SerialPort("/dev/ttyAMA0", {
    baudrate: 9600
    }, false); // this is the openImmediately flag [default is true]

    serialPort.open(function () {

    Trigger this command and “high” will be sent to the Alamode

    // Sends "high" to the Alamode
    serialPort.write("high", function(err, results) {
          if(err != undefined) {
                console.log(‘err ‘ + err);

    To receive serial data from the Alamode, listen for data with this code:

    serialPort.open(function () {
          serialPort.on(‘data’, function(data) {
                console.log(‘data received: ‘ + data);
                if(data == "alamode_data") {
                     // Do something

    External power
    If you are dealing with many power consuming sensors on your Alamode, it’s a good idea to power your Alamode externally with its own 5V power adapter.

  • Control stepper motors with Raspberry Pi and node.js

    Ellen 11:55 on February 25, 2014 | 11 Permalink | Reply
    Tags: , , , , steppers

    Continuing the journey on how to control things with node.js on the Raspberry Pi I set up 2 stepper motors and controlled them in real time with Hydna. You can can read futher on how to install Hydna on Raspberry Pi here.


    Wire up your motors with a stepper motor driver shield. I used Easy Driver and connected it with Pololu stepper motors:
    The to pins that controls the motors in this diagram are pin number 16(GPIO 23) and pin number 18(GPIO 24). Pin number 18 controls the direction of the motor and pin number 16 the speed. With 1K ohm resistors connected to the ground for each of these pins we connect them to the Easy driver.

    Depending on the stepper motor you have, you will need to check the bipolar stepper motor wiring diagram for your motor. The motors I used had the following diagram where A(black) and C(green) connects to the A pins and B(red) and D(blue) connects to B pins.


    Install pi-gpio and go ahead with this script to control the stepper motors:

    var gpio=require("pi-gpio");

    stopMotors = false;

    function sleep(milliseconds) {
      var start = new Date().getTime();
      for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){

      console.log("Pin 16 open"); // Opens pin 16 as output  

      console.log("Pin 18 open"); // Opens pin 18 as output  

    // Runs motor in the set direction
    function move() {
       gpio.write(16, 1, function() {
             gpio.write(16, 0, function() {

    function stopMotor() {
      stopMotors = true;

    // Changing direction of motor
    function left() {
      stopMotors = false;
      gpio.write(18, 1, function() {

    // Changing direction of motor
    function right() {
      stopMotors = false;
      gpio.write(18, 0, function() {

  • Realtime control of GPIO:s with Hydna

    Ellen 12:33 on February 13, 2014 | 0 Permalink | Reply
    Tags: , gpio, , , , realtime


    Want to control the pins on you Raspberry Pi in real time? With the scaleable realtime platform from Hydna you can set how many that can access the GPIOs and when. Install the node modules gpio and hydna to controll your GPIO:s over the net.

    Install node.js

    sudo apt-get upgrade;
    sudo apt-get update
    sudo apt-get install nodejs npm node-semver
    npm config set registry http://registry.npmjs.org/

    Open the profile file with:

    sudo nano /etc/profile

    And enter the following:


    NOTE! Log out and then in again in order to make the changes go through.

    To run nodejs with with the command node, link them to with:

    sudo ln -s /usr/bin/nodejs /usr/bin/node

    Make sure to check where your node was installed and add it to NODE_JS_HOME

    Install GPIO

    npm install pi-gpio

    Install GPIO-ADMIN

    cd /home/pi
    sudo git clone git://github.com/quick2wire/quick2wire-gpio-admin.git
    cd quick2wire-gpio-admin
    sudo make
    sudo make install
    sudo adduser pi gpio

    Try out gpio-admin with the following line:

    gpio-admin export 22

    If you get this error

    Error /bin/sh: 1: gpio-admin: Permission denied

    follow these steps:

    sudo groupadd gpio
    sudo usermod -aG gpio
    sudo chgrp gpio /sys/class/gpio/export
    sudo chgrp gpio /sys/class/gpio/unexport
    sudo chmod 775 /sys/class/gpio/export
    sudo chmod 775 /sys/class/gpio/unexport

    Install Hydna

    npm install hydna

    With Hydna you can send real time messages to your pi and allow a certain number of clients to connect to your Raspberry Pi. With Hydna’s Behaviours you set the behaviours of your different channels.

    The following example code shows how to control your gpios with messages from Hydna:

    var gpio=require("pi-gpio"); // Include the pi-gpio library to control the gpios
    console.log("Pin open"); // Opens pin 12 as output
    var hydna = require(‘hydna’);
    // Open channel in "read/write" mode. All data sent to channel will
    // loop back from the remote connection.
    var channel = hydna.createChannel(‘domainname.hydna.net/rpi’, ‘readwrite’);
    // Connect handler, is triggered once that the channel is connected
    channel.on(‘connect’, function () {
    this.write(‘Status: ok’);
    // Data handler, is triggered each time DATA is received on the channel
    channel.on(‘data’, function (data) {
    // Log data received on channel.
    if(data == "on") {
    gpio.write(12, 1, function() {
    } else if(data == "off") {
    gpio.write(12, 0, function() {
    } else if(data == "end") {
    gpio.close(12); // Close pin
    this.end(); //Close the channel, which terminates the underlying receive-loop.

  • Looping videos seamlessly OMXPlayer

    Ellen 16:30 on October 15, 2013 | 40 Permalink | Reply
    Tags: omxplayer, python,

    As I looked for different solutions for looping videos on the Raspberry Pi seamlessly I eventually came out with a solution that worked quited good for videos looping with sounds. Looking at the possiblities of using the existing example of hello_video/video.c to loop a video wasn’t an option as sound was not supported and syncing sound was not something I wanted to spend time on.

    Instead I looked to jbaiter’s OMXPlayer library pyomxplayer build in python. It calls the OMXPlayer through the command line and with some testing I could run several instances of OMXPlayer at the same time. This meant that I could start one movie and pause a copy of the same movie in the background. When the first movie came to an end I could start the second movie which was an exact copy of the first one in order to get the seamless loop. No terminal windows showing and no gap between the movies. And so the loop goes on.

    By having 2 different names of the same movie I was in complete control of the omxplayer processes running in the background to play another movie on top of this.

    I start off loading both movies by calling making to OMXPlayer instances in pyomxplayer and pausing the second movie:

    self.loop1= OMXPlayer(‘/home/pi/loop1.mp4′, ‘-o local’, start_playback=True, do_dict=False)
    self.loop2 = OMXPlayer(‘/home/pi/loop2.mp4′, ‘-o local’, start_playback=True,do_dict=False)

    In a loop I check when the first video reaches its end position and pause it just before to start the next movie. Since it already loaded, there is no buffering for it to play. Note that the end position needs to be set a little bit before the video exactly ends in order to not get out of the video screen mode.

    position = self.loop1.position/1000000
    if position > 12.8:

    A few seconds later I kill the process of the first movie to start it and pause it for next time.

    os.system(‘pkill -9 -f "/usr/bin/omxplayer.bin -s /home/pi/loop1.mp4 -o local"’)
    os.system(‘pkill -9 -f "/bin/bash /usr/bin/omxplayer -s /home/pi/loop1.mp4 -o local"’)
    self.loop1= OMXPlayer(‘/home/pi/loop1.mp4′, ‘-o local’, start_playback=True, do_dict=False)

    I added a 2 seconds delay in order for the new movie to have time to show and to allow for some time to kill the process.

  • Connect Parallax RFID to Raspberry Pi

    Ellen 15:01 on September 18, 2013 | 5 Permalink | Reply
    Tags: , ,


    To connect a Parallax RFID Reader to the Raspberry Pi you can either use the USB version of the Parallax RFID reader or the pin enabled used in this example. With the pin enabled Parallax version the data is sent to the Raspberry pi serial pins with the pins TXD and RXD pins. With the RFID reader with only need to use RXD as we will only receive data from the RFID reader.

    Wiring setup

    The RFID reader operates on 5V but the Raspberry Pi GPIOs operate on 3.3 V which mean that in order to read the serial data we need to convert it from high volt to low volt. There is circuit available from Sparkfun doing just that. It is called Logic Level Converter and will be part of the wiring between the Raspberry Pi and the RFID reader.

    Below is the schematics for the connections you need to make.

    1. Connect your common ground to both ends of the Logic Level Converter and RFID reader. Note that the Parallax RFID reader needs the Enable pin to be connected to ground in order to read RFID tags. When the LED on the RFID reader turns red it means that it is ready to read. (Black)

    2. Connect the high volt  from 5V pin to HV pin. (Red)

    3. Connect the low volt from 3.3 V pin to LV pin. (Orange)

    4. Connect the SOUT pin to  serial input RXI on the Logic Level Converter. (Blue)

    5. Connect the seriel output RXO to the pin RXD on the Raspberry Pi.

    Screen Shot 2013-09-18 at 3.07.29 PM

    Enable serial port

    To make the serial port available for your own use you need to edit the file /etc/inittab.

    sudo nano /etc/inittab

    Comment out the following line in inittab

    T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

    Like this:

    #T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

    Install minicom for testing

    To read and test your tags on the Raspberry Pi you need a set of packages:
    A great package to test your serial port is to install minicom:

    sudo apt-get install minicom

    To test your serial port you can use mimicom command like this:

    minicom -b 115200 -o -D /dev/ttyAMA0

    Read RFID tags with Python

    To access the serial port from Python install the pySerial package with command line:

    sudo apt-get install python-serial

    Now you can import the serial library on order to access the serial data sent to the Raspberry Pi from the serial port. Note that you can set the timeout of the RFID reader to make the read timeout after a while. The example code below times out the serial read after half a second. This can be useful to set a longer or shorter timeout depending on if you execute other things in your loop or application.

    import serial
    ser = serial.Serial(‘/dev/ttyAMA0′, 2400, timeout=0.5)
    while True:
        string = ser.read(12)  
        if len(string) != 0:
            print string

    Raspberry Pi Lab posted a great Python script on how to check which tag is read in the rfid-test2.py.

  • Clone SD card for Raspberry Pi(Mac)

    Ellen 10:46 on September 16, 2013 | 10 Permalink | Reply
    Tags: , sd card

    Backup SD card

    To clone an SD card setup for your Raspberry Pi on a Mac, do the following:

    Input the SD card you want to clone. Open the Terminal window and type:

    diskutil list

    This will list your connected disks. See the name of your SD card, on mine in looks like this:
    diskutil list on Mac

    Make an image of the content with the following command:

    sudo dd if=/dev/disk1 of=~/Desktop/boot.dmg

    This might take a while and when it is finished you will see how many bytes were transferred.

    Edject your SD card and input the SD card you want to clone to.

    Format new SD card

    If the SD card is not formatted you can open the Disk Utility and select the card(not the volumes) . Click on the “Erase”-tab and select the format “MS-DOS(FAT)”. Name your card and click on the button “Erase”. This will only take a few seconds. The SD card is now formatted in FAT32.

    Screen Shot 2013-09-16 at 11.15.05 AM

    If you want to change the format to FAT16 just go to your Terminal window and type:

    sudo newfs_msdos -F 16 /dev/disk1

    Note that the name of the disk can be different. Run “diskutil list” again to find out.

    Clone SD card

    Now the SD card is prepared to get the cloned image. Unmount the volumes on the SD card before you go ahead with cloning. NOTE! That you should unmount and NOT eject.
    Screen Shot 2013-09-16 at 11.44.26 AM

    To transfer the image you just made before you write in the Terminal window:

    sudo dd if=~/Desktop/boot.dmg of=/dev/disk1

    This can take long depending on the class of your SD card.

    During the process you can to checks that the cloning is progressing. Open a new Terminal window and type:

    ps ax | grep dd

    This will list processes on your computer with “dd” as part of it. At the bottom of the list you will find something like this:

    11502 s002  S+     0:00.01 sudo dd if=~/Desktop/boot.dmg of=/dev/disk1 bs=5
    11503 s002  R+     0:58.27 dd if=~/Desktop/boot.dmg of=/dev/disk1 bs=5
    11524 s003  R+     0:00.00 grep dd

    Note the id of the process and type:

    sudo kill -s SIGINFO 11503

    In the other window where you did your clone command, it will now print out how much data that has been transfered to your SD card in the format seen on success in the below example.

    When the process is finished you will see how many bytes were tranfered and compare it with the bytes when you made the backup.

    60392+1 records in
    60392+0 records out
    30920704 bytes transferred in 132.542963 secs (233288 bytes/sec)

compose new post
next post/next comment
previous post/previous comment
show/hide comments
go to top