Monday, December 29, 2014

Config WiFi on new Raspbian

To run WiFi Configuration Utility on new Raspbian without icon on desktop, click Menu on Raspbian top banner, click Preferences, and WiFi Configuration.


This view show how:

python3-pygame preinstalled on new Raspbian

python3-pygame preinstalled on new Raspbian

New LXDE look of Raspbian

New LXDE look of Raspbian, 2014-12-24, updated with no icons on the desktop other than the wastebasket.



Related: CHANGES TO THE RASPBIAN USER INTERFACE

New NOOBS and RASPBIAN updated

New version of NOOBS and RASPBIAN, 2014-12-24, is available now, download HERE.

~ Release notes: http://downloads.raspberrypi.org/raspbian/release_notes.txt

Sunday, December 28, 2014

scp copy folder

Linux command scp option -r recursively copy entire directories.  Note that scp follows sym‐bolic links encountered in the tree traversal.


To copy folder from Linux host to Raspberry Pi (or any Linux machine) user home, enter the command:
$ scp -r testscp pi@192.168.1.107:

where testscp is the folder to be copied.

or
$ scp -r testscp pi@192.168.1.107:newfolder

where newfolder will be created.


Thursday, December 25, 2014

Raspberry Pi + Arduino i2c communication, write block and read byte

This example extends work on last example "Raspberry Pi send block of data to Arduino using I2C"; the Raspberry Pi read byte from Arduino Uno after block sent, and the Arduino always send back length of data received.


