码迷,mamicode.com
首页 > Web开发 > 详细

RASPBERRY PI 外设学习资源

时间:2014-07-01 09:18:14      阅读:1482      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   java   color   

参考: http://www.siongboon.com/projects/2013-07-08_raspberry_pi/index.html

Raspberry Pi bubuko.com,布布扣

bubuko.com,布布扣       Get started with Raspberry Pi (RPi), a step by step approach to get your Raspberry Pi with low level electronics hardware control.

Make simple, step by step.

 

Edited by Lim Siong Boon, last dated 22-Sep-2013.

email:    bubuko.com,布布扣  

website: http://www.siongboon.com

Topic Discussion Overview

  1. Installation from scratch
  2. Hardware Pin Out
  3. Raspberry Pi, HelloWorld for I/O pins
  4. Understanding UART, SPI, I2C port on Raspberry Pi
  5. Networking on Raspberry Pi
  6. Accessing Raspberry Pi through the network
  7. C Programming
  8. Python Programming
  9. Java Programming
  10. List of frequent used Commands
  11. Add Wifi to Raspberry Pi

 

1. Installation from scratch

 

 

 

Your orientation to Raspberry Pi.

bubuko.com,布布扣

http://www.raspberrypi.org/

bubuko.com,布布扣

Status LED Indicator 
OK  (Green) - SDCard Access       (D5 via GPIO16)
PWR (Red)   - 3.3 V Power         (D6           )
FDX (Green) - Full Duplex   (LAN) (D7 Model B   )
LNK (Green) - Link/Activity (LAN) (D8 Model B   )
10M (Yellow)- 10/100Mbit    (LAN) (D9 Model B   )

 

Click here for Raspberry Pi Schematic

STEP 01:

Download this quick start up guide to help you install your Linux OS on your Raspberry Pi.

bubuko.com,布布扣

STEP 02:

Get yourself a 4GB SD card, which is enough for use in many application.


NOTE: Not all SD cards work with the Raspberry Pi. High speed cards can be too fast for the Raspberry Pi bus. Check out which SD card is suitable for your Raspberry Pi. It has a lists of cards that have and have not worked for Raspberry Pi users. http://elinux.org/RPi_SD_cards

You may also like to check out the various peripherals that are compatiable to Raspberry Pi.
http://elinux.org/RPi_VerifiedPeripherals

bubuko.com,布布扣

 

STEP 03:

Format your SD card with SD Formatter 4.0 for SD/SDHC/SDXC 
SDFormatter4exe.zip (5.99MB)

 

 

STEP 04:

You can download the image version New Out Of Box Software (NOOBS), extract all the files and copy into your SD card.

Insert this SD card into your Raspberry Pi, and power on it. Follow the instruction on your screen display to complete the installation process. 

 

 

 

 

 

STEP 05:

You will be ask to select an Linux OS to install on your Raspberry Pi.

Choose the recommended "Raspian", which is also the Raspbian "wheezy".

The installation process will proceed.

 

Proceed to step 10.

Installing Raspbian operating system onto my Raspberry Pi.

bubuko.com,布布扣

 

 

 

STEP 06:

As of 02 Nov 2013, Raspbian now supports and pre-installed with Java.

Note: For those who want to run Java SDK on Raspberry Pi.

Raspbian “wheezy” is the recommended Linux OS for Raspberry Pi. This version is optimized to be run by Raspberry Pi which is using RP‘s ARM processor supporting ‘hard-float‘. However Java SDK only support ‘soft-float‘ at this point in time (Jul 2013). 

This call for another Debian Linux version which is known asSoft-float Debian “wheezy” (It is same as Raspbian "wheezy", except that it will be slower. Use this version if you need to run Java JDK Linux ARM)

 

 

STEP 07:

Download and run the Win32DiskImager on your Windows Operating System.
bubuko.com,布布扣 win32diskimager-v0.8-binary.zip (5.67MB)

You can download the latest version at this website,
http://sourceforge.net/projects/win32diskimager/

 

STEP 08:

Unzip the Debian Linux version Soft-float Debian “wheezy”, which is a "2013-05-29-wheezy-armel.img" file.

Run the program Win32 Disk Imager.
a) Select the Image File "2013-05-29-wheezy-armel.img"
b) Select the Device, which is your storage drive for your SD card.
c) Click on the <Write> button to write the raw image onto your SD card.

Note: You can also use Win32 Disk Imager software to backup (clone)your existing SD card image, by click on the <Read> button, and choosing a *.img file name.

bubuko.com,布布扣

STEP 09:

Insert the SD card into your Raspberry Pi and power it up.

 

STEP 10:

On the first boot, the "raspi-config" menu will pop up.

bubuko.com,布布扣



Note: If you are at the command shell prompt. You can key in
"sudo raspi-config" to access to this menu.

bubuko.com,布布扣

 

"raspi-config" menu

bubuko.com,布布扣

 

Note: You may find yourself having problem when trying to key in the ‘#‘ char by pressing <Shift+‘3‘>. A ‘£‘ pound char may be generated instead.

This is because the Raspberry Pi‘s default locale code is set as UK. You will need to set the locale code to US, for a US keyboard layout.

Key in the following command,
"sudo dpkg-reconfigure keyboard-configuration"

 

Alternative method to configure you keyboard layout.
a) key in "sudo nano /etc/default/keyboard"
b) look for the line containing "XKBLAYOUT="gb"".
c) change "gb" to "us" for US keyboard layout.
d) save and exit.
e) reboot or key in the following "invoke-rc.d keyboard-setup start", to reload the keymap.

STEP 11:

Select <1> and press enter to Expand Filesystem.

If you are connected to the network, s
elect <8 Advanced Options> and press enter.

<A2 Hostname> to change the hostname default "raspberrypi".

<A3 Memory Split> to configure the amount of ram allocation for GPU (graphic processing).

<A4 SSH> to enable or disable SSH (remote command access); it is enable by default.

<A5 Update> and then press enter to upgrade to the latest version of this tool. Try to perform this update.

"raspi-config" menu 8-A

bubuko.com,布布扣

To change to the Standard US Keyboard mapping, select <4 Internationalisation Options>,

<I1 Change Locale>, with the following options,
Default Locale : None

<I2 Time Zone >, with the following options,
Geographic area: Asia
Time Zone      : Singapore

<I3>, with the following options, 
Keyboard model : "Generic 105-key (Intl) PC"
Keyboard layout: "Others" -> "English (US)"
AltGr as       : "The default for the keyboard layout"
Compose Key    : "No compose key"
Ctrl+Alt+Backsp: "No", (don‘t use it to terminate Xserver)

You can also configure to allow the system to boot directly straight into the GUI desktop, using this raspi-config. 

Select <Finish> then press enter to proceed to the system command shell. 

You can always come back to this raspi-config menu again by executing the command "sudo raspi-config" from the shell command.

"raspi-config" menu 4-I

bubuko.com,布布扣

Very Very Important Note regarding boot up error

If you have encounter any error during the Linux operating system boot up, be sure to check the voltage level being supplied to your Raspberry Pi. It is a very common problem faced, if you have tried to power up your Raspberry Pi using any power adaptor that you have picked up.

Always check if your power adaptor is suitable by measuring the voltage supplied to your Raspberry Pi. If you deploy your Raspberry Pi for yoru project without ensuring that your power adaptor is ok, you may face random system error freeze/hang/halt. Problem can occur out of the norm. Be sure to check. Click here to find out how you can ensure that you are using the correct power adaptor and cable for your Raspberry Pi.
 

 

bubuko.com,布布扣

 

2. Hardware Pin Out

 

Raspberry Pi revision 2, header pins out.

  3V3 1 2
5V
 
GPIO_2
<->SDA0 3 4
5V
 
GPIO_3
<->SCL0 5 6
Gnd
 
GPIO_4
GPCLK0 7 8
TXD->
GPIO_14
  Gnd 9 10
RXD<-
GPIO_15
GPIO_17
GPIO0 11 12
GPIO1/PWM
GPIO_18
GPIO_27
GPIO2 13 14
Gnd
 
GPIO_22
GPIO3 15 16
GPIO4
GPIO_23
  3V3 17 18
GPIO5
GPIO_24
GPIO_10
<-MOSI 19 20
Gnd
 
GPIO_9
->MISO 21 22
GPIO6
GPIO_29
GPIO_11
<-SCLK 23 24
CE0->
GPIO_8
  Gnd 25 26
CE1->
GPIO_7

 

This is my Raspberry Pi. I have custom built a prototyping board that can be plugged on top of my Raspberry Pi. This prototyping board is soldered with 2.54mm housing connector (2 rows of 13 pins) so that I can easily access to the I/O pins of my Raspberry Pi.bubuko.com,布布扣

My LED indicator wiring is as follows,
LED0 - GPIO_17 (Pin11)

LED1 - GPIO_18 (Pin12)
LED2 - GPIO_27 (Pin13)
LED3 - GPIO_22 (Pin15)
LED4 - GPIO_23 (Pin16)
LED5 - GPIO_24 (Pin18)
LED6 - GPIO_29 (Pin22)

UART (serial communication) wiring,
Gnd -         (Pin06) 
TXD - GPIO_14 (Pin08)
RXD - GPIO_15 (Pin10)

SPI (serial communication) wiring,
MOSI - GPIO_10 (Pin19)
MISO - GPIO_09 (Pin21)
SCLK - GPIO_11 (Pin23)
CE0  - GPIO_08 (Pin24)
CE1  - GPIO_07 (Pin26)

I2C (serial communication) wiring,
SDA0 - GPIO_02 (Pin03)
SCL0 - GPIO_03 (Pin05)

 

GPIO input/output pin electrical characteristics
Output low voltage
VOL
< 0.40 V
< 0.66 V
< 0.40 V
Output high voltage
VOH
> 2.40 V
> 2.64 V
> 2.90 V
Input low voltage
VIL
< 0.80 V 
< 0.54 V 
< 1.15 V
Input high voltage
VIH
> 2.00 V 
> 2.31 V 
> 2.15 V
Hystereses > 0.25 V 
   0.66 – 2.08 V
Schmitt trigger input low threshold
VT–
1.09 - 1.16 V 
0.9
Schmitt trigger input high threshold
VT+
2.24 - 2.74 V 
0.90 V
Pull-up/down
resistance
40 – 65KΩ
100KΩ
Pull-up/down
current
< 50 uA
< 28 uA
Pin capacitance 5 pF
Bus hold resistance 5-11KΩ

Information taken from
http://www.mosaic-industries.com/embedded-systems/

bubuko.com,布布扣

 

3. Raspberry Pi, HelloWorld for I/O pins  

Learning to control Raspberry Pi general purpose I/O pin 11 (which is known as GPIO_0, or GPIO_17 if base on BCM2835 IC pin assignment)Power on my Raspberry, and the operating system will prompt for my raspberrypi login.Key in "pi" for the login, and "raspberry" for the password.

 

bubuko.com,布布扣raspberrypi login: pi
Password: raspberry

pi@raspberrypi ~ $

First start by keying the command "" to change to the root user, which have a higher privilege access rights to the system. pi@raspberrypi ~ $ sudo -i
You will see a new prompt -> root@raspberrypi:~#

