Thursday, April 30, 2015

Windows 10 IoT Core Insider Preview with support for Raspberry Pi 2, available now.

Starting today you can download Windows 10 IoT Core Insider Preview with support for Raspberry Pi 2 and Intel’s Minnowboard Max. Windows 10 IoT Core is a new Windows 10 edition for low-cost, small-footprint devices that will be available ‘free’ for Makers and commercial device builders.

Get Started
Click to Learn how to set up the Raspberry Pi 2 and connect it to your computer. Note that this requires you to have a PC running Windows 10 Technical Preview.


Stream RPi Camera Module Video to network, using Python

It's a example on Picamera docs - Recording to a network stream , to stream video of Raspberry Pi Camera Module to network using Python.

import socket
import time
import picamera

with picamera.PiCamera() as camera:
    camera.resolution = (640, 480)
    camera.framerate = 24

    server_socket = socket.socket()
    server_socket.bind(('0.0.0.0', 8000))
    server_socket.listen(0)

    # Accept a single connection and make a file-like object out of it
    connection = server_socket.accept()[0].makefile('wb')
    try:
        camera.start_recording(connection, format='h264')
        camera.wait_recording(60)
        camera.stop_recording()
    finally:
        connection.close()
        server_socket.close()


Run the Python on Raspberry Pi

View on desktop using VLC

In this scenario, the Pi acts as the server, waiting for a connection from the client. When it accepts a connection, it starts streaming video over it for 60 seconds.

Bo script is needed on the client side - we can simply use VLC with a network URL:

$ vlc tcp/h264://my_pi_address:8000/


There 2~3 seconds delay in my test on Raspberry Pi 2.

Tuesday, April 28, 2015

Install VLC Media Player on Raspberry Pi

VLC is a free and open source cross-platform multimedia player. To install VLC on Raspberry Pi, enter the command at Terminal:

$ sudo apt-get install vlc


Monday, April 27, 2015

Control RPi Camera Module over web - RPi-Cam-Web-Interface


RPi Cam Web Interface is a web interface for the RPi Cam that can be opened on any browser (smartphones included).


To install RPi-Cam-Web-Interface:
(Warning: The installer will replace various files, so backup all your data)

$ git clone https://github.com/silvanmelchior/RPi_Cam_Web_Interface.git
$ cd RPi_Cam_Web_Interface
$ chmod u+x RPi_Cam_Web_Interface_Installer.sh
./RPi_Cam_Web_Interface_Installer.sh install
- Reboot
- Open browser to visit the IP of your Raspberry Pi.

refer: http://elinux.org/RPi-Cam-Web-Interface#Basic_Installation


Check picamera version

To check the version of your installed picamera, in Python:

from pkg_resources import require
print(require('picamera'))
print(require('picamera')[0].version)


Or run dpkg-query in Terminal:
$ dpkg-query -l python-picamera


Sunday, April 26, 2015

Python to capture image from Raspberry Pi Camera Module

This Python 2 code run on Raspberry Pi 2 to capture image from Camera Module.


Because the preview will cover the main screen, so this example run remotely on Android tablet running Microsoft Remote Desktop Client App, login Raspberry Pi via xrdp.


myPiCam.py
import picamera
from time import sleep
import Tkinter
import time
from PIL import ImageTk, Image


def quit():
    camera.stop_preview()
    global tkTop
    tkTop.destroy()

def setBrightness(ev=None):
    global camera
    global tkScale
    camera.brightness = tkScale.get()
    