i2c_slave_12x6LCD.ino sketch run on Arduino Uno.
/*
 LCD part reference to:
 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

#include <LiquidCrystal.h>
#include <Wire.h>

#define LED_PIN 13
boolean ledon = HIGH;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

byte slave_address = 7;
int echonum = 0;

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print startup message to the LCD.
  lcd.print("Arduino Uno");
  
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  
  Wire.begin(slave_address);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);

}

void loop() {

}

void requestEvent(){
  Wire.write(echonum);
  toggleLED();
}


void receiveEvent(int howMany) {
  lcd.clear();
  
  int numOfBytes = Wire.available();
  //display number of bytes and cmd received, as bytes
  lcd.setCursor(0, 0);
  lcd.print("len:");
  lcd.print(numOfBytes);
  lcd.print(" ");
  
  byte b = Wire.read();  //cmd
  lcd.print("cmd:");
  lcd.print(b);
  lcd.print(" ");

  //display message received, as char
  lcd.setCursor(0, 1);
  for(int i=0; i<numOfBytes-1; i++){
    char data = Wire.read();
    lcd.print(data);
  }
  
  echonum = numOfBytes-1;
}

void toggleLED(){
  ledon = !ledon;
  if(ledon){
    digitalWrite(LED_PIN, HIGH);
  }else{
    digitalWrite(LED_PIN, LOW);
  }
}

i2c_uno.py, python program run on Raspberry Pi.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
import os

# display system info
print os.uname()

bus = smbus.SMBus(1)

# I2C address of Arduino Slave
i2c_address = 0x07
i2c_cmd = 0x01

def ConvertStringToBytes(src):
    converted = []
    for b in src:
        converted.append(ord(b))
    return converted

# send welcome message at start-up
bytesToSend = ConvertStringToBytes("Hello Uno")
bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)

# loop to send message
exit = False
while not exit:
    r = raw_input('Enter something, "q" to quit"')
    print(r)
    
    bytesToSend = ConvertStringToBytes(r)
    bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)
    
    # delay 0.1 second
    # with delay will cause error of:
    # IOError: [Error 5] Input/output error
    time.sleep(0.1)
    number = bus.read_byte(i2c_address)
    print('echo: ' + str(number))
    
    if r=='q':
        exit=True


Next:
Wire.write() multi-byte from Arduino requestEvent


WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.

Tuesday, December 23, 2014

Saturday, December 20, 2014

Raspberry Pi Hardware Reference

Raspberry Pi Hardware Reference

The Raspberry Pi is deceptively simple. Plug it in, boot it up, and use it as a personal computer, or attach a million gizmos and modules and invent something new and amazing. Either way, what it can actually do is not simple, and you should know exactly what the Raspberry Pi hardware is all about. Raspberry Pi Hardware Reference, from Mastering the Raspberry Pi, is the hardware guide you need on your desk or workbench.

Every detail is covered: from power to memory, from the CPU to working with USB. You'll find all the details about working with both wired and wireless Ethernet, SD cards, and the UART interface. The GPIO chapter is invaluable, covering power budgeting, access, and even small but important details like the correct usage of sudo when working with GPIO pins. You'll also find details about the 1-Wire driver, the I2C bus, and the SPI bus. If you need to know anything about your Raspberry Pi's hardware, you will find it here, in Raspberry Pi Hardware Reference.

What you’ll learn
  • How to work with Raspberry Pi power, including adapters and battery requirements
  • Working with header strips and LEDs
  • Working with SDRAM and memory mapping
  • Understanding the CPU
  • Interface details, including USB, UART, and GPIO

Who this book is for
Raspberry Pi hobbyists who need know all of the details about Raspberry Pi hardware and what Linux files and commands control that hardware.

Table of Contents
Ch. 1 - The Raspberry Pi
Ch. 2 – Figuring Out Power Requirements
Ch. 3 - Header Strips, LEDs, and Reset
Ch. 4 – Working with Memory
Ch. 5 – The CPU and Working with Threads
Ch. 6 – USB Power and API Support
Ch. 7 – Working with Wired and Wireless Ethernet
Ch. 8 - SD Card Storage
Ch. 9 – Serial Communication
Ch. 10 – GPIO: Your Interface to the Outside World
Ch. 11 - 1-Wire Driver
Ch. 12 - I2C Bus: The Two Wire Interface
Ch. 13 - SPI Bus: Signaling, API, and Testing
Appendix A: Glossary
Appendix B: Power Standards
Appendix C: Electronics Reference

Thursday, December 18, 2014

Play mp4 on Raspberry Pi

To play mp4 video files on Raspberry Pi, can use omxplayer.

Example: enter the command to play movie.mp4.
omxplayer movie.mp4


Monday, December 15, 2014

Raspberry Jams event around the world

Raspberry Jams are events organised by the community to share knowledge, learn new things, and meet other Pi enthusiasts. They’re a great way to find our more about the Raspberry Pi and what you can do with it, and to find like-minded people.

visit: http://www.raspberrypi.org/jam/


Sunday, December 14, 2014

Raspberry Pi send block of data to Arduino using I2C

In this example, Raspberry Pi programmed using Python with smbus library, act as I2C master, ask user enter something as string, then send to Arduino Uno in blocks of data. In Arduino side, act as I2C slave, interpret received data in number of bytes, command, and body of data, to display on 16x2 LCD display.


Prepare on Raspberry Pi for I2C communication, refer to previous post "Communication between Raspberry Pi and Arduino via I2C, using Python".

Connection between Raspberry Pi, Arduino Uno and 16x2 LCD:


i2c_slave_12x6LCD.ino sketch run on Arduino Uno.
/*
 LCD part reference to:
 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

#include <LiquidCrystal.h>
#include <Wire.h>

#define LED_PIN 13
boolean ledon = HIGH;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

byte slave_address = 7;

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print startup message to the LCD.
  lcd.print("Arduino Uno");
  
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  
  Wire.begin(slave_address);
  Wire.onReceive(receiveEvent);
}

void loop() {

}

void receiveEvent(int howMany) {
  lcd.clear();
  
  int numOfBytes = Wire.available();
  //display number of bytes and cmd received, as bytes
  lcd.setCursor(0, 0);
  lcd.print("len:");
  lcd.print(numOfBytes);
  lcd.print(" ");
  
  byte b = Wire.read();  //cmd
  lcd.print("cmd:");
  lcd.print(b);
  lcd.print(" ");

  //display message received, as char
  lcd.setCursor(0, 1);
  for(int i=0; i<numOfBytes-1; i++){
    char data = Wire.read();
    lcd.print(data);
  }
  
  toggleLED();
}

void toggleLED(){
  ledon = !ledon;
  if(ledon){
    digitalWrite(LED_PIN, HIGH);
  }else{
    digitalWrite(LED_PIN, LOW);
  }
}

i2c_uno.py, python program run on Raspberry Pi.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
import os

# display system info
print os.uname()

bus = smbus.SMBus(1)

# I2C address of Arduino Slave
i2c_address = 0x07
i2c_cmd = 0x01

def ConvertStringToBytes(src):
    converted = []
    for b in src:
        converted.append(ord(b))
    return converted

# send welcome message at start-up
bytesToSend = ConvertStringToBytes("Hello Uno")
bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)

# loop to send message
exit = False
while not exit:
    r = raw_input('Enter something, "q" to quit"')
    print(r)
    
    bytesToSend = ConvertStringToBytes(r)
    bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)
    
    if r=='q':
        exit=True


next:
- Raspberry Pi + Arduino i2c communication, write block and read byte


WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.

Python exercise: read line of input, 'q' to quit

Python example to read line of input, 'q' to quit, using raw_input().



exit = False
while not exit:
    r = raw_input('Enter something, "q" to quit"')
    print(r)
    if r=='q':
        exit=True

Saturday, December 13, 2014

Communication between Raspberry Pi and Arduino via I2C, using Python.

This exercise implement communiation between Raspberry Pi and Arduino using I2C. Here Raspberry Pi, programmed with Python, act as I2C host and Arduino Uno act as slave.

Download the sketch (I2CSlave.ino) to Arduino Uno. It receive I2C data, turn ON LED if 0x00 received, turn OFF LED if 0x01 received.
#include <Wire.h>

#define LED_PIN 13

byte slave_address = 7;
byte CMD_ON = 0x00;
byte CMD_OFF = 0x01;

void setup() {
  // Start I2C Bus as Slave
  Wire.begin(slave_address);
  Wire.onReceive(receiveEvent);
  
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);  

}

void loop() {

}

void receiveEvent(int howMany) {
  byte cmd = Wire.read();
  if (cmd == CMD_ON){
    digitalWrite(LED_PIN, HIGH);
  }else if(cmd == CMD_OFF){
    digitalWrite(LED_PIN, LOW);
  }
}

Prepare on Raspberry Pi, refer to last post "Enable I2C and install tools on Raspberry Pi".

Connection between Raspberry Pi and Arduino.


Then you can varify the I2C connection using i2cdetect command. Refer to below video, the I2C device with address 07 match with slave_address = 7 defined in Arduino sketch.


On Raspberry Pi, run the command to install smbus for Python, in order to use I2C bus.
sudo apt-get install python-smbus


Now create a Python program (i2c_uno.py), act as I2C master to write series of data to Arduino Uno, to turn ON/OFF the LED on Arduino Uno. Where address = 0x07 have to match with the slave_address in Arduino side.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
bus = smbus.SMBus(1)

# I2C address of Arduino Slave
address = 0x07

LEDst = [0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01]
for s in LEDst:
    bus.write_byte(address, s)
    time.sleep(1)

Finally, run with command:
$ sudo python i2c_uno.py



Next:
Raspberry Pi send block of data to Arduino using I2C
Write block and read byte
Wire.write() multi-byte from Arduino requestEvent


WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.

Enable I2C and install tools on Raspberry Pi

To enable I2C and install tools on Raspberry Pi, such that you can develop program to communicate with I2C devices.

  • $ sudo apt-get install i2c-tools
  • $ sudo apt-get install libi2c-dev
  • $ sudo nano /etc/modprobe.d/raspi-blacklist.conf
    comment the line of
    #blacklist i2c-bcm2708
  • $ sudo nano /etc/modules
    add the lines:
    i2c-bcm2708
    i2c-dev
  • reboot
After reboot, run i2c-tools to test
run the command with -1 option for rev 2 board, or -0 for rev 1 board.
$ sudo i2cdetect -y 1
$ sudo i2cdetect -y 0

updated@2016-06-21:
Enable I2C on Raspberry Pi running Raspbian Jessie

Related:
Communication between Raspberry Pi and Arduino via I2C, using Python.
Raspberry Pi send block of data to Arduino using I2C.

Friday, December 12, 2014

The MagPi, December 2014,is available

The MagPi issue 29, December 2014, is available. View or download HERE now.

The Internet of Things: Do-It-Yourself at Home Projects for Arduino, Raspberry Pi and BeagleBone Black

Build and program projects that tap into the Internet of Things (IoT) using Arduino, Raspberry Pi, and BeagleBone Black!

This innovative guide gets you started right away working with the most popular processing platforms, wireless communication technologies, the Cloud, and a variety of sensors. You’ll learn how to take advantage of the utility and versatility of the IoT and connect devices and systems to the Internet using sensors. Each project features a list of the tools and components, how-to explanations with photos and illustrations, and complete programming code. All projects can be modified and expanded, so you can build on your skills.

The Internet of Things: Do-It-Yourself at Home Projects for Arduino, Raspberry Pi and BeagleBone Black
  • Covers the basics of Java, C#, Python, JavaScript, and other programming languages used in the projects
  • Shows you how to use IBM’s Net Beans IDE and the Eclipse IDE
  • Explains how to set up small-scale networks to connect the projects to the Internet
  • Includes essential tips for setting up and using a MySQL database.
The fun, DIY projects in the book include:
  • Raspberry Pi home temperature measurements
  • Raspberry Pi surveillance webcams
  • Raspberry Pi home weather station
  • Arduino garage door controller
  • Arduino irrigation controller
  • Arduino outdoor lighting controller
  • Beaglebone message panel
  • Beaglebone remote control SDR
  • Machine-to-machine demonstration project

Banana PI M2 (BPI-M2) is available to pre-order now

BPI-M2 Mass production will come out after 50 days, you can pre-order it.
~ link: http://www.aliexpress.com/store/product/Single-Board-Computer-Quad-Core-Banana-PI-wifi-on-Board-BPI-M2/302756_32251903757.html

Banana PI M2:

  • open source hardware platform
  • an quad core version of Banana Pi, same size
  • support WIFI onboard.
  • run Android (4.4), Debian, Ubuntu, Raspberry Pi imange and others imange.
  • 1Ghz ARM7 quad-core processor, 1GB DDR3 SDRAM,
  • with Gigabit ethernet port
  • can easily run with the game it support 1080P high definition video output
  • the GPIO compatible with Raspberry Pi B+ and can run the ROM Image.




Hope it can available at taobao.com ASAP.



Friday, December 5, 2014

Banana Pi-M2 (A31S ARM Cortex-A7 quad-core, Coming soon)

Banana PI M2 is the open source hardware platform,Banana PI M2 is an quad core version of Banana Pi ,Banana PI M2 is the quad core more better than the Banana Pi M1,it support WIFI onboard.

Banana Pi M2 series run Android,Debian linux,Ubuntu linux, Raspberry Pi imange and others imange.


Details: http://bananapi.com/index.php/component/content/article?layout=edit&id=73

Monday, December 1, 2014

Weaved IoT Kit for Raspberry Pi


Weaved, Inc. has launched the public beta version of the first kit that easily allows hobbyists and others to easily add Internet of Things (IoT) capabilities to the Raspberry Pi platform. There have been over 3.8 million Raspberry Pi boards sold and now all of them and any new boards can now be transformed to IoT devices.

source: http://www.weaved.com/archives/2895

Saturday, November 29, 2014

Friday, November 28, 2014

OwnCloud installation on Banana Pi- Personal Cloud and NAS


Pumpkin Pi is an mere idea, a seed, of great potential. It aims to bring to your fingertips a personal cloud experience and a fun Do-It-Yourself project. Powered by an embedded board running on Linux, Pumpkin Pi is all the imagination and work of developers and programmer worldwide. To be loaded with an open source cloud software, Pumpkin Pi stores all of your information on a hard drive in your house.

https://pumpkinpi.cu.cc/generic.html

Linux command "$ sudo !!", to run last command with sudo

To run last command with sudo right, enter:
$ sudo !!

Thursday, November 27, 2014

Code Java on the Raspberry Pi, BlueJ on the Raspberry Pi

BlueJ, start from version 3.14, fully supports the Raspberry Pi. BlueJ is a Java development environment that allows development as well as program execution on the Pi.

BlueJ on the Raspberry Pi provides full access to hardware attached to the Raspberry Pi via the open source Pi4J library, from the the familiar Java SE language, including the new Java 8.

link:
http://bluej.org/raspberrypi/index.html



Current issue of Java Magazine, november/december 2014, have a charter of "Code Java on Raspberry Pi" introduce how BlueJ brings Java SE 8 development directly to the Raspberry Pi.



Friday, November 21, 2014

Raspberry Pi Challenge Day @ UKFast

UKFast hosted a challenge day for The Dean Trust Ashton-On-Mersey School to inspire the next generation of software engineers. Guided by our industry experts; the students learned to program the Raspberry Pi to control bedroom lamps with their smartphones and modified Minecraft.

Thursday, November 20, 2014

Banana Pi Camera & LCD

An overview of the LeMaker Banana Pi camera and five inch LCD module, including connection and driver information.

Wednesday, November 12, 2014

How much current does the Raspberry Pi Model A+ need


Raspberry Pi A+ power measurements. How much current does the A+ need to do various things? Comparison with B+ and older model A. Blog article here http://raspi.tv/?p=7238

Tuesday, November 11, 2014

Raspberry Pi Model A+ announced

Raspberry Pi Model A+ announced, at lower price of $20. Source: http://www.raspberrypi.org/raspberry-pi-model-a-plus-on-sale/





Foundations of Python Network Programming

Foundations of Python Network Programming , Third Edition, covers all of the classic topics found in the second edition of this book, including network protocols, network data and errors, email, server architecture, and HTTP and web applications, plus updates for Python 3.

Some of the new topics in this edition include:
• Extensive coverage of the updated SSL support in Python 3
• How to write your own asynchronous I/O loop.
• An overview of the "asyncio" framework that comes with Python 3.4.
• How the Flask web framework connects URLs to your Python code.
• How cross-site scripting and cross-site request forgery can be used to attack your web site, and how to protect against them.
• How a full-stack web framework like Django can automate the round trip from your database to the screen and back.

If you're a Python programmer who needs a deep understanding of how to use Python for network-related tasks and applications, this is the book for you. From web application developers, to systems integrators, to system administrators—this book has everything that you need to know.

Practical Node.js: Building Real-World Scalable Web Apps

Practical Node.js: Building Real-World Scalable Web Apps is your step-by-step guide to learning how to build a wide range of scalable real-world web applications using a professional development toolkit. Node.js is an innovative and highly efficient platform for creating web services. But Node.js doesn't live in a vacuum! In a modern web development, many different components need to be put together — routing, database driver, ORM, session management, OAuth, HTML template engine, CSS compiler and many more.

If you already know the basics of Node.js, now is the time to discover how to bring it to production level by leveraging its vast ecosystem of packages. As a web developer, you'll work with a varied collection of standards and frameworks - Practical Node.js shows you how all those pieces fit together.

Practical Node.js takes you from installing all the necessary modules to writing full-stack web applications by harnessing the power of the Express.js and Hapi frameworks, the MongoDB database with Mongoskin and Mongoose, Jade and Handlebars template engines, Stylus and LESS CSS languages, OAuth and Everyauth libraries, and the Socket.IO and Derby libraries, and everything in between. The book also covers how to deploy to Heroku and AWS, daemonize apps, and write REST APIs. You'll build full-stack real-world Node.js apps from scratch, and also discover how to write your own Node.js modules and publish them on NPM. You already know what Node.js is; now learn what you can do with it and how far you can take it!

What you’ll learn
  • Manipulate data from the mongo console
  • Use the Mongoskin and Mongoose MongoDB libraries
  • Build REST API servers with Express and Hapi
  • Deploy apps to Heroku and AWS
  • Test services with Mocha, Expect and TravisCI
  • Utilize sessions for authentication
  • Implement a third-party OAuth strategy with Everyauth
  • Apply Redis, domains, WebSockets, and clusters
  • Write your own Node.js module, and publish it on NPM
Who this book is for
Practical Node.js is for web developers who have some familiarity with the basics of Node.js and want to learn how to use it to build apps in a professional environment.

Table of Contents
  • Setting Up Node.js and Other Essentials
  • Using Express.js to Create Rapid Node.js Web Apps
  • TDD and BDD for Node.js with Mocha
  • Template Engines: Jade and Handlebars
  • Persistence with MongoDB and Mongoskin
  • Using Sessions and OAuth to Authorize and Authenticate Users in Node.js Apps
  • Boosting Your Node.js Data with the Mongoose ORM Library
  • Building a Node.js REST API Server App
  • Realtime Apps with WebSockets, Socket.IO, and Derby JS
  • Getting Node.js Apps Production Ready
  • Deploying Node.js Apps
  • Publishing a Node.js Module and Contributing Back to the Project

Tuesday, November 4, 2014

Develop C# program on Raspberry Pi, with mono

Sponsored by Xamarin, Mono is an open source implementation of Microsoft's .NET Framework based on the ECMA standards for C# and the Common Language Runtime. A growing family of solutions and an active and enthusiastic contributing community is helping position Mono to become the leading choice for development of cross platform applications.

To install mono on Raspberry Pi, run the command:
$ sudo apt-get install mono-complete


Currently, the installed version is 3.2.8.


Create a simple console program of HelloWorld using C# language, HelloWorld.cs.
using System;

public class HelloWorld
{
    public static void Main()
    {
        Console.WriteLine("Hello Raspberry Pi...using c#");
    }
}


Compile it with the command:
$ gmcs HelloWorld.cs

And run it:
$ mono HelloWorld.exe



Updated post: Install Mono/MonoDevelop on Raspberry Pi/Raspbian

Wednesday, October 22, 2014

Linux command tree, list contents of directories in a tree-like format

The Linux command tree list contents of directories in a tree-like format.

To install trr on Raspberry Pi, enter the command:
$ sudo apt-get install tree



Linux command free, display amount of free and used memory in the Raspberry Pi system

The Linux command free - Display amount of free and used memory in the system


Thursday, October 16, 2014

Banana Pro Released

New version single board computer, Banana Pro, released.


Banana Pro is an update version of Banana Pi, designed by LeMaker Team and it has more enhanced features. Banana Pro has an excellent compatibility with multiply software supports. Basically all mainstream Linux-based operating system can run on Banana Pro, with the version of Lubuntu, Android, Debian, Bananian, Berryboot, OpenSuse, Scratch, Fedora, Gentoo, Open MediaVault, OpenWRT.Banana Pro also supports BSD system.



Visit: http://www.lemaker.org/

Saturday, October 11, 2014

Check your Raspberry Pi board revision

To find the board revision of your Raspberry Pi, enter the following command:
cat /proc/cpuinfo



The number in Revision identify the board revision. check the revision list here: http://elinux.org/RPi_HardwareHistory#Board_Revision_History


Friday, October 10, 2014

Scan network using nmap command

On host pc running Linux, we can scan network using nmap command to determine the IP of connected Raspberry Pi.

$ sudo nmap -sP 192.168.1.1-254



Tuesday, October 7, 2014

Mastering the Raspberry Pi

Mastering the Raspberry Pi

You probably already know that the Raspberry Pi is an excellent teaching tool. If you want to teach Linux basics or Python programming or basic electronics, it's a great place to start. But what if you are an electronics engineer or a Linux systems administrator or a very experienced maker? You want to know all of the details and inner working of the Raspberry Pi -- how to (figuratively or maybe even literally) make it get up and dance without wading through basics and introductory material.

If you want to get right into the pro-level guts of the Raspberry Pi, complete with schematics, detailed hardware explanations, messing around with runlevels, reporting voltages and temperatures, and recompiling the kernel, then Mastering the Raspberry Pi is just the book you need. Along with all of the thorough explanations of hardware and operating system, you'll also get a variety of project examples and explanations that you can tune for your own project ideas.

You'll find yourself turning to Mastering the Raspberry Pi over and over again for both inspiration and reference. Whether you're an electronics professional, an entrepreneurial maker, or just looking for more detailed information on the Raspberry Pi, this is exactly the book for you.

What you’ll learn
  • How to set up the Raspberry Pi for bare metal interfacing
  • Detailed and clear explanations of the Pi's hardware capabilities, including GPIO
  • Working with Linux on the Pi, including boot files, the Pi's own vcgencmd command, and cross-compiling software, including the kernel
  • How to make a GPIO extender
  • How to work with a stepper motor and the Pi, including building an H-bridge driver
  • How to make a remote control panel with the Pi
  • How to use Pulse Width Modulation with the Pi
Who this book is for

Experienced electronics engineers, Linux admins and users, and makers wanting to go far beyond the basics with Raspberry Pi.

Table of Contents

Part I: Introduction
Ch. 1 - Why This Book?
Ch. 2 - The Raspberry Pi
Ch. 3 – Preparation: Hardware and Network

Part II: Hardware
Ch. 4 – Figuring Out Power Requirements
Ch. 5 - Header Strips, LEDs, and Reset
Ch. 6 – Working with Memory
Ch. 7 – The CPU and Working with Threads
Ch. 8 – USB Power and API Support
Ch. 9 – Working with Wired and Wireless Ethernet
Ch. 10 - SD Card Storage
Ch. 11 – Serial Communication
Ch. 12 – GPIO: Your Interface to the Outside World
Ch. 13 - 1-Wire Driver
Ch. 14 - I2C Bus: The Two Wire Interface
Ch. 15 - SPI Bus: Signaling, API, and Testing

Part III: Software
Ch. 16 – Booting ARM Linux
Ch. 17 – Initialization: Working with Runlevels
Ch. 18 – vcgencmd: Reporting Voltages and Temperatures
Ch. 19 - Linux Console
Ch. 20 – Building a Cross-Compiler
Ch. 21 – Cross-Compiling the Kernel

Part IV: Projects
Ch. 22 – Humidity and Temperature Sensor
Ch. 23 - GPIO Extender
Ch. 24 - Nunchuk Mouse
Ch. 25 - Real-Time Clock
Ch. 26 - IR Receiver
Ch. 27 - Stepper Motor
Ch. 28 - The H-Bridge Driver
Ch. 29 - Remote Control Panel
Ch. 30 - Pulse Width Modulation: Driving an Analog Meter

Appendices:
A. Glossary
B. Power Standards
C. Electronics Reference
D. Raspbian apt Commands
E. ARM Compile Options
F. Mac OS X Tips
G. Bibliography

Friday, September 19, 2014

Display CPU Frequency monitor on Raspberry Pi Task Bar

To enable CPUFreq frontend applet on your Raspberry Pi taskbar to monitor CPU frequency:




  • Right click Task Bar
  • Select Add/Remove Panel Items
  • Select CPU Usage Monitor, click Add.
  • CPUFreq frontend, click Add.

CPUFreq frontend applet will be added on your Task Bar. To monitor your CPU frequency, move mouse hover over the CPUFreq frontend applet.


HummingBoard Vs Raspberry Pi


Learn more about HummingBoard: http://www.solid-run.com/products/hummingboard/

High Performance Python: Practical Performant Programming for Humans



High Performance Python: Practical Performant Programming for Humans

Your Python code may run correctly, but you need it to run faster. By exploring the fundamental theory behind design choices, this practical guide helps you gain a deeper understanding of Python’s implementation. You’ll learn how to locate performance bottlenecks and significantly speed up your code in high-data-volume programs.

How can you take advantage of multi-core architectures or clusters? Or build a system that can scale up and down without losing reliability? Experienced Python programmers will learn concrete solutions to these and other issues, along with war stories from companies that use high performance Python for social media analytics, productionized machine learning, and other situations.
  • Get a better grasp of numpy, Cython, and profilers
  • Learn how Python abstracts the underlying computer architecture
  • Use profiling to find bottlenecks in CPU time and memory usage
  • Write efficient programs by choosing appropriate data structures
  • Speed up matrix and vector computations
  • Use tools to compile Python down to machine code
  • Manage multiple I/O and computational operations concurrently
  • Convert multiprocessing code to run on a local or remote cluster
  • Solve large problems while using less RAM

Tuesday, September 16, 2014

Monday, September 15, 2014

Web control to display on Pi connected LCD Module, with Python and bottle

This post show how to build a simple web application on Raspberry Pi using Python + bottle, receive POST from client to display message on connected 2x16 LCD Module.


To install python-bottle on Raspberry Pi, refer to the post "Python + bottle@Raspberry Pi: Web based GPIO control".

The previouse post "2x16 LCD Display on Raspberry Pi" show how to connect and text 2x16 LCD Module on Raspberry Pi. To control the LCD Module with Python, the program Adafruit_CharLCD.py in the post is needed.

weblcd.py
from bottle import route, run
from bottle import post, request

from Adafruit_CharLCD import Adafruit_CharLCD
lcd = Adafruit_CharLCD()

host = '192.168.1.105'

@route('/')
def index():
    return '''
        <form action="/" method="post">
            Hello: <input name="msg" type="text" />
            <input value="post" type="submit" />
        </form>
    '''

@route('/', method='POST')
def do_msg():
    msg = request.forms.get('msg')
    lcd.clear()
    lcd.message(msg)
    return index()

lcd.clear()
lcd.message("Hello:\n Raspberry Pi")

run(host=host, port=80)

Download HERE.

2x16 LCD Display on Raspberry Pi

This post show how to connect 2x16 LCD Display Module (come from another Arduino starter kit) to Raspberry Pi, and test it with Python.


How to connect 2x16 LCD Display Module to Raspberry Pi:


Visit GitHib of adafruit/Adafruit-Raspberry-Pi-Python-Code/Adafruit_CharLCD. There is a sample Python code to drive 2x16 CharLCD on Raspberry Pi, Adafruit_CharLCD.py.

For Raspberry Pi Model B, rev 2, change pin 21 to 27:
Search the code:
    def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, 21, 22], GPIO=None):

to:
    def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, 27, 22], GPIO=None):

Run it with sudo, to display welcome message of " Adafruit 16x2\n Standard LCD".

$ sudo python Adafruit_CharLCD.py

Another sample code Adafruit_CharLCD_IPclock_example.py, display datetime and the IP of your Raspberry Pi.

$ sudo python Adafruit_CharLCD_IPclock_example.py

Both sampls can be download Here.

Related:
- Web control to display on Pi connected LCD Module, with Python and bottle

Sunday, September 14, 2014

Control Raspberry Pi GPIO using C language

This example show how to control GPIO (pin 18 in this example) using C language.



testPin.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

#define BCM2708_PERI_BASE   0x20000000
#define GPIO_BASE           (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */

