RASPBERRY PI 外设学习资源

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

Raspberry Pi 

       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:      

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.

http://www.raspberrypi.org/


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.


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_cardsYou may also like to check out the various peripherals that are compatiable to Raspberry Pi.
http://elinux.org/RPi_VerifiedPeripherals



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.

 

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


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.

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


"raspi-config" menu

 
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, select <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


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

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.

 

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.

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/


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.


raspberrypi login: pi
Password: raspberry

[email protected] ~ $

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

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

[email protected]:~# 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" [email protected]:~# 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" [email protected]:~# 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...
To switch off my LED, send a text "0" to the operating file system "/sys/class/gpio/gpio17/value" [email protected]:~# 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. [email protected]:~# echo "18" > /sys/class/gpio/export
Setup port 18 as an input port. [email protected]:~# echo "in" > /sys/class/gpio/gpio18/direction
Reading input port 18. [email protected]:~# cat /sys/class/gpio/gpio18/value
Command prompt will return the following value (logic 0) after reading the port. 0
[email protected]:~#
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. [email protected]:~# cat /sys/class/gpio/gpio18/value
Command prompt will return the following value (logic 1) after reading the port, which is correct. 1
[email protected]:~#

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: NoneThis 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 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.
[email protected]:~$


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. -> [email protected] ~ $ 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

[email protected] ~ $ 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. [email protected] ~ $ 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. [email protected] ~ $ 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.

[email protected] ~ $ 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.


[email protected] ~ $ sudo minicom -b 9600 -o -D /dev/ttyAMA0

-------------------------------------------
Welcome to minicom 2.6.1OPTIONS: I18n
Compiled on Apr 28 2012, 19:24:31.
Port /dev/ttyAMA0Press 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

[email protected] ~ $ 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.


[email protected] ~ $ 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-bcm27088

Reboot Raspberry Pi [email protected] ~ $ 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


[email protected] ~ $ ls /dev/spidev*
/dev/spidev0.0 /dev/spidev0.1
[email protected] ~ $


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.


[email protected] ~ $ gcc spidev_test.c -o spidev_test 
[email protected] ~ $ 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
[email protected] ~ $


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.

[email protected] ~ $ 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
[email protected] ~ $

   

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.


[email protected] ~ $ 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-bcm27088


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.


[email protected] ~ $ 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. [email protected] ~ $ 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.

[email protected] ~ $ sudo adduser pi i2c
Adding user `pi‘ to group `i2c‘ ...
Adding user pi to group i2c
Done.
Reboot Raspberry Pi [email protected] ~ $ 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.


[email protected] ~ $ ls /dev/i2c*
/dev/i2c-0 /dev/i2c-1
[email protected] ~ $


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.

[email protected] ~ $ 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.
[email protected] ~ $ 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: -- -- -- -- -- -- -- --

5. Networking on Raspberry Pi References:
Installing Samba program
Checking the IP setting on my Raspberry Pi. [email protected] 
Ping gateway 192.168.1.1 [email protected] 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 [email protected] ~ $ 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.

[email protected] ~ $ 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. [email protected] ~ $ sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.old
Edit the samba configuration file using the nano text editor [email protected] ~ $ 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. [email protected] ~ $ 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"


[email protected] ~ $ hostname -I
192.168.1.99

[email protected] ~ $  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" [email protected] ~ $ 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
 [email protected] ~ $ 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.

 [email protected] ~ $ 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. [email protected] ~ $ 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.


[email protected] ~ $ 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.


[email protected] ~ $ sudo nano /etc/hostname

[email protected] ~ $ sudo nano /etc/hosts

[email protected] ~ $ sudo reboot

[email protected] ~ $


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

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.
[email protected]‘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
[email protected] ~ $


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. [email protected] ~ $ lxsession&
The Raspberry Pi‘s desktop will be launched from your Window operating system, as follows...
GUI application can also be launched directly within WinOS without accessing to the Raspberry Pi Linux desktop.
[email protected] ~ $ leadpad&

Using MobaXterm, you can actually drag and drop file in the lower left corner of the MobaXterm‘s windows.
Key in "exit", then press enter, to terminate the session. [email protected] ~ $ 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.
[email protected] ~ $ 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 [email protected] ~ $ mkdir tutorial
Get into the newly create tutorial folder [email protected] ~ $ cd tutorial
Create a "main.c" file using the program nano (text editor) [email protected] ~ $ 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" [email protected] ~ $ 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. [email protected] ~ $ ./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.
[email protected] ~ $ 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.