Setup or initialise I/O port 17, by sending text "17" to the operating file system "/sys/class/gpio/export"

A directory folder will be created. "/sys/class/gpio/gpio17/"

root@raspberrypi:~# echo "17" > /sys/class/gpio/export
Setting the I/O pin as an output port, by sending text "out" to the operating file system "/sys/class/gpio/gpio17/direction" root@raspberrypi:~# echo "out" > /sys/class/gpio/gpio17/direction
To set logic 1 to the output port, send a text "1" to the operating file system "/sys/class/gpio/gpio17/value" root@raspberrypi:~# echo "1" > /sys/class/gpio/gpio17/value
My LED indicator0 (green color) gets lighted up. My very first hardware control using Raspberry Pi, Linux operating system. Yuppee... bubuko.com,布布扣
To switch off my LED, send a text "0" to the operating file system "/sys/class/gpio/gpio17/value" root@raspberrypi:~# echo "0" > /sys/class/gpio/gpio17/value
 
Setting up an input port is quite similar. I will be using I/O port 18 as input.  
Setup I/O port 18. root@raspberrypi:~# echo "18" > /sys/class/gpio/export
Setup port 18 as an input port. root@raspberrypi:~# echo "in" > /sys/class/gpio/gpio18/direction
Reading input port 18. root@raspberrypi:~# cat /sys/class/gpio/gpio18/value
Command prompt will return the following value (logic 0) after reading the port. 0
root@raspberrypi:~#
The port 18, which is pin 12 on my Raspberry Pi is now connected to 3.3V to simulate a logic 1 input. The input port is then rRead in again. root@raspberrypi:~# cat /sys/class/gpio/gpio18/value
Command prompt will return the following value (logic 1) after reading the port, which is correct. 1
root@raspberrypi:~#

Reference:
http://elinux.org/RPi_Low-level_peripherals#GPIO_Driving_Example_.28C.29

 

 
 

I am able to control the I/O pins on my Raspberry Pi, but I want to larn more into controlling the I/O pins using native C. Controlling I/O pins using the "file directory system" like method will be very slow.The speed achieved base on this benchmark website, I/O control through this shell (or file directory system) method, achieved a maximum process speed of about 6.8kHz (2x 3.4kHz).To achieve a higher speed, I will need to use native C programming, which can process from 9.4Mhz to 44Mhz (2x 4.7Mhz to 22Mhz).

More things to learn...

 

References:

Notes regarding digital I/O pins,https://www.kernel.org/doc/Documentation/gpio.txt

 

 

4. Understanding UART, SPI, I2C port on Raspberry Pi  

UART

The UART port is actually pin8 (TxD) and pin10 (RxD) on the Raspberry Pi connectors. The UART signal is 3.3V.You can use RS232/RS422/RS485 communication to talk to the UART, but a level shifter (for example MAX3232) required. RS232 uses about +/- 7 to 13V, while UART uses digital voltage (1.8V, 3.3V or 5V). For our Raspberry Pi UART, it is 3.3V. More information about making your own level shifter, you can visit this page. There are also standard USB to UART products for interfacing to your Raspberry Pi.The Raspberry Pi default operating system uses this UART port as its diagnostic port. This port has the following default UART settings,
- Baudrate   : 115200bps
- Data       : 8 bits
- Parity     : None
- Handshaking: None
This default port act as another Linux shell terminal screen, as you would have seen on the screen through the Raspberry Pi‘s HDMI or video output.

 

 

You can use a terminal program to access through this port.Using the Window‘s Hyperterminal program, setup the correct com port settings. And connect the terminal. You will see nothing on the terminal screen, but actually the Raspberry Pi is prompting you for your login ID. This ID is "pi" which is similar to how you log on to your typical terminal screen. You will see the terminal replying you with the prompt for password. Key in the default password "raspberry". You shall get a similar print out from the terminal program, as on the right. ->Looks very much like the typical terminal on your local display. This is mainly for troubleshooting, diagnostic or perhaps used for remote access of your Raspberry Pi.

 

raspberrypi login: pi
Password:
Last login: Wed Jun 19 15:36:44 UTC 2013 on tty1
Linux raspberrypi 3.6.11+ #474 PREEMPT Thu Jun 13 17:14:42 BST 2013 armv6l
The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
pi@raspberrypi:~$

The UART on the Raspberry Pi is quite an useful peripheral. For me, I would like to use this UART as a serial communication to control my other circuit modular.

In order to use this UART, I need to disable the diagnostic features from the operating system‘s boot up. This means that I do not want the system to setup the UART pins as diagnotic port, when the system boots up.

 
This means that we need to edit the boot up file. Before we do any editing, it is good to save a backup copy of it. Type the copy command "cp" as follows. -> pi@raspberrypi ~ $ sudo cp /boot/cmdline.txt /boot/cmdline_backup.txt

The following command is key in to edit the system boot up script. vi is an text editor program, which is not very user friendly.Alternative, you can usenano editor instead of vi for the text file editing.
Or gedit editor. You can install then if they are not installed.
"sudo apt-get install nano" or
"sudo apt-get install gedit " 
To learn how to use the vi editor, click on the following link,http://www.unix-manuals.com/tutorials/vi/vi-in-10-1.html

A summary of the vi editor‘s command is summeries as follows,http://osr600doc.sco.com/en/FD_create/vi_summary.html

pi@raspberrypi ~ $ sudo vi /boot/cmdline.txt

After the vi command, you should see the following screen display. This is the vi editor diaplaying the text in the "cmdline.txt file".The objective is to delete the text (in red color), which is relating to the UART setup. Press ‘l‘ on your keyboard to shift the cursor to the right, until it is at the position of the char that we want to delete. Move the cursor under the first char ‘c‘ (char as illustrated in red).Press ‘x‘ on your keyboard to delete the char one by one. You should observed the delete action.When all the text in red are deleted, press ‘:w‘ on your keyboard, follow by a enter key to save the text file.Press ‘:q‘ on your keyboard, follow by a enter key to exit the vi program.If at anytime you have edit wrongly, you can enter the command ‘:q!‘ on your keyboard, to exit the vi program without saving the text file.

 

dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait
~
~
~
~
~
~

Your "cmdline.txt" should contain the following text after the editing. dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait
~
~
~
Next edit inittab with the following command. pi@raspberrypi ~ $ sudo vi /etc/inittab

Find and comment away the line containing the following text (near the end of the file),
"T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100",
by pressing the ‘j‘ on your keyboard to scroll down line by line.Issue an insert command by pressing ‘i‘ to insert some text before the cursor. Insert a char ‘#‘ at the beginning of the line to comment the whole line. The ‘#‘ mask off the whole line. The line that are masked off will not be intepreted by the system.After the ‘#‘ char is inserted, press <Esc> key on your keyboard to end the insert command that was issued.Press ‘:w‘ save the text file.

Press ‘:q‘ to exit the vi program.

#Spawn a getty on Raspberry Pi serial line
#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

The UART device name is /dev/ttyAMA0
Now the UART is not in use by the Linux Raspbian operating system, and is available for my own use.

 

 
Reboot for the operating system‘s settings to take effect. pi@raspberrypi ~ $ sudo reboot
 

To test the UART serial communication port, we can install a program call minicom. The use of minicom is similar to hyperterminal program that I use in Windows operating system (OS).

Enter the command "
sudo apt-get install minicom"

There are also alternative GUI based serial communication program, cutecom.

pi@raspberrypi ~ $ sudo apt-get install minicom

Reading package lists... Done
Building dependency tree
Reading state information... Done
...
Need to get 420 kB of archives.
After this operation, 1,189 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
Get:1 http://mirrordirector.raspbian.org/raspbian/ wheezy/main lrzsz armhf 0.12.21-5 [106 kB]
Get:2 http://mirrordirector.raspbian.org/raspbian/ wheezy/main minicom armhf 2.6.1-1 [314 kB]
Fetched 420 kB in 13s (30.2 kB/s)
...
Unpacking minicom (from .../minicom_2.6.1-1_armhf.deb) ...
Processing triggers for man-db ...
Processing triggers for menu ...
Setting up lrzsz (0.12.21-5) ...
Setting up minicom (2.6.1-1) ...
Processing triggers for menu ...

To run the minicom terminal program. Key in the following command "sudo minicom -b 9600 -o -D /dev/ttyAMA0".

-o
              (skip initialisation)
-D /dev/ttyAMA0
 (specify the serial port)

Key in command "man minicom" to find out the other options that you can set with the minicom program.

Configuration Settings: 
Baudrate : 9600bps 
Data bit : 8    (default)
Stop bits: 1    (default)
Parity   : None (default)


Apply the configuration settings to serial port "ttyAMA0". The label tty (known as teletype) denotes all serial communication that the linux operating system is handling. In Raspberry Pi, ttyAMA0 refers to the pin8 (TxD) and pin10 (RxD).

When you type a char on your keyboard, an ascii char code is actually sent out of the Raspberry Pi ‘s pin8 (TxD). You will not be able to see it on the screen. What you will see on your screen will be those serial data that the Raspberry Pi received through pin10, which is the RxD.

In order to see what we have transmitted out from TxD, we can short the pin8 (TxD) and pin10 (RxD) together. This means that what you send will be receive and display on the display. The serial port configuration for the TxD and RxD is the same, so the serial data that is received will be exactly what you have transmitted.

The following text "Hello World!!! " were typed on the keyboard after shorting the RxD and Txd pin. The text will be displayed, indicating that the UART is working properly.

Now that you know that the UART on your Raspberry Pi is ready for use, you can use it to communicate with many other 
peripheral.

Press <Ctrl + ‘A‘>, followed by <‘X‘>, then key in enter for "Yes" to quit the minicom program.

pi@raspberrypi ~ $ sudo minicom -b 9600 -o -D /dev/ttyAMA0

-------------------------------------------
Welcome to minicom 2.6.1
OPTIONS: I18n
Compiled on Apr 28 2012, 19:24:31.
Port /dev/ttyAMA0
Press CTRL-A Z for help on special keysHello World!!!

CTRL-A Z for help | 9600 8N1 | NOR | Minicom 2.6.1 | VT102 | Offline
-------------------------------------------

Setting up the serial port with other settings,
Baudrate : 115200bps 
Data bit : 8    
Stop bits: 1    
Parity   : Even


pi@raspberrypi ~ $ sudo minicom -b 115200 -8 -o -D /dev/ttyAMA0
Key in command "sudo minicom -s " to launch the minicom menu for other default settings, which can be save onto *.dfl files.
The default config file is minicom.dfl
 
Other related commands

- "dmesg | grep tty" checking up the UART available on the system.
 
   

SPI

The SPI port onboard the Raspberry is disable by default. The first thing to do is to enable the SPI port.

Edit the file "/etc/modprobe.d/raspi-blacklist.conf"

Comment off the line "blacklist spi-bcm2708" with a # in front.

Key in Ctrl+‘X‘ to exit, then ‘Y‘ yes to save the change to the file, and finally ‘Enter‘. This will brings you back to the command prompt.

pi@raspberrypi ~ $ sudo nano /etc/modprobe.d/raspi-blacklist.conf

GNU nano 2.2.6 File: /etc/modprobe.d/raspi-blacklist.conf Modified