#define LED_18              18

#define BLOCK_SIZE (4*1024)

int mem_fd;
void *gpio_map;
volatile unsigned *gpio;

// GPIO setup macros. Always use INP_GPIO(x) before using OUT_GPIO(x) or SET_GPIO_ALT(x,y)
#define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3))
#define OUT_GPIO(g) *(gpio+((g)/10)) |=  (1<<(((g)%10)*3))
#define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3))

#define GPIO_SET *(gpio+7)  // sets   bits which are 1 ignores bits which are 0
#define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0
 
int init_io()
{
    /* open /dev/mem */
    if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
        printf("can't open /dev/mem \n");
        return(-1);
    }else{
        printf("/dev/mem opened\n");
        
        /* mmap GPIO */
        gpio_map = mmap(
            NULL,             //Any adddress in our space will do
            BLOCK_SIZE,       //Map length
            PROT_READ|PROT_WRITE,// Enable reading & writting to mapped memory
            MAP_SHARED,       //Shared with other processes
            mem_fd,           //File to map
            GPIO_BASE         //Offset to GPIO peripheral   
        );
        
        close(mem_fd);
        printf("/dev/mem closed\n");
        
        if (gpio_map == MAP_FAILED) {
            printf("mmap error %d\n", (int)gpio_map);//errno also set!
            return(-1);
        }else{
            printf("mmap Success.\n");
        }
        
    }
    
    // Always use volatile pointer!
   gpio = (volatile unsigned *)gpio_map;

   return 0;
}