[email protected] ~ $ 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

[email protected] ~ $ mkdir python_tutorial
Get into the newly create tutorial folder [email protected] ~ $ cd python_tutorial
Create a "hello.py" file using the program nano (text editor) [email protected] ~ $ 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. [email protected] ~ $ python hello.py
Alternative, you can make the file executable, and execute the file directly. [email protected] ~ $ chmod a+x hello.py
[email protected] ~ $ ./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.


[email protected] ~ $ wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.1.0.tar.gz
[email protected] ~ $ tar zxf RPi.GPIO-0.1.0.tar.gz
[email protected]errypi ~ $ cd RPi.GPIO-0.1.0
[email protected] ~ $ 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.


[email protected] ~ $ 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)"

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


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

Untar the Java JDK distribution file. [email protected] ~ $ 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.
[email protected] ~ $ sudo mkdir -p -v /opt/java
[email protected] ~ $ sudo mv -v ~/jdk1.7.0_21 /opt/java/
[email protected] ~ $ 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. [email protected] ~ $ sudo update-alternatives --install "/usr/bin/java" "java" "/opt/java/jdk1.7.0_21/bin/java" 1
[email protected] ~ $ sudo update-alternatives --set java /opt/java/jdk1.7.0_21/bin/java
[email protected] ~ $ sudo update-alternatives --install "/usr/bin/javac" "javac" "/opt/java/jdk1.7.0_21/bin/javac" 1
[email protected] ~ $ 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.

[email protected] ~ $ 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.

[email protected] ~ $ wget http://pi4j.googlecode.com/files/pi4j-0.0.5.deb
[email protected] ~ $ 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.


[email protected] ~ $ cd /opt/pi4j/examples/
[email protected] /opt/pi4j/examples $ sudo javac -classpath .:classes:/opt/pi4j/lib/‘*‘ -d . WiringPiGpioExample.java
[email protected] /opt/pi4j/examples $ sudo java -classpath .:classes:/opt/pi4j/lib/‘*‘WiringPiGpioExample

To uninstall PI4J, check out the following command. [email protected] ~ $ 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‘.


[email protected] ~ $ 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.


[email protected] ~ $ javac hello.java


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

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