# blacklist spi and i2c by default (many users don‘t need them)

#blacklist spi-bcm2708
blacklist i2c-bcm2708
8

 

 

Reboot Raspberry Pi pi@raspberrypi ~ $ sudo reboot

Check to see if the SPI is successfully enable in the Raspberry Pi.

You should see "/dev/spidev0.0 /dev/spidev0.1" created.

0.0 means SPI0 CS0 (CS is the chip select)
0.1 means SPI0 CS1

pi@raspberrypi ~ $ ls /dev/spidev*
/dev/spidev0.0 /dev/spidev0.1
pi@raspberrypi ~ $

Testing the SPI port

download this SPI loopback test code written in ‘C‘ programming language.

spidev_test.c

Compile the *.c file using gcc command,then run the compiled program.

You should see the following hex dump data, indicating all 0x00.

This means that the SPI is receiving nothing, no data.

pi@raspberrypi ~ $ gcc spidev_test.c -o spidev_test 
pi@raspberrypi ~ $ sudo ./spidev_test -D /dev/spidev0.0
spi mode: 0
bits per word: 8
max speed: 500000 Hz (500 KHz)

00 00 00 00 00 00
00 00 00 00 00 00
00 00 00 00 00 00
00 00 00 00 00 00
00 00 00 00 00 00
00 00 00 00 00 00
00 00

pi@raspberrypi ~ $

Now we do a SPI data loopback test.
Short the pins MISO (GPIO 9, Pin21) and MOSI (GPIO 10, Pin19) on your Raspberry Pie. This will enables the SPI MISO to received whatever data that is sent out from the MOSI pins.

From this test, we will be able to know if SPI hardware for sending and receving is working ok. Whatever that is sent out, the data should be properly received.

Run the compiled program again.

You should see the following hex dump data. This means that your SPI peripheral is working fine.

pi@raspberrypi ~ $ sudo ./spidev_test -D /dev/spidev0.0

spi mode: 0
bits per word: 8
max speed: 500000 Hz (500 KHz)

FF FF FF FF FF FF
40 00 00 00 00 95
FF FF FF FF FF FF
FF FF FF FF FF FF
FF FF FF FF FF FF
DE AD BE EF BA AD
F0 0D

pi@raspberrypi ~ $

   

I2C

The SPI port onboard the Raspberry is disable by default. The first thing to do is to enable the SPI port.

Edit the file "/etc/modprobe.d/raspi-blacklist.conf"

Comment off the line "blacklist i2c-bcm2708" with a # in front.

Key in Ctrl+‘X‘ to exit, then ‘Y‘ yes to save the change to the file, and finally ‘Enter‘. This will brings you back to the command prompt.

pi@raspberrypi ~ $ sudo nano /etc/modprobe.d/raspi-blacklist.conf

GNU nano 2.2.6 File: /etc/modprobe.d/raspi-blacklist.conf Modified

# blacklist spi and i2c by default (many users don‘t need them)

blacklist spi-bcm2708
#blacklist i2c-bcm2708
8

 

 

Edit the file "/etc/modules"

Add in "i2c-dev" to the end of the file.

Key in Ctrl+‘X‘ to exit, then ‘Y‘ yes to save the change to the file, and finally ‘Enter‘. This will brings you back to the command prompt.

pi@raspberrypi ~ $ sudo nano /etc/modules

# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.
# Parameters can be specified after the module name.

snd-bcm2835
i2c-dev

 

Install I2C Tools to test on the I2C peripheral. pi@raspberrypi ~ $ sudo apt-get install i2c-tools
Reading package lists... Done
Building dependency tree
Reading state information... Done
Suggested packages:
libi2c-dev python-smbus
The following NEW packages will be installed:
i2c-tools
0 upgraded, 1 newly installed, 0 to remove and 52 not upgraded.
Need to get 59.5 kB of archives.
After this operation, 223 kB of additional disk space will be used.
Get:1 http://http.debian.net/debian/ wheezy/main i2c-tools armel 3.1.0-2 [59.5 kB]
Fetched 59.5 kB in 4s (12.5 kB/s)
Selecting previously unselected package i2c-tools.
(Reading database ... 57047 files and directories currently installed.)
Unpacking i2c-tools (from .../i2c-tools_3.1.0-2_armel.deb) ...
Processing triggers for man-db ...
Setting up i2c-tools (3.1.0-2) ...

Allow Pi User to Access I2C peripheral.

This allow configuration of the software.

pi@raspberrypi ~ $ sudo adduser pi i2c
Adding user `pi‘ to group `i2c‘ ...
Adding user pi to group i2c
Done.
Reboot Raspberry Pi pi@raspberrypi ~ $ sudo reboot

Check to see if the SPI is successfully enable in the Raspberry Pi.

You should see "/dev/i2c-0 /dev/i2c-1" created.

pi@raspberrypi ~ $ ls /dev/i2c*
/dev/i2c-0 /dev/i2c-1
pi@raspberrypi ~ $

Running the test program.

You will see that there is a total of 0x77 or 119 blanks "--". This indicates that no I2C devices is detected on the bus. 

pi@raspberrypi ~ $ i2cdetect -y 0
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
If the I2C devices is on the I2C bus, it will appeared as follows.
For this example, the I2C devices has an address of 0x60. The software detects a device is currently onto the I2C data bus.
pi@raspberrypi ~ $ i2cdetect -y 0
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: 60 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

 

 

bubuko.com,布布扣

 

5. Networking on Raspberry Pi References:
Installing Samba program
Checking the IP setting on my Raspberry Pi. pi@raspberrypi 
Ping gateway 192.168.1.1 pi@raspberrypi ping 192.168.1.1 -c 4 
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=1.98 ms
64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=1.17 ms
64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=1.19 ms
64 bytes from 192.168.1.1: icmp_seq=4 ttl=64 time=1.23 ms

--- 192.168.1.1 ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 1.171/1.399/1.988/0.340 ms
Ping website www.yahoo.com.sg pi@raspberrypi ~ $ ping yahoo.com.sg -c 4 
PING yahoo.com.sg (106.10.165.51) 56(84) bytes of data.
64 bytes from w2.rc.vip.sg3.yahoo.com (106.10.165.51): icmp_seq=1 ttl=51 time=16.9 ms
64 bytes from w2.rc.vip.sg3.yahoo.com (106.10.165.51): icmp_seq=2 ttl=51 time=28.1 ms
64 bytes from w2.rc.vip.sg3.yahoo.com (106.10.165.51): icmp_seq=3 ttl=51 time=20.3 ms
64 bytes from w2.rc.vip.sg3.yahoo.com (106.10.165.51): icmp_seq=4 ttl=51 time=17.5 ms

--- yahoo.com.sg ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 16.996/20.762/28.140/4.441 ms

Other command:
ifconfig eth0 (display the first ethernet adaptor) 
- ifconfig -a (show all network interface, active or inactive) 
traceroute

 
 

Install Samba on the system so that my Raspberry Pi can be access from a Window operating system.

Ensure that the network cable (internet enabled) is plugged onto the Raspberry Pi before powering on the board. Enter the following command to install samba software. The process will fetch the installation from the internet.

pi@raspberrypi ~ $ sudo apt-get install samba samba-common-bin
Optional:
Enable security on the Samba server on the Raspberry Pi (RPi)
 
Making a backup of the samba configuration file. pi@raspberrypi ~ $ sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.old
Edit the samba configuration file using the nano text editor pi@raspberrypi ~ $ sudo nano /etc/samba/smb.conf

Search for the section marked ##### Authentication #####,
Change the following text "# security = user" to "security = user".
To save the text file, Press "Ctrl+X", then ‘Y‘, then enter.

 
Restart samba to use the new configuration file. pi@raspberrypi ~ $ sudo /etc/init.d/samba restart
ok ] Stopping Samba daemons: nmdb smdb
ok ] Stopping Samba daemons: nmdb smdb

Use command "hostname -I" to check the IP address.

Alternate command "ifconfig" to check the IP address of my Raspberry Pi, which IP address is "192.168.1.99"

pi@raspberrypi ~ $ hostname -I
192.168.1.99

pi@raspberrypi ~ $  ifconfig
eth0  Link encap:Ethernet  HWaddr b8:27:eb:dc:ee:af
      inet addr:
192.168.1.99  Bcast:192.168.1.255  Mask:255.255.255.0
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:337 errors:0 dropped:0 overruns:0 frame:0
      TX packets:198 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:30734 (30.0 Kib)  TX bytes:20136 (19.6 Kib)

Or using command "ip address show" pi@raspberrypi ~ $ ip address show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether b8:27:eb:dc:ee:af brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.95/24 brd 192.168.1.255 scope global eth0
Configuring your network settings 
sudo nano /etc/network/interfaces
 pi@raspberrypi ~ $ sudo nano /etc/network/interfaces

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
To set static IP address, edit the file "interfaces" to the example as follows.
Save the file and reboot Raspberry Pi for the changes to take effect.
auto lo

iface lo inet loopback

#wired connection (using static IP address, instead of DHCP to auto allocate IP) 
#iface eth0 inet dhcp
iface eth0 inet static
address 192.168.1.201
netmask 255.255.255.0
gateway 192.168.1.1

#wireless connection (using static IP address, instead of DHCP to auto allocate IP) 
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
#iface wlan0 inet dhcp
iface wlan0 inet static
address 192.168.1.202
netmask 255.255.255.0
gateway 192.168.1.1
#iface default inet dhcp

Go to window‘s to map a network drive. The network folder path is "//192.168.1.99". Check box for "Reconnect at logon" & "Connect using different credentials"

 

Check the network and port bind on the Raspberry Pi.

 

From the list, it can be seen that UDP port 6324 is currently being used by process ID PID 2361/java program.

 pi@raspberrypi ~ $ netstat -nlptu
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:6010 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN -
udp 0 0 192.168.1.99:123 0.0.0.0:* -
udp 0 0 127.0.0.1:123 0.0.0.0:* -
udp 0 0 0.0.0.0:123 0.0.0.0:* -
udp 0 0 0.0.0.0:51876 0.0.0.0:* -
udp 0 0 0.0.0.0:6324 0.0.0.0:* 2361/java
udp 0 0 0.0.0.0:68 0.0.0.0:* -
Setting up a secure home Web Server with Raspberry Pi  

 

6. Accessing Raspberry Pi through the network

Sometimes you may like to access to your Raspberry Pi without connecting your display monitor and your keyboard. This section provide a guide to allow access to your Raspberry Pi remotely through network connection.

 

Checking the IP setting on the Raspberry Pi, using command "ip address show". For my Raspberry Pi, the IP address is 192.168.1.95. pi@raspberrypi ~ $ ip address show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 
00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether b8:27:eb:dc:ee:af brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.95/24 brd 192.168.1.255 scope global eth0

How to locate your Raspberry Pi IP address from a remote computer?

The method above requires you to plugged a monitor display to your Raspberry Pi in order to obtain its IP address. The following method allows you to obtain raspberry pi address through thr

You can also check the IP address of your Raspberry Pi that is plugged into a dynamic network through the router webserver. Typical router‘s IP address for a local network is 192.168.1.1. You will need your user name and password to log into the router‘s webserver. From the webserver, you should be able to locate the device name "raspberrypi" (or known as hostname) and its allocated dynamic IP address and its MAC address.

