Updates from admin RSS

  • Control stepper motors with Raspberry Pi and node.js

    Ellen 11:55 on February 25, 2014 | 5 Permalink | Reply
    Tags: , motors, , , 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.

    stepper_motors_sundh_com

    Wire up your motors with a stepper motor driver shield. I used Easy Driver and connected it with Pololu stepper motors:
    nodejs_stepper_motor_ellen_sundh
    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.

    0J2296.230

    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){
          break;
        }
      }
    }

    gpio.open(16,"output",function(err){    
      console.log("Pin 16 open"); // Opens pin 16 as output  
    });

    gpio.open(18,"output",function(err){    
      console.log("Pin 18 open"); // Opens pin 18 as output  
    });

    // Runs motor in the set direction
    function move() {
       gpio.write(16, 1, function() {
            sleep(1000);  
             gpio.write(16, 0, function() {
                sleep(1000);
                if(!stopMotors)move();
            });      
          });
    }

    function stopMotor() {
      stopMotors = true;
    }

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

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

  • Realtime control of GPIO:s with Hydna

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

    raspberry_pi_nodejs_hydna

    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:

    NODE_JS_HOME=/usr/bin/nodejs
    PATH=$PATH:$NODE_JS_HOME/bin

    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
    su
    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
    gpio.open(12,"output",function(err){
    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.
    console.log(data);
    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 | 21 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)
    self.loop2.toggle_pause()

    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:
         self.loop1.toggle_pause()

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

    sleep(2)
    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"’)
    sleep(2)
    self.loop1= OMXPlayer(‘/home/pi/loop1.mp4′, ‘-o local’, start_playback=True, do_dict=False)
    self.loop1.toggle_pause()

    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 | 2 Permalink | Reply
    Tags: , ,

    parallax_rfid_reader

    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 | 8 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)

  • Useful Raspberry Pi commands

    Ellen 09:54 on September 12, 2013 | 0 Permalink | Reply
    Tags: commands,

    Autostart desktop

    1. Enter the following on the command line

    sudo raspi-config

    2. Select “3 Enable Boot to Desktop” with your arrow keys and press enter key
    3. Select and press enter key and your are back on the main menu
    4. Select with the tab key
    5. A dialogue saying “Would you like to reboot now?” Select with the tab key

    Autologin

    Enter the following on the command line

    sudo nano /etc/inittab

    Change the line:

    1:2345:respawn:/sbin/getty noclear 38400 tty1

    to this with {USER} as the name of the user you want to auto login with

    1:2345:respawn:/sbin/getty autologin pi  38400 tty1

    Hide mouse

    Install unclutter and it will hide when there is not activity.

    sudo apt-get install unclutter

    Then set a delay for how long it will take before hiding the mouse through the command line:

    unclutter -idle 1

    You can also set it for a specific user

    unclutter -idle 1 -user

    If you always want to hide the mouse, add the code into a shell script and make an auto start file like below:

    Autostart python script

    1. Create a desktop file that will run your python script

    cd /usr/share/applications/
    sudo nano app.desktop

    Add the following content to your desktop file:

    [Desktop Entry]
    Encoding=UTF-8
    Type=Application
    Name=app
    Comment=Start application
    Exec=sudo python path_to_your_script.py
    StartupNofitfy=false
    Terminal=false
    Hidden=false

    2. Save the file and exit the editor.

    3. Add the desktop file to your autostart directory with this command

    ln -s /usr/share/applications/app.desktop ~/.config/autostart/

    Make sure that you add this to the user you log in to. So if you log in as pi, stand in the directory pi and run the above command. If you use another user it would be /home/username/.config/autostart/

    To double check that your desktop file runs you can run it from /usr/share/applications/ directory.

    4. Reboot and see result

    Kill all processes for one service

    pkill omx

    From Python script:

    os.system(‘pkill omx’)

    Kill a certain process

    To kill a certain process you can pass it the entire command of the process to target just that process.

    pkill -9 -f "/bin/bash /usr/bin/omxplayer -s /home/pi/myfilm.mp4 -o local"

    This can be done directly from Python as well:

    os.system(‘pkill -9 -f "/bin/bash /usr/bin/omxplayer -s /home/pi/myfilm.mp4 -o local"’)

  • How to enable reverb in FMOD iOS

    Ellen 19:40 on May 5, 2013 | 0 Permalink | Reply
    Tags: , iOS

    To enable reverb settings in Fmod Designer click on “Window” > “Reverb Defs”. Select your reverb and click on the play button. The reverb is now active and the project can be built. Notice that for the time being Fmod Designer requires you to always activate this whenever you open your project. This is not done automatically. The name of your reverb, in this case “Reverb00″ is used later on in the code.

    Fmod_designer

    To activate the reverb in the code the follow code needs to be added:

    #import "SoundManager.h"
    #import "mySoundProject.h"
    @implementation SoundManager
    void ERRCHECK(FMOD_RESULT result)
    {
        if (result != FMOD_OK)
        {
            //fprintf(stderr, "FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
            exit(-1);
        }
    }
    - (id)initWithString:(NSString*)selectedProfile
    {
    system  = NULL;
        eventSystem = NULL;
     
        FMOD_RESULT result      = FMOD_OK;
        char        buffer[200] = {0};
        FMOD_REVERB_PROPERTIES reverb00;
       
        result = FMOD::EventSystem_Create(&eventSystem);
        ERRCHECK(result);
       
        result = eventSystem->init(32, FMOD_INIT_NORMAL | FMOD_INIT_ENABLE_PROFILE  | FMOD_INIT_DISTANCE_FILTERING, NULL, FMOD_EVENT_INIT_NORMAL);
        ERRCHECK(result);
        [[NSString stringWithFormat:@"%@/mySoundProject.fev", [[NSBundle mainBundle] resourcePath]] getCString:buffer maxLength:200 encoding:NSASCIIStringEncoding];
        result = eventSystem->load(buffer, NULL, NULL);
        ERRCHECK(result);
       
        result = eventSystem->getReverbPreset("REVERB00", &reverb00); // Same name as in Fmod Designer.
        ERRCHECK(result);
       
        result = eventSystem->setReverbProperties(&reverb00);
        ERRCHECK(result);
       
        result = eventSystem->getGroup("MySoundProject/MySoundProject", FMOD_EVENT_DEFAULT, &group);
        ERRCHECK(result);

  • Send OSC messages from Unity

    Ellen 11:30 on January 31, 2013 | 3 Permalink | Reply

    Many people wrote to me wondering how to send data from Unity through OSC back to Processing and other applications. Well the answer is simple, write the following code:

    oscListener.oscHandler.Send(Osc.StringToOscMessage(”/Your event name”));

  • Real time blend 2 textures in Unity

    Ellen 08:40 on September 6, 2012 | 6 Permalink | Reply
    Tags: , shaders,

    I had a hard time changing the texture of a game object in real-time where I tried out a movie fading between textures and using Lerp on the material. I wanted it to be dynamic and just be able to pass an argument to my script defining which texture to animate to. Many game objects had different shaders so it didn’t work just to Lerp the current material. So I create custom shaders for different objects that contained 2 textures “_MainTex” and “_Texture2″. I also added the blend option the the shader order to be able to control the blend of the texture from outside. Just adding the shader you can change the blend slider to see the result.

    See example of one diffuse shader with normal map.

    In my javascript I could then pass in which texture to change to and which one to change from.
    I set the textures I want to change between. These are set in the inspector of athouring environment of Unity and passed to the script.

    var firstTexture:Texture;
    var secondTexture:Texture;
    var thirdTexture:Texture;

    The script starts out with setting the default texture of the chosen game object. The game object could have been passed to the script as well. :-)

    function Start () {
        textureObject = gameObject.Find("myTextureObject");
        textureObject.renderer.material.SetFloat( "_Blend", 1 ); // Setting the current texture to be 100% visible
    }

    The public function changeTexture can be accessed from outside to recieve arguments for new textures. newTexture is used to store the new texture as soon as it is time to animate.

    public function changeTexture(myArg : float) {
      yield WaitForSeconds(0.3);

      if(myArg == 1) {
          newTexture = firstTexture;
      } else if (myArg == 2){
          newTexture = secondTexture;
      } else if (myArg == 3){
          newTexture = thirdTexture;
      }

      textureObject.renderer.material.mainTexture = newTexture;
      triggerChange = true;
    }

    In the update function the script always checks if it should change to a new texture. If changeTexture was called it starts blending to the new texture. At the end it sets the old texture to the new one and resets the blend:

    function Update () {
         if(triggerChange == true) {
              changeCount = changeCount - 0.05;

              textureObject.renderer.material.SetFloat( "_Blend", changeCount );
              if(changeCount <= 0) {
                   triggerChange = false;
                   changeCount = 1.0;
                   textureObject.renderer.material.SetTexture ("_Texture2", newTexture);
                   textureObject.renderer.material.SetFloat( "_Blend", 1);
              }

         }
    }

    BlendTextures.js is the entire javascript file of the script above.

    To implement this in Unity follow these steps:
    1. Add your script to the scene. Select the textures and normalmap you defined as public variables in BlendTextures.js.
    2. Create a material and choose your custom shader.
    3. Add the material to your game object.

    blend_textures_unity

    Read up on how to create your custom shaders in the Unity Documentation.

  • Unity + Processing Demo

    Ellen 10:11 on July 2, 2012 | 4 Permalink | Reply
    Tags: osc, , ,

    Test your Unity project with the Processing Osc Demo. Send your events through the Processing app and see them appear in the Unity project. There is also a timer in Processing sending events at all time changing the width of a cube in Unity. Download the Unity OSC example here.
    unity_processing_demo

c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
esc
cancel