[email protected] ~ $ 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[] = { 
            0, 1, 1, 1, 1, 1, 0, 0, 0, 2, 1, 1, 1, 0, 0, 3, 1, 1, 2, 0, 0, 4, 1, 1, 3, 0, 0, 5, 1, 1, 4,
            0, 0, 6, 1, 1, 5, 0, 0, 7, 1, 1, 6, 0, 1, 7, 0, 1,
            0, 0,
            1, // Extra delay
            // Back again
            7, 1, 1, 6, 1, 1, 7, 0, 0, 5, 1, 1, 6, 0, 0, 4, 1, 1, 5, 0, 0, 3, 1, 1, 4, 0, 0, 2, 1,
            1, 3, 0, 0, 1, 1, 1, 2, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1,
            0, 0, 1, // Extra delay
            9, 9, 9, // 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 [email protected] ~ $  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.


[email protected] ~ $ java -classpath .:classes:/opt/pi4j/lib/‘*‘ WiringPiGpioExample

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

[email protected] ~ $ 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((byte) 13);
                    serial.write((byte) 10);
    
                    // 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" [email protected] ~ $ 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.

[email protected] ~ $ 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

[email protected] ~ $ . 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.

[email protected] ~ $ 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.
[email protected] ~ $ 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.


[email protected] ~ $ 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.


[email protected] ~ $ 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.

[email protected] ~ $ sudo kill -9 2242
[email protected] ~ $ ps ax | grep run.sh
2487 pts/0 S+ 0:00 grep --color=auto run.sh 
[email protected] ~ $ 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 [email protected] ~ $ ls
Desktop ocr_pi.png python_games
or
[email protected] ~ $ ls -all
Change directory [email protected] ~ $ cd Desktop
Returning down one directory level. [email protected] ~/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

[email protected] ~ $ /sys
[email protected] /sys $ 
Return to user‘s root directory (~). [email protected] /sys $ cd ~
Rename a file from abc.txt to xyz.txt [email protected] /sys $ mv abc.txt xyz.txt
Delete or Remove a file [email protected] /sys $ rm abc.txt
Find or search a file name in the sub-directory, where ‘*‘ is a wildcard. [email protected] /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. [email protected] ~ $ mk DIRECTORY_NAME
Remove file. [email protected] ~ $ rm FILENAME
Launch GUI, or Linux‘s GUI [email protected] ~ $ startx
Stop Linux operating system [email protected] ~ $ sudo exit
or
[email protected] ~ $ sudo halt
or
[email protected] ~ $ sudo shutdown -h now
Reboot Linux operating system [email protected] ~ $ sudo reboot
or
[email protected] ~ $ 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.

[email protected] ~ $ 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. [email protected] ~ $ XXXX | grep TEXT_FILTER
Direct the terminal output text, saving to this file.txt [email protected] ~ $ XXXX > file.txt
To enable root privilege. Any command entered will be treated with root privilege as long as the terminal remains open. [email protected] ~ $ sudo su
Allow root privilege only for the command "XXXX" [email protected] ~ $ 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"

[email protected] ~ $ cat XXXX
[email protected] ~ $ 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". [email protected] ~ $ 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"


[email protected] ~ $ 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.


[email protected] ~ $ 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: [email protected]
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: [email protected]/0
2678 ? S 0:00 sshd: [email protected]
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: [email protected]/1
3408 ? S 0:00 sshd: [email protected]
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

[email protected] ~ $ 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.


[email protected] ~ $ kill ####

or

[email protected] ~ $ kill -9 ####

Check physical disk information. [email protected] ~ $ sudo fdisk -l
Check physical disk mount information [email protected] ~ $ sudo df -h
Measure Raspberry Pi temperature [email protected] ~ $ vcgencmd measure_temp
temp=58.4‘C
 
Running a simple echo bash script on the command line terminal. [email protected] ~ $ 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". [email protected] ~ $ 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.

[email protected] ~ $ source bash_script.sh
Hello World!!!
or
[email protected] ~ $ . bash_script.sh
Hello World!!!

or
[email protected] ~ $ sudo chmod u+x bash_script.sh
[email protected] ~ $ ./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"


[email protected] ~ $ 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

[email protected] ~ $ ls -l Desktop 
drwxr-xr-x 2 pi pi 4096 May 30 04:07 Desktop

[email protected] ~ $ chmod a+x ocr_pi.png
[email protected] ~ $ 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

[email protected] ~ $ chmod a-x ocr_pi.png
[email protected] ~ $ 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.


[email protected] ~ $ 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.***
If 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.


[email protected] ~ $ sudo apt-get install fbi

[email protected] ~ $ sudo mv splash.png /etc

[email protected] ~ $ sudo nano

cut and paste, save file as

/etc/init.d/asplashscreen

[email protected] ~ $ sudo chmod a+x /etc/init.d/asplashscreen

[email protected] ~ $ sudo insserv /etc/init.d/asplashscreen

[email protected] ~ $ 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. [email protected] ~ $ 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.
[email protected] ~ $ 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.


[email protected] ~ $ sudo visudo

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

Testing the newUserName if it is working properly with sudo privileges.
[email protected] ~ $ logout

[email protected] ~ $ 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

/~--/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 [email protected] ~ $ 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. [email protected] ~ $ 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. [email protected] ~ $ 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 外设学习资源

时间: 2024-07-29 17:09:14

RASPBERRY PI 外设学习资源的相关文章

树莓派(raspberry pi)学习11: 将树莓派变成一个Web服务器(转)

将树莓派变成一个Web服务器,通过访问网页,就可以控制树莓派,比如:查看摄像头\开灯等等. 一想到Linux Web服务器,我们首先想到的是,Apache + MySql + Php. 树莓派可以安装这个LAMP系列,但Apache 和 MySql对于树莓派这个小小的机器,太重了,主要是消耗内存多\速度慢\占用磁盘大(约200M吧) 所以要安装一个轻量级的Web服务器. 经试用,推荐组合为:  nginx + php + sqlite nginx 是个轻量级的Web服务器,比Apache不差 s

Raspberry Pi 学习笔记之一

记录几个搭建服务器教程: [教程] 将树莓派变成网络打印机服务器(更新PC和手机端设置)!http://www.eeboard.com/bbs/thread-8818-1-1.html[心得] [分享]用树莓派构建你自己的微型服务器,可以外网访问http://www.eeboard.com/bbs/thread-5526-1-1.html配置树莓派(Raspberry Pi)成为一台完美的家用服务器 http://www.eeboard.com/bbs/thread-20798-1-1.html

树莓派(raspberry pi)学习4: 更改键盘布局(转)

树莓派(raspberry pi)用了几次后,发现键盘老是按错,一些字符打不出来或打错 这个问题,折腾我半天.还是把心得分享一下吧 上网查,发现是键盘布局不对,树莓派(raspberry pi)是英国产品,默认键盘布局是英国(GB),我们用的键盘布局一般是美国(US)的 更改键盘布局,命令如下: sudo dpkg-reconfigure keyboard-configuration 进入后,选通用的101键PC键盘 按tab键,到OK,按Enter确定 在键盘layout选择中,选Other

如何在Raspberry Pi 3B中安装Windows 10 IoT Core

Windows 10 IoT Core简介 Windows 10 IoT是微软专门为物联网生态打造的操作系统,Windows 10 IoT Core则是Windows 10 IoT 操作系统的核心版本,功能相对精简.使用Windows 10 IoT可以打造属于自己的物联网生态系统. Windows 10 IoT的版本介绍 Windows 10 IoT 企业版 Windows 10 IoT 企业版将 Windows 10 企业版功能广泛应用于零售.制造.医疗.金融和其他行业的设备上.Windows

树莓派raspberry pi配置

(1)国际化语言 树莓派初装系统之后,首次启动会出现“raspi-config”工具,如下图:(若不是初次启动,在命令模式下,请输入 sudo raspi-config 命令,即可调出此界面.若在图形桌面下,打开桌面的 LXT 客户端,输入 sudo raspi-config 命令也可以调出这个工具.   1.如上图,通过键盘上下键,将蓝条,移动到第 4 步“Internationalisation Options”,回车进入,会出现下图:   2.如上图,“Change Locale“,就是汉

Raspberry Pi B+ 定时向物联网yeelink上传CPU GPU温度

 Raspberry Pi B+ 定时向物联网yeelink上传CPU GPU温度 硬件平台: Raspberry Pi B+ 软件平台: 1  安装 requests 库 首先我们要先解决requests库,当我们向YEELINK POST 消息的时候会用到  : r = requests.post(apiurl, headers=apiheaders, data=json.dumps(payload)) 安装easy_install: <span style="line-heigh

我的第一个Raspberry PI装置

好吧,我先承认是这是从书上学习的第一个示例. 我入手的是Raspberry红版,版本2,看到这么小巧的卡片电脑可以做这么多事情,真是让人惊喜! 安装系统等都很顺利,启动.安装程序.远程桌面.SSH登录等都很顺利,就是安装XBMC不行,各种版本都不行,启动起来后操作不一会就挂掉了,不知道是什么原因,电源没有问题,2A的,之后再测试吧.以后我觉得买绿版就可以,没什么区别. 今天试了一下刚入手的各种配件,先晒个小图: 这大概是最简单的Rasp应用了  :-) 面包板上是简单的串联电路,电阻是10K的,

【智能家居】Raspberry Pi 系统安装篇

Raspberry Pi 中国名 树莓派,科普请移步 树莓派-百度百科 ,智能家居这个系列想了很久了,但一直不知道从何落笔,Raspberry Pi 很像 Arduino 但又不是,它出现大大降低进入智能家居领域的门槛, 啰嗦两句: 1.树莓派购买的时候建议买个外壳,安全第一哦!如果动手能力强的可以参考我的这边文章自己做一个,也是So easy ! Raspberry Pi 外壳DIY(图解) 2.树莓派SD卡选购可以购买SD卡或TF卡,为了防止资源浪费可以购买带SD卡转换卡皮的TF卡,将来不玩

Raspberry PI硬件

Raspberry Pi硬件 1.目前树莓派的型号(根据处理器分) 第一代 Model A Model B Model A+ Model B+ ZERO 第二代 Model B 第三代 Model B 还有一个Raspberry Pi Compute Module 第二代是不是叫Raspberry Pi 2B啊 图片 Raspberry Pi 1 Model A+ Raspberry Pi 1 Model B v1.0 正面 Raspberry Pi 1 Model B v1.0 背面 Rasp