Alternative, you can use this software "Advance Port Scanner" to scan for your Raspberry Device on the network.

pi@raspberrypi ~ $ hostname
raspberrypi

 

 

 

Note: To change the Raspberry Pi‘s hostname "raspberrypi", use nano text editor to edit the following file "/etc/hostname" and "/etc/hosts". Replace the old hostname "raspberrypi" to your new hostname. Your new hostname can only contains lower/upper case character, numbers, and ‘-‘.

Your new hostname will appear on the raspberry prompt, after the device reboot.

pi@raspberrypi ~ $ sudo nano /etc/hostname

pi@raspberrypi ~ $ sudo nano /etc/hosts

pi@raspberrypi ~ $ sudo reboot

pi@newHostname ~ $

 

Download this program MobaXterm, and install in your Window operating system. You can download fromhttp://mobaxterm.mobatek.net/
bubuko.com,布布扣

Alternative, you can also use this program call Putty.
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

Alternative, you can also use this program call Filezilla

https://filezilla-project.org/ (for Microsoft Windows OS).
or (for Linux OS) "sudo apt-get install filezilla"

These program allow SSH connection logging in to your Raspberry Pi. You will be able to see what you would see with the display monitor and keyboard connected to your Raspberry Pi

 

Run the installed MobaXterm program.
Click on "Session"->"Open New Session".
Choose "SSH" as the session type.
Key in the IP address of your Raspberry Pi.
The standard port number for SSH Remote Login Protocol is 22.

 

Click "OK" to connect to your Raspberry Pi.

Key in the Login user name "pi", then press enter, and 
standard password "raspberry" then press enter key.

You will see the following display as on the right. 

Login: pi
Permanently added ‘192.168.1.95‘ (ECDSA) to the list of known hosts.
rasppi@192.168.1.95‘s password:
Linux raspberrypi 3.6.11+ #474 PREEMPT Thu Jun 13 17:14:42 BST 2013 armv6lThe programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Mon Jul 22 13:47:57 2013
pi@raspberrypi ~ $

You may encounter the following error on the right.
If not, you can skip this section.
This happens when you login successfully for the first time, but then you reinstall the server. The key becomes different, and you get prompt for this security message.
Access into your Raspberry Pi and key in the following command, 
"rm -f ~/.ssh/known_hosts"

Delete from your client computer. 
C:\Users\LSB\Documents\MobaXterm\home\.ssh\known_hosts.

You may need to reboot the Linux in order for the change to take effect "sudo reboot". 

It should solve the problem. For more information regarding this issue, you can visit the following website,
http://www.geekride.com/ssh-warning-remote-host-identification-has-changed/


@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that a host key has just been changed. The fingerprint for the RSA key sent by the remote host is xx:xx:xx:xx:b1:66:fd:05:0c:43: .... ... .. .

Congratulation. You have access your Raspberry Pi remotely through the network.  
To remotely access the desktop GUI of your Raspberry Pi, key in the following command from your MobaXterm‘s command console. The ‘&‘ at the end of the command help launch the application in the background (another thread process) so that we can continue using the terminal. pi@raspberrypi ~ $ lxsession&
The Raspberry Pi‘s desktop will be launched from your Window operating system, as follows... bubuko.com,布布扣
GUI application can also be launched directly within WinOS without accessing to the Raspberry Pi Linux desktop.

pi@raspberrypi ~ $ leadpad&

bubuko.com,布布扣

Using MobaXterm, you can actually drag and drop file in the lower left corner of the MobaXterm‘s windows. bubuko.com,布布扣
Key in "exit", then press enter, to terminate the session. pi@raspberrypi ~ $ exit

 

7. C Programming on Raspberry Pi, Hello World!!!  
Classic first program to write every time we learn a new programming language on a new platform.  
Type in "gcc" command with a flag -v to see the version of the C complier.

pi@raspberrypi ~ $ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO...
...
...

Thread model: posix
gcc version 4.6.3 (Debian 4.6.3-14+rpi1)

Create a folder "tutorial" to hold the files for this tutorial pi@raspberrypi ~ $ mkdir tutorial
Get into the newly create tutorial folder pi@raspberrypi ~ $ cd tutorial
Create a "main.c" file using the program nano (text editor) pi@raspberrypi ~ $ sudo nano main.c

Key in the following hello world source code into the nano editor.

When finish typing in the source code text, press CTRL+X to save this file "main.c", press ‘Y‘ to confirm. Press enter key to finish the process.

#include <stdio.h>

int main()
{
   printf("Hello World!!!");
   return(0);
}

Now compile the source code file "main.c" to executable file "main" pi@raspberrypi ~ $ gcc -o main main.c
Now execute the file "main", you should see the text "Hello World!!!" as you have programmed in the source code. pi@raspberrypi ~ $ ./main
Hello World!!!

For compiling C++ language (*.cpp file), use g++ compiler.

 

 

8. Python Programming on Raspberry Pi, Hello World!!!  
Classic first program to write every time we learn a new programming language on a new platform.  
Type in "python -V " command to see the version of the C complier.

pi@raspberrypi ~ $ python -V 
Python 2.7.3

Run the python program, and key in the python script directly onto the python command line.

Type the script >>> print "Hello World!!!"

You will see the "Hellow World!!!" text echo back.

Press <Ctrl+‘z‘> to terminate the Python program.
pi@raspberrypi ~ $ sudo python
Python 2.7.3 (default, Jan 13 2013, 11:20:46)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Hello World!!!"
Hello World!!!
>>>
You can also write the phython codes onto a *.py file, and run directly from the file saved with python scripts.

Create a folder "python_tutorial" to hold the files for this tutorial
pi@raspberrypi ~ $ mkdir python_tutorial
Get into the newly create tutorial folder pi@raspberrypi ~ $ cd python_tutorial
Create a "hello.py" file using the program nano (text editor) pi@raspberrypi ~ $ sudo nano hello.py

Key in the following hello world source code into the nano editor.

When finish typing in the source code text, press CTRL+X to save this file "hello.py", press ‘Y‘ to confirm. Press enter key to finish the process.

#!/usr/bin/python

print "Hello World!!!"nt "Boon, you‘re awesome"
else : 
print "Hello", name

Now execute the file "hello.py", you should see the text "Hello World!!!" as you have programmed in the source code. pi@raspberrypi ~ $ python hello.py
Alternative, you can make the file executable, and execute the file directly. pi@raspberrypi ~ $ chmod a+x hello.py
pi@raspberrypi ~ $ ./hello.py
Hello World!!!

Using Python to control the digital I/O port.
Before starting to program your I/O on Raspberry Pi, we will need to download and setup the library.

pi@raspberrypi ~ $ wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.1.0.tar.gz
pi@raspberrypi ~ $ tar zxf RPi.GPIO-0.1.0.tar.gz
pi@raspberrypi ~ $ cd RPi.GPIO-0.1.0
pi@raspberrypi ~ $ sudo python setup.py install

Try controlling the Raspberry Pi‘s digital I/O GPIO1 (pin12 of the header, GPIO18) as output port, using Python script.

1) import RPi.GPIO

2) setup I/O direction, as output port. 
3) set digital I/O port to logic ‘1‘, high
4) set digital I/O port to logic ‘0‘, low

You should see the LED lights up and switched off, if wired an indicator to pin 12.

pi@raspberrypi ~ $ sudo Python
>>> import RPi.GPIO as GPIO
>>> GPIO.setup(18, GPIO.OUT)
>>> GPIO.output(18, True)
>>> GPIO.output(18, False)

Example of a typical python‘s source code.

#!/usr/bin/python 

import sys
import time
import serial

#print title 
print("start python program.")#print out the arg passed from command line 
for arg in sys.argv:
  print arg#delay 0.1sec 
time.sleep(0.1)

#delay 1.0sec 
time.sleep(1) #setup serial port 
port = serial.Serial("/dev/ttyAMA0", baudrate=115200, timeout=3.0)#get user input
name = raw_input(‘what is your name? ‘)#conditional statement
if name == ‘Boon‘ :
  print "Boon, you‘re awesome"
else : 
  print "Hello", name

#while loop
while True: 
  port.write("\r\nSay something:")
  rcv = port.read(10)
  port.write("\r\nYou sent:" + repr(rcv))

Python code example for I/O.

#!/usr/bin/python

import time
import RPi.GPIO as GPIO

GPIO.setup(11, GPIO.IN)
while True:
  mybutton = GPIO.input(11)
  if mybutton == False:
    print "giggle"
  time.sleep(.2)

#!/usr/bin/python
import RPi.GPIO as GPIO
GPIO.setup(11, GPIO.IN)
GPIO.setup(12, GPIO.OUT)
while True:
  if GPIO.input(11):
    GPIO.output(12, True)
  else:
    GPIO.output(12, False)
Invoke system command (shell command) from Python script. >>> import commands
>>> commands.getstatusoutput(‘ls /bin/ls‘)
(0, ‘/bin/ls‘)
>>> commands.getstatusoutput(‘cat /bin/junk‘)
(256, ‘cat: /bin/junk: No such file or directory‘)
>>> commands.getstatusoutput(‘/bin/junk‘)
(256, ‘sh: /bin/junk: not found‘)
>>> commands.getoutput(‘ls /bin/ls‘)
‘/bin/ls‘
>>> commands.getstatus(‘/bin/ls‘)
‘-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls‘

 

9. Java Programming on Raspberry Pi, Hello World!!!  

Note: As of Nov 2013, the official operating system for Raspberry Pi "Raspian" is installed with Java by default. Proceed to the step for installing Pi4J.

Installing Java to your Raspberry Pi

First, we will need to download and instal the Java JDK onto the Raspberry Pi.Do take note that the JDK version that we will be downloading is meant for Linux ARM processor "Linux ARM v6/v7 Soft Float ABI".
(28 July 2013)

JDK for Linux ARM, "jdk-21-linux-arm-sfp.tar.gz (65.12MB)"

bubuko.com,布布扣

You can download the lastest version of this file from thisJava website,
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html

bubuko.com,布布扣

Remember to accept the Oracle Binary Code License Agreement for Java SE.

Untar the Java JDK distribution file. pi@raspberrypi ~ $ tar xvzf ~/jdk-7u21-linux-arm-sfp.tar.gz
Create a java directory and move the untarred distribution to it.
Delete the tar file once we are done.
pi@raspberrypi ~ $ sudo mkdir -p -v /opt/java
pi@raspberrypi ~ $ sudo mv -v ~/jdk1.7.0_21 /opt/java/
pi@raspberrypi ~ $ rm ~/jdk-7u21-linux-arm-sfp.tar.gz
Create the environment paths to the java and javac commands so that they can be used anywhere in the command line environment. pi@raspberrypi ~ $ sudo update-alternatives --install "/usr/bin/java" "java" "/opt/java/jdk1.7.0_21/bin/java" 1
pi@raspberrypi ~ $ sudo update-alternatives --set java /opt/java/jdk1.7.0_21/bin/java

pi@raspberrypi ~ $ sudo update-alternatives --install "/usr/bin/javac" "javac" "/opt/java/jdk1.7.0_21/bin/javac" 1