int main(){
    
    if(init_io() == -1) 
    {
        printf("Failed to map the physical GPIO registers into the virtual memory space.\n");
        return -1;
    }
    
    // must use INP_GPIO before we can use OUT_GPIO
    INP_GPIO(LED_18); 
    OUT_GPIO(LED_18);
    
    int repeat;
    for (repeat=1; repeat<5; repeat++)
    {
        GPIO_CLR = 1 << LED_18;
        printf("LED OFF\n");
        sleep(2);

        GPIO_SET = 1 << LED_18;
        printf("LED ON\n");
        sleep(1);
    }
    
    printf("- finished -\n");
    return 0;
}

Download HERE.

Compile with:
$ gcc testPin.c

Run with sudo:
$ sudo ./a.out


Python + bottle@Raspberry Pi: Web based GPIO control

This example show how to program in Python with bottle on Raspberry Pi, to implement web base GPIO control.

bottle is a Python web server library. To install bottle on Raspberry Pi, enter the command:
sudo apt-get install python-bottle


Create webled.py
from bottle import route, run
import RPi.GPIO as GPIO

host = '192.168.1.105'

pinButton = 17
pinLed = 18
GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(pinButton, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(pinLed, GPIO.OUT)

LedState = False

def read_button():
    if GPIO.input(pinButton):
        return 'Released'
    else:
        return 'Pressed'

def update_led():
    GPIO.output(pinLed, LedState)
    
def toggleLed():
    global LedState
    LedState = not LedState
    
@route('/')
@route('/<arg>')
def index(arg=""):
    if arg == "toggle":
        toggleLed()
        
    update_led()
    
    response = "<html>\n"
    response += "<body>\n"
    response += "<script>\n"
    response += "function changed()\n"
    response += "{window.location.href='/toggle'}\n"
    response += "</script>\n"
    
    response += "Button: " + read_button() +"\n"
    response += "<br/><br/>\n"
    response += "<input type='button' onClick='changed()' value=' LED '/>\n"
    response += "</body></html>\n"
    return response
    
run(host=host, port=80)

Run it:
$ sudo python webled.py



Related:
- Web control to display on Pi connected LCD Module, with Python and bottle

Python RPi.GPIO: Read Button using GPIO.add_event_detect() with callback

The example show how to detect events of GPIO, to detect button pressed/released. It have the same operation in the post "Python RPi.GPIO: Button and LED".



import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(18, GPIO.OUT)

def ButtonCallback(channel):
    if (GPIO.input(17)):
        GPIO.output(18, False)
    else:
        GPIO.output(18, True)
    
GPIO.add_event_detect(17, GPIO.BOTH, callback=ButtonCallback);

while(True):
    #do nothing
    time.sleep(1)

Friday, September 12, 2014

Learn about physical computing with Raspberry Pi

New Raspbian (and NOOBS) available

New release (2014-09-09) of Raspbian, and also New Out Of the Box Software (NOOBS), available.

  • New firmware with various fixes and improvements
  • Minecraft Pi pre-installed
  • Sonic Pi upgraded to 2.0
  • Include Epiphany browser work from Collabora
  • Switch to Java 8 from Java 7
  • Updated Mathematica
  • Misc minor configuration changes

Download: http://www.raspberrypi.org/downloads/


Python RPi.GPIO: Button and LED

This example read button input from pin 17 (set as input with pull-up resister) and set output to pin 18 to turn ON/OFF LED accordingly.



The code GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) set pin 17 as input with pull-up resistor. If you omit the option pull_up_down=GPIO.PUD_UP, the pin will have no pull-up resistor, and become un-stable.

