Monday, May 30, 2016

Raspberry Pi Cookbook: Software and Hardware Problems and Solutions 2nd Edition

Raspberry Pi Cookbook: Software and Hardware Problems and Solutions

With millions of new users and several new models, the Raspberry Pi ecosystem continues to expand—along with a lot of new questions about the Pi’s capabilities. The second edition of this popular cookbook provides more than 240 hands-on recipes for running this tiny low-cost computer with Linux, programming it with Python, and hooking up sensors, motors, and other hardware—including Arduino and the Internet of Things.

Prolific hacker and author Simon Monk also teaches basic principles to help you use new technologies with Raspberry Pi as its ecosystem continues to develop. This cookbook is ideal for programmers and hobbyists familiar with the Pi through resources, including Getting Started with Raspberry Pi (O’Reilly). Python and other code examples from the book are available on GitHub.
  • Set up your Raspberry Pi and connect to a network
  • Work with its Linux-based operating system
  • Program Raspberry Pi with Python
  • Give your Pi "eyes" with computer vision
  • Control hardware through the GPIO connector
  • Use Raspberry Pi to run different types of motors
  • Work with switches, keypads, and other digital inputs
  • Use sensors to measure temperature, light, and distance
  • Connect to IoT devices in various ways
  • Create dynamic projects with Arduino

Sunday, May 29, 2016

Java Datagram/UDP Server and Client, run on raspberry Pi


A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed. It's simple exampls of Datagram/UDP Client and Server, modified from Java Tutorial - Writing a Datagram Client and Server.

It's assumed both server and client run on the same Raspberry Pi, so the IP is fixed "127.0.0.1", local loopback. And the port is arbitrarily chosen 4445.


In the Server side, JavaUdpServer.java, creates a DatagramSocket on port 4445. Wait for client connect, and reply with current date/time.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

/*
reference:
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
*/
public class JavaUdpServer {
    
    static UdpServerThread udpServerThread;

    public static void main(String[] args) throws IOException {
        System.out.println("Server start");
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        
        
        new UdpServerThread().start();
    }

    private static class UdpServerThread extends Thread{
        
        final int serverport = 4445;
        
        protected DatagramSocket socket = null;
        
        public UdpServerThread() throws IOException {
            this("UdpServerThread");
        }
        
        public UdpServerThread(String name) throws IOException {
            super(name);
            socket = new DatagramSocket(serverport);
            System.out.println("JavaUdpServer run on: " + serverport);
        }

        @Override
        public void run() {
            
            while(true){
                
                try {
                    byte[] buf = new byte[256];
                    
                    // receive request
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    socket.receive(packet);
                    
                    String dString = new Date().toString();
                    buf = dString.getBytes();
                    
                    // send the response to the client at "address" and "port"
                    InetAddress address = packet.getAddress();
                    int port = packet.getPort();
                    System.out.println("Request from: " + address + ":" + port);
                    packet = new DatagramPacket(buf, buf.length, address, port);
                    socket.send(packet);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
                
            }
            
        }
        
    }
    
}


In the client side, JavaUdpClient.java, sends a request to the Server, and waits for the response.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/*
reference:
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
*/
public class JavaUdpClient {

    public static void main(String[] args) 
            throws UnknownHostException, SocketException, IOException {
        
        //Hardcode ip:port
        String ipLocalLoopback = "127.0.0.1";
        int serverport = 4445;
        
        
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        System.out.println("JavaUdpClient running, connect to: " 
                + ipLocalLoopback + ":" + serverport);
        
        // get a datagram socket
        DatagramSocket socket = new DatagramSocket();
        
        // send request
        byte[] buf = new byte[256];
        InetAddress address = InetAddress.getByName(ipLocalLoopback);
        DatagramPacket packet = 
                new DatagramPacket(buf, buf.length, address, serverport);
        socket.send(packet);
        
        // get response
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);
        
        String received = new String(packet.getData(), 0, packet.getLength());
        System.out.println(received);
        
        socket.close();
    }
    
}


Related:
- Android version Datagram/UDP Client
Android version Datagram/UDP Server

Thursday, May 26, 2016