pi@raspberrypi ~ $ sudo update-alternatives --set javac /opt/java/jdk1.7.0_21/bin/javac

Check that the Java environment variable is setup correctly.

Note: If the following error is encountered when the command "java -version" is executed. 
java: error while load­ing shared libraries: libjli.so: can­not open shared object file: No such file or directory

It is propably that you have installed the incorrect version of Debian Linux. At this point in time, Java SDK for Linux ARM has yet to support.

Please refer to the previous section, for the installtion of the correct Debian Linux version for use with Java SDK Linux ARM

pi@raspberrypi ~ $ java -version
java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) Client VM (build 23.21-b01, mixed mode)
Installing PI4J, a bridge project between the native libraries and Java for full access to the Raspberry Pi‘s peripheral.

Check out PI4J website for more information.
pi@raspberrypi ~ $ wget http://pi4j.googlecode.com/files/pi4j-0.0.5.deb
pi@raspberrypi ~ $ sudo dpkg -i pi4j-0.0.5.deb

Check if PI4J is installed correctly.
Go to PI4J directory.
Compile the example "WiringPiGpioExample.java".
Run the compile java program "WiringPiGpioExample".

I am able to see my rows of LED lighting up in a wave sequence, up and down non-stop.

pi@raspberrypi ~ $ cd /opt/pi4j/examples/
pi@raspberrypi /opt/pi4j/examples $ sudo javac -classpath .:classes:/opt/pi4j/lib/‘*‘ -d . WiringPiGpioExample.java
pi@raspberrypi /opt/pi4j/examples $ sudo java -classpath .:classes:/opt/pi4j/lib/‘*‘WiringPiGpioExample

To uninstall PI4J, check out the following command. pi@raspberrypi ~ $ sudo dpkg -r pi4j

Testing out with a simple Java program.
Let us do a hello world example.

Key in "nano hello.java".
This will open a text editor for us to key in the java source code for our hello world example.

Key in the following java source code.

Press ‘Ctrl+X‘ to exit, then ‘Y‘ to save, then press ‘Enter‘.

pi@raspberrypi ~ $ nano hello.java

class hello
{
   public static void main(String args[])
   {
      System.out.println("Hello World!");
   }
}

 

Compile the java source code "hello.java", a java compiled file "hello.class" will be generated.

 

pi@raspberrypi ~ $ javac hello.java

To run the program, key in "java hello".

You should be able to see the printed text "Hello World!" after execution.

pi@raspberrypi ~ $ java hello
Hello World!

Looking back to the wiringPi, which is the library for java to access to the native hardware I/O on the Raspberry Pi.

Taking a look at the java code using pi4j wiringPi.

WiringPiGpioExample.java

 

import com.pi4j.wiringpi.Gpio;
import com.pi4j.wiringpi.GpioUtil;

public class WiringPiGpioExample {
    
    // Simple sequencer data
    // Triplets of LED, On/Off and delay

    private static final int data[] = { 
            0111110002111003112004113005114,
            00611500711601701,
            00,
            1// Extra delay
            // Back again
            71161170051160041150031140021,
            1300111200011101001,
            001// Extra delay
            999// End marker
    };

    public static void main(String args[]) throws InterruptedException {
        int pin;
        int dataPtr;
        int l, s, d;
        
        System.out.println("<--Pi4J--> GPIO test program");

        // setup wiringPi
        if (Gpio.wiringPiSetup() == -1) {
            System.out.println(" ==>> GPIO SETUP FAILED");
            return;
        }

        // set GPIO 4 as the input trigger 
        GpioUtil.export(7, GpioUtil.DIRECTION_IN);
        GpioUtil.setEdgeDetection(7, GpioUtil.EDGE_BOTH);
        Gpio.pinMode (7, Gpio.INPUT) ;  
        Gpio.pullUpDnControl(7, Gpio.PUD_DOWN);        

        // set all other GPIO as outputs
        for (pin = 0; pin < 7; ++pin) {
            // export all the GPIO pins that we will be using
            GpioUtil.export(pin, GpioUtil.DIRECTION_OUT);            
            Gpio.pinMode(pin, Gpio.OUTPUT);
        }
        
        dataPtr = 0;
        for (;;) {
            l = data[dataPtr++]; // LED
            s = data[dataPtr++]; // State
            d = data[dataPtr++]; // Duration (10ths)

            if ((l + s + d) == 27) {
                dataPtr = 0;
                continue;
            }

            Gpio.digitalWrite(l, s);
            
            if (Gpio.digitalRead(7) == 1// Pressed as our switch shorts to ground
                Gpio.delay(d * 10); // Faster!
            else
                Gpio.delay(d * 100);
        }
    }
}
Compile the "WiringPiGpioExample.java" with the pi4j lib files pi@raspberrypi ~ $  javac -classpath .:classes:/opt/pi4j/lib/‘*‘ -d . WiringPiGpioExample.java

Run the java program.

You may notice "wiringPiSetup: Unable to open /dev/mem". This means that you do not have access to the hardware.

 

 

Run the java program with the "sudo" in front as follows.

You should see the LED light running from left to right. 

pi@raspberrypi ~ $ java -classpath .:classes:/opt/pi4j/lib/‘*‘ WiringPiGpioExample

<--Pi4J--> GPIO test program
wiringPiSetup: Unable to open /dev/mem: Permission denied
==>> GPIO SETUP FAILED

pi@raspberrypi ~ $ sudo java -classpath .:classes:/opt/pi4j/lib/‘*‘ WiringPiGpioExample

<--Pi4J--> GPIO test program

   

Serial Java Programming with pi4j on Raspberry Pi

SerialExample.java

import java.util.Date;

import com.pi4j.io.serial.Serial;
import com.pi4j.io.serial.SerialDataEvent;
import com.pi4j.io.serial.SerialDataListener;
import com.pi4j.io.serial.SerialFactory;
import com.pi4j.io.serial.SerialPortException;

/**
* This example code demonstrates how to perform serial communications using the Raspberry Pi.
*
@author Robert Savage
*/
public class SerialExample {
    