led.py
import RPi.GPIO as GPIO


GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(18, GPIO.OUT)

while(True):
 if (GPIO.input(17)):
  GPIO.output(18, False)
 else:
  GPIO.output(18, True)


Next:
Read Button using GPIO.add_event_detect() with callback

Wednesday, September 10, 2014

Raspberry Pi Python exercise: Change GPIO LED brightness with GPIO.PWM

Example of Python on Raspberry Pi, to change GPIO LED brightness with GPIO.PWM.



led.py
import RPi.GPIO as GPIO
import time

led_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)

#frequency 500 Hz
led_pwm = GPIO.PWM(led_pin, 500)
#duty cycle = 100
led_pwm.start(100)

while(True):
    led_pwm.ChangeDutyCycle(100)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(80)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(60)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(40)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(20)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(0)
    time.sleep(1)


Connection, check lst post of "Toggle LED on GPIO".

Raspberry Pi Python exercise: Toggle LED on GPIO

Python example run on Raspberry Pi, to toggle GPIO pin for LED.

connection:

Example code, led.py:
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

while(True):
    GPIO.output(18, True)
    time.sleep(1.5)
    GPIO.output(18, False)
    time.sleep(0.5)


Run it with sudo:
$ sudo python led.py

Next:
Change GPIO LED brightness with GPIO.PWM