The MagPi issue 46, Jun 2016, is available

  • Electronics with the Raspberry Pi
    Build your first circuits and projects in easy steps
  • Raspberry Pi Zero Updgrade
    Learn about the latest Pi Zero and get one free when you subscribe
  • Hack an RC controller with Pi Zero
    Upgrade your robot project today!
  • Measure gravity with the Raspberry Pi
    Science made simple with the Sense HAT
  • And much, much more!
Download HERE.

Tuesday, May 24, 2016

Java Network exercise: bi-direction communication, between echo server and client

My former post show examples of Client/Server using ServerSocket and Socket, with sending message from server to client, and from client to server. This example implement a echo server to show how to do bi-directional communication.



JavaServer run a ServerSocket and wait for connection and data receiving. Once connected and data received, it send back the data to the sender.

JavaServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class JavaServer {

    public static void main(String[] args) {
        System.out.println("Server start");
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        
        ServerSocket serverSocket = null;
        Socket clientSocket = null;
        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;
        
        try {
            serverSocket = new ServerSocket(8000);
            System.out.println("Server port: " 
                    + serverSocket.getLocalPort());
            
            clientSocket = serverSocket.accept();
            
            //Client connected
            InputStream inputStream = clientSocket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            
            OutputStream outputStream = clientSocket.getOutputStream();
            printWriter = new PrintWriter(outputStream, true);

            String line;
            while((line = bufferedReader.readLine()) != null){
                System.out.println(line);
                printWriter.println(line);  //echo back to sender
            };
            
        } catch (IOException ex) {
            System.err.println(ex.toString());
        }finally{
            
            if(printWriter != null){
                printWriter.close();
                System.out.println("printWriter closed");
            }
            
            if(bufferedReader != null){
                try {
                    bufferedReader.close();
                    System.out.println("bufferedReader closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
            
            if(clientSocket != null){
                try {
                    clientSocket.close();
                    System.out.println("clientSocket closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
            
            if(serverSocket != null){
                try {
                    serverSocket.close();
                    System.out.println("serverSocket closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
            
        }
        
    }
    
}


JavaClient make connection to server and send something, and wait for any data received.

JavaClient .java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class JavaClient {

    public static void main(String[] args) {
        System.out.println("Run Client");
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        
        if(args.length != 2){
            System.out.println("usage: java client <port> <something>");
            System.exit(1);
        }
        
        int port = isParseInt(args[0]);
        if(port == -1){
            System.out.println("usage: java client <port> <something>");
            System.out.println("<port>: integer");
            System.exit(1);
        }
        
        Socket socket = null;
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        
        try {
            /*
            IP is hard coded, Local Loopback = "127.0.0.1"
            Port is user entry
            */
            socket = new Socket("127.0.0.1", port);
            System.out.println("Connected...");
            
            OutputStream outputStream = socket.getOutputStream();
            printWriter = new PrintWriter(outputStream, true);
            
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = 
                    new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            
            printWriter.println(args[1]);
            
            String line;
            while((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            };
            
        } catch (IOException ex) {
            System.out.println(ex.toString());
        } finally{
            
            if(bufferedReader != null){
                try {
                    bufferedReader.close();
                    System.out.println("bufferedReader closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
            
            if(printWriter != null){
                printWriter.close();
                System.out.println("printWriter closed");
            }
            
            if(socket != null){
                try {
                    socket.close();
                    System.out.println("socket closed");
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        }
        
    }
    
    private static int isParseInt(String str){
        
        int num = -1;
        try{
             num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        
        return num;
    }
    
}


In both side, press Ctrl-C to stop the program.

download filesDownload the files .

Related:
- Android version of the Client side
Java Datagram/UDP Server and Client, run on raspberry Pi

Monday, May 23, 2016

Java Network exercise: client and server - client send something to server

Refer to my old post of "Java exercise - Implement client and server to communicate using Socket", setup bold server and client. The server reply something to client once connected.


It's modified, client connect to server and send something. In server side, wait connected and print the received text to screen.


host.java
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

class host
{
    public static void main(String srgs[])
    {   
        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedReader bufferedReader = null;
        PrintStream printStream = null;
        
        try{
            serverSocket = new ServerSocket(0);
            System.out.println("I'm waiting here: " 
                + serverSocket.getLocalPort());            
                                
            socket = serverSocket.accept();
            System.out.println("from " + 
                socket.getInetAddress() + ":" + socket.getPort());
            
            InputStreamReader inputStreamReader = 
                new InputStreamReader(socket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader);
            
            String line;
            while((line=bufferedReader.readLine()) != null){
                System.out.println(line);
            }
        }catch(IOException e){
            System.out.println(e.toString());
        }finally{
            if(bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    System.out.print(ex.toString());
                }
            }
            
            if(printStream!=null){
                printStream.close();
            }
            
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException ex) {
                    System.out.print(ex.toString());
                }
            }
        }
    }
}


client.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {

    public static void main(String args[])
    { 
        if(args.length != 2){
            System.out.println("usage: java client <port> <something>");
            System.exit(1);
        }
        
        int port = isParseInt(args[0]);
        if(port == -1){
            System.out.println("usage: java client <port> <something>");
            System.out.println("<port>: integer");
            System.exit(1);
        }
        
        try{
            //IP is hard coded, Local Loopback = "127.0.0.1"
            //port is user entry
            Socket socket = new Socket("127.0.0.1", port);

            
            //Send msg to server
            OutputStream outputStream = socket.getOutputStream();
            PrintStream printStream = new PrintStream(outputStream);
            printStream.print(args[1]);
                
            socket.close();

        }catch(UnknownHostException e){
            System.out.println(e.toString());
        }catch(IOException e){
            System.out.println(e.toString());
        }

    }
    
    private static int isParseInt(String str){
        
        int num = -1;
        try{
             num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        
        return num;
    }
    
}


It's Android version of the Client.

Next:
- bi-direction communication, between echo server and client

Sunday, May 22, 2016

Sunday, May 15, 2016

Raspbian Jessie update release 2016-05-10

Raspbian Jessie update release 2016-05-10, DOWNLOAD HERE.

Release note:
2016-05-10:
  * New version of Scratch, which no longer requires sudo
  * New version of BlueJ
  * New version of NodeRED
  * New version of pypy
  * pigpio included
  * geany editor included
  * SD Card Copier added (can be used to duplicate or back up the Pi)
  * Bluetooth plugin added to taskbar
  * Volume control on taskbar now compatible with Bluetooth devices
  * New shutdown helper application
  * Mouse double-click speed setting added to mouse and keyboard preference application
  * Option to enable / disable 1-wire interface and remote access to pigpio added to Raspberry Pi config application
  * File system automatically expanded on first boot
  * Empty Wastebasket option added to right-click menu
  * Ctrl-Alt-T can be used to open a terminal window
  * Various small bug fixes and appearance tweaks
  * Updated firmware and kernel (https://github.com/raspberrypi/firmware/commit/cc6d7bf8b4c03a2a660ff9fdf4083fc165620866)

Saturday, May 14, 2016

Filter test on Pi NoIR v1: UV-IR CUT/Hoya R72 (and align focus for infrared)

Filter test on Pi NoIR v1 on Raspberry Pi 2 - UV-IR CUT/Hoya R72(720nm Infrared):
























Focus alignment on Pi NoIR v1:
Compare with my old post of Pi NoIR v1 with IR filter:
Pi NoIR photo samples (without and with Hoya R72 filter)
Test Pi NoIR Camera Module with Infrared filter, 680nm vs 720nm
by Pi NoIR Camera Module + IR 680nm filter

It can be noted that the image become little bit blur (out focus) when using with IR filter. It's normal and reasonable because the lens cannot focus the whole range cover visible light and infrared. So I tried to align the focus to make IR image more clear.

(*Doing so have risk to damage the lens, so NOT recommended!)

The photos shown in this post taken after aligned.

The the following photos, the white marked on the lens indicate the original position and after aligned.

original position

aligned position


Related:
- Filter test on Pi NoIR Camera 2, IR 680nm, 720nm, 850nm, and UV-IR CUT