    public static void main(String args[]) throws InterruptedException {
        
        // !! ATTENTION !!
        // By default, the serial port is configured as a console port
        // for interacting with the Linux OS shell. If you want to use
        // the serial port in a software program, you must disable the
        // OS from using this port. Please see this blog article by
        // Clayton Smith for step-by-step instructions on how to disable
        // the OS console for this port:
        // http://www.irrational.net/2012/04/19/using-the-raspberry-pis-serial-port/
                
        System.out.println("<--Pi4J--> Serial Communication Example ... started.");
        System.out.println(" ... connect using settings: 38400, N, 8, 1.");
        System.out.println(" ... data received on serial port should be displayed below.");
        
        // create an instance of the serial communications class
        final Serial serial = SerialFactory.createInstance();

        // create and register the serial data listener
        serial.addListener(new SerialDataListener() {
            @Override
            public void dataReceived(SerialDataEvent event) {
                // print out the data received to the console
                System.out.print(event.getData());
            }
        });
                
        try {
            // open the default serial port provided on the GPIO header
            serial.open(Serial.DEFAULT_COM_PORT, 38400);
            
            // continuous loop to keep the program running until the user terminates the program
            for (;;) {
                try {
                    // write a formatted string to the serial transmit buffer
                    serial.write("CURRENT TIME: %s"new Date().toString());
    
                    // write a individual bytes to the serial transmit buffer
                    serial.write((byte13);
                    serial.write((byte10);
    
                    // write a simple string to the serial transmit buffer
                    serial.write("Second Line");
    
                    // write a individual characters to the serial transmit buffer
                    serial.write(‘\r‘);
                    serial.write(‘\n‘);
    
                    // write a string terminating with CR+LF to the serial transmit buffer
                    serial.writeln("Third Line");
                }
                catch(IllegalStateException ex){
                    ex.printStackTrace();
                }
                
                // wait 1 second before continuing
                Thread.sleep(1000);
            }
            
        }
        catch(SerialPortException ex) {
            System.out.println(" ==>> SERIAL SETUP FAILED : " + ex.getMessage());
            return;
        }
    }
}
Compile the "SerialExample.java" pi@raspberrypi ~ $ javac -classpath .:classes:/opt/pi4j/lib/‘*‘ -d . SerialExample.java

Run the "SerialExample.java"

If you encounter error when opening the serial port, do check out the eariler posting to ensure that the serial port is properly configured.

 

pi@raspberrypi ~ $ java -classpath .:classes:/opt/pi4j/lib/‘*‘ SerialExample
If you short the TX (GPIO_14, Pin08) & RX (GPIO_15, Pin10)pin on the Raspberry Pi, you should be able to see the following timestamp messages.
Raspberry Pi transmit the timestamp message for each second.

If the RX pin received data from other serial devices, the data can be seen on the console as well.

CURRENT TIME: Mon Nov 04 12:23:23 SGT 2013
Second Line
Third Line
CURRENT TIME: Mon Nov 04 12:23:24 SGT 2013
Second Line
Third Line
CURRENT TIME: Mon Nov 04 12:23:25 SGT 2013
Second Line
Third Line

   
SPI Java Programming with pi4j on Raspberry Pi  
   

Java examples (taken from www.pi4j.com)

WiringPiGpioExample.java
ControlGpioExample.java
ListenGpioExample.java
ShutdownGpioExample.java
TriggerGpioExample.java
SerialExample.java
SystemInfoExample.java

 
   

Linux bash script for launching/starting Java program. The command to launch Java is similar to those in WinOs, except for some notation changes. Note the use of char ‘:‘ as the seperator and the slash ‘/‘ for its file path. WinOS uses ‘;‘ and the backslash ‘\‘. 
The script is similar to the batch file used in WinOS.

The following is an example of the script,
"run.sh"

Key in ". run.sh" to run the script in Linux command prompt.
Note: remember to make this file "run.sh" executable. (see examples in this website.)

inside file "run.sh"
#!/bin/bash
echo "Running SmartHomeSensors Java Program..."
java -classpath .:bin:lib/log4j-1.2.14.jar:lib/commons-logging-1.1.jar:classes:/opt/pi4j/lib/‘*‘:lib/json-simple-1.1.1.jar:lib/org.apache.httpcomponents.httpclient_4.3.1.jar:lib/utilities.jar:resource com.picControl.smartHomeSensors.MyMain

pi@raspberrypi ~ $ . run.sh

To auto run the script which launch the java program upon Raspberry Pi boot up (startup), edit the file "rc.local".

Add in the following to the file,

cd /home/pi/smartHomeSensor
echo "Run script for SmartHomeSensor Java program"
SCRIPT="/home/pi/smartHomeSensor/run.sh"
echo "run script \"-> $SCRIPT\""
sudo $SCRIPT &

 

The add command set the current directory to the project folder. During the boot process, it cannot be assume that you are in the user directory. Reference to the root directory to be safe.

Use sudo to run the script, and make the script run in the background.

pi@raspberrypi ~ $ sudo nano /etc/rc.local


#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
   printf "My IP address is %s\n" "$_IP"
fi

cd /home/pi/smartHomeSensor
echo "Run script for SmartHomeSensor Java program"
ensor Java program"
SCRIPT="/home/pi/smartHomeSensor/run.sh"
echo "run script \"-> $SCRIPT\""
sudo $SCRIPT &

exit 0

save and reboot Raspberry Pi. After the Raspberry Pi reboot, you should be able to see the text "Run script for SmartHomeSensor Java program" printed before the user prompt or login. There should be no error message.

pi@raspberrypi ~ $ sudo nano /etc/rc.local

 

Login to check if the java process is running.
command "ps ax" print out the list of processes (thread) currently running in Raspberry Pi. "| grep java" pipe the output result and print out only those result that have the word "java" in it.

The result shows that the java program is running with PID 2242 (process ID). Remember this number, for you may need to use it to kill the process.

 

pi@raspberrypi ~ $ ps ax | grep java
2242 ? Sl 0:44 java -classpath .:bin:lib/log4j-1.2.14.jar:lib/commons-logging-1.1.jar:classes:/opt/pi4j/lib/*:lib/json-simple-1.1.1.jar:lib/org.apache.httpcomponents.httpclient_4.3.1.jar:lib/utilities.jar:resource com.picControl.smartHomeSensors.MyMain
2461 pts/0 S+ 0:00 grep --color=auto java

 

Now grep "run.sh". Notice the PID 2241.

This is generated before the Java program is launch. Remember this PID no. You may need this number to kill the same java program.

pi@raspberrypi ~ $ ps ax | grep run.sh

2233 ? S 0:00 sudo /home/pi/smartHomeSensor/run.sh
2241 ? S 0:00 /bin/bash /home/pi/smartHomeSensor/run.sh
2481 pts/0 S+ 0:00 grep --color=auto run.sh

To kill the process.
Check the process currently running.
The previous process that appear is no longer running.

pi@raspberrypi ~ $ sudo kill -9 2242
pi@raspberrypi ~ $ ps ax | grep run.sh
2487 pts/0 S+ 0:00 grep --color=auto run.sh 
pi@raspberrypi ~ $ ps ax | grep java
2489 pts/0 S+ 0:00 grep --color=auto java

 

List of frequently used commands 
A list of frequently used Linux command (using Bash Shell)

Commands Illustration

List directory pi@raspberrypi ~ $ ls
Desktop ocr_pi.png python_games
or
pi@raspberrypi ~ $ ls -all
Change directory pi@raspberrypi ~ $ cd Desktop
Returning down one directory level. pi@raspberrypi ~/Desktop $ cd ..

Access to /sys directory which is hidden.
Containing system peripherals directory/information, for example GPIO, I2C, tty (UART, teletype).
http://www.linusakesson.net/programming/tty/index.php

pi@raspberrypi ~ $ /sys
pi@raspberrypi /sys $ 
Return to user‘s root directory (~). pi@raspberrypi /sys $ cd ~
Rename a file from abc.txt to xyz.txt pi@raspberrypi /sys $ mv abc.txt xyz.txt
Delete or Remove a file pi@raspberrypi /sys $ rm abc.txt
Find or search a file name in the sub-directory, where ‘*‘ is a wildcard. pi@raspberrypi /sys $ sudo find / -name *findText*
   
Press up down arrow keys to scroll through the previously executed commad list.  
Press tab to auto complete the command, file name, directory name or list all possibility. Press up down to select related name.  
Shortcut key to open terminal console <Ctrl+Alt+‘T‘>  
Create new directory. pi@raspberrypi ~ $ mk DIRECTORY_NAME
Remove file. pi@raspberrypi ~ $ rm FILENAME
Launch GUI, or Linux‘s GUI pi@raspberrypi ~ $ startx
Stop Linux operating system pi@raspberrypi ~ $ sudo exit
or
pi@raspberrypi ~ $ sudo halt
or
pi@raspberrypi
 ~ $ sudo shutdown -h now
Reboot Linux operating system pi@raspberrypi ~ $ sudo reboot
or
pi@raspberrypi ~ $ sudo shutdown -r now

To get help or further details for any linux command, use the "man" command. 
Help manual for any command or program, where ???? is the command/program name.

pi@raspberrypi ~ $ man ???? 
Pipe following terminal output text to this grep filter before display on the terminal console. Only the lines containing the text will be printed out. "XXXX" will be the command that generate the printed text on the terminal console, while "TEXT_FILTER" is the text to be filtered. The operator ‘|‘ pipes the console output from "XXXX" to the grep program. pi@raspberrypi ~ $ XXXX | grep TEXT_FILTER
Direct the terminal output text, saving to this file.txt pi@raspberrypi ~ $ XXXX > file.txt
To enable root privilege. Any command entered will be treated with root privilege as long as the terminal remains open. pi@raspberrypi ~ $ sudo su
Allow root privilege only for the command "XXXX" pi@raspberrypi ~ $ sudo XXXX

Display the content of the file "XXXX".
Example to display Raspberry Pi hardware revision, key in "cat /proc/cpuinfo"

Example to display Linux OS information, key in "cat /etc/lsb-release"

pi@raspberrypi ~ $ cat XXXX
pi@raspberrypi ~ $ cat /proc/cpuinfoProcessor : ARMv6-compatible processor rev 7 (v6l)
BogoMIPS : 697.95
Features : swp half thumb fastmult vfp edsp java tls
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xb76
CPU revision : 7

Hardware : BCM2708
Revision : 000e
Serial : 000000005fdceeaf

Execute program in the background (execute program in a seperated thread), while allowing the current terminal for other more commands. This is done by appending the ‘&‘ behind a program execution command, which is denoted as "XXXX". pi@raspberrypi ~ $ XXXX&

Command "PS" List the program or threads running in the background of the Linux operating system (for the current user session only).
Where PID is the process ID number.

Command "ps" is a useful troubleshooting tools. Other related command is "top".

Other useful troubleshooting commands are,
- "strace", "ltrace"
- "mtrace"

 

pi@raspberrypi ~ $ ps
PID TTY TIME CMD
2803 pts/1 00:00:02 bash
2948 pts/1 00:00:00 ps

 

 

 

 

 

To list all the process running in the Raspberry Pi device, use command "PS AX".
You can see the process created by other user session and you can kill it as well.

 

These are the bash session started by various user session 0, 1, 2, etc... ,

3477 pts/0 T 0:00 -bash
347? pts/1 T 0:00 -bash
347? pts/2 T 0:00 -bash

 

This is a bash session started for the main hardware,

2121 tty1 S+ 0:01 -bash

 

 

 

To list only the PID for a particular program, you can use with grep.

pi@raspberrypi ~ $ ps ax 
PID TTY STAT TIME COMMAND
1 ? Ss 0:01 init [2]
2 ? S 0:00 [kthreadd]
3 ? S 0:00 [ksoftirqd/0]
5 ? S< 0:00 [kworker/0:0H]
6 ? S 0:01 [kworker/u:0]
7 ? S< 0:00 [kworker/u:0H]
8 ? S< 0:00 [khelper]
9 ? S 0:00 [kdevtmpfs]
10 ? S< 0:00 [netns]
12 ? S 0:00 [bdi-default]
13 ? S< 0:00 [kblockd]
14 ? S 0:00 [khubd]
15 ? S< 0:00 [rpciod]
16 ? S 0:00 [khungtaskd]
17 ? S 0:00 [kswapd0]
18 ? S 0:00 [fsnotify_mark]
19 ? S< 0:00 [nfsiod]
20 ? S< 0:00 [crypto]
27 ? S< 0:00 [kthrotld]
28 ? S< 0:00 [VCHIQ-0]
29 ? S< 0:00 [VCHIQr-0]
30 ? S< 0:00 [VCHIQs-0]
31 ? S< 0:00 [iscsi_eh]
32 ? S< 0:00 [dwc_otg]
33 ? S< 0:00 [DWC Notificatio]
35 ? S< 0:00 [deferwq]
36 ? S 0:00 [kworker/u:2]
37 ? S 0:08 [mmcqd/0]
38 ? S 0:00 [jbd2/mmcblk0p6-]
39 ? S< 0:00 [ext4-dio-unwrit]
154 ? Ss 0:00 udevd --daemon
1503 ? S 0:01 /usr/sbin/ifplugd -i lo -q -f -u0 -d10 -w -I
1592 ? S 0:07 /usr/sbin/ifplugd -i eth0 -q -f -u0 -d10 -w -I
1778 ? Sl 0:00 /usr/sbin/rsyslogd -c5
1863 ? Ss 0:00 /usr/sbin/cron
1888 ? Ss 0:00 dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhcli
1918 ? Ss 0:00 /usr/bin/dbus-daemon --system
1964 ? Ss 0:02 /usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 102:104
2003 ? Ss 0:00 /usr/sbin/thd --daemon --triggers /etc/triggerhappy/triggers.d
2008 ? Ss 0:00 /usr/sbin/sshd
2037 tty1 Ss 0:00 /bin/login -f tty1
2038 tty2 Ss+ 0:00 /sbin/getty 38400 tty2
2039 tty3 Ss+ 0:00 /sbin/getty 38400 tty3
2040 tty4 Ss+ 0:00 /sbin/getty 38400 tty4
2041 tty5 Ss+ 0:00 /sbin/getty 38400 tty5
2042 tty6 Ss+ 0:00 /sbin/getty 38400 tty6
2044 ? Sl 0:01 /usr/sbin/console-kit-daemon --no-daemon
2111 ? Sl 0:00 /usr/lib/policykit-1/polkitd --no-debug
2121 tty1 S+ 0:01 -bash
2151 ? S 0:00 [kworker/0:0]
2249 ? Ss 0:00 sshd: pi [priv]
2256 ? S 0:00 sshd: pi@notty
2257 ? Ss 0:00 /usr/lib/openssh/sftp-server
2258 ? Ss 0:00 /usr/lib/openssh/sftp-server
2662 ? S 0:00 [flush-179:0]
2663 ? Ss 0:00 sshd: pi [priv]
2667 ? Ss 0:00 sshd: pi [priv]
2674 ? S 0:01 sshd: pi@pts/0
2678 ? S 0:00 sshd: pi@notty
2679 ? Ss 0:00 /usr/lib/openssh/sftp-server
2684 pts/0 Ss 0:03 -bash
3127 ? S 0:00 udevd --daemon
3130 ? S 0:00 udevd --daemon
3338 ? S 0:00 [kworker/0:1]
3393 ? Ss 0:00 sshd: pi [priv]
3397 ? Ss 0:00 sshd: pi [priv]
3404 ? S 0:00 sshd: pi@pts/1
3408 ? S 0:00 sshd: pi@notty
3409 ? Ss 0:00 /usr/lib/openssh/sftp-server
3416 pts/1 Ss+ 0:01 -bash
3469 ? S 0:00 [kworker/0:2]
3476 pts/0 R+ 0:00 ps ax

3477 pts/0 T 0:00 -bash
3478 pts/0 Tl 0:03 java -classpath .:bin:lib/log4j-1.2.14.jar:lib/commons-logging

pi@raspberrypi ~ $ ps ax | grep java
3478 pts/0 Tl 0:03 java -classpath .:bin:lib/log4j-1.2.14.jar:lib/commons-logging

To terminate the program running in the background thread, use the kill command. Where "####" is the process ID (PID)

Putting an option -9 will force the process to be killed.

The process PID can be kill from another user session, even if the PID is not listed in its session.

pi@raspberrypi ~ $ kill ####

or

pi@raspberrypi ~ $ kill -9 ####

Check physical disk information. pi@raspberrypi ~ $ sudo fdisk -l
Check physical disk mount information pi@raspberrypi ~ $ sudo df -h
Measure Raspberry Pi temperature pi@raspberrypi ~ $ vcgencmd measure_temp
temp=58.4‘C
 
Running a simple echo bash script on the command line terminal. pi@raspberrypi ~ $ echo "Hello World!!!"
Hello World!!!
The script can be save onto a file and be run just like a batch file under Microsoft Windows OS. Save the following echo bash script onto a file name "bash_script.sh".

You can actually name the file whatever you like, but it is good to keep the *.sh file extension as under some GUI Linux OS, double clicking the file will automatic launch the correct application which runs the file.
#!/bin/bash
echo "Hello World!!!"
Run the file "bash_script.sh". pi@raspberrypi ~ $ bash bash_script.sh
Hello World!!!

To run the "bash_script.sh" without the command bash, set the file as executable and run the file. 

Note: You may encounter with the following 
./test.sh: /bin/bash^M: bad interpreter: No such file or directory
.

There is a ‘^M‘ char detected at the end of the first line. Ensure that the script is not written on a Microsoft Window OS. Window‘s environment will append ‘^M‘ for enter key.

Use vi editor to view the file.
Type in command "vi bash_script.sh".
You will see the ‘^M‘ char in blue.
Delete those char. 

Press ‘:w‘ save the text file.

Press ‘:q‘ to exit the vi program.

Try again, it should work fine now.

pi@raspberrypi ~ $ source bash_script.sh
Hello World!!!
or
pi@raspberrypi ~ $ . bash_script.sh
Hello World!!!

or
pi@raspberrypi ~ $ sudo chmod u+x bash_script.sh
pi@raspberrypi
 ~ $ ./bash_script.sh
Hello World!!!

To check the permission for the files in the current directory use "ls -l".

To check permission for a particular file, type out the file name behind "ls -l filname"

File permissiondrwxrwxrwx 2 pi pi

    d - represent the name as a directory.
    - - Regular file or program.
    l - file/dir is a symbolic link.
    s - setuid/setgid permissions. 
    t - sticky bit permissions.
    b - driver for storage medium.
    c - driver for communication hardware.


rwx - ‘r‘ refers to the read permission
      ‘w‘ refers to the write permission
      ‘x‘ refers to the permission to execute

1st "rwx" -> owner (‘u‘) 
2nd "rwx" -> group (‘g‘) 
3rd "rwx" -> all users (‘o‘ or ‘a‘) 
2 - referes to the number of hardlinks to the file.
pi pi -> Owner:Group

To change the file permission, use the following command,

"chmod a+x filename"
This will add all (‘a‘) with executable (‘x‘) permission.

"chmod a-x filename"
This will remove all (‘a‘) with executable (‘x‘) permission.
You can also set file permission using binary references (set to _rwxr-----),
command "chmod 740 filename"
To change file‘s owner and group,
command "chown newuser:newgroup filename" 

 

pi@raspberrypi ~ $ ls -l
drwxr-xr-x 2 pi pi 4096 May 30 04:07 Desktop
-rw-r--r-- 1 pi pi 5781 Feb  3  2013 ocr_pi.png
drwxrwxr-x 2 pi pi 4096 Mar 10 18:20 python_games

pi@raspberrypi ~ $ ls -l Desktop 
drwxr-xr-x 2 pi pi 4096 May 30 04:07 Desktop

pi@raspberrypi ~ $ chmod a+x ocr_pi.png
pi@raspberrypi ~ $ ls -l
drwxr-xr-x 2 pi pi 4096 May 30 04:07 Desktop
-rwxr-xr-x 1 pi pi 5781 Feb  3  2013 ocr_pi.png
drwxrwxr-x 2 pi pi 4096 Mar 10 18:20 python_games

pi@raspberrypi ~ $ chmod a-x ocr_pi.png
pi@raspberrypi ~ $ ls -l
drwxr-xr-x 2 pi pi 4096 May 30 04:07 Desktop
-rw-r--r-- 1 pi pi 5781 Feb  3  2013 ocr_pi.png
drwxrwxr-x 2 pi pi 4096 Mar 10 18:20 python_games

Auto Login (login without being prompt for password). Edit the file /etc/inittab.

Comment away the following line by inserting a ‘#‘ in front of the statement.
"#1:2345:respawn:/sbin/getty 115200 tty1"
and insert the following line below it.
"1:2345:respawn:/bin/login -f pi tty1 </dev/tty1 >/dev/tty1 2>&1"

Reboot the system and you should be able to power up and go striaght into the command prompt without being prompt for user ID and password. 

pi@raspberrypi ~ $ sudo nano /etc/inittab

#1:2345:respawn:/sbin/getty 38400 tty1
1:2345:respawn:/bin/login -f pi tty1 </dev/tty1 >/dev/tty1 2>&1

Run a script after login (user specific),
by adding the following line to the end of the file /etc/profile (similar to /home/pi/.bashrc) 
". /home/pi/script1.sh"

"script1.sh" will run after the user has been sucessfully login. Local or remote user will get to auto execute "script1.sh" after login.

NOTE!!!
Please ensure to set the file as executable and run the file.

#! /bin/sh
echo "--- script<1> --------------"
Run a script after the very end of the boot process (before any login), by adding the following line to the end of the file /etc/rc.local
"/home/pi/script3.sh"
 

Run a script after the booting process (or within the booting process), but before the login (using service method).

1) Create a script "script2.sh" in the folder /etc/init.d/script2.sh.
"sudo nano /etc/init.d/script2.sh"

2) Make the script executable.
"sudo chmod 755 /etc/init.d/script2.sh" 

3) Test the script (service start).
"sudo /etc/init.d/script2.sh start" 

4) Test the script (service stop).
"sudo /etc/init.d/script2.sh stop" 

5) Register the script to be run at start-up (with default priorities).
"sudo update-rc.d script2.sh defaults"

update-rc.d is a program which mananged the start-up and shutdown using the file /etc/rcX.d (where rcX.d means rc0.d to rc6.d, rcS.d)
You can key in the following command to view the link to your script. 
"ls -l /etc/rc?.d/"

6) To remove the script from start-up,
"sudo update-rc.d -f script2.sh remove"
‘-f‘ is to force the removal of the symlinks even if the script is still under the /etc/init.d folder. Remember to delete away your script away from the folder /etc/init.d 
Note: The command above will only disable the service until the next time the service is upgraded. To enable the service will not be re-enabled upon upgrade, type the following command, "update-rc.d script2.sh stop 80 0 1 2 3 4 5 6"

7) You can also register the services with custom priorities. (you can visit this website)

#! /bin/sh
# /etc/init.d/script2.sh
### BEGIN INIT INFO
# Provides: --- 
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Simple script to start a program at boot
# Description: A simple script which will start / stop a program a boot / shutdown.
### END INIT INFO
# If you want a command to always run, put it here# Carry out specific functions when asked to by the system
case "$1" in
  start)
    echo "--- script<2> start ---------"
    # run application you want to start
    # /usr/local/bin/noip2
    ;;
  stop)
    echo "--- script<2> stop ---------"
    # kill application you want to stop
    # killall noip2
    ;;
  *)
    echo "Usage: /etc/init.d/noip {start|stop}"
    exit 1
    ;;
esac

exit 0

After testing with various start-up scripts process, I have summarizes the sequence in which the scripts are call up.

--- Booting process --------
    before user login

- Script registered with update-rc.d
- /etc/rc.local

--- User login prompt-------
    after user login

- /etc/profile
- /home/pi/.bashrc

--- End of start-up process -----
    command prompt 

 

Custom Splash screen
"apt-get install fbi"

Name your image file to "splash.png" and copy to the directory /etc

****encounter problem copying file to /etc directory.***
I
f the error above is encountered, copy the image file to the user directory instead. Then use "sudo mv" (move file command) to move it to the etc directory.

Edit a new text file "sudo nano".
Cut and paste the followings,

#! /bin/sh
### BEGIN INIT INFO
# Provides: asplashscreen
# Required-Start:
# Required-Stop:
# Should-Start:
# Default-Start: S
# Default-Stop:
# Short-Description: Show custom splashscreen
# Description: Show custom splashscreen
### END INIT INFO
do_start () {
/usr/bin/fbi -T 1 -noverbose -a /etc/splash.png
exit 0
}
case "$1" in
start|"")
do_start
;;
restart|reload|force-reload)
echo "Error: argument ‘$1‘ not supported" >&2
exit 3
;;
stop)
# No-op
;;
status)
exit 0
;;
*)
echo "Usage: asplashscreen [start|stop]" >&2
exit 3
;;
esac

:

save the file as /etc/init.d/asplashscreen

make the script executable and install it for init mode:

"sudo chmod a+x /etc/init.d/asplashscreen"

"sudo insserv /etc/init.d/asplashscreen"

Reboot

"sudo reboot "

 

The custom logo is displayed near the end of the booting process, not at the beginning.

This is followed by a blank screen.
Press <Ctrl + Alt + F2> to return to the command prompt. 

pi@raspberrypi ~ $ sudo apt-get install fbi

pi@raspberrypi ~ $ sudo mv splash.png /etc

pi@raspberrypi ~ $ sudo nano

cut and paste, save file as

/etc/init.d/asplashscreen

pi@raspberrypi ~ $ sudo chmod a+x /etc/init.d/asplashscreen

pi@raspberrypi ~ $ sudo insserv /etc/init.d/asplashscreen

pi@raspberrypi ~ $ sudo reboot

 

Place your favourite wall paper on the desktop.
-> Login GUI Desktop
-> On the desktop, press right click , and -> Select "Desktop Preferences".

-> Select your favourite wallpaper.

 
Hide boot up text, kernel loading modules (slient pi boot)  
- List process task, thread

enable sound
sudo modprobe snd_bcm2835
disable sound
rmmod snd_bcm2835

Root access

Some users believe that the root account has a password that they are not aware of. This is not the case. For security reasons, Raspbmc has been hardened by disabling the root account. There is no need to enable the root account in Raspbmc, and doing so increases the likelihood of you causing damage to the system. Instead, the following options are recommended:

  • Prefixing the command requiring root privileges with sudowill allow you to run the command as root.
  • Alternatively, you can temporarily have root privileges with the command sudo -s

If you truly wish to enable root access so that you can login as root. You can do so as follows:sudo passwd rootYou have now set a root password you can login with.To disable the root account again:

sudo passwd -l root

To change Raspberry Pi password. pi@raspberrypi ~ $ passwd
Changing password for pi.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

Changing Raspberry Pi user name ("newUserName") and password ("abc1234").

Follow the following procedure,

 
Add a new user with new password.

pi@raspberrypi ~ $ sudo adduser newUserName

Adding user `newUserName‘ ...
Adding new group `
newUserName‘ (1004) ...
Adding new user `
newUserName‘ (1001) with group `newUserName‘ ...
Creating home directory `/home/
newUserName‘ ...
Copying files from `/etc/skel‘ ...
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for 
newUserName
Enter the new value, or press ENTER for the default
     Full Name []:
     Room Number []:
     Work Phone []:
     Home Phone []:
     Other []:
Is the information correct? [Y/n] y
 

Give the new user sudo privileges, by editing the sudoers file.
Copy the line with the default user name pi and copy below it. Change the name pi to your newUserName.

After you have finished, key in Ctrl+‘x‘ then ‘Y‘, followed by enter key.

pi@raspberrypi ~ $ sudo visudo

pi ALL=(ALL) NOPASSWD: ALL
newUserName ALL=(ALL) NOPASSWD: ALL

Testing the newUserName if it is working properly with sudo privileges.

pi@raspberrypi ~ $ logout

pi@raspberrypi ~ $ login

Enter your newUserName and passsword.

 

Try to see if you can edit the sudoers file. The file can only be edited if it has sudo access privileges.

Delete the line containing the "pi" user, if it is no longer required.
After you have finished, key in Ctrl+‘x‘ then ‘Y‘, followed by enter key.

newUserName@raspberrypi ~ $ sudo visudo

Delete the old user "pi" account,
or add in option flag "-remove-home" to remove the "/home/pi" directory as well.

The process of changing the Raspberry Pi user name and password is completed.
Reboot the Raspberry Pi for the new user name to take effect. Old user name can no longer be in use.

(method do not work so well. still able login using pi as the user name.)

newUserName@raspberrypi ~ $ sudo deluser pi 
newUserName@raspberrypi ~ $ sudo deluser -remove-home pi
Disable screen saver, or disable auto blank screen.

newUserName@raspberrypi ~ $ sudo nano /etc/kbd/config

BLANK_TIME=0
BLANK_DPMS=off
POWERDOWN_TIME=0

   
   
   

Advance command
- "lsusb" List all the USB peripherals
- "df /" check disk space
- "free" check memory RAM 

 
Directory Structure of 
Raspberry Pi running 
Soft-float Debian “wheezy”

I have created an overview directory maps of my Raspberry Pi directory map to assist me in understanding the files modification that I will be dealing with.

Learning how things are being organised in a Linux platform.
/~--/bin    Essential commands that all user 
  |
  |-/boot   Information that boots the machine, including Kernel. 
  |  |-boot.rc
  |
  |-/dev    Device driver for all the hardware peripherals. 
  |  |-/block
  |  |-/bus
  |  |-/char
  |  |-/disk
  |  |-/input
  |  |-/mapper
  |  |-/net
  |  |-/pts
  |  |-/raw
  |  |-/snd
  |-/etc    Configuration files for your system.
  |  |-/alternatives
  |  |-/apm
  |  |-/apparmor.d
  |  |-/apt
  |  |-/avahi
  |  |-/bash_completion.d
  |  |-/ca-certificates
  |  |-/calendar
  |  |-/console-setup
  |  |-/ConsoleKit
  |  |-/cron.d
  |  |-/cron.daily
  |  |-/cron.hourly

  |  |-/cron.monthly
  |  |-/cron.weekly
  |  |-/dbus-1
  |  |-/default
  |  |-/dhcp
  |  |-/dhcp3
  |  |-/dictionaries-common
  |  |-/dillo
  |  |-/dpkg
  |  |-/emacs
  |  |-/fonts
  |  |-/fstab.d
  |  |-/gconf
  |  |-/gdb
  |  |-/ghostscript
  |  |-/groff
  |  |-/gtk-2.0
  |  |-/gtk-3.0
  |  |-/ifplugd
  |  |-/init
  |  |-/init.d         save and register scripts in this directory to auto run when bootup or shutdown 
  |  |-/insserv
  |  |-/insserv.conf.d
  |  |-/iproute2
  |  |-/kbd
  |  |-/ld.so.conf.d
  |  |-/ldap
  |  |-/libnl-3
  |  |-/libpaper.d
  |  |-/lightdm
  |  |-/logcheck
  |  |-/logrotate.d
  |  |-/menu
  |  |-/menu-methods
  |  |-/modprobe.d
  |  |-/network
  |  |-/opt
  |  |-/pam.d
  |  |-/perl
  |  |-/pm
  |  |-/polkit-1
  |  |-/profile.d
  |  |-/pulse
  |  |-/python
  |  |-/python2.7
  |  |-/python3
  |  |-/python3.2
  |  |-/rc0.d
  |  |-/rc1.d
  |  |-/rc2.d
  |  |-/rc3.d
  |  |-/rc4.d
  |  |-/rc5.d
  |  |-/rc6.d
  |  |-/rcS.d
  |  |-/request-key.d
  |  |-/rsyslog.d
  |  |-/samba
  |  |-/security
  |  |-/selinux
  |  |-/sgml
  |  |-/skel
  |  |-/ssh
  |  |-/ssl
  |  |-/sudoers.d
  |  |-/sysctl.d
  |  |-/systemd
  |  |-/terminfo
  |  |-/triggerhappy
  |  |-/udev
  |  |-/ufw
  |  |-/vim
  |  |-/wpa_supplicant
  |  |-/X11
  |  |-/xdg
  |  |-/xml
  |  |-/xpdf
  |  |-inittab   controls the startup/initialization process (example: auto login)
  |  |-profile
  |  |-rc.local

  |
  |-/home   Home directory for each of the user 
  |  |~/pi  (User named pi)
  |     |-/Desktop
  |     |-/python_games
  |     |-.bashrc        script trigger everytime a specific user logs in 
  |
  |-/lib    Library or code, Kernel or other programs use. 
  |  |-/arm-linux-gnueabi
  |  |-/firmware
  |  |-/init
  |  |-/lsb
  |  |-/modprobe.d
  |  |-/modules
  |  |-/systemd
  |  |-/terminfo
  |  |-/udev
  |  |-/xtables
  |
  |-/lost+found
  |
  |-/media  Temp media (disk, CD-ROM)
  |
  |-/mnt    Temp media (disk, CD-ROM, network drive)
  |
  |-/opt    Location for installing new software package.
  |  |-/java
  |  |-/pi4j
  |  |-/vc
  |
  |-/proc
  |
  |-/root   Super user‘s home directory 
  |
  |-/run
  |  |-/ConsoleKit
  |  |-/dbus
  |  |-/lock
  |  |-/mount
  |  |-/network
  |  |-/sendsigs.omit.d
  |  |-/shm
  |  |-/sshd
  |  |-/udev
  |
  |-/sbin   Commands for system adminstrator. 
  |
  |-/selinux
  |
  |-/srv    Data for system‘s services (programs running in the background)
  |
  |-/sys
  |  |-/block
  |  |-/bus
  |  |-/class
  |  |-/dev
  |  |-/devices
  |  |-/firmware
  |  |-/fs
  |  |-/kernel
  |  |-/module
  |  |-/power
  |
  |-/tmp    for storing temp files 
  |
  |-/usr    A complex hierarchy of additional programs and files 
  |  |-/bin
  |  |-/games
  |  |-/include
  |  |-/lib
  |  |-/local
  |  |-/sbin
  |  |-/share
  |  |-/src
  |
  |-/var    The data that changes frequently. (log files, emails) 
  |  |-/backups
  |  |-/cache
  |  |-/lib
  |  |-/local
  |  |-/log
  |  |-/mail
  |  |-/opt
  |  |-/spool
  |  |-/tmp


Linux Files and Directory Structure Reference
bubuko.com,布布扣

 

/~--/bin    Essential commands that all user 
  |
  |-/boot   Information that boots the machine, including Kernel. 
  |
  |-/dev    Device driver for all the hardware peripherals. 
  |  |-/cd-rom
  |  |-/fd0
  |  |-/fd1
  |  |-/hda
  |  |-/hda1
  |  |-/hda2
  |  |-/hdb
  |  |-/hdb1
  |  |-/hdb2
  |  |-/sda
  |  |-/sda1
  |
  |-/etc    Configuration files for your system. 
  |
  |-/home   Home directory for each of the user 
  |  |~/pi  (User named pi)
  |     |-/Desktop
  |
  |-/lib    Library or code, Kernel or other programs use. 
  |
  |-/media  Temp media (disk, CD-ROM)
  |
  |-/mnt    Temp media (disk, CD-ROM, network drive)
  |
  |-/opt    Location for installing new software package.
  |
  |-/root   Super user‘s home directory 
  |
  |-/sbin   Commands for system adminstrator. 
  |
  |-/srv    Data for system‘s services (programs running in the background)
  |
  |-/tmp    for storing temp files 
  |
  |-/usr    A complex hierarchy of additional programs and files 
  |  |-/X11R6
  |  |-/bin
  |  |-/games
  |  |-/include
  |  |-/lib
  |  |-/local
  |  |-/sbin
  |  |-/share
  |  |-/src
  |
  |-/var    The data that changes frequently. (log files, emails) 

-/??? -> Directory related to the Linux operating system that needs careful attention in handling.

Linux Command Reference
linux_quickref.pdf

linuxcard.pdf

 
 
 

 

 

Add Wifi to Raspberry Pi 
Add a Wifi to tap the internet access from your Wifi wireless network.

WiFi dongle keyword
- Edimax EW-7811Un 

- Dynamode WL-700N-RXS

Commands Illustration

In order to connect to the Wifi, the first thing you will need is a Wifi dongle for your Raspberry Pi. The following contains the list of Wifi adaptors available that can work with Raspberry Pi.

http://elinux.org/RPi_USB_Wi-Fi_Adapters

In this example, D-Link DWA-123, H/W Ver.: B1, P/N IWA123EU.....B1G

 
Edit and Setup the network interface configuration pi@raspberrypi ~ $ sudo nano /etc/network/interfaces

Original setup look like the following,
------------------------------------------------------
auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp 

 

If you have a DHCP server, change to the following 
------------------------------------------------------
auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
auto wlan0
iface wlan0 inet manualdhcp
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

 
If you are using a static IP, change to the following 
------------------------------------------------------
auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
address 192.168.0.100
netmask 255.255.255.0
gateway 192.168.0.1

wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
 
Setup the WPA configuration, the following block to the file. Change the text in blue to your router settings. pi@raspberrypi ~ $ sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
network={
ssid="SSID-GOES-HERE"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=CCMP TKIP
psk="WIFI-PASSWORD-GOES-HERE"
}
 
Reboot and unplug the ethernet cable. The Wifi should be taking over the network connection after the reboot. pi@raspberrypi ~ $ sudo reboot
Reference:
http://www.correderajorge.es/wifi-under-raspberry-pi-with-archlinux/
 

 

 



Reference book- Embedded Linux Primer (2nd Edition), A Practical, Real-World Approach, by Christopher Hallinan (indepth details of Linux OS operations) To explore list
- start up script, shutdown script
- Play Audio, Display images, Video - C I/O, UART, SPI programming



Keyword: Raspberry Pi, electronic hardware setup, UART, I2C, SPI, Digital I/O port, Python Programming, C Programming.

 

RASPBERRY PI 外设学习资源,布布扣,bubuko.com

RASPBERRY PI 外设学习资源

标签:des   style   blog   http   java   color   

原文地址:http://www.cnblogs.com/rfnets/p/3817588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!