def loadJpg(file):

    JpgWin = Tkinter.Toplevel(tkTop)
    JpgWin.title('New Window')
    JpgWin.geometry('400x300')

    image = Image.open(file)
    image = image.resize((400, 300), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(image)
    panel = Tkinter.Label(JpgWin, image=img)
    panel.pack(side = "bottom", fill = "both", expand = "yes")

    JpgWin.mainloop()

def capture():
    timeStamp = time.strftime("%Y%m%d-%H%M%S")
    jpgFile='img_'+timeStamp+'.jpg'
    camera.capture(jpgFile)
    loadJpg(jpgFile)

camera = picamera.PiCamera()
camera.start_preview()
camera.brightness = 50

tkTop = Tkinter.Tk()
tkTop.wm_title("Raspberry Pi Camera - Brightness")
tkTop.geometry('400x200')

tkButtonQuit = Tkinter.Button(
    tkTop, text="Quit", command=quit)
tkButtonQuit.pack()

tkButtonCapture = Tkinter.Button(
    tkTop, text="Capture", command=capture)
tkButtonCapture.pack()

tkScale = Tkinter.Scale(
    tkTop,
    from_=0, to=100,
    length=300,
    orient=Tkinter.HORIZONTAL,
    command=setBrightness)
tkScale
tkScale.set(50)
tkScale.pack(anchor=Tkinter.CENTER)

Tkinter.mainloop()



To run the Python code on Raspberry Pi, we need to install PIL with jpg supported:

$ sudo apt-get install libjpeg8-dev

Then find libjpeg.so and create link on /usr/lib/
$ find /usr/lib -name libjpeg.so
/usr/lib/arm-linux-gnueabihf/libjpeg.so
$ sudo ln -s /usr/lib/arm-linux-gnueabihf/libjpeg.so /usr/lib/

Then install PIL and python-imaging-tk
$ sudo apt-get install python-pip
$ sudo pip install PIL


If you reported with error like this:

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DHAVE_LIBJPEG -IlibImaging -I/usr/include -I/usr/local/include -I/usr/include/python2.7 -c _imaging.c -o build/temp.linux-armv7l-2.7/_imaging.o

_imaging.c:75:20: fatal error: Python.h: No such file or directory

compilation terminated.

error: command 'gcc' failed with exit status 1
----------------------------------------

Install python-dev:
$ sudo apt-get install python-dev


$ sudo apt-get install python-imaging-tk


Updated@2015-12-13 for Jessie:
Tested on Raspberry Pi 2 running Raspbian Jessie 2015-11-21, no need install PIL, but still have to install python-imaging-tk.


Friday, April 24, 2015

My Raspberry Pi 2 cannot detect monitor resolution!!!

I use a DVI-HDMI cable to connect my Raspberry Pi 2 to Monitor. Originally, it can recognize the monitor as 1440x900. Suddenly, it cannot recognize it, and treat it as 640x480. Something fail on my RPi 2!? I know how to manually set resolution on /boot/config.txt, but I want it detect automatically.



Correct display on Raspberry Pi 1 board:

Thursday, April 23, 2015

Ubuntu MATE for the Raspberry Pi 2 officially

ubuntu-mate.org now officially provide download of Ubuntu MATE for the Raspberry Pi 2. Here show how to download and boot-up current Ubuntu MATE 15.04 for the Raspberry Pi 2 (2015-04-22 version), on Ubuntu.

In my case, after setup wizard in first boot, system hang-up with failed message:
[FAILED] Failed to start oem-config.service.
See "systemctl status oem-config.service" for details.

Anyway, the system still can run after power-off and re-boot again.

Download Ubuntu MATE for the Raspberry Pi 2 (2015-04-22 version)


Boot-up Ubuntu MATE 15.04 for the Raspberry Pi 2 (2015-04-22 version)


To write the img on microSD, ddrescue is needed. To install ddrescue on Ubuntu, enter the command:
$ sudo apt-get install gddrescue

Wednesday, April 22, 2015

Raspberry Pi Python to set Brightness of Camera Module and preview

Example code of Python 2, run on Raspberry Pi, to control Camera Module, set Brightness and preview. Control Camera Module with picamera, and implement GUI with Tkinter. It's a Tkinter.Scale to set brightness.


Because the preview will be shown on main display, so I run the Python code remotely on Android tablet with Microsoft Remote Desktop app.


testBrightness.py
import picamera
from time import sleep
import Tkinter

def quit():
    camera.stop_preview()
    global tkTop
    tkTop.destroy()

def setBrightness(ev=None):
    global camera
    global tkScale
    camera.brightness = tkScale.get()

camera = picamera.PiCamera()
camera.start_preview()
camera.brightness = 50

tkTop = Tkinter.Tk()
tkTop.wm_title("Raspberry Pi Camera - Brightness")
tkTop.geometry('400x200')

tkButtonQuit = Tkinter.Button(
    tkTop, text="Quit", command=quit)
tkButtonQuit.pack()

tkScale = Tkinter.Scale(
    tkTop,
    from_=0, to=100,
    length=300,
    orient=Tkinter.HORIZONTAL,
    command=setBrightness)
tkScale
tkScale.set(50)
tkScale.pack(anchor=Tkinter.CENTER)

Tkinter.mainloop()


Next:
Python to capture image from Raspberry Pi Camera Module

Friday, April 17, 2015

Install Qt5 on Raspberry Pi/Raspbian and Hello World


Updated@2016-02-27: 
For Raspbian Jessie, qt5-default (Qt 5 development defaults package) is included in default repository. Refer the updated post "Install Qt5/Qt Creator for Raspberry Pi 2/Raspbian Jessie".

A member mentioned in the post on raspberrypi.org forums that there are "backports" packages of Qt5 you can install.



Edit the file: /etc/apt/sources.list and add:
deb http://twolife.be/raspbian/ wheezy main backports
deb-src http://twolife.be/raspbian/ wheezy main backports

Install the required key:
$sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-key 2578B775

Then get Qt5 and esoteric requirements installed:
$ sudo apt-get update
$ sudo apt-get install qt5-default qt5-qmake libegl1-mesa libgles2-mesa



Hello World Qt5 on Raspberry Pi/Raspbian (console application)

- Create a directory, for example, named helloworld. And change to it.
- Create a cpp file, named helloworld.cpp.

#include <QCoreApplication>
#include <QDebug>
#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Qt Version %s\n", QT_VERSION_STR);
    QCoreApplication app(argc, argv);
    qDebug() << "Hello Qt5"; 
    return app.exec();
 
}

