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.

Learning Raspberry Pi

Unlock your creative programming potential by creating web technologies, image processing, electronics- and robotics-based projects using the Raspberry Pi

Learning Raspberry Pi

About This Book
  • Learn how to create games, web, and desktop applications using the best features of the Raspberry Pi
  • Discover the powerful development tools that allow you to cross-compile your software and build your own Linux distribution for maximum performance
  • Step-by-step tutorials show you how to quickly develop real-world applications using the Raspberry Pi
Who This Book Is For
If you have a passion for technology and want to explore the world of Raspberry Pi, then this book provides you with all the tools and information you are looking for. Although being familiar with basic programming concepts is useful, you can still learn a lot from this book as a wide variety of topics are covered.

In Detail
Raspberry Pi is one of the most popular development boards and a staple tool among developers because of its low cost and flexibility.

Learning Raspberry Pi is a practical tutorial, providing you with the skills required to design and build your own projects. By working through the examples and projects in the book, you will build up your knowledge of software and hardware development and be able to create projects of your own.

This book contains a set of tutorials and examples for commonly used technologies, accompanied by practical projects that bring the topics together. Each individual project that you become involved with allows you to develop an important set of skills, building up your confidence to tackle more advanced applications of your own.

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


Network and Web applications using Raspberry Pi, Arduino and Teensy

Network and Web applications using Raspberry Pi, Arduino and Teensy

Popular Raspberry Pi miniature computers and small development boards operating in real-time environment can be used together for designing complex and powerful measurement and control systems. In these systems, the high-level programming environment of Raspbian OS running on the Raspberry Pi can be applied for high-level data processing, while real-time signal processing will be performed by some popular and low-cost development board such as Arduino or Teensy 3.1. The great benefit of such configurations is that a developer doesn’t need to build external circuitry that may take a long time.

This highly practical guide describes how to build measurement systems that will include Raspberry Pi 2, Arduino Uno or Teensy 3.1 developments boards and will be controlled over a TCP/IP network or the Internet using a Web browser. Almost all applications from this guide use USB-to-Serial interfaces between Raspberry Pi, Arduino or Teensy 3.1.

The material of the book assumes that the readers are familiar, at least, with basics of designing and assembling electronic circuits. For most projects, having some basic skills in electronics will serve the readers well and allow them to understand what is going on behind the scenes. Each project is accompanied by a detailed description which helps to make things clear.

All projects were designed using Raspberry Pi 2 Model B and Arduino Uno or Teensy 3.1 boards. The source code for applications running on Raspbian OS was developed in Python. The Arduino and Teensy 3.1 applications were developed using Processing and supplemental libraries. Most projects described in this guide can be easily improved or modified if necessary.

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".

Tuesday, April 14, 2015

Learning Raspbian

Get up and running with Raspbian and make the most out of your Raspberry Pi

Learning Raspbian

About This Book
  • Acquire the practical skills required to develop applications in Raspbian
  • Interact with the Raspbian operating system via its console
  • Explore the Raspbian GUI and the bundled console applications with this easy-to-follow guide
Who This Book Is For
This book is intended for developers who have worked with the Raspberry Pi and who want to learn how to make the most of the Raspbian operating system and their Raspberry Pi. Whether you are a beginner to the Raspberry Pi or a seasoned expert, this book will make you familiar with the Raspbian operating system and teach you how to get your Raspberry Pi up and running.

In Detail
The huge popularity of the Raspberry Pi has led to the development of many excellent operating systems such as Raspbian, which is the official operating system for Raspberry Pi. It is a Debian-based operating system that is specially optimized for the Raspberry Pi hardware.

With this book, you will be taken through starting Raspbian after its first boot and move on to learn about the different features of the Raspbian desktop. The book will then walk you through installing different software on your machine to make your work easier, familiarizing you with the console and teaching you how to interact with the Raspbian operating system. Finally, you will be equipped with ample information about other Linux distributions based on Raspbian.

Packed full of useful screenshots, this book is an excellent guide to the Raspbian operating system and will ensure your success with the Raspberry Pi!

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

Raspberry Pi Home Automation with Arduino - Second Edition

Unleash the power of the most popular microboards to build convenient, useful, and fun home automation projects

Raspberry Pi Home Automation with Arduino - Second Edition

About This Book
  • Revolutionize the way you automate your home by combining the power of the Raspberry Pi and Arduino
  • Build simple yet awesome home automated projects using an Arduino and the Raspberry Pi
  • Learn how to dynamically adjust your living environment with detailed step-by-step examples
Who This Book Is For
If you are new to the Raspberry Pi, the Arduino, or home automation and wish to develop some amazing projects using these tools, then this book is for you. Any experience in using the Raspberry Pi would be an added advantage.

In Detail
Revolutionize the way you interact with your home and become part of the rapidly growing group of hobbyists and enthusiasts by combining the powerful Raspberry Pi with an Arduino board.

Starting with an introduction to the Raspberry Pi and Arduino boards you will set up your very own home automation system through a series of exciting projects, making your life a lot easier.

Build a thermostat, a Raspberry Pi control device, a parcel delivery detector, and a water and damp detector, and then move on to more complex projects including a motor mechanism to control your curtains.

By the end of this practical guide, you will be a confident user who can program, set up, and run a wide range of applications using both the Raspberry Pi and the Arduino.

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)

Raspberry Pi For Dummies

Raspberry Pi For Dummies

Master your Raspberry Pi in a flash with this easy-to-followguide

Raspberry Pi For Dummies, 2nd Edition is acomprehensive guide to this exciting technology, fully updated toalign with the Rev 3 board. Veteran technology authors provideexpert insight and guidance that get you up and running fast,allowing you to explore the full capabilities of your Raspberry Pi.The clear, concise style makes this guide easy to follow forcomplete beginners, providing step-by-step instruction throughoutthe setup process and into systems administration and programming.Updated information includes coverage of Noobs, PiStore and makingmusic with SonicPi, in addition to basic Raspberry Pi operationsand features.

Raspberry Pi For Dummies, 2nd Edition teachesyou everything you need to know to get the most out of your device.Even if you've never ventured beyond e-mail and web browsers, thisguide will give you the skills and confidence you need to takeadvantage of everything the Raspberry Pi has to offer. * Find out how to install the operating system and connect toother devices * Install, use and remove software like a pro * Learn basic Linux systems administration * Program with Scratch, Python and Minecraft on your RaspberryPi

The Raspberry Pi has awakened a whole new generation of hardwaregeeks, hackers and hobbyists, and now it's your turn to join theirranks. Learning how to fully use your new technology is the firststep, and Raspberry Pi For Dummies, 2nd Editionis the ideal companion guide.

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