Saturday, September 6, 2014

Yahoo Weather on Raspberry Pi, with text-to-speech

With java-google-translate-text-to-speech, we can add text-to-speech (tts) to previous Yahoo Weather exercise.


Java code on Raspberry Pi.
package java_jssc_uno;

import com.gtranslate.Audio;
import com.gtranslate.Language;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javazoom.jl.decoder.JavaLayerException;
import jssc.SerialPort;
import jssc.SerialPortException;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class Java_jSSC_Uno {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());

            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Java_jSSC_Uno".getBytes()));
            //System.out.println("Port closed: " + serialPort.closePort());
        } catch (SerialPortException ex) {
            System.out.println(ex);
        }

        YahooWeather yahooWeather = new YahooWeather();
        yahooWeather.queryWeather();
        
        MyWeather myYahooWeatherResult = yahooWeather.getWeatherResult();
        System.out.println(myYahooWeatherResult.toString());
        
        Reporter reporter = new Reporter(serialPort, myYahooWeatherResult);
        reporter.report();
        
        try {
            System.out.println("Port closed: " + serialPort.closePort());
        } catch (SerialPortException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

class Reporter{
    SerialPort serialPort;
    MyWeather myWeather;
    
    Reporter(SerialPort serialPort, MyWeather myWeather){
        this.serialPort = serialPort;
        this.myWeather = myWeather;
    }
    
    public void report(){
        reportWord(myWeather.description);
        //reportWord(myWeather.city);
        //reportWord(myWeather.region);
        //reportWord(myWeather.country);
        reportWord(myWeather.conditiondate);
        
        reportWord("humidity: " + myWeather.humidity);
        reportWord("visibility: " + myWeather.visibility);
        reportWord("pressure: " + myWeather.pressure);
        reportWord("rising: " + myWeather.rising);
        
        reportWord("Wind chill: " + myWeather.windChill);
        reportWord("direction: " + myWeather.windDirection);
        reportWord("speed: " + myWeather.windSpeed);
        reportWord("Sunrise: " + myWeather.sunrise);
        reportWord("Sunset: " + myWeather.sunset);
        reportWord(myWeather.conditiontext);

    }
    
    private void reportWord(String word){
        try {
            serialPort.writeBytes(word.getBytes());
        } catch (SerialPortException ex) {
            Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
        }
        speak(word);
        delay2s();
    }
    
    private void speak(String word){
        Audio audio = Audio.getInstance();
        InputStream sound;
        try {
            sound = audio.getAudio(word, Language.ENGLISH);
            audio.play(sound);
        } catch (IOException | JavaLayerException ex) {
            Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

    private void delay2s(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}

class MyWeather{
    String description;
    String city;
    String region;
    String country;
    
    String windChill;
    String windDirection;
    String windSpeed;
    
    String humidity;
    String visibility;
    String pressure;
    String rising;
    
    String sunrise;
    String sunset;
    
    String conditiontext;
    String conditiondate;
    
    @Override
    public String toString(){
        
        return "\n- " + description + " -\n\n" 
            + "city: " + city + "\n"
            + "region: " + region + "\n"
            + "country: " + country + "\n\n"

            + "Wind\n"
            + "chill: " + windChill + "\n"
            + "direction: " + windDirection + "\n"
            + "speed: " + windSpeed + "\n\n"
            
            + "humidity: " + humidity + "\n"
            + "visibility: " + visibility + "\n"
            + "pressure: " + pressure + "\n"
            + "rising: " + rising + "\n\n"
            
            + "Sunrise: " + sunrise + "\n"
            + "Sunset: " + sunset + "\n\n"
            
            + "Condition: " + conditiontext + "\n"
            + conditiondate +"\n";
    }
}

class YahooWeather {
    
    MyWeather weatherResult;
    
    public void queryWeather(){
        String weatherString = query();
        Document weatherDoc = convertStringToDocument(weatherString);
        
        weatherResult = parseWeather(weatherDoc);
    }

    private String query() {
        String qResult = "";
        //Yahoo Weather Query URL for New York
        String queryString = "http://weather.yahooapis.com/forecastrss?w=2459115";

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(queryString);

        try {
            HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Reader in = new InputStreamReader(inputStream);
                BufferedReader bufferedreader = new BufferedReader(in);
                StringBuilder stringBuilder = new StringBuilder();

                String stringReadLine;

                while ((stringReadLine = bufferedreader.readLine()) != null) {
                    stringBuilder.append(stringReadLine).append("\n");
                }

                qResult = stringBuilder.toString();

            }

        } catch (IOException ex) {
            Logger.getLogger(YahooWeather.class.getName()).log(Level.SEVERE, null, ex);
        }

        return qResult;
    }

    private Document convertStringToDocument(String src) {
        Document doc = null;

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser;

        try {
            parser = dbFactory.newDocumentBuilder();
            doc = parser.parse(new ByteArrayInputStream(src.getBytes()));
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(YahooWeather.class.getName()).log(Level.SEVERE, null, ex);
        }

        return doc;
    }

    private MyWeather parseWeather(Document srcDoc){
        
        MyWeather myWeather = new MyWeather();

        //<description>Yahoo! Weather for New York, NY</description>
        myWeather.description = srcDoc.getElementsByTagName("description")
            .item(0)
            .getTextContent();

        //<yweather:location city="New York" region="NY" country="United States"/>
        Node locationNode = srcDoc.getElementsByTagName("yweather:location").item(0);
        myWeather.city = locationNode.getAttributes()
            .getNamedItem("city")
            .getNodeValue();
        
        myWeather.region = locationNode.getAttributes()
            .getNamedItem("region")
            .getNodeValue();
        
        myWeather.country = locationNode.getAttributes()
            .getNamedItem("country")
            .getNodeValue();

        //<yweather:wind chill="60" direction="0" speed="0"/>
        Node windNode = srcDoc.getElementsByTagName("yweather:wind").item(0);
        myWeather.windChill = windNode.getAttributes()
            .getNamedItem("chill")
            .getNodeValue();
        
        myWeather.windDirection = windNode.getAttributes()
            .getNamedItem("direction")
            .getNodeValue();
        
        myWeather.windSpeed = windNode.getAttributes()
            .getNamedItem("speed")
            .getNodeValue();
        
        //<yweather:atmosphere humidity="82" visibility="6" pressure="30.2" rising="0"/>
        Node atmosphereNode = srcDoc.getElementsByTagName("yweather:atmosphere").item(0);
        myWeather.humidity = atmosphereNode.getAttributes()
            .getNamedItem("humidity")
            .getNodeValue();
        
        myWeather.visibility = atmosphereNode.getAttributes()
            .getNamedItem("visibility")
            .getNodeValue();
        
        myWeather.pressure = atmosphereNode.getAttributes()
            .getNamedItem("pressure")
            .getNodeValue();
        
        myWeather.rising = atmosphereNode.getAttributes()
            .getNamedItem("rising")
            .getNodeValue();

        //<yweather:astronomy sunrise="6:52 am" sunset="7:10 pm"/>
        Node astronomyNode = srcDoc.getElementsByTagName("yweather:astronomy").item(0);
        myWeather.sunrise = astronomyNode.getAttributes()
            .getNamedItem("sunrise")
            .getNodeValue();
        
        myWeather.sunset = astronomyNode.getAttributes()
            .getNamedItem("sunset")
            .getNodeValue();

        //<yweather:condition text="Fair" code="33" temp="60" date="Fri, 23 Mar 2012 8:49 pm EDT"/>
        Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
        myWeather.conditiontext = conditionNode.getAttributes()
            .getNamedItem("text")
            .getNodeValue();
        
        myWeather.conditiondate = conditionNode.getAttributes()
            .getNamedItem("date")
            .getNodeValue();

        return myWeather;
    }
    
    public MyWeather getWeatherResult(){
        return weatherResult;
    }
    
    @Override
    public String toString(){
        return weatherResult.toString();
    }
}

Download HERE.

Keep using the sketch in the post "Read from Arduino Serial port, and write to 2x16 LCD" on Arduino Uno.

java-google-translate-text-to-speech, unofficial API for Google Translate in Java.

java-google-translate-text-to-speech is API unofficial with the main features of Google Translate in Java. I will add text-to-speech (tts) function in my next Yahoo Weather exercise.

This video show how to download jars, and add library to Netbeans Java project.

Install espeak, Text to Speech (Speech Synthesis), on Raspberry Pi

eSpeak is a compact open source software speech synthesizer for English and other languages, for Linux and Windows.   http://espeak.sourceforge.net.

To install espeak on Raspberry Pi, enter the command:
sudo apt-get install espeak

To test:
$ espeak hello




Play mp3 on Raspberry Pi

To play mp3 on Raspberry Pi, using omxplayer command:

example:
$ omxplayer HelloWorld.mp3


scp, easiest way to copy file from Linux PC to Raspberry Pi

Example:

$ scp HelloWorld.mp3 pi@192.168.1.105:~/


Friday, September 5, 2014

Java on Raspberry Pi example: read Yahoo Weather, send to Arduino Uno, display on LCD Module

It's a Java example running on Raspberry Pi, read Yahoo Weather, then send to Arduino and display on 2x16 LCD Module.


Here, jSSC (Java Simple Serial Connector) is needed, refer to the post "Java serial communication with Arduino Uno with jSSC, on Raspberry Pi" to know how to add it to Netbeans project.

For sketch on Arduino Uno, read from serial port and write to 2x16 LCD Module, and connection of LCD Module, refer to the post in my another Arduino blog.

Apache HttpComponents is also needed to read Yahoo Weather with HttpClient, read previous post "Download and add Apache HttpComponents jar to Netbeans Project".

Java code:
package java_jssc_uno;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import jssc.SerialPort;
import jssc.SerialPortException;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class Java_jSSC_Uno {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());

            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Java_jSSC_Uno".getBytes()));
            //System.out.println("Port closed: " + serialPort.closePort());
        } catch (SerialPortException ex) {
            System.out.println(ex);
        }

        YahooWeather yahooWeather = new YahooWeather();
        yahooWeather.queryWeather();
        
        MyWeather myYahooWeatherResult = yahooWeather.getWeatherResult();
        System.out.println(myYahooWeatherResult.toString());
        
        try {
            serialPort.writeBytes(myYahooWeatherResult.description.getBytes());
            delay1s();
            
            serialPort.writeBytes(myYahooWeatherResult.city.getBytes());
            delay1s();
            serialPort.writeBytes(myYahooWeatherResult.region.getBytes());
            delay1s();
            serialPort.writeBytes(myYahooWeatherResult.country.getBytes());
            delay1s();
            
            serialPort.writeBytes(myYahooWeatherResult.conditiondate.getBytes());
            delay1s();

            serialPort.writeBytes(("humidity: " + myYahooWeatherResult.humidity).getBytes());
            delay1s();
            serialPort.writeBytes(("visibility: " + myYahooWeatherResult.visibility).getBytes());
            delay1s();
            serialPort.writeBytes(("pressure: " + myYahooWeatherResult.pressure).getBytes());
            delay1s();
            serialPort.writeBytes(("rising: " + myYahooWeatherResult.rising).getBytes());
            delay1s();
            
            serialPort.writeBytes(("chill: " + myYahooWeatherResult.windChill).getBytes());
            delay1s();
            serialPort.writeBytes(("direction: " + myYahooWeatherResult.windDirection).getBytes());
            delay1s();
            serialPort.writeBytes(("speed: " + myYahooWeatherResult.windSpeed).getBytes());
            delay1s();
            
            serialPort.writeBytes(("Sunrise: " + myYahooWeatherResult.sunrise).getBytes());
            delay1s();
            serialPort.writeBytes(("Sunset: " + myYahooWeatherResult.sunset).getBytes());
            delay1s();
            
            serialPort.writeBytes(myYahooWeatherResult.conditiontext.getBytes());
            delay1s();
        } catch (SerialPortException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        try {
            System.out.println("Port closed: " + serialPort.closePort());
        } catch (SerialPortException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static private void delay1s(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

class MyWeather{
    String description;
    String city;
    String region;
    String country;
    
    String windChill;
    String windDirection;
    String windSpeed;
    
    String humidity;
    String visibility;
    String pressure;
    String rising;
    
    String sunrise;
    String sunset;
    
    String conditiontext;
    String conditiondate;
    
    @Override
    public String toString(){
        
        return "\n- " + description + " -\n\n" 
            + "city: " + city + "\n"
            + "region: " + region + "\n"
            + "country: " + country + "\n\n"

            + "Wind\n"
            + "chill: " + windChill + "\n"
            + "direction: " + windDirection + "\n"
            + "speed: " + windSpeed + "\n\n"
            
            + "humidity: " + humidity + "\n"
            + "visibility: " + visibility + "\n"
            + "pressure: " + pressure + "\n"
            + "rising: " + rising + "\n\n"
            
            + "Sunrise: " + sunrise + "\n"
            + "Sunset: " + sunset + "\n\n"
            
            + "Condition: " + conditiontext + "\n"
            + conditiondate +"\n";
    }
}

class YahooWeather {
    
    MyWeather weatherResult;
    
    public void queryWeather(){
        String weatherString = query();
        Document weatherDoc = convertStringToDocument(weatherString);
        
        weatherResult = parseWeather(weatherDoc);
    }

    private String query() {
        String qResult = "";
        //Yahoo Weather Query URL for New York
        String queryString = "http://weather.yahooapis.com/forecastrss?w=2459115";

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(queryString);

        try {
            HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Reader in = new InputStreamReader(inputStream);
                BufferedReader bufferedreader = new BufferedReader(in);
                StringBuilder stringBuilder = new StringBuilder();

                String stringReadLine;

                while ((stringReadLine = bufferedreader.readLine()) != null) {
                    stringBuilder.append(stringReadLine).append("\n");
                }

                qResult = stringBuilder.toString();

            }

        } catch (IOException ex) {
            Logger.getLogger(YahooWeather.class.getName()).log(Level.SEVERE, null, ex);
        }

        return qResult;
    }

    private Document convertStringToDocument(String src) {
        Document doc = null;

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser;

        try {
            parser = dbFactory.newDocumentBuilder();
            doc = parser.parse(new ByteArrayInputStream(src.getBytes()));
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(YahooWeather.class.getName()).log(Level.SEVERE, null, ex);
        }

        return doc;
    }

    private MyWeather parseWeather(Document srcDoc){
        
        MyWeather myWeather = new MyWeather();

        //<description>Yahoo! Weather for New York, NY</description>
        myWeather.description = srcDoc.getElementsByTagName("description")
            .item(0)
            .getTextContent();

        //<yweather:location city="New York" region="NY" country="United States"/>
        Node locationNode = srcDoc.getElementsByTagName("yweather:location").item(0);
        myWeather.city = locationNode.getAttributes()
            .getNamedItem("city")
            .getNodeValue();
        
        myWeather.region = locationNode.getAttributes()
            .getNamedItem("region")
            .getNodeValue();
        
        myWeather.country = locationNode.getAttributes()
            .getNamedItem("country")
            .getNodeValue();

        //<yweather:wind chill="60" direction="0" speed="0"/>
        Node windNode = srcDoc.getElementsByTagName("yweather:wind").item(0);
        myWeather.windChill = windNode.getAttributes()
            .getNamedItem("chill")
            .getNodeValue();
        
        myWeather.windDirection = windNode.getAttributes()
            .getNamedItem("direction")
            .getNodeValue();
        
        myWeather.windSpeed = windNode.getAttributes()
            .getNamedItem("speed")
            .getNodeValue();
        
        //<yweather:atmosphere humidity="82" visibility="6" pressure="30.2" rising="0"/>
        Node atmosphereNode = srcDoc.getElementsByTagName("yweather:atmosphere").item(0);
        myWeather.humidity = atmosphereNode.getAttributes()
            .getNamedItem("humidity")
            .getNodeValue();
        
        myWeather.visibility = atmosphereNode.getAttributes()
            .getNamedItem("visibility")
            .getNodeValue();
        
        myWeather.pressure = atmosphereNode.getAttributes()
            .getNamedItem("pressure")
            .getNodeValue();
        
        myWeather.rising = atmosphereNode.getAttributes()
            .getNamedItem("rising")
            .getNodeValue();

        //<yweather:astronomy sunrise="6:52 am" sunset="7:10 pm"/>
        Node astronomyNode = srcDoc.getElementsByTagName("yweather:astronomy").item(0);
        myWeather.sunrise = astronomyNode.getAttributes()
            .getNamedItem("sunrise")
            .getNodeValue();
        
        myWeather.sunset = astronomyNode.getAttributes()
            .getNamedItem("sunset")
            .getNodeValue();

        //<yweather:condition text="Fair" code="33" temp="60" date="Fri, 23 Mar 2012 8:49 pm EDT"/>
        Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
        myWeather.conditiontext = conditionNode.getAttributes()
            .getNamedItem("text")
            .getNodeValue();
        
        myWeather.conditiondate = conditionNode.getAttributes()
            .getNamedItem("date")
            .getNodeValue();

        return myWeather;
    }
    
    public MyWeather getWeatherResult(){
        return weatherResult;
    }
    
    @Override
    public String toString(){
        return weatherResult.toString();
    }
}


Download HERE.

- To know how to deploy to Raspberry Pi remotely with Netbeans 8, refer to the post "Set up Java SE 8 Remote Platform on Netbeans 8 for Raspberry Pi".

Remark:
This example port from my old exercise on Android, "Get weather info from Yahoo! Weather RSS Feed".


Download and add Apache HttpComponents jar to Netbeans Project

In the coming post, I have to use Apache HttpComponents jar in my code. The Apache HttpComponents™ project is responsible for creating and maintaining a toolset of low level Java components focused on HTTP and associated protocols.

It can be download here: http://hc.apache.org/.

This video show how to download and add the Apache HttpComponents jar to your project in Netbeans.