Make it with Qt5:
$ qmake -project
$ qmake
$ make


Hello World Qt5 on Raspberry Pi/Raspbian (with GUI widgets)

- Create a directory, for example, named helloqt5. And change to it.
- Create a cpp file, named helloqt5.cpp.

#include <QtWidgets/QApplication>
#include <QtWidgets/QLabel>
#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Qt Version %s\n", QT_VERSION_STR);
 
    QApplication app(argc, argv);
    QLabel *label = new QLabel("Hello Qt5");
    label->show();
    return app.exec();
}

Make it with Qt5:
$ qmake -project
$ qmake
$ make

Now you have some error reported. Like this:

helloqt5.cpp:(.text.startup+0x1c): undefined reference to `QApplication::QApplication(int&, char**, int)'
helloqt5.cpp:(.text.startup+0x50): undefined reference to `QLabel::QLabel(QString const&, QWidget*, QFlags<Qt::WindowType>)'
helloqt5.cpp:(.text.startup+0x60): undefined reference to `QWidget::show()'
helloqt5.cpp:(.text.startup+0x64): undefined reference to `QApplication::exec()'
helloqt5.cpp:(.text.startup+0x70): undefined reference to `QApplication::~QApplication()'
helloqt5.cpp:(.text.startup+0x84): undefined reference to `QApplication::~QApplication()'


Now open and edit helloqt5.pro, add the line "QT += widgets":

TEMPLATE = app
TARGET = helloqt5
INCLUDEPATH += .

QT += widgets

# Input
SOURCES += helloqt5.cpp


Now re-make the project:
$ qmake
$ make


How cool is a fan for Raspberry Pi 2

This video show The cooling effect of fan case for Raspberry Pi 2. Run the Raspberry Pi 2 inside a open top case, to stable around 48C, then cover with fan, the temperature drop to around 37C.


The Python code can be found here: "Plot "vcgencmd measure_temp" on uptime, Raspberry Pi 1 vs 2".

Monday, April 13, 2015

Resize file system on microSD of Ubuntu MATE 15.04 for Raspberry Pi 2

This post show how to resize file system on microSD with Ubuntu MATE 15.04 for Raspberry Pi 2 installed, using Linux GUI application GParted run on another Linux machine.

To install GParted, enter the command:
$ sudo apt-get install gparted

This video show how:


After resized and boot up Ubuntu MATE on Raspberry Pi 2, now I have 15.7G on a 16G microSD.




This page (eLinux: RPi Resize Flash Partitions http://elinux.org/RPi_Resize_Flash_Partitions) describes activities relating to partitions on the Raspberry Pi for Linux based operating systems, such as Raspian Linux. It may also apply to other operating systems too, but you should check. Incorrectly using the instructions is likely to corrupt your system.

Sunday, April 12, 2015

Ubuntu MATE 15.04 for Raspberry Pi 2


It's Ubuntu MATE 15.04 for the Raspberry Pi 2, you can find more details and download link here: https://ubuntu-mate.community/t/ubuntu-mate-15-04-for-raspberry-pi-2/517.


This video show how to download and burn microSD on Ubuntu Linux.


And my first boot Ubuntu MATE 15.04 for Raspberry Pi 2:

The OS unresponsive at the first boot only. After sometime, it become more smooth.

I always run apt-get update and upgrade on Raspberry Pi/Raspbian. The first time it run more than 14 hrs to finish.
$ sudo apt-get update
$ sudo apt-get upgrade

This video below show remote login Ubuntu MATE 15.04 for Raspberry Pi 2 with ssh from PC running Ubuntu Linux. Then install xrdp on ubuntuMATE@RPi 2, and login xrdp using Remmina.



After installed, the microSD partition to have 4G only. I use Linux GUI program gparted to resize the file system.




Updated:
- Ubuntu MATE for the Raspberry Pi 2 officially

Updated@2014-04-26:
Download, install and boot-up Ubuntu MATE 16.04 on Raspberry Pi 3

Saturday, April 11, 2015

mono/C# on Raspberry Pi, get system info

Example to get system info with mono/C# run on Raspberry Pi, using System.Environment class.


using System;
using System.Collections;

namespace Csharp_SysInfo
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            printSysInfo ();
        }

        /*
         * reference:
         * https://msdn.microsoft.com/en-us/library/system.environment.aspx
         */
        private static void printSysInfo ()
        {
            String str;
            String nl = Environment.NewLine;
            //
            Console.WriteLine ();
            Console.WriteLine ("-- Environment members --");

            //  Invoke this sample with an arbitrary set of command line arguments.
            Console.WriteLine ("CommandLine: {0}", Environment.CommandLine);

            String[] arguments = Environment.GetCommandLineArgs ();
            Console.WriteLine ("GetCommandLineArgs: {0}", String.Join (", ", arguments));

            //  <-- Keep this information secure! -->
            Console.WriteLine ("CurrentDirectory: {0}", Environment.CurrentDirectory);

            Console.WriteLine ("ExitCode: {0}", Environment.ExitCode);

            Console.WriteLine ("HasShutdownStarted: {0}", Environment.HasShutdownStarted);

            //  <-- Keep this information secure! -->
            Console.WriteLine ("MachineName: {0}", Environment.MachineName);

            Console.WriteLine ("NewLine: {0}  first line{0}  second line{0}  third line",
                Environment.NewLine);

            Console.WriteLine ("OSVersion: {0}", Environment.OSVersion.ToString ());

            Console.WriteLine ("StackTrace: '{0}'", Environment.StackTrace);

            //  <-- Keep this information secure! -->
            Console.WriteLine ("SystemDirectory: {0}", Environment.SystemDirectory);

            Console.WriteLine ("TickCount: {0}", Environment.TickCount);

            //  <-- Keep this information secure! -->
            Console.WriteLine ("UserDomainName: {0}", Environment.UserDomainName);

            Console.WriteLine ("UserInteractive: {0}", Environment.UserInteractive);

            //  <-- Keep this information secure! -->
            Console.WriteLine ("UserName: {0}", Environment.UserName);

            Console.WriteLine ("Version: {0}", Environment.Version.ToString ());

            Console.WriteLine ("WorkingSet: {0}", Environment.WorkingSet);

            //  No example for Exit(exitCode) because doing so would terminate this example. 

            //  <-- Keep this information secure! -->
            String query = "My system drive is %SystemDrive% and my system root is %SystemRoot%";
            str = Environment.ExpandEnvironmentVariables (query);
            Console.WriteLine ("ExpandEnvironmentVariables: {0}  {1}", nl, str);

            Console.WriteLine ("GetEnvironmentVariable: {0}  My temporary directory is {1}.", nl,
                Environment.GetEnvironmentVariable ("TEMP"));

            Console.WriteLine ("GetEnvironmentVariables: ");
            IDictionary environmentVariables = Environment.GetEnvironmentVariables ();
            foreach (DictionaryEntry de in environmentVariables) {
                Console.WriteLine ("  {0} = {1}", de.Key, de.Value);
            }

            Console.WriteLine ("GetFolderPath: {0}", 
                Environment.GetFolderPath (Environment.SpecialFolder.System));

            String[] drives = Environment.GetLogicalDrives ();
            Console.WriteLine ("GetLogicalDrives: {0}", String.Join (", ", drives));
        }
    }
}

Solve MonoDevelop error: cannot execute "...". File name hase not been set.

After you Install Mono/MonoDevelop on Raspberry Pi/Raspbian or Install latest version of Mono and MonoDevelop on Raspberry Pi/Raspbian, try to run your first "Hello World" in MonoDevelop, but report error of cannot execute "...". File name hase not been set.

To solve it, close MonoDevelop.

Install xterm in LXTerminal
$ sudo apt-get install xterm

Restart MonoDevelop, problem solved.


Java 8 example: call between Java and Javascript

This example show how to call Javascript function from Java, and call Java method from Javascript.


JavaTryJavaScript.java
package javatryjavascript;

import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavaTryJavaScript {
    
    final static String myJavascript = "/home/pi/testJS/newjavascript.js";

    public static void main(String[] args) 
            throws FileNotFoundException, ScriptException, NoSuchMethodException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashornEngine = scriptEngineManager.getEngineByName("nashorn");
        
        FileReader fileReader = new FileReader(myJavascript);
        nashornEngine.eval(fileReader);
        
        Invocable invocable = (Invocable)nashornEngine;
        invocable.invokeFunction("testJavaScript1", "Hello from Java");
        
    }
    
    public static void JavaCalledFromJS(String s){
        System.out.println("Java method called from JavaScript: " + s);
    }
    
}

The Javascript in a separated file, /home/pi/testJS/newjavascript.js
var testJavaScript1 = function(a){
    print('testJavaScript1, called from Java: ' + a);
    testJavaScript2();
    return;
}

var testJavaScript2 = function(){
    print('testJavaScript2');
    var javaClass = Java.type("javatryjavascript.JavaTryJavaScript");
    javaClass.JavaCalledFromJS("message from JavaScript");
    return;
}

Read dweet.io JSON using Java, develop and run on Raspberry Pi

I have a previous exercise of "Python to send data to Cloud". It can be viewed on browser at: http://dweet.io/follow/helloRaspberryPi_RPi2_vcgencmd.


Or read the dweets in JSON at: https://dweet.io/get/dweets/for/helloRaspberryPi_RPi2_vcgencmd
(Note that dweet.io only holds on to the last 500 dweets over a 24 hour period. If the thing hasn't dweeted in the last 24 hours, its history will be removed.)


Here is a Java exercise to parse the dweets JSON, develop and run on Raspberry Pi 2 with Netbeans IDE. Suppose it can run on any other Java SE supported platform.

JavaDweetIO.java
package javadweetio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JavaDweetIO {

    public static void main(String[] args) {
        
        String myThing = "helloRaspberryPi_RPi2_vcgencmd";
        try {
            JSONObject json = 
                ReadJSON("http://dweet.io/get/dweets/for/" + myThing);

            JSONArray jsonArray_with = json.getJSONArray("with");
            
            for(int i=0; i<jsonArray_with.length(); i++){
                JSONObject jsonObject_with = (JSONObject) jsonArray_with.get(i);
                String created = jsonObject_with.getString("created");
                JSONObject jsonObject_with_content = 
                    jsonObject_with.getJSONObject("content");
                Double RaspberryPi2_core_temp = 
                    jsonObject_with_content.getDouble("RaspberryPi2_core_temp");
                
                System.out.println(created);
                System.out.println(RaspberryPi2_core_temp);
                System.out.println("-----");
            }
            
        } catch (IOException | JSONException e){
            System.out.println(e.toString());
        }
    }

    public static JSONObject ReadJSON(String url) 
            throws IOException, JSONException {
        
        try (InputStream inputStream = new URL(url).openStream()) {
            InputStreamReader inputStreamReader = 
                new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader bufferedReader = 
                new BufferedReader(inputStreamReader);

            StringBuilder jsonBody = new StringBuilder();
            int singleChar;
            while ((singleChar = bufferedReader.read()) != -1) {
                jsonBody.append((char)singleChar);
            }

            JSONObject json = new JSONObject(jsonBody.toString());
            return json;
        }
    }
}


To import org.json in our Java code, we have to Add org.json library, java-json.jar, to NetBeans Java project.




If you want check the JSON online, before you parse it, you can try: http://jsonlint.com/



Add org.json library, java-json.jar, to NetBeans Java project. Run on Raspberry Pi

In next example, I will retrieve my dweet.io thing in JSON format. I will use JSON in Java (org.json) to parse JSON. The java-json.jar can be download here: http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

This video show how to download and add java-json.jar (org.json) to Netbeans Java project, run on Raspberry Pi 2/Raspbian. Suppose it is same in NetBeans run on other platforms.

Wednesday, April 8, 2015

Plot "vcgencmd measure_temp" on uptime, Raspberry Pi 1 vs 2

It's a Python script to plot "vcgencmd measure_temp" on uptime.

plotTemp.py
import os
import matplotlib.pyplot as plt
import multiprocessing

tempC = []
upTimes = []
plt.ion()
cnt=0

def getUpTIme():
    ut = os.popen("awk '{print $1}' /proc/uptime").readline()
    return ut

def plotNow():
    plt.clf()
    plt.ylim(20,60)
    plt.title(title)
    plt.grid(True)
    plt.ylabel('Temp (C)')
    plt.xlabel('uptime (S)')
    plt.plot(upTimes, tempC, 'rx-')
    plt.show()

numOfCPU = multiprocessing.cpu_count()
title = "temp. vs uptime@Raspberry Pi (" + str(numOfCPU) + " core)"

while True:
    ostemp = os.popen('vcgencmd measure_temp').readline()
    temp = (ostemp.replace("temp=", "").replace("'C\n", ""))
    tempC.append(temp)
    
    ut = getUpTIme()
    upTimes.append(ut)

    print(len(tempC))
    print(temp)
    print("uptime(sec) = "+ut)
    
    if len(tempC)>=200:
        tempC.pop(0)
        upTimes.pop(0)
    
    plotNow()
    plt.pause(1)



Run on Raspberry Pi 1 Model B, with medium overclock, at power up, running this script only:




Run on Raspberry Pi 2 Model B, with medium overclock.


at power up, running this sript only:

Playing Youtube:

Python to get uptime of Raspberry Pi, in second

In linux, the command "$ cat /proc/uptime" shows how long the system has been on since it was last restarted. ~ http://en.wikipedia.org/wiki/Uptime#Using_uptime


This Python example code get uptime in second, run on Raspberry Pi:
import os

uptime = os.popen("awk '{print $1}' /proc/uptime").readline()
print("uptime(sec) = "+uptime)


Plot RPi 2 core temperature using Python 2 and matplotlib.pyplot

Similar to the previous example "Display Raspberry Pi CPU temperature graphically, using Python 2 with Matplotlib and drawnow", but use library of matplotlib.pyplot only, no drawnow.


import os
import matplotlib.pyplot as plt

tempC = []
plt.ion()
cnt=0

def plotNow():
    plt.clf()
    plt.ylim(20,80)
    plt.title('Raspberry Pi core temperture')
    plt.grid(True)
    plt.ylabel('Temp C')
    plt.plot(tempC, 'rx-', label='Degrees C')
    plt.legend(loc='upper right')
    plt.plot(tempC)
    plt.show()

#pre-load dummy data
for i in range(0,26):
    tempC.append(0)
    
while True:
    ostemp = os.popen('vcgencmd measure_temp').readline()
    temp = (ostemp.replace("temp=", "").replace("'C\n", ""))
    print(temp)
    tempC.append(temp)
    tempC.pop(0)
    plotNow()
    plt.pause(.5)



Python comment block of code using IDLE

IDLE (Python IDE) have a very useful function to comment or un-comment block of code, Alt-3 and Alt-4.



Sunday, April 5, 2015

Ubuntu 14.10 run on Raspberry Pi 2, with LXDE desktop

A Rasperry Pi Forum contributor, wintrmute, released Ubuntu 14.10 / Linaro 15.01 "developer" image for the Raspberry Pi 2, with LXDE desktop. It can be download here: http://www.raspberrypi.org/forums/viewtopic.php?f=56&t=98997.

Default hostname: raspberry
Default user: linaro (password=linaro)


It's my first try:
(The Raspberry Pi screen is capture from AV output using USB Video Adapter, so it is in low resolution and quality)

Saturday, April 4, 2015

Create dashboards for dweet.io things with freeboard.io

With freeboard.io, you can create simple dashboards for your devices, include dweet.io things. In previous post, I have create my thing of RPi 2 core temp at dweet.io.


This video show how to create a simple dashboard on freeboard.io link to my thing on dweet.io.



My dashboard on freeboard.io: https://freeboard.io/board/2u9N6O

Updated version of dweetIoTemp.py, to send data to dweet.io.
#$ sudo pip install requests
import requests
import os
import matplotlib.pyplot as plt
from drawnow import *

# This example send the core temperature of Raspberry Pi
# to http://dweet.io/, a IoT on Cloud.
# with name = helloRaspberryPi_RPi2_vcgencmd
#
# To check this dweet, visit here on browser
# http://dweet.io/follow/helloRaspberryPi_RPi2_vcgencmd
#
dweetIO = "https://dweet.io/dweet/for/"
myName = "helloRaspberryPi_RPi2_vcgencmd"
myKey = "RaspberryPi2_core_temp"
myLink = "link=http://helloraspberrypi.blogspot.com/"

tempC = []

plt.ion()
cnt=0

def plotTempC():
    plt.ylim(20,80)
    plt.title('Raspberry Pi core temperture')
    plt.grid(True)
    plt.ylabel('Temp C')
    plt.plot(tempC, 'rx-', label='Degrees C')
    plt.legend(loc='upper right')

#pre-load dummy data
for i in range(0,26):
    tempC.append(0)
    
while True:

    ostemp = os.popen('vcgencmd measure_temp').readline()
    temp = (ostemp.replace("temp=", "").replace("'C\n", ""))
    print(temp)
    tempC.append(temp)
    tempC.pop(0)
    drawnow(plotTempC)

    #Send to Cloud, dweet.io
    rqsString = dweetIO+myName+'?'+myKey+'='+str(temp)+'&'+myLink
    print(rqsString)
    rqs = requests.get(rqsString)
    print rqs.status_code
    print rqs.headers
    print rqs.content
    
    plt.pause(.5)



Related example on Arduino:
Arduino Uno + Ethernet Shield send data to dweet.io and freeboard.io

Install latest version of Mono and MonoDevelop on Raspberry Pi/Raspbian

My previous post show Install Mono/MonoDevelop on Raspberry Pi/Raspbian using the default package repository. The installed version will be mono 3.2.8 and monodevelop 3.0.3.2. Alternatively, we can update the package repository on the system to install with latest release: mono 3.12.1 and monodevelop 5.7.0 currently.




The page http://www.monodevelop.com/download/linux/ and http://www.mono-project.com/docs/getting-started/install/linux/#debian-ubuntu-and-derivatives provide instructions to install MonoDevelop and Mono on Linux, include Debian. We can follow the steps to install on Raspberry Pi/Raspbian.

My steps is summrized here:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF

echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list

echo "deb http://download.mono-project.com/repo/debian wheezy-apache24-compat main" | sudo tee -a /etc/apt/sources.list.d/mono-xamarin.list

sudo apt-get update
sudo apt-get upgrade

sudo apt-get install mono-devel
sudo apt-get install mono-complete
sudo apt-get install referenceassemblies-pcl

sudo apt-get install monodevelop
sudo apt-get install monodevelop-nunit
sudo apt-get install monodevelop-versioncontrol
sudo apt-get install monodevelop-database

The videos show how to, on Raspberry Pi 2/Raspbian:



Here how it run remotely via ssh:



and via xrdp on Raspberry Pi and remmina on Ubuntu Linux:




Related:
- Solve MonoDevelop error: cannot execute "...". File name hase not been set.

Friday, April 3, 2015

IoT at dweet.io, Python on RPi 2 to send data to Cloud

This example modify from my previous example of "Display Raspberry Pi CPU temperature graphically, using Python 2 with Matplotlib", add the function to send the temperature to cloud, dweet.io.



dweet.io doesn't require any setup or sign-up— just publish and go.

dweet.io is simple publishing and subscribing for machines, sensors, devices, robots, and gadgets (we just call them things). We call published messages ‘dweets’. It’s helpful to think of dweet.io as a Twitter for things, in fact.



This example code run on Python 2, Raspberry Pi 2/Raspbian, get CPU temperature, plot the graph on local screen, and send to dweet.io, with API like this:
https://dweet.io/dweet/for/helloRaspberryPi_RPi2_vcgencmd?measure_temp=xx.x

Where helloRaspberryPi_RPi2_vcgencmd is my-thing-name. To view my thing online, visit:
http://dweet.io/follow/helloRaspberryPi_RPi2_vcgencmd

Please notice that it is just a trial experience, not a completed example.

View on dweet.io

view on Raspberry Pi 2

#$ sudo pip install requests
import requests
import os
import matplotlib.pyplot as plt
from drawnow import *

# This example send the core temperature of Raspberry Pi
# to http://dweet.io/, a IoT on Cloud.
# with name = helloRaspberryPi_RPi2_vcgencmd
#
# To check this dweet, visit here on browser
# http://dweet.io/follow/helloRaspberryPi_RPi2_vcgencmd
#
dweetIO = "https://dweet.io/dweet/for/"
myName = "helloRaspberryPi_RPi2_vcgencmd"
myKey = "measure_temp"

tempC = []

plt.ion()
cnt=0

def plotTempC():
    plt.ylim(20,80)
    plt.title('Raspberry Pi core temperture')
    plt.grid(True)
    plt.ylabel('Temp C')
    plt.plot(tempC, 'rx-', label='Degrees C')
    plt.legend(loc='upper right')

#pre-load dummy data
for i in range(0,26):
    tempC.append(0)
    
while True:

    ostemp = os.popen('vcgencmd measure_temp').readline()
    temp = (ostemp.replace("temp=", "").replace("'C\n", ""))
    print(temp)
    tempC.append(temp)
    tempC.pop(0)
    drawnow(plotTempC)

    #Send to Cloud, dweet.io
    rqsString = dweetIO+myName+'?'+myKey+'='+str(temp)
    print(rqsString)
    rqs = requests.get(rqsString)
    print rqs.status_code
    print rqs.headers
    print rqs.content
    
    plt.pause(.5)


Next:
Create dashboards for dweet.io things with freeboard.io
Read dweet.io JSON using Java

Related example on Arduino:
Arduino Uno + Ethernet Shield send data to dweet.io and freeboard.io

Thursday, April 2, 2015

Create Gtk# application using C#/MonoDevelop on Raspberry Pi

This video show creating Gtk# GUI application of Hello World on Raspberry Pi 2 using C#/MonoDevelop.




Related:
- Install Mono/MonoDevelop on Raspberry Pi/Raspbian


What is Gtk#?
Gtk# is a Graphical User Interface Toolkit for mono and .Net. The project binds the gtk+ toolkit and assorted GNOME libraries, enabling fully native graphical Gnome application development using the Mono and .Net development frameworks.
~ reference: http://www.mono-project.com/docs/gui/gtksharp/

Install Mono/MonoDevelop on Raspberry Pi/Raspbian

MonoDevelop run on Raspberry Pi 2/Raspbian


Mono, sponsored by Xamarin, is an open source implementation of Microsoft's .NET Framework based on the ECMA standards for C# and the Common Language Runtime.

MonoDevelop enables developers to quickly write desktop and web applications on Linux, Windows and Mac OS X.


Always run this commands to update your apt before installation:
$ sudo apt-get update
$ sudo apt-get upgrade

To install Mono/MonoDevelop on Raspberry Pi running Raspbian:
$ sudo apt-get install mono-complete
$ sudo apt-get install monodevelop

This video show how to install on Raspberry Pi 2 running Raspbian version 2015-02-16.


The current installed version is mono-complete 3.2.8 and monodevelop 3.0.3.2.


Once installed, run it with Menu > Programming > MonoDevelop




THis video show a "Hello World" of C# console program build using MonoDevelop running on Raspberry Pi 2:


Next:
- Create Gtk# application using C#/MonoDevelop on Raspberry Pi 2

Related:
- Solve MonoDevelop error: cannot execute "...". File name hase not been set.


Updated: Install latest version of Mono and MonoDevelop on Raspberry Pi/Raspbian

Wednesday, April 1, 2015

List all Linux command available - compgen

To list all available Linux command can be run:
$ compgen -c

To list all command start with "ls"
$ compgen -c ls

To list all command contain the letters "ls"
$ compgen -c | grep ls