0% found this document useful (0 votes)
635 views

Rasp

The document discusses connecting and controlling a 16x2 LCD display directly with a Raspberry Pi. It describes the LCD's pinout including data pins, register select pin, read/write pin, and enable pin. It explains how these pins are used to send commands and data to the LCD in 4-bit mode without reading any data back. Instructions are provided on wiring the LCD to the Raspberry Pi Cobbler board and controlling it from a Python script.

Uploaded by

pensamemucho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
635 views

Rasp

The document discusses connecting and controlling a 16x2 LCD display directly with a Raspberry Pi. It describes the LCD's pinout including data pins, register select pin, read/write pin, and enable pin. It explains how these pins are used to send commands and data to the LCD in 4-bit mode without reading any data back. Instructions are provided on wiring the LCD to the Raspberry Pi Cobbler board and controlling it from a Python script.

Uploaded by

pensamemucho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 493

================================================================================

AZARTICOLO:Raspberry Pi 3 Model B SPECIFICHE


================================================================================

Single-board computer with wireless LAN and Bluetooth connectivity

You’ll need (not included):

Micro SD card with NOOBS


Micro USB power supply (2.1 A)
And to use it as a desktop computer, you’ll need:

TV or monitor and HDMI cable


Keyboard and mouse

For a step-by-step guide to getting your Pi up and running, check out our online
Getting started guide.

The Raspberry Pi 3 Model B is the earliest model of the third-generation Raspberry


Pi.
It replaced the Raspberry Pi 2 Model B in February 2016.
See also the Raspberry Pi 3 Model B+, the latest product in the Raspberry Pi 3
range.

Quad Core 1.2GHz Broadcom BCM2837 64bit CPU


1GB RAM
BCM43438 wireless LAN and Bluetooth Low Energy (BLE) on board
100 Base Ethernet
40-pin extended GPIO
4 USB 2 ports
4 Pole stereo output and composite video port
Full size HDMI
CSI camera port for connecting a Raspberry Pi camera
DSI display port for connecting a Raspberry Pi touchscreen display
Micro SD port for loading your operating system and storing data
Upgraded switched Micro USB power source up to 2.5A

===================================================================================
The Raspberry Pi 3 Model B+ is the latest product in the Raspberry Pi 3 range.
===================================================================================

Broadcom BCM2837B0, Cortex-A53 (ARMv8) 64-bit SoC @ 1.4GHz


1GB LPDDR2 SDRAM
2.4GHz and 5GHz IEEE 802.11.b/g/n/ac wireless LAN, Bluetooth 4.2, BLE
Gigabit Ethernet over USB 2.0 (maximum throughput 300 Mbps)
Extended 40-pin GPIO header
Full-size HDMI
4 USB 2.0 ports
CSI camera port for connecting a Raspberry Pi camera
DSI display port for connecting a Raspberry Pi touchscreen display
4-pole stereo output and composite video port
Micro SD port for loading your operating system and storing data
5V/2.5A DC power input
Power-over-Ethernet (PoE) support (requires separate PoE HAT)

===================================================================================
=========
AZARTICOLO:ROBOT DOMESTICI INDUSTRIES
===================================================================================
=========
DI ARMANDO PALIANI
Via Montauro 33 - 00118 ROMA (RM)
P.I. 12960231004 - C.F. PLNRND74R03G763Q
REA di Roma n. RM1413309
Telefono 06 45548263 - Fax 06 45595204
dal Lunedì al Venerdì
dalle 10:00 alle 18:00
orario continuato

================================================================================
AZARTICOLO:Versione di rasbian
================================================================================

cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"
NAME="Raspbian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=raspbian
ID_LIKE=debian
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"

===================================================================================
========
AZARTICOLO:Raspbian: handling temperature sensor and leds on the Raspberry Pi
===================================================================================
========
http://www.xappsoftware.com/wordpress/?s=raspbian

by gg1 · October 11, 2012

In this short tutorial I m going to show to you how to build a temperature alarm
with the
Raspberry Pi.

Raspbian is a free operating system based on Debian optimized for the Raspberry Pi
hardware.
An operating system is the set of basic programs and utilities that make your
Raspberry Pi run.
However, Raspbian provides more than a pure OS: it comes with over 35,000
packages,
pre-compiled software bundled in a nice format for easy installation on your
Raspberry Pi.

The Raspberry Pi provides a lot of hardware, two items of this HW are very
interesting to
control the status of the system.

The first one is the temperature sensor into the CPU and the other one is the
presence of
two leds.

We can think to use the leds to signal (with a fade in fade out effect) when the
temperature overcomes a threshold.
Raspbian provides the access to these two devices using the sys filesystem.
So they are very simple to control also using the bash.

Temperature sensor
------------------

The temperature sensor is directly accessible through the sys filesystem,


So if you want to monitorize the temperature you can use standard tools from the
bash.

Try issueing the following command:

# watch -d cat /sys/class/thermal/thermal_zone0/temp

you should view an output like the following:

the output will be refreshed every two seconds (see man watch), stop the watch
command hitting CTRL-C

Using the LED


-------------

You can connect many leds to the gpio output of your Raspberry Pi, but you already
have
four leds wired onto the board.

The RED LED is hardwired to the onboard 3V3


the FDX, LNK/10M are hardwired to the USB/Ethernet Chip
the GREEN LED is hardwired to GPIO16

So the first 3 leds cannot be used, while we are going to use the last one.
The green leds is available through the sysfs at
/sys/class/leds/led0

The default trigger for this led is 'mmc0' , so before using this led you have to
deactivate
this trigger. Simply issue the following command (you must be root or you need to
be sudo):

# echo none >/sys/class/leds/led0/trigger

to turn on/off the leds you must write on /sys/class/leds/led0/brightness


0 turn off
1 turn off
try issueing the following commands

# echo 1 >/sys/class/leds/led0/brightness
# echo 0 >/sys/class/leds/led0/brightness

to restore the original functionality issue the following command:


# echo mmc0 > /sys/class/leds/led0/trigger

Mixing the things


-----------------

Now we are going to write a simple shell script which will flash the led when the
teperature
overcomes 40 degrees.
in pseudo code

while (1)
{
temp = currentTemperature
if temp > 40
start flashing led 0
else
stop flashing led 0
sleep 5 seconds
}

and now let s start coding:

#!/bin/bash
fault=0
while [ 1 ] ; do
temp=cat /sys/class/thermal/thermal_zone0/temp
if [ $temp -gt 40000 ]
then
fault=1
echo "Starting flash"
else
if [ $fault -eq 1 ]
then
fault=0
echo "Stopping flash"
fi
fi
sleep 5
done

In the above code I have added the fault variable to avoid the stop of the led
blinking at each
loop (I m going to stop the flashing only if it is yet blinking).

At this point we have only to drive the led. A kernel module, can help us to do
this job,
it is the ledtrig_heartbeat module. we can attach this module to the trigger of the
led.
with the following commands:

# modprobe ledtrig_heartbeat
# echo heartbeat >/sys/class/leds/led0/trigger
and we will stop the blinking with this command:

# echo none >/sys/class/leds/led0/trigger

Here you are the final code:

#!/bin/bash
modprobe ledtrig_heartbeat
fault=0
echo none >/sys/class/leds/led0/trigger
while [ 1 ] ; do
temp=cat /sys/class/thermal/thermal_zone0/temp
echo $temp
if [ $temp -gt 40000 ]
then
if [ $fault -eq 0 ]
then
fault=1
echo "Starting flash"
echo heartbeat >/sys/class/leds/led0/trigger
fi
else
if [ $fault -eq 1 ]
then
fault=0
echo "Stopping flash"
echo none >/sys/class/leds/led0/trigger
fi
fi
sleep 5
done

save this script (I named it "my.sh"), then chmod +x it


# chmod +x my.sh

last, try to run it

root@raspberrypi:/home/pi# ./my.sh
40084
Starting flash
39546
Stopping flash
39546
39007
39546
39007
40084
Starting flash
40084

After you read "Starting flash" you should see the led blinking.
Try to change the temperature, using a lighter or something similar,
Note I m not responsible for any damages you can cause. So be careful.

===================================================================================
=========
AZARTICOLO: Wiring the Cobbler to the LCD by Michael Sklar
===================================================================================
========
https://learn.adafruit.com/drive-a-16x2-lcd-directly-with-a-raspberry-pi/overview

The LCD
raspberry_pi_IMG_5592.jpg
Whenever you come across a LCD that looks like it has 16 connectors it is most
likely using a
HD44780 controller. These devices provide the same pinouts making them relatively
easy to work with.
The LCD uses a parallel interface meaning that we will need many pins from our
raspberry pi to control it.
In this tutorial we will use 4 data pins (4-bit mode) and two control pins.

The data pins are straightforward.


They are sending data to the display (toggled high/low).
We will only be using write mode and not reading any data.
The register select pin has two uses.
When pulled low it can send commands to the LCD (like position to move to, or clear
the screen).
This is referred to as writing to the instruction or command register.
When toggled the other way (1) the register select pin goes into a data mode and
will be used to
send data to the screen.

The read/write pin will be pulled low (write only) as we only want to write to the
LCD based on
this setup.

The enable pin will be toggled to write data to the registers.


LCD Pinout
1 Ground
2 VCC - 5v not 3.3v
3 Contrast adjustment (VO) from potentiometer
4 Register Select (RS). RS=0: Command, RS=1: Data
5 Read/Write (R/W). R/W=0: Write, R/W=1: Read (we won't use this pin)
6 Clock (Enable). Falling edge triggered
7 Bit 0 (Not used in 4-bit operation)
8 Bit 1 (Not used in 4-bit operation)
9 Bit 2 (Not used in 4-bit operation)
10 Bit 3 (Not used in 4-bit operation)
11 Bit 4
12 Bit 5
13 Bit 6
14 Bit 7
15 Backlight LED Anode (+)
16 Backlight LED Cathode (-)

Before wiring, check that your LCD has an LED backlight, not an EL backlight.
LED backlights use 10-40mA of power, EL backlights use 200+ma!
EL backlights are often cheap to get but are not usable, make sure you don't use
one or you will
overload the Pi. Some cheap LCDs that have LED backlights do not include a resistor
on the LCD
module for the backlight, if you're not sure, connect a 1Kohm resistor between pin
15 and 5V
instead of connecting directly. All Adafruit LCDs have LED backlights with built in
resistors so
you do not need an extra resistor!

Wiring Diagram
-------------
raspberry_pi_pi-char-lcd.gif

First, connect the Cobbler power pins to the breadboard power rail. +5.0V from the
Cobbler
goes to the red striped rail (red wire) and GND from the cobbler goes to the blue
striped
rail (black wire)

In order to send data to the LCD we are going to wire it up as follows


Pin #1 of the LCD goes to ground (black wire)
Pin #2 of the LCD goes to +5V (red wire)
Pin #3 (Vo) connects to the middle of the potentiometer (orange wire)
Pin #4 (RS) connects to the Cobbler #25 (yellow wire)
Pin #5 (RW) goes to ground (black wire)
Pin #6 (EN) connects to Cobbler #24 (green wire)
Skip LCD Pins #7, #8, #9 and #10
Pin #11 (D4) connects to cobbler #23 (blue wire)
Pin #12 (D5) connects to Cobbler #17 (violet wire)
Pin #13 (D6) connects to Cobber #21 (gray wire)
Pin #14 (D7) connects to Cobber #22 (white wire)
Pin #15 (LED +) goes to +5V (red wire)
Pin #16 (LED -) goes to ground (black wire)

Then connect up the potentiometer, the left pin connects to ground (black wire) and
the right pin
connects to +5V (red wire)

If you're using a Cobbler Plus with a B+ or Pi 2, the pins will be arranged


somewhat differently.

Here's a sketch of the Cobbler Plus version:


raspberry_pi_pi_lcd_bb.png

Schematic
raspberry_pi_Untitled.png

5v LCD vs 3.3v Pi
---------------

The raspberry Pi GPIOs are designed for 3.3v, but our LCD is a 5v device.
It's fine to use a 5v display, but only if we are sending data out of the Pi.
We are not going to use the 3.3v power rail on the Cobbler, and we will tie the RW
(read/write)
pin of the display to GND as we do not want the display sending a 5v signal into
the Pi.

Don't cross the streams!

Preparing the LCD


---------------

Before you start, make sure you have a strip of 0.1" male header and a 10K
potentiometer.
All Adafruit Character LCDs come with these parts so you should be good to go.

raspberry_pi_parts.jpg

Most LCDs have a strip of 16 pins on the top, if the header is a little longer,
just break it off
until its the right length

raspberry_pi_headersize.jpg

Next you'll need to solder the header to the LCD.


You must do this, it is not OK to just try to "press fit" the LCD!

raspberry_pi_lcdbb.jpg

Start by connecting the 5V and GND wires from the cobbler to the breadboard.
Then connect pins #1, #2 and #15, #16 to the breadboard power rails as shown.
The backlight should come on. If it doesn't, check the wiring!

raspberry_pi_lcdpower.jpg
raspberry_pi_charbacklite.jpg

Next, wire up the contrast potentiometer as shown above, with the middle pin
connecting
to LCD pin #3 and the other two pins going to 5V and ground.

Twist the potentiometer until you see the first line of the LCD fill with boxes.
If you don't see the boxes, check your wiring!

raspberry_pi_charboxes.jpg

Finish the wiring for the RS, RW, EN, D4, D5, D6, and D7 pins as shown in the
diagram up top
raspberry_pi_lcdwire.jpg

That's it! Now you're ready to run the Python script to draw text on the screen!

Necessary Packages by Michael Sklar


-------------------------------

This guide is based on Debian's "Wheezy" release for Raspberry Pi.


It was made available in Mid July 2012. The following items must be installed in
order to utilize
the Raspberry Pi's GPIO pins.

Add the latest dev packages for Python (2.x):

apt-get install python-dev

raspberry_pi_cosm-python-dev.gif

Upgrade distribute (required for RPi.GPIO 0.3.1a) - [No image for this one]

apt-get install python-setuptools


easy_install -U distribute

apt-get install python-pip


raspberry_pi_cosm-python-pip.gif

Install rpi.gpio (0.3.1a) or later:

pip install rpi.gpio


raspberry_pi_cosm-rpi-gpio.gif

Python Script by Michael Sklar

NOTE: This page describes an older version of the Raspberry Pi character LCD Python
code.
You can find a newer library that works on more platforms like the Raspberry Pi and
by checking out the new character LCD Python library guide.
For new projects it's recommended to use the new library!

The Code
--------

The Python code for Adafruit's Character LCDs on the Pi is available on Github at
https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code

There are two files we will be working with:


Adafruit_CharLCD.py - contains python class for LCD control
Adafruit_CharLCD_IPclock_example.py - code for IP address and date/time calls
methods from
Adafruit_CharLCD.py

The first file, Adafruit_CharLCD.py is a mashup from two different sources of LCD
code.
Github user lrvick put together a nice python class.
His work is the baseline that is slowly being changed as we are bringing in more
elements from
the Arduino LiquidCrystal library.

The easiest way to get the code onto your Pi is to hook up an Ethernet cable, and
clone it directly
using 'git', which is installed by default on most distros.
Simply run the following commands from an appropriate location (ex. /home/pi):

Copy Code
apt-get install git
git clone git://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git
cd Adafruit-Raspberry-Pi-Python-Code
cd Adafruit_CharLCD
Testing
You can test the wiring from the previous step by simply running the
Adafruit_CharLCD.py
Python code, as it has a little code it in that will simply display a test message
when wired correctly
You can use vi Adafruit_CharLCD.py to edit.
Copy Code
chmod +x Adafruit_CharLCD.py
./Adafruit_CharLCD.py

IP Clock Example
This script assumes you ll want to display the Ethernet (eth0) IP address.
You may want to replace eth0 with wlan0 or wlan1 (etc) for Wireless IP address!
Copy Code
#!/usr/bin/python

from Adafruit_CharLCD import Adafruit_CharLCD


from subprocess import *
from time import sleep, strftime
from datetime import datetime

lcd = Adafruit_CharLCD()

cmd = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1"

lcd.begin(16,1)

def run_cmd(cmd):
p = Popen(cmd, shell=True, stdout=PIPE)
output = p.communicate()[0]
return output

while 1:
lcd.clear()
ipaddr = run_cmd(cmd)
lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n'))
lcd.message('IP %s' % ( ipaddr ) )
sleep(2)
Running the Code
Start the IP + Clock example
Copy Code
$ ./Adafruit_CharLCD_IPclock_example.py
What You Should See
raspberry_pi_timeip.jpg

===================================================================================
==
AZARTICOLO: Wiring Pi: GPIO Interface library for the Raspberry Pi
===================================================================================
==

http://wiringpi.com/

About

WiringPi is a GPIO access library written in C for the BCM2835 used in the
Raspberry Pi.
It’s released under the GNU LGPLv3 license and is usable from C and C++ and many
other languages
with suitable wrappers (See below)
It’s designed to be familiar to people who have used the Arduino “wiring” system1
Arduino is really two things; one is a hardware platform, the other software, and
part of the
software is a package called Wiring.
Wiring is the core of the input and output for the Arduino, so I thought it would
be good to
replicate that functionality (or a good usable subset with Raspberry Pi extensions)
on the Raspberry Pi.

The original Raspberry Pi Model A and B version B1 was a $35 single board computer
with a 26-pin
General Purpose Input/Output (GPIO) connector and this carries a set of signals and
buses.

There are 8 general purpose digital I/O pins – these can be programmed as either
digital outputs
or inputs. One of these pins can be designated for hardware PWM output too.

Additionally there is a 2-wire I2C interface and a 4-wire SPI interface


(with a 2nd select line, making it 5 pins in total) and the serial UART with a
further 2 pins.

Over the years there have been some updates:

The model B, Revision 1.1 Raspberry Pi has an additional 4 GPIO lines on a separate
connector
which you have to solder onto the board.

The model A+ and B+ Raspberry Pi’s represents 2 years of research, development and
testing and
now features a single 40-pin GPIO connector with 28 usable GPIO pins and 4 USB
sockets.

The model 2 features a quad-core Arm A7 processor with 1GB of RAM. Same GPIO.

The model 3 features a quad-core Arm A8 processor (64-bits) with the same RAM and
GPIO as
the model 2, however it also features on-board Wi-Fi and Bluetooth. Still the same
$35 price tag.

The I2C, SPI and UART interfaces can also be used as general purpose I/O pins when
not being
used in their bus modes, giving a grand total of 8 + 2 + 5 + 2 = 17 I/O pins on the
P1 connector
(plus 4 more on the P5 connector on a Revision 2 Pi) and 28 I/O pins on the B+ and
version 2 and 3
boards (Although 2 are reserved for the HAT I2C interface, but can be used as
normal GPIOs
if not using a HAT board)

WiringPi includes a command-line utility gpio which can be used to program and
setup the GPIO pins.
You can use this to read and write the pins and even use it to control them from
shell scripts.

WiringPi is extendable and modules are provided to extend wiringPi to use analog
interface devices
on the Gertboard, and to use the popular MCP23x17/MCP23x08 (I2C 7 SPI) GPIO
expansion chips,
as well as module that will allow blocks of up to 4 74×595 shift registers to be
daisy-chained
together for an additional 32-bits worth of output as a single unit.
(You can have several blocks of 4 74x595s if needed)

One of the extension modules allows you to use an ATmega (e.g. Arduino, or the
Gertboard) as
more GPIO expansion too – via the Pi’s serial port.

Additionally, you can easily write your own expansion modules to integrate your own
peripheral
devices with wiringPi as required.

WiringPi supports analog reading and writing, and while there is no native analog
hardware on a
Pi by default, modules are provided to support the Gertboards analog chips and
other A/D and
D/A devices can be implemented relatively easily.

NOTE:

Download wiringPi here


http://wiringpi.com/download-and-install/

There is a version of wiringPi hosted on Github. Do not use this version of


wiringPi.
It only exists to facilitate building the Ruby and Python wrappers which have been
written
by Gadgetoid.

The wiringPi devLib


--------------------------------

The devLib is a set of library routines implemented using wiringPi to give you easy
access to some
popular peripherals. Devices supported include
character LCD displays (based on the Hitachi HD44780U chips),
and graphical ones – e.g. the common 128×64 pixel displays with the generic 12864H
driver chip.
The DS1302 RTC clock chip, sensors based on the Maxdetect chips (e.g. RHT003) the
Gertboard
and PiFace interface boards and so on.

WiringPi Resources
---------------

Raspberry Pi GPIO Pin numbering http://wiringpi.com/pins/


Download and install http://wiringpi.com/download-and-
install/
Examples and How-To’s
WiringPi function referrence manual/documentation
GPIO Extensions
DevLib
The GPIO Utility
PiFace

WiringPi fully supports the PiFace board too. See this page for more details.

Gertboard

WiringPi fully supports the Gertboard. See this page for more details.

Other wiringPi resources:

Thanks to Gadgetoid there are now wrappers for Ruby, Python and Perl and these can
all be found here.
Thanks to Jeroen Kransen there are wrappers for Java which can be found here.
Thanks to Dave Boulton for creating a TCL wrapper which can be found here.
Pi4J is another Java project that uses WiringPi. It has a Github repository here.
Additional information can be found on the Raspberry Pi Wiki pages.

Download and Install


------------------

WiringPi is maintained under GIT for ease of change tracking, however there is a
Plan B if you’re
unable to use GIT for whatever reasons (usually your firewall will be blocking you,
so do check that first!)
If you do not have GIT installed, then under any of the Debian releases (e.g.
Raspbian), you can install
it with:

apt-get install git-core

If you get any errors here, make sure your Pi is up to date with the latest
versions of Raspbian:

apt-get update
apt-get upgrade

To obtain WiringPi using GIT:

git clone git://git.drogon.net/wiringPi

If you have already used the clone operation for the first time, then
cd wiringPi
git pull origin

Will fetch an updated version then you can re-run the build script below.

To build/install there is a new simplified script:

cd wiringPi
./build

The new build script will compile and install it all for you – it does use the
command at one
point, so you may wish to inspect the script before running it.

Plan B
------

Click on this URL: (it should open in a new page)

https://git.drogon.net/?p=wiringPi;a=summary

Then look for the link marked snapshot at the right-hand side.
You want to click on the top one.
This will download a tar.gz file with a name like wiringPi-98bcb20.tar.gz.
Note that the numbers and letters after wiringPi (98bcb20 in this case) will
probably be different –
they’re a unique identifier for each release.

You then need to do this to install:

tar xfz wiringPi-98bcb20.tar.gz


cd wiringPi-98bcb20
./build

Note that the actual filename will be different – you will have to check the name
and adjust
accordingly.

Test wiringPi’s installation


---------------------

run the gpio command to check the installation:

gpio -v
gpio readall

That should give you some confidence that it’s working OK.

WiringPi is released under the GNU Lesser Public License version 3.

===================================================================================
=========
AZARTICOLO:Wiring Pi GPIO Interface library for the Raspberry Pi Examples/How-To
===================================================================================
=========

Examples/How-To
wiringPi comes with many example programs to perform different tasks.
You’ll find these in the examples directory of the distribution if you downloaded
it from the
git.drogon.net website. Additionally in the examples directory, there are 2 others
– Gertboard,
q2w and Piface with examples for the Gertboard, quick2Wire and Piface interface
boards.

Examples presented here are:

Blink – The simple blink an LED example.


Adafruit RGB LCD Plate
The Quick2Wire system

Esempio di Blink
-------------

Blink is the “Hello World” of the GPIO interfacing world.


It’s the simplest program and circuit that lets you see something happening.

If you have the following saved in a file called blink.c:

#include <wiringPi.h>
int main (void)
{
wiringPiSetup () ;
pinMode (0, OUTPUT) ;
for (;;)
{
digitalWrite (0, HIGH) ; delay (500) ;
digitalWrite (0, LOW) ; delay (500) ;
}
return 0 ;
}

then to compile and run, you would enter:

gcc -Wall -o blink blink.c -lwiringPi


./blink

To see the output of this, you would need to connect a single LED to the GPIO
connector of the
Raspberry Pi as follows:

blink1and if all goes well, you should see the LED flashing once a second.

The LED is any generic LED you may have – typically 5mm diameter and the resistor
is 330Ω.

You can find blink.c and others – blink8.c and blink12.c in the examples directory
of the wiringPi
distribution. To use the makefile to compile them:

make blink
make blink8
make blink12

LCD Library (HD44780U)


-----------------------

The wiringPi LCD devLib allows you to drive most of the popular 1, 2 and 4-line LCD
displays that
are based on the Hitachi HD44780U or compatible controllers.

It allows you to connect multiple displays to a single Raspberry Pi.


The displays can be connected directly to the Pi’s on-board GPIO or via the many
GPIO expander
chips supported by wiringPi – e.g. the MCP23017 I2C GPIO expander
(e.g. as used on some of the Adafruit boards)

displaysTop: standard 16×2 LCD display connected directly to a Raspberry Pi and


(below) an
Adafruit RGB back-lit LCD plate with control buttons.
See this page for more details of the Adafruit display setup using wiringPi

The following Fritzing diagrams describe how to connect the displays directly to
the on-board
GPIO of a Raspberry Pi in both 8 and 4-bit modes:

The library is simple to use in your own programs, however wiring the displays up
may be challenging,
so do take care.

It is possible to wire up more than one display.


In 8-bit mode, the first display needs 10 GPIO pins and each additional display
needs just one
more pin, so with a maximum of 17 GPIO pins, that’s 8 displays.
If you move to using a 4-bit interface (trivial in the code), then it’s 4 more
displays – 12 LCDs!
However I suspect the rest of the wiring might be somewhat challenging…
Wiring is described at the end of the this page.

The LCD display can be either a 5V display or a 3,3v display, however if we are
using a 5V display
then we must make absolutely sure the display can never write data back to the
Raspberry Pi,
otherwise it will present 5V on the Pi’s GPIO pins which will not be good.
At best you’ll destroy the pin drivers, at worst you’ll destroy your Pi.

When using a 5v display, make sure you always connect the R/W pin on the display to
ground to
force the display to be read-only to the host. If not, the display can potentially
present 5v back
to the Pi which is potentially damaging.

Initialisation and Usage


-------------------

To use the LCD library, you’ll need this at the start of your program:

#include <wiringPi.h>
#include <lcd.h>

First, you need to initialise wiringPi in the way you want to.
The LCD library will call pinMode functions as required.

int lcdInit (int rows, int cols, int bits, int rs, int strb,
int d0, int d1, int d2, int d3, int d4, int d5, int d6, int
d7) ;

This is the main initialisation function and must be called before you use any
other LCD functions.

Rows and cols are the rows and columns on the display (e.g. 2, 16 or 4,20).
Bits is the number of bits wide on the interface (4 or 8).

The rs and strb represent the pin numbers of the displays RS pin and Strobe (E)
pin.

The parameters d0 through d7 are the pin numbers of the 8 data pins connected from
the Pi to
the display. Only the first 4 are used if you are running the display in 4-bit
mode.

The return value is the ‘handle’ to be used for all subsequent calls to the lcd
library when dealing
with that LCD, or -1 to indicate a fault. (Usually incorrect parameters)

In the above Fritzing diagrams, the 4-bit one would be initialised by:

fd = lcdInit (2, 16, 4, 11,10 , 0,1,2,3,0,0,0,0) ;

and the 8-bit one by:


fd = lcdInit (2, 16, 8, 11,10 , 0,1,2,3,4,5,6,7) ;

Functions
--------

- lcdHome (int handle)


- lcdClear (int handle)
These home the cursor and clear the screen respectively.

- lcdDisplay (int fd, int state) ;


- lcdCursor (int fd, int state) ;
- lcdCursorBlink (int fd, int state) ;

These turn the display on or off, turn the cursor on or off and the cursor blink
on or off.
The state parameter is True or False.
The initial settings are display on, cursor off and cursor blink off.

- lcdPosition (int handle, int x, int y) ;


Set the position of the cursor for subsequent text entry.
x is the column and 0 is the left-most edge.
y is the line and 0 is the top line.

- lcdCharDef (int handle, int index, unsigned char data [8]) ;


This allows you to re-define one of the 8 user-definable chanracters in the
display.
The data array is 8 bytes which represent the character from the top-line to the
bottom line.
Note that the characters are actually 5×8, so only the lower 5 bits are used.
The index is from 0 to 7 and you can subsequently print the character defined
using the
lcdPutchar() call.
- lcdPutchar (int handle, unsigned char data) ;
- lcdPuts (int handle, const char *string) ;
- lcdPrintf (int handle, const char *message, …) ;
These output a single ASCII character, a string or a formatted string using the
usual printf
formatting commands.

At the moment, there is no clever scrolling of the screen, but long lines will wrap
to the next line,
if necessary.

Do see the example program lcd.c in the examples directory inside the wiringPi
software distribution.

Connecting them up:

Connecting up displays is relatively straight forward.


You pick 4 or 8 GPIO pins for the data bus, then 2 more pins for the control.
The LCDs have 2 control wires labeled RS and E.
the E pin is what we refer to as the strobe pin above.

When using a 5v display, make sure you always connect the R/W pin on the display to
ground to
force the display to be read-only to the host.
If not, the display can potentially present 5v back to the Pi which is potentially
damaging.

You refer to the diagram of the edge connector on the LCD and use that to hook up
the pins
on the GPIO connector. Use the diagram here to help you keep track of the GPIO pins
you are using.

For a 2nd (or 3rd, etc.) display, you wire the displays in parallel, connecting up
all the same pins
with the exception of the E pin. Each display needs its own unique E pin connected
back to a
different GPIO pin.

------------------------
PROGETTO PIR
------------------------

import RPi.GPIO as GPIO


import time
pir=11
led=12
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pir,GPIO.IN)
GPIO.setup(led,GPIO.OUT)
while 1:
if GPIO.input(pir):

GPIO.output (led,GPIO.HIGH)
print "Ti Vedo!"
time.sleep (5)
else:

GPIO.output (led,GPIO.LOW)
print "Non ti vedo"
time.sleep (1)
--------------------------------------------------------------------------------
The GPIO utility
--------------------------------------------------------------------------------

WiringPi comes with a separate program to help manage the on-board GPIO interface
as well as
additional modules such as the PiFace and other devices like the Gertboard as well
as generic
GPIO expander type devices.

This program, called gpio, can also be used in scripts to manipulate the GPIO pins

set outputs and read inputs. It’s even possible to write entire programs just using
the gpio command
in a shell-script, although it’s not terribly efficient doing it that way… Another
way to call it is
using the system() function in C/C++ or it’s equivalent in other programming
languages.

The gpio command is designed to be installed as a setuid program and called by a


normal user
without using the command or logging in as root.

In addition to using the gpio utility to control, read and write the GPIO pins, you
can:

Export/Unexport pins via the /sys/class/gpio interface, where they will then be
available to user
programs (that then do not need to be run as root or with)
Export pins to enable edge-triggered interrupts via the /sys/class/gpio interface.

Load SPI and I2C modules and set /dev/ permissions to enable read/write by the user
running
the gpio program.

Run the i2cdetect program with appropriate flags for your Raspberry Pi board
revision.

Set the SPI buffer size and I2C baud rate (when loading the modules)
Determine your Raspberry Pi board hardware revision.
See the man page for the gpio program to see what all the features are by typing

man gpio
at the command prompt.

Usage

From the Linux command line:

gpio -v
------

This prints the version.


gpio -v
gpio version: 2.32
Copyright (c) 2012-2015 Gordon Henderson
This is free software with ABSOLUTELY NO WARRANTY.
For details type: gpio -warranty
Raspberry Pi Details:
Type: Pi 3, Revision: 02, Memory: 1024MB, Maker: Sony
* Device tree is enabled.
* This Raspberry Pi supports user-level GPIO access.
-> See the man-page for more details
-> ie. export WIRINGPI_GPIOMEM=1

gpio -g …
-----
The optional -g flag causes pin numbers to be interpreted as BCM_GPIO pin numbers
rather
than standard wiringPi pin numbers.

gpio -1 …
------
The optional -1 flag causes pin numbers to be interpreted as hardware pin numbers –
this works for the P1 connector only.

gpio -p …
------
The optional -p flag causes the gpio program to assume there is a PiFace board
fitted to the
Rasberry Pi and subsequent commands are interpreted as pins on the PiFace.
Note: Pins on the PiFace are 200 through 207 for both reading and writing,
with pins 208 through 215 reading the state of the output latch register
(ie. you can read the state of the output pins)

gpio -x …
--------
The optional -x flag causes the gpio program to initialise an additional expansion
module.
Expansion modules are defined with their name (e.g. mcp23s17), and a set of
parameters
separated by colons. The first parameter is always the base pin number for this
expansion module.
See the documentation for each module type to determine the additional parameter
values and
functions.

Standard input and output commands


-------------------------------

gpio mode <pin> in/out/pwm/clock/up/down/tri


---------------------------------------
This sets the mode of a pin to be input, output, pwm or clock mode, and
additionally can set the
internal pull-up/down resistors to pull-up, pull-down or none.

gpio write <pin> 0/1


-----------------
This sets an output pin to high (1) or low (0)

gpio pwm <pin> <value>


-------------------
Set the pin to a PWM value (0-1023 is supported)

gpio read <pin>


-------------
Reads and prints the logic value of the given pin. It will print 0 (low) or 1
(high).

gpio awrite <pin> <value>


---------------------
This performs an analog read from the given pin.
The Pi has no on-board analog hardware so you need to specify an external module
using the -x flag.

gpio aread <pin>


--------------
This read the analog value on the given pin.
The has no on-board analog hardware so you need to specify an external module using
the -x flag.

gpio readall
----------
This reads all the normally accessible pins and prints a table of their numbers
(wiringPi, BCM_GPIO and physical pin numbers), so makes for a handy cross-reference
chart),
along with their modes and current values.
This command will detect the version/model of your Pi and printout the pin diagram
appropriate
to your Pi.

gpio allreadall
-----------
This reads all the pins on your Raspberry Pi.
It’s essentially the same format as used on the Compute Module.

gpio wfi <pin> rising/falling/both


---------------------------
This causes GPIO to perform a non-busy wait on a single GPIO pin until it changes
state to that
indicated.

Kernel module Load Commands


-------------------------
Note that these command will not work if you have enabled the device-tree
interface.
A warning will be printed if-so.

gpio load spi [buffer size in KB]


--------------------------
This loads the SPI kernel modules and optionally sets the internal buffer to the
given size in KB
(multiples of 1024). The default is 4KB and is usually more than enough for most
application
which only exchange a byte or 2 at a time over the SPI bus.

The /dev/spi* entries are set to be owned by the person using the gpio program, so
there is no
need to run subsequent programs as root (unless they use other wiringPi functions)

gpio load i2c [baud rate in Kb/sec]


-----------------------------
This loads the I2C kernel modules and optionally sets the baud rate to the given
speed in Kb/sec
(multiples of 1000). The default is 100Kb/sec.

The /dev/I2c* entries are set to be owned by the person using the gpio program, so
there is no
need to run subsequent programs as root (unless they use other wiringPi functions)

I2C Detection
------------

gpio i2cdetect
------------
This runs the i2cdetect command, but passes in the correct parameters for the I2C
bus for the
Pi’s hardware revision. ie. it runs i2cdetect -y 0 on a Rev. 1 Pi, and i2cdetect -y
1 on a Rev. 2 Pi.
(You can shorten i2cdetect to i2cd)

/sys/class/gpio mode commands

gpio export <pin> in/out


This exports the given pin (BCM-GPIO pin number) as an input or output and makes it
available
for a user program running as the same user to use.

gpio unexport <pin>


-----------------
Removes the export of the given pin.

gpio unexportall
--------------
Removes all /sys/class/gpio exports.

gpio exports
----------
This prints a list of all gpio pins which have been exported via the
/sys/class/gpio interface and
their modes.

gpio edge <pin> rising/falling/both/none


----------------------------------
This enables the given pin for edge interrupt triggering on the rising, falling or
both edges.
(Or none which disables it)

Note: The pin numbers in the sys mode are always BCM-GPIO pin numbers.

Examples
--------

gpio mode 0 out


gpio write 0 1

The above uses the wiringPi pin numbers to set pin 0 as an output and then sets the
pin to a logic 1.

gpio -g mode 17 out


gpio -g write 17 1
This uses the BCM_GPIO pin numbering scheme and performs the same operation as
above.
gpio -1 mode 11 out
gpio -1 write 11 1
This uses the physical P1 pin numbering scheme and performs the same operation as
above.

Internal pull up/down resistors


--------------------------

The GPIO lines have internal pull up or pull-down resistors which can be controlled
via software
when a pin is in input mode. There is no-way to read the status of these resistors.

gpio mode 0 up
gpio mode 0 down
gpio mode 0 tri

These set the resistors to pull-up, pull-down and none respectively on wiringPi pin
0.

================================================================================
AZARTICOLO: INTERFACING A 16 X 2 LCD WITH THE RASPBERRY PI
================================================================================
http://ozzmaker.com/interface-16x2-lcd-with-the-raspberry-pi/?utm_source=feedly

In this post I’ll show how to connect and use a 16 x 2 LCD on a Raspberry Pi.

The LCD I am using is a Blue Character OLED(LCD) 16×2 from adafruit.

This display has ultra-high contrast and any-angle readability. It has the best
display I have seen on any LCD.

This LCD uses the HD44780 controller which is present in almost all LCDs.
LCDs that use this controller usually have 14 or 16 pins. This LCD has 16, numbered
from 0 to 16 as shown below.

OLED.front 823back_LRG
Sometimes these pins are present, but not used. Eg, pins 15 & 16 are for back-light
and they are not used on this LCD. It depends on the manufacture.

HD44780 PINS IN DETAIL

Pin 1 Ground.
Pin 2 Supply Voltage for OLED and logic
Pin 3 Is usually connected to a potentiometer to control the contrast of the
display.
Pin 4 The register select signal (RS) determines whether the Data Bit values are
interpreted as a command (E.g. clear screen) or data (aka: a character to display).
Pin 5 Is the Read/Write pin. In read mode, this pin is used to get feedback from
the LCD to work out if the LCD can accept commands or to indicate it is too busy.

We don’t need this function as we can wait the maximum time for a command to be
written (200us) before sending the next command.
If read is enabled and Pin4 on the LCD is connected to a pin on your Raspberry Pi,
there is a chance that you can destroy your Pi. We only ever want to write to the
LCD, we never want to read from it. So this should always be connected to ground.
Pin 6 The enable pin (E)functions as the command/data latching signal for the LCD.
The LCD will latch in whatever is on the Data Bits and process it on the falling
edge of the E signal
Meaning, when this pin goes low, the LCD will take the input from the data pins at
this time.
Pins 7 to 14 Are the data pins. In 4 pin mode, only pins 11 to 14 are used.
Pins 15 & 16 Are used for the backlight if present.

Wiring the LCD up


-----------------------------

Below shows how to wire up the LCD to the Raspberry Pi. We will be using 4 pin
mode, so there is no need to connect pins 7 to 10. This LCD doesn’t use the
backlight pins, pins 15 and 16. It also doesn’t use the contrast pin, pin 3.

OLED2

Code

In the past, you would have had to know the registers used by the controller to
setup the display, position the cursor or even write a single character. There was
also timing issues to take into consideration. This is no more, with thanks to
WiringPi.

Installing WiringPi;

pi@raspberrypi ~ $ apt-get update


pi@raspberrypi ~ $ git clone git://git.drogon.net/wiringPi
pi@raspberrypi ~ $ cd wiringPi
pi@raspberrypi ~ $ git pull origin
pi@raspberrypi ~ $ ./build
The code below is a very simple example of displaying some text on the top line of
the LCD. There is a complete list of all the functions in the LCD library on the
WiringPi website.

#include <wiringPi.h> //WiringPi headers


#include <lcd.h> //LCD headers from WiringPi
#include <stdio.h> //Needed for the printf function below

//Pin numbers below are the WiringPi pin numbers

#define LCD_RS 3 //Register select pin


#define LCD_E 0 //Enable Pin
#define LCD_D4 6 //Data pin 4
#define LCD_D5 1 //Data pin 5
#define LCD_D6 5 //Data pin 6
#define LCD_D7 4 //Data pin 7

int main()
{
int lcd; //Handle for LCD
wiringPiSetup(); //Initialise WiringPi

//Initialise LCD(int rows, int cols, int bits, int rs, int enable, int d0, int
d1, int d2, int d3, int d4, int d5, int d6, int d7)
if (lcd = lcdInit (2, 16,4, LCD_RS, LCD_E ,LCD_D4 , LCD_D5,
LCD_D6,LCD_D7,0,0,0,0)){
printf ("lcdInit failed! \n");
return -1 ;
}

lcdPosition(lcd,0,0); //Position cursor on the first line in the


first column
lcdPuts(lcd, "Character LCD"); //Print the text on the LCD at the current
cursor postion
getchar(); //Wait for key press
lcdClear(lcd); //Clear the display
}
Lines 1 and 2 are required as these are the headers for the WiringPi LCD library.
Lines 7 to 12 are the definitions for the pins used to connect the LCD to the
Raspberry Pi. Pin numbers can be found here.
Line 21 will initialise the LCD with lcdInit()
PiScreen TFT Raspberry Pi

The augments used in the lcdint() function are;


(int rows, int cols, int bits, int rs, int enable, int d0, int d1, int d2, int d3,
int d4, int d5, int d6, int d7)
rows = Number of rows on the LCD
cols = Number of columns on the LCD
bits = Number of bits or data pins used. Either 8 or 4.
rs = Register select pin
enable = Enable pin
d0-d7 = 8 or 4 bit mode. In for 4 bit mode, only specificity pins from d0 to d3. If
using 8 bit mode, you need to specify pins from d0 to d7. In the example code
above, we are using 4 bit mode.

The code below is what was used in the video at the top of this post
Compile with;

pi@raspberrypi ~ $ gcc -o lcd lcd.c -lwiringPi -lwiringPiDev

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <wiringPi.h>
#include <lcd.h>
#include <string.h>
#include <time.h>

char level0[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000,


0b11111};
char level1[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111,
0b11111};
char level2[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111, 0b11111,
0b11111};
char level3[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b11111, 0b11111, 0b11111,
0b11111};
char level4[8] = { 0b00000, 0b00000, 0b00000, 0b11111, 0b11111, 0b11111, 0b11111,
0b11111};
char level5[8] = { 0b00000, 0b00000, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111,
0b11111};
char level6[8] = { 0b00000, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111,
0b11111};
char level7[8] = { 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111,
0b11111};

#define COLUMNS 16
#define LCD_RS 3
#define LCD_E 0
#define LCD_D4 6
#define LCD_D5 1
#define LCD_D6 5
#define LCD_D7 4

void uptime(void);
void memory(void);
void volume(void);
void scrollText(void);
void INThandler(int sig);
int mymillis(void);

char message[] = "WWW.OZZMAKER.COM";


int count =0;
int j = 0;
FILE *uptime_file, *mem_file;
char *temp;
int lcd;

int main()
{
signal(SIGINT, INThandler);

wiringPiSetup () ;

if (lcd = lcdInit (2, 16,4, LCD_RS, LCD_E ,LCD_D4 , LCD_D5,


LCD_D6,LCD_D7,0,0,0,0)){
printf ("lcdInit failed! \n");
return -1 ;
}

int uptimeTimer;

while(1){
lcdClear (lcd);
volume();
sleep(1);
memory();
sleep(4);
lcdClear (lcd);
uptimeTimer = mymillis();
while ((mymillis() - uptimeTimer) < 5000)
uptime();
sleep(1);
lcdClear (lcd);

scrollText();
}

void uptime(void)
{
unsigned int uptime_unsorted = 0;
unsigned char c;
unsigned int DD;
unsigned int HH;
unsigned int MM;
unsigned int SS;

uptime_file=fopen("/proc/uptime","r");

if(NULL != uptime_file)
{
while((c=fgetc(uptime_file))!= '.')
{
unsigned int i;
i = atoi(&c);
uptime_unsorted = (uptime_unsorted * 10) + i;
}
SS = uptime_unsorted % 60;
MM = uptime_unsorted / 60 % 60;
HH = uptime_unsorted / 60 / 60 % 24;
DD = uptime_unsorted / 60 / 60 / 24;
printf("\x1B[2J");

printf("Uptime:D%i,%02i:%02i:%02i\n",DD,HH,MM,SS);
lcdPosition(lcd,0,0);
lcdPrintf(lcd,"Uptime: Days %i", DD);

lcdPosition(lcd,4,1);
lcdPrintf(lcd,"%02i:%02i:%02i",HH,MM,SS);

}
else
{
printf("Open file \"proc/uptime\" failed!\n");
}
}
void memory(void)
{
char MemTotal[35];
char MemFree[35];
char total[35];
char free[35];
lcdClear (lcd);

mem_file=fopen("/proc/meminfo","r");

if(NULL != mem_file)
{
fscanf(mem_file,"%*s%s%*s", MemTotal);
fscanf(mem_file,"%*s%s%*s", MemFree);
printf("\x1B[2J");

lcdPosition(lcd,0,0);
lcdPrintf(lcd,"MemTotal-%sk",MemTotal);
lcdPosition(lcd,0,1);
lcdPrintf(lcd,"MemFree -%sk",MemFree);
fclose(mem_file);
}
else
{
printf("Open file \"/proc/meminfo\" failed!\n");
}
}
void volume(void)
{
//Defined custom characters for volume display
lcdCharDef (lcd, 0, level0);
lcdCharDef (lcd, 1, level1);
lcdCharDef (lcd, 2, level2);
lcdCharDef (lcd, 3, level3);
lcdCharDef (lcd, 4, level4);
lcdCharDef (lcd, 5, level5);
lcdCharDef (lcd, 6, level6);
lcdCharDef (lcd, 7, level7);

lcdClear (lcd);

int i;
lcdPosition (lcd, 9,1);
lcdPuts (lcd, ":Volume");
for (i = 0; i < 7; i++){
lcdPosition (lcd, i, 1);
lcdPutchar (lcd, i);
usleep(400000);
}
}

void scrollText(void)
{
int i,n;
int h ;
int tempSpace = 0;
char scrollPadding[] = " ";

int messageLength = strlen (scrollPadding)+strlen(message);


for (n=0;n<messageLength;n++){ h = COLUMNS; usleep(300000); printf("\
x1B[2J"); if ( j > messageLength )
j = 0;
for (i = 0 ; i < j ; i ++){
scrollPadding[h-j] = message[ i];
h++;
}
lcdPosition(lcd,0,0);
lcdClear (lcd);
lcdPrintf(lcd,"%s",scrollPadding);
j++;
}

void INThandler(int sig)


{
lcdClear (lcd);
fclose(uptime_file);
signal(sig, SIG_IGN);
exit(0);
}

int mymillis(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000;
}

How to Control the GPIO on a Raspberry Pi with an IR Remote

The LCD->Pi wiring diagram has an error, the sire from the LCD RS line (4) is going
to the Pi
connector pin 17 (3.3 v power), it should be going to ping 15 (GPIO3).

REPLY

I have updated the diagram.


thanks!

REPLY

================================================================================
MOUSE
================================================================================
dmesg -C cancella device messagge
dmesg

[ 4631.136768] usb 1-1.5: USB disconnect, device number 4


[ 4636.445078] w1_master_driver w1_bus_master1: Family 0 for 00.fa0000000000.0a is
not registered.
[ 4638.785333] usb 1-1.5: new low-speed USB device number 6 using dwc_otg
[ 4638.891819] usb 1-1.5: New USB device found, idVendor=15d9, idProduct=0a4c
[ 4638.891845] usb 1-1.5: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 4638.891859] usb 1-1.5: Product: USB OPTICAL MOUSE
[ 4638.900557] input: USB OPTICAL MOUSE as
/devices/platform/soc/3f980000.usb/usb1/1-1/1-1.5/1-1.5:1.0/0003:15D9:0A4C.0002/
input/input1
[ 4638.901495] hid-generic 0003:15D9:0A4C.0002: input,hidraw0: USB HID v1.11 Mouse
[ USB OPTICAL MOUSE] on usb-3f980000.usb-1.5/input0

================================================================================
Settato Controllo: [./?action=command&dest=0&plugin=0&id=9963776&group=1&value=51]
================================================================================
-------------------------------------
Logging in via SSH without a password
-------------------------------------

The target root file system included in the STLinux distribution is setup in such a
way that the user root can log on to a target system without a password.

We achieve this by leaving the password field on the target´s etc/passwd file is
empty:

root::0:0:root:/root:/bin/bash

The configuration file for the Open SSH server running on the target has also been
modified to allow users to login without a pasword.

The following line in ./etc/openssh/sshd_config allows users to connect to the


target using ssh without using a password

PermitEmptyPasswords yes
Securing the Target

From what has been said above, a target system can be made more secure by either

setting a root password


changing the Open SSH server configuration file to deny access using an empty
password (notice that rlogin and telnetd still need to be deal with separately

Alternatively, it is possible to connect to an SSH server using a public/private


key authentication method as described bellow.
Setting up RSA/DSA SSH Authentication

Create a public key by typing the following on the host at the shell prompt
(note that there are no spaces in ssh-keygen):

host% ssh-keygen -t rsa


Generating public/private rsa key pair.
Enter file in which to save the key (/home/<user>/.ssh/id_rsa):

Press Return (to use the default directory).

Created directory '/home/<user>/.ssh'.


Enter passphrase (empty for no passphrase):

Press Return (to leave the passphrase blank).

Enter same passphrase again:

Press Return again.

Your identification has been saved in /home/<user>/.ssh/id_rsa.


Your public key has been saved in /home/<user>/.ssh/id_rsa.pub.
The key fingerprint is:
xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx <user>@<machine>

Create a directory .ssh on the target by typing:

host% ssh root@<target> mkdir /root/.ssh

and press Return:

The authenticity of host '<target>' can't be established.


RSA key fingerprint is xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx.
Are you sure you want to continue connecting (yes/no)?

Type yes and press Return:

Warning: Permanently added '<target>' (RSA) to the list of known hosts.


root@<target>'s password:

Enter the root password of the target machine and press Return.

To transfer the public key to the target type:

host% scp /home/<user>/.ssh/id_rsa.pub


root@<target>:/root/.ssh/authorized_keys
root@<target>'s password:
Enter the root password of the target and press Return:

id_rsa.pub 100% 236 1.1MB/s 00:00

SSH is now configured on both sides and will work without a password. To check
this, type the following at the shell prompt on the host:

host% ssh root@<target>


Last login: Sat Jan 1 00:43:43 2000 from 164.129.15.35
Linux <target> 2.6.11 #4 Sun Sep 18 17:17:44 BST 2005 sh4 unknown unknown GNU/Linux
Welcome to STMicroelectronics Base Distribution

--------------------------------------------------------------------------------
sshpass: Login To SSH Server / Provide SSH Password Using A Shell Script
--------------------------------------------------------------------------------
by Vivek Gite on September 12, 2008 · 12 comments

How do I login over ssh without using password less RSA / DSA public keys?
How do I use ssh in a shell script?
How do I login non-interactivly performing password authentication
with SSH and shell scripts?

You can use sshpass command to provide password for ssh based login.

From the man page:

sshpass is a utility designed for running ssh using the mode referred to as
"keyboard-interactive" password authentication, but in non-interactive mode.

ssh uses direct TTY access to make sure that the password is indeed issued by an
interactive keyboard user. Sshpass runs ssh in a dedicated tty, fooling it into
thinking it is getting the password from an interactive user.

The command to run is specified after sshpass' own options.


Typically it will be "ssh" with arguments, but it can just as well be any other
command. The password prompt used by ssh is, however, currently hardcoded into
sshpass.

[Warning following examples may expose your computer security] WARNING!


These examples considered the least secure as simple ps command can expose password
to all users on the same host.

I highly recommend using ssh's public key authentication or keychain software to


set up secure passwordless SSH access

Install sshpass Ubuntu Linux


----------------------------

Type the following command:

$ sudo apt-get install sshpass

How do I use sshpass?


---------------------

Login to ssh server called server.example.com with password called t@uyM59bQ:

sshpass -p 't@uyM59bQ' ssh [email protected]


Under shell script you may need to disable host key checking:

sshpass -p 't@uyM59bQ' ssh -o StrictHostKeyChecking=no [email protected]

How do I backup /var/www/html using rsync?


------------------------------------------

Run rsync over SSH using password authentication, passing the password on the
command line:

rsync --rsh="sshpass -p myPassword ssh -l username"


server.example.com:/var/www/html/ /backup/

Further readings:

- keychain: Set Up Secure Passwordless SSH Access For Backup Scripts


- sshpass man page
--------------------------------------------------------------------------------
================================================================================
AZARTICOLO:Come configurare ssh in modo che non venga chiesta la password
================================================================================
https://www.debian.org/devel/passwordlessssh

N.B Se manca la directory occorre crearla con:

mkdir ${HOME}/.ssh
% chmod 700 ~/.ssh

occorre dare al solo utente che deve accedere i permessi su tale directory !!

È possibile creare una chiave RSA per poter accedere al sito remoto dal tuo
account, senza avere
bisogno di inserire la password.

Notare che una volta che tutto ciò è configurato, se un estraneo si inserisce nel
vostro account
avrà accesso anche ai sistemi remoti ai quali avete accesso!
Per questo motivo è meglio che questa procedura non sia mai fatta da root.

Eseguire ssh-keygen sulla tua macchina e premere Invio quando viene chiesta la
password.

Verranno generate sia la chiave privata che quella pubblica.


Con le vecchie versioni di SSH, le chiavi sarano memorizzate in

~/.ssh/identity e
~/.ssh/identity.pub;

con le nuove versioni saranno memorizzate in

~/.ssh/id_rsa e
~/.ssh/id_rsa.pub.

Successivamente aggiungere il contenuto del file con la chiave pubblica in


~/.ssh/authorized_keys
sul sito remoto (il file deve essere protetto con permessi 600).

Se si è uno sviluppatore e si vuole accedere ai sistemi di debian.org con questa


chiave, è possibile
fare in modo che il database degli sviluppatori diffonda la chiave a tutte le
macchine.
Vedere la documentazione sul gateway LDAP.

Adesso si dovrebbe avere la possibilità di utilizzare ssh per collegarsi alraspi-


config sistema
remoto senza che sia richiesta la password.

Importante: Notare che chiunque abbia accesso in lettura al file con la chiave
privata può usarla
per avere lo stesso accesso senza password al sito remoto. Fra queste persone sono
incluse coloro
che hanno accesso come root alla vostra macchina locale, di conseguenza se non
siete l'unico
amministratore della macchina locale è fortemente raccomandato proteggere la
vostra chiave
privata con una passphrase.

È possibile usare ssh-agent e ssh-add(1) per inserire la passphrase della chiave


una sola volta e
usare la chiave quante volte si vuole all'interno di una sessione.
Si può automatizzare il caricamento di tutte le chiavi nell agente aggiungendo le
seguenti righe
nel file ~/.xsession:

# se in /etc/X11/Xsession.options è specificato use-ssh-agent


# (impostazione predefinita) allora è sufficiente solo la seconda riga
# eval ssh-agent
ssh-add <nome-del-file-della-chiave-ssh>

Il pacchetto ssh-askpass deve essere installato per poter eseguire ssh-add senza un
terminale.

===================================================================================
=========
AZARTICOLO:Abilitare ssh server login con password
===================================================================================
=========

Per abilitare il login con password decommenta:


#PasswordAuthentication yes

Per abilitare il login di root aggiungi:


#PermitRootLogin yes
e commenta
#PermitRootLogin without-password

Per abilitare l'ssh key login, decommenta le seguenti linee

#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys

otteniamo alfine il file:

/etc/ssh/sshd_config
-------------------------------

# Package generated configuration file


# See the sshd_config(5) manpage for details
Port 22
ListenAddress ::
ListenAddress 0.0.0.0
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
UsePrivilegeSeparation yes
KeyRegenerationInterval 3600
ServerKeyBits 1024
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 120

# AZPATCH
#PermitRootLogin without-password
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile %h/.ssh/authorized_keys

IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM yes

-----------------------------------------------------------------------------------
-------------------------------------------------------------
Setting up an SSH Server
-----------------------------------------------------------------------------------
-------------------------------------------------------------

Edit this on GitHub

You can access the command line of a Raspberry Pi remotely from another computer or
device
on the same network using the Secure Shell (SSH) protocol.

You will only have access to the command line, not the full desktop environment.
For a full remote desktop, see VNC.

Set up your Local Network


----------------------------------------

Make sure your Raspberry Pi is properly set up and connected.


If you are using wireless networking, this can be enabled via the desktop user
interface,
or using from the command line. If you are not using wireless connectivity, plug
your Raspberry
Pi directly into the router.

NOTE

You will need to note down the IP address of your Raspberry Pi in order to connect
to it later.
Using the ifconfig command will display information about the current network
status, including
the IP address, or you can use hostname -I to display the IP addresses associated
with the device.

Enabling the Server

Raspberry Pi OS has the SSH server disabled by default. It can be enabled manually
from the
desktop:

Launch Raspberry Pi Configuration from the Preferences menu

Navigate to the Interfaces tab

Select Enabled next to SSH

Click OK

Alternatively you can enable it from the terminal using the raspi-config
application,

Enter sudo raspi-config in a terminal window

Select Interfacing Options

Navigate to and select SSH

Choose Yes

Select Ok

Choose Finish

NOTE

For headless setup, SSH can be enabled by placing a file named ssh, without any
extension,
onto the boot partition of the SD Card. When the Raspberry Pi boots, it looks for
the ssh file.
If it is found, SSH is enabled and the file is deleted.
The content of the file does not matter; it could contain text, or nothing at all.

NOTE

For headless setup in addition to the ssh file you need a userconf.txt file, which
contains a string
username:encryptedpassword.
Please refer to the section on configuring a user in the discussions around
headless setup of a
Raspberry Pi.

WARNING

When enabling SSH on a Raspberry Pi that may be connected to the internet, you
should ensure
that your password is not easily brute forced.
Secure Shell from Linux or Mac OS
Edit this on GitHub

You can use SSH to connect to your Raspberry Pi from a Linux desktop, another
Raspberry Pi,
or from an Apple Mac without installing additional software.

Open a terminal window on your computer replacing <IP> with the IP address of the
Raspberry
Pi you’re trying to connect to,

ssh pi@<IP>

When the connection works you will see a security/authenticity warning.


Type yes to continue. You will only see this warning the first time you connect.

NOTE
If you receive a connection timed out error it is likely that you have entered the
wrong IP address
for the Raspberry Pi.

WARNING

In the event your Raspberry Pi has taken the IP address of a device to which your
computer has
connected before (even if this was on another network), you may be given a warning
and asked
to clear the record from your list of known devices.
Following this instruction and trying the ssh command again should be successful.
Next you will be prompted for the password for the pi login: the default password
on Raspberry
Pi OS is raspberry.

For security reasons it is highly recommended to change the default password on the
Raspberry Pi (also, you can not login through ssh if the password is blank).
You should now be able to see the Raspberry Pi prompt, which will be identical to
the one found
on the Raspberry Pi itself.

If you have set up another user on the Raspberry Pi, you can connect to it in the
same way,
replacing the username with your own, e.g. [email protected]

pi@raspberrypi ~ $
You are now connected to the Raspberry Pi remotely, and can execute commands.

Forwarding X11
You can also forward your X session over SSH, to allow the use of graphical
applications, by using the -Y flag:

ssh -Y [email protected]
NOTE

X11 is no longer installed by default on macOS, so you will have to download and
install it.
Now you are on the command line as before, but you have the ability to open up
graphical windows.
For example, typing:

geany &
will open up the Geany editor in a window on your local desktop.

Secure Shell from Windows 10


Edit this on GitHub

You can use SSH to connect to your Raspberry Pi from a Windows 10 computer that is
using
October 2018 Update or later without having to use third-party clients.

Open a terminal window on your computer replacing <IP> with the IP address of the
Raspberry Pi you’re trying to connect to,

ssh pi@<IP>
When the connection works you will see a security/authenticity warning.
Type yes to continue. You will only see this warning the first time you connect.

NOTE
If you receive a connection timed out error it is likely that you have entered the
wrong
IP address for the Raspberry Pi.

WARNING
In the event your Raspberry Pi has taken the IP address of a device to which your
computer has
connected before (even if this was on another network), you may be given a warning
and asked to
clear the record from your list of known devices.
Following this instruction and trying the ssh command again should be successful.
Next you will be prompted for the password for the pi login: the default password
on Raspberry
Pi OS is raspberry.

For security reasons it is highly recommended to change the default password on the
Raspberry Pi
(also, you can not login through ssh if the password is blank).
You should now be able to see the Raspberry Pi prompt, which will be identical to
the one found
on the Raspberry Pi itself.

If you have set up another user on the Raspberry Pi, you can connect to it in the
same way, replacing the username with your own, e.g. [email protected]

pi@raspberrypi ~ $
You are now connected to the Raspberry Pi remotely, and can execute commands.

Passwordless SSH Access


-----------------------------------------

Edit this on GitHub


It is possible to configure your Raspberry Pi to allow access from another computer
without
needing to provide a password each time you connect.
To do this, you need to use an SSH key instead of a password.
To generate an SSH key:

Checking for Existing SSH Keys

First, check whether there are already keys on the computer you are using to
connect to the Raspberry Pi:

ls ~/.ssh
If you see files named id_rsa.pub or id_dsa.pub then you have keys set up already,
so you can
skip the 'Generate new SSH keys' step below.

Generate new SSH Keys

To generate new SSH keys enter the following command:

ssh-keygen

Upon entering this command, you will be asked where to save the key.
We suggest saving it in the default location (~/.ssh/id_rsa) by pressing Enter.

You will also be asked to enter a passphrase, which is optional.


The passphrase is used to encrypt the private SSH key, so that if someone else
copied the key,
they could not impersonate you to gain access. If you choose to use a passphrase,
type it here
and press Enter, then type it again when prompted. Leave the field empty for no
passphrase.

Now look inside your .ssh directory:

ls ~/.ssh
and you should see the files id_rsa and id_rsa.pub:

authorized_keys id_rsa id_rsa.pub known_hosts


The id_rsa file is your private key. Keep this on your computer.

The id_rsa.pub file is your public key.


This is what you share with machines that you connect to: in this case your
Raspberry Pi.
When the machine you try to connect to matches up your public and private key, it
will allow you to connect.

Take a look at your public key to see what it looks like:

cat ~/.ssh/id_rsa.pub
It should be in the form:

ssh-rsa <REALLY LONG STRING OF RANDOM CHARACTERS> user@host

Copy your Key to your Raspberry Pi

Using the computer which you will be connecting from, append the public key to your
authorized_keys
file on the Raspberry Pi by sending it over SSH:
ssh-copy-id <USERNAME>@<IP-ADDRESS>

NOTE
During this step you will need to authenticate with your password.

-----------------------------------------------------------------------------------
------------------------------------------------------------
ssh-copy-id [email protected]
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed:
"/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out
any that are already installed

/usr/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on
the remote system.
(if you think this is a mistake, you may want to use -f option)

[root@portatile2009 .ssh] # ssh 192.168.1.5


Linux raspberry 6.1.21-v8+ #1642 SMP PREEMPT Mon Apr 3 17:24:16 BST 2023 aarch64

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.
Last login: Sun May 14 15:08:02 2023 from 192.168.1.2

-----------------------------------------------------------------------------------
-------------------------------------------------------------

Alternatively, if ssh-copy-id is not available on your system, you can copy the
file manually over SSH:

cat ~/.ssh/id_rsa.pub | ssh <USERNAME>@<IP-ADDRESS> 'mkdir -p ~/.ssh && cat >>


~/.ssh/authorized_keys'

If you see the message ssh: connect to host <IP-ADDRESS> port 22: Connection
refused and
you know the IP-ADDRESS is correct, then you may not have enabled SSH on your
Raspberry Pi.
Run sudo raspi-config in the Raspberry Pi’s terminal window, enable SSH, then try
to copy the files
again.

Now try ssh <USER>@<IP-ADDRESS> and you should connect without a password prompt.

If you see a message "Agent admitted failure to sign using the key" then add your
RSA or DSA
identities to the authentication agent ssh-agent then execute the following
command:

ssh-add

NOTE

You can also send files over SSH using the scp (secure copy) command.
Adjust Directory Permissions

If you can’t establish a connection after following the steps above there might be
a problem with
your directory permissions. First, you want to check the logs for any errors:

tail -f /var/log/secure

# might return:
Nov 23 12:31:26 raspberrypi sshd[9146]: Authentication refused: bad ownership or
modes for directory /home/pi
If the log says Authentication refused: bad ownership or modes for directory
/home/pi there is a
permission problem regarding your home directory.
SSH needs your home and ~/.ssh directory to not have group write access.
You can adjust the permissions using chmod:

chmod g-w $HOME


chmod 700 $HOME/.ssh
chmod 600 $HOME/.ssh/authorized_keys

Now only the user itself has access to .ssh and .ssh/authorized_keys in which the
public keys
of your remote machines are stored.

Storing the passphrase in the macOS keychain

If you are using macOS, and after verifying that your new key allows you to
connect, you have
the option of storing the passphrase for your key in the macOS keychain.
This allows you to connect to your Raspberry Pi without entering the passphrase.

Run the following command to store it in your keychain:

ssh-add -K ~/.ssh/id_rsa

NOTE
From macOS Monterey onwards the -K flag has been deprecated and been replaced by
the --apple-use-keychain flag.

Using Secure Copy


-----------------------------

Edit this on GitHub

Secure Copy (scp) is a command for sending files over SSH. This means you can copy
files
between computers, say from your Raspberry Pi to your desktop or laptop, or vice-
versa.

First of all, you’ll need to know your Raspberry Pi’s IP address.

Copying Files to your Raspberry Pi

Copy the file myfile.txt from your computer to the pi user’s home folder of your
Raspberry Pi at
the IP address 192.168.1.3 with the following command:

scp myfile.txt [email protected]:


Copy the file to the /home/pi/project/ directory on your Raspberry Pi (the project
folder must already exist):

scp myfile.txt [email protected]:project/

Copying Files from your Raspberry Pi

Copy the file myfile.txt from your Raspberry Pi to the current directory on your
other computer:

scp [email protected]:myfile.txt .

Copying Multiple Files

Copy multiple files by separating them with spaces:

scp myfile.txt myfile2.txt [email protected]:


Alternatively, use a wildcard to copy all files matching a particular search with:

scp *.txt [email protected]:


(all files ending in .txt)

scp m* [email protected]:
(all files starting with m)

scp m*.txt [email protected]:


(all files starting with m and ending in .txt)

NOTE
Some of the examples above will not work for file names containing spaces.
Names like this need to be enclosed in quotes:

scp "my file.txt" [email protected]:

Copying a Whole Directory

Copy the directory project/ from your computer to the pi user’s home folder of your
Raspberry
Pi at the IP address 192.168.1.3 with the following command:

scp -r project/ [email protected]:

Using rsync
-------------------

Edit this on GitHub

You can use the tool rsync to synchronise folders between computers. You might want
to transfer
some files from your desktop computer or laptop to your Raspberry Pi, for example,
and for them
to be kept up to date, or you might want the pictures taken by your Raspberry Pi
transferred to
your computer automatically.

Using rsync over SSH allows you to transfer files to your computer automatically.

Here is an example of how to set up the sync of a folder of pictures on your


Raspberry Pi to your computer:

On your computer, create a folder called camera:

mkdir camera

Look up the Raspberry Pi’s IP address by logging in to it and running hostname -I.
In this example, the Raspberry Pi is creating a timelapse by capturing a photo
every minute, and
saving the picture with a timestamp in the local folder camera on its SD card.

Now run the following command (substituting your own Raspberry Pi’s IP address):

rsync -avz -e ssh [email protected]:camera/ camera/


This will copy all files from the Raspberry Pi’s camera folder to your computer’s
new camera folder.

================================================================================
AZARTICOLO:Force a full fsck on reboot, ignoring the dirty flag
================================================================================
Raspberry Pi Forums
https://www.raspberrypi.org/forums/

I have experienced several instances of data corruption on the SD card on my Pi.


I am still investigating the root cause of this.
At the moment to correct filesystem errors I shutdown the pi and put the card into
my laptop
to fsck the root filesystem. This is because a "forced" fsck on reboot does not
always work:
the filesystem will only be checked if the dirty flag is set. Usually the dirty
flag is not set,
since the OS thinks the filesystem is fine, except for reading duff data from
certain parts of the FS.
I need a way to forcible run an "e2fsck -fy" on the root filesystem on reboot.
This would remove the need to take the SD card out of the Pi and do the filesystem
check on my laptop.

Does anyone have any ideas how to accomplish this?

Thanks

Andrew.
Re: Force a full fsck on reboot, ignoring the dirty flag

As root (or using),


I 'mount / -o remount,ro' to remount the filesystem read-only, then fsck can be run
safely.

This might require shutting down daemons (e.g. /etc/init.d/apache2 stop) that hold
write-locks
on files in your root filesystem.
The utility 'lsof' (apt-get install lsof) is useful to identify owning processes of
currently open files,
should you keep getting the '/ is busy' messages when trying to remount read-only.

I tried that and did indeed get the '/ is busy' message.
lsof did not prove useful though as I could not see any way to identify which open
files had write
locks set on them.

What I really need is a way to just force a filesystem check on each boot,
before the root filesystem gets remounted rw.

Thanks

I have done some more digging. It seems that forcing an fsck in reboot adds '-f' to
the command line
for fsck, so that should work.

I have found the script that does the fsck on boot - it is


/etc/rcS.d/S05checkroot.sh .

For some reason in this script the 'rootcheck' variable is being set to 'no', which
is disabling the
root filesystem check. I am still investigating this but it looks like it is
actually a bug in raspbian.
I will post more once I have idenitifed why rootcheck is being set to 'no'.

Cheers

Andrew.
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Wed Aug 29, 2012 12:10 pm


by ksangeelee

andrum99 wrote: I tried that and did indeed get the '/ is busy' message. lsof did
not prove useful though as I could not see any way to identify which open files had
write locks set on them. What I really need is a way to just force a filesystem
check on each boot, before the root filesystem gets remounted rw.
First of all, lsof's output, the FD column entries which are a number followed by
'w' or 'u' will have write or read/write locks (e.g. '2w' or '7u' - the number is
the file-descriptor).

Sorry for not reading your original question properly - I'd incorrectly read that
you wanted to do a one-time fsck.

I also had problems last night getting a boot-time fsck to work. Using 'touch
/forcefsck' or shutdown with a -F flag didn't work.

Looking deeper, I found that my fstab file didn't have the DUMP and PASS fields
defined for the root entry, and these default to zero if not specified. Adding '0
1' to the end of my root entry fixed this (a PASS of zero causes the init script to
skip the filesystem - see /lib/init/mount-functions.sh)
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Wed Aug 29, 2012 3:39 pm


by andrum99
Sorry for not reading your original question properly - I'd incorrectly read that
you wanted to do a one-time fsck.
I changed my requirements halfway through this thread - sorry. I had thought a one-
time check would be OK but then revised this to a check on every boot.

I have set up my fstab as you suggested and my system now responds to the presence
of the /forcefsck file.
I will ask the raspbian developer mailing list why they disabled fsck on boot as on
the face of it this seems like an odd thing to do.

I have also changed FSCKFIX to yes in /etc/default/rcS to allow all fixes to be


made to the filesystem during the boot time check.

Thanks for your help in tracking this one down.

Andrew.
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Wed Aug 29, 2012 4:01 pm


by andrum99
I added '/usr/bin/touch /forcefsck' to /etc/rc.local so that the Pi always does a
forced fsck of the root filesystem on each boot. It also just picked up some
filesystem corruption, but luckily none of the daemons seems to be affected.

Cheers

Andrew.
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Wed Aug 29, 2012 6:25 pm


by ksangeelee
andrum99 wrote: It also just picked up some filesystem corruption, but luckily none
of the daemons seems to be affected.
I assume you've already followed the various threads that discuss power-supplies,
poor solder-joints, bent card-slot connectors, etc. as causes of filesystem
corruption. If you're on recent firmware and kernel, without over-clocking, and if
the filesystems are being unmounted cleanly, then you shouldn't be seeing this kind
of problem.
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Wed Aug 29, 2012 6:43 pm


by andrum99
I've not followed those threads - that's my next port of call.

Cheers

Andrew.
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Sat Aug 02, 2014 2:57 pm


by diggool
Hi,

I'm having problems forcing the "fsck" to run. I'm sure I've followed the
suggestions in the the posts but I still no sign that "fsck" is running at start up
and getting the boot message to run "fsck".
Could someone list the files that need to be changed / created
then the commands that can be used
Just so I'm clear that I am doing things right, I'm not as clued up on files and
structure as the rest of you seem to be.

Many Thanks
Jon
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Thu Apr 02, 2015 2:02 pm


by davemunn73
Hi Andrum99
Can you tell me how you got to pi to do a fsck on every reboot when the filesystem
was flagged as dirty?
Id like to do that for some pi's i have running chromium in kiosk mode.
Thanks
Dave
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Thu Jan 14, 2016 7:23 pm


by Fahrenheit
diggool wrote:Hi,

I m having problems forcing the "fsck" to run. I'm sure I've followed the
suggestions in the the posts but I still no sign that "fsck" is running at start up
and getting the boot message to run "fsck".
Could someone list the files that need to be changed / created
then the commands that can be used
Just so I'm clear that I am doing things right, I'm not as clued up on files and
structure as the rest of you seem to be.

Many Thanks
Jon
Looks like this is still an issue in Raspbian Jessie. To recap what the gentlemen
did above (and how I got it to work on my system):
Code: Select all

vi /cat/default/rcS
Change the FSCKFIX option to yes
Code: Select all

FSCKFIX=Yes
ctrl-x and y to save

Next use the "touch" executable to create a "forcefsck" file in the root /
Code: Select all

touch /forcefsck
Reboot the Pi
Code: Select all

shutdown -h -r
You should see fsck lines during boot, checking all attached drives. You can
validate whether it ran by checking the syslog:
Code: Select all

cat /var/log/syslog | grep fsck


Funny, it actually says not to use "/forcefsck" but I'm not sure how to pass
"fsck.mode=force" to the kernel. Also, I haven't seen if the devs removed the
feature for a particular reason.
Re: Force a full fsck on reboot, ignoring the dirty flag

I'm not sure how to pass "fsck.mode=force" to the kernel


That is really a userspace parameter; the kernel knows nothing about fsck.
To pass such an option to the kernel and userspace on every boot, add it to
/boot/cmdline.txt, keeping that file all on one line.

But the whole premise of this thread is flawed. fsck can repair routine
inconsistencies, not corruption.
If a filesystem is marked clean, but is actually corrupt, then some device-level
problem
has occurred. Perhaps the SD card is faulty, or power has been removed before the
card
finished reallocating data.

For fsck to run at all, the filesystem must be good enough to mount and boot, and
to find and load the fsck binary and all its libraries correctly. Then it can
repair any inconsistencies, and gloss over any corruption. If there are device-
level problems, sooner or later the system will stop booting, regardless of how
often or how hard you run fsck.
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Tue Aug 23, 2016 6:55 am


by ferdyp
Code: Select all

shutdown -r -F now
works for me @wheezy
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Tue Jan 31, 2017 11:54 am


by alexghiti
Hi all,

Old thread but without any clear good solution. The only good solution I found is
to create a new kernel image with initramfs embedded that include e2fsck and that
handles mounting rootfs afterwards.
If anyone interested, I will push on github the buildroot .config and init script.
However, I think that the best way for users to have easily access to the above
solution would be a package in raspbian repos.

So if any moderator/contributor/user is interested, do not hesitate to contact me.

Thanks

Alex
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Mon Mar 27, 2017 6:30 pm


by havasu
I have remote wifi routers based on raspberries.
It is critical make it boot on power failures.
So far /usr/bin/touch /forcefsck to /etc/rc.local helps but guess could be
other filesystem failure situations and it would stop doing fsck on boot.
alexghiti: kernel image with initramfs embedded would be best solution.
I googled but could not find any samples how to make initramfs with fsck.
Please let us know how to make it.
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Tue Mar 28, 2017 1:20 pm


by alexghiti
Hi @havasu,

I uploaded on github all you need :


https://github.com/AlexGhiti/rpi_initramfs_e2fsck
I have just tested what I wrote in the README, if anyone needs more infos, please
file an issue in github.
Hope it will help some people, it helped me :)

Alex
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Fri Apr 21, 2017 1:46 pm


by valent
There were typos and wrong path names, so to have correct steps in one place here
is what you need to do:
Code: Select all

su -c 'echo "FSCKFIX=yes" >> /etc/default/rcS'


touch /forcefsck
reboot & exit
Re: Force a full fsck on reboot, ignoring the dirty flag

Posted: Sun Jul 23, 2017 5:32 am


by capricorn180
Fahrenheit wrote:
diggool wrote:Hi,
Code: Select all

vi /cat/default/rcS
Change the FSCKFIX option to yes
Code: Select all

FSCKFIX=Yes
ctrl-x and y to save
I just found this page and its really useful, anyone following the steps above the
rcS is file path should be
Code: Select all

vi /etc/default/rcS
All times are UTC
Page 1 of 1
Powered by phpBB® Forum Software © phpBB Limited
https://www.phpbb.com/

=================================================================================
AZARTICOLO: Repairing Corrupted SD Cards for the Raspberry Pi on Mac
=================================================================================
http://www.switchdoc.com/2016/01/tutorial-repairing-corrupted-sd-cards-for-
the-raspberry-pi-on-mac/

Posted by SwitchDoc Labs in Raspberry Pi, Tutorials.

Have you ever had your Raspberry Pi stopped booting up?


The red and the yellow lights flash a few times and then quit?
These are classic symptoms of a corrupted SD Card.

This posting will walk through how to fix a corrupted SD Card for your Raspberry Pi
using a Mac and
VirtualBox.

This is a fairly complicated procedure, but most of it only has to be done once and
then you can
fix corrupted cards quickly and efficiently.
Why do SD Cards get Corrupted?

When the SD Card is being written, there are windows of vulnerability.


There seem to be four main scenarios during which SD Cards become corrupted:

Powering your Raspberry Pi down without doing a “halt“.


Do this enough, you will corrupt your card.

Poor quality SD Cards. Fake SanDisk cards especially.

Marginal power supplies. Watch the Red LED on newer Raspberry Pi’s.
If it is blinking, there are issues.
Poor power quality from the mains can also screw up your Raspberry Pi

Overclocking your Pi. If you push it too far, things start not quite working
correctly.

OK, what can I do with a Corrupted SD Card?

The first thing you can do is BEFORE you get corrupted, back up your SD Card on a
regular basis.
If you spend hours configuring an SD Card, then back it up. Changing your
software? Back it up.
It will save you a lot of time if you end up corrupting or destroying the SD Card.
Here is how to do it on a Mac.

Sometimes, the SD Card is actually damaged.


In that case, you aren’t going to be able to fix the card.
However, you can get your files off the SD Card in many cases.
Check out this posting.

Fixing a Corrupted SD Card


------------------------

Overall, this is the procedure for fixing a corrupted SD Card using a Mac.
The process is similar for a PC, but requires different instructions to install and
get VirtualBox working.

Back up your SD Card, if possible.


Here is how to do it on a Mac.

Install VirtualBox on your Mac


Install Ubuntu in Virtual Box
Attach SD Card to Ubuntu

Run “fsck” to repair the SD Card

Install VirtualBox on your Mac


-------------------------

VirtualBox is a “virtualizer” which means that it allows you to install an


operating system in a
“Box” inside another operating system. It is open source and free to use.
In this case we will be installing Linux (Ubuntu) on a Mac OS X platform.

Step 1: Download the VirtualBox .dmg file for the Mac OS X from this page:

Step 2: Click on the downloaded .dmg file.


Step 3: Double click on the VirtualBox.pkg icon

Screen Shot 2016-01-25 at 7.52.07 AM

Step 4: Follow the instructions to install VirtualBox in the applications


directory.

Step 5: Now download the installation file (.iso) for Ubuntu from this link:
Note: Make sure you use this link – ubuntu-1510-desktop-i386.iso.
If this link isn’t available, go to http://mirror.pnl.gov/releases/ and find the
latest release.
The default download link on Ubuntu server will download an amd64 image,
which WILL NOT WORK on your Mac OS X.

Step 6: Start up VirtualBox from Applications

Step 7: Click on “New”

Step 8: Enter “Ubuntu” as the name. Linux and 64 bit will be automatically
selected. Click Continue.

Step 9: Click on continue until you are done, using all the defaults.

Step 10: Click on settings and then on Storage and then on Controller: SATA

Step 11: Enter 2 in port count! This is an important step not to miss! Click
“OK” to close

Step 12: Ready to install Ubuntu now! Click the Start Button

Step 13: When you are promoted to select an image, select the ubuntu .iso image
downloaded in Step 5.

Step 14: Select “Install Ubuntu” from the screen, then “Continue” from the next
screen and then keeping the defaults, finally “Install Now”.

Step 15: Click “Continue” when asked to erase the virtual disk. Don’t worry, this
is not your Mac OS X disk.

Step 16: Select your Timezone. Hit “Continue”

Step 17: Put in your name and choose a password. Make sure you can remember it!
Now hit “Continue” and you are installing Ubuntu.

Step 18: Now click “Restart Now” when the installation is finished.
If Ubuntu does not start (which happens often the first time), then hit the “x” in
the corner
and select “Power Off the Machine”.

Step 19: Now you have your Ubuntu Virtual Machine running.
Click the “X’ on the window and select “Send the shutdown signal”. Then click
“Shutdown”

Adding the SD Card to your Ubuntu Virtual Machine


----------------------------------------------------------------------------
In order to mount and fix your corrupted SD Card, you need to add it to the Ubuntu
virtual machine.
This is the complicated part of this procedure.

Step 1: Insert your SD Card into the reader on your Mac OS X machine.
Below is on the Mac Mini. On a Mac Book, it will be on the side.

Step 2: Open up a terminal window and type:

diskutil list

Step 3: You will see a list similar to this. Look for your SD card and note the
/dev path (/dev/disk4 in this case)

Step 4: In the terminal window type (replacing /dev/diskX with what you found in
Step 3):

diskutil unmountDisk /dev/diskX

Step 5: change directory in the terminal window to the “VirtualBox VMs” on our
development machine this command is:

cd "/Users/development/VirtualBox VMs"

Note the quotes around the directory name. Adding spaces in directory names and
filenames
causes all sorts of issues. The user on our machine is “development”.
The user name on your machine will be different.

Step 6: Now we come to the magic. Type the following (replacing diskX with what
you found in Step 3):

VBoxManage internalcommands createrawvmdk -filename ./sd-card.vmdk -rawdisk


/dev/diskX

Step 7: Now we have an .vmdk file pointing to your raw SD Card device.

We next have to set the permissions on this file so your Ubuntu VirtualBox machine
can read the file.

chmod 777 /dev/diskX


chmod 777 ./sd-card.vmdk

Step 8: Next we have to add the SD Card (a SATA device) in the Ubuntu virtual
machine storage
configuration built in the previous section.

Step 9: Click on Settings in VirtualBox and select Storage.


If port count is “1” change it to “2”

Step 10: Click on the icon on the right of the Controller: SATA disk and select
“Choose existing disk”.
Select the .vmdk file built in Step 6 above. If it reports that it is busy
(Mac OS X likes to remount things for some reason), repeat Step 4 and quickly do
Step 10 again.

Step 11: Click OK

Step 12: Start your Ubuntu Virtual machine with the start button.
Now finally, we can repair the SD Card.

Repairing the SD Card


-------------------

Step 1: Select the top most icon on the Ubuntu Desktop. Type “Terminal” in the
search line.

Step 2: Select the Terminal Icon on the top line. You will get a terminal window.

Step 3: type

lsblk -l
into the terminal window (you may have to enter your password from Step 17 in the
section above)

Step 4: Note the name “/dev/sdb”. That is your SD Card on the Ubuntu system.
Note it may be different, but if you followed these directions, it should be the
same.

Step 5: Now the magic. Finally. We will fix the sdb2 partition on sdb.
That is the linux system.
Type the following in the terminal window:

fsck -fy /dev/sdb2

This may take a while, depending on the speed of your machine.


Note that the following picture shows you what you get on a clean, good SD Card.
If you have issues, it will show you what it is doing.

rasberry-pi-b_-with-sd-cardConclusion

Now you should have a repaired Raspberry Pi SD Card.


If it doesn’t work, you may have bigger issues. Start by looking at more “fsck
repair” pages on the web.
If the card is bad, look at mounting the SD Card under your Ubuntu Virtual machine
and going into
the file system to try to recover your most important files.

The next time you need to repair an SD Card, you should only have to plug it into
your Mac OS X
and then start Ubuntu from VirtualBox. Note that the image you built for the SD
Card repair
probably won’t boot without an SD Card plugged in. If you want to use Ubuntu
without the SD Card,
build another image in VirtualBox. You don’t have to delete the SD Card Ubuntu
image.

================================================================================
AZARTICOLO: LA MIA RASPBERRY
================================================================================

raspy
description: Computer
product: Raspberry Pi 3 Model B Rev 1.2
width: 32 bits

*-core
description: Motherboard
physical id: 0
capabilities: brcm_bcm2710 brcm_bcm2709

*-cpu:0

description: CPU
product: cpu
physical id: 0
bus info: cpu@0
size: 1200MHz
capacity: 1200MHz
capabilities: cpufreq

*-cpu:1 DISABLED

description: CPU
product: cpu
physical id: 1
bus info: cpu@1
size: 1200MHz
capacity: 1200MHz
capabilities: cpufreq

*-cpu:2 DISABLED

description: CPU
product: cpu
physical id: 2
bus info: cpu@2
size: 1200MHz
capacity: 1200MHz
capabilities: cpufreq

*-cpu:3 DISABLED

description: CPU
product: cpu
physical id: 3
bus info: cpu@3
size: 1200MHz
capacity: 1200MHz
capabilities: cpufreq

*-memory

description: System memory


physical id: 4
size: 735MiB

*-usbhost

product: DWC OTG Controller


vendor: Linux 4.4.21-v7+ dwc_otg_hcd
physical id: 1
bus info: usb@1
logical name: usb1
version: 4.04
capabilities: usb-2.00
configuration: driver=hub slots=1 speed=480Mbit/s

*-usb

description: USB hub


vendor: Standard Microsystems Corp.
physical id: 1
bus info: usb@1:1
version: 2.00
capabilities: usb-2.00
configuration: driver=hub maxpower=2mA slots=5 speed=480Mbit/s

*-usb

description: Generic USB device


product: SMSC9512/9514 Fast Ethernet Adapter
vendor: Standard Microsystems Corp.
physical id: 1
bus info: usb@1:1.1
version: 2.00
capabilities: usb-2.00
configuration: driver=smsc95xx maxpower=2mA speed=480Mbit/s

*-network:0

description: Wireless interface


physical id: 2
logical name: wlan0
serial: b8:27:eb:72:dd:6c
capabilities: ethernet physical wireless
configuration: broadcast=yes driver=brcmfmac driverversion=7.45.41.26
firmware=01-df77e4a7 ip=192.168.1.4 multicast=yes wireless=IEEE 802.11bgn

*-network:1

description: Ethernet interface


physical id: 3
logical name: eth0
serial: b8:27:eb:27:88:39
size: 100Mbit/s
capacity: 100Mbit/s
capabilities: ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd
autonegotiation
configuration: autonegotiation=on broadcast=yes driver=smsc95xx
driverversion=22-Aug-2005
duplex=full firmware=smsc95xx USB 2.0 Ethernet ip=192.168.1.5 link=yes
multicast=yes
port=MII speed=100Mbit/s

=================================================================================
AZARTICOLO:RASPBERRY PI 3 GPIO HEADER PINOUTS
=================================================================================
https://pinout.xyz/

================================================================================
RASPBERRY PI 2 COMPATIBLE TESTA SD CARD
SLOT
================================================================================
MARRONE | | 3.3V || 01 || 02 || 5V
| |
ROSSO | wpi:08 | GPIO02/SDA1 || 03 || 04 || 5V
| | S) I2C
ARANCIONE | wpi:09 | GPIO03/SCL1 || 05 || 06 || GND |
| S) I2C
GIALLO | wpi:07 | GPIO04/GCLK || 07 || 08 || GPIO14/TXD | wpi:15 |
D) UART
VERDE | | GND || 09 || 10 ||
GPIO15/RXD | wpi:16 | D) UART
BLUE | wpi 00 | GPIO17/GEN0 || 11 || 12 || GPIO18/GEN1 | wpi:01
|
VIOLA | wpi 02 | GPIO27/GEN2 || 13 || 14 || GND
| |
GRIGIO | wpi 03 | GPIO22/GEN3 || 15 || 16 || GPIO23/GEN4 | wpi:04 |
BIANCO | | 3.3V || 17 || 18 ||
GPIO24/GEN5 | wpi:05 |
NERO |wpi 12 | GPIO10/MOSI || 19 || 20 || GND
| | S) SPI
MARRONE |wpi 13 | GPIO09/MISO || 21 || 22 || GPIO25/GEN6 | wpi:06 | S)
SPI
ROSSO |wpi 14 | GPIO11/SCLK || 23 || 24 || GPIO08 /CE0 | wpi:10 |
S) SPI D) SPI
ARANCIONE | | GND || 25 || 26 || GPIO07 /CE1 |
wpi:11 | D) SPI
--------------------------------------------------------------------------------
RASPBERRY PI 3 SPECIFICO (NON COPERTO DA WIRINGPI)
--------------------------------------------------------------------------------
GIALLO | wpi 30 | GPIO00/ID_SD || 27 || 28 || GPIO01/ID_SC | wpi:31 | S)
EPROM D) EPROM
VERDE | wpi 21 | GPIO05 || 29 || 30 || GND |
|
BLUE | wpi 22 | GPIO06 || 31 || 32 || GPIO12 |
wpi:26 |
VIOLA | wpi 23 | GPIO13 || 33 || 34 || GND |
|
GRIGIO | wpi 24 | GPIO19/MISO || 35 || 36 || GPIO16/CE2 | wpi:27 |
BIANCO | wpi 25 | GPIO26 || 37 || 38 || GPIO20/MOSI | wpi:28 |
NERO | | GND || 39 || 40 || GPIO21/SCLK
| wpi:29 |
================================================================================
CONNETTORE P5 sotto MB
================================================================================
01 5V
02 3.3V
03 GPIO 28 wpi:17
04 GPIO 29 wpi:18
05 GPIO 30 wpi:19
06 GPIO 31 wpi:20
07 GND
08 GND

================================================================================
AZARTICOLO:SHIELD PIATTINA A 40 PIN 40° PIN
================================================================================

1022 1027 1017 GND 1004 SCL SLA 3V 5V 5V GND TxD RxD PCL GND
1023
| | | | | | | | | | | |
| | | |
| | | | | | | | | | | |
| | | |
| | | | | | | | | | | |
| | | |
| | | | | | | | | \--\ \ | |
| | |
| | | | | | \ 3V °01 °02 5V | | | |
| | |
| | | | | | SDA1 °03 °04 5V -/ | | |
| | |
| | | | | \-- SCL1 °05 °06 GND -/ | |
| | |
| | | | \------ GCLK °07 °08 TxD ----/ | |
| |
| | | \----------- GND °09 °10 RxD ---------/ |
| |
| | \-------------- GPIO17 °11 °12 GPIO18 ----------/ |
|
| \-------------------- GPIO27 °13 °14 GND -----------------/
|
\-------------------------- GPIO22 °15 °16 GPIO23 -------------------/
3V °---------------------------- 3V °17 °18 GPIO24 -------------- ° 1024
MOSI °-------------------------- MOSI °19 °20 GND ----------------- ° GND
MISO °-------------------------- MISO °21 °22 GPIO25 --------------- ° 1025
SCLK °-------------------------- SCLK °23 °24 CE0 ------------------ ° CE0
GND °--------------------------- GND °25 °26 CE1 ------------------ ° CE1
EED °-------------------------- ID_SD °27 °28 ID_SC ---------------- ° EEC
1005 °------------------------- GPIO05 °29 °30 GND ------------------ ° GND
1006 °------------------------- GPIO06 °31 °32 GPIO12 --------------- ° 1012
1013 °------------------------- GPIO13 °33 °34 GND ------------------ ° GND
1019 °------------------------- GPIO19 °35 °36 CE2 ------------------ ° 1016
1026 °------------------------- GPIO26 °37 °38 MOSI ---------------- ° 1020
GND °--------------------------- GND °39 °40 SCLK ----------------- ° 1021

http://www.raspberry-projects.com/pi/programming-in-c/io-pins/bcm2835-by-mike-
mccauley

root@raspy:~/.netbeans/remote/raspyc/portatile2009-Linux-x86_64/prog/wiringPi/gpio#
lshw

=================================================================================
AZARTICOLO: Raspberry Pi GPIO Pin numbering
=================================================================================

Pins
---

Pin numbering of the BCM2835 GPIO port(s) on the Raspberry Pi has been a source of
great
confusion since the designs for the Pi were first published.
In the early days (even before hardware was available) the default usable GPIO pins
were simply
referred to by number as GPIO0 through GPIO7. Additionally there were pins for
other purposes,
SPI, I2C and serial. This was highlighted on the original image on the Raspberry Pi
Wiki site too.

So when initially writing wiringPi, I chose to have the same default pin numbering
scheme and
numbered them from 0 upwards. This is no different to how the Arduino operates –
“Pin 13” on the Arduino is Port B, bit 5 for example.
The underlying hardware definitions are hidden by a simplified numbering scheme.

On the Pi, using wiringPi, pin 0 is BCM_GPIO pin 17 for example)

However this has subsequently been viewed as “wrong” and several people have
expressed concern
about my numbering scheme, however I’ve stuck with it (as by then people were using
wiringPi).
and it’s proven its worth over the hardware board revisions where some pins changed
their hardware
definitions, however wiringPi was able to hide this from the user.

As a result (for example) a program that uses wiringPi pin 2 on a Rev. 1 Pi will
work unchanged on
a Rev 2. Pi, however someone using BCM_GPIO pin 21 on a Rev 1 Pi will need to
change their program
to use BCM_GPIO pin 27 on a Rev 2.

So wiringPi supports its own pin numbering scheme as well as the BCM_GPIO pin
numbering scheme,
and as of Version 2, it also supports the physical hardware pin numbers (for the P1
connector only),
but I would like to suggest you stick to the simplified wiringPi pin numbers.
That way your programs will be portable over different hardware revisions without
needing any changes.

The following tables give the mapping of the Raspberry Pi GPIO Pins to the (P1)
GPIO connector
in relation to the pin numbers and the physical location on the connector.
This is a representation of the GPIO connector as viewed looking at the board from
above.
The GPIO connector is to the top-right of the board with the Ethernet and USB
sockets to the
bottom.

gpio1Board Revisions: Please note the differences between board revisions 1 and 2
(Rv1 and Rv2 above) The Revision 2 is readily identifiable by the presence of the 2
mounting holes.

gpio2

The P5 connector is designed to have the header soldered on the underside of the
board.
Pin 1 is identified by the square solder pad.
So if you solder the header on the top of the board be aware that the pin locations
will be the
other way round!

For a printable version of these tables, click here.

Special Pin Functions


-----------------

Notare che il processore BCM2837 e' un evoluzione del processore BCM2835.


L'unica differenza e' che il BCM2837 puo' indirizzare piu' RAM (fino a 1GB) e che
da un singolo
CPU come il single core ARM11 di BCM2835 si e' passati ad un Quad core Cortex A53
con 512 KB
dedicata alla cache L2 come nel chip BCM2837.

Tutte le interfaccie di I/O e le periferiche restano le stesse tra i due chip.

WiringPi defines 17 pins, (21 on a Rev. 2 board) but some of them and the functions
we can
use may potentially cause problems with other parts of the Raspberry Pi Linux
system.

-----------------------------------------------------------------------------------
---------------------------------------------
WiringPi | 0 1 2 3 4 5 6 | 7 | 8 9 | 10 11 12 13 14 | 15 16
| 17 18 19 20
BCM_GPIO | 17 18 27 22 23 24 25 | 04 | 02 03 | 8 7 10 9 11 | 14 15 | 28
29 30 31
Raspberry PINs| 11 12 13 15 16 18 22 | 07 | 03 05 | 24 26 19 21 23 | 08 10 |
-----------------------------------------------------------------------------------
---------------------------------------------
| AU | CLK | I2C | SPI | TX
RX | CONN P5
-----------------------------------------------------------------------------------
---------------------------------------------

Pin 0 1 2 3 4 5 6
---------------------------
These are safe to use at any time and can be set to input or output with or without
the internal
pull-up or pull-down resistors enabled.

Pin 7 (BCM_GPIO 4)
----------------------------
This is normally OK to use, however it is used by the 1-Wire kernel driver
and it can
optionally be connected to a GPIO clock source.

PWM: You can change the function of pin 1 (BCM_GPIPO 18) to be PWM output,
however if you are currently playing music or using the audio system via
the 3.5mm
jack socket, then you’ll find one channel of audio PWM coming through the
pin!
If you are not using the audio at all, (or the audio is going via the HDMI
cable),
then this pin is free to be used in PWM mode.

Pins 8 9 (BCM GPIO 0 and 1 on a Rev. 1 board, 2 and 3 on a Rev. 2 board):


-----------------------------------------------------------------------------------
------------------

These are the I2C pins.

You may use them for digital IO if you are not using any I2C drivers which
use these
pins, however note that they have on-board 1.8KΩ resistors pulling the
signals to
the 3v3 supply. This feature does make them handy for switch inputs where
the
switch simply shorts the pin to ground without having to enable the
internal pull-up resistors

Pins 10, 11, 12, 13 and 14 (GPIO 8, 7, 10, 9 and 11 respectively):


-----------------------------------------------------------------------------------
----

These are used for the SPI interface.

Like the I2C interface, if you are not using it, then you can freely use
them for
your own purposes. Unlike I2C, these pins do not have any external pull up
(or pull down) resistors.

Pins 15 16 (GPIO 14 and 15):


-------------------------------------

These are used by the UART for Tx and RX respectively.

If you want to use these pins as general purpose I/O pins then you need to
make sure
that you reboot your Pi with the serial console disabled.
See the file /boot/cmdline.txt and edit it appropriately.

Pins 17, 18, 19 and 20: (BCM_GPIO 28, 29, 30 31)


---------------------------------------------------------------------

These are additional GPIO pins on the Rev. 2 board.

Remember: The Raspberry Pi is a 3.3 volt device! Attempting to directly connect to


any
5V logic system will very likely result in tears…

=================================================================================
AZARTICOLO:How to install Microsoft fonts in Linux office suites
=================================================================================

Times New Roman, Calibri, and many other popular fonts are created by Microsoft and
can’t
be included with Linux. If you open a Word document or another Microsoft Office
document in
LibreOffice or OpenOffice, you’ll need Microsoft’s fonts installed on your Linux
system to see
the documents as they were intended to look.

You can also use Microsoft’s fonts to create documents of your own, so you can
compose
a document in Calibri or Times New Roman and save it as a DOCX or DOC file for
maximum
compatibility with Office.

Install Microsoft’s TrueType Core fonts


--------------------------------------------------------

Microsoft released a package of “TrueType core fonts for the web” back in 1996.
These fonts were given a very permissive license agreement, so anyone could install
them.
Microsoft wanted their fonts to be the standard fonts everyone with a web browser
had,
so they gave them away. Microsoft terminated this project in 2002, but the fonts
can still be
installed thanks to MIcrosoft’s old license agreement.

This font pack contains Andale Mono, Arial, Arial Black, Comic Sans MS, Courier
New, Georgia,
Impact, Times New Roman, Trebuchet, Verdana, and Webdings.
Times New Roman was the default font for Office documents until Calibri debuted in
Office 2007.

This package can be easily installed on Ubuntu.


Unfortunately, you can’t install it from the Ubuntu Software Center on modern
versions of Ubuntu
like Ubuntu 14.04. If you try to install this package from the Ubuntu Software
Center,
the Software Center will freeze—you need to use the terminal so you can accept
Microsoft’s
License agreement. Don’t worry! This is easy.

First, open a terminal. Click the Ubuntu icon on the dock, search for “Terminal,”
and click the
terminal shortcut.

Type or copy-and-paste the following command into the terminal and press Enter.
This command asks for administrator access (sudo) before launching the package
manager
(apt-get) and telling it to download and install (install) the ttf-mscorefonts-
installer package:

apt-get install ttf-mscorefonts-installer

Type your password when prompted and press Enter again.


When the license agreement appears, use the arrow and Page Down/Page Up keys to
scroll through it.
Press Tab to select the OK button and press Enter to accept Microsoft’s license
agreement.
The installer will download the fonts onto your system and configure them so
they’re immediately
available to applications like LibreOffice and OpenOffice.

Other Linux distributions also offer similarly named “corefonts” packages you can
easily install.
Search your Linux distribution’s package manager for such a package.

Install Microsoft’s ClearType fonts


--------------------------------------------------

Microsoft added a group of new “ClearType Fonts” to Windows with Windows Vista and
Office 2007.
These fonts are named Constantia, Corbel, Calibri, Cambria, Candara, and Consolas.
Calibri became
the default font on Microsoft Word 2007, and it’s still the default font on Word
2013 today.

Microsoft never released these fonts to everyone like they did with the older core
fonts.
However, Microsoft does make these fonts available to download as part of their
free
PowerPoint Viewer 2007 application. If you don’t have a Windows system around, you
can use a
script that downloads the PowerPoint Viewer 2007 application from Microsoft,
extracts the six
ClearType fonts, and installs them on your Linux system.
This script will install the ClearType fonts for just your user account, while the
above script installs
the TrueType core fonts for every user account on your system.

The fastest, easiest way to do this is with a few terminal commands.


These commands are easy-to-use—rather than walk you through clicking many different
things,
we can just have you copy-and-paste a few commands.

If you haven’t yet installed the TrueType core fonts, you’ll need to run the apt-
get install
cabextract command to install the cabextract utility on your system. If you
installed the Microsoft
core fonts using the command above, this should already be installed.

Next, type mkdir .fonts and press Enter to create the fonts directory the script
requires.
The script will complain that you don’t have a .fonts directory if you don’t do
this first.

Next, copy-and-paste or type the following command into the terminal and press
Enter.
This command downloads the VistaFonts-Installer script and runs it.
The script downloads the fonts from Microsoft and installs them on your system:

wget -qO- http://plasmasturm.org/code/vistafonts-installer/vistafonts-installer |


bash

Install Tahoma, Segoe UI, and other fonts


-------------------------------------------------------------

The above two font packages are probably all you’ll need.
They’ll give you the standard Microsoft Office fonts, from the older TrueType core
fonts like
Times New Roman to the newer ClearType Fonts like calibri.
These are the standard fonts used in Microsoft Office documents by default.

However, some fonts aren’t included in these packages.


Tahoma isn’t included with the TrueType core fonts package, while Segoe UI and
other newer
Windows fonts aren’t included with the ClearType Fonts package.

If you have a Windows system lying around, these fonts are fairly easy to install.
For example, let’s say you’re dual-booting Ubuntu Linux and Windows.
You’ll find your Windows partition in Ubuntu’s file manager.
Click the Windows drive in the sidebar to access it. Navigate to the Windows\Fonts
directory
and you’ll see all the fonts installed on your Windows PC, including the fonts that
came with it.
Double-click a font and click the Install button to install it for your user
account.
You can use this trick to quickly install any other Windows fonts you want,
including Tahoma and Segoe UI. In fact, you can even use this trick to install
fonts like
Times New Roman and Calibri if you have a Windows system.
If you have another Windows computer, you can navigate to the Fonts pane in the
Control Panel
or open the Fonts folder at C:\Windows\Fonts. Select the fonts you want to use,
then
drag-and-drop them to a removable drive. You’ll get copies of the fonts in .ttf
form.
Take the removable drive to your Ubuntu system, double-click each .ttf file you
want to install,
and click the Install button to install it.

Configure LibreOffice or OpenOffice


-----------------------------------------------------

Whether your Linux distribution uses LibreOffice or OpenOffice, configuring your


office suite of
choice to work with these fonts is easy. If you’ve installed them using any of the
instructions above,
they’ll already be available to use. If either office suite was open as you
installed the fonts, you
may have to first close the office suite and re-open it.
The fonts will appear as options in the Fonts dropdown box, so you can use them
like any other font.

Open a Microsoft Office document created using these fonts and LibreOffice or
OpenOffice will
automatically use the appropriate fonts.
They’ll display the document as it was intended to look, Microsoft fonts and all.

If you’d like to change your default fonts for new documents, click
Tools > Options > LibreOffice Writer or OpenOffice Writer > Basic Fonts (Western).
Your office suite of choice will use Microsoft’s fonts as the default fonts in
future documents
if you choose them here.

Ubuntu and other Linux distributions actually include Red Hat’s “Liberation Fonts”
and use them
by default in their office suites. These fonts were designed to substitute for
Arial, Arial Narrow, Times New Roman, and Courier New.
They have the same widths as Microsoft’s popular fonts.
If you open a document written with Times New Roman, the appropriate Liberation
font will be
used instead so the flow of the document won’t be interrupted.
However, these fonts don’t look identical to Microsoft’s fonts.
The Liberation project also doesn’t provide fonts designed to match the width of
Calibri and
Microsoft’s other newer ClearType fonts.
If you’re a Linux user that wants the best Microsoft Office compatibility possible,
you should install Microsoft’s fonts.

================================================================================
AZARTICOLO:Raspbian
================================================================================
Raspbian is the recommended operating system for normal use on a Raspberry Pi.

Raspbian is a free operating system based on Debian, optimised for the Raspberry Pi
hardware.
Raspbian comes with over 35,000 packages;
precompiled software bundled in a nice format for easy installation on your
Raspberry Pi.

Raspbian is a community project under active development, with an emphasis on


improving the
stability and performance of as many Debian packages as possible.

## Contents

- [Installing Raspbian] (../installation/installing-images/README.md)


- [Installing software in Raspbian](../linux/software/apt.md)
- [Updating/Upgrading Raspbian] (updating.md)

- Configuring Raspbian
- [raspi-config] (../configuration/raspi-config.md)
- [config.txt] (../configuration/config-txt.md)
- [Applications] (applications/README.md)
- [Camera] (applications/camera.md)

==============================================================
AZARTICOLO:NOOBS INSTALLATION INSTRUCTIONS
==============================================================

1. Insert an SD card that is 4GB or greater in size into your computer.


2. Format the SD card using the platform-specific instructions below:

a. Windows
i. Download the SD Association's Formatting Tool from
https://www.sdcard.org/downloads/formatter_4/eula_windows/
ii. Install and run the Formatting Tool on your machine
iii. Set "FORMAT SIZE ADJUSTMENT" option to "ON" in the "Options" menu
iv. Check that the SD card you inserted matches the one selected by the Tool
v. Click the "Format" button
b. Mac
i. Download the SD Association's Formatting Tool from
ii. Install and run the Formatting Tool on your machine
iii. Select "Overwrite Format"
iv. Check that the SD card you inserted matches the one selected by the Tool
v. Click the "Format" button
c. Linux
i. We recommend using gparted (or the command line version parted)
ii. Format the entire disk as FAT

3. Extract the files contained in this NOOBS zip file.

4. Copy the extracted files onto the SD card that you just formatted so that this
file is at the
root directory of the SD card. Please note that in some cases it may extract the
files into a folder,
if this is the case then please copy across the files from inside the folder rather
than the folder itself.

5. Insert the SD card into your Pi and connect the power supply.

Your Pi will now boot into NOOBS and should display a list of operating systems
that you can choose to install.
If your display remains blank, you should select the correct output mode for your
display by pressing
one of the following number keys on your keyboard:
1. HDMI mode - this is the default display mode.
2. HDMI safe mode - select this mode if you are using the HDMI connector and cannot
see anything on screen when the Pi has booted.
3. Composite PAL mode - select either this mode or composite NTSC mode if you are
using the composite RCA video connector.
4. Composite NTSC mode

If you are still having difficulties after following these instructions, then
please visit the
Raspberry Pi Forums ( http://www.raspberrypi.org/forums/ ) for support.

===================================================================================
========
AZARTICOLO:Setting up a RAM drive on Raspberry Pi
===================================================================================
========
http://www.domoticz.com/ domotica open source

Introduction

It is strongly believed that excessive writing to the Raspberry Pi's SD card will
finally cause
it to fail. But the only way to exchange data between Lua and shell scripts is
through
temporarily files.

To avoid SD card wearing these files could be written to a virtual drive in RAM.
This guide shows how to set up a 1 MB RAM drive on your Raspberry Pi.

Setup

Goal is to have a 1MB directory in RAM for temporarily storage.


First create the tmp dir:

mkdir /var/tmp
then edit the fstab file by

vi /etc/fstab
and add the line

tmpfs /var/tmp tmpfs nodev,nosuid,size=1M 0 0


save and close the file. Now issue

mount -a
To check if your operation succeeded issue

df
which should report (among the other disks) a tmpfs with 1024 1K blocks (=1MB)
as /var/tmp

pi@raspberrypi ~ $ df
Filesystem 1K-blocks Used Available Use% Mounted on
rootfs 3807952 1814024 1820896 50% /
/dev/root 3807952 1814024 1820896 50% /
devtmpfs 183596 0 183596 0% /dev
tmpfs 38372 268 38104 1% /run
tmpfs 5120 0 5120 0% /run/lock
tmpfs 76740 0 76740 0% /run/shm
/dev/mmcblk0p1 57288 18544 38744 33% /boot
tmpfs 1024 4 1020 1% /var/tmp

This should give you a small space for your garbage.


Instead of writing your tmp files to /tmp, now write them to /var/tmp.
And remember that, as is generally the case with RAM drives, data on the drive is
lost
after a reboot.

=================================================================================
AZARTICOLO:Raspberry Pi firmware updates
=================================================================================

The Hexxeh / rpi-update project provides a script that updates the


Raspberry Pi firmware (kernel, modules, etc.) to the latest version.
See the project homepage about further details.

Installing rpi-update
----------------------------

Install dependencies
-----------------------------

# dnf install binutils git tar

Install rpi-update

# curl -L -o /usr/bin/rpi-update https://raw.githubusercontent.com/Hexxeh/rpi-


update/master/rpi-update
# chmod +x /usr/bin/rpi-update

Updating the Raspberry Pi firmware


------------------------------

The firmware (kernel, etc.) can easily be updated by running:

# rpi-update
*** Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS and Dom
*** Performing self-update
*** Relaunching after update
*** Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS and Dom
#############################################################
This update bumps to rpi-4.1.y linux tree
Be aware there could be compatibility issues with some drivers
Discussion here:
https://www.raspberrypi.org/forums/viewtopic.php?f=29&t=113753
##############################################################
*** Downloading specific firmware revision (this will take a few minutes)
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 168 0 168 0 0 221 0 --:--:-- --:--:-- --:--:-- 221
100 49.2M 100 49.2M 0 0 1111k 0 0:00:45 0:00:45 --:--:-- 974k
*** Updating firmware
*** Updating kernel modules
*** depmod 4.1.18-v7+
*** depmod 4.1.18+
*** Updating VideoCore libraries
*** Using HardFP libraries
*** Updating SDK
*** Running ldconfig
*** Storing current firmware revision
*** Deleting downloaded files
*** Syncing changes to disk
*** If no errors appeared, your firmware was successfully updated to
0d25b1c25d135090269ff74dc94dac0d31dcbcf9
*** A reboot is needed to activate the new firmware

If a new kernel was installed, a reboot is required.

===================================================================================
=========
AZARTICOLO:Introducing the Raspberry Pi 3
===================================================================================
=========

TL;DR: The Raspberry Pi 3 Model B is out now.


This latest model includes 802.11n WiFi, Bluetooth 4.0, and a quad-core 64-bit ARM
Cortex A53
running at 1.2 GHz.

Available now at the usual Pi retailers for $35.

The Raspberry Pi 3 Model B features a quad-core 64-bit ARM Cortex A53 clocked at
1.2 GHz.
This puts the Pi 3 roughly 50% faster than the Pi 2.
Compared to the Pi 2, the RAM remains the same – 1GB of LPDDR2-900 SDRAM,
and the graphics capabilities, provided by the VideoCore IV GPU, are the same as
they ever were.
As the leaked FCC docs will tell you, the Pi 3 now includes on-board 802.11n WiFi
and
Bluetooth 4.0. WiFi, wireless keyboards, and wireless mice now work out of the box.

The Raspberry Pi 2 (left) and the Raspberry Pi 3 (right). Physically, there are
very few differences.

Specs

Here’s the complete specs for the Pi 3:

SoC: Broadcom BCM2837 (roughly 50% faster than the Pi 2)


CPU: 1.2 GHZ quad-core ARM Cortex A53 (ARMv8 Instruction Set)
GPU: Broadcom VideoCore IV @ 400 MHz
Memory: 1 GB LPDDR2-900 SDRAM
USB ports: 4
Network: 10/100 MBPS Ethernet, 802.11n Wireless LAN, Bluetooth 4.0

Force Full HD over HDMI


---------------------

In the next few steps we’ll be doing as much prep work while our SD card is still
mounted so when we boot up for the first time there’s nothing to do post-install.

cat <<EOF>/mnt/sdcard/boot/config.txt
disable_overscan=1
hdmi_force_hotplug=1
hdmi_group=1
hdmi_mode=16
EOF

Setup Raspberry Pi Update


--------------------------

rpi-update is a useful utility that will sync the latest kernel and firmware/boot
files to your Raspberry Pi. Let’s get this in place

wget -O /mnt/sdcard/usr/bin/rpi-update
https://raw.githubusercontent.com/Hexxeh/rpi-update/master/rpi-update
chmod +x /mnt/sdcard/usr/bin/rpi-update

Setup Wifi Firmware & Modules


---------------------------

Currently the wifi does not work out of the box without some newer firmware,
particularly the non-free firmware. Fix it by plopping these files into
/lib/firmware.
In future rpi updates this should be resolved.

First, grab the firmware files

wget -O /mnt/sdcard/lib/firmware/brcm https://github.com/RPi-Distro/firmware-


nonfree/raw/master/brcm80211/brcm/brcmfmac43430-sdio.bin
wget -O /mnt/sdcard/lib/firmware/brcm https://github.com/RPi-Distro/firmware-
nonfree/raw/master/brcm80211/brcm/brcmfmac43430-sdio.txt

Setup the module to load on boot


--------------------------------

printf "# load wifi\nbrcmfmac\n" > /mnt/sdcard/etc/modules-load.d/brcmfmac.conf

Set Root Password


----------------

This will set your root password, you can skip this step if your first boot will be
hooked up to a
monitor (as it will boot to run level 5 with the “first” boot screen allowing you
to set things like
account passwords, timezone, etc.). If you’re running headless or with a non-
graphical image
you’ll want to perform this.

read -s -p "Enter password: " pass


echo -n root:$pass | chpasswd -c SHA512 -R /mnt/sdcard

Now load the BCM chipset driver


---------------------------

modprobe snd_bcm2835

Fix: Firewall
Despite generally not caring for firewalld and the over-engineered approach to
“zones” I’ve found it does not work reliably on ARMv7 in either CentOS or Fedora.
Let’s remove it and move back to trusty old iptables.

systemctl stop firewalld


systemctl mask firewalld
Install the iptables service.

dnf install iptables-services

Now set things up.

systemctl enable iptables


service iptables save

Now edit your firewall rules like a sane human in /etc/sysconfig/iptables and when
you’re done
you can save them.

systemctl start iptables.service

================================================================================
AZARTICOLO:Installare Node.js su Raspberry Pi
================================================================================

Vediamo in questa guida come installare e configurare Node.js sul nostro Rapsberry
Pi.

nodejs

Passo dopo passo mostriamo quanto facile sia installare questo potente strumento
sul RPi.

1. Configurare il Raspberry Pi
-------------------------

Un passo che diamo per scontato, è l’aver una versione di Raspbian o NOOBS pronta e
funzionante.
La guida ufficiale spiega in modo esaustivo come fare.

2. Installare Node.js
------------------

Assicuratevi di avere una connessione internet attiva e aprite il terminale sul


RPi.

Installare una versione ARM di Node.js è diventato veramente facile:

wget http://node-arm.herokuapp.com/node_latest_armhf.deb
dpkg -i node_latest_armhf.deb

Non dovrebbe metterci troppo tempo a scaricarlo e installarlo.

Dopo aver eseguito i due comandi, consiglio di riavviare con reboot.

A questo punto per verificare che l’installazione sia avvenuta con successo,
lanciate il comando

node -v

che dovrebbe restituire la versione corrente di node e

npm -v
che restituisce la versione corrente del node package manager, necessario per
l’installazione rapida
di librerie.

Se volete installare l’ultima versione disponibile di Node.js consiglio di


guardarsi direttamente da qua:
Distribuzioni Node Js

quali distribuzioni son disponibili per sistemi linux-arm!

Dopodichè seguendo Installing Node JS on Raspberry Pi è possibile installare


facilmente la versione
voluta.

NB. E’ necessario che l’archivio di node scaricato sia espressamente per Linux-ARM.

3. Eseguiamo uno script di prova


----------------------------

Eseguiamo il classico script di Hello World!

touch app.js crea il file app.js.

Con vi app.js siamo in grado di editare il file e scriverci dentro questo:

var http = require('http');


http.createServer(function (req, res)
{
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

Ctrl+X per chiudere, Y per salvare e date l’invio per confermare.

Lanciamo dunque lo script con il comando node app.js, sulla console ci apparirà

Server running at http://127.0.0.1:1337/.

Se da browser ci rechiamo all’indirizzo: http://192.168.x.x:1337 vedremo la scritta


Hello World.

4. Eseguiamo lo script all’avvio del RPi


-------------------------------

Come fare per eseguire il server appena creato con Node.js ad ogni avvio del
Raspberry?
Semplice! E’ sufficiente inserire nel file /etc/rc.local il comando che segue
(prima dell’istruzione exit 0):

node /home/pi/Desktop/app.js &

E’ necessario inserire perchè l’esecuzione deve avvenire con i permessi


d’amministrazione,
specie se poi vogliamo fare in modo che il server piloti i pin GPIO etc.
Il percorso dev’essere assoluto, partendo dalla directory home. Nel mio caso app.js
si trova sul Desktop.
per modificare il file /etc/rc.local si può usare al solito il comando vi
/etc/rc.local ricordandosi
di salvare dopo aver apportato le modifiche volute.

How to Install the Latest Version of NodeJS, NPM and Express on the Raspberry Pi
----------------------------------------------------------------------

Please note that this blog post assumes that you have properly set up your
Raspberry Pi with the
Raspbian “wheezy” image and have SSH enabled. If you do not, please take a moment
to read
my earlier blog post, Super Easy Install of Raspbian “wheezy” on the Raspberry Pi
Using a Mac.
With that, let’s jump right in.

SETTING UP AND INSTALLING NODE

Create a node directory under the /opt directory.


This is where we’re going to store our version of node:
mkdir /opt/node
Go to http://nodejs.org/dist/ and find the latest distro with a linux arm version.
At the time of this writing, 11.3 was available.
The file you are looking for will be named something like node-v0.11.3-linux-arm-
pi.tar.gz but it
will have the words “linux” and “arm” in the name.

Right-click on the .gz file and copy the full path.

SSH into your Raspberry Pi


-----------------------

Use wget to pull the path you just copied:


wget http://nodejs.org/dist/v0.11.3/node-v0.11.3-linux-arm-pi.tar.gz
Use tar to unstuff the .gz file you just downloaded:
tar xvzf node-v0.11.3-linux-arm-pi.tar.gz
Copy the contents of the unstuffed directory to the /opt/node directory we created
earlier:
cp -r node-v0.11.3-linux-arm-pi/* /opt/node

This next part is where Matt and I deviate. I’m a fan of making things easy.
Had we been installing NodeJS on a desktop or laptop, we would be able to use node
from the
command line simply by typing “node [COMMAND]”. This was how I set that up.
We’re going to create a symbolic link to both node and npm and put those links
in /usr/local/bin:

ln -s /opt/node/bin/node /usr/local/bin/node
ln -s /opt/node/bin/npm /usr/local/bin/npm

Now restart the .bashrc as follows:

source ~/.bashrc

Now that .bashrc has been restarted, let’s verify that not only did our symbolic
link work, but
we have node and npm properly installed. First type node -v to see the installed
version of node
and then type npm -v to see the installed version of npm. You should see something
like the following:
pi@raspberrypi ~ $ node -v
v0.11.3
pi@raspberrypi ~ $ npm -v
1.2.25

INSTALLING EXPRESS
-------------------

Please note that this next section is completely optional and as of the latest RPi
OS,
seem to not work as listed here. Please use with caution.

To install Express, simply enter the following on the command line:

npm install -g express

You may see some warnings, that’s OK for now.


If you want to dig in further, you can review them and fix them at your leisure.

With Express properly installed, it’s now time to create our working directory.
However, we’re going to let Express do that for us.
The working directory that we’re going to create will be /var/www though depending
upon your setup,
the directory www may or may not exist yet.
For the purposes of this tutorial, we are assuming it does not yet exist.
Simply type the following into the command line:

cd /var
express -e www

There are several flags you can set and depending upon what you prefer, many
combinations.
To see all of them, type express –help in the command line.
You should see something like the following:

Usage: express [options]

Options:

-h, --help output usage information


-V, --version output the version number
-s, --sessions add session support
-e, --ejs add ejs engine support (defaults to jade)
-J, --jshtml add jshtml engine support (defaults to jade)
-H, --hogan add hogan.js engine support
-c, --css add stylesheet support (less|stylus) (defaults to plain
css)
-f, --force force on non-empty directory

Once Express successfully creates the necessary directory structure, the last step
before we turn
the sucker on is to jump into the www directory and let npm add the finishing
touches.
We do this as so (please note that I’ve chosen to add to the command which deviates
from
what Express shows. Without permissions, npm will not be able to install all the
dependencies
properly:
cd www && npm install

Again, you should see some warnings which you are welcome to go back and correct
but they will
not impact this process.

Once npm is done, it’s finally time to flip the switch and see if we made
Frankenstein or a flub:

node app.js

If all goes well, you should see the following message:

Express server listening on port 3000

Go out to your Raspberry Pi’s ip address at port 3000 and if you created
Frankenstein,
you should see something like this:

pi@raspberrypi ~ $ node -v
v0.11.3
pi@raspberrypi ~ $ npm -v
1.2.25

Congratulations!
You have successfully installed NodeJS, NPM and Express on the Raspberry Pi!

================================================================================
AZARTICOLO:Generate Self-signed SSL Certificate
================================================================================

Using HTTPS for your web application is a no-brainer, but sometimes it is not
intuitively clear on
how to get started on using SSL for your website. I'm going to be going over step-
by-step on
generating a self-signed certficate and testing it out on a Node.js web server.

Generating Private Key


-------------------

First let's generate a private key.


The private key is used to decrypt the data encrypted by the public key.
Only your server should have access to the private key.
The generated RSA key is 1024-bit triple DES encrypted.
It will ask you for a passphrase so make sure you remember it.

openssl genrsa -des3 -out server.key 1024

The output:

Generating RSA private key, 1024 bit long modulus


...............................++++++
..........................++++++
e is 65537 (0x10001)

Enter pass phrase for server.key:


Verifying - Enter pass phrase for server.key:
This will create a server.key file.

Note that if you do not want to use a passphrase for your key, you can remove it
from the private key.

openssl rsa -in server.key -out server.key

Generating a Certificate Signing Request


---------------------------------

Next we need to issue a Certificate Signing Request (CSR), which is responsible for
sending a
message to a Certificate Authority (CA) in order to apply for a digital certificate
which certifies
the ownership of the public key.
It will ask you for information for the certificate regarding your company and
location.
See the output after the command as an example.

openssl req -new -key server.key -out server.csr

The output:

Enter pass phrase for server.key:


You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:CA
Locality Name (eg, city) []:Los Angeles
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company
Organizational Unit Name (eg, section) []:Information Technology
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:[email protected]

Please enter the following 'extra' attributes


to be sent with your certificate request
A challenge password []:password
An optional company name []:My Company

This will create a server.csr file.

Generating Certificate
-------------------

Now we use the Certficate Signing Request file to self-sign a new X.509
Certificate, valid for 365 days.

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

The output:

Signature ok
subject=/C=US/ST=CA/L=Los Angeles/O=My Company/OU=Information
Technology/CN=localhost/[email protected]
Getting Private key
----------------

Enter pass phrase for server.key:

This will create the actual certificate server.crt file.

Using SSL Certificate with Node.js


-----------------------------

Incorporating the Self-signed Certificate in Node.js in relatively straightfowward.


We map the file contents for the Private Key and the SSL Certificate in the options
object for
the node https server, Try running the example below.

const https = require('https');


const fs = require('fs');

const options =
{
// Private Key
key: fs.readFileSync('./ssl/server.key'),

// SSL Certficate
cert: fs.readFileSync('./ssl/server.crt'),

// Passphrase for Private Key, if you used one.


passphrase: 's0m3P4sZw0rD',

// Make sure an error is not emitted on connection when the server certificate
verification against the list of supplied CAs fails.
rejectUnauthorized: false
};

const server = https.createServer(options, handlRequest);

function handlRequest(req, res)


{
res.writeHead(200);
res.end('Served over SSL.\n');
}

server.listen(9000);

Now open up your browser and head over to


https://localhost:9000.

You should get a browser warning like this one saying that the certificate could
not be validated.

This is normal since we're using this for development purposes. Go ahead and hit
Proceed to localhost.

Trusting The Certificate


--------------------

You probably noticed the ugly red x over the https lock icon since the certificate
could not be
validated by a CA.

In order to get the nice green lock we can tell our operating system to always
trust this certificate.

If you're on Mac OSX; Open up the Keychain Acess app and on the left sidebar click
on System
under Keychains and click on Certificates under Category.

Drag the certficate server.crt into here.

Now double-click on the certificate you just added and under Trust options, next to
When using
this certficate select the Always Trust option.

Enter your password when prompted and restart your browser.

Voilà, green lock.

Conclusion

It is standard practice to use a SSL certificate for web applications even if not
planning on
sharing confidential data with visitors. Having encrypted communication ensures
trust with the
user accessing your site. Hope this guide helped you get started on using SSL while
developing.

================================================================================
AZARTICOLO:How to install the Microsoft Core Fonts on Debian or Sparkylinux
================================================================================

To install the Microsoft Fonts in Linux, you have to install the Microsoft TrueType
core fonts package.

apt-cache search microsoft truetype core fonts

ttf-mscorefonts-installer - Installer for Microsoft TrueType core fonts

And now, install the package with apt-get:

apt-get install ttf-mscorefonts-installer

After you press <OK> and <Yes> to accept the Terms and Conditions in the TUI (text
user interface)
window that appears your installation will finish and you will be able to use both
the Microsoft and the
Ubuntu fonts in OpenOffice, LibreOffice or any other text editor.

The Microsoft most famous fonts are now available in your Linux:

Arial
Comic Sans
Times New Roman
Verdana
Webdings

For a better font rendering, do this:


ln -s /etc/fonts/conf.avail/10-autohint.conf /etc/fonts/conf.d/

After the next login you should notice a big difference in the font rendering.

================================================================================
AZARTICOLO: VLC is not supposed to be run as root. Sorry. – Solution
================================================================================

by SYED ALAM in LINUX, TROUBLESHOOTINGS

Today i captured one tutorial using recordmydesktop utility on my backtrack and


decided to view it
but unfortunately backtrack 5 Linux didn’t include a good media player to do
entertainment
when you get bored with dirty work.

Anyways, i installed vlc using following command ;

aptitude install vlc

And tried to run vlc as root i got error on my terminal ;

vlc

VLC is not supposed to be run as root. Sorry.


If you need to use real-time priorities and/or privileged TCP ports
you can use vlc-wrapper (make sure it is Set-UID root and cannot be run by non-
trusted users first).

This error says straight forward vlc can not be run as root privileged user.
What to do now? Don’t be panic. Here is the hacked solution 😀

vi /usr/bin/vlc

search for geteuid and replace it with getppid

Save file & Exit.

================================================================================
AZARTICOLO: Raspberry Pi - Raspbian Locale Settings
================================================================================

During installation of new packages, I get a "Setting Locale Failed". Therefore it


appears that my
locale settings have not been configured during the setup of my Raspberry Pi, so
now we are
going to fix this.

Example message:

perl: warning: Setting locale failed.


perl: warning: Please check that your locale settings:

LANGUAGE = (unset),
LC_ALL = (unset),
LC_CTYPE = "UTF-8",
LANG = "en_GB.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory

To fix this warning, we can run the following command to generate the settings:

A) First we need to install the latest locales

apt-get install locales

Output of rebuilding locales


Reading package lists... Done
Building dependency tree
Reading state information... Done
locales is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 57 not upgraded.

B) Next we will export our language:

export LANGUAGE='en_GB'
and export LC_All
export LC_ALL="en_GB.UTF-8"

Once we have done this, we can update our locale config and we should no longer get
this warning

C) dpkg-reconfigure locales

Here we can use the up down keys to scroll for your language settings, and the
space bar to select it.
Once done hit tab to tab to OK or Cancel.

To check our locale settings we can use the locales command.


As we see below, no more warnings.

LANG=en_GB.UTF-8
LANGUAGE=en_GB
LC_CTYPE="en_GB.UTF-8"
LC_NUMERIC="en_GB.UTF-8"
LC_TIME="en_GB.UTF-8"
LC_COLLATE="en_GB.UTF-8"
LC_MONETARY="en_GB.UTF-8"
LC_MESSAGES="en_GB.UTF-8"
LC_PAPER="en_GB.UTF-8"
LC_NAME="en_GB.UTF-8"
LC_ADDRESS="en_GB.UTF-8"
LC_TELEPHONE="en_GB.UTF-8"
LC_MEASUREMENT="en_GB.UTF-8"
LC_IDENTIFICATION="en_GB.UTF-8"
LC_ALL=en_GB.UTF-8

MN4N2-AHA9S-DS3R2-7BCWS-VN7YA licenza vnc

================================================================================
AZARTICOLO: Control LED Using GPIO Output Pin
================================================================================
By Matt on June 10, 2012 Hardware, Python, Tutorials & Help

The circuit below shows to turn an LED on and off using a Raspberry Pi GPIO pin
configured as
an output. It uses the output pin to turn on a transistor which allows the LED to
draw current
from the supply.

The following header pins are required :

Header Pin 2 : 5V
Header Pin 6 : Ground
Header Pin 11 : GPIO

The Header Pins are defined in my Raspberry Pi Header Pin page.


You can use whatever GPIO pin you like but I used pin 11 for my tests.

The LED is a standard 5mm red type with a forward voltage of 2V.
The transistor could be a BC547, BC548 or equivalent.

Resistor R1 limits current through the LED from the 5V pin.


If the voltage drop across the LED is 2V then voltage across the
resistor is 3V.
So current is 3/560 = 5.4mA.
Resistor R2 limits current from the GPIO pin.
GPIO is either 0v or 3.3V so the maximum current into base of transistor
is 3.3/27000 = 120uA.
Assuming the gain of the transistor is 200 a base current of 120uA
would allow a
maximum of 24mA (120uA x 200) to pass through the LED.

R1 could be increased you just need to make sure you allow enough current to power
your LED.

R2 could be increased and this would reduce the current drawn from the GPIO pin but
it would
reduce the maximum current allowed to flow through the transistor.

Note : As with all connections you make to the Pi’s PCB you must double check
everything.
Making a mistake in your wiring could damage the CPU as some of the GPIO pins are
connected
straight to the Broadcom chip.

I’ve modified some of the details on this page thanks to feedback from Gert (see
comments below).

Python Code
----------

In order to control GPIO pins in Python you must install the RPi.GPIO library.
Installing the library is easy if you follow my RPi.GPIO Installation Guide.
Once installed you can use the following Python script to toggle the GPIO output on
header pin 11 (GPIO17) :

import RPi.GPIO as GPIO


import time

# Use physical pin numbers


GPIO.setmode(GPIO.BOARD)
# Set up header pin 11 (GPIO17) as an output
print "Setup Pin 11"
GPIO.setup(11, GPIO.OUT)
var=1
print "Start loop"
while var==1 :
print "Set Output False"
GPIO.output(11, False)
time.sleep(1)
print "Set Output True"
GPIO.output(11, True)
time.sleep(1)

This script will continue running until you press CTRL-C.

Python scripts must be run as the super user when they are using the GPIO library.
So if your script is called “ledtest.py” you would run it by typing :

python ledtest.py

The script should print text messages to the command line while toggling the state
of pin 11.
If your circuit is correct then the LED should turn on and off every one second.

================================================================================
AZJSON
================================================================================

Un JSONObject non e' altro che una LinkedHashMap ovvero dei vettori (accessibili
via indice) di
hash ovvero di coppie nome valore, ovvero del tipo <String nome,Object valore>
Infatti viene al suo interna definita come:

LinkedHashMap<String, Object> nameValuePairs = new LinkedHashMap<String, Object>();

In Realtà in un oggetto JSON gli elementi in esso contenuti possono essere solo 3
categorie:

- JSONOBject
- JSONArray
- tipi primitivi: String,Integer,Boolean,Double,Long,NULL
(nel nostro caso si utilizzano solo Stringhe)

Le JSONArray poi non sono altro che delle ArrayList, ovvero dei vettori accessibili
via indice,
ma al contrario delle LinkedHashMap, le entry delle ArrayList sono anonime,
possiedono il solo valore,
il nome e' in sostanza dato dall'indice dell'array. Sono definite come:

List<Object> values = new ArrayList<Object>();

L' ArrayList contiene oggetti che nel nostro caso possono essere solo oggetti
JSONObject

Ora il nostro oggetto JSON, e' LinkedHashMap denominata all suo interno
nameValuePairs,
i cui elementi sono solo due hash, di nome "controls" e "formats", ed il cui valore
e' rappresentato
per ambedue da una JSONArray.
L' JSONArray "controls" che al suo interno ha 34 oggetti
e "formats che a sua volta e' formato da 12 oggetti

Ogni elemento della ArrayList "controls" e' formata da un oggetto JSON


semplificato, ovvero
trattasi sempre di una LinkedHashMap, ovvero di un vettore di hash (nome,valore) ma
stavolta il
valore e' di tipo primitivo, ovvero e' sempre di tipo <String> In controls ogni
elemento ha pertanto
11 attributi definiti come predetto:

"id":
"type"
"min"
"max"
"step"
"default"
"value"
"dest"
"flags"
"group"

esiste solo un eccezione: l'hash denominata "menu" ha come valore un oggetto JSON!
Tale oggetto e' composto da una serie di Hash di tipo semplice:
il nome e' una stringa corrispondente alla posizione della stringa nel vettore che
memorizza il menu,
il valore della coppia hash e' una stringa.
Il menu viene utilizzato allorche' nella hash "valore" andrebbe indicata una
stringa, ma avendo
deciso di trasformarla in numerico, allora tale valore coincide col indice del menu
in cui e'
memorizzata la stringa desiderata.

"0": "Disabled",
"1": "50 Hz",
"2": "60 Hz",
"3": "Auto"

"formats" invece e' una JSONArray contenente 14 elementi a loro volta oggetti JSON
Questi sono 7 coppie hash (nome,valore) il cui valore e' sempre di tipo <String>

"id": "1",
"name": "YUYV 4:2:2",
"compressed": "false",
"emulated": "false",
"current": "true",
"resolutions":
{
"0": "32x2592"
},

"currentResolution": "255"

Anche qui vi e' l'eccezione data da "esolutions" che in e' un JSONObject composto
da una sola
hash contenente la stringa che rappresenta le dimensioni

Ora ad ogni passo estraggo dall oggetto JSON la componente che mi interessa e la
memorizzo
in ItemsApp items composto dalle seguenti array_list <String>

--------------------------------------------------------------------------------
nome = key_name key_name key_name
"menu"
tipo = "ARRAY" "OBJECT" "STRING" MENU
"MITEM"

valore = len_array_str key_value valore


num_coppie_obj
o elemento_json.length
se key_value = NULL

oggetto = stringa_array stringa_json_obj "NONE"


stringa_json_obj

--------------------------------------------------------------------------------
LO STACK
--------------------------------------------------------------------------------

Per percorrere all'indietro l'oggetto JSON mi servo di uno stack di stringhe dove
memorizzo
l'oggetto contenitore come stringa_json del contenitore stesso.

In realta' siccome l'elemento di posto 0 e' l'intero oggetto sarebbe sufficente che
lo stack
memorizzasse i nomi degli oggetti attraversati, ovvero il percorso fino
all'elemento attuale e
non tutto l'oggetto che non occorre affatto!

Stack<String> json_stack

on Resume() : Creo lo stack se non esiste json_stack = new Stack<>();


aggiorna_item() : Memorizza indice dello Stack in L. [json_stack_index]
carica_oggetti() : Pulizia Stack se ricarico (pos=-1) json_stack_index = -1;
json_stack.clear();

Async BackJSONTask() ->


onBackPressed() -> json_stack_back ():
Per tornare indietro devo prima ricaricare dallo stack
l'oggetto contenitore
e poi l'oggetto che a sua volta lo conteneva!

// Ricarico oggetto contenitore


json_stack_index--;
stringa_json = json_stack.pop ();

if (json_stack_index > -1)


{ // Ricarico oggetto contenitore padre
json_stack_index--;
stringa_json = json_stack.pop ();
}

json_parser_array(): Carico nello stack l'intera matrice prima di esaminare gli


elementi
json_stack_index++;
json_stack.push(stringa_json);
json_parser_object(); Carico nello stack l'intero oggetto prima di esaminare gli
elementi
json_stack_index++;
json_stack.push(stringa_json);

menu_editor(pos): Prelevo oggetto padre con json_stack_back () perche' e' qui che
e' contenuto
valore da modificare
if (json.has("value"))
json.putOpt("value",
Integer.toString(position_to_edit));

setta_nuovo_valore () Richiamato da item_editor () deve prelevare dallo stack il


contenitore per
poter memorizzare il nuovo valore
json_stack_index--;
stringa_json = json_stack.pop ();
if (json.has("value"))
json.putOpt("value",
Integer.toString(position_to_edit));
---------------------------------------------------------------------------------
Analisi:
---------------------------------------------------------------------------------

A) J0 : intero JSON_object

Quando viene caricato il file nello stack al posto 0 ci finisce l'intero oggetto
json
json_parser_object itera poi tutti i nomi dei suboggetti (JSONARRAY "controls" e
"formats")
ed infila i nomi in items (items.add()).

Nota
----

Basterebbe lo stack vuoto e mi andrei a prendere l'intero oggetto!


Inoltre non devo lavorare sulle copie degli oggetti ma utilizzando i path sugli
oggetti stessi!
In questo modo facendo una modifica non dovrei ricostruire l'intero oggetto.

A video appare solo controls 34 e formats 14

B) J1: intera json_array "controls" ma in forma anonima

Se premo Controls viene chiamato json_parser_array con l'oggetto json_array


"controls" senza nome
Notare che non ho mai memorizzato il nome "controls" ovvero la scelta effettuata!
E tuttavia nello stack viene inserita l'intera matrice ma nel formato anonimo:

[
{
"name": "User Controls",
"id": "9961473",
"type": "6",
"min": "0",
"max": "0",
"step": "0",
"default": "0",
"value": "1",
"dest": "0",
"flags": "68",
"group": "1"
},
{
"name": "Brightness",
"id": "9963776",
"type": "1",
"min": "0",
"max": "100",
"step": "1",
"default": "50",
"value": "50",
"dest": "0",
"flags": "32",
"group": "1"
}
]

Cioè nel formato anonimo, come insieme di oggetti JSON anonimi.

A questo punto, in items finiscono tutte le entry ma in formato conciso, ovvero


emetto solo
le hash che si chiamano nome come key_name value come value se esiste altrimenti il
numero
di elementi dell'intera entry.

Se flag_hidden=false allora chiamerei json_parser_object() che memorizzerebbe e


visualizzerebbe
la entry per intero

A video appaiono tutte le entry della json_array "controls" ma in forma concisa

C) J2 : Intera Entry name:"User Controls"


che e' un JSON_OBJECT ma mi sono perso ancora una volta la scelta
effettuata ovvero
che era stata selezionata la prima entry della JSONArray in items ci finiscono
tutte le componenti
dell entry prescelta perche' sono primitives e non oggetti

d) J2 : Intera Entry name:"User Controls" POP E PUSH

Scelgo di modificare "value", dopo aver accettato dall utente il nuovo valore
prelevo dallo stack
L'intera entry "User Controls" gli modifico il valore e poi la rimando di nuovo
nello stack

Avendo memorizzato gli interi oggetti ora l'oggetto modificato "User Controls"
andrebbe
modificato anche in tutti gli oggetti che si trovano nello stack almeno in quello
iniziale
ma avendo perso le scelte di come sono arrivato non posso farlo!

================================================================================
AZARTICOLO:How to Install the No-IP DUC on Raspberry Pi
================================================================================

You will be able to install No-IP’s Dynamic Update Client on Raspberry Pi in just a
few minutes
using Terminal. Installing the service is simple to do, and requires little
knowledge of Linux.

You will need to create a directory for the client software to be installed.

Open Terminal and type the following. After each entry press “Enter“.
mkdir /home/pi/noip
cd /home/pi/noip

After creating the folders for the DUC it is time to download the software.

Within the Terminal window type the following. After each entry you will press
“Enter”.
wget http://www.no-ip.com/client/linux/noip-duc-linux.tar.gz
tar vzxf noip-duc-linux.tar.gz

Next navigate to the directory you created to locate the downloaded files.
cd noip-2.1.9-1

Now install the program.


make
make install

After typing “make install” you will be prompted to login with your No-IP account
username and password.

After logging into the DUC answer the questions to proceed. When asked how often
you want the
update to happen you must choose 5 or more.
The interval is listed in minutes, if you choose 5 the update interval will be 5
minutes.
If you choose 30 the interval will be 30 minutes.
/usr/local/bin/noip2

To confirm that the service is working properly you can run the following command.
noip2 -S (Capital “S”)

================================================================================
AZARTICOLO:Configurare NO-IP Su Raspbian Per Raggiungere Il Raspberry Da Remoto
================================================================================

GNU/Linux by Geek - 5 marzo 20141


raspberry-pi-berries

Il giorno che presi il Raspberry, una volta arrivato il pacco mi chiesi:


“E adesso? Che ci faccio?”. Ecco, iniziando il mio nuovo lavoro mi si è riaccesa
la scintilla per lo
smanettamento e ora ho in testa tanti piccoli progettini (alcuni utili, altri meno)
che possono essere
attuati sulla single board più famosa del mondo.

Ho iniziato a pensare ad una configurazione “standard” per il Raspberry, una


configurazione basilare
che mi permetta di gestirlo, aggiornarlo, raggiungerlo in remoto ecc. senza alcun
problema.
Ho quindi fatto qualche googlata in vecchio stile e la seguente per me è la
configurazione minima
indispensabile da avere sul Raspi:
Raspbian
Firmware updater by Hexxeh
Accesso FTP
Accesso SSH
Accesso da remoto

Sembrano tutte cose banali e scontate, ma su uno strumento come il Raspberry è


tutta roba
(a mio avviso) davvero utile. Con questo articolo voglio focalizzarmi sull’accesso
da remoto visto che
il resto è tutto pre-configurato o facilmente installabile/configurabile.

Innanzitutto serve un DNS dinamico (Dynamic DNS).


Cosa è? Il Dynamic DNS (DDNS) è un servizio che permette di associare l’ indirizzo
pubblico
del router sul quale è nattato l’ indirizzo privato della macchina host ad un DNS,
in modo che
questo sia sempre raggiungibile, anche al cambio di IP imposto dal router.
Questo significa che bisognerà scrivere nel router l’ indirizzo IP fisso dell’ host
(il Raspberry nel nostro caso) in modo che il router sappia DOVE trovarlo.
Successicamente NO-IP si preoccuperà di aggiornare i record DNS ad ogni cambio di
indirizzo pubblico del router.

Requisiti:

Raspbian

Indirizzo IP statico assegnato al raspi (leggete nota a fine articolo per una
indicazione generica)
Procedimento – Creazione account:

Innanzitutto procediamo con la creazione di un account GRATUITO su NO-IP.


L’ account sarà sempre disponibile e sempre gratuito, ovviamente con alcune
limitazioni,
per esempio non potrete scegliere l’ “estensione” del dominio, ma non
preoccupatevi.

Recatevi su http://www.noip.com/ e registratevi


Controllate la mail e verificate l’ account
A questo punto loggatevi e cliccate su “ADD HOST”
Nel campo hostname inserite il dominio che volete (esempio: pippo.pluto)
Come host type lasciate il tipo A
Come indirizzo IP inserite il vostro attuale indirizzo IP che potete scoprire
andando su www.ilmioip.it
Cliccate sul bottone arancio a fine pagine “add host”
Fine
Procedimento – Installazione e configurazione NO-IP.
Ora dovremmo configurare in modo corretto anche NO-IP sulla nostra Raspbian.

Aprite il terminale
Digitate: mkdir /home/pi/noip
Ora spostatevi nella cartella con: cd /home/pi/noip
Quindi scaricate NO-IP tramite: wget http://www.no-ip.com/client/linux/noip-duc-
linux.tar.gz
Estraete quindi l’ archivio: tar vzxf noip-duc-linux.tar.gz
Ora entrate nella cartella estratta con: cd noip-2.1.9-1
Ora date: make
E per iniziare l’ installazione e la configurazione: make install
Inserite la vostra mail di registrazione e la password quando richiesto
Ora avviate il servizio con: /usr/local/bin/noip2
Fine
Bonus – Avviare NO-IP all’ avvio del Raspi:

Create un nuovo file tramite: vi /etc/init.d/noip2


Incollateci questo:#######################################################
#! /bin/sh
case "$1" in
start)
echo "Starting noip2."
/usr/local/bin/noip2
;;
stop)
echo -n "Shutting down noip2."
killall -q -TERM /usr/local/bin/noip2
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
esac
exit 0
#######################################################
Ora date i permessi al file appena creato con: chmod 755 /etc/init.d/noip2
E per finire: update-rc.d noip2 defaults
Fine
Port Forwarding:

Ricordatevi di abilitare il PF sull’ IP statico del dispositivo e nattare le porte


che vi servono.
Per esempio se avete assegnato l’ IP 192.168.0.567 al Raspi e volete usare l’ SSH
in remoto
(quindi quando non siete sulla vostra rete domestica, ma per esempio al McDonalds)
dovete inserire
tra le regole del vostro router l’ IP del raspi e inserire come porta locale la 22
(SSH) e come porta
pubblica una porta “qualunque”, per esempio la 10456. In questo modo dopo avere
settato anche il NO-IP
in modo opportuno se provate a collegarvi potete usare:
indirizzodnsdinamico.noip.com:10456 et voilà.

Il gioco è fatto.

Configurare NO-IP su Raspbian per raggiungere il Raspberry da remoto, 4.6 out of 5


based on 11 ratings

===================================================================================
=========
AZARTICOLO:NOOBS (New Out of Box Software)
===================================================================================
=========
https://github.com/raspberrypi/noobs

NOOBS (New Out Of Box Software) - An easy Operating System install manager for the
Raspberry Pi
http://www.raspberrypi.org/downloads

An easy Operating System installer for the Raspberry Pi


NOOBS is designed to make it easy to select and install operating systems for the
Raspberry Pi
without having to worry about manually imaging your SD card.
The latest official release of NOOBS can be downloaded from
http://downloads.raspberrypi.org/NOOBS_latest

OS Boot Selector
--------------

After multiple OSes have been installed, you can select which OS to boot through
this selection
window that is automatically displayed. NOOBS will remember your choice and boot
this OS by
default unless a different option has been selected within 10 seconds.

Note that if only one OS is installed then the boot selector will not be displayed
and the OS will
be automatically booted.

Troubleshooting
-------------

What to do if your SHIFT keypress isn't detected

Try pressing shift only when the grey splashscreen is displayed rather than holding
it from boot up.

How to boot into "Safe Mode"


-------------------------

To boot into a basic busybox shell rather than launching the NOOBS GUI, you can
either:

Append rescueshell to the argument list in the recovery.cmdline file which is found
in the root
NOOBS directory.

Insert a physical jumper between pins 5 & 6 of GPIO header P1.


If you have external hardware or an addon board connected to the GPIO header,
you may find that pin 5 is being pulled low and accidentally triggering "Safe
Mode".
To prevent this you can append disablesafemode to the argument list in the
recovery.cmdline file
which is found in the root NOOBS directory.

How to enable using the GPIO to trigger entering Recovery Mode


------------------------------------------------------
To force Recovery Mode to be entered on boot and to show the NOOBS interface,
you normally press the SHIFT key during bootup.
If you don't have a keyboard or the SHIFT keypress isn't being detected, you should
complete
the following steps to force the NOOBS interface to be displayed on boot:

Append gpiotriggerenable to the argument list in the recovery.cmdline file which is


found in the root NOOBS directory.

Reboot

To force Recovery Mode being entered on boot, connect GPIO pin 3 on header P1 to
GND (pin 25).
If GPIO pin 3 remains unconnected then it will boot through to the installed OS as
normal.

How to force Recovery Mode being entered on boot (overrides GPIO or keyboard input)
-------------------------------------------------------------------------

Alternatively, if you are unable to use either the GPIO or keyboard to trigger
entering
Recovery Mode, you can:

Append forcetrigger to the argument list in the recovery.cmdline file which is


found in the root
NOOBS directory.

Reboot

Note that with this option enabled, the Recovery Mode will be displayed every time
you boot from
your NOOBS card (until you edit recovery.cmdline again).

How to disable using the keyboard to trigger entering Recovery Mode


----------------------------------------------------------

In some rare cases, you may find that NOOBS incorrectly detects a SHIFT keypress
from your
keyboard regardless of the presence of user input.
In such cases it may be helpful to disable using the keyboard to trigger Recovery
Mode being entered.

To prevent a SHIFT keypress from entering Recovery Mode on boot


(maybe you have a problematic keyboard which is erroneously triggering every time
you boot), you can:

Append keyboardtriggerdisable to the argument list in the recovery.cmdline file


which is found in the root NOOBS directory.
Reboot

How to change display output modes


------------------------------
By default, NOOBS will output over HDMI at your display’s preferred resolution,
even if no
HDMI display is connected. If you do not see any output on your HDMI display or are
using the
composite output, press 1, 2, 3 or 4 on your keyboard to select HDMI preferred
mode,
HDMI safe mode, composite PAL mode or composite NTSC mode respectively.

If you don't have a keyboard, you can still change the display mode used by NOOBS
through
editing the recovery.cmdline file in the root NOOBS directory prior to first boot
and appending
the following argument:

display=<display mode number> (e.g. display=1 or display=3)

================================================================================
AZARTICOLO:NOOBS partitioning explained
================================================================================
https://github.com/raspberrypi/noobs.wiki.git
NOOBS partitioning (and booting) explained
-----------------------------------------------------------------

Note that this was written for NOOBS v1.3.x / v1.4.x and the partition numbering
has changed
slightly in NOOBS v1.5.x

The multiple partitions that NOOBS divides your SD card into (at least 5) can be
quite overwhelming
and confusing. This page will try and explain how it all works, and illustrate how
NOOBS differs from
the 'traditional' standalone images.

Non-NOOBS partitioning
------------------------------------

Before you can understand how NOOBS partitioning works, you need to understand how
standalone
partitioning works on the Raspberry Pi, so go and read that page if you haven't
already.

More partition naming theory


-------------------------------------------

For historical reasons (only 4 'slots' in the partition table), hard-drives and SD
cards can only
have a maximum of 4 primary partitions. To work around that limitation, one of
those primary
partitions can optionally be an extended partition.
An extended partition can contain an unlimited number of logical partitions inside
it.
Under Linux, the primary partitions are always numbered 1-4 (i.e. seen as
/dev/mmcblk0p1 -
/dev/mmcblk0p4 on the Pi), and any logical partitions are always numbered 5 and
above
(i.e. seen as /dev/mmcblk0p5 and above on the Pi).

NOOBS partitioning
------------------------------

When NOOBS is first copied to a FAT-format SD card, there's just a single partition
taking up
all the space on the card, and this is where the files from the NOOBS zipfile get
written to.
In tabular form it looks like:

Primary partition Logical partition Type Label Contents

1 FAT New Volume NOOBS boot files & initramfs, OS recovery images

The only difference between NOOBS and NOOBS lite is that NOOBS lite doesn't include
any
OS recovery images.

NOOBS bootup (low-level)


----------------------

When the Raspberry Pi is powered on with a NOOBS card inserted, it:


- Loads and runs bootcode.bin from the FAT-format /dev/mmcblk0p1, exactly as it
does for
standalone images. (This behaviour is built into the BCM2835's internal firmware
on all Pis, and
so can't be changed.)

- bootcode.bin then spots that start.elf is missing, so it loads and runs


recovery.elf instead.
- Running recovery.elf then switches the firmware into "NOOBS mode"
- it uses recovery.img instead of kernel.img,
recovery.cmdline instead of cmdline.txt,
and it sets the root filesystem to recovery.rfs.
- recovery.elf then reads recovery.cmdline and loads and runs recovery.img (the
Linux kernel),
passing it the entire command-line that it read from recovery.cmdline and
telling it to load
recovery.rfs as the root filesystem (an initramfs containing various scripts and
the
NOOBS GUI application).

What happens next depends on which 'mode' NOOBS is operating in...

NOOBS bootup (setup mode)


------------------------

If runinstaller is present in the kernel command-line, then this must be the first
time NOOBS
has been booted, so it enters 'setup mode'. It then:

- Automatically shrinks the first (and only) partition /dev/mmcblk0p1, making it


just large enough
to hold whatever files it contains, and labels it as 'RECOVERY'.
For NOOBS lite this partition will have a size of approximately XMB;
for NOOBS this partition will have a size of approximately XGB.

- Creates a new large empty extended partition /dev/mmcblk0p2, using up the vast
majority of
the remaining card space.
- Creates a new small (32MB) ext4-format partition /dev/mmcblk0p3 at the end of the
card,
and labels it as 'SETTINGS'. This is used to store files telling NOOBS which OSes
are installed
(and what partitions they're installed on), which OS should be loaded by default,
which language/keyboard NOOBS should use, etc.

- Removes runinstaller from recovery.cmdline to prevent this process from being


triggered again.

- The settings are stored on a small auxiliary partition rather than the same
/dev/mmcblk0p1
partition as everything else. This is because of the NOOBS 'prime directive' -
"NOOBS never
writes to the first FAT partition.
FAT partition the first, NOOBS no writee...".
By never writing anything to the first partition (after the 'setup mode' has
finished),
this ensures that the first partition can never become corrupted;
and so NOOBS 'recovery mode' will always be accessible (to allow OSes to be re-
installed),
no matter what happens to the rest of the SD card.

This then changes the partitions to:

--------------------------------------------------------------------------------
Primary partition Logical partition Type Label Contents
--------------------------------------------------------------------------------
1 FAT RECOVERY NOOBS boot files & initramfs, OS recovery images
2 extended Any logical partitions
3 ext4 SETTINGS NOOBS settings
--------------------------------------------------------------------------------

NOOBS bootup (recovery mode)


--------------------------

If NOOBS detects that no Operating Systems have been installed yet, or if the user
is pressing
the Shift key (or any of the other trigger actions are in effect), NOOBS enters
'recovery mode'.
This displays the OS-installation menu, allowing the user to choose which OS(es) to
install.
Refer to the normal documentation for more details a about this menu.

Install menu
----------

As you may have guessed, the "Available space" displayed here is the size of the
extended
/dev/mmcblk0p2 partition, which is where all the OSes get installed to.

NOOBS datafiles
---------------

In contrast to the standalone images described earlier (which contain raw


partitions),
NOOBS instead uses (compressed) tarballs of the partition contents, along with a
bunch of settings
files. NOOBS is responsible for actually creating the partitions on the SD card
itself, which means
the partitions are always created at the "correct" size in the first place, there's
no need to resize
them later. And unlike the low-level raw partitions, the tarballs don't store
unused disk blocks.

NOOBS OS installation
---------------------------------

For the first example, let's assume that the user is installing just Raspbian.
The partitions.json (which can be viewed online here) then specifies which
partitions should be created,
how big they should be, and which filesystems they should use.
In this example it would create a 60MB FAT partition (/dev/mmcblk0p5), format it,
and extract
the contents of boot.tar.xz to it.

As the root partition has want_maximised: true it would then create an ext4
partition
(/dev/mmcblk0p6) filling up the entirety of the rest of the extended partition,
format it, and
extract the contents of root.tar.xz to it.

This gives us the full partition layout shown in the table earlier.
It then runs the partition_setup.sh script which mounts these new partitions, and
edits files
(typically just cmdline.txt on the boot partition and /etc/fstab on the root
partition) to tell
Raspbian which partitions it got installed to.

This allows Raspbian to adjust itself to being stored on /dev/mmcblk0p5 and


/dev/mmcblk0p6
instead of /dev/mmcblk0p1 and /dev/mmcblk0p2.

And finally it updates the settings partition with details of the OS we just
installed.

--------------------------------------------------------------------------------
Primary partition Logical partition Type Label Contents
--------------------------------------------------------------------------------
1 FAT RECOVERY NOOBS boot files & initramfs, OS recovery images
2 extended Any logical partitions
5 FAT boot Raspbian boot files
6 ext4 root Raspbian root filesystem
3 ext4 SETTINGS NOOBS settings
---------------------------------------------------------------------------------

If instead we were installing Raspbian and ArchLinux then we might end up with
ArchLinux's boot
partition as /dev/mmcblk0p5, ArchLinux's root partition as /dev/mmcblk0p6,
Raspbian's boot
partition as /dev/mmcblk0p7 and Raspbian's root partition as /dev/mmcblk0p8.
As both Raspbian's and ArchLinux's partitions.json file specify one of their
partitions as want_maximised: true then we'd end up with two small boot partitions
and two
large-as-possible root partitions.

NOOBS never 'wastes' any space on an SD card.

---------------------------------------------------------------------------------
Primary partition Logical partition Type Label Contents
---------------------------------------------------------------------------------
1 FAT RECOVERY NOOBS boot files & initramfs, OS recovery images
2 extended Any logical partitions
5 FAT boot ArchLinux boot files
6 ext4 root ArchLinux root filesystem
7 FAT boot1 Raspbian boot files
8 ext4 root1 Raspbian root filesystem
3 ext4 SETTINGS NOOBS settings
---------------------------------------------------------------------------------

Update for NOOBS v1.5 and later


-----------------------------

To accommodate Win10IoT, the partition layout has changed from v1.5 onwards.
Instead of the SETTINGS partition being fixed on the 3rd primary partition, it is
now located in
the first logical partition within the extended partition. This would change the
above layout as follows:
---------------------------------------------------------------------------------
Primary partition Logical partition Type Label Contents
---------------------------------------------------------------------------------
1 FAT RECOVERY NOOBS boot files & initramfs, OS recovery images
2 extended Any logical partitions
5 ext4 SETTINGS NOOBS settings
6 FAT boot ArchLinux boot files
7 ext4 root ArchLinux root filesystem
8 FAT boot1 Raspbian boot files
9 ext4 root1 Raspbian root filesystem
---------------------------------------------------------------------------------

Because of this partition change it is not advisable to 'upgrade' the version of


NOOBS on an
existing SD card from a version prior to v1.5 to one at v1.5 or later.

NOOBS bootup ('boot mode')


-------------------------

If the user isn't pressing the Shift key, and (using the information stored on the
settings partition)
NOOBS detects that only one bootable Operating System has been installed, it
automatically boots
that Operating System.

It does this by reading the settings partition to determine the boot partition for
that OS, and
then instructs the firmware to "soft-reboot" using the OS's boot partition. This
then 'reboots'
the firmware and loads start.elf from the specified partition
(typically /dev/mmcblk0p5 if only one OS is installed) and then proceeds the same
as the standalone
boot described at the very top of this page - start.elf loads kernel.img and reads
cmdline.txt,
and then kernel.img uses the command-line that was passed to it to determine which
partition
the root filesystem is stored on (typically /dev/mmcblk0p6 if only one OS is
installed), and loads
the rest of the system from there.

If instead multiple Operating Systems have been installed, NOOBS then displays the
OS-boot menu,
allowing the user to choose which OS(es) to boot. Boot menu Once the user has
selected an option
(or if the menu times out and defaults to the last-booted option) then the boot
proceeds as
described immediately above, with NOOBS using the information on the settings
partition to
determine which partition to "soft-reboot" as the boot partition.

If using the autoboot.txt feature described here then bootcode.bin immediately


"soft-reboots"
to the specified partition at power-on, and skips loading NOOBS entirely.

--------------------------
Booting RISC OS within NOOBS
--------------------------

The one small caveat to the above is that RISC OS doesn't understand partition
tables,
and so it has to be installed to a specific partition at a specific offset.
This is what the riscos-boot.bin file is for, and why the RISC OS 'root' partition
is still stored
as a raw partition and not as a tarball.
However NOOBS handles all these details for you automatically, and it's still
possible to install
other OSes alongside RISC OS.

================================================================================
AZARTICOLO: uv4l : Tutorials for RaspberryPi
================================================================================

https://www.linux-projects.org/uv4l/tutorials/
Overview
Features
Installation for ARM (Raspberry Pi)
Installation for x86-64
Documentation

Tutorials

RESTful API
Manuals

uv4l core
uv4l-server
uv4l-raspicam
uv4l-uvc
uv4l-mjpegstream
uv4l-raspidisp
uv4l-xscreen
uv4l-dummy
Demos
Downloads
RPi VideoConference Demo OS
xmpp-bridge
TC++PL exercise solutions
Drivers
et61x251
sn9c10x
w996[87]cf
zc0301
Contacts

Tutorials

Tutorials for RaspberryPi


----------------------------------------

First of all, if you have never installed UV4L on Raspbian Wheezy or Raspbian
Jessie, do it by
following these instructions, otherwise upgrade UV4L to the latest version:

raspberrypi ~ $ apt-get update


raspberrypi ~ $ apt-get upgrade

Below is a list of some examples of how to use the UV4L suite of modules in
combination with
some applications. To show you the complete examples, I will be assuming that you
have not
installed the recent uv4l-raspicam-extras optional package yet, which provides a
system service
that automatically loads all the installed uv4l modules at boot. Remember that, in
all the cases,
to eventually “unload” uv4l, it’s enough to kill the corresponding system process.
Almost all the examples have been originally tested on the (old) Raspberry Pi 1 and
Compute Module 1.
The Raspberry Pi 2 and greater can perform much better in all the cases where the
CPU would
be a bottleneck.

Record an H264 video at full 1920×1080 resolution, 30 fps


Motion
Capture and display with OpenCV
Use the Camera Board on the Rpi as a (virtual) camera plugged into another PC
Set up a real-time Streaming Server (RTSP)
FFmpeg Server & avconv
Setup an RTMP Server (in H264 full res, 30fps) with crtmpserver and FFMpeg
Full fps, Live Text Overlay (over video)
Real-time Object Detection and Object Tracking
Real-time HTTP/HTTPS Streaming Server with the native uv4l-server module
Compute Module: stereoscopic vision
Compute Module: use Dual Cameras separately
Start or Join a Multi Peer-to-Peer Audio/Video Conference with WebRTC
Live Desktop & Audio Streaming to the browser with WebRTC
How to broadcast or have bidirectional live audio and video conferences to/in a
Jitsi Meet Room over the Web
Webinars and Video Conferences in Full HD with the Janus WebRTC Gateway
UV4L for the Internet of Things with WebRTC Data Channels
Turn any MJPEG stream (e.g. from an IP camera) into a virtual camera
Example of custom web app in HTML5 and plain JavaScript: face detection on a video
stream from a camera in the network

===================================================================================
=========
AZARTICOLO:Project List
===================================================================================
=========
https://rbnrpi.wordpress.com/project-list/

This page contains a list of my projects for the Raspberry Pi

1 WiFi to ethernet adapter for an ethernet-read TV


2 Setting up Wireless motion-detect cam
3 A musical 12-tone alarm for the Raspberry Pi (part 1)
4 A musical 12-tone alarm for the Raspberry Pi (part 2)
5 A musical 12-tone alarm for the Raspberry Pi (part 3)
6 Mozart Musical Dice Game
7 A musical 12-tone alarm for the Raspberry Pi (part4)
8 Developing Music for Sonic Pi 2
9 Sonic Pi 2 plays Bach with expression!
10 Adding a new sample based flute voice for Sonic Pi
11 Grand Piano sample based instrument for Sonic Pi 2
12 Sonic Pi glass harmonica emulator
13 An improved sample based flute voice for Sonic Pi
14 Harp sample based voice for Sonic Pi
15 Sonic Pi plays church bells, using a sample based chimes voice
16 Playing with live coding and samples
17 Sonic Pi: accessing the cutting edge
18 Mozart Dice Generated Waltz: revisited with Sonic Pi
19 Raspberry Pi: Control GPIO and your Pi Camera using your phone
20 AutoBoot for Telegram GPIO Project and new Sonic Pi Jukebox
21 PS3 wireless controlled MeArm using Pi and 4Tronix picon zero board
22 ps3 wireless controlled MeArm robot part 2
23 ps3 wireless controlled MeArm robot part3
24 McRoboFace singalong with Sonic Pi

===================================================================================
========
AZARTICOLO:How to control GPIO pins and operate relays with the Raspberry Pi
===================================================================================
=========
https://opensource.com/article/17/3/operate-relays-control-gpio-pins-raspberry-pi

Learn how to operate relays and control GPIO pins with the Pi using PHP and a
temperature sensor.

Ever wondered how to control items like your fans, lights, and more using your
phone or
computer from anywhere?

I was looking to control my Christmas lights using any mobile phone, tablet,
laptop... simply
by using a Raspberry Pi. Let me show you how to operate relays and control GPIO
pins with
the Pi using PHP and a temperature sensor.

I put them all together using AJAX.

Hardware requirements
------------------------------------

Raspberry Pi

SD Card with Raspbian installed (any SD card would work, but I prefer to use a 32GB
class 10 card)

Power adapter
Jumper wires (female to female and male to female)

Relay board (I use a 12V relay board with for relays)

DS18B20 temperature probe

Wi-Fi adapter for Raspberry Pi

Router (for Internet access, you need to have a port-forwarding supported router)

10K-ohm resistor

Software requirements
-----------------------------------

Download and install Raspbian on your SD Card


Working Internet connection
Apache web server
PHP
WiringPi
SSH client on a Mac or Windows client

General configurations and setup


-------------------------------------------------

1. Insert the SD card into Raspberry Pi and connect it to the router using an
Ethernet cable

2. Connect the Wi-Fi Adapter.

3. Now SSH to Pi and edit the interfaces file using:

vi /etc/network/interfaces

This will open the file in an editor called nano.


It is a very simple text editor that is easy to approach and use.
If you're not familiar to a Linux-based operating systems, just use the arrow keys.

After opening the file in vi you will see a screen like this:

File editor nano

4. To configure your wireless network, modify the file as follows:

iface lo inet loopback


iface eth0 inet dhcp
allow-hotplug wlan0
auto wlan0
iface wlan0 inet dhcp
wpa-ssid "CISCOWIFI"
wpa-psk "intrapam123$"

5. Press CTRL + O to save it, and then CTRL + X to exit the editor.

At this point, everything is configured and all you need to do is reload the
network interfaces
by running:

service networking reload

(Warning: if you are connected using a remote connection it will disconnect now.)

Software configurations
------------------------------------

Installing Apache Web Server

Apache is a popular web server application you can install on the Raspberry Pi to
allow
it to serve web pages. On its own, Apache can serve HTML files over HTTP, and with
additional
modules it can serve dynamic web pages using scripting languages such as PHP.

Install Apache by typing the following command on the command line:

apt-get install apache2 -y


Once the installation is complete, type in the IP Address of your Pi to test the
server.
If you get the next image, then you have installed and set up your server
successfully.

Successful server setup

To change this default page and add your own html file, go to var/www/html:

cd /var/www/html

To test this, add any file to this folder.

Installing PHP
----------------------

PHP is a preprocessor, meaning this is code that runs when the server receives a
request
for a web page. It runs, works out what needs to be shown on the page, then sends
that
page to the browser. Unlike static HTML, PHP can show different content under
different
circumstances. Other languages are capable of this, but since WordPress is written
in PHP
it's what you need to use this time. PHP is a very popular language on the web,
with large
projects like Facebook and Wikipedia written in it.

Install the PHP and Apache packages with the following command:

apt-get install php5 libapache2-mod-php5 -y

Testing PHP

Create the file index.php:

vi index.php

Put some PHP content in it:

<?php echo "hello world"; ?>

Save the file. Next, delete "index.html" because it takes precedence over
"index.php":

rm index.html

Refresh your browser. You should see “hello world.”


This is not dynamic, but it is still served by PHP.
If you see the raw PHP above instead of “hello world,” reload and restart Apache
with:

/etc/init.d/apache2 reload
/etc/init.d/apache2 restart

Installing WiringPi
----------------------------
WiringPi is maintained under git for ease of change tracking; however, you have a
plan
B if you’re unable to use git for whatever reason.
(Usually your firewall will be blocking you, so do check that first!)

If you do not have git installed, then under any of the Debian releases
(e.g., Raspbian), you can install it with:

apt-get install git-core

If you get any errors here, make sure your Pi is up to date with the latest version
of Raspbian:

apt-get update apt-get upgrade

To obtain WiringPi using git:

git clone git://git.drogon.net/wiringPi

If you have already used the clone operation for the first time, then:

cd wiringPi git pull origin

It will fetch an updated version, and then you can re-run the build script below.

To build/install there is a new simplified script:

cd wiringPi ./build

The new build script will compile and install it all for you. It does use the
command at one
point, so you may wish to inspect the script before running it.

Testing WiringPi
-------------------------
Run the gpio command to check the installation:

gpio -v gpio readall

This should give you some confidence that it’s working OK.

Connecting DS18B20 To Raspberry Pi

The Black wire on your probe is for GND


The Red wire is for VCC
The Yellow wire is the GPIO wire
GPIO image

Connect:

VCC to 3V Pin 1
GPIO wire to Pin 7 (GPIO 04)
Ground wire to any GND Pin 9
Software Configuration

For using DS18B20 temperature sensor module with PHP, you need to activate the
kernel module for the GPIO pins on the Raspberry Pi and the DS18B20 by executing
the commands:
modprobe w1-gpio

modprobe w1-therm

You do not want to do that manually every time the Raspberry reboots, so you want
to enable these modules on every boot. This is done by adding the following lines
to the file /etc/modules:

vi /etc/modules/

Add the following lines to it:

w1-gpio

w1-therm

To test this, type in:

cd /sys/bus/w1/devices/

Now type ls.

You should see your device information. In the device drivers, your DS18B20 sensor
should be listed as a series of numbers and letters. In this case, the device is
registered as 28-000005e2fdc3. You then need to access the sensor with the cd
command, replacing my serial number with your own: cd 28-000005e2fdc3.

The DS18B20 sensor periodically writes to the w1_slave file, so you simply use the
cat command to read it: cat w1_slave.

This yields the following two lines of text, with the output t= showing the
temperature in degrees Celsius. Place a decimal point after the first two digits
(e.g., the temperature reading I received is 30.125 degrees Celsius).

Connecting the relay


--------------------------------

1. Take two jumper wires and connect one of them to the GPIO 24 (Pin18) on the Pi
and the other one to the GND Pin. You may refer the following diagram.

2. Now connect the other ends of the wire to the relay board. Connect the GND to
the GND on the relay and GPIO Output wire to the relay channel pin number, which
depends on the relay that you are using. Remember the GND goes to GND on the relay
and GPIO Output goes to the relay input pin.

Headers
------------------

Caution! Be very careful with the relay connections with Pi because if it causes a
backflow of current, you with have a short circuit.

3. Now connect the power supply to the relay, either using 12V power adapter or by
connecting the VCC Pin to 3.3V or 5V on the Pi.

Controlling the relay using PHP

Let's create a PHP script to control the GPIO pins on the Raspberry Pi, with the
help of the WiringPi software.
1. Create a file in the Apache server’s root web directory. Navigate using:

cd ../../../

cd var/www/html/

2. Create a new folder called Home:

mkdir Home

3. Create a new PHP file called on.php:

vi on.php

4. Add the following code to it:

<?php

system(“ gpio-g mode 24 out “) ;


system(“ gpio-g write 24 1”) ;

?>
5. Save the file using CTRL + O and exit using CTRL + X

In the code above, in the first line you've set the GPIO Pin 24 to output mode
using the command:

system(“ gpio-g mode 24 out “) ;


In the second line, you’ve turned on the GPIO Pin 24, Using “1,” where “1” in
binary refers to ON and “0” Means OFF.

6. To turn off the relay, create another file called off.php and replace “1” with
“0.”

<?php

system(“ gpio-g mode 24 out “) ;


system(“ gpio-g write 24 0”) ;

?>
7. If you have your relay connected to the Pi, visit your web browser and type in
the IP Address of your Pi followed by the directory name and file name:

http://{IPADDRESS}/home/on.php

This will turn ON the relay.

8. To turn it OFF, open the page called off.php,

http://{IPADDRESS}/home/off.php

Now you need to control both these things from a single page without refreshing or
visiting the pages individually. For that you'll use AJAX.

9. Create a new HTML file and add this code to it.


---------------------------------------------

[html + php + ajax codeblock]


<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></
script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$('#on').click(function(){
var a= new XMLHttpRequest();
a.open("GET", "on.php"); a.onreadystatechange=function(){
if(a.readyState==4){ if(a.status ==200){
} else alert ("http error"); } }
a.send();
});
});
$(document).ready(function()

{ $('#Off').click(function(){

var a= new XMLHttpRequest();

a.open("GET", "off.php");

a.onreadystatechange=function(){

if(a.readyState==4){

if(a.status ==200){

} else alert ("http error"); } }

a.send();

});

});

</script>

<button id="on" type="button"> Switch Lights On </button>

<button id="off" type="button"> Switch Lights Off </button>

10. Save the file, go to your web browser, and open that page.
You’ll see two buttons, which will turn lights on and off. Based on the same idea,
you can create a beautiful web interface using bootstrap and CSS skills.

Viewing temperature on this web page

1. Create a file called temperature.php:

vi temperature.php
2. Add the following code to it, replace 10-000802292522 with your device ID:

<?php
//File to read
$file = '/sys/devices/w1_bus_master1/10-000802292522/w1_slave';
//Read the file line by line
$lines = file($file);
//Get the temp from second line
$temp = explode('=', $lines[1]);
//Setup some nice formatting (i.e., 21,3)
$temp = number_format($temp[1] / 1000, 1, ',', '');
//And echo that temp
echo $temp . " °C";
?>
3. Go to the HTML file that you just created, and create a new <div> with the id
“screen”: <div id=“screen”></div>.

4. Add the following code after the <body> tag or at the end of the document:

<script>
$(document).ready(function(){
setInterval(function(){
$("#screen").load('temperature.php')
}, 1000);
});
</script>
In this, #screen is the id of <div> in which you want to display the temperature.
It loads the temperature.php file every 1000 milliseconds.

I have used bootstrap to make a beautiful panel for displaying temperature. You can
add multiple icons and glyphicons as well to make it more attractive.

This was just a basic system that controls a relay board and displays the
temperature. You can develop it even further by creating event-based triggers based
on timings, temperature readings from the thermostat, etc.

===================================================================================
=========
AZARTICOLO:LXDE on Raspberry Pi
===================================================================================
=========

The Raspbian image comes with LXDE as default desktop environment which is very
snappy
and responsive. It is fast, lightweight and includes many useful applications and
utilities by default.

However, in case you want some more variety or a more appealing desktop
environment,
then Xfce is a good alternative. It is also lightweight but with more customisation
features.
And the best of all: it is surprisingly easy to install and set it up as default.

To install Xfce, open a terminal session and type:

apt-get install Xfce4

That's it. Now reboot and when you are back open again a terminal session and type:

update-alternatives --config x-session-manager

You should see something similar to this:

There are 6 choices for the alternative x-session-manager (providing /usr/bin/x-


session-manager).

Selection Path Priority Status


-------------------------------------------------------------------------
0 /usr/bin/startlxde-pi 90 auto mode
1 /usr/bin/lxsession 49 manual mode
2 /usr/bin/openbox-session 40 manual mode
3 /usr/bin/startlxde 50 manual mode
4 /usr/bin/startlxde-pi 90 manual mode
5 /usr/bin/startxfce4 50 manual mode
6 /usr/bin/xfce4-session 40 manual mode

Press enter to keep the current choice[*], or type selection number:

Now all you have to do is to type 6 and press enter.


After a reboot, Xfce will be your new Raspbian desktop environment.

cat /root/.cache/lxsession/LXDE-pi/run.log

===================================================================================
========
AZARTICOLO:UPDATING AND UPGRADING RASPBIAN DOCUMENTAZIONE UFFICIALE
===================================================================================
========

First, update your system's package list by entering the following command in
LXTerminal or from the command line:

apt-get update
apt-get upgrade

Next, upgrade all your installed packages to their latest versions with the
command:

apt-get dist-upgrade

Generally speaking, doing this regularly will keep your installation up to date, in
that it will be
equivalent to the latest released image available from

raspberrypi.org/downloads.

However, there are occasional changes made in the Foundation's Raspbian image that
require manual
intervention, for example a newly introduced package.
These are not installed with an upgrade, as this command only updates the packages
you already
have installed.

UPDATING THE KERNEL AND FIRMWARE


-----------------------------------

The kernel and firmware are installed as a Debian package, and so will also get
updates when
using the procedure above. These packages are updated infrequently and after
extensive testing.

RUNNING OUT OF SPACE


-------------------------------------

When running apt-get dist-upgrade, it will show how much data will be downloaded
and how much space it will take up on the SD card. It's worth checking with df -h
that
you have enough disk space free, as unfortunately apt will not do this for you.

Also be aware that downloaded package files (.deb files) are kept in

/var/cache/apt/archives.

You can remove these in order to free up space with

apt-get clean.

===================================================================================
=========
Raspbian GNU/Linux upgrade from Jessie to Raspbian Stretch 9
===================================================================================
=========

Introduction
-------------------

The upgrade from Raspbian Jessie to Raspbian 9 Stretch is a relatively simple


procedure.
However, exercise caution, as there is always a chance to break the entire system.
The fewer installed 3rd-party packages and services, the more likely you are able
successfully
to upgrade your Raspbian Linux system. apt-get update

Recommendations
--------------------------------

Remove unnecessary or obsolete packages


Make a data and configuration backup
Perform an upgrade directly using console
Installed 3rd-party software on Raspbian Stretch 9

Warning:
--------------

MariaDB is now the default SQL database in Debian 9 Stretch.


This introduces a new database binary data file format which is not backwards
compatible with your current ( Debian 8 Jessie ) database format.
During the upgrade your databases will be upgraded automatically.
However, when you run into some issues during or after the upgrade,
you will not be able revert back!

From this reason it is important to backup all your current databases before you
proceed
with a Debian 9 Stretch upgrade!

REFERENCE: debian.org
Fully Upgrade Current System

Start by fully upgrade your current Raspbian system before you proceed with a
Stretch
upgrade.

# apt-get update
# apt-get upgrade

Upgrade any held back packages:


# apt-get dist-upgrade

System Check
---------------------
Last, chance to check for any system inconsistencies.
Perform database sanity and consistency checks for partially installed, missing and
obsolete packages:

# dpkg -C

If no issues are reported, check what packages are held back:

# apt-mark showhold

Packages On Hold will not upgrade.


On Hold packages may cause inconsistencies after Stretch upgrade.
Before you move to the following part, it is suggested to fix all issues provided
by both
above commands.

Update Package Repository to Debian Stretch


----------------------------------------------------------------------

Next, update your /etc/apt/sources.list to include new Stretch repositories.

# sed -i 's/jessie/stretch/g' /etc/apt/sources.list

The above command will replace any Jessie keyword occurrence to Stretch thus
effectively
enabling new Stretch repositories.

Once your /etc/apt/sources.list is updated to included Stretch repositories,


update your local package index with:

# apt-get update

Raspbian Stretch Upgrade Simulation


----------------------------------------------------------
Used the bellow command to see what we are facing.
It is a simulated dry-run thus not system changes will be implemented.

# apt-get --simulate upgrade

Rasbian Stretch Upgrade


-------------------------------------

We have come to the most exciting part, which is the actual Jessie upgrade to
Raspbian
Stretch system. During the upgrade you may be asked:

There are services installed on your system which need to be restarted when certain
libraries, such as libpam, libc, and libssl, are upgraded.

Since these restarts may cause interruptions of service for the system, you will
normally
be prompted on each upgrade for the list of services you wish to restart.
You can choose this option to avoid being prompted;
instead, all necessary restarts will be done for you automatically so you can avoid
being
asked questions on each library upgrade.

Restart services during package upgrades without asking?

The choice is about whether you wish the system to restart your services
automatically
during the system upgrade or you wish to do it manually or after the system is
fully upgrade
to Stretch.

When ready, execute the bellow commands to commence the Debian Stretch upgrade
process:

# apt-get upgrade
# apt-get dist-upgrade

All done. Reboot your system.

===================================================================================
=========
AZARTICOLO: Tutorial – Install Nginx and PHP on Raspbian
===================================================================================
=========

This is the first in a three part tutorial series on how to install and run NGINX
on a Raspberry Pi.
The first concentrates on installing and configuring Nginx web server and PHP on
Raspbian OS,
the second talks about installing MySQL server on Raspberry Pi, the third will walk
you through
installing WordPress on Nginx.

For many, Apache2 has become too bloated, and uses more resources than it needs to.
Nginx is a very light-weight web server, that works great on a Raspberry Pi.

Prerequisites

Before doing this tutorial I assume that you are familiar with Terminal, and are
proficient and
comfortable in command line interface.

Step 1 – Install Nginx


-------------------

To begin, using terminal or accessing directly, type the following command to


ensure everything’s
up-to-date before installing the required packages:

apt-get update && apt-get upgrade


Chances are there are packages that’ll need updating by running this command.
If prompted, hit ‘Y’ to install the updates. Now type the following command to
install Nginx:

apt-get install nginx

There we go, we’ve now got nginx installed. Next, we want to launch nginx and test
that it’s working ok.
Type the following command into the command line interface:
/etc/init.d/nginx start
If all goes well, you should see this message:

Launch nginx on Raspbian

If you visit your Raspberry Pi’s IP address in your web browser, you should see the
default Nginx page,
which looks a little something like this:

Nginx on a Raspberry Pi

Great success! You now have Nginx running on your Raspberry Pi. Next, we’ll install
PHP.

Step 2 – Install PHP


-----------------

The packages required for PHP to work with Nginx is a little different to those
when using PHP
with Apache2. PHP runs as a FastCGI interface, so we need to install the PHP FPM
package by
typing the following command:

apt-get install php5-fpm

Once we’ve done that we’re almost ready to rock.


We next need to make a few minor changes to the Nginx configuration to begin using
PHP with Nginx.

Step 3 – Configure Nginx and PHP


-----------------------------

You’re almost there. Similar to Apache2, Nginx works on a virtual hosts principle,
but is arguably
easier to configure multiple vhosts on Nginx. We’ll look at this in a later
tutorial.

Next, we’re going to adjust the default configuration to allow Nginx to start
serving content
using PHP. Begin by typing the following command:

vi /etc/nginx/sites-available/default
The vi editor will appear. If you’re more comfortable using VI, use this command
instead:

vi /etc/nginx/sites-available/default
Scroll down the configuration file until you find the ‘server’ block with the
following lines contained within it:

#listen 80; ## listen for ipv4; this line is default and implied
#listen [::]:80 default_server ipv6only=on; ## listen for ipv6
Uncomment them both out by removing the first #, so that they read like this:

listen 80; ## listen for ipv4; this line is default and implied
listen [::]:80 default_server ipv6only=on; ## listen for ipv6

This allows Nginx to listen on port 80 (the default http port) and listen for both
IPv4 and IPv6
requests. Next we need to edit the name of our server to match our domain. In my
care,
the domain is dingleberrypi.com but be sure to substitute this with your own domain
or IP address.

# Make site accessible from http://localhost/


server_name www.raspipress.com;
Change the index line from this:

index index.html index.htm;


To this:

index index.php index.html index.htm;

This allows files with the name index.php to be served up as the default index
page,
and takes priority over index.html and index.htm. Now we need to tell the
configuration
how to handle PHP files. Scroll down until you see this:

#location ~ .php$ {
# fastcgi_split_path_info ^(.+.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php5-fpm:
# fastcgi_pass unix:/var/run/php5-fpm.sock;
# fastcgi_index index.php;
# include fastcgi_params;
#}
Uncomment some of the lines so that it reads like this:

location ~ .php$ {
fastcgi_split_path_info ^(.+.php)(/.+)$;
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

# # With php5-cgi alone:


# fastcgi_pass 127.0.0.1:9000;

# # With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}

Be careful to edit the correct lines. We’re using a socket, so uncomment the
configuration accordingly.
Finally, we need to change the PHP configuration to fix a possible security
vulnerability.
Type the following command to edit the PHP configuration file:

vi /etc/php5/fpm/php.ini
Scroll down (or search for the line using CTRL + W in nano) for:

;cgi.fix_pathinfo=1
Uncomment the line by removing the semicolon from the start, and change the value
from 1 to 0. Save and exit nano.
Configure PHP with Nginx on Raspberry Pi

All we need to do now is restart php5-fpm and nginx to make the configuration
changes take:

/etc/init.d/php5-fpm reload && /etc/init.d/nginx reload

Step 4 – Test the PHP configuration


-------------------------------

Now all that’s left to do is to test to ensure PHP and Nginx are correctly
configured. Navigate to the default document root:

cd /usr/share/nginx/www
Create a file called index.php:

vi index.php
Add the following line to the file, save and exit nano:

<?php phpinfo(); ?>


Visit your raspberry pi in your web browser by typing its domain name or IP
address, and you should see the PHP info page:

PHP5 and Nginx on Raspbian

That’s it! We’ve installed, configured and tested PHP5 and Nginx. Grab a brew,
you’ve earned it! Any questions or comments, feel free to add them below.

Next, we’ll look at installing MySQL on Raspberry Pi and creating a new database
and database user for WordPress to use.

RELATED Tutorial - Install WordPress on a Raspberry Pi using Nginx

===================================================================================
=========
AZARTICOLO:Tutorial – Install MySQL server on Raspbian
===================================================================================
=========

================================================================================
AZARTICOLO:Tutorial – Install Apache, PHP and MySQL on a Raspberry Pi 2
================================================================================

Apache e' in grado di fornire pagine dinamiche via PHP

Controllo del firmware


------------------

uname -a
Linux raspy 4.4.13-v7+ #894 SMP Mon Jun 13 13:13:27 BST 2016 armv7l GNU/Linux

Se occorre aggiornarlo occorre sapere il seriale del firmware e digitare

rpi-update <serial fw number>

poi occorre eseguire il reboot

reboot
Aggiorna il dispositivo
------------------

apt-get update && apt-get upgrade

Installa Apache2
-------------

apt-get install apache2 apache2-utils -y

Installa PHP e le PHP libraries per WordPress (se si desidera):

apt-get install php5 php5-mysql libapache2-mod-php5 php-pear php5-xcache php5-curl


php5-gd

Per testarlo utilizzare l'IP del raspberry;

http://localhost/
http://192.168.1.10

Per trovare l'IP della Pi:

hostname -I

MODIFICARE LA DEFAULT WEB PAGE


--------------------------------

E' posta sotto:

/var/www/html/index.html.

Nota: La home directory era /var/www in Raspbian Wheezy ma ora e' /var/www/html in
Raspbian Jessie

notare che tutti permessi su tale directory sono assegnati a root ma posso cambiare
proprietario:
chown pi: index.html

in tale directory posso porre tutto il mio site

Installa MySQL Server


-------------------

Esegui il comando:

apt-get install mysql-server --fix-missing

Viene poi richiesta la master password per l'accesso al database da parte dell
utente corrente (root)

Installa MySQL Client


------------------

Infatti il pacchetto php5-mysql installato prima e' il client per accedere da


programma PHP
ma se voglio eseguire i comandi da linea di comando CLI occorre installare:

apt-get install mysql-client


Connessione al database
-------------------

mysql -uroot -hlocalhost -p

dare la password indicata in installazione

MySQL server on RPi


-----------------

Se vogliamo creare un database:

CREATE DATABASE wpdb;

Creazione di un utente con password:

CREATE USER 'wpuser'@'localhost' IDENTIFIED BY 'password_here';

Tale utente sara' proprietario del database appena creato e che utilizzero' nei
programmi per
connettermia a tale database. Doniamo i diritti di accesso al database a tale
utente:

GRANT ALL PRIVILEGES ON wpdb.* TO 'wpuser'@'localhost';


FLUSH PRIVILEGES;

Premere CTRL + C per uscire dal MySQL Client.

tentiamo il login al database con il nuovo utente:

mysql -uwpuser -hlocalhost wpdb -p

mi verra' richiesta la password associata a tale utente

===================================================================================
=========
AZARTICOLO:Add virtual hosts and subdomains to your Raspberry Pi Apache2 server
===================================================================================
=========

https://www.stewright.me/2013/08/add-virtual-hosts-and-subdomains-to-your-
raspberry-pi-apache2-server/

Vediamo come ospitare piu' virtual server o piu' sottodomini sul servizio apache.
Si suppone di aver gia' eseguito l'intallazione di apache2 mysql server e client e
php
come indicato nell'articolo:

https://www.stewright.me/2012/09/tutorial-install-apache-php-and-mysql-on-
raspberry-pi/

Inoltre di aver gia' ascritto a DNS domini e sottodomini.

Files di configurazione coinvolti:


-------------------------

vi /etc/apache2/envvars
vi /etc/apache2/sites-available/raspicam.conf
vi /etc/apache2/sites-available/raspicam.conf

vi motion/motion.conf
vi apache2/ports.conf

systemctl restart apache2.service

Step 1 – Create the sites available file for your domain or subdomain
----------------------------------------------------------

Utilizzeremo come esempio il dominio: video.dingleberrypi.com

cp /etc/apache2/sites-available/default
/etc/apache2/sites-available/video.dingleberrypi.com

in realta' utilizziamo editiamo il file:


vi /etc/apache2/sites-available/raspicam.conf

dove e' definita la document root insieme con molte altre informazioni

La riga :

ServerAdmin [email protected]

puo ' essere sostituita con il proprio indirizzo di posta.

inoltre posso aggiungere il nome canonico del server:

ServerName azmyweb.no-ip.org

ServerName video.dingleberrypi.com
<VirtualHost *:80>
ServerAdmin [email protected]
ServerName azmyweb.no-ip.org
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn

SetEnvIf Request_URI "/cam_pic.php$|/status_mjpeg.php$" dontlog


CustomLog ${APACHE_LOG_DIR}/access.log common env=!dontlog
</VirtualHost>

Posso modificare tranquillamente la document root,ovvero tutta la parte del path


dove e' posto
il sito che non deve essere indicata nella url, sostuita da /.
Se il folder non esiste viene creato. Di default e' posta uguale a:

‘/var/www/html’:

Change the sites-available fileMake a note of the directory, we’ll create it next.
Now press CTRL + X to quit, and save when prompted.

Per la directory indicata esiste di seguito una sezione che ne specifica i permessi
di accesso,
ma ne posso creare di ulteriori per eventuali sottodirectory della document root, e
che in quanto
tali dovranno essere specificate nella URL di accesso al sito

Step 2 – Creazione della document root per il sottodominio


------------------------------------------------

Supponiamo di avere un sottodominio vhost e di voler creare il relativo site


Occorre dapprima creare la directory:

mkdir /var/www/html/vhosts/

Occorre settare i permessi in modo che root possa scrivere e gli altri leggere:
chmod -R 755 /var/www/html/vhosts

Ripetere il procedimento se la sottodirectory ospita il site di un dominio:

mkdir /var/www/vhosts/video.dingleberrypi.com/
chmod -R 755 /var/www/html/vhosts/video.dingleberrypi.com/

Poi occorre abilitare il nuovo dominio


a2ensite video.dingleberrypi.com

e far ripartire apache:

service apache2 restart

Nel nuovo site occorre porre il file indice:

vi /var/www/html/vhosts/video.dingleberrypi.com/index.php

Replace the index.php file with your subdomain or virtual host, and that’s it.
Just in case you wondered what video is on my video.dingleberrypi.com it’s below!

===================================================================================
=========
AZARTICOLO: Tutorial – Install PhpMyAdmin on your Raspberry Pi
===================================================================================
=========
https://www.stewright.me/2012/09/tutorial-install-phpmyadmin-on-your-raspberry-pi/

Passo successivo a quelli descritti nell'articolo:


install Apache, PHP and MySQL on Raspberry Pi.

Step 1 – Installazione PhpMyAdmin


------------------------------

apt-get install phpmyadmin

Quando chiede graficamente dove installare rispondere apache2.


poi rispondere YES quando chiede se voglio amministrare mysql

Step 2 – configurare dbconfig-common


---------------------------------

Poi mi viene richiesta la password di root utilizzata nell installazione del


database

Poi mi vine chiesta la password per PhpMySQL, utilizzate la stessa del database.

Next we need to change the apache configuration to allow us to use

http://your.raspberrypi.domain/phpmyadmin to access it.

Step 3 – Configurare Apache per abilitare PhpMyAdmin


--------------------------------------------

editare la configurazione di Apache

vi /etc/apache2/apache2.conf

includere al fonodo la definizione del virtual server di phpmyadmin:

Include /etc/phpmyadmin/apache.conf

Far ripartire apache:

/etc/init.d/apache2 restart oppure


systemctl restart apache2.service

Accesso a phpmyadmin:

http://192.168.1.4/phpmyadmin
http://192.168.1.5:8080/phpmyadmin

=================================================================================
AZARTICOLO: How to build a REST Web API on a Raspberry PI in JavaScript
=================================================================================

One of the most useful reasons for providing your Raspberry Pi with a REST API is
to expose its
inputs and outputs to a web client (on any iPhone, laptop or desktop PC anywhere in
the world)
for remote monitoring and/or control. This is part 1 of a 2 part blog showing how
to implement
a REST API in JavaScript.

What’s REST ?
-------------
In recent years, the Web has turned from a network of webservers serving mainly
static pages to web browsers…

Web 1.0 – How the Internet was


-----------------------------

…into a full client-server architecture, where single-page client web apps use AJAX
principles
to communicate with server-side applications, increasingly via simple but powerful
RESTful APIs.

The Web as a client-server application framework

REST, AJAX and JAVASCRIPT


---------------------------

With REST, the idea is that, rather than using complex mechanisms such as CORBA,
RPC or
SOAP to connect between clients and servers, simple HTTP queries are used.
RESTful applications use HTTP requests to POST data (create and/or update data),
GET data (make queries), and delete data on the server.
Thus, REST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

AJAX is a popular web development technique that makes web pages interactive using
JavaScript.
In AJAX, requests are sent to the server using XMLHttpRequest objects.
The response is used by the JavaScript code to dynamically change the current page.
Each XMLHttpRequest can be viewed as a REST service request, sent using GET.
And the response is often in JSON format.

For example, if our client application wants to get the ISBN for a book the user
knows the title
of, we might send our API server an HTTP GET with the URL :

http://www.myapiserver.com/books/ISBN/Catch-22

Using jQuery we can implement this AJAX request in our client application simply
like this:

$.getJSON("http://www.myapiserver.com/books/ISBN/Catch-22", function(data) {
console.log("The ISBN for this book is "+data );
});

The HTTP reply our server sends back to the client is the raw result data — not
embedded inside
an HTML page, not XML-encoded, just the data you need in a way you can immediately
use –
a String or a JSON object you can use directly.

With REST, a simple network connection is all you need.


You can even test the API directly, by typing the API URL into your browser.
For instance, try out the twitter API by entering

https://api.twitter.com/1/statuses/home_timeline.json?include_entities=true
in your browser. Because you haven’t included a key in your request, you will see
an authentication
error response in the browser window, encoded as a JSON object, which looks
something like this:

{"errors":[{"message":"Bad Authentication data","code":215}]}

As you may have noticed in these examples, REST can easily handle more complex
requests, including multiple parameters. In most cases, you’ll just use HTTP GET
parameters in the URL.

For example, if we can only uniquely specify a book by both title and author, our
API might accept a request like this: “http://myapiserver/books/ISBN?title=Catch-
22&author=Heller”
As a convention, HTTP GET requests should be for read-only queries; they should not
change the state of the server and its data. For creation, updating, and deleting
data, use POST requests.

REST on the Raspberry Pi


---------------------

Nodejs_logo_lightI’ve been using Node.JS as the backend (server-side) framework for


building single-page or client-server web apps and more recently as a Javascript
platform on my Raspberry Pi. On top of providing the advantage of an asynchronous,
event-based programming model, it means I can code in he same language – Javascript
– on the frontend and the backend and on the Pi.

REST for RPiThe Raspberry Pi as a Web Application server

To install Node.JS on your Raspberry Pi, see my earlier Blog post HOW TO INSTALL
NODE.JS ON A RASPBERRY PI

On the Raspberry Pi, we need to use the Node Package Manager npm to download and
install the other modules we will need to build our web application. We will be
using the express web application framework module initially, and also the connect
module it depends on.
On your RPi, create a new directory for your project, and download the node modules
you’ll need as follows :

$ mkdir myapp
$ cd myapp
$ npm init
$ npm install express --save
$ npm install connect --save
Or use the -g flag if you prefer the package to be installed globally, i.e. in
/usr/local where node is installed, rather than in ./node_modules. To install
global packages, you need to use to execute with superuser priviledges.

The node package manager will download and install the express framework.

Coding a RESTful API example on the Raspberry Pi

We’re now going to build an example client-server application using our Raspberry
Pi as the server.

To build this full REST example, we need to create three source files on our
Raspberry Pi: The server-side Javascript code, a simple HTML page, and some client-
side Javascript.

myapi.js – our server-side Javascript code uses the Node and the Express framework
to provide simplistic Web server functionality and to expose a RESTful API.

index.html – the HTML page which the browser loads from the Raspberry Pi and uses
to render the presentation layer for our application.

myclient.js – Javascript code executed in the browser when our HTML page loads.
This code implements the AJAX client functionality to call our API and render the
results directly in the HTML page.

The application architecture looks like this:


Our Example – using Raspberry Pi as an App Server

MYAPI.JS: The Server(RPi)-side code

Now create a file called myapi.js on your Pi and copy the code below to build a
simple server in
Javascript, which processes API requests on port 3000 with a JSON object.
(Port 3000 is the standard port most commonly used for an express server).

First we need to let Node know we will be using the http and express packages,
call express to create our application server as an object, and assign it to a
variable.

var http = require('http');


var express = require('express');

var app = express();


Next we will define an array of objects the client will be able to query….

var inputs = [{ pin: '11', gpio: '17', value: 1 },


{ pin: '12', gpio: '18', value: 0 }];

Then configure Express to serve index.html and any other static pages stored in the
home directory,
such as your myclient.js JavaScript source file

app.use(express['static'](__dirname ));

Next we need to define the API middleware for our server-side application.
We use express’s get function to define routes for the API calls and/or page
requests to our server.

// Express route for incoming requests for a customer name


app.get('/inputs/:id', function(req, res) {
res.status(200).send(inputs[req.params.id]);
});

// Express route for any other unrecognised incoming requests


app.get('*', function(req, res) {
res.status(404).send('Unrecognised API call');
});

// Express route to handle errors


app.use(function(err, req, res, next) {
if (req.xhr) {
res.status(500).send('Oops, Something went wrong!');
} else {
next(err);
}
});
Finally, start the server application, listening on port 3000:

app.listen(3000);
console.log('App Server running at port 3000');
INDEX.HTML: the homepage

Our web page simply displays a title, and sets up an input div as a placeholder
that will be used
by our client-side JavaScript code in myclient.js to display the I/O values
retrieved from our RPi.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Express API server example</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="myclient.js"></script>
</head>
<body>
<H1>My Express API server example</H1>
<div id="input"></div>
</body>
</html>
MYCLIENT.JS: the client-side code

this JavaScript code will be loaded and executed on the client machine when the
browser loads our HTML page. It makes 2 calls to our API server running on the
Raspberry Pi to retrieve and display the state of two inputs.

window.onload = function () {
var url,
i,
jqxhr;

for (i = 0; i < 2; i++) {


url = document.URL + 'inputs/' + i;
jqxhr = $.getJSON(url, function(data) {
console.log('API response received');
$('#input').append('<p>input gpio port ' + data['gpio'] + ' on pin ' +
data['pin'] + ' has current value ' + data['value'] + '</p>');
});
}
};

Download the Source Code


----------------------------------------

You can also download the full source code (client, server and html) for this
example from github here https://github.com/fatkahawai/rpi-webapp-express

Create or download the three source files into a new folder on your RPi.

Running your Raspberry Pi Web App Server

To start up your web server on your RPi , invoke your application with node, from
the folder you have saved the source files in.

$ node myapi.js
App Server running at port 3000
$
(Making sure that you have first installed the express module using npm, as already
described above.)

Your web server is now running continuously in the background, waiting for API
calls.
Finally, using another machine on the same local network, open a web browser and
navigate to your App Server hosted on the RPi.

If your RPi has the local IP address 192.168.0.22, you would enter this in your
browser:

http://192.168.0.22:3000

This will cause the browser to load your index.html file from your RPi, which then
loads your javascript client code in myclient.js.

If you’re in luck, this should appear in your browser window:

What’s Next ?
--------------------

One of the most useful reasons for providing your Raspberry Pi with a RESTful API
is to
expose its input and output ports to web clients for remote monitoring and
control.

So in our next exercise, we will do just this, exposing the real GPIO I/O ports
through a
RESTful API, which will allow you to control your Pi’s inputs and outputs from any
smartphone
or PC wherever you are in the world.

Next

I hope this exercise has been useful. If you have any feedback or spot any errors
or omissions,
feel free to leave a note in the comments section below.

===================================================================================
=========
AZARTICOLO: How to Write and Run a C Program on the Raspberry Pi
===================================================================================
=========

In this brief tutorial, I’ll discuss what a C program is, what C programming is
used for,
and finally, how to write and run a C program on the Raspberry Pi.

What is a C Program?
-------------------

The C programming language is one of the most widely used programming languages of
all time.
It is computationally faster and more powerful than Python. C is a middle level
programming
language because of its low level of abstraction to assembly language. High level
languages provide
the programmer with constructs, or commands that make it easy to do certain tasks
like printing
to the computer monitor, or logic functions like and, or, and not. Low level
programming languages
only give you access to the machine’s basic instruction set. C does have some of
these useful constructs,
but not as many as higher level languages like Python.

The advantage of C is that it produces code that is almost as fast computationally


as assembly code,
it gives you access to powerful low level machine functions, and it has a syntax
that is easier to read
than assembly code. For example, compare this assembly code for our “hello world”
program to the
C code for the same program below:

.arch armv6
.eabi_attribute 27, 3
.eabi_attribute 28, 1
.fpu vfp
.eabi_attribute 20, 1
.eabi_attribute 21, 1
.eabi_attribute 23, 3
.eabi_attribute 24, 1
.eabi_attribute 25, 1
.eabi_attribute 26, 2
.eabi_attribute 30, 6

Code written in C will need to be compiled before it can be run on a computer.


Compiling is the process of converting human readable code into machine readable
code that can
be understood by the computer’s CPU.

C is so widely used that it can be compiled for almost any system with minimal
changes to the source code.
The C language is available on a wide range of computer platforms including
personal computers,
embedded microcontrollers, and supercomputers.

What can a C program do?


----------------------------------------
C was initially used to develop operating systems, so it may not surprise to you
that the Linux kernel is written in C.
C can do pretty much anything you would want to do in computer programming.
Some example applications include:

Operating systems
Large programs
Databases
Desktop utilities
Language compilers
Text/photo editors
Network drivers

How to create and run a program in C

The intent of this article is to give a high level view of the main programming
languages used on
the Raspberry Pi. If you’re looking for in depth information on C programming, a
great book is the
de facto standard, The C Programming Language by Brian Kernighan and Dennis
Ritchie.
It’s a useful text for anyone currently using C, or anyone that wants to learn it.
The coding process in C consists of four steps:

Writing the code


Compiling the program
Making the program executable
Executing the program

To start, open the vi text editor with a new file by entering vi hello-world.c
at the command prompt. When you create the initial uncompiled text file where you
will save the C code,
it must have a “.c” extension. Now, enter this code into nano:

#include <stdio.h>
int main()
{
printf("Hello, World! \n");
return 0;
}
After entering the code, enter Ctrl-X to save and exit nano.

The next step is to compile the source file hello-world.c.


This will make a new file which we can name anything we want, for example
myfirstcprogram.
At the command prompt, enter

gcc hello-world.c -o myfirstcprogram.

The -o myfirstcprogram part tells the compiler to take the source file (hello-
world.c) and output
another file (myfirstcprogram) that we can make executable.

Now, we need to change the file permissions of myfirstcprogram to make it


executable.
At the command prompt, enter chmod +x myfirstcprogram.
The program can now be run by entering ./myfirstcprogram.

Hope this helps you get a basic idea on how to get started programming in C on the
Raspberry Pi.

===================================================================================
=========
AZARTICOLO: IBEX:bcm2835 by Mike McCauley Programming in C/C++
===================================================================================
=========

http://www.raspberry-projects.com/pi/programming-in-c/io-pins/bcm2835-by-mike-
mccauley

Questa libreria supporta RPi ver 2 con il chipset bcm2836

Installing The Library


------------------

The library homepage

In the commands below change the .XX to match the current library version number,
e.g. ".50".

If you are using the GUI then open the command prompt using Menu > Other >
LXTerminal
Using your RPi download the .tar.gz file from the library page to your "/home/pi/"
root directory.
You can do this using wget on the command line:

cd /home/pi/
wget http://www.airspayce.com/mikem/bcm2835/bcm2835-1.50.tar.gz

Install the library files using the following commands:

Unzip the downloaded file

tar zxvf bcm2835-1.50.tar.gz

The files will be unzipped into a folder called "/home/pi/bcm2835-#.#" where # is


the version number.
(The following instructions are based on the instructions in the bcm2835.h file so
if something doesn't
work check there to see if the instructions have changed)

Change to the directory the files we're unzipped into


(Change the directory version number to match your downloaded version)

cd bcm2835-1.XX

./configure
make
make check
make install

The library is now ready to use.

Using the Library In A NetBeans Project


---------------------------------

Including the library header file

#include <bcm2835.h>

When you compile you also need to include -lbcm2835 so the libraries object file is
added to the final compilation.

Right click the project > Properties > Build > Linker > In the 'Libraries' section
press the
'…' button > Add Option… > Other Option > Enter: -lbcm2835

Using the Library In A Geany Project


------------------------------

Including the library header file

#include <bcm2835.h>

When you compile you also need to include -lbcm2835 so the libraries object file is
added to the final compilation.
For example at the command line:

gcc clk.c -o clk -lbcm2835


In a simple makefile for a project with a single file called main.c:

all: output_file_name

output_file_name: main.o
gcc main.o -lbcm2835 -o output_file_name

main.o: main.c
gcc -c main.c

clean:
rm -rf *o output_file_name

Trying out an example project using the command line C compiler

You can compile one of the examples using this:

cd examples/blink
gcc -o blink -l rt blink.c -l bcm2835

and then run the blink exe with this command:

./blink

If you connect the positive pin of a 5V LED to pin 11 of the P1 header it should be
blinking. Use CTRL+Break or CTRL+SHIFT+C to stop the exe.
Problems With The Library

DelayMicroseconds() is a handy function but if you use it a lot you'll find


operation takes much longer than it should. This is because the function allows
the linux scheduler to know the process is sleeping and decide to move on to
another process. See here for a better solution if you need to avoid this.
Controlling Pins

See the header file for all of the functions.


RPi1 Model B+ and RPi2 Model B

//Setup
bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_40, BCM2835_GPIO_FSEL_INPT); //RPI1B+ &
RPi2B <<Set as input
bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_40, BCM2835_GPIO_FSEL_OUTP); //RPI1B+ &
RPi2B <<Set as output
bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_40, BCM2835_GPIO_PUD_UP); //RPI1B+ &
RPi2B <<Set pull up

//Outputs
#define LED_GREEN(state)
bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_40, !state) //RPI1B+ & RPi2B

//Inputs
//bcm2835_gpio_lev returns uint8_t
#define SW_A_INPUT
bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_40) //RPI1B+ & RPi2B

RPi1 V2 (old)
//Outputs
#define LED_GREEN(state)
bcm2835_gpio_write(RPI_V2_GPIO_P1_24, !state)
#define LED_YELLOW(state)
bcm2835_gpio_write(RPI_V2_GPIO_P1_26, !state)

//Inputs
//bcm2835_gpio_lev returns uint8_t
#define SW_A_INPUT
bcm2835_gpio_lev(RPI_V2_GPIO_P1_03)

Upgrading to a newer version of the library

Just reinstall, no need to uninstall the old one.

===================================================================================
=========
AZARTICOLO:C and Python implementation for RaspberryPi to detect movement using
PIR motion sensor (HC-SR501)
===================================================================================
=========
https://bhavyanshu.me/tutorials/raspberrypi-to-detect-movement-using-pir-motion-
sensor-hc-sr501/11/21/2014
git clone https://github.com/bhavyanshu/rPiExperiments.git

Overview

I recently bought a motion detection sensor HC-SR501. First, we will see how to
connect it to
our raspberry pi and then we will run the C code which helps us detect motion.
Once the movement has been detected, it will set LED to HIGH and play an audio
(.wav) file.
There are a lot of python implementations for it out there but if you are
interested in specifically
using C for this, then you have come to the right place.

Hardware

Breadboard
Jumper Wires
4.7K ohm resistor (If using +5 volt - PIN 2) else no resistor required,
if using +3.3V (PIN 1).
See diagram below.

HC-SR501
3.5 mm jack speaker/headphones (Optional, if you want sound)
Raspberry Pi (I am using model B revision 2)

We connect board pin number 1 (+3.3 V) to the VCC of the sensor, pin number 6 for
GND and
finally pin number 7 as data input from the sensor to raspberry pi.

PIR sensors work by detecting a change in the infrared radiation level in the
detection region.
So when there is no movement, the digital out pin on the sensor will remain LOW but
as soon as
there is a movement in the detection range, it will go HIGH and our Raspberry Pi
will be able to
sense this change when we run our C program.
Next we connect anode of LED to pin number 11 and cathode to GND.
Look at the figure below to understand the connections.
It may not be the best diagram ever but this is all I have for now.

PIR

GPIO17 ---------|R|----------------A-|led rosso|--c-- GND --|


|----------------------------|
GND ------------------- GND ------|\
GPIO04 ------------------- OUT ------| |
3V3 ------------------- VCC ------| /

The fun begins


--------------
Please make sure your connections are correct.
If you are using some other pins then keep them in mind.
You will have to change the
#define SENSOR and
#define LED macro in that case.

The below given C program depends on bcm2835 library.


It will not compile without it.
First copy paste the contents of pir.c file or you can find the raw file here.

pir.c file :
---------

/**
* Program for PIRsensor. Detects movement and activates connected LED
* for 2 seconds.
* Connect on board pin number 07 to Sensor, 11 to LED
* - Refer RPiGPIOPin section of
* http://www.airspayce.com/mikem/bcm2835/group__constants.html
*/

#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SENSOR RPI_GPIO_P1_07


#define LED RPI_GPIO_P1_11
#define ACTIVE_VALUE 1

int main(int argc, char **argv)


{
if (!bcm2835_init()) {
printf("Please run this with\n");
return EXIT_FAILURE;
}

bcm2835_gpio_fsel(SENSOR, BCM2835_GPIO_FSEL_INPT);//SENSOR as input


bcm2835_gpio_fsel(LED, BCM2835_GPIO_FSEL_OUTP); //LED as output
bcm2835_gpio_set_pud(SENSOR, BCM2835_GPIO_PUD_UP);
uint8_t state = ACTIVE_VALUE; //Init state to HIGH
while (1) {
state = bcm2835_gpio_lev(SENSOR); //HIGH or LOW?
if(state != ACTIVE_VALUE)
{
//Sensor not active
}
else
{
printf("Movement at %d\n",(int)time(NULL));
bcm2835_gpio_set(LED);
/* Comment out both system() lines
if don't wanna play wav file */
system("omxplayer beep.wav");
sleep(2);
//Another extra overhead!
system("killall omxplayer.bin");
bcm2835_gpio_clr(LED);
}
}
bcm2835_close();
return EXIT_SUCCESS;
}
#undef SENSOR
#undef LED
#undef ACTIVE_VALUE

You will have to install the library manually using

$ wget http://www.open.com.au/mikem/bcm2835/bcm2835-1.5.tar.gz
$ tar zxvf bcm2835-1.5.tar.gz
$ cd bcm2835-1.5
$ ./configure
$ make
$ make check
$ make install
and then compile the pir.c using
gcc pir.c -o pir -l bcm2835
To run it, use
./pir
It has to be run as root for it to be able to access hardware.

That’s all. Now move around the sensor.


You will see LED is HIGH while you move and the .wav file also plays. Once you
stand still,
the LED will go off too. If there is an audio issue, take a look at this or post a
comment below.
Now let us quickly go through python implementation as well. Raw File
pir.py file :
#!/usr/bin/env python

# Info - This program is for PIR sensor. Contionusly checks for state,
# set LED if movement detected and plays wav file on detection.

import RPi.GPIO as GPIO


import time
import pygame

pygame.mixer.init()
pygame.mixer.music.load("beep.wav")
PIR = 7 # On-board pin number 7 (GPIO04)
LED = 11 # On-board pin number 11 (GPIO17)

state = False
val = False

GPIO.setmode(GPIO.BOARD) # Change this if using GPIO numbering


GPIO.setup(PIR, GPIO.IN) # Set PIR as input
GPIO.setup(LED, GPIO.OUT) # Set LED as output

try:
while True:
val = GPIO.input(PIR) # read input value
if (val == True): # check if the input is HIGH
GPIO.output(LED, True) # turn LED ON
if (state == False):
# ON
pygame.mixer.music.play()
state = True
else:
GPIO.output(LED, False) # turn LED OFF
if (state == True):
# OFF
time.sleep(2)
state = False;
except KeyboardInterrupt:
GPIO.cleanup()

Run above using


python pir.py
That’s all. Test it out and if you get stuck, just post in the comments below. I
will help you out.

===================================================================================
=========
AZDIET
===================================================================================
========

================================================================================
AZARTICOLO:INSTALLING OPERATING SYSTEM IMAGES ON LINUX
================================================================================
https://www.raspberrypi.org/documentation/installation/installing-images/linux.md

Etcher is typically the easiest option for most users to write images to SD cards,
so it is a good
place to start. If you're looking for more advanced options on Linux, you can use
the standard
command line tools below.

Note: use of the dd tool can overwrite any partition of your machine.
If you specify the wrong device in the instructions below, you could delete your
primary
Linux partition. Please be careful.

DISCOVERING THE SD CARD MOUNTPOINT AND UNMOUNTING IT


-----------------------------------------------------------------------------------
---------------
Run df -h to see which devices are currently mounted.

If your computer has a slot for SD cards, insert the card. If not, insert the card
into an SD
card reader, then connect the reader to your computer.

Run df -h again.

The new device that has appeared is your SD card.


If no device appears, then your system is not automounting devices.
In this case, you will need to search for the device name using another method.
The dmesg | tail command will display the most recent system messages, which
should
contain information on the naming of the SD card device.

The naming of the device will follow the format described in the next paragraph.
Note that if the SD card was not automounted, you do not need to unmount later.

The left column of the results from df -h command gives the device name of your SD
card.
It will be listed as something like /dev/mmcblk0p1 or /dev/sdX1, where X is a
lower case
letter indicating the device. The last part (p1 or 1 respectively) is the partition
number.

You want to write to the whole SD card, not just one partition.
You therefore need to remove that section from the name.
You should see something like /dev/mmcblk0 or /dev/sdX as the device name for the
whole SD card. Note that the SD card can show up more than once in the output of
df.
It will do this if you have previously written a Raspberry Pi image to this SD
card, because
the Raspberry Pi SD images have more than one partition.

Now you have noted the device name, you need to unmount it so that files can't be
read
or written to the SD card while you are copying over the SD image.

Run umount /dev/sdX1, replacing sdX1 with whatever your SD card's device name is,
including the partition number.

If your SD card shows up more than once in the output of df, this shows that the
card has
multiple partitions. You should unmount all of these partitions.

COPYING THE IMAGE TO THE SD CARD


---------------------------------------------------------

In a terminal window, write the image to the card with the command below, making
sure
you replace the input file if= argument with the path to your .img file, and
the /dev/sdX
in the output file of= argument with the correct device name. This is very
important,
as you will lose all the data on the hard drive if you provide the wrong device
name.
Make sure the device name is the name of the whole SD card as described above, not
just
a partition. For example: sdd, not sdds1 or sddp1, and mmcblk0, not mmcblk0p1.
dd bs=4M if=2017-04-10-raspbian-jessie.img of=/dev/sdX

Please note that block size set to 4M will work most of the time.
If not, try 1M, although this will take considerably longer.

Also note that if you are not logged in as root you will need to prefix this with .

COPYING A ZIPPED IMAGE TO THE SD CARD


----------------------------------------------------------------

In Linux it is possible to combine the unzip and SD copying process into one
command,
which avoids any issues that might occur when the unzipped image is larger than
4GB.
This can happen on certain filesystems that do not support files larger than 4GB
(e.g. FAT),
although it should be noted that most Linux installsations do not use FAT and
therefore
do not have this limitation.

The following command unzips the zip file (replace 2017-04-10-raspbian-jessie.zip


with
the appropriate zip filename), and pipes the output directly to the dd command.
This in turn copies it to the SD card, as described in the previous section.

unzip -p 2017-04-10-raspbian-jessie.zip | dd of=/dev/sdX bs=4096

CHECKING THE IMAGE COPY PROGRESS


------------------------------------------------------------

By default, the dd command does not give any information about its progress, so it
may
appear to have frozen. It can take more than five minutes to finish writing to the
card.
If your card reader has an LED, it may blink during the write process.

To see the progress of the copy operation, you can run the dd command with the
status option.

dd bs=4M if=2017-04-10-raspbian-jessie.img of=/dev/sdX status=progress

If you are using an older version of dd, the status option may not be available.
You may be able to use the dcfldd command instead, which will give a progress
report
showing how much has been written.

CHECKING WHETHER THE IMAGE WAS CORRECTLY WRITTEN TO THE SD CARD


-----------------------------------------------------------------------------------
------------------------------------

After dd has finished copying, you can check what has been written to the SD card
by
dd-ing from the card back to another image on your hard disk; truncating the new
image
to the same size as the original; and then running diff (or md5sum) on those two
images.

If the SD card is bigger than the original image size, dd will make a copy of the
whole card.
We must therefore truncate the new image to the size of the original image.
Make sure you replace the input file if= argument with the correct device name.
diff should
report that the files are identical.

dd bs=4M if=/dev/sdX of=from-sd-card.img


truncate --reference 2017-04-10-raspbian-jessie.img from-sd-card.img
diff -s from-sd-card.img 2017-04-10-raspbian-jessie.img
Run sync. This will ensure the write cache is flushed and that it is safe to
unmount your SD card.

Remove the SD card from the card reade

================================================================================
AZARICOLO:INSTALLING OPERATING SYSTEM IMAGES
================================================================================

https://www.raspberrypi.org/documentation/installation/installing-images/README.md

This resource explains how to install a Raspberry Pi operating system image on an


SD card.
You will need another computer with an SD card reader to install the image.

We recommend most users download NOOBS, which is designed to be very easy to use.
However, more advanced users looking to install a particular image should use this
guide.

DOWNLOAD THE IMAGE


------------------------------------

Official images for recommended operating systems are available to download from
the
Raspberry Pi website Downloads page.

Alternative distributions are available from third-party vendors.

If you're not using Etcher (see below), you'll need to unzip .zip downloads to get
the image file (.img) to write to your SD card.

Note: the Raspbian with PIXEL image contained in the ZIP archive is over 4GB in
size and uses the ZIP64 format.
To uncompress the archive, a unzip tool that supports ZIP64 is required.
The following zip tools support ZIP64:

7-Zip (Windows)
The Unarchiver (Mac)
Unzip (Linux)

WRITING AN IMAGE TO THE SD CARD


--------------------------------------------------------

You will need to use an image writing tool to install the image you have downloaded
on your SD card.

Etcher is a graphical SD card writing tool that works on Mac OS, Linux and Windows,
and is the easiest option for most users. Etcher also supports writing images
directly from the zip file,
without any unzipping required. To write your image with Etcher:
Download Etcher and install it.
Connect an SD card reader with the SD card inside.
Open Etcher and select from your hard drive the Raspberry Pi .img or .zip file you
wish to write to the SD card.
Select the SD card you wish to write your image to.
Review your selections and click 'Flash!' to begin writing data to the SD card.
For more advanced control of this process, see our system-specific guides:

Linux
Mac OS
Windows

================================================================================
AZARTICOLO:CONNESSIONE AD ARDUINO
================================================================================
https://oscarliang.com/raspberry-pi-and-arduino-connected-serial-gpio/
https://oscarliang.com/raspberry-pi-arduino-connected-i2c/
https://oscarliang.com/connect-raspberry-pi-and-arduino-usb-cable/

================================================================================
AZARTICOLO: House-Monitoring Framework with Arduino and Raspberry Pi: The Paranoid
App
================================================================================

http://www.allaboutcircuits.com/projects/house-monitoring-framework-with-arduino-
and-raspberry-pi/
June 03, 2016 by Cezar Chirila

So you have a Raspberry Pi and an Arduino and you want to develop a system to
monitor and
control your home. If I'm reading your mind correctly, after you're done reading
this article you
will be able to do exactly what you want.
There are plenty of articles on the internet, but most are either too basic or they
even skip some
of the steps. I will guide you through every step and make sure that you don’t run
into any known problems.

Introduction
-----------

First of all, why would you want to use an Arduino and a Raspberry Pi together?
The Pi has GPIOs that are great for simple Boolean tasks (On or Off) and for
reading a cheap
temperature sensor. Is that enough? No! For more complex systems, you will want to
use a
microcontroller to do the heavy work. It has an ADC with multiple channels
(Analog to Digital converter), PWM (Pulse Width Modulation) channels, and very
accurate timing.

For example, if you want to measure the electric energy consumption of your house,
you need a
current transformer and a basic circuit that will output a voltage that you can
measure using the
ADC. If you want to output something in between 1 and 0, let’s say to fade an LED,
you would
use the PWM outputs. Finally, you need a microcontroller if you need something with
very precise
timing like a PID system, multiplexing an LED array, or controlling a stepper
motor. In our case,
we will be using the Arduino Uno as the microcontroller.

BOM and Schematic


-------------------------------

For this project, you will need the following:

Arduino Uno (Though you can use a different Arduino product if you wish.)
Raspberry Pi (I used a Pi Zero, but any will work.)
Raspberry Pi power supply
SD Card with Raspbian installed (The Raspbian Lite is ok, too.)
Sensors and other modules for the Arduino (This will be based on what you'd like to
accomplish.)
Basic knowledge of Arduino IDE, Raspbian, C/C++, HTML, and javascript
(Don't worry. If you already know C/C++, that'll be enough.)
The schematic is not very complicated and it varies depending on what you want to
achieve.
In this example, I used a temperature/humidity sensor and an LED.

Arduino Code
-----------------------

For the sake of simplicity, I will only show you here how to read temperature and
humidity from
a DHT11 sensor and how to remote blink an LED. For your actual project, you will
want something
more complex as this can be done with just a Raspberry Pi. In case you do want to
start with this,
here is the schematic:

---------- ------------ ---- -------- --------


|INTERNET|------|rASPBERRRY|------|USB|-------|Arduino|------|Sensors|
---------- ------------ ---- -------- --------

Let’s start with the basics. The data is sent over the serial port at a baud rate
of 9600.
In the main function, we read the serial port and we check what we receive.

If we receive the string “thl”, it means that we need to send the data from the
sensors over
the serial port. For this function to work properly we use a while loop and send
the data over and
over again until we receive an “ok” to know that the data has reached the server.
If we receive the string “led”, we just blink the LED. Here you can add any
function and string
you want just remember to use “thl” for sending data.

What you need to know is that we send data in JavaScript Object Notation (JSON)
form.
JavaScript Object Notation is an open-source format to transmit data objects.
We use this because we can easily use this data within the main.html file using
javascript.
To use it, we will need a library called ArduinoJson which you can find here or
download below.
The function “send_data()” does as its name implies: It sends the data over the
serial port in
JSON form. To add data, you just need to add a line inside this function that looks
like this :

root["name_of_data"] = function_that_returns_data();

Where the “function_that_return_data()” looks like this:

int function_that_return_data()
{
int data;
//insert code that reads data from a sensor and attributes the value to
variable 'data'
return (data);
}

That is all for the Arduino part. Below you can see the exact code that I have
written for this
particular case with the DHT11 sensor and the LED.

//House monitoring framework with Arduino and Raspberry Pi


//Cezar Chirila
//AllAboutCircuits.com
//epilepsynerd.wordpress.com

#include "ArduinoJson.h"
#include "dht.h"

dht DHT; //give name to your DHT sensor

#define DHT11_PIN A0 //Pin for DHT11 data


#define LED_PIN A1 //PIN for LED

void setup()
{
Serial.begin(9600);
}

void loop()
{
String str;
str = Serial.readString(); //Read serial
str.toLowerCase(); //Convert to lowercase
if (str == "thl")
do
{
str = Serial.readString(); //Read the serial again
send_data(); //Call send data function
} while (str != "ok"); //Continue to send data until we receive an "ok"
if (str == "led")
{
digitalWrite(LED_PIN, HIGH); // turn the LED on (HIGH is the
voltage level)
delay(1000); // wait for a second
digitalWrite(LED_PIN, LOW); // turn the LED off by making the
voltage LOW
}
}
void send_data()
{
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["temp"] = get_temperature();
root["humidity"] = get_humidity();
root.printTo(Serial);
Serial.println();
}

int get_temperature() // function that return the temperature as an integer


{
int temperature;
DHT.read11(DHT11_PIN);
temperature = DHT.temperature;
return (temperature);
}

int get_humidity() //function that return the temperature as an integer


{
int humidity;
DHT.read11(DHT11_PIN);
humidity = DHT.humidity;
return (humidity);
}

Setting Up the Web Server on Raspberry Pi


-------------------------------------

We will be using the Raspberry Pi as a web server using NGINX.


I will guide you through each step to install this, as well as other components
that are needed,
such as PHP.

Let’s explain some basics.


First of all, you need Raspbian installed on your Pi and a network connection.
Now, you can either connect a keyboard and a monitor to the board and open up the
terminal,
or do as I did and do it over SSH. Whichever method you use, remember that all
commands need
to be run as root; otherwise, you will get a permission error. This is done by
writing “sudo” in front.
All that being said, let’s start.

First, let’s update the repository and the packages.


If you are not familiar with Linux, what this does is update the place from which
the packages
(applications) are installed and then update them.

apt-get update
apt-get upgrade

We want to install NGINX, PHP, and git (optional, but makes your life easier).
When asked, type ‘y’ and press enter.

apt-get install nginx php5-fpm git

Now, we need to change the default NGINX directory and make it work with PHP.

cd /etc/nginx
vi sites-enabled/default

You need to make that file looks like this:

server {
listen 80; ## listen for ipv4; this line is default and implied
listen [::]:80 default_server ipv6only=on; ## listen for ipv6
root /var/www;
index index.html index.php;
# Make site accessible from http://localhost/
server_name _;
location / {
index index.html index.php;
# First attempt to serve request as file, then as
# directory, then fall back to the CMS.
try_files $uri $uri/index.html;
}

location /doc/ {
alias /usr/share/doc/;
autoindex on;
allow 127.0.0.1;
allow ::1;
deny all;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
}

Now restart NGINX.


service nginx restart
To test that everything is working, make a PHP test page.

cd /var/www
vi test.php

And put this into the test.php file:

<?php
phpinfo();
?>

Now navigate to Raspberry-Pi-Ip-Address/test.php (Ex: 192.168.0.2/test.php).

If you see a page with PHP info like the one below, then it works and you should
proceed to the next step.
If it does not work, then read this part again and check to see if you did
something wrong.

The last step is to input this code to allow the user www-data, which is the user
that NGINX uses, to access the serial port.

usermod -a -G dialout www-data


After this, do one more restart and take a break. You deserve it.

Website Files
------------

Hang in there, we're almost done.


You just need to download the files onto your Raspberry Pi and edit the m to your
needs.

You can manually download the files and put them into /var/www or you can execute
this command
and automatically download them from github:

cd /var/www
git clone https://github.com/alexonaci/Paranoid/tree/AAC

Now that we have the files, let’s examine them for a moment.
Just so you know, we are using bootstrap to model our website so that it is mobile-
compatible and looks good.

/img folder: Contains thumbnails and the background image for the index page
ArduinoCode.ino: The file that contains the Arduino sketch
PhpSerial.php: A library for PHP allowing us to communicate over serial with the
Uno using PHP
Style.css: The CSS for the page
Main.html: The most important page that contains the javascript, the buttons, and
the visual data
Relay.php: The file which initiates communication with the Arduino
You only need to worry about the main.html page; leave the rest as they are. Sure,
if you want,
you can customize them to your liking— it’s your project after all.

I will explain here how to add items. To add a new button, just add this line:

<div class="col-sm-2" class="jobs">


<h2 class="header-default" class="jobs-header"><img width=100
src="img/Thumbnail_Image"></h2>
<button type="button" id="Name_action" class="btn btn-danger"><span
class="glyphicon glyphicon-off"></span>On/Off</button>
</div>

Thumbnail_Image is the path to the image you want to use as the thumbnail
(remember to place it in the /img folder). Name_action is the name that you want to
pick for your button.
You can check the types of buttons you can use here.

Navigate to the bottom of the file where you can see the line "$("#led-
button").click(blinkLED);" and add below it:

$("#Name_action").click(Function_Name);

Just above it, add the function that relates to it:

function Function_Name ()
{
$.get(url + "Parameter")
}
“Parameter” is the string that it will be sent to your Arduino over serial when you
press the button.
It needs to be associated with a function inside the sketch. We talked about this
in the “Arduino Code” chapter.

To add a new item on the screen that will show a value that the Arduino sends, like
sensor data, add this type of item :

<div class="col-sm-2" class="jobs"//>


<h2 class="header-default" class="jobs-header"><img width=100
src="img/Thumbnail_image"></h2>
<h3>Display_data: </h3>
<div id="DataID"></div>
</div>

Where "Display_data" is the name that will appear before the data, such as
"temperature:",
and DataID is the identifier.

Remember when I said that we will receive data as JSON?


This is where it comes in handy. Search for the
“getLuminosityTemperatureHumidity()” function
and just add at the end of it:

$("#DataID").html(parsedJSON.name_of_data);

Where “name_of_data” is the string that you have chosen for the data in the Arduino
Code section.

There is a function that will call this function every 10 seconds and that is it.
setInterval(getLuminosityTemperatureHumidity,10000);

You can change the timing if you would like.

All there is left is for me to explain to you is how the relay.php script works.
It is open every time a function like “getLuminosityTemperatureHumidity()” calls.
In order to work, it uses the PhpSerial library. The first 8 lines that start with
"$serial->" are
to establish a serial connection to your Arduino.

ATTENTION! Every time this script is executed, the Arduino will reset.
If you do not wish for this to happen, simply connect a 10uF capacitor with the
negative pin to
GND and positive pin to RESET.

Now that we've gotten that out of the way, let's continue.
The "sleep(2);" line is needed because the Arduino is unresponsive for the first
few moments
when we open the serial connection. After that we send the parameter that we
received
via GET method, "$_GET["command"]", to the Arduino, and if that command is "thl" we
read
incoming data from the microcontroller. After the data has been received, we send
an "ok" and
return the data. That's it.

Here is how your project should look after following these steps:

Debugging
--------

If you are having trouble, such as not receiving data, the easiest place to start
debugging is right
in your browser. You need to be using Chrome for these instructions:
Just press F12, go to the Network tab, click on it, press F5 to refresh and click
on
"relay.php?command=thl". If everything works, the data should appear like in the
screenshot below:

Enjoy your house monitoring system. If you have any questions, please put them in
the comments
section and I will do my best to help you.

=================================================================================
AZARTICOLO:Decode 433 MHz signals w/ Raspberry Pi & 433 MHz Receiver
=================================================================================
http://www.princetronics.com/how-to-read-433-mhz-codes-w-raspberry-pi-433-mhz-
receiver/

BY PRINCE · PUBLISHED 06/18/2014 · UPDATED 05/29/2016

This post will show you how to read 433 MHz codes using a Raspberry Pi.
This tutorial was made to complement the Voice Controlling project which needed 433
MHz
Unit Code Values to control the wireless switches.

If you want to know how to read 433 MHz codes using an Arduino, go to this post!

I learned how to do this by reading this post. So credit goes to Paul Pinault for
making this project a reality.

Contents [hide]
1 Hardware Requirements
2 Installing WiringPi
3 Installing 433Utils
4 Connecting the 433 MHz receiver
5 Running the code
Hardware Requirements
Raspberry Pi(I used a Raspberry Pi Rev.2)
433 MHz receiver(Any type of 433 Mhz receiver should work, but for this tutorial I
used a 4 pin variant)
A breadboard
Some jumper wires
A 433 MHz transmitter(I used a 4 channel 433 MHz transmitter Remote)

Installing WiringPi
---------------

WiringPi is needed to control the pins on the Raspberry Pi. Which will be connected
to the 433 MHz Receiver.

To install WiringPi, SSH into your Raspberry Pi or open up a console, then run
these commands:

cd ~/
git clone git://git.drogon.net/wiringPi
cd wiringPi
./build

cd ~/
git clone git://git.drogon.net/wiringPi
cd wiringPi
./build
After running the last command, WiringPi should be installed!

Installing 433Utils
---------------
433Utils is made by GitHub user wolfeidau.
He gathered a bunch of code and wrote some himself, all about 433 MHz Radio
Transmissions,
then made a repo of it.

To install 433Utils, run these commands:

cd ~/
git clone git://github.com/ninjablocks/433Utils.git
cd 433Utils/RPi_utils
make

cd ~/
git clone git://github.com/ninjablocks/433Utils.git
cd 433Utils/RPi_utils
make
Now 433Utils should be installed!

Connecting the 433 MHz receiver


receiver

As you can see in the picture, my 433 MHz receiver actually has two Data-pins.
Why it has two pins I don’t exactly know, but a possibility is it is used to easily
connect
two output-sources, or two different Arduinos.

In this project however we will only need to use one of the pins.
I used the one closest to the GND-pin.
If anybody knows why it has two Data-pins, let me know in the comments!

The code we will be running will be speaking out to the GPIO2 pin, according to
this site,
GPIO2 is GPIO pin 21 on Rev.1, or GPIO pin 27 on Rev.2

Here is an image of the P1 pin header on the Raspberry Pi Rev.1.


GPIO pin 21 and 27 should be on the same pin on both versions.

GPIO-Pins-Layout

Basically the connection between the receiver and Raspberry Pi can be described
with a table.

Raspberry Pi Pin 433 MHz Receiver Pins


GND GND
5V VCC
GPIO 21/27 Data

Here is how the connection looks like to me, I’m using a breakout board and a
breadboard.
rpi433Sniffer

Running the code


--------------

To start listening for the 433 MHz codes, start the RFSniffer program we got from
433Utils,
using this command.

~/433Utils/RPi_utils/RFSniffer

I used a simple 4 channel 433 MHz Remote to send some 433 MHz codes to my receiver.

remote

Now bring your 433 MHz transmitter remote VERY close to your receiver, and press
some buttons.
The range of the receiver is not very far on the Raspberry Pi, so make sure you
bring the remote
as close as you can.

The received codes should print out as you press the buttons on the remote.
I’m using terminal and for me it looks like this:

RFSniffer

Pressing the buttons on my transmitter prints out values ranging between 16738081-
16738088.

Congrats, you now know how to print out 433 MHz codes using your Raspberry Pi & 433
MHz Receiver!

If you have any questions feel free to ask me by using the Contact page or by
commenting below.

===================================================================================
=======
AZARTICOLO:RASPBERRY PI AND ARDUINO CONNECTED USING I2C
===================================================================================
=======
https://oscarliang.com/raspberry-pi-arduino-connected-i2c/

Share this:
Facebook37GoogleTwitterReddit

With Raspberry Pi and I2C communication, we can connect the Pi with single or
multiple Arduino boards. The Raspberry Pi has only 8 GPIO’s, so it would be really
useful to have additional Inputs and outputs by combining the Raspberry Pi and
Arduino.

There are many ways of Linking them such as using USB cable and Serial Connection.
Why do we choose to use I2C? One reason could be it does not use your serial, USB
on the Pi. Given the fact that there are only 2 USB ports, this is definitely a big
advantage. Secondly, flexibility. You can easily connect up to 128 slaves with the
Pi. Also we can just link them directly without a Logic Level Converter.
In this article I will describe how to configure the devices and setup Raspberry Pi
as master and Arduino as slave for I2C communication. Article1 and Article2 if you
don’t know what is I2C.

In the next article I will be doing some Voice Recognition, if you are interested
see here Raspberry Pi Voice Recognition Works Like Siri

How Does It Work? Is It Safe?

The Raspberry Pi is running at 3.3 Volts while the Arduino is running at 5 Volts.
There are tutorials suggest using a level converter for the I2C communication. This
is NOT needed if the Raspberry Pi is running as “master” and the Arduino is running
as “slave”.

The reason it works is because the Arduino does not have any pull-ups resistors
installed, but the P1 header on the Raspberry Pi has 1k8 ohms resistors to the 3.3
volts power rail. Data is transmitted by pulling the lines to 0v, for a “high”
logic signal. For “low” logic signal, it’s pulled up to the supply rail voltage
level. Because there is no pull-up resistors in the Arduino and because 3.3 volts
is within the “low” logic level range for the Arduino everything works as it
should.

Raspberry-PI-I2c-Arduino-connected

Remember though that if other I2C devices are added to the bus they must have their
pull-up resistors removed. For more information, see here.

These are the images showing where the I2C pins are on the Raspberry Pi and
Arduino.

Note that the built-in pull-up resistors are only available on the Pi’s I2C pins
(Pins 3 (SDA) and 5 (SCL), i.e. the GPIO0 and GPIO1 on a Rev. 1 board, GPIO2 and
GPIOP3 on a Rev. 2 board:

I2C Raspberry Pi and Arduino Connect Link

On the Arduino Uno, the I2C pins are pins A4 (SDA) and A5 (SCL), On the Arduino
Mega, they are 20 (SDA), 21 (SCL)

I2C Raspberry Pi and Arduino Connect Link

For information about the Arduino I2C Configuration and for other models of
Arduino, check out this documentation Wire library.

Setup Environment on Raspberry Pi for I2C Communication

I will describe the process briefly here, if you are in doubt please refer to a
more detailed process here and here.

Remove I2C from Blacklist:

$ cat /etc/modprobe.d/raspi-blacklist.conf
# blacklist spi and i2c by default (many users don't need them)
blacklist spi-bcm2708
#blacklist i2c-bcm2708
Load i2c.dev in Module File
Add this to the end of /etc/modules

i2c-dev
Install I2C Tools

$ apt-get install i2c-tools


Allow Pi User to Access I2C Devices

$ adduser pi i2c
Now reboot the RPI. After that you should see the i2c devices:

pi@raspberrypi ~ $ ll /dev/i2c*
crw-rw---T 1 root i2c 89, 0 May 25 11:56 /dev/i2c-0
crw-rw---T 1 root i2c 89, 1 May 25 11:56 /dev/i2c-1
Now we run a simple test, scan the i2c bus:

pi@raspberrypi ~ $ i2cdetect -y 1
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

Hint: if you’re using the first revision of the RPI board, use “-y 0″ as parameter.
The I2C bus address changed between those two revisions.

Install Python-SMBus

This provides I2C support for Python, documentation can be found here.
Alternatively, Quck2Wire is also available.

apt-get install python-smbus


Configure Arduino As Slave Device For I2C

Load this sketch on the Arduino. We basically define an address for the slave (in
this case, 4) and callback functions for sending data, and receiving data. When we
receive a digit, we acknowledge by sending it back. If the digit happens to be ‘1’,
we switch on the LED.

This program has only been tested with Arduino IDE 1.0.

[sourcecode language=”cpp”]

#include <Wire.h>

#define SLAVE_ADDRESS 0x04


int number = 0;
int state = 0;

void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600); // start serial for output
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveData);
Wire.onRequest(sendData);

Serial.println(“Ready!”);
}

void loop() {
delay(100);
}

// callback for received data


void receiveData(int byteCount){

while(Wire.available()) {
number = Wire.read();
Serial.print(“data received: “);
Serial.println(number);

if (number == 1){

if (state == 0){
digitalWrite(13, HIGH); // set the LED on
state = 1;
}
else{
digitalWrite(13, LOW); // set the LED off
state = 0;
}
}
}
}

// callback for sending data


void sendData(){
Wire.write(number);
}

[/sourcecode]

Configure Raspberry Pi As Master Device

Since we have a listening Arduino slave, we now need a I2C master.

I have written this testing program in Python. This is what it does: the Raspberry
Pi asks you to enter a digit and sends it to the Arduino, the Arduino acknowledges
the received data by send the exact same number back.

In the video, I used a built-in programming tool called “IDLE” in Raspberry Pi for
compiling.

[sourcecode language=”python”]

import smbus
import time
# for RPI version 1, use “bus = smbus.SMBus(0)”
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program


address = 0x04

def writeNumber(value):
bus.write_byte(address, value)
# bus.write_byte_data(address, 0, value)
return -1

def readNumber():
number = bus.read_byte(address)
# number = bus.read_byte_data(address, 1)
return number

while True:
var = input(“Enter 1 – 9: “)
if not var:
continue

writeNumber(var)
print “RPI: Hi Arduino, I sent you “, var
# sleep one second
time.sleep(1)

number = readNumber()
print “Arduino: Hey RPI, I received a digit “, number
print
[/sourcecode]

For more read/write functions, check out this useful look up table for the
functions.

Connect Your Arduino With Raspberry Pi

Finally, we need to connect the Raspberry Pi and Arduino on the I2C bus. Connection
is easy:

RaspberryPI-I2c-Arduino

RPI Arduino (Uno/Duemillanove)


--------------------------------------------
GPIO 0 (SDA) <--> Pin 4 (SDA)
GPIO 1 (SCL) <--> Pin 5 (SCL)
Ground <--> Ground
To make sure this is working, run i2cdetect -y 1 again in the terminal, you should
get something like this. 04 is the address we defined in the Arduino sketch.

pi@raspberrypi ~ $ i2cdetect -y 1
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- 04 -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
That’s the end of this article, for results, please see video on top. From here,
you can add sensors to the Arduino, to send data back to the Raspberry. Or have
servos and motors on the Arduino that can be controlled from the Raspberry Pi. It’s
just Fun.
Updates: 07/07/2013

Someone messaged me asking how to use logic level converter for i2c connection
between Raspberry Pi an d Arduino. I happen to have a spare Logic Level converter,
so I gave it a go.

This is how I connect them.

GPIO0 (SDA) -- | TX1 -- TX0 | -- A4 (SDA)


GPIO1 (SCL) -- | RX0 -- RX1 | -- A5 (SCL)
3.3V -- | LV -- HV | -- 5V
GND -- | GND -- GND | -- GND
08745-04-L

But the result was a little weird. The data successfully sent to the Arduino, and
the data was also received successfully from the Arduino on the Pi, but the data
was wrong at the raspberry pi side.

When I sent number 1 to the Arduino, I got 0 back.


When I sent 2, I got 1 back.
sent 3 and got 1 back
sent 4 and got 2 back… etc…
I don’t know why this is happening, something to do with the converter? or maybe
the connection is wrong? I don’t have time to figure this out. Since I can get it
working without a logic level converter, i will leave it for now, if you do know
why, please let me know.

Related
Raspberry Pi and Arduino Connected Over Serial GPIO
Raspberry Pi and Arduino Connected Over Serial GPIO
21st May 2013
In "Electronics"
Connect Raspberry Pi and Arduino with Serial USB Cable
Connect Raspberry Pi and Arduino with Serial USB Cable
20th May 2013
In "Electronics"
Raspberry Pi Face Recognition Using OpenCV
Raspberry Pi Face Recognition Using OpenCV
9th June 2013
In "Electronics"
Posted in Electronics, Featured, Raspberry Pi and tagged arduino, raspberry pi on
25th May 2013. 97 Replies
Post navigation← Raspberry Pi and Arduino Connected Over Serial GPIORaspberry Pi
Voice Recognition Works Like Siri →
97 thoughts on “Raspberry Pi and Arduino Connected Using I2C”

Michael

===================================================================================
=======
AZARTICOLO:COME TRASFORMARE LA NOSTRA RASPBERRY PI3 CON UNA SEMPLICE WEBCAM
IN UN SERVIZIO STREAMING LOCALE
===================================================================================
=======

Il procedimento è molto semplice

Prima cosa installiamo sulla nostra raspberry i programmi che utilizzeremo per
lo streaming con i seguenti comandi:

$ apt-get install motion


$ apt-get install libv4l-0
$ apt-get install uvccapture

Andiamo a cambiare stato di default del nostro demone motion scrivendo il comando:

$ vi /etc/default/motion

Ed andiamo a modificare “start_motion_daemon no“

in “start_motion_daemon yes“

Poi andiamo a configurare il nostro motion onserendo il comando: in

$ vi /etc/motio/motion.conf

E modifichiamo:

daemon on (da “off”)

stream_localhost off (da “on”)

framerate 30 (da “2”) non impostatelo troppo alto o vi intaserà la rete

stream_maxrate 10 (da “1”)

Adesso siamo pronti per far partire programma e servizio

$ service motion start


$ motion start

Per fermarlo:

$ motion stop
$ service motion stop

Infine aprimao il web browser aggiungendo :8081 alla fine dell’indirizzo IP della
nostra raspberry ( se non siete in grado di individuarlo, basta lanciare il
comando:
ifconfig)

es. 192.168.0.108:8081

The following two tabs change content below.


Bio
Ultimi Post
salvatore famà
salvatore famà
Navigazione articolo
ARTICOLO PRECEDENTE
Come configurare la raspberry pi3 in un access point con hostapd
ARTICOLO SUCCESSIVO
Schiena stampata in 3D scala 1:1
Idee e progetti

Ricerca per:
Cerca …
ARTICOLI RECENTI

Stepper motor con Arduino


Come controllare la raspberry pi da desktop remoto con windows
Schiena stampata in 3D scala 1:1

================================================================================
AZARTICOLO:SERVER MQTT CON RASPBERRY PI 3
================================================================================
http://www.robot-domestici.it/idea/?p=252
https://github.com/fabaff/mqtt-panel

in questa guida vi illustriamo come creare un server MQTT


(Message Queuing Telemetry Transport), che è un protocollo di comunicazione
fra client e server a basso traffico di dati.

per creare il nostro server ci serve:

– una scheda Raspberry Pi 3 (l’ultima uscita), che potete acquistare qui;


-l’alimentatore dedicato che trovate qui;
-un case per il raspberry pi 3
-Una scheda microSD da almeno 8 giga
-Cavo HDMI (solo per la fase iniziale di
configurazione);
-Una tastiera ed un mouse (solo per la fase iniziale di configurazione);

adesso installiamo raspian Jessie sulla micro-SD.

inserite la microSD nel vostro computer:

-UTENTI WINDOWS: dovete scaricare il programma Win32DiskImager

Cattura
------------

-UTENTI LINUX: potete divertirvi dal terminale col comando dd oppure utilizzare
Unetbootin

UNetbootin
---------------

(Ci vorrà del tempo, dipende dalla classe della SD e dal vostro computer).
adesso incominciamo a configurare il nostro server.

inserire la scheda microSD nel Raspberry Pi 3 , e collegate tastiera, mouse,


alimentazione
ed il cavo HDMI. (il raspberry Pi 3 si accenderà)
per connetersi alla propria rete wi-fi dal raspberry Pi 3 clicccare dove è indicato
dalla
freccia,si aprirà un menù con le reti wi-fi intorno a voi cliccare sulla propria
rete wi-fi ed
inserite la vostra password. il raspberry pi si sarà connesso ad internet ed aprite
il terminale

digitare

apt update && apt upgrade && apt dist-upgrade && apt install mosquitto

la password è “raspberry” (se non fa vedere che digitate è normale).


quando chiede di dare conferma premere y ed invio.

passiamo a configurare il raspberry PI 3 per avere un ip statico (si può fare


in due modi o dal router oppure modificando un file del raspberry Pi 3
(noi faremo vedere la seconda opzione):

aprire il file

vi /etc/network/interfaces

e aggiungere quanto segue dopo “iface wlan0 inet manual”

#indirizzo ip del router


premere ctrl+x poi y ed invio, invio per salvare

passiamo alla configurazione del server MQTT:


---------------------------------------------------------

vi /etc/mosquitto/mosquitto,conf

ed incollare quanto segue

pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d

#config by matteo bocci ([email protected])


#porta che usa il server
port 1883
allow_anonymous false
connection_messages true
use_identity_as_username true
password_file /etc/mosquitto/passwd
premere ctrl+x poi y ed invio ed invio per salvare

creare il file della password con

mosquitto_passwd -c /etc/mosquitto/passwd mosquitto

settare il server mqtt che si avvia al boot del sistema, digitare:

crontab -e

poi premere sul 2 ed alla fine del file scrivere quanto segue.

@reboot mosquitto -d -c /etc/mosquitto/mosquitto.conf

premere ctrl+x poi y ed invio ed invio per salvare

riavviarre il raspberry Pi 3 con

reboot -h now

ora si può scollegare il raspberry Pi 3 da tutto tranne la microSD e


l’alimentazione.
==============================================================
AZARTICOLO:How to control a Raspberry Pi using WhatsApp
==============================================================
http://www.techradar.com/how-to/computing/how-to-control-a-raspberry-pi-using-
whatsapp-1315610/2
By Mayank Sharma February 24, 2016How To
Build a PiBot monitor

WhatsApp is one of the most popular messaging apps and you can use it with the
Raspberry Pi.
The Yowsup Python library enables you to use your WhatsApp account to exchange
messages with your contacts.

After the novelty of messaging your friends from the Raspberry Pi wears off, you
can use the Yowsup library to monitor and control the Pi by sending messages via
WhatsApp.

Before you can install the Yowsup library, fetch its dependencies with:

$ apt-get install git python-dev libncurses5-dev

Then use:

$ git clone git://github.com/tgalal/yowsup.git

to download the library under the current directory, and install it with:

$ cd yowsup

$ python setup.py install

How to control a Raspberry Pi using WhatsApp


------------------------------------------------------------------------
There isn't much documentation for the Yowsup library, but it does ship with some
useful example
applications, which make for an interesting study

Once the library has been installed, it's time to register your mobile number with
WhatsApp.
In the yowsup directory, create a file called mydetails with the following:

$ vi mydetails

cc=44

phone=447712345678

The cc option points to the country code, which is 44 in the UK.


Replace it and the phone number with your particulars. Make sure you don't enter
the + symbol.
Then save the file and use the following to ask WhatsApp for a registration code:

$ python yowsup-cli registration --config mydetails

--requestcode sms

After a few seconds, you should receive an SMS on the phone with the SIM card for
the number
you've entered in the mydetails file. The message contains a six-digit code.
Use this to register the phone number with WhatsApp:

$ python yowsup-cli registration --config mydetails --register

xxx-xxx

Replace xxx-xxx with your code. After a second or two, you'll receive a response
from WhatsApp
on the Pi that will look something like this:

status: ok

kind: free

pw: jK0zdPJ9zz0BBC3CwmnLqmxuhBk=

price: 0.89

price_expiration: 1434674993

currency: EUR

cost: 0.89

expiration: 1463544490

login: 448375972334

type: new

The only bit of information we're interested in is the password mentioned with the
pw variable.
Copy it and paste it in the mydetails file, which should now read:

cc=44

phone=447712345678

password=jK0zdPJ9zz0M8G3CwmnLqmxuhBk=

That's all there's to it. The Yowsup library includes a demo application, which you
can use to
send and receive messages. Bring it up with:

$ yowsup-cli demos --yowsup --config mydetails

This brings up the Yowsup command line client. Type /help to see all the available
commands.
The [offline] prompt indicates that you aren't connected to the WhatsApp servers.
Use the /L command, which picks up the authentication information from the
mydetails file and
connects to the server.

The prompt now changes to [connected].

You can now send messages to other WhatsApp users. To send a message to
449988776655 enter:
/message send 449988776655 "Hiya mate, I'm sending this from the Raspberry Pi!"

If the recipient responds with a message, it is displayed on the console on the


Raspberry Pi. To end the session, use the /disconnect command to quit.
What's up Pi!

The real advantage of the Yowsup library is that it can be used to invoke actions
on the Raspberry Pi, so for example you can send a WhatsApp message to check
certain details on the Raspberry Pi, such as its disk space or temperature, then
maybe update it or shut it down.

You can also use it to influence the GPIO pins and control any connected
peripherals – a door, for example. You can use the Python script in Listing 1 to
interact with the Raspberry Pi. The script listens to messages from a certain
predefined number, recognises certain keywords and responds accordingly.

How to control a Raspberry Pi using WhatsApp

Advertisement
----------------------

So if you send something like 'Hiya Pi', it greets you back. If it receives a
message that begins
with 'memory', the Raspberry Pi executes the df -h . command and messages you the
results.

The script uses classes created by Italian blogger Carlo Mascellani.


They are housed with two files, named wasend.py and warecieve,py, which you can
download with:

$ wget http://www.mascal.it/public/wasend.py
$ wget http://www.mascal.it/public/wareceive.py

In the same directory, create a file called pitalk.py with the contents of Listing
2
(which again can be found here). Now create a shell script called talktome.sh that
calls the
pitalk.py Python script:

$ vi talktome.sh

#!/bin/bash

while :

do

python /home/pi/yowsup/pitalk.py

done

Now make it executable with chmod +x talktome.sh and make sure it runs
automatically whenever
the Pi boots up by pointing to it in the /etc/rc.local file:

$ vi /etc/rc.local

/home/pi/yowsup/talktome.sh
Save the file and reboot the Raspberry Pi, and the script starts automatically.
Let's break down the script to understand it better.
The credential() function at the top helps connect the script to the WhatsApp
server by using the
credentials for your account.

Make sure you edit both the parameters in this function. The Answer() function
specifies the WhatsApp number our Raspberry Pi communicates with. This is important
because we don't want just anybody to control our Raspberry Pi.

Parsing the script


--------------------------

Then we define the functions that do the actual task we query the Raspberry Pi for
via the WhatsApp messages, eg the Refresh() function refreshes the repository list
and Restart() reboots the Raspberry Pi. The Temp() and Disk() functions are a
little more complex.

The former fetches and truncates the temperature information, as illustrated


earlier in the tutorial. Similarly, Disk() formats and rearranges the output of the
df -h command for easier reading.

How to control a Raspberry Pi using WhatsApp

In the main part of the program (the while loop), the script waits for a message,
and when it gets one, it raises a MessageReceived exception. The received message
begins with a phone number followed by a message, such as "449876543210Message".

When it raises the exception, the script first converts the whole string to
lowercase with the value.lower() method. It then checks whether the message is from
the number it's supposed to respond to. If it isn't, the script appends it to a log
file and doesn't respond.

If, however, the phone number is correct, the script then strips the number from
the message and just leaves the textual bit. The If conditions then parse the
message to decide how to respond. We've used different types of matching to give
you an idea of what's possible.

The first two look for matching characters at the start of the text, eg if
received[:4]=="hiya": Answer("Hi chap!") is triggered if the first four characters
of the message are h, i, y and a, and responds with 'Hi chap!' . This condition is
met even if the message it receives is, 'Hiya Raspberry Pi, are you online?'

The second also looks for matching characters at the beginning of the message but
is triggered if it finds either of the two strings (restart or reboot). The next
three do a different kind of matching. They're triggered if their corresponding
text is in any part of the message and not just at the beginning.
Advertisement

So if you send a "What's the status of your disk?" message, the script picks up the
"disk" keyword and triggers the Disk() function. Similarly, if you send a 'You're
not running too hot, are you?' message, the script picks up the 'hot' keyword and
responds with a readout from its temperature sensor.

If it fails to pick up any keywords, the scripts just responds with the "Eh? What
was that?" message. You can extend this script for a whole variety of home
automation tasks. You can even hook up the Raspberry Pi camera module and use the
Python Picam library to take pictures or videos and send them to you via a WhatsApp
message.
Check the Yowsup library's wiki page for some examples of rolling the script into
usable applications.

Enjoyed this article? Expand your knowledge of Linux, get more from your code,
and discover the latest open source developments inside Linux Format. Read our
sampler today and take advantage of the offer inside.

Related product: Sound Radix Pi

===================================================================================
========
AZARTICOLO:How to guard your home with Raspberry Pi
===================================================================================
========

By Linux Format August 07, 2015How To


Guard your home with a Pi

The Raspberry Pi is an impressive platform for prototyping projects of any scale.


From a simple blinking LED to a quadcopter, anything is possible with a Raspberry
Pi –
all you need is a little imagination and some extra components.

One of the most interesting areas of practical use is sensing the world around us,
and using the
data gathered in all sorts of ways. The world is full of data just waiting to be
recorded and manipulated
– for example, weather stations come with many different sensors to measure
temperature, wind speed,
humidity and pressure.

All this data can be stored and manipulated by a savvy hacker to produce graphs and
tables
that can be imported into other applications or projects. And of all the sensors on
the market,
the cheapest and most simple is the humble PIR, which is present in so many parts
of everyday life.

Raspberry Pi

PIR plans

Passive infrared sensors (PIR) are commonly used in devices such as triggers for
burglar alarms
in homes and offices. In fact, they are so cheap that they're found inside motion-
activated air fresheners,
which could be a ripe source of components for this project.

The PIR sensor works on the simple principle of sending a beam of infrared light
into a room.
If the beam remains unbroken – by which we mean there is no movement in the room –
no action is taken.

But the second the beam is broken, a signal is sent to a device that's programmed
to respond in
a certain manner. These PIR sensors are very cheap – around £4 (about $6, AU$8.40)
delivered on
eBay – and they are also an excellent starter project because they require very
little breadboarding
or prototyping.

For our project, we will set up a PIR sensor to watch an area for any movement.
Once movement is detected, it will trigger the code to complete a sequence of
events that will
capture a picture of the event and record a short 10-second video at a resolution
of 640 pixels by 480 pixels.

The project will culminate with a text message being sent to our phone, alerting us
to an intruder
or other event. To explain how this project will work, we'll illustrate it using
pseudocode, which is
a way of explaining a programming sequence using easy-to-understand language.
Here's how the project will work in pseudo code:

PIR sensor sends out a beam.

If the beam is broken.

Send a signal to our Raspberry Pi.

On receiving the signal, the Raspberry Pi will take a picture of the activity.

The Pi will then record 10 seconds of video.

After the picture is created, the Pi will attempt to send a text alerting us to the
activity.

This text will contain a picture and video .

Once the text has been sent, the Pi will wait for 30 seconds before looping the
process.

So where could you use this project?


The most obvious answer would be home security but let's think of something nicer.

In the summer there are lots of plants growing and animals moving in the sunshine,
so why not use your Raspberry Pi and this project to capture the joys of summer?

You could house this project in a weatherproof case and leave it outside to record
animal life.
In fact, a project similar to this was used to monitor the feeding patterns of
birds caring for their
offspring.

A sensor was placed near the nesting box, and this would record the comings and
goings of the
parent birds. This data was then linked to weather data for that area.

When comparing the data, it became clear that the natural food of birds – insects –
were not as abundant when the weather was rainy or windy.
This meant the offspring were not being fed as often.

Alert! Alert! In this project, we're choosing to alert the user via a text message,
because no
matter what type of phone you have, and what type of signal you receive, a text
message is more
reliable as a method of delivery than an email or tweet, which rely on 3G or Wi-Fi
coverage to
receive data.

This project can be built upon to include other methods of delivering the alert –
in fact, you can send more than one alert from the project.

To send an email, you can use the smtplib, and we found a great how-to.
You can also send a tweet from Python using the tweepy library.

To do this you will need to create an application via https://dev.twitter.com.


Once you have completed this part of the process, you can import the API key into
tweepy and
use it to send and receive tweets.

You can read more about tweepy via its website.


The pictures and video that are captured in this project are stored on our
Raspberry Pi for later
retrieval via any means that is convenient.

How to guard your home with Raspberry Pi

By Linux Format August 07, 2015How To

Guard your home with a Pi


-----------------------------------------

In brief, our goal is to build an alarm system with our Raspberry Pi that's
triggered by a
PIR sensor, which detects movement.

Once the alarm is tripped, a camera will take a quick picture of the event, and
then record 10
seconds of video. To alert the user that the alarm has been triggered a text
message is sent.
So let's get started!

Raspberry Pi

1. Connect the PIR


----------------------------

Our PIR sensor needs three connections to work: VCC (5V), Out and Ground (GND).
To connect our sensor to the Raspberry Pi, we need to use female to female jumper
cables.

You can buy them from many online retailers. On the sensor, locate the VCC pin and
gently push
a cable until it is firmly in place.

On your Raspberry Pi, locate Pin 2 and gently push the VCC cable into place.
We connect the VCC pin on the PIR sensor to a 5V pin on a Raspberry Pi, which is
Pin 2.

When connecting anything to the GPIO, ensure that the Raspberry Pi is powered off
and that all connections are checked before powering on your Raspberry Pi.

Raspberry Pi

2. Ground and Out


----------------------------

We then need to repeat the process and connect the GND pin of our sensor to GND on
a Raspberry Pi, which is Pin 6. Lastly, we connect our Out pin to Pin 7.

For our connection to the PIR sensor, we will require no resistors inline as the
PIR has a diode to protect the board, and the signal sent via the Out pin is 3V and
safe with our Raspberry Pi.

Our PIR sensor needs three connections to work: VCC (5V), Out and Ground (GND). To
connect our sensor to the Raspberry Pi, we need to use female to female jumper
cables. You can buy them from many online retailers. On the sensor, locate the VCC
pin and gently push a cable until it is firmly in place.

On your Raspberry Pi, locate Pin 2 and gently push the VCC cable into place. We
connect the VCC pin on the PIR sensor to a 5V pin on a Raspberry Pi, which is Pin
2. When connecting anything to the GPIO, ensure that the Raspberry Pi is powered
off and that all connections are checked before powering on your Raspberry Pi.

Raspberry Pi

3. Connect the camera


----------------------------------

Our next piece of hardware is the Raspberry Pi Camera, and to insert the camera,
you need to locate a plastic port between the HDMI and Ethernet port on the board.

Gently lift the plastic lock from the port and then slide the ribbon cable into the
slot, with the silver strips of the ribbon facing the HDMI port.

Once fully slid into place, press the plastic lock back into its original position.
The ribbon cable will now be locked in place.

How to guard your home with Raspberry Pi

By Linux Format August 07, 2015How To


Guard your home with a Pi

Raspberry Pi

1. Enable the camera

Now we have our hardware installed, it's time to configure the software that will
control it.
Firstly we need to set up our camera and that is done via this command – in a
terminal type:

raspi-config

In the menu, there is an option to 'Enable the camera' – move to there and then
press [Enter].
You will now be asked whether you would like to enable the camera, so move the
cursor to
'Enable' and press [Enter]. You will now return to the original menu, so move your
cursor to
'Finish' and press [Enter].

2. Test the camera


---------------------------
Now we have told the Raspberry Pi to use the camera, we need to test that it can
take a picture,
and the best way to do that is via this command in the terminal:

raspistill -o test.jpg

This command will launch an application to take a picture using the camera.
If you encounter any errors, check that you have the correct syntax and that the
camera is enabled
in the raspi-config menu.

The last thing to check should be the physical connection between the camera and
the Raspberry Pi.

Raspberry Pi

3. Install pip
------------------

In order to use the camera with Python, we need to download the library picamera,
and the best
way to do this is via a package manager for Python called pip.

Pip works in the same way that apt-get works on your Raspberry Pi, and it is a
great tool to keep
your projects up to date. To use pip we first need to install it via a terminal.

Raspberry Pi

4. Install picamera
---------------------------

To install pip, type in the following:

apt-get update

apt-get install python-pip

pip install picamera

Pip will now install the picamera library for Python. Now it is time to grab a copy
of the project code.
Download the project as a zip file.

5. Open the project files


------------------------------------

To use the project files, we need to open idle, the Python editor, but because we
are using the
GPIO, we need to do so using:

idle

This will open the idle application, and in the application, go to 'File > Open'
and then navigate
to where your project files are located. We will be working with pir_alarm.py.

6. Added extras
------------------------

In our code we have a section that imports extra functionality; these are
libraries.
The first is time, which enables control of our program.

Next we import datetime, which enables our program to use calendar dates and clock
times.
Next we import the RPi.GPIO library but rename it to GPIO to make it easier to use.

We then import picamera which enables the use of the official Pi camera with
Python.

How to guard your home with Raspberry Pi

By Linux Format August 07, 2015


How To Guard your home with a Pi

Raspberry Pi

1. Store the pin number


-----------------------------------

Earlier we referred to connecting the Out pin of the PIR sensor to Pin 7 of our
Raspberry Pi.

Well, in order to be efficient with our code, we need to create a variable that
stores the pin
number ready for use in our code.

To do that, use the following code:

pir = 7

By doing this, we can easily change the pin in our code if we need to.

2. Enable text messages


------------------------------------

Creating a function called sms() on line 14 is a great way contain the code kindly
provided by
smspi.co.uk.

Using three arguments called to, message and hash we can easily pass the target
phone number,
the alert message and the unique hash which permits the use of the SMSpi text
message gateway.

To use the text message service, you will need to sign up for a free login and hash
to use in your project.

3. Easier coding
-------------------------

In the code you can see:

GPIO.setup(pir, GPIO.IN)

This line of code sets our pin 7, which is referenced as a variable called pir, as
an input, so that
it waits to receive a signal from the sensor.

The next line of code shortens the full picamera function down to just camera
making it easier
to work with.

camera = picamera.PiCamera()

4. How the main loop works


------------------------------------------

If the alarm is triggered.

Get the date and time and convert it to a string.


Alter the string to only contain the first 20 characters.
Create the message and file name for the alert.
Take the picture and record 10 seconds of video.
Use the sms function to send the alert to our phone.
Sleep for 30 seconds.

Loop the process if the alarm is triggered.

SMSpi
-----------

The team at SMSpi project has kindly provided its Python code for this project.
SMSpi offers a free text messaging service for Pibased projects.
The SMSpi project is powered by Raspberry Pi; all your texts are routed via the
same device
that is powering our alarm.

Advertisement
----------------------

The API can be dropped into most common programming languages, including CURL,
PERL,
Python, PHP and Ruby.

To use the service, you need to sign up for a free login, which then allows access
to the network
via a hash that acts as your unique key.

Using the service, you can easily send SMS messages over the SMSpi network, as
proven by
this project, but you can also receive text messages and have them forwarded to an
email address
or posted to a web page for use in web apps.

Once you have your hash, paste it into your Python project code on line 11.

With your alarm now installed and working, you need to remotely access your
Raspberry Pi to
see the pictures and video.

The easiest way would be to remove the card and view the media on your computer.
But you could enable SSH on your Raspberry Pi via the raspi-config advanced menu
and then
use your file manager to SSHFS into the folder where the pics are.

If you are feeling adventurous, you could install lighttpd or nginx to serve the
content over a network.
The choice is yours but remember to be careful with sharing the images over an open
connection
to the internet.

Find out what else you can do with the tiny PC with our collection of Raspberry Pi
Projects

Related product: Sound Radix Pi

Boost BGP Network Performance by 42% - [Free Demo]

===================================================================================
============
AZARTICOLO:How to migrate MySQL to MariaDB on Linux
===================================================================================
============
http://xmodulo.com/migrate-mysql-to-mariadb-linux.html

Last updated on August 14, 2015 Authored by Kristophorus Hadiono Leave a comment
Since the Oracle's acquisition of MySQL, a lot of MySQL developers and users moved
away from
MySQL due to Oracle's more closed-door stance on MySQL development and maintenance.
The community-driven outcome of such movement is a fork of MySQL, called MariaDB.
Led by original MySQL developers, the development of MariaDB follows the open-
source philosophy and makes sure of its binary compatibility with MySQL.
The Linux distributions such as Red Hat families (Fedora, CentOS, RHEL), Ubuntu and
Mint,
openSUSE and Debian already started to use and support MariaDB as a drop-in
replacement of MySQL.

If you want to migrate your database from MySQL to MariaDB, this article is what
you are looking for. Fortunately, due to their binary compatibility, MySQL-to-
MariaDB migration process is pretty much straightforward. If you follow the steps
below, the migration from MySQL to MariaDB will most likely be painless.

Prepare a MySQL Database and a Table


For demonstration purpose, let's create a test MySQL database and one table in the
database before doing the migration. Skip this step if you already have existing
MySQL database(s) to migrate to MariaDB. Otherwise proceed as follows.

Log in into MySQL from a terminal by typing your MySQL root user password.

$ mysql -u root -p
Create a database and a table.

mysql> create database test01;


mysql> use test01;
mysql> create table pet(name varchar(30), owner varchar(30), species varchar(20),
sex char(1));
Add some records to the table.

mysql> insert into pet values('brandon','Jack','puddle','m'),


('dixie','Danny','chihuahua','f');
Then quit the MySQL database.
Backup the MySQL Database
The next step is to back up existing MySQL database(s). Use the following mysqldump
command to export all existing databases to a file. Before running this command,
make sure that binary logging is enabled in your MySQL server. If you don't know
how to enable binary logging, see the instructions toward the end of the tutorial.

$ mysqldump --all-databases --user=root --password --master-data > backupdb.sql

Now create a backup of my.cnf file somewhere in your system before uninstalling
MySQL. This step is optional.

$ cp /etc/mysql/my.cnf /opt/my.cnf.bak
Uninstall MySQL Package
First, you need to stop the MySQL service.

$ service mysql stop


or:

$ systemctl stop mysql


or:

$ /etc/init.d/mysql stop
Then go ahead and remove MySQL packages and configurations as follows.

On RPM based system (e.g., CentOS, Fedora or RHEL):

$ yum remove mysql* mysql-server mysql-devel mysql-libs


$ rm -rf /var/lib/mysql
On Debian based system (e.g., Debian, Ubuntu or Mint):

$ apt-get remove mysql-server mysql-client mysql-common


$ apt-get autoremove
$ apt-get autoclean
$ deluser mysql
$ rm -rf /var/lib/mysql
Install MariaDB Package
The latest CentOS/RHEL 7 and Ubuntu (14.04 or later) contain MariaDB packages in
their official repositories.
In Fedora, MariaDB has become a replacement of MySQL since version 19.
If you are using an old version or LTS type like Ubuntu 13.10 or earlier,
you still can install MariaDB by adding its official repository.

MariaDB website provide an online tool to help you add MariaDB's official
repository
according to your Linux distribution.
This tool provides steps to add the MariaDB repository for openSUSE,
Arch Linux, Mageia, Fedora, CentOS, RedHat, Mint, Ubuntu, and Debian.

As an example, let's use the Ubuntu 14.04 distribution and CentOS 7 to configure
the MariaDB repository.

Ubuntu 14.04
$ apt-get install software-properties-common
$ apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80
0xcbcb082a1bb943db
$ add-apt-repository 'deb http://mirror.mephi.ru/mariadb/repo/5.5/ubuntu trusty
main'
$ apt-get update
$ apt-get install mariadb-server
CentOS 7
Create a custom yum repository file for MariaDB as follows.

$ vi /etc/yum.repos.d/MariaDB.repo
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/5.5/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
$ yum install MariaDB-server MariaDB-client
After all necessary packages are installed, you may be asked to type a new password
for root user account. After setting the root password, don't forget to recover
my.cnf backup file.

$ cp /opt/my.cnf /etc/mysql/
Now start MariaDB service as follows.

$ service mariadb start


or:

$ systemctl start mariadb


or:

$ /etc/init.d/mariadb start
Importing MySQL Database(s)
Finally, we have to import the previously exported database(s) back to MariaDB
server as follows.

$ mysql -u root -p < backupdb.sql


Enter your MariaDB's root password, and the database import process will start.
When the import process is finished, it will return to a command prompt.

To check whether or not the import process is completed successfully, log in into
MariaDB server and perform some sample queries.

$ mysql -u root -p
MariaDB [(none)]> show databases;
MariaDB [(none)]> use test01;
MariaDB [test01]> select * from pet;

Conclusion
As you can see in this tutorial, MySQL-to-MariaDB migration is not difficult.
MariaDB has a lot of new features than MySQL, that you should know about. As far as
configuration is concerned, in my test case, I simply used my old MySQL
configuration file (my.cnf) as a MariaDB configuration file, and the import process
was completed fine without any issue. My suggestion for the configuration is that
you read the documentation on MariaDB configuration options carefully before the
migration, especially if you are using specific MySQL configurations.

If you are running more complex setup with tons of tables and databases including
clustering or master-slave replication, take a look at the more detailed guide by
the Mozilla IT and Operations team, or the official MariaDB documentation.

Troubleshooting
1. While running mysqldump command to back up databases, you are getting the
following error.
$ mysqldump --all-databases --user=root --password --master-data > backupdb.sql
mysqldump: Error: Binlogging on server not active
By using "--master-data", you are trying to include binary log information in the
exported output, which is useful for database replication and recovery. However,
binary logging is not enabled in MySQL server. To fix this error, modify your
my.cnf file, and add the following option under [mysqld] section.

log-bin=mysql-bin
Save my.cnf file, and restart the MySQL service:

service mysql restart


or: systemctl restart mysql
or: /etc/init.d/mysql restart

==============================================================
AZARTICOLO:Install Emoncms on Raspberry Pi (Raspbian Stretch)
==============================================================
https://github.com/emoncms/emoncms/blob/master/docs/RaspberryPi/readme.md

This guide will install the current full version of emoncms onto a Raspberry
Pi running the Raspbian Stretch operating system.

Highly Recommended: A pre-built Raspberry Pi SD card image is available


with Emoncms pre-installed & optimised for low-write.
SD card image download & change log repository.
Full image build guide/notes are available here.

An alternative (older) installation guide is avaliable for Raspbian Jessie -


they are different, so ensure that you use the correct guide!

Due to the number of writes that the full version of emoncms makes, the
lifespan of an SD card will almost certainly be shortened, and it is therefore
recommended that you eventually move the operating system partition (root)
to an USB HDD or to lower the write frequency to the SD card by enabling
the low-write mode.

Before installing emoncms, it is essential you have a working version of


Raspbian Stretch installed on your Raspberry Pi.

If not, head over to raspberrypi.org and follow their installation guide.

Preparation
---------------

Start by updating the system repositories and packages:

apt-get update && apt-get upgrade


apt-get dist-upgrade && rpi-update

Raspberry Pi v3 Compatibility
--------------------------------------
This section only applies to Raspberry Pi v3 and later.

To avoid UART conflicts, it's necessary to disable Pi3 Bluetooth and restore
UART0/ttyAMA0 over GPIOs 14 & 15;

vi /boot/config.txt

Add to the end of the file


dtoverlay=pi3-disable-bt

We also need to stop the Bluetooth modem trying to use UART

systemctl disable hciuart

See RasPi device tree commit for pi3-disable-bt and forum thread discussion

I believe it may be possible to alter the kernel to be able to put it in airplane


mode permanently, but have not had a chance to try it yet...

# put into airplane mode


rfkill.default_state=0
#stop airplane mode button from doing anything
rfkill.master_switch_mode=0

The only other thing I can think of is to disable the loading of the drivers for
now:

/etc/modprobe.d/raspi-blacklist.conf

#wifi
blacklist brcmfmac
blacklist brcmutil

#bt
blacklist btbcm
blacklist hci_uart

Lista dei Moduli caricati


------------------------------

rfcomm 37723 0
bluetooth 365780 3 rfcomm
evdev 12423 6
uinput 9125 3
binfmt_misc 7988 1
sg 20781 0
brcmfmac 292632 0
brcmutil 9863 1 brcmfmac
cfg80211 544545 1 brcmfmac
rfkill 20851 5 bluetooth,cfg80211
uio_pdrv_genirq 3923 0
fixed 3285 0
uio 10204 1 uio_pdrv_genirq
snd_bcm2835 24427 0
snd_pcm 98501 1 snd_bcm2835
snd_timer 23968 1 snd_pcm
snd 70032 3 snd_timer,snd_bcm2835,snd_pcm

Installation
--------------

Install the dependencies:

apt-get install -y apache2 mariadb-server mysql-client php7.0 libapache2-mod-php7.0


php7.0-mysql php7.0-gd php7.0-opcache php7.0-curl php-pear php7.0-dev
php7.0-mcrypt php7.0-common redis-server php-redis git-core build-essential ufw ntp

Install the pecl dependencies (swift mailer):

pear channel-discover pear.swiftmailer.org


pecl channel-update pecl.php.net
pecl install channel://pecl.php.net/dio-0.1.0 swift/swift

Add the modules to php7 config:

sh -c 'echo "extension=dio.so" > /etc/php/7.0/apache2/conf.d/20-dio.ini'


sh -c 'echo "extension=dio.so" > /etc/php/7.0/cli/conf.d/20-dio.ini'

Issue the command:

a2enmod rewrite

For <Directory /> and <Directory /var/www/> change AllowOverride None to


AllowOverride All.

This should be on, or very close to lines 161 and 172 of /etc/apache2/apache2.conf

vi /etc/apache2/apache2.conf
Save & exit, then restart Apache:

systemctl restart apache2

Install the emoncms application via git


-------------------------------------------------

Git is a source code management and revision control system but at this
stage we use it to just download and update the emoncms application.

First, set the permissions for the www directory:

chown $USER /var/www


Cd into the www directory and git clone emoncms:

cd /var/www && git clone -b stable https://github.com/emoncms/emoncms.git

Setup the Mariadb server (MYSQL)


---------------------------------------------------
Firstly we should secure the database server, and then create a database and
database
user for emoncms to use;

The following configuration commands gives 'sudoers' Mariadb root privileges from
within the local network, to administer all aspects of the databases and users.
It also removes an 'example' database and user, which is no longer required.

mysql -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost',
'127.0.0.1', '::1'); DELETE FROM mysql.user WHERE User=''; DROP DATABASE IF EXISTS
test; DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%'; FLUSH PRIVILEGES;"

Create the emoncms database using utf8 character decoding:


-----------------------------------------------------------------------------------
-------
mysql -e "CREATE DATABASE emoncms DEFAULT CHARACTER SET utf8;"

Add an emoncms database user and set that user's permissions.


In the command below, we're creating the database 'user' named 'emoncms', and you
should create a new secure password of your choice for that user.
Make a note of both the database 'username' ('emoncms') & the
'new_secure_password'.
They will be inserted into the settings.php file in a later step:

mysql -e "CREATE USER 'emoncms'@'localhost' IDENTIFIED BY 'new_secure_password';


GRANT ALL ON emoncms.* TO 'emoncms'@'localhost'; flush privileges;"

Create data repositories for emoncms feed engines:

mkdir /var/lib/{phpfiwa,phpfina,phptimeseries}

...and set their permissions

chown www-data:root /var/lib/{phpfiwa,phpfina,phptimeseries}

Configure emoncms database settings


---------------------------------------------------------

Make a copy of default.settings.php and call it settings.php:

cd /var/www/emoncms && cp default.settings.php settings.php


Open settings.php in an editor:

vi settings.php
Update your settings to use your Database 'user' & 'password', which will enable
emoncms
to access the database:

$server = "localhost";
$database = "emoncms";
$username = "emoncms";
$password = "new_secure_password";

Further down in settings is an optional 'data structure store' - Redis, which acts
as a cache
for the data produced by emoncms, to ensure that it is efficiently written to disk.

To activate Redis, change 'false' to 'true'. :

//2 #### Redis


redis_enabled = true;
AZPATCH Disabilitato

save and exit.

Per fermarlo:
systemctl status redis-server
root@raspi:/var/www/emoncms# systemctl stop redis-server
root@raspi:/var/www/emoncms# systemctl disable redis-server

Create a symlink to reference emoncms within the web root folder:

cd /var/www/html && ln -s /var/www/emoncms


Set write permissions for the emoncms logfile:

touch /var/log/emoncms.log && chmod 666 /var/log/emoncms.log

To enable the emoncms user-interface to reboot or shutdown the system, it's


necessary
to give the web-server sufficient privilege to do so.
Open the sudoers file :

visudo
and edit the # User privilege specification section to be :

# User privilege specification


root ALL=(ALL:ALL) ALL
www-data ALL=(ALL) NOPASSWD:/sbin/shutdown
Save & exit

In an internet browser, load emoncms:

http://localhost/emoncms

If you want Emoncms to redirect from web root i.e load Emoncms with
http://localhost add reference in index.php and remove the default apache
index.html
test page:

echo "<?php header('Location: ../emoncms'); ?>" > /var/www/html/index.php


rm /var/www/html/index.html
exit

The first time you run emoncms it will automatically set up the database and you
will be
taken to the register/login screen.
Create an account by entering your email and password and clicking register.

Once you are logged in;

Check the Administration page - 'Setup > Administration' noting and acting upon any
messages reported.

Update your database - 'Setup > Administration > Update database'.

Make a note of your 'Write API Key' from the 'Setup > My Account' page, and also
ensure
that the correct timezone is selected & saved.

Install Emonhub
--------------------------

git clone https://github.com/emonhub/dev-emonhub.git ~/dev-emonhub && ~/dev-


emonhub/upgrade

Edit the emonhub configuration file, entering your emoncms 'Write API Key' and set
the
"local" emoncms address url = http://localhost/emoncms (emonhub sends to
http://emoncms.org
by default). Also set your RFM2Pi frequency, group & base id if necessary:

vi /etc/emonhub/emonhub.conf
Save & exit.

Edit the cmdline.txt file:

vi /boot/cmdline.txt
by changing the line to - dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2
rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait

Per fermarlo
# systemctl stop emonhub
# systemctl disable emonhub

Disable serial console boot


----------------------------------------

systemctl stop [email protected]


systemctl disable [email protected]
At this stage, power off your Raspberry Pi:
AZPATCH riabilitato
AZPATCH disabilitato mosquitto

mosquitto.service - Mosquitto MQTT Broker


# systemctl stop mosquitto
# systemctl disable mosquitto
# systemctl disable mosquitto

poweroff
--------------

Once your Pi has stopped, disconnect the power lead and connect your RFM69Pi add-on
board, ensuring it's positioned correctly (see the photos in the OEM shop pages).

You should now have a fully working version of emoncms installed on your Raspberry
Pi,
if at this stage you don't, you may wish to check the emoncms log
- 'Setup > Administration > Logger' or report the issue in the OEM forum giving as
much detail as possible.

-----------------------
System Options
-----------------------

Move the operating system partition (root) to an USB HDD

Enabling low-write mode

Enabling MQTT
Installing emoncms Modules
Updating emoncms
System Logs

================================================================================
AZARTICOLO:How to enable auto-login?
================================================================================

So I just installed raspbian jessie lite on my pi 2. But I can't get it to login


automatically.
I first tried with raspi-config, which didn't work. Then after googling a bit, I
found a tutorial
which I'm suppose to edit inittab but when I try to access it, it's empty.

raspi-config

If you select the right option in raspi-config it should work.


Anything using inittab won't.
Indeed most of the tutorials before mid 2015 (and many after) are for SysV and
won't work.
Some will actually interfere with normal operation.

@Milliways I have tried going into raspi-config, and changed the boot option to,
console autologin but it doesn't work. –

I have the same Rasbian Jessie on a Ras Pi 2.

Try THIS (solution via raspberrypi.stackexchange) will probably help!

First create a new service similar to [email protected]:

# cp /lib/systemd/system/[email protected] \
/etc/systemd/system/[email protected]

# ln -s /etc/systemd/system/[email protected] \
/etc/systemd/system/getty.target.wants/[email protected]

then edit ExecStart, Restart and Alias values, like this:

ExecStart=-/sbin/mingetty --autologin USERNAME %I


Restart=no
Alias=getty.target.wants/[email protected]

and finally reload daemon and start the service:

systemctl daemon-reload
systemctl start [email protected]

Note that if you exit tty8 session, you wont be able to use it until next reboot or
manual
start by systemctl, except if you leave Restart as ‘always’, but I highly recommend
to avoid this according to security reasons.

source: fedoraproject.org/wiki

The simplest way I have found, if using Raspbian, is to edit the raspi-config file:
/etc/lightd/lightdm.con and set the autologin-user= parameter.

Change: autologin-user=pi to autologin-user=username where username is your


username

===================================================================================
=============
AZARTICOLO:Auto-login with GUI disabled in Raspbian
===================================================================================
=============

How can I make the RPi auto-login when booted, when the GUI is disabled?

You don't have to type a password, when logging in when GUI enabled, so there is
probably
an easy way of disabling the password prompt in the console.

Very dangerous, I missed the bit about not having a password and seemed to have
screwed
up the SD card. Be warned!

For Raspbian Wheezy:

You should be able to edit the /etc/inittab file to enable autologin.

Find a line like this in /etc/inittab

1:2345:respawn:/sbin/getty --noclear 38400 tty1

This starts the getty process on tty1.


You can add the getty --autologin option to that line:

1:2345:respawn:/sbin/getty --autologin {USERNAME} --noclear 38400 tty1

Replace {USERNAME} with the user you want to login.

Note I have not tested this, check the manpage for getty for more details.

Update: Raspbian Jessie uses systemd so inittab is not used.


Here is a FAQ that may help for Jessie:

https://fedoraproject.org/wiki/
Systemd#How_do_I_set_automatic_login_on_a_virtual_console_terminal.3F

The FAQ is for Fedora but it should be very similar on Raspbian Jessie.

I have tested it; it works fine. Also, put something in ~/.bash_profile and that
will get run
automatically after you are logged in. – greggo Jan 18 '13 at 18:28

Please update the answer!


There is no /etc/inittab file in raspbian jessie.

No, I still get the login prompt upon boot.


The Raspbian Jessie solution doesn't work.
there is an easier way to do this using raspi-config this article explains it
http://www.opentechguides.com/how-to/article/raspberry-pi/5/raspberry-pi-auto-
start.html

showing :

how to auto login to the shell prompt (using a method similar to above)
Run scripts at startup
Auto start the desktop using raspi-config

this article shows how to auto login to the desktop using raspi-config, but the
question
is asking how to auto login when there is no GUI or Desktop
(so bringing up the shell prompt).
However this article also shows how to auto login to the shell as well.
This worked for me with Jessie Lite:

-i
mkdir -pv /etc/systemd/system/[email protected]
nano /etc/systemd/system/[email protected]/autologin.conf

[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin pi --noclear %I 38400 linux

only catch is that I can't logon using SSH anymore - access denied. :-(

A good answer should give an indication as to why it works.


What do the those two steps do?
Can you really say it works if it breaks SSH?

This doesn't work!


Still forces me to login at command line.

does using $TERM work for you?


ExecStart=-/usr/bin/agetty --autologin username --noclear %I $TERM – esharp Aug 1
'16 at 8:54
If you want auto-login to Raspberry Pi on Serial line, you need to edit the
/etc/inittab file
on pi with permissions.

Find a line like this in /etc/inittab

T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

Add the getty --autologin option to that line.

T0:23:respawn:/sbin/getty --autologin {username} -L ttyAMA0 115200 vt100

Save and Reboot.


What is T0:23?? I thought it should be 1:2345.

I'm running NOOBS and had a slightly different inittab file.


Here's what I changed that combined both the "--autologin" on the T0 line and the
1:2345 line:

#1:2345:respawn:/sbin/getty --noclear 38400 tty1"


1:2345:respawn:/bin/login -f pi tty1 <dev/tty1 >/dev/tty1 2>&1
T0:23:respawn:/sbin/getty --autologin pi - L ttyAMA0 115200 vt100

so lightdm.conf method didnt work for me, after a bit of playing around the easiest
method
I found was below.

cd /etc/systemd/system/

from there type: ls

you will see [email protected]

just nano [email protected]

and change line ExecStart=-/sbin/agetty --autologin pi --noclear % I $TERM


to

ExecStart=-/sbin/agetty --autologin [Username] --noclear % I $TERM

where [Username] is put the user you wish to login without the brackets.

now I did have pi auto login working using the raspi-config setup, but used the
above
method to change the autologin for a new user.
hope this helps

==============================================================
AZARTICOLO: DIFFERENZA TRA MBR E GPT
==============================================================
MBR disks

Picture of MBR disk layout

----------------------
MBR: Master Boot Record
----------------------
1 Partition Table Entry
----------------------
2 Partition Table Entry
----------------------
3 Partition Table Entry
----------------------
4 Partition Table Entry
----------------------
0x55AA
----------------------
C: Primary Partition
----------------------
D: Primary Partition
----------------------
E: Primary Partition
----------------------
F: Primary Partition
----------------------
G: Extended Partition
----------------------
H: Extended Partition
----------------------

This is the disk layout for a typical MBR system.

First of all, we have the partition tables at the beginning.


These are used to boot and should not be tampered with.
They occupy the first x bytes of the disk and let your system get to your
bootloader.
Basically, don't worry about this bit. Then, down in the middle, we have three
"primary partitions."
As shown, these are like your Windows C:\ and D:\ partitions.
They are the primary partitions and in Linux, these three are usually /, /home/ and
/etc.
There can be up to 3 primary partitions in an MBR disk, making it a limited
environment for
multiple partitions. At the bottom, there are a bunch of other partitions all named
extended
partitions. Since there can only be 3 primary partitions, you can have extended
partitions with
multiple logical drives inside of them. These logical drives can even contain a
whole Linux system
with the logical drives being the partitions (/home, /etc, /var).
Lastly, MBR disks can only have 2TB in capacity.

GPT Disks
--------

GPT is the latest standard for laying out the partitions of a hard disk.
It makes use of globally unique identifiers (GUID) to define the partition and it
is part of the
UEFI standard. This means that on a UEFI-based system
(which is required for Windows 8 Secure Boot feature), it is a must to use GPT.
With GPT, you can create theoretically unlimited partitions on the hard disk, even
though it is
generally restricted to 128 partitions by most OSes.

Unlike MBR that limits each partition to only 2TB in size, each partition in GPT
can hold up to
2^64 blocks in length (as it is using 64-bit), which is equivalent to 9.44ZB for a
512-byte block
(1 ZB is 1 billion terabytes). In Microsoft Windows, that size is limited to 256TB.

GPT
---

------------------------------------
lba0: PMBR: Protective Master Boot Record
------------------------------------
lba1 Primary GPT Header
------------------------------------
lba2 | Entry1 | Entry2 | Entry3 | Entry4 |
------------------------------------
lba3 Entry 5-128
------------------------------------
lba34 Partition 1
------------------------------------
lba34 Partition 2
------------------------------------
lba-34 Partition (Others)
------------------------------------
lba-33 | Entry1 | Entry2 | Entry3 | Entry4 |
------------------------------------
lba-2 Entry 5-128
------------------------------------
lba-1 Secondary GPT Header
------------------------------------

From the GPT Table Scheme diagram above, you can see that there is a primary GPT at
the
beginning of the hard disk and a secondary GPT at the end.
This is what makes GPT more useful than MBR. GPT stores a backup header and
partition table
at the end of the disk so it can be recovered if the primary tables are corrupted.
It also carry out CRC32 checksums to detect errors and corruption of the header and
partition table.
In other words, GPT is a newer fashion, has the latest sizes, and is easier to use,
less confusing
sometimes. For example, GPT supports 128 primary partitions (I know, right?) while
MBR only
supports 3 (?). And in my honest opinion, the command parted handles GPT and MBR
disks
perfectly (unfortunately not exactly the case with fdisk).
GPT's have different sorts of BIOS and they usually are on, if not required, on
UEFI or EFI systems.

In systems as like mine, the GPT disk is needed.

For example, see my parted -l:

Model: ATA WDC WD10JPCX-24U (scsi)


Disk /dev/sda: 1000GB
Sector size (logical/physical): 512B/4096B
Partition Table: gpt
Disk Flags:

Number Start End Size File system Name


Flags
1 1049kB 1050MB 1049MB ntfs Basic data partition
hidden, diag
2 1050MB 1322MB 273MB fat32 EFI system partition
boot, hidden
3 1322MB 2371MB 1049MB fat32 Basic data partition
hidden
4 2371MB 2505MB 134MB Microsoft reserved partition
msftres
5 2505MB 486GB 484GB ntfs Basic data partition
8 486GB 492GB 5243MB fat32 EFI System Partition
boot
9 492GB 502GB 10.5GB ext4
10 502GB 607GB 105GB ext4
11 607GB 628GB 21.0GB ext4
12 628GB 641GB 12.6GB linux-swap(v1)
13 641GB 961GB 320GB ext4
6 961GB 988GB 26.8GB ntfs Basic data partition
7 988GB 1000GB 12.6GB ntfs Basic data partition
hidden, diag

I've got 13 primary partitions!

Difference for Fedora


-----------------

There really is not that much difference between Fedora on a GPT disk than a Fedora
on an
MBR disk. Super minor speed differences maybe.
There might be a tiny inconvenience using an MBR disk with resizing and adding
partitions,
but besides that, Fedora is a very adaptable,

smart system. Even if your disk is really strange, it can adjust. Don't worry too
much about that.
However, I would prefer GPT, because I have more than 2.0TB disks on me sometimes,
it is more convenient. Some OS's also only run on GPT, like Mac OSX.
HTH and if you can, choose GPT!

TL;DR? ;) Read this brief summary here:

Basically, GPT supports more primary partitions.


MBR supports 3, while GPT can handle 128.
The MBR disks can have extended partitions, though, and they can hold sections
called logical drives.
I would say GPT is the better choice if you have one for two reasons. First, new
hardware.
MBR is super old. Period. Second, it is easier to create partitions on GPT
(no need to fudge around with primary/extended). Honestly, though, there is no
difference.

===================================================================================
========
AZARTICOLO:BACKUP DELLA SCHEDA SD
===================================================================================
========

Con PC con Linux


--------------

Una volta inserita la scheda SD in un lettore collegato al computer Linux, da


terminale impartire
i seguenti comandi:

fdisk -l

E prendere nota di come viene chiamata la Sd, ad esempio /dev/sdb1 oppure qualcosa
tipo
/dev/mmcblk0, dipende dalla distribuzione.

Poi potete dare:

dd bs=4M if=/dev/sdb | gzip > /home/il_tuo_username/immagine`date +%d%m%y`.gz

per ottenere una immagine compressa con gzip.

Per ripristinare poi il backup sulla SD,


gzip -dc /home/il_tuo_username/immagine.gz | dd bs=4M of=/dev/sdb

Ricordatevi che questi sono comandi da dare sul terminale del PC che utilizzerete
per fare il backup,
non sul Raspberry!

/dev/mmcblk0p7 on / type ext4 (rw,noatime,data=ordered)


/dev/mmcblk0p6 on /boot type vfat
(rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,err
ors=remount-ro)
/dev/mmcblk0p8 on /data type ext4 (rw,relatime,data=ordered)

===================================================================================
==============
AZARTICOLO:Boot the Raspberry Pi From USB by techno guy in raspberry-pi
===================================================================================
============

Introduction:
--------------------

Boot the Raspberry Pi From USB

Hello world, time for me to gift some raspberry pi to the people.


So here's my story, I recently graduated high school and I've been working
with the school's IT guy for my senior year. When I graduated, he decided
to get me the latest Raspberry Pi as a graduation present
(at the time of writing this, the Raspberry Pi 2 Model B).

I thought it was really generous of him and I wanted to use it. Here's the problem,
I've only got 2 GB SD cards and the latest Raspbian image (2015-05-05) was
like 3.5 GB in size.

No problem, I'm a technology guy, surely I could figure this out, and I did.
So now I'm here showing a step-by-step picture guide as to how I did it.

This instructable assumes that the reader has at least some basic experience
with Ubuntu, the Raspberry Pi and the GParted partition editor.
If not, then this probably isn't for you.

This article is also centered around doing the whole process using Ubuntu

Step 1: Prepare the Flash Drive


-----------------------------------------
Show All 7 Items

Navigate to your flash drive in GParted, in my case it is drive /dev/sdb.

Unmount the flash drive so you can make changes.

Delete any partitions so you can make a new one.

Add a new partition.

Format it to fat32 and give it any name.

Apply all operations to format the flash drive.

Step 2: Burn the Image to the Flash Drive


----------------------------------------------------

Type "-s" to get into a root shell, so you don't have to type again.

The easiest way to burn the image is to type in "

dd if=path/to/image of=path/to/flashdrive".
In my case I found the path to the flash drive from GParted, it was /dev/sdb
but it might be different for you.

If you want to know the status of the burn, you can install pv by typing in
"apt-get install pv" and then using the altered command of
"dd if=path/to/image | pv | dd of=path/to/flashdrive".

When the image is finished burning, the contents of the drive should look
more or less like they do in the picture of the GParted screen.
It should have one fat16 partition and one ext4 partition and maybe some
unallocated space if your drive is big enough.
Step 3: Prepare the SD Card
-----------------------------------

Show All 8 Items

Insert your SD card and navigate to it in GParted, /dev/sdc in my case.

Unmount it and delete the partition.

Add a new partition and make sure it is 56 MB in size while being labeled
"boot" and being a fat16 file system.

The point is to clone the boot partition on the flash drive over to the SD card
because the Raspberry Pi can't completely boot from a flash drive.

Then click "manage flags" and add the "lba" flag and you're done prepping
the SD card.

Step 4: Transfer the Boot Partition


-------------------------------------------

Get back into your root shell to prepare the boot partition transfer.

Again, use "dd" to transfer the partitions, my boot partition is /dev/sdb1 for
the flash drive and /dev/sdc1 for the SD card.
Notice the 1 at the end of each, that signifies the first logical partition
which I can see from the GParted screen.

The command for me is "dd if=/dev/sdb1 of=/dev/sdc1"


but I used the "pv" version because I like to see how everything works out.
It's the same as in the last step, only change the "if" and "of" parts.

Step 5: Set to Boot From the Flash Drive


--------------------------------------------------

Get into the SD card file system with your favorite file explorer and open up
the file called "cmdline.txt".

We will edit the word in the line that starts with


"root=" so we can tell the SD card where it's supposed to boot, in this case
the flash drive.

Change the line from "root=/dev/mmcblk0p2" to "root=/dev/sda2".


It is "/dev/sda2"
because in GParted, it shows my flash drive root partition as being /dev/sdb2,
but when the Raspberry Pi mounts it, it will be /dev/sda and I want the second
partition to get booted from.

Step 6: Finish Up With the Flash Drive


--------------------------------------------------

Show All 9 Items

Get back to GParted and navigate to the flash drive.


Delete the fat16 "boot" partition, "/dev/sdb1" in my case.

Then resize the ext4 partition by clicking "resize/move" and dragging each
end of the partitions to the corresponding ends.
Apply all operations and wait quite a bit of time for the partition to grow.
When it's finished, there should be only one partition, and ext4, that has
the same partition path (/dev/sdb2) as the original ext4 partition.

Step 7: Set Up the Raspberry Pi


----------------------------------------

Now just insert your SD card into the Raspberry Pi along with the root flash
drive that we were working on.

Plug everything you need in like power, video, keyboard/mouse and wifi and turn it
on.

Step 8: Moment of Truth


--------------------------------

If all worked well for you, then you should see the Raspberry Pi boot up
normally and the setup screen come up for the first time.
CONGRATULATIONS!!!

If not, then something probably went wrong and you should try to see if
you can fix it by going backwards to see what went wrong or just redoing the
whole process again.

I typed in "startx" and the desktop interface came up, all is well and now I
can use the Pi normally.

===================================================================================
===================================================================================
==================
===================================================================================
===================================================================================
==================
===================================================================================
=========
AZARTICOLO:SETTING WIFI UP VIA THE COMMAND LINE documentazione ufficiale
===================================================================================
=========
https://www.debian.org/doc/manuals/debian-reference/
ch05.en.html#_the_basic_syntax_of_etc_network_interfaces
https://www.raspberrypi.org/documentation/configuration/wireless/wireless-cli.md

This method is suitable if you don't have access to the graphical user interface
normally used to set up WiFi on the Raspberry Pi. It's especially suitable for use
with a serial console cable if you don't have access to a screen or wired Ethernet
network. Note also that no additional software is required; everything you need is
already included on the Raspberry Pi.

GETTING WIFI NETWORK DETAILS


--------------------------------------------

To scan for WiFi networks, use the command iwlist wlan0 scan.
This will list all available WiFi networks, along with other useful information.
Look out for:

ESSID:"testing". This is the name of the WiFi network.

IE: IEEE 802.11i/WPA2 Version 1. This is the authentication used; in this case it's
WPA2,
the newer and more secure wireless standard which replaces WPA.
This guide should work for WPA or WPA2, but may not work for WPA2 enterprise;
for WEP hex keys, see the last example here.
You'll also need the password for the WiFi network.
For most home routers this is located on a sticker on the back of the router.
The ESSID (ssid) for the network in this case is testing and the password (psk) is
testingPassword.

ADDING THE NETWORK DETAILS TO THE RASPBERRY PI


----------------------------------------------
pa-supplicant configuration file in nano:

vi /etc/wpa_supplicant/wpa_supplicant.conf

Go to the bottom of the file and add the following:

network={
ssid="The_ESSID_from_earlier"
psk="Your_wifi_password"
}
In the case of the example network, we would enter:

network={
ssid="testing"
psk="testingPassword"
}

Now save the file by pressing Ctrl+X then Y, then finally press Enter.

At this point, wpa-supplicant will normally notice a change has occurred within a
few seconds, and it
will try and connect to the network. If it does not, either manually restart the
interface with
ifdown wlan0 and ifup wlan0, or reboot your Raspberry Pi with reboot.

You can verify if it has successfully connected using ifconfig wlan0.


If the inet addr field has an address beside it, the Pi has connected to the
network.
If not, check your password and ESSID are correct.

==============================================================
AZARTICOLO:CONFIGURAZIONE WIFI FUNZIONANTE
==============================================================

-----------------------------------------------------------------------
cat /etc/network/interfaces IP STATICO ANCHE SUL WI-FI
-----------------------------------------------------------------------

# interfaces(5) file used by ifup(8) and ifdown(8)


# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'
# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback
#allow-hotplug eth0
iface eth0 inet static
address 192.168.1.5
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
mtu 1492
metric 1
#up route add default gw 192.168.1.1 metric 1 dev eth0
#dns-nameservers 192.168.1.1 8.8.4.4

# AZPATCH andrebbe invertitito l'utilizzo!


#auto wlan0
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface azcam inet static
address 192.168.1.7
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
mtu 1492
wireless-power off
metric 2
#up route add default gw 192.168.1.1 metric 2 dev wlan0
#down route del default gw 192.168.1.1 metric 2 dev wlan0
dns-domain homenet.telecomitalia.it
dns-nameservers 192.168.1.1 8.8.4.4
iface default inet dhcp

==============================================================
WPA_SUPPLICANT WPA2
==============================================================
root@raspi:/etc/wpa_supplicant# cat wpa_supplicant.conf

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=IT
network={
ssid="CISCOWIFI"
psk="intrapam123$"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
id_str="azcam"
}

==============================================================
configurazione del router fibra WPA2
==============================================================

Impostazioni Rete Wi-Fi 2.4 GHz

Interfaccia Radio:
Attiva
Rete Wi-Fi (SSID): CISCOWIFI (Visibile)
Canale Radio: 1 (Automatico) Cerca canale
Ampiezza di banda (Canale): Auto 20 MHz / 40 MHz
Modalità di cifratura: WPA-PSK TKIP-AES 256 bit
Chiave di cifratura: intrapam123$ [ASCII]
Controllo Accesso: Disabilitato

Impostazioni Base|Wi-Fi|Wi-Fi 2.4 GHz


WI-FI 2.4GHz
CONFIGURA WI-FI 2.4 GHz

==============================================================
configurazione del router fibra WPA1
==============================================================

Impostazioni Rete Wi-Fi 2.4 GHz

Interfaccia Radio:
Attiva
Rete Wi-Fi (SSID):
CISCOWIFI (Visibile)
Canale Radio: 1 (Automatico) Cerca canale
Ampiezza di banda (Canale): Auto 20 MHz / 40 MHz
Modalità di cifratura: WPA-PSK TKIP 256 bit
Chiave di cifratura: intrapam123$ [ASCII]
Controllo Accesso: Disabilitato

==============================================================
WPA_SUPPLICANT WPA1
==============================================================

/etc/wpa_supplicant# cat wpa_supplicant.conf


ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=IT
network={
ssid="CISCOWIFI"
psk="intrapam123$"
# psk=0f1a94ca5722a564249371073210bc9911ad5c1993c1302e7d0dee3b17e5ebad
#proto=RSN
proto=WPA
key_mgmt=WPA-PSK
# pairwise=CCMP
pairwise=TKIP
auth_alg=OPEN
id_str="azcam"
}

-----------------------------------------------------------------------------------
----------
CISCOWIFI WPA2
-----------------------------------------------------------------------------------
----------
# iwlist wlan0 scanning essid CISCOWIFI

wlan0 Scan completed :


Cell 01 - Address: C4:EA:1D:5F:7C:21
Channel:1
Frequency:2.412 GHz (Channel 1)
Quality=70/70 Signal level=-12 dBm
Encryption key:on
ESSID:"CISCOWIFI"
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
24 Mb/s; 36 Mb/s; 54 Mb/s
Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 48 Mb/s
Mode:Master
Extra:tsf=0000000000000000
Extra: Last beacon: 80ms ago
IE: IEEE 802.11i/WPA2 Version 1
Group Cipher : TKIP
Pairwise Ciphers (1) : CCMP
Authentication Suites (1) : PSK
IE: Unknown: 32040C121860
IE: WPA Version 1
Group Cipher : TKIP
Pairwise Ciphers (1) : TKIP
Authentication Suites (1) : PSK
IE: Unknown:
DD180050F2020101000003A4000027A4000042435E0062322F00

-----------------------------------------------------------------------------------
----------
CISCOWIFI WPA1
-----------------------------------------------------------------------------------
----------

root@raspi:/etc/wpa_supplicant# iwlist wlan0 scanning essid CISCOWIFI

wlan0 Scan completed :


Cell 01 - Address: C4:EA:1D:5F:7C:21
Channel:1
Frequency:2.412 GHz (Channel 1)
Quality=70/70 Signal level=-26 dBm
Encryption key:on
ESSID:"CISCOWIFI"
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
24 Mb/s; 36 Mb/s; 54 Mb/s
Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 48 Mb/s
Mode:Master
Extra:tsf=0000000000000000
Extra: Last beacon: 30ms ago
IE: WPA Version 1
Group Cipher : TKIP
Pairwise Ciphers (1) : TKIP
Authentication Suites (1) : PSK
IE: Unknown:
DD180050F2020101000003A4000027A4000042435E0062322F00
-----------------------------------------------------------------------------------
----------

Connessione
----------------

wlan0 IEEE 802.11 ESSID:"CISCOWIFI"


Mode:Managed Frequency:2.412 GHz Access Point: C4:EA:1D:5F:7C:21
Bit Rate=65 Mb/s Tx-Power=31 dBm
Retry short limit:7 RTS thr:off Fragment thr:off
Encryption key:off
Power Management:off
Link Quality=70/70 Signal level=-24 dBm
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:1 Invalid misc:0 Missed beacon:0
Connessione attiva processi:
----------------------------

/sbin/wpa_supplicant -u -s -O /run/wpa_supplicant <--- daemon tolto!


/sbin/wpa_supplicant -s -B -P /run/wpa_supplicant.wlan0.pid -i wlan0 -W -D
nl80211,wext -c /etc/wpa_supplicant/wpa_supplicant.conf
/sbin/wpa_cli -B -P /run/wpa_action.wlan0.pid -i wlan0 -p /var/run/wpa_supplicant -
a /sbin/wpa_action

Se uccido la wlan0 con ifdown wlan0 --force:


/sbin/wpa_supplicant -u -s -O /run/wpa_supplicant

Se fermo il serivizio con: service wpa_supplicant stop


nessun processo piu' attivo!

==============================================================
AZARTICOLO:Doppio routing LAN/WLAN
==============================================================

ip route list
-----------------

default via 192.168.1.1 dev eth0 metric 1


default via 192.168.root@raspi:~# cat /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'
# Include files from /etc/network/interfaces.d:

source-directory /etc/network/interfaces.d

auto lo
auto eth0
auto wlan0
iface lo inet loopback

allow-hotplug eth0
#iface eth0 inet manual
iface eth0 inet static
address 192.168.1.5
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
up route add -net default gw 192.168.1.1 netmask 0.0.0.0 dev eth0 metric 1
down route del -net default gw 192.168.1.1 netmask 0.0.0.0 dev eth0 metric 1
dns-nameservers 192.168.1.1 8.8.8.8 4.2.2.1

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface azcam inet static
address 192.168.1.7
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
up route add -net default gw 192.168.1.1 netmask 0.0.0.0 dev wlan0 metric 2
down route del -net default gw 192.168.1.1 netmask 0.0.0.0 dev wlan0 metric 2
iface default inet dhcp
1.1 dev wlan0 metric 2
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.5
192.168.1.0/24 dev wlan0 proto kernel scope link src 192.168.1.7

Controllare quale interfaccia viene utilizzata


...................................................................................
..........................
root@raspi:~#
ip -o route get 216.58.211.99
216.58.211.99 via 192.168.1.1 dev eth0 src 192.168.1.5 \ cache

================================================================================
AZARTICOLO::USING YOUR NEW RASPBERRY PI 3 AS A WIFI ACCESS POINT WITH HOSTAPD
================================================================================
https://frillip.com/using-your-raspberry-pi-3-as-a-wifi-access-point-with-hostapd/

04 MARCH 2016 on wifi, raspberrypi, hostapd, softap

There's a new Raspberry Pi. This is exciting.


It also has on-board WiFi. This makes it doubly exciting!

One of my first thoughts was, can I use it as a SoftAP for some ESP8266 sensor
nodes?
As it turns out, you can, and it's not that difficult, as the BCM43438 chip is
supported
by the open-source brcmfmac driver!

PACKAGES
--------------

The first step is to install the required packages: apt-get install dnsmasq hostapd

I'll go into a little detail about the two:

hostapd - This is the package that allows you to use the built in WiFi as an access
point
dnsmasq - This is a combined DHCP and DNS server that's very easy to configure

If you want something a little more 'heavyweight', you can use the isc-dhcp-server
and bind9
packages for DHCP and DNS respectively, but for our purposes, dnsmasq works just
fine.

CONFIGURE YOUR INTERFACES


---------------------------

The first thing you'll need to do is to configure your wlan0 interface with a
static IP.

If you're connected to the Pi via WiFi, connect via ethernet/serial/keyboard first.

In newer Raspian versions, interface configuration is handled by dhcpcd by default.


We need to tell it to ignore wlan0, as we will be configuring it with a static IP
address elsewhere.
So open up the dhcpcd configuration file with vi /etc/dhcpcd.conf and add the
following
line to the bottom of the file:
denyinterfaces wlan0

Note: This must be ABOVE any interface lines you may have added!

Now we need to configure our static IP.


To do this open up the interface configuration file with vi /etc/network/interfaces
and
edit the wlan0 section so that it looks like this:

allow-hotplug wlan0
iface wlan0 inet static
address 172.24.1.1
netmask 255.255.255.0
network 172.24.1.0
broadcast 172.24.1.255
# wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

Restart dhcpcd with service dhcpcd restart and then reload the configuration for
wlan0
with ifdown wlan0; ifup wlan0.

CONFIGURE HOSTAPD
-----------------------------
Next, we need to configure hostapd.
Create a new configuration file with vi /etc/hostapd/hostapd.conf with the
following contents:

# This is the name of the WiFi interface we configured above


interface=wlan0

# Use the nl80211 driver with the brcmfmac driver


driver=nl80211

# This is the name of the network


ssid=Pi3-AP

# Use the 2.4GHz band


hw_mode=g

# Use channel 6
channel=6

# Enable 802.11n
ieee80211n=1

# Enable WMM
wmm_enabled=1

# Enable 40MHz channels with 20ns guard interval


ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40]

# Accept all MAC addresses


macaddr_acl=0

# Use WPA authentication


auth_algs=1

# Require clients to know the network name


ignore_broadcast_ssid=0

# Use WPA2
wpa=2

# Use a pre-shared key


wpa_key_mgmt=WPA-PSK

# The network passphrase


wpa_passphrase=raspberry

# Use AES, instead of TKIP


rsn_pairwise=CCMP

We can check if it's working at this stage by running /usr/sbin/hostapd


/etc/hostapd/hostapd.conf.
If it's all gone well thus far, you should be able to see to the network Pi3-AP!
If you try connecting to it, you will see some output from the Pi, but you won't
receive and
IP address until we set up dnsmasq in the next step. Use Ctrl+C to stop it.

We aren't quite done yet, because we also need to tell hostapd where to look for
the config
file when it starts up on boot. Open up the default configuration file with vi
/etc/default/hostapd
and find the line #DAEMON_CONF="" and replace it with
DAEMON_CONF="/etc/hostapd/hostapd.conf".

CONFIGURE DNSMASQ
-----------------------------

The shipped dnsmasq config file contains a wealth of information on how to use it,
but
the majority of it is largely redundant for our purposes. I'd advise moving it
(rather than
deleting it), and creating a new one with

mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig
vi /etc/dnsmasq.conf
Paste the following into the new file:

interface=wlan0 # Use interface wlan0


listen-address=172.24.1.1 # Explicitly specify the address to listen on
bind-interfaces # Bind to the interface to make sure we aren't sending things
elsewhere
server=8.8.8.8 # Forward DNS requests to Google DNS
domain-needed # Don't forward short names
bogus-priv # Never forward addresses in the non-routed address spaces.
dhcp-range=172.24.1.50,172.24.1.150,12h # Assign IP addresses between 172.24.1.50
and 172.24.1.150 with a 12 hour lease time

SET UP IPV4 FORWARDING


----------------------

One of the last things that we need to do before we send traffic anywhere is to
enable packet forwarding.

To do this, open up the sysctl.conf file with vi /etc/sysctl.conf, and remove the #
from the
beginning of the line containing net.ipv4.ip_forward=1. This will enable it on the
next reboot,
but because we are impatient, activate it immediately with :
sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"

We also need to share our Pi's internet connection to our devices connected over
WiFi by
the configuring a NAT between our wlan0 interface and our eth0 interface.

We can do this using the following commands:

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE


iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

However, we need these rules to be applied every time we reboot the Pi,
so run sh -c "iptables-save > /etc/iptables.ipv4.nat" to save the rules to the
file /etc/iptables.ipv4.nat. Now we need to run this after each reboot, so open the
rc.local
file with vi /etc/rc.local and just above the line exit 0, add the following line:

iptables-restore < /etc/iptables.ipv4.nat


WE'RE ALMOST THERE!

Now we just need to start our services:

service hostapd start


service dnsmasq start

And that's it! You should now be able to connect to the internet through your Pi,
via the on-board WiFi!

To double check we have got everything configured correctly, reboot with reboot.

EDIT4: Fixed race condition between dhcpcd and dnsmasq, wlan0 is no longer
configured by dhcpcd.

===================================================================================
=========
AZARTICOLO:Raspberry Pi Course Week 3 – Day 1.0 (WiFi Config)
===================================================================================
========
http://www.suntimebox.com/raspberry-pi-tutorial-course/week-3/day-1/

Raspberry Pi Course Day1 WiFi Config


Make sure that you are logged into your Raspberry Pi desktop and that you have a
Wi-Fi adapter plugged in. If you do not have a compatible wi-fi adapter then you
can
purchased one below from Amazon.

Wireless Raspberry Pi adapter Wireless wifi adapter for the Raspberry Pi


Click on the WiFi Config icon that appears on the desktop.
Wireless configuration for the Raspberry Pi
A window will appear with a number of options.

Wireless Config Raspberry Pi


------------------------------------------
Click on the scan button to scan for your wireless network.
You should see a number of wireless networks but this is dependent on how close
you are to other interfering wireless networks.
Select the name of you Wi-Fi network and double click on your network.
Enter your wireless network password into the PSK field and click the add button.
Pay attention the Status label as this will inform you if there are any connection
problems.
The status label will read Completed (station) when connected.
You can also see your IP address which has been allocated to your Raspberry Pi.

Raspberry Pi Course Week 3 – Day 2.0 (Command Line Wi Fi Setup)

Raspberry Pi Course wireless


-------------------------------------------

Connecting the Raspberry Pi to a Wi-Fi network is straight forward providing you


have a
compatible Wi-Fi adapter. If you do not have a compatible wireless adapter then
you can
purchased one below from Amazon.

Wireless Raspberry Pi adapter Wireless wifi adapter for the Raspberry Pi

To achieve this, a file called interfaces needs to be edited with the correct
network information.

What is the interfaces file?


---------------------------------------

The interfaces file holds the information required to give the Raspberry Pi access
to the
wireless network or a wired network. The file exists in /etc/network/ folder.
Open a terminal window and enter the following.
$ vi /etc/network/interfaces
vi will load a file similar to this.

—————————————–
auto lo

iface lo inet loopback


iface eth0 inet dhcp
allow-hotplug wlan0
auto wlan0
iface wlan0 inet dhcp
wpa-ssid “YOUR_SSID”
wpa-psk “YOUR-PASSWORD”
—————————————–

Edit the last two lines with your SSID and your password.
Your SSID is the network ID that your Wi-Fi router is broadcasting.
Note that your SSID and password need to appear in between the quotes.

Save the file by pressing CTRL-X followed by Y to overwrite the file.


To be sure that these changes take affect reboot your password by enter the
following.
Before continuing, a quick summary of the file is in order.

The word auto is used to identify the physical interface files that will be
brought on or offline.
The line auto wlan0 is an example of this. It will allow wlan0 to be shut down or
brought back
online when using commands or when the system boots up.

The iface refers to the interface which is followed by eth0, eth1 or wlan0
etc ,depending
on which device it is referencing. The inet dhcp is informing the raspberry pi
that you
require an IP address in order to access the network. Enter the following to
restart the system.

$ reboot

If you are still having problems connecting see the troubleshooting page on
Raspberry
Pi Wireless Network Setup Issues.

Raspberry Pi Course Week 3 – Day 3 (Pi Store)


----------------------------------------------------------------

The Pi Store

The app store for the Raspberry Pi is much like any other app store found with
Apple, Microsoft
or the Android Play store. The app store gives you access to some of the software
available for
the Raspberry Pi which include both free and paid apps.

To access the Pi Store login to your desktop and double click on the Pi Store icon
which appears
on the desktop or you can visit http://store.raspberrypi.com.

Note

If your distribution does not appear to have a Pi Store icon, do not fear. You can
install it
by using the following command in a terminal.

$ apt-get install pistore


the-pi-store-app

Before you can access the store you will need to register. Click on the login link
located at the top right corner of the window and click register.
Fill in your email address, password and the security question. Click on the sign
me up button and you will be signed into your account. You can change your
username by clicking on the edit link which allows you to change your username and
upload an avatar for the account.
When you have completed the above process you will see the Pi Store. A list of
apps will be displayed which can filtered by clicking on the games, apps,
tutorials, dev tools & media menu buttons. Next to the menu buttons appears a
number. This number indicates how many apps are available for this type of
application. You can also filter by tags by clicking on one of the subjects that
appear on the left hand side of the window.
Note
Tags are very much like keywords so that the app can easily be searched and
recognised when looking for them.
To install an app on your Raspberry Pi, click on the Free Download button of the
Buy button.
When the app has successfully been downloaded and installed it will appear in the
My Library.
The my library button will display any apps that you have downloaded and installed
previously.

Raspberry Pi Course Week 3 – Day 4.0 (IP Address)


-------------------------------------------

Raspberry Pi Address
We have talked about IP address and how to configure them and we have briefly
explained why you need one for the Raspberry Pi. A more in depth explanation of
IP addresses are needed so you can really understand the network around you and the
type of devices that require an IP address.
Every device from a computer to a phone requires a unique identifier to communicate
with other devices on a network or the internet. If you are to address a letter in
the mail, then you need to address with an exact address so that the post office
know where house address this id destined for. Most networks on the internet use
something called TCP/IP protocol to communicate. This is a common standard which
allows all devices to abide by these rules so that each device can communicate with
each other. This is no different from learning the French language so that you are
able to communicate with a French speaking person.

Currently, two standards for IP addresses exist and they are IPv4 and IPv6. The
main different between the two is that IPv6 is a new addition which allows more
devices to be connected to the internet and at the same time be unique. With IPv4
this would not be possible because there isn’t enough IP address available with
IPv4. Another difference is the way in which the IP addresses are represented.
IPv4 looks like this 192.168.100.100.
IPv6 is expressed like this 201c:cab7:0000:9832:0000:0000:ad01:fffa
This early part of course will only look at IPv4.
How can you get an IP address?
An IP address can either be dynamic of static. Dynamic means that the Raspberry Pi
will automatically get an IP address from a server of router. Static means that
the IP address has to be allocated to the Raspberry Pi manually.
Open a terminal window and type the following.
# ifconfig
The following information will be returned although your IP address and device may
be different.
eth0 Link encap:Ethernet HWaddr 08:10:27:ff:65:cc
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:feef:65bc/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:19 errors:0 dropped:0 overruns:0 frame:0
TX packets:52 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:2372 (2.3 KiB) TX bytes:7776 (7.5 KiB)

Raspberry Pi Course Week 3 – Day 5 (Raspberry Pi Static IP Address)


----------------------------------------------------------

The Raspberry Pi is automatically set to obtain an IP address from your wired or


wireless network.
Why does the Raspberry Pi need an IP address? This address is needed so that any
traffic destined
for your Raspberry Pi will be able to find it on the network.

This is method of obtaining an IP address is called DHCP or Dynamic Host


Configuration Protocol.
It is sometimes referred to as a dynamic IP. Your router will normally distribute
these IP addresses
but it isn’t guaranteed that it will get the same IP address every time.
This can cause problems if you are trying to connect to your Raspberry Pi remotely.

So how do you set a static IP address?


Login and enter the following command

cat /etc/network/interfaces

The line below is referring to the eth0 interface and that is should use DHCP.

iface eth0 inet dhcp


To change this line to a static IP address, enter the following command to retrieve
your existing
IP address and network information.

ifconfig

Make a note of your current IP address, the broadcast IP and the Mask. This is
represented by the

inet addr: 192.168.0.6 [CHANGE]


Bcast: 192.168.0.255 [CHANGE]
Mask: 255.255.255.0

One last thing that is required is the gateway.


This is in most cases your routers internal IP address.

Enter the following


route -nee
Make a note of Gateway address.
Gateway: 192.168.0.1

Next you need to edit the interfaces file to set this static information. Enter
the following command.

vi /etc/network/interfaces

Remove the line that reads


iface eth0 inet dhcp

Add the following


iface eth0 inet static
address 192.168.0.6
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.1

Save the file by pressing CTRL-X and select Y to save the changes.

When the raspberry Pi reads this file when booting up, it will look at the
interface eth0 and set
it to a static IP address. I will set the IP address to 192.168.0.6, the network
to 192.168.0.0,
the broadcast address and the gateway address so that it can find its way out of
the network.

Reboot your Raspberry Pi with the following command


reboot

Login back in and enter the following.


ping 192.168.0.1 -c5

This will ping your gateway address or router and will return :
64 bytes from 192.168.1.254: icmp_req=1 ttl=255 time=2.18
64 bytes from 192.168.1.254: icmp_req=2 ttl=255 time=2.43
64 bytes from 192.168.1.254: icmp_req=3 ttl=255 time=3.24
64 bytes from 192.168.1.254: icmp_req=4 ttl=255 time=2.20
64 bytes from 192.168.1.254: icmp_req=5 ttl=255 time=3.37

One last thing that needs to be modified is the /etc/resolv.conf file.


This file contains information of DNS name resolvers that allow your raspberry pi
to resolve
names to IP addresses. For example, if you ping www.suntimebox.com the raspberry
pi will have
to determine the IP address of www.suntimebox.com.

Enter the following command to edit the resolv.conf file.


vi /etc/resolv.conf
Enter the follow Google public dns server IP address.
nameserver 8.8.8.8
name server 8.8.4.4
Press CTRL-X to exit but remember to save the file by accepting the changes.

If you prefer, you can always make a reservation on your router or server.
For this you will have to make a note of the hardware address when you enter the
ifconfig command. The hardware address is represent as the HWaddr:
08:00:22:ef:65:bc.
Note that your hardware address will be different.

Please let me know if I have missed anything or you want to add something that will
benefit
someone or a comment saying thank you would be nice.
It makes it all worthwhile knowing that I helped someone and if I didn’t, let me
know where I went wrong.

Raspberry Pi Course Week 6 – Day 3 (Installing Apache Web Server)


---------------------------------------------------------

This tutorial will teach you the basics of installing Apache Web Server on the
Raspberry Pi and
you will create a simple HTML page to verify that the page will being delivered to
the client using
a web browser.

To install the apache web server, which is also known as apache2 can be installed
using the following commands.

apt-get install apache2

When the installation is complete enter the following command.

cd /var/www/html

And list the file contents by entering ls at the command prompt.


$ ls
index.html
This directory is used for files that you want to serve up using Apache2 and the
index.html file
is one of the default files that Apache will display when accessing the server.

Log into the Raspberry Pi desktop and open a web browser. In the web address bar
enter the following.

http://localhost

This will retrieve the index.html file and display something similar to this.

Raspberry pi apache web browser


The Apache web server is now up and running.

To confirm that additional HTML pages can be added we will create an html page and
store it in the
/var/www/html directory.

Open a terminal window and enter the following commands.

cd /var/www/html
vi mypage.html
When vi opens enter the following basic html code
<html>
<head>
<title>This is my Raspberry Pi Page</title>
</head>
<body>This is where the action happens</body>
</html>

Save this file by holding down CTRL-X. vi will prompt you to save the file.
Open a web browser and in the address bar enter
http://localhost/mypage.html
You will see a web page with the content being displayed.

Raspberry Pi Course Week 6 – Day 4 (Installing PHP)


--------------------------------------------

Occorre per far diventare dinamiche le pagine ovvero che siano diverse in base alle
risposte date
dall utente o per i risultati di una query eseguita in un database

Per prima cosa installiamo php

apt-get install php5 libapache2-mod-php5 -y

Poi il conponente che permette di interagire con un database mysql:

apt-get install php5-mysql

Posso rimuovere il file indice originale:


rm index.html

e crearne uno personalizzato:

cd /var/www/html
vi index.php
Immettere il seguente codice:

<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
echo date('Y-m-d H:i:s');
echo "hello world";
phpinfo();
?>
</body>
</html>

==============================================================
AZARTICOLO: CISCO LEARNING:WEP, WPA, WPA2, TKIP, AES, CCMP, EAP.
==============================================================

John Leader 2 Star


John 27-feb-2010 9.13

Hi

WPA
-------

Implements the majority of IEEE 802.11i, but with different headers (so can operate
both
in same network). Designed to require only a firmware upgrade
(full 802.11i usually requires hardware change).

As designed, WPA uses TKIP and Michael for message integrity, based on RC4 for
encryption.

Pre-shared (personal) vs. Enterprise (RADIUS)

Defines the type of authentication used.

WPA (and WPA2) may operate in enterprise mode, using a RADIUS server to hold per-
user keys.
This allows individual access to be controlled in a large network.
For a small network, e.g. home network, without a RADIUS server a pre-shared key
(PSK)
may be used. The same key is used by all clients, so may require more work to
update.

TKIP vs. AES-based CCMP


-------------------------------------

Defines the algorithm used for message integrity and confidentiality.


WPA was designed to be used with TKIP (and WPA2 designed to use stronger AES-
based).
However, some devices allow WPA (not WPA2) with AES (and WPA2 with TKIP).
AES is optional in WPA;
in WPA2 both AES is mandatory, BUT TKIP is optional.

Note that TKIP is not directly comparable to AES;


TKIP is an integrity check, AES is an encryption algorithm.

In the context of wireless security this actually means TKIP vs. "AES-based CCMP"
(not just AES).
TKIP is a lower end encryption protocol (WEP2) and AES is a higher end
(WPA2/802.11i)
encryption protocol. AES is preferred.

TKIP+AES
----------------

This is what the encryption standards are for WEP2 (TKIP) and WPA2/802.11i (AES).
It will attempt to use AES if available and fall back to TKIP if not.
This setting offers the most compatibility but won't guarantee a higher level of
encryption
if a device falls back to TKIP.

WPA2, ovvero 802.11i


-------------------------------

Fully conforms with 802.11i as it implements all mandatory features.


Guarantees interoperability certification.
Effectively WPA2 is Wi-Fi Alliance's brand name for 802.11i.

Note: In some cases other optional features of 802.11i may be required, but
interoperability
may not be guaranteed.

Support for AES encryption and AES-based CCMP message integrity is mandatory
(is optional in WPA).

As well as mandatory AES, WPA2 also adds PMK (Pair-wise Master Key) and
Pre-authentication to help fast roaming.

EAP options
-------------------

Authentication options for 802.11i.


Two initial types - pre-shared key (personal) or RADIUS (enterprise), same as per
WPA.
Additional types of enterprise authentication types now available
(usually not relevant for home users).

AES-based CCMP
-------------------------
WPA2 mandates AES-based CCMP for message integrity and confidentiality.
TKIP (weaker) is optional.

WPA2 mixed
--------------------

Mixed mode allows device to try WPA2 first, and if that fails fall-back to WPA.

WEP
--------

WEP was supposed to provide Confidentiality, but has found to be vulnerable and
should
no longer be used, has been found to be vulnerable and is often the default;
this should be changed. Most devices that support WEP can be firmware/software
upgraded to WPA. Do not use unless some devices can not be upgraded to support WPA.

WEP has been outdated for years and has better replacements.
The 40-bit encryption is just not strong enough to keep data secure and can be
broken
rather easily. Newer encryption methods use stronger encryption and have yet to be
broken while WEP can be broken in a minute, use WPA where possible.

Preference Summary
----------------------------------

To keep things simple, the best options, in decreasing order of preference, may be:

WPA2 + AES
WPA + AES (only if all devices support it).
WPA + TKIP+AES (only if all devices can support it).
WPA + TKIP
Disabled (no security)

The most common two options will be WPA2 + AES and WPA + TKIP,
because they match the mandatory requirements in the standards
(WPA2 requires AES, WPA requires TKIP).

You can use WPA + AES for higher security than TKIP, but only if your devices
support it
(it is optional). For this reason it is not very common.
You also do not get the improved roaming features of WPA2.

WPA + TKIP+AES provides a fallback in case AES is not supported by a device in that
it
switches to the more common TKIP. The disadvantage is that it might switch to TKIP
unexpectedly but is more backwards compatible if needed.

Currently TKIP has no known vulnerabilities, so for broadest compatibility stick


with
WPA + TKIP.

The remaining combination, WPA2 + TKIP, is possible (as TKIP is optional in WPA2),
but doesn't make much sense because AES is more secure and mandatory for all
WPA2 devices.

================================================================================
AZARTICOLO:How-To: Turn a Raspberry Pi into a WiFi router
================================================================================

http://raspberrypihq.com/how-to-turn-a-raspberry-pi-into-a-wifi-router/

December 4, 2013admin
Raspberry Pi with Edimax Wifi Adapter
Share this: Share on FacebookShare on Google+Tweet about this on TwitterPin on
PinterestShare on RedditShare on LinkedIn
Do you want a separate WiFi network for your guests? or would you like to have
network running an alternative DNS configuration in your house? You no longer have
to buy a new WiFi router to do this – you can turn your Raspberry Pi into a WiFi
router.
This post will guide you through the process of setting up your Raspberry Pi as a
WiFi network.

Prerequisites & Equipment

You are going to need the following:

A Raspberry Pi (Buy here)


A USB WiFi Adapter (I use the Edimax – Wireless 802.11b/g/n vi USB adapter – its
small and cheap!)
A SD Card flashed with the Raspbian OS (Here is a guide if you need)
Access to the Raspberry either via keyboard and a monitor or remotely
Raspberry Pi with Edimax Wifi Adapter
Raspberry Pi with Edimax Wifi Adapter
Before we proceed I want to point out the importance of buying the right USB WiFi
Adapter. As you may have experienced with other types of hardware devices not all
devices are plug-n-play. Sometimes you will need to download a driver to make them
work. While drivers are normally readily available for Windows computers – it is a
different world for Linux and Raspberry Pi’s. This is why it is very important to
buy a WiFi Adapter that mentions “Linux” in the product description or package. I
use the Edimax – Wireless 802.11b/g/n vi USB adapter because I have found it to be
cheap and very easy to work with. I very recommend you do the same – it could save
you a lot of headaches.

Getting WiFi adapter running on the Raspberry Pi


-----------------------------------------
Plug the USB WiFi adapter into one of the free USB ports on the Raspberry Pi.
Power up the Raspberry Pi. At this point you need to either connect to the
Raspberry Pi via an
Ethernet cable or use a keyboard and a monitor to access the Raspberry Pi.

If you need help connecting to the Raspberry Pi look at this post remotely using a
wired network connection.

After booting and logging-in you want to make sure that the Raspberry Pi found your
new wireless adapter. To look at which peripherals the operating system found when
booting run the following command:

dmesg | more
You can use the spacebar to scroll down a page at a time – towards the end you will
see something similar to the following lines:

[ 3.282651] usb 1-1.2: new high-speed USB device number 4 using dwc_otg
[ 3.394810] usb 1-1.2: New USB device found, idVendor=7392, idProduct=7811
[ 3.407489] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 3.420530] usb 1-1.2: Product: 802.11n WLAN Adapter
This means that the operating system recognized the USB WiFi Adapter using one of
the built-in drivers (you can return to the terminal by pressing “q”). All that is
left is to configure your WiFi connection.

Install the router software

In order for the Raspberry Pi to act as a WiFi router and access point you need to
install some extra software on the Raspberry. You are going to need the following
pieces of software:

hostapd
HostAPD is a user space daemon for access point and authentication servers. That
means it can will turn your Raspberry Pi into a access point that other computers
can connect to. It will also handle security such that you can setup a WiFi
password.
isc-dhcp-server
isc-dhcp-server is the Internet Systems Consortium’s implementation of a DHCP
server. A DHCP server is responsible for assigning addresses to computers and
devices connection to the WiFi access point.
To install the DHCP software run the following command:

apt-get install isc-dhcp-server


Next up is the HostAPD software. Because our USB stick needs an access point driver
not supported by the native HostAPD application we must install a custom version
compiled with the driver we need. This can be done by running the following
commands one at a time.

wget https://github.com/jenssegers/RTL8188-hostapd/archive/v1.1.tar.gz
tar -zxvf v1.1.tar.gz
cd RTL8188-hostapd-1.1/hostapd
make
make install
This will take a little time – while waiting for the program to compile send a
friendly thought to Jens Segers over at http://jenssegers.be for making this
software available.

Once downloaded we are ready to configure the software.

Configure the ISC-DHCP-Server

To configure the DHCP server open the file /etc/dhcp/dhcpd.conf in your favorite
text editor. You can open it in vi using this command:

vi /etc/dhcp/dhcpd.conf
Find the following section and comment it out by placing a hashtag at the beginning
of the line.

option domain-name "example.org";


option domain-name-servers ns1.example.org, ns2.example.org;
Next find the section below and un-comment the word authoritative (remove hastag):

# If this DHCP server is the official DHCP server for the local
# network, the authoritative directive should be uncommented.
#authoritative;
The file now looks like this:

dhcpconfig1

Next we need to define the network and network addresses that the DHCP server will
be serving. This is done by adding the following block of configuration to the end
of file:

subnet 192.168.10.0 netmask 255.255.255.0 {


range 192.168.10.10 192.168.10.20;
option broadcast-address 192.168.10.255;
option routers 192.168.10.1;
default-lease-time 600;
max-lease-time 7200;
option domain-name "local-network";
option domain-name-servers 8.8.8.8, 8.8.4.4;
}
This will enable the DHCP server to hand out the ip addresses from 192.168.10.10 to
192.168.10.20 in its own local network. People who are skilled in network
configuration can change these values if they wish to use some other network
addresses and/or other DNS servers. This configuration will use the Google DNS
servers at 8.8.8.8 and 8.8.4.4.

To save the file press Ctrl+O this will write the file to the disk – afterwards you
can exit vi by pressing Ctrl+X. If vi asks if you want to Save modified buffer?
press “Y” followed by hitting enter to confirm the filename.

Next file to edit is /etc/default/isc-dhcp-server, you can open it in vi using this


command:

vi /etc/default/isc-dhcp-server
Scroll down to the line saying interfaces and update the line to say:

INTERFACES="wlan0"
This will make the DHCP server hand out network addresses on the wireless
interface. Save the file and exit nano.

The last step in configuring the DHCP server is to configure a static ip address
for the wireless network adapter. This is done in the file /etc/network/interfaces
– before opening it make sure the WLAN interface is down. Do this with the
following commands:

ifdown wlan0
vi /etc/network/interfaces
Change the file to look like this:

interfaces

This will make the wireless adapter take the address 192.168.10.1 in our new local
network. Remember to comment out the last 3 lines of the file.

This concludes the setup of the DHCP server – however we still cannot connect to
our new network because we have not setup the access point yet. This is done by
configuring the hostapd application.

Configuring HostAPD

To configure HostAPD, open the file called /etc/hostapd/hostapd.conf in your


favorite text editor. You can open it in vi using this command:

vi /etc/hostapd/hostapd.conf
The standard configuration will create a new wireless network called wifi with the
password YourPassPhrase. You can change the parameter “ssid=wifi” to the SSID wifi
name you want and the parameter “wpa_passphrase=YourPassPhrase” to your own
password.

This concludes the configuration of our access point software HostAPD. Next up is
enabling NAT.

Enable NAT
-----------------
The last step before we can start the access point is setting up Network Address
Translation (NAT). This will make sure that our network traffic will be able to
reach the internet using the Raspberry Pi’s Ethernet cable connection to your
internet router.

Open /etc/sysctl.conf with:


vi /etc/sysctl.conf
Scroll down to the last line of the file and add the line:

net.ipv4.ip_forward=1
Next start the translation right away by running:

sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"


Start the wireless network by running:

ifup wlan0
Next step is setting up the actual translation between the ethernet port called
eth0 and the wireless card called wlan0.

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE


iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

With the NAT configured it is now time to run your access point for the first time.

Starting your wireless router

You are now ready to start the DHCP server and the HostAPD access point
application.You can do so by running:

service isc-dhcp-server start


service hostapd start
At this point you should be able to find your wireless network on your laptop and
connect to it and the internet!

Finishing up …

While it is pretty cool you now have your Raspberry Pi running as a wireless access
point it is not so cool you have to login every time it reboots to start the
HostAPD and DHCP software…

To avoid this run the following commands:

update-rc.d hostapd enable


update-rc.d isc-dhcp-server enable
To avoid having to configure NAT every time the Raspberry Pi reboots you can do the
following.

Run this command to backup the NAT configuration.

sh -c "iptables-save > /etc/iptables.ipv4.nat"

Add the following to the end of the file /etc/network/interfaces to restore the
configuration when the network interface comes up:

up iptables-restore < /etc/iptables.ipv4.nat

The file should now look like:

interfaces_iptables

At this point try to reboot the raspberry pi just to make sure everything works as
intended
– you can reboot with the command:
reboot

Hopefully you will see your new access point come online again.
After it comes up again you should be able to connect to it and access the
internet!

================================================================================
AZARTICOLO: How to Set Up WiFi on the Raspberry Pi
================================================================================
http://www.circuitbasics.com/raspberry-pi-wifi-installing-wifi-dongle/

In the last post, I explained how to install the Raspbian operating system without
a monitor
or keyboard, and how to establish an SSH connection to your Raspberry Pi over an
ethernet
connection. Now I’ll explain how to use that SSH connection to setup a WiFi dongle
so you can
run your Raspberry Pi wirelessly from a remote desktop application.

This is a really useful way to set up your Raspberry Pi, because you will be able
to access your
it over the internet from anywhere in the world. You can use it from your iPhone,
iPad, or Laptop
from anywhere with an internet connection.

We have already established an SSH connection to our Raspberry Pi with an ethernet


cable, and
that is fine if you want to leave it connected to your router with a physical
cable.

However, I prefer to use a WiFi dongle, which gives me more flexibility with the
physical locations
I can store the Raspberry Pi while it is running. Be careful when choosing a WiFi
dongle for the
Raspberry Pi though, because not all WiFi dongles will work without a lot of
configuration and headaches.
I found that this one from Kootek works great without any driver installations
needed.

Still, there are some things that need to be done in order to set up the WiFi
dongle to work
properly with your Raspberry Pi. I will go through them step by step in this
article.
You should already have set up the SSH over ethernet connection I described in part
one of this post.

Now, login to your Raspberry Pi over SSH through the PuTTY SSH client, and get to
the
pi@raspberrypi – $ command prompt:

raspi after entering password, before raspi-config

Next, we need to will need to change a few configuration settings in two files:
/etc/network/interfaces, and /etc/wpa_supplicant/wpa_supplicant.conf.

To edit these files, we need to use the Raspbian text editor, Nano.
At the command prompt, type
vi /etc/network/interfaces to edit the /etc/network/interfaces file.
Pro Tip: If you ever want to copy something from your laptop/desktop and paste it
into
PuTTY, just copy it on your laptop/desktop, then right click with your mouse where
you
want to paste it into PuTTY and it will be inserted.

Replace the code in the file with this code:

auto lo
iface lo inet loopback
iface eth0 inet dhcp
auto wlan0
iface wlan0 inet dhcp
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

Afterwards, the file should look like this:

etc,network,interfaces file

Then type ctrl X to exit, and Y to save the changes.


Now edit the /etc/wpa_supplicant/wpa_supplicant.conf file by typing
vi /etc/wpa_supplicant/wpa_supplicant.conf at the command prompt.

Replace the code in the file with this code:

ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=0
update_config=1
network={
ssid="YOUR WIFI NETWORK NAME"
psk="YOUR WIFI PASSWORD"
proto=WPA
key_mgmt=WPA-PSK
pairwise=TKIP
group=TKIP
}

The file should look like this:

etc,wpa supplicant

The entry for ssid=”YOUR WIFI NETWORK NAME” should be the name of your wireless
network,
typed exactly as it shows when you connect to your WiFi from another computer. It
is case sensitive.

The entry for psk=”YOUR WIFI PASSWORD” is the password you normally use to login to
your
home wireless network.

Then re-enter your network name under the id_str=”YOUR WIFI NETWORK NAME” line.
Now press ctrl X, then Y, to save the changes to the file.

To see a list of the currently available WiFi networks, enter


iwlist wlan0 scan | grep ESSID at the command prompt.
To check the status of your WiFi connection, type iwconfig at the command prompt.
Your WiFi network name should appear under ESSID: “YOUR WIFI NETWORK NAME”,
in my case it is “Siamese“. If your WiFi connection is successful, you should see
a message like this:

iwconfig2

If you see something like “Link Quality=0/100“ or “Signal Level=0/100“, go back and
make sure
that you have entered everything exactly as it is shown in the images.
All of the configuration settings should now be saved to work with your WiFi
dongle, so enter
poweroff into the command prompt to shut down the Raspberry Pi.
Now disconnect the ethernet cable and the power cord.
Wait about one minute, then plug the power cord back into it without the ethernet
cable.
Now we will need to use Advanced IP Scanner again to find the new local IP address
of the
Raspberry Pi when it is connected via WiFi. This has likely changed slightly from
when we used it
on the ethernet connection. It is useful to keep track of both IP’s if you will be
connecting with
ethernet at all in the future.

PuTTY is great if all you need to do is access your Raspberry Pi from the command
line.
However, many features are only available through the Raspbian desktop.
In order to access the desktop remotely, we need to install and configure a Remote
Desktop Connection.
Read How to Set Up Access to the Raspbian GUI via a Remote Desktop Connection for a
tutorial
on how to do that.

===============================================================================
AZARTICOLO: How to Set Up a Static IP on the Raspberry Pi
================================================================================

Have you ever tried to log into your Raspberry Pi via SSH and been denied because
the IP address
couldn’t be found? Do you have to scan your network every time you connect to find
your local IP
address? If the IP address of your Raspberry Pi changes all the time, it’s because
you’re using a
dynamic IP. If you want your Raspberry Pi to have an IP address that doesn’t change
automatically,
assign it a static IP address. With a static IP, you can be sure that the same IP
will work each
and every time. In this article, I’ll show you how to configure a static IP address
using a clean
installation of Raspbian Jessie and Raspbian Jessie Lite, but this should work with
newer versions
of Raspbian Wheezy as well. However, since there are pros and cons to each type of
IP, lets first
talk about why you would want a static IP vs. a dynamic IP.

Static IP vs Dynamic IP
--------------------
Dynamic IP

Dynamic IP’s are good to use if you are concerned about security.
If a hacker gets access to your IP address, you will be less vulnerable to attack
since your IP
changes frequently. A dynamic IP can change every time you log in, or only at
certain intervals.
A program installed on your network router called the dynamic host configuration
protocol (DHCP),
automatically changes and assigns new dynamic IP addresses to computers on your
network.

Static IP
--------

A static IP (as you could probably tell by the name) is one that doesn’t change.
This makes them more reliable when using services that depend on a stable internet
connection,
like online gaming, VOIP, or remote access applications. With a static IP, you’ll
be able to use
the same IP address every time you connect to your Pi via SSH or remote desktop
applications.

Setting up a Static IP on the Raspberry Pi


------------------------------------
Before starting, make sure you have already set up and configured a way to access
the command prompt.
Check out our tutorials, How to Set Up WiFi on the Raspberry Pi and How to Set Up a
Raspberry Pi
Without a Monitor or Keyboard to see how to do that if you haven’t already.

In this tutorial we’ll set up static IP’s for both WiFi and ethernet connections.
If you only need one or the other, just omit the code below for the connection you
don’t need.

Find Out Your Network Information


-----------------------------
The first step is to find out your default gateway IP.
This is the local IP address of your network router.
The computers on your network use it to communicate with the router and access the
internet.
If you already know what it is, just skip this step. If not, do continue…

Power up and log into your Raspberry Pi via WiFi or ethernet, then enter route -ne
at the command
prompt to see your network routing information:

Under the “Gateway” column, you can see your Default Gateway IP (10.0.0.1 in my
case)
for each interface (Iface) – ethernet (eth0) and WiFi (wlan0). Write down your
default gateway IP,
we will need it later.

Now we need to find out the IP addresses of your domain name servers.
Your Pi sends the domain names you enter into your browser (i.e. www.google.com) to
domain
name servers, which then converts them to IP addresses (i.e. 8.8.8.8) that your Pi
can use to
directly access the website’s server. Enter cat /etc/resolv.conf at the command
prompt to find
the list of domain name servers your Pi uses:

Copy these IP addresses to a text editor on your PC or write them down for later.
Configuration of Network Settings
-----------------------------

Now we’re ready to configure the network settings.


By default the Pi is configured with a dynamic IP address.
To give it a static IP, we need to add our desired static IP, our default gateway
IP,
and our static domain name servers IP addresses to the dhcpcd.conf file.

At the command prompt, enter vi /etc/dhcpcd.conf to edit the dhcpcd.conf file:

How to Set Up a Static IP for your Raspberry Pi - vi dhcpcd conf

Now, without changing anything else in the file, add this code to the end of the
/etc/dhcpcd.conf file, replacing the IP addresses with your own IP addresses found
above:

interface eth0
static ip_address=10.0.0.100
interface wlan0
static ip_address=10.0.0.99
static routers=10.0.0.1
static domain_name_servers=75.75.75.75 75.75.76.76 2001:558:feed::1
2001:558:feed::2

Replace the addresses in the code above with your own addresses:

static ip_address= This is the static IP address you will use to SSH or remotely
connect to your Pi.
Take your default gateway IP (found in the steps above), and
change the last
number to any other number between 0 and 255.
static routers= This is your default gateway IP address.
static domain_name_servers= These are the IP’s we found in the /etc/resolv.conf
file above.
Seperate each IP with a single space.

For example, my default gateway IP address is 10.0.0.1.


To get the static ip_address for my ethernet connection (eth0),
I replaced the 1 with 100 to get 10.0.0.100.
To get the static ip_address for my WiFi connection (wlan0),
I replaced the 1 with 99 to get 10.0.0.99.
These are the static IP’s I will use to log in to my Pi from now on.

The file should look like this (with your own IP addresses):

Static IP Address for Raspberry Pi - dhcpcd File Contents

Once you’ve replaced the IP addresses in the example code with your own IP
addresses,
press Ctrl-X and Y to exit and save the /etc/dhcpcd.conf file.
Now enter reboot to reboot the Pi. Log in with your new static ethernet IP or
static WiFi IP:

Static IP Address for the Raspberry Pi in PuTTY


---------------------------------------------
To check that everything is working correctly and we can access the internet, lets
ping Google.
Enter ping www.google.com at the command prompt:
Press Ctrl-C to stop the pinging. If the connection is successful, you will see
that packets have
been sent and received. If your connection isn’t successful, you will get a
“Network is unreachable” error:

How to Set Up a Static IP for your Raspberry Pi -


Direct Ethernet Connection Ping Google Network Unreachable

You should probably test the connection by pinging Google with both eth0 and wlan0
(ethernet and WiFi) IP’s.

Watch the video version of the process here:

Another nice way to connect to your Pi is via a direct ethernet connection to your
laptop or desktop.
A direct connection is extremely fast and stable. If you connect to your Pi via SSH
a lot,
I would definitely recommend setting this up.
Check out our article, How to Connect to a Raspberry Pi Directly with an Ethernet
Cable to learn how.
I would definitely recommend setting this up.
Thanks for reading! Now that you have a static IP set up, your Pi’s connection to
the internet will
be a lot more reliable.

================================================================================
AZARTICOLO:Use the Raspberry Pi Serial Port to Connect to a Device
================================================================================
https://it.mathworks.com/help/supportpkg/raspberrypiio/ug/use-the-serial-interface-
on-raspberry-pi-hardware.html

This example shows how to create a connection to a serial device, write data to the
device,
and read data from the device.

By default, the serial console in the customized version of Raspian Wheezy on your
Raspberry Pi™ hardware is enabled.
To use the serialdev, the serial console must be disabled.

Warning

Excessive voltage and current can damage the Raspberry Pi hardware.


Observe the manufacturer’s precautions for handling the Raspberry Pi hardware and
connecting it to other devices. For more information, see

http://www.raspberrypi.org/technical-help-and-resource-documents.

Create a connection to the Raspberry Pi hardware using raspi.

mypi = raspi

Show the location of the Tx and Rx pins, GPIO 14 (UART0_TXD) and GPIO 15
(UART0_RXD),
on the GPIO header.

showPins (mypi)

Raspberry Pi hardware uses +3.3V.


Do not connect Raspberry Pi hardware directly to devices that use higher voltages.

Connect the Raspberry Pi board to a +3.3V serial device.

To receive data, connect the GPIO 15 (UART0_RXD) pin on the Raspberry Pi board
to the
TxD pin on the serial device.

To transmit data, connect the GPIO 14 (UART0_TXD) pin on the Raspberry Pi board to
the
RxD pin on the serial device.

Connect a ground pin, GND, on the Raspberry Pi board to the GND pin on the serial
device.

Connect a +3.3V pin on the Raspberry Pi board to the VCC pin on the serial device.

Before continuing, research the manufacturer’s product information to determine


which
baud rate, data bits, parity, and stop bit settings the serial device supports.

Use serialdev to create a connection to the serial device and assign the connection
to a handle.

myserialdevice = serialdev (mypi,'/dev/ttyAMA0')

myserialdevice =

serialdev with properties:

BaudRate: 115200
DataBits: 8
Parity: 'none'
StopBits: 1
Timeout: 10

In this example, the connection uses the


default values for baud rate (115200), data bits (8), parity ('none'), and stop bit
(1).

If the serial device requires nondefault values, use a set of optional arguments to
override
those defaults.

myserialdevice = serialdev(mypi,'/dev/ttyAMA0',115200,8,'none',2)

myserialdevice =

serialdev with properties:

BaudRate: 115200
DataBits: 8
Parity: 'none'
StopBits: 2
Timeout: 10

This example overrides the default value of StopBits by setting it to 2.


It uses the other arguments to maintain the correct sequence of arguments to the
left of
the rightmost overriding value.

You can write values to the serial device.

write(myserialdevice,[10 12],'uint16')

This example writes two values to the serial device.


It overrides the default precision, uint8, by setting it to uint16.

You can also read an array of values from the serial port.

output = read(myserialdevice,100)

This example reads a 100-element array of uint8 values from the serial device.

If the serial connection times out during read operations, you can adjust the time
out period
by assigning a new value to the Timeout property.

myserialdevice.Timeout = 20

myserialdevice =

serialdev with properties:

BaudRate: 115200
DataBits: 8
Parity: 'none'
StopBits: 1
Timeout: 20

To use the serial console, enable the serial console and reboot the Raspberry Pi
hardware.

system(mypi, 'rpi-serial-console enable')


system(mypi, 'shutdown -r now')
clear mypi

When the Raspberry Pi hardware finishes rebooting, you can communicate with the
Linux® command interface over a USB to TTL serial cable that is connected to the
serial
pins on the GPIO header.

However, you cannot use serialdev until you disable the console.

================================================================================
root@raspi:/lib/modules/4.4.15+# rpi-update

*** Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS and Dom


*** Performing self-update
*** Relaunching after update
*** Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS and Dom
*** We're running for the first time
*** Backing up files (this will take a few minutes)
*** Remove old firmware backup
*** Backing up firmware
*** Remove old modules backup
*** Backing up modules 4.9.35-v7+
#############################################################
This update bumps to rpi-4.9.y linux tree
Be aware there could be compatibility issues with some drivers
Discussion here:
https://www.raspberrypi.org/forums/viewtopic.php?f=29&t=167934
##############################################################
*** Downloading specific firmware revision (this will take a few minutes)
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 168 0 168 0 0 245 0 --:--:-- --:--:-- --:--:-- 245
100 54.0M 100 54.0M 0 0 1277k 0 0:00:43 0:00:43 --:--:-- 1891k

*** Updating firmware


*** Updating kernel modules
*** depmod 4.9.53+
*** depmod 4.9.53-v7+
*** Updating VideoCore libraries
*** Using HardFP libraries
*** Updating SDK
*** Running ldconfig
*** Storing current firmware revision
*** Deleting downloaded files
*** Syncing changes to disk
*** If no errors appeared, your firmware was successfully updated to
5d03351413d4021cc3feeb04459eea98bcb731c0
*** A reboot is needed to activate the new firmware

root@raspi:/lib/modules/4.4.15+# reboot
Connection to raspi closed by remote host.
Connection to raspi closed.

================================================================================
IFPLUGD
================================================================================

/usr/sbin/ifplugd -i eth0 -q -f -u0 -d10 -w -I


/usr/sbin/ifplugd -i wlan0 -q -f -u0 -d10 -w -I

root@raspi:~# ifplugd --help


----------------------------

ifplugd -- Network Interface Plug Detection Daemon

Usage: ifplugd [options]

Options:
-q --no-shutdown Non lanciare lo script in fase di uscita del
daemon padre (quit =off)
-f --ignore-fail Non terminare sui fallimenti, invece
ritenta
(ovvero il fallimento
e' trattato come un DOWN) (off)
-u --delay-up=SECS Tempo di attesa prima di configurare
l'interfaccia (default 0)
-d --delay-down=SECS Tempo di attesa prima di sconfigurare l'interfaccia
(default 5)
-w --wait-on-fork Attendi fin quando la fork del daemon e'
terminata (default off)
-i --iface=IFACE Specifica interfaccia ethernet da
monitorare (eth0)
-I --ignore-retval Non uscire se il programma eseguito
termina con errore (off)
-b --no-beep Do not beep (off)
-U --no-beep-up Do not beep on interface up (off)
-D --no-beep-down Do not beep on interface down (off)
-a --no-auto Do not enable interface
automatically (off)
-n --no-daemon Do not daemonize (for debugging) (off)
-s --no-syslog Do not use syslog, use stderr instead
(for debugging) (off)
-F --ignore-fail-positive Ignore detection failure, retry instead (failure is
treated as UP) (off)
-r --run=EXEC Specify program to execute
(/etc/ifplugd/ifplugd.action)
-t --poll-time=SECS Specify poll time in seconds (1)
-T --poll-utime=USECS Specify poll time in microseconds, add to -t (0)
-m --api-mode=MODE Force API mode (mii, priv, ethtool, wlan, auto) (auto)
-p --no-startup Don't run script on daemon startup (off)
-l --initial-down Run "down" script on startup if no cable
is detected (off)
-W --wait-on-kill When run with -k, wait until the daemon died
(off)
-x --extra-arg Specify an extra argument for action
script
-M --monitor Use interface monitoring (off)
-h --help Show this help
-k --kill Kill a running daemon
-c --check-running Check if a daemon is currently running
-v --version Show version
-S --suspend Suspend running daemon
-R --resume Resume running daemon
-z --info Write status of running daemon to
syslog

===================================================================================
========
AZARTICOLO: Settare il WiFi Roaming con wpa_roaming
===================================================================================
========

Overview
-------------

wpa-roaming e' un metodo per eseguire la connessione ed il browser della rete


wireless
da linea di comando. e' preconfigurata in modo che se il cavo ethernet e'
scollegato la
linea wireless wlan0 prende la precedenza

Se si collega il cavo ethernet la rete wireless viene buttata giu' e ci si


connette solo via cavo
La rete Wireless va su non appena si stacca il cavo

Io invece desidero che la rete wireless sia su al boot e non sia mai scollegata
la rete ethernet deve essere normalmente down e se viene collegato il cavo deve
andare su ma solo come default gateway ovvero deve permettere il solo accesso in
uscita
fuori della LAN mentre tutto il traffico LAN deve comunque passare dal Wireless
tutto questo viene comandato dal daemon
/usr/sbin/ifplugd -i eth0 -q -f -u0 -d10 -w -I -b

Provo a disabilitarlo
systemctl disable ifplugd
al boot non e' stato ripristinato !

Settaggio della rete


-----------------------------

La rete deve essere cosi configurata in /etc/network/interfaces

# The loopback network interface


auto lo
iface lo inet loopback

#Aggiunta dall utente


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

#Questa linea ci deve sempre essere


iface default inet dhcp

Ora a wpa_supplicant occorre che sia configurato il file wpa-roam.conf

Copiamolo dalla documentazione:


cp /usr/share/doc/wpasupplicant/examples/wpa-roam.conf /etc/wpa_supplicant/wpa-
roam.conf

editiamolo:

vi /etc/wpa_supplicant/wpa-roam.conf

Decommentiamo la linea 30 (rimuovere #). Serve affinche il file venga


effettivamente
salvato

update_config=1

Mettiamo in sicurezza l'accesso alla rete wireless

Esempio WEP
--------------------

network={
ssid="debian"
key_mgmt=NONE
wep_key0=6162636465
wep_tx_keyidx=0
}

Esempio WPA-WPA2PSK
------------------------------------

network={
ssid="aptosid_Worldwide"
psk="mysecretpassphrase"
}

Mettiamo in sicurezza il file wpa-roam.conf perche' contiene la chiave di accesso


alla rete

chmod 600 /etc/wpa_supplicant/wpa-roam.conf

Portiamo su la rete wireless

ifup wlan0

Controlliamo se siamo connessi

wpa_cli status

Selected interface 'wlan0'


bssid=94:0c:6d:aa:f4:42
ssid=aptosid_Melbourne
id=3
pairwise_cipher=CCMP
group_cipher=CCMP
key_mgmt=WPA2-PSK
wpa_state=COMPLETED
ip_address=192.168.1.102

Se non si vede nulla sull'indirizzo IP non si e' connessi, pertanto rifacciamo un


tentativo
If you can not see ip_address= numbers you are not connected so recheck the configs
by
first stopping wlan0:

wpa_action wlan0 stop

Should you require specialised networking configs see here

To enable switching between wired and wireless networks


-----------------------------------------------------------------------------------
---

First see Switching between cable and wireless because if its not set up correctly
switching
and connection to the network will not happen.

After setting up ifplugd the final config should look like this:

auto lo
iface lo inet loopback

# governed by ifplugd ... do not use allow-hotplug or auto options


iface eth0 inet dhcp

#Added by user
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa-roam.conf

#this line must always be here


iface default inet dhcp
Using wpa-roam.conf with manually specified network configurations

With the help of IDString and Priority you can direct to which network the box is
connected
at boot time. Highest priority is 1000, lowest priority is 0.
You have to add the id_str to /etc/network/interfaces as well.

The syntax for /etc/network/interfaces.

First is for the connection to DHCP servers, the second is if you are provided with
a fixed
IP address. To adjust your settings:

# id_str="home_dhcp"
iface home_dhcp inet dhcp

#this line must always be here


iface default inet dhcp

# id_str="home_static"
iface home_static inet static

address 192.168.0.20
netmask 255.255.255.0
network 192.168.0.0

broadcast 192.168.0.255
gateway 192.168.0.1

Practical Examples
-------------------------------

If you want to be automatically connected to your home WLAN when at home, give the
the IDString "home" and priority "15". If you are travelling, and want the laptop
to connect
to any free, non passworded network which is available, give it the IDString
"stalk" and priority
"1" (very low). But please, always check if your connection is legal and disconnect
if it is obviously
not intended to be free.

Example stanzas in /etc/network/interfaces:

# /etc/network/interfaces -- configuration file for ifup(8), ifdown(8)

# The loopback interface


# automatically added when upgrading
auto lo
iface lo inet loopback

allow-hotplug eth0
iface eth0 inet dhcp

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

#this line must always be here


iface default inet dhcp

iface home inet dhcp


iface stalk inet dhcp

Example /etc/wpa_supplicant/wpa-roam.conf (SSID and passwords are changed or just


explained):

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
ssid="my_ssid"
scan_ssid=1
psk=123ABC ##here comes the passphrase in hexadecimal code!!
# psk="password_in_ascii" ##you dont need to
key_mgmt=WPA-PSK
pairwise=TKIP
group=TKIP
auth_alg=OPEN
priority=15
id_str="home"
}

network={
ssid=""
scan_ssid=1
key_mgmt=NONE
auth_alg=OPEN
priority=1
disabled=1 ## no automatic connection, one needs wpa_cli or wpa_gui
id_str="stalk"
}

With "disabled=1" you will not be automatically connected to a defined network


block
(open WLANs), you have to initiate roaming through wpa_gui or wpa_cli.
For automatic roaming don't use the option at all or comment the line with the
"disabled"
option using a #.

WEP encryption

If you want to add WEP encrypted networks to your wpa-roam.conf permanently, the
syntax is:

network={
ssid="example wep network"
key_mgmt=NONE
wep_key0="abcde"
wep_key1=0102030405
wep_tx_keyidx=0
}

Notes

1. Easy to reuse
----------------------
Once set up, you can easily reuse your setup on other laptops or desktops with WLAN
cards.
Just copy /etc/network/interfaces (adjust the name of the interface if needed) and
/etc/wpa_supplicant/wpa-roam.conf to your new box.
There is no need of "installing" anything after that.

2. Backup
------------------

It is a good idea to backup /etc/network/interfaces and /etc/wpa_supplicant/wpa-


roam.conf,
but encrypt your backup because it contains sensitive information.

A good method to safely backup and encrypt the config files is with tar and gpg. As
root:

tar -cf- /etc/network/interfaces /etc/wpa_supplicant/wpa-roam.conf | gpg -c >


backup_name.tar.gpg

A file has now been created in $ HOME:


backup_name.tar.gpg

To list the contents of the backup_name.tar.gpg file:

gpg -d -o - backup_name.tar.gpg | tar vtf -

To extract and decrypt the contents of the archive backup_name.tar.gpg file:

gpg -d -o - backup_name.tar.gpg | tar vxf -

3. Hidden SSIDs
-----------------------

Hidden SSIDs are detected when scan_ssid=1 is defined in the network block.
Basic wireless modem/router security

Where you have control of the wireless router/modem, there are a few basic security
policies to implement to help protect your side of the network from intruders.

Basic protocol choices


---------------------------------

WPA2-PSK is the better option.


For encryption protocol choose AES.
The passphrase should be really strong.

Passphrase / passwords
-----------------------------------
For a passphrase/password that is strong and not really able to be memorised, use
pwgen
in a terminal (also read: man pwgen):

$ pwgen -s 63 1
VltnfGmGKXovVv2rmrCFFXBZ55Mij5bA6WytVJnVoKUqRn6dfjldG6MBrRo0Cdi

-s = secure (no mnemonics)


63 = amount of characters
1 = only generate one random password
Without the -s you get speaking type passwords. however it is unlikley you would
want that:

$ pwgen 8 3
Sooxae2s Niew9ugh Hi7eeloo

Once you have generated the passphrase/password store it in a text file on a USB-
stick
and apply the passphrase/password to the other computers that use your wireless
network.
Do not store the passphrase/password on your computer.

Example of final router setup:

Version: WPA2-PSK
Encryption: AES
PSK Password: VltnfGmGKXovVv2rmrCFFXBZ55Mij5bA6WytVJnVoKUqRn6dfjldG6MBrRo0Cdi

===================================================================================
=========
AZARTICOLO:CISCO ACCESS POINT
===================================================================================
=========
Cell 03 - Address: C4:EA:1D:5F:7C:21
Channel:5
Frequency:2.432 GHz (Channel 5)
Quality=70/70 Signal level=-19 dBm
Encryption key:on
ESSID:"CISCOWIFI"
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
24 Mb/s; 36 Mb/s; 54 Mb/s
Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 48 Mb/s
Mode:Master
Extra:tsf=0000000000000000
Extra: Last beacon: 80ms ago

IE: Unknown: 0009434953434F57494649


IE: Unknown: 010882848B962430486C
IE: Unknown: 030105
IE: Unknown: 2A0100
IE: Unknown: 2F0100

IE:
IEEE 802.11i/WPA2 Version 1 *
Group Cipher : CCMP *
Pairwise Ciphers (1) : CCMP *
Authentication Suites (1) : PSK

Prima era:

IE:
WPA Version 1
Group Cipher : TKIP
Pairwise Ciphers (1) : TKIP
Authentication Suites (1) : PSK

IE: Unknown: 32040C121860


IE: Unknown:
2D1A1E181BFFFF000000000000000000000000000000000000000000
IE: Unknown: 3D1605080000000000000000000000000000000000000000
IE: Unknown: 4A0E14000A002C01C800140005001900
IE: Unknown: 7F0101
IE: Unknown:
DDA00050F204104A0001101044000102103B000103104700109C8254764E8E

540397D22571F3C86DFB1021000B546563686E69636F6C6F721023000E4D656

469614163636573732054471024000D373939766E207632203547487A1042000

93135333754414D47461054000800060050F2040001101100154D6F64656D2054

656C65636F6D20414720706C7573100800020004103C0001011049000600372A
000120
IE: Unknown: DD090010180200000C0000
IE: Unknown:
DD180050F2020101000003A4000027A4000042435E0062322F00

===================================================================================
============
AZARTICOLO: UBUNTU:Connect to WiFi network from command line in Linux
===================================================================================
============

How many of you failed to connect to WiFi network in Linux?

Following guide explains how you can connect to a WiFi network in Linux from
command Line.
This guide will take you through the steps for connecting to a WPA/WPA2 WiFi
network.
In case you’ve only got wired connection only, you can use this guide to setup DHCP
or static IP
address from command line in Linux.

WiFi network from command line – Required tools

Following tools are required to connect to WiFi network in Linux from command line

wpa_supplicant
iw
ip
ping

Before we jump into technical jargons let’s just quickly go over each item at a
time.

Linux WPA/WPA2/IEEE 802.1X Supplicant


-------------------------------------------------------------

wpa_supplicant is a WPA Supplicant for Linux, BSD, Mac OS X, and Windows with
support for WPA and WPA2 (IEEE 802.11i / RSN).
It is suitable for both desktop/laptop computers and embedded systems.
Supplicant is the IEEE 802.1X/WPA component that is used in the client stations.
It implements key negotiation with a WPA Authenticator and it controls the roaming
and IEEE 802.11 authentication/association of the wlan driver.

iw – Linux Wireless
------------------------------
iw is a new nl80211 based CLI configuration utility for wireless devices.
It supports all new drivers that have been added to the kernel recently.
The old tool iwconfing, which uses Wireless Extensions interface, is deprecated and
it’s
strongly recommended to switch to iw and nl80211.

ip – ip program in Linux
----------------------------------

ip is used to show / manipulate routing, devices, policy routing and tunnels. It is


used
for enabling/disabling devices and it helps you to find general networking
informations.
ip was written by Alexey N. Kuznetsov and added in Linux 2.2.
Use man ip to see full help/man page.

ping
--------

Good old ping For every ping, there shall be a pong …. ping-pong – ping-pong –
ping-pong …
that should explain it.

BTW man ping helps too …

Step 1: Find available WiFi adapters – WiFi network from command line
-----------------------------------------------------------------------------------
---------------------
This actually help .. I mean you need to know your WiFi device name before you go
an
connect to a WiFi network. So just use the following command that will list all the
connected WiFi adapters in your Linux machines.

root@kali:~# iw dev
phy#1
Interface wlan0
ifindex 4
type managed
root@kali:~#

Let me explain the output:

This system has 1 physical WiFi adapters.

Designated name: phy#1


Device names: wlan0
Interface Index: 4. Usually as per connected ports (which can be an USB port).
Type: Managed. Type specifies the operational mode of the wireless devices.
managed
means the device is a WiFi station or client that connects to an access point.

Connect to WiFi network in Linux from command line - Find WiFi adapters - blackMORE
Ops-1

Step 2: Check device status – WiFi network from command line


-----------------------------------------------------------------------------------
---------

By this time many of you are thinking, why two network devices.
The reason I am using two is because I would like to show how a connected and
disconnected
device looks like side by side. Next command will show you exactly that.

You can check that if the wireless device is up or not using the following command:

root@kali:~# ip link show wlan0

4: wlan0: <BROADCAST,MULTICAST> mtu 1500 qdisc mq state DOWN mode DORMANT qlen 1000
link/ether 00:60:64:37:4a:30 brd ff:ff:ff:ff:ff:ff
root@kali:~#

As you can already see, I got once interface (wlan0) as state UP and wlan1 as state
DOWN.

Look for the word “UP” inside the brackets in the first line of the output.

Connect to WiFi network in Linux from command line - Check device status- blackMORE
Ops-2

In the above example, wlan1 is not UP. Execute the following command to
Step 3: Bring up the WiFi interface – WiFi network from command line

Use the following command to bring up the WiFI interface

root@kali:~# ip link set wlan0 up

Note: If you’re using Ubuntu, Linux Mint, CentOS, Fedora etc. use the command
with ‘sudo’ prefix

Connect to WiFi network in Linux from command line - Bring device up - blackMORE
Ops-3

If you run the show link command again, you can tell that wlan1 is now UP.

root@kali:~# ip link show wlan0


4: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DORMANT
qlen 1000
link/ether 00:60:64:37:4a:30 brd ff:ff:ff:ff:ff:ff
root@kali:~#

Step 4: Check the connection status – WiFi network from command line
-----------------------------------------------------------------------------------
------------------------

You can check WiFi network connection status from command line using the following
command:

root@kali:~# iw wlan0 link


Not connected.
root@kali:~#

Connect to WiFi network in Linux from command line -


Check device connection - blackMORE Ops-4

The above output shows that you are not connected to any network.

Step 5: Scan to find WiFi Network – WiFi network from command line
-----------------------------------------------------------------------------------
------------------

Scan to find out what WiFi network(s) are detected

root@kali:~# iw wlan0 scan


BSS 9c:97:26:de:12:37 (on wlan0)
TSF: 5311608514951 usec (61d, 11:26:48)
freq: 2462
beacon interval: 100
capability: ESS Privacy ShortSlotTime (0x0411)
signal: -53.00 dBm
last seen: 104 ms ago
Information elements from Probe Response frame:
SSID: blackMOREOps
Supported rates: 1.0* 2.0* 5.5* 11.0* 18.0 24.0 36.0 54.0
DS Parameter set: channel 11
ERP: Barker_Preamble_Mode
RSN: * Version: 1
* Group cipher: CCMP
* Pairwise ciphers: CCMP
* Authentication suites: PSK
* Capabilities: 16-PTKSA-RC (0x000c)
Extended supported rates: 6.0 9.0 12.0 48.0
---- truncated ----

The 2 important pieces of information from the above are the SSID and the security
protocol
(WPA/WPA2 vs WEP). The SSID from the above example is blackMOREOps.
The security protocol is RSN, also commonly referred to as WPA2.
The security protocol is important because it determines what tool you use to
connect to
the network.

— following image is a sample only —

Connect to WiFi network in Linux from command line - Scan Wifi Network using iw -
blackMORE Ops - 5

Step 6: Generate a wpa/wpa2 configuration file


----------------------------------------------------------------------

Now we will generate a configuration file for wpa_supplicant that contains the pre-
shared key
(“passphrase”) for the WiFi network.

root@kali:~# wpa_passphrase blackMOREOps >> /etc/wpa_supplicant.conf


abcd1234
root@kali:~#
(where 'abcd1234' was the Network password)

wpa_passphrase uses SSID as a string, that means you need to type in the passphrase
for the
WiFi network blackMOREOps after you run the command.

Connect to WiFi network in Linux from command line - Connect to WPA WPA2 WiFi
network - blackMORE Ops - 6

Note: If you’re using Ubuntu, Linux Mint, CentOS, Fedora etc. use the command with
‘sudo’ prefix
wpa_passphrase will create the necessary configuration entries based on your input.
Each new network will be added as a new configuration (it wont replace existing
configurations)
in the configurations file /etc/wpa_supplicant.conf.

root@kali:~# cat /etc/wpa_supplicant.conf


# reading passphrase from stdin
network={
ssid="blackMOREOps"
#psk="abcd1234"
psk=42e1cbd0f7fbf3824393920ea41ad6cc8528957a80a404b24b5e4461a31c820c
}
root@kali:~#

Step 7: Connect to WPA/WPA2 WiFi network


-----------------------------------------------------------------
Now that we have the configuration file, we can use it to connect to the WiFi
network.
We will be using wpa_supplicant to connect. Use the following command

root@kali:~# wpa_supplicant -B -D wext -i wlan0 -c /etc/wpa_supplicant.conf


ioctl[SIOCSIWENCODEEXT]: Invalid argument
ioctl[SIOCSIWENCODEEXT]: Invalid argument
root@kali:~#

Where,

-B means run wpa_supplicant in the background.


-D specifies the wireless driver. wext is the generic driver.
-c specifies the path for the configuration file.

Connect to WiFi network in Linux from command line


- Connect to WPA WPA2 WiFi network - blackMORE Ops - 7

Use the iw command to verify that you are indeed connected to the SSID.

root@kali:~# iw wlan0 link


Connected to 9c:97:00:aa:11:33 (on wlan0)
SSID: blackMOREOps
freq: 2412
RX: 26951 bytes (265 packets)
TX: 1400 bytes (14 packets)
signal: -51 dBm
tx bitrate: 6.5 MBit/s MCS 0

bss flags: short-slot-time


dtim period: 0
beacon int: 100

Step 8: Get an IP using dhclient


----------------------------------------------

Until step 7, we’ve spent time connecting to the WiFi network.


Now use dhclient to get an IP address by DHCP

root@kali:~# dhclient wlan0


Reloading /etc/samba/smb.conf: smbd only.
root@kali:~#
You can use ip or ifconfig command to verify the IP address assigned by DHCP. The
IP address is 10.0.0.4 from below.

root@kali:~# ip addr show wlan0


4: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000
link/ether 00:60:64:37:4a:30 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.4/24 brd 10.0.0.255 scope global wlan0
valid_lft forever preferred_lft forever
inet6 fe80::260:64ff:fe37:4a30/64 scope link
valid_lft forever preferred_lft forever
root@kali:~#

(or)

root@kali:~# ifconfig wlan0


wlan0 Link encap:Ethernet HWaddr 00:60:64:37:4a:30
inet addr:10.0.0.4 Bcast:10.0.0.255 Mask:255.255.255.0
inet6 addr: fe80::260:64ff:fe37:4a30/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:23868 errors:0 dropped:0 overruns:0 frame:0
TX packets:23502 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:22999066 (21.9 MiB) TX bytes:5776947 (5.5 MiB)

root@kali:~#

Add default routing rule.


The last configuration step is to make sure that you have the proper routing rules.

root@kali:~# ip route show


default via 10.0.0.138 dev wlan0
10.0.0.0/24 dev wlan0 proto kernel scope link src 10.0.0.4

Connect to WiFi network in Linux from command line - Check Routing and DHCP -
blackMORE Ops - 8
Step 9: Test connectivity – WiFi network from command line

Ping Google’s IP to confirm network connection (or you can just browse?)

root@kali:~# ping 8.8.8.8


PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_req=3 ttl=42 time=265 ms
64 bytes from 8.8.8.8: icmp_req=4 ttl=42 time=176 ms
64 bytes from 8.8.8.8: icmp_req=5 ttl=42 time=174 ms
64 bytes from 8.8.8.8: icmp_req=6 ttl=42 time=174 ms
^C
--- 8.8.8.8 ping statistics ---
6 packets transmitted, 4 received, 33% packet loss, time 5020ms
rtt min/avg/max/mdev = 174.353/197.683/265.456/39.134 ms
root@kali:~#

Conclusion
-----------------

This is a very detailed and long guide.


Here is a short summary of all the things you need to do in just few line.

# iw dev
# ip link set wlan0 up
# iw wlan0 scan

#wpa_passphrase CISCOWIFI intrapam123$ >> /etc/wpa_supplicant/wpa_supplicant.conf

network={
ssid="CISCOWIFI"
#psk="intrapam123$"
psk=0f1a94ca5722a564249371073210bc9911ad5c1993c1302e7d0dee3b17e5ebad
}

# wpa_supplicant -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf


# iw wlan0 link
# dhclient wlan0
# ping 8.8.8.8

(Where wlan0 is wifi adapter and blackMOREOps is SSID)


(Add Routing manually)
# ip route add default via 10.0.0.138 dev wlan0

At the end of it, you should be able to connect to WiFi network.


Depending on the Linux distro you are using and how things go, your commands might
be slightly different. Edit commands as required to meet your needs.
Thanks for reading. Please share and tweet.

Dopo aver ucciso il demone ifplugd facciamo salire la rete wireless


------------------------------------------------------------------------------

root@raspi:~# ifconfig

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500


inet 192.168.1.5 netmask 255.255.255.0 broadcast 192.168.1.255
ether b8:27:eb:27:88:39 txqueuelen 1000 (Ethernet)
RX packets 194 bytes 20281 (19.8 KiB)
RX errors 0 dropped 1 overruns 0 frame 0
TX packets 219 bytes 26673 (26.0 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536


inet 127.0.0.1 netmask 255.0.0.0
loop txqueuelen 1 (Local Loopback)
RX packets 41 bytes 4861 (4.7 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 41 bytes 4861 (4.7 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500


inet 192.168.1.7 netmask 255.255.255.0 broadcast 192.168.1.255
ether b8:27:eb:72:dd:6c txqueuelen 1000 (Ethernet)
RX packets 13 bytes 1044 (1.0 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 26 bytes 3596 (3.5 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

ma se ne chiedo lo stato mi dice che non ha indirizzo IP e me la da disconnessa:

root@raspi:~# wpa_cli status

Selected interface 'p2p-dev-wlan0'


wpa_state=DISCONNECTED
p2p_device_address=ba:27:eb:72:dd:6c
address=ba:27:eb:72:dd:6c
uuid=da8ed45e-9cb1-59fb-88e0-d75ae6613775

Iplink invece me la da in LOWER_UP ovvero in mode DORMANT:

root@raspi:~# ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT
group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode


DEFAULT group default qlen 1000
link/ether b8:27:eb:27:88:39 brd ff:ff:ff:ff:ff:ff

3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode


DORMANT group default qlen 1000
link/ether b8:27:eb:72:dd:6c brd ff:ff:ff:ff:ff:ff

Questo implica che se provo ad accedervi dal portatile in realta' il router non
avendo il
suo MAC ADDRESS mi mappa a livello arp eth0 e wlan0 sullo stesso mac della eth0
per cui se mi collego all indirizzo di wlan0 in realta' passo sempre per eth0 !!!

Se tuttavia eseguo questo trucco vado sulla Raspberry epingo il PC dalla


interfaccia wlan0

root@raspi:~# ping -I wlan0 portatile2009

PING portatile2009 (192.168.1.2) from 192.168.1.7 wlan0: 56(84) bytes of data.


64 bytes from portatile2009 (192.168.1.2): icmp_seq=1 ttl=64 time=6.95 ms

Sul PC ricevo il MAC ADDRESS corretto e se da questo mi connetto utilizzando


l'indirizzo
della WIFI passo effettivamente da questa:

[root@portatile2009 /]# arp -a


raspiw (192.168.1.7) at b8:27:eb:72:dd:6c [ether] on eth0
raspi (192.168.1.5) at b8:27:eb:27:88:39 [ether] on eth0
ciscowifi (192.168.1.1) at c4:ea:1d:5f:7c:20 [ether] on eth0
[root@portatile2009 /]# ssh raspiw

Vediamo cosa accade al boot

===================================================================================
============
AZARTICOLO:Configuring Raspberry Pi as a Wireless-to-Wired Ethernet Island
===================================================================================
============

http://www.glennklockwood.com/sysadmin-howtos/rpi-wifi-island.html

My apartment does not have hardwired ethernet, and the physical location of our
incoming cable
is such that it’s very difficult to position wired ethernet anywhere. I’ve
considered using a
powerline adapter to run ethernet over the apartment’s electric, but those adapter
kits are
a bit expensive. When I got my Raspberry Pi though, it occurred to me that I could
use it
to create an island of wired ethernet that feeds to the wifi connection we’ve got
set up.

This is a depiction of the setup I was going for to turn wireless internet into
wired.

Raspberry Pi network diagram

I find iptables (and networking in Linux) extremely obtuse and hate having to
figure this stuff out, so now that I’ve got it working I will leave the necessary
configuration details below.

A much more comprehensive writeup on this concept has been developed by Robin
Newman, so if this guide is unclear, I highly recommend checking out Robin’s guide.

Ben Low also pointed out a handy tutorial that gives a much more sophisticated
treatment of this approach using Proxy ARP that is a good thing to check out if
this configuration is not good enough.

/etc/network/interfaces should look something like this.


If you couldn’t tell, this is Raspbian (a Debian-derived distribution)

# The loopback network interface


auto lo
iface lo inet loopback

# the internal (wired) network interface


allow-hotplug eth0
iface eth0 inet static
address 192.168.2.1
network 192.168.2.0
netmask 255.255.255.0
broadcast 192.168.2.255
gateway 192.168.2.1

# the external (wifi) interface


allow-hotplug wlan0
iface wlan0 inet static
address 192.168.1.98
network 192.168.1.0
netmask 255.255.255.0
broadcast 192.168.1.255
gateway 192.168.1.1
wpa-ssid "homewifi"
wpa-psk ...

pre-up iptables-restore < /etc/network/iptables

The contents of /etc/network/iptables are:

*filter
:INPUT ACCEPT [73:5085]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [72:6792]
-A FORWARD -i eth0 -j ACCEPT
-A FORWARD -i wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
COMMIT
*nat
:PREROUTING ACCEPT [43:2584]
:INPUT ACCEPT [2:278]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -o eth0 -j MASQUERADE
-A POSTROUTING -o eth0 -j MASQUERADE
-A POSTROUTING -o wlan0 -j SNAT --to-source 192.168.1.98
COMMIT

which was generated by this script:

#!/bin/sh
IPT=/sbin/iptables
LOCAL_IFACE=eth0
INET_IFACE=wlan0
INET_ADDRESS=192.168.1.98

# Flush the tables


$IPT -F INPUT
$IPT -F OUTPUT
$IPT -F FORWARD

$IPT -t nat -P PREROUTING ACCEPT


$IPT -t nat -P POSTROUTING ACCEPT
$IPT -t nat -P OUTPUT ACCEPT

# Allow forwarding packets:


$IPT -A FORWARD -p ALL -i $LOCAL_IFACE -j ACCEPT
$IPT -A FORWARD -i $INET_IFACE -m state --state ESTABLISHED,RELATED -j ACCEPT

# Packet masquerading
$IPT -t nat -A POSTROUTING -o $INET_IFACE -j SNAT --to-source $INET_ADDRESS

Of course, ip forwarding has to be enabled in the kernel by editing


/etc/sysctl.conf and uncommenting a line:

# Uncomment the next line to enable packet forwarding for IPv4


net.ipv4.ip_forward=1

and then doing sysctl –system.

================================================================================
AZARTICOLO:WATCHDOG:How do I hard reset a Raspberry Pi?
================================================================================

How do I hard reset a Raspberry Pi?

Obviously you can power cycle, but is there a more subtle way, like a reset pin?
It would be very useful to connect a watchdog in case the Raspberry Pi crashes

EDIT: The rev 2.0 board has a header you can connect a reset switch to.
hardware reset watchdog
shareimprove this question

Power cycling is dangerous. Be ready to say goodbye to the contents of the SD card
if you
use that method. Below I show the answer for the PI 3.
Using a reset button is rarely necessary, but is MUCH safer than power cycling.
You can use the BCM2708's hardware watchdog.

To use it begin by loading the module:

modprobe bcm2708_wdog

Then edit the /etc/modules file:

nano /etc/modules

and add the following line:

bcm2708_wdog

Next you will need to setup the watchdog daemon.

Install and confiigure it to start on bootup:


--------------------------------------------

apt-get install watchdog chkconfig


chkconfig watchdog on
/etc/init.d/watchdog start

Next configure watchdog:


-----------------------

nano /etc/watchdog.conf

Uncomment the line #watchdog-device = /dev/watchdog so it reads:

watchdog-device = /dev/watchdog

The watchdog daemon will send /dev/watchdog a heartbeat every 10 seconds.


If /dev/watchdog does not receive this signal it will restart your Raspberry Pi.

This can be useful if you are accessing your Pi remotely, and it dies or locks up.
However, this is not the preferred method of restarting the system, but can be used
to
restart a locked system, where the only other option is to remove power from the
device.
Be warned that this can result in filesystem damage that could prevent the Pi from
booting
and operating correctly.

More info including a method to test this setup can be found in Gadgetoid's blog
post

Who watches the watcher?.

Binerry's tumblr post

Raspberry Pi Watchdog Timer should also be a must read.

--------------------------------------------------------------------------------
I found that I couldn't shut down my Pi for a clean power off. It would shut down,
the hardware watchdog kick in and reboot the system seconds after.
I've removed the options Wojciech suggested and have changed my
/etc/init.d/watchdog as follows:
stop)
if [ $run_watchdog = 1 ]
then
log_begin_msg "Stopping watchdog daemon..."
start-stop-daemon --stop --quiet --retry $STOP_RETRY_SCHEDULE \
--pidfile /var/run/$NAME.pid
modprobe -r bcm2708_wdog
log_end_msg $?

## # make sure that wd_keepalive is started


## log_begin_msg "Starting watchdog keepalive daemon..."
## start-stop-daemon --start --quiet --pidfile
/var/run/$KEEPALIVE_NAME.pid \
## --exec $KEEPALIVE_DAEMON -- $watchdog_options
## log_end_msg $?
fi ;;

I found the "chkconfig" command wasn't available on my RPi

The following seems to be the RPi/Debian equivalent:


"update-rc.d watchdog enable"

Tested and working :)


Reply

Share ›

Avatar
Gadgetoid Mod Pete • 4 years ago

You're correct. I often forget that I install chkconfig simply because I'm
familiar with it, and only recently came across update-rc.d.

To get chkconfig just:

sudo apt-get install chkconfig

Edit: I've updated the guide to reflect this!



Reply

Share ›

Avatar
Wojciech Niziński • 5 years ago

To prevent hardware watchdog from being stopped, when watchdog process is killed,
please load module with additional options.
Create new file i.e. /etc/modprobe.d/watchdog.conf with content:

options bcm2708_wdog nowayout=1

================================================================================
AZARTICOLO:Raspberry Pi Watchdog Timer
================================================================================
http://binerry.de/post/28263824530/raspberry-pi-watchdog-timer

Since i’m familiar with using a watchdog timer in some microcontroller-projects,


i’ve been thinking about watchdog-support for Raspberry Pi.

Generally a watchdog timer is nothing else than a timer-register which can be


realized on hardware- and/or software-side.

It’s main purpose is to trigger a system reset or other corrective action if


something doesn’t works anymore as it should be.

In detail the timer-register needs to get resetted in a functional workflow


before its filled up and triggers the reset or special action.

This means that the functional system must trigger a heartbeat to the watchdog
(“feeding the dog”)
within a hard (hardware, not changeable) or soft (software, self-definable) time
period.
An absence of some heartbeats results in reaching the time limit and triggering the
reset/action.

Luckily the BCM2835 SoC has a hardware-based watchdog timer on board - but sadly
there are no further informations about it in the actual datasheet.
If i’m right informed this watchdog timeout register has 20 bits and counts down
every
16µs (source: Raspberry PI BB), so the the hardware timer limit is something around
16 seconds (16*2^20µs) which seems to be right according to bcm2708_wdog module
source.

The actual firmware includes the driver-module bcm2708_wdog (or if you compiled
your
kernel by yourself ensure that you have enabled BCM2835 watchdog support
[CONFIG_WATCHDOG=y, CONFIG_BCM2708_WDT=m|y]).
Just load it and add it if necessary to your modules-configuration for loading it
at startup:

sudo modprobe bcm2708_wdog


sudo nano /etc/modules (add line “bcm2708_wdog”)

This will create the device /dev/watchdog.

The watchdog is automatically started once the device is opened.


Once the watchdog is started, it needs to get feeded with heartbeats -
this is done by writing anything but the character “V” to the device
(see watchdog api). “V” is a magic character which will disable the watchdog -
so it’s important to know that just closing the device without writing the magic
char to it won’t stops the watchdog, quite the contrary will happen and the timer

limit will be reached and the reset gets triggered.

If you want to use the watchdog within an own application scenario its recommended
to use ioctl-api. For feeding the watchdog you can insert WDIOC_KEEPALIVE via
ioctl.
You can get or set the soft timer limitvia WDIOC_GETTIMEOUT and WDIOC_SETTIMEOUT,
but remember that its hard limited to 16s, so if you set a soft-timeout larger
than this limit it will be just setted to 15s.
Also remember to disable the watchdog by writing a “V” for a straight program exit.

I have written a small test-snippet for demonstrating the use of the watchdog timer
within an own application. You can find it in my github-repository -
Just build it and play with it - It supports a clean and a failure exit
for testing purposes:

cc -o wdt_test wdt_test.c (or just:) make

sudo ./wdt_test (for a clean exit)


sudo ./wdt_test -t (for a failure exit)

If you don’t want to control the watchdog by your own, of course you can use a
ready-to-use watchdog-daemon, which provides some more features than just feeding
the dog with heartbeats every 10 or 15s.
It can also run several tests to check the system healthfulness like monitoring
memory and load, checking ping-results, measuring temperature or performing
user-defined commands to do arbitrary tests and trigger reboot when they fail.

sudo bash
apt-get install watchdog chkconfig

chkconfig watchdog on
/etc/init.d/watchdog start

nano /etc/watchdog.conf
(enable line “watchdog-device = /dev/watchdog”)

So now its time to test if everything works as it should be. Ensure that there
aren’t any critical processes running and try to cause a kernel panic for example.

This can be tried with deactivating any swap space and a nasty forkbomb
(: (){ :|:& };:), but more reliable will be a fake kernel-module.

If everything is set up correctly the system will reboot a few seconds later.
So from now your system is protected by the watchdog.

================================================================================
AZARTICOLO:4 Awesome ways to find top CPU consuming processes in Linux.
================================================================================

https://linuxroutes.com/how-to-find-top-cpu-consuming-processes-in-linux/

Major part of sysadmin time goes into finding the cause of the load on the system
eg.
Finding processes which are consuming the resources.
This post will help you with how to quickly find top CPU consuming processes in
Linux.

Top CPU consuming processes in Linux


------------------------------------

1. Finding out top CPU consuming processes in Linux using ps command.


-----------------------------------------------------------------------------------
-----------------------

There is one liner code available with ps command which will help you to find top
CPU
consuming processes in Linux.

Command:

ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head

Sample Output:

ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head

PID PPID CMD %MEM %CPU


23236 20520 dd if=/dev/zero of=/dev/nul 0.0 96.6
19509 1 /usr/bin/Xvnc :1 -desktop r 0.8 0.3
19559 19514 nautilus 0.4 0.1
19668 1 /usr/lib64/firefox-3.6/fire 2.0 0.1

1 0 /sbin/init 0.0 0.0


2 0 [kthreadd] 0.0 0.0
3 2 [migration/0] 0.0 0.0
4 2 [ksoftirqd/0] 0.0 0.0
5 2 [migration/0] 0.0 0.0

2. Continuously monitoring top CPU consuming processes in Linux.


----------------------------------------------------------------

Lets say you don’t want single sample output of the command instead you want to
monitor
the output continuously. Yes you can do it using watch command as below:

Command:

watch "ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu"

Sample output:
Every 2.0s: ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head

PID PPID CMD %MEM %CPU


23236 20520 dd if=/dev/zero of=/dev/nul 0.0 99.2
19509 1 /usr/bin/Xvnc :1 -desktop r 0.8 0.2
19559 19514 nautilus 0.4 0.1
19668 1 /usr/lib64/firefox-3.6/fire 2.0 0.1
1 0 /sbin/init 0.0 0.0
2 0 [kthreadd] 0.0 0.0
3 2 [migration/0] 0.0 0.0
4 2 [ksoftirqd/0] 0.0 0.0
5 2 [migration/0] 0.0 0.0

3. Top CPU consuming processes in Linux using top command.


----------------------------------------------------------

The same output of the ps command can also be achieved using the native top command
in linux to find top cpu consuming processes in Linux.

Command:
# top -b -n 1 | head -n 12 | tail -n 6

Sample output:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
23236 root 20 0 102m 672 568 R 100.0 0.0 12:43.07 dd
23377 root 20 0 15084 1184 848 R 2.0 0.0 0:00.01 top
1 root 20 0 19396 1532 1228 S 0.0 0.0 0:01.34 init
2 root 20 0 0 0 0 S 0.0 0.0 0:00.01 kthreadd
3 root RT 0 0 0 0 S 0.0 0.0 0:05.08 migration/0

4. Find Top CPU consuming processes in Linux using htop command.


----------------------------------------------------------------

Like top command htop utility within linux which will help you to find the top cpu
consuming processes in Linux. To find it out use “htop” command.

[root@rhel1 ~]# htop

Once you fired htop command, a continuous running window will open same like top as
below:

top cpu consuming processes in Linux

Now to sort out the processes by cpu utilization simply press “F6” button and then
select
cpu and press enter. You will now see the processes sorted according to cpu
utilization as below:

You may like:


-----------------------

How to Stop and delete Linux Raid array


Quick way to configure FTP server
How to extend linux mount point.
Complete Guide: Rename file Linux
How to extend-resize Linux root partition on AWS EC2
How To bash compare numbers
Automate remote linux commands from Windows terminal using plink.
Complete Guide: Linux grep command

================================================================================
AZARTICOLO:X-based VNC server
================================================================================

Xvnc is the Unix VNC server, which is based on a standard X server.


Applications can display themselves on it as if it were a normal X display, but
they will
actually appear on any connected VNC viewers rather than on a physical screen.

So Xvnc is really two servers in one.


To the applications it is an X server, and to the remote VNC users it is a VNC
server.
By convention we have arranged that the VNC server display number will be the same
as the X server display number, which means you can use eg. snoopy:2 to refer to
display 2
on machine 'snoopy' in both the X world and the VNC world.

Normally you will start Xvnc using the vncserver script, which is designed to
simplify the
process, and which is written in Perl.
You will probably want to edit this to suit your preferences and local conditions.
We recommend using vncserver rather than running Xvnc directly, but Xvnc has
essentially
the same options as a standard X server, with a few extensions.
Running Xvnc -h will display a list.

As mentioned in Getting Started , vncserver can be run with no options at all.


In this case it will choose the first available display number, start Xvnc as that
display,
and run a couple of basic applications to get you started.
You can also specify the display number, in which case it will use that number if
it is
available and exit if not, eg: vncserver :13

uinput
----------

uinput is a kernel module that makes it possible to emulate input devices from
userspace.
By writing to /dev/uinput (or /dev/input/uinput) device, a process can create a
virtual
input device with specific capabilities. Once this virtual device is created, the
process can
send events through it, that will be delivered to userspace and in-kernel
consumers.

Un device driver di input virtuale. Crea un device driver in cui scrivere eventi
relatvi a
tastiera o mouse e che poi saranno consegnati a /dev/input ovvero ai processi che
girano
nello user space come se fossero stati generati dalle periferiche fisiche

evdev
---------

evdev e' un interfaccia normalizzatrice degli eventi di input ovvero genera degli
eventi di
input con un interfaccia indipendente dal device di input.. Ovvia sia che l'evento
sia scaturito
da un mouse o da una tastiera il kernel attraverso tale device permette al processo
nello spazio user di
ricevere un evento dallostesso device e con un interfaccia comune. Altamente
consigliato

================================================================================
AZARTICOLO:Installazione di Raspbian su Raspberry Pi & utilizzando SSH e VNC
================================================================================

The installation of the Raspbian Wheezy Linux Distribution on an SD card.


Powering up the Raspberry Pi (RPi) board and connecting it to the network
Remotely Accessing the RPi board via SSH
Initial Configuration of the Rasbpian OS/ RPi board
Remotely Accessing the RPi's graphical desktop environment (LXDE) via VNC

For starters you'll need a microUSB terminated AC adapter, an Ethernet cable & an
SD card.
I highly recommend that you use a 4GB SD card as a minimum. Also this tutorial
assumes that
you are running a Debian or Ubuntu Based Linux operating system on your PC.
I myself run Crunchbang Linux 11, which is based on Debian Wheezy 7.
If you are running a fresh install of Debian Wheezy please setup the utility
appropriately.

Installing Raspbian on your SD Card


------------------------------

Plug in the SD card into the PC then run the following command in a terminal
window: "fdisk -l".
This will list all of the available drives available on your PC as shown in
Figure 1.

Figure 1. Display all hard/flash drives attached to the PC with the 'fdisk' command
Figure 1. Display all hard/flash drives attached to the PC with the 'fdisk'
command

From the output in Figure 1 you can see that the operating system detects two
drives,
"/dev/sda" is a 64.0GB SSD drive and the "/dev/sdb/" is our 8.0GB SD card.

The next step is to download the latest Raspbian Wheezy Linux distribution image
from this page.
Take note of SHA-1 hash string and the username (pi) and password (raspberry)
listed on the page.
Once downloaded, in a terminal window, navigate to the folder containing the
compressed Raspbian
image with "cd".** **

Type the following command:


"sha1sum 20xx-xx-xx-wheezy-raspbian.zip".

Where the 'x's should represent the compressed image version.

After a few seconds, a long string will be printed in the console window.
Compare this string with the one on the Raspbian download page.
If the Raspbian image is complete and not not corrupted, then both strings
(hash codes) should be identical.

Now that you verified the file integrity of the compressed Raspbian image,
uncompress it using
the following command:
"unzip 20xx-xx-xx-wheezy-raspbian.zip".
You should end up with another file called "20xx-xx-xx-wheezy-raspbian.img".

Copy the Raspbian image to the SD card using the following command:
"dd bs=1M if=20xx-xx-xx-wheezy-raspbian.img of=/dev/sdb".
Make sure that you specify the correct device found using the fdisk command.
This command will take a few minutes to complete.

Once the "dd" command completes, type into the same terminal "sync" to ensure the
write
cache is flushed properly and that you can safely remove the SD card.
Remove your SD card from the card reader and plug it into your RPi.

Putting the RPi with Raspbian OS onto the network


--------------------------------------------------------------------------------

We will connect to the RPi over the network.


This way we can access both our Linux PC and the RPi through a single monitor....no
need to
have multiple monitors and HDMI cables. This can be done in two ways:

*Connect the RPi directly to the network via an Ethernet Switch*


Power your RPi & connect it to your network (via an Ethernet port on an accessible
switch
connected to your home network) using the Ethernet cable.
You should see the LEDs start to come up implying that the Raspbian image has been
successfully
started. Once the green "LNK" LED and the "10M" orange LED light up on the RPi
board,
we can assume that the Raspbian image booted and an IP address has been assigned to
the RPi.
To figure out the IP address assigned to the RPI by the DHCP server running on our
router, we
can use the IP Scanner tool nmap. Install nmap on your Linux PC :"apt-get install
nmap".
Then type
"nmap -sP 192.168.0.2-254".
This command lists all IP addresses that are up on your local network (typically a
192.168.0.0 network).
Find the one that lists "Raspberry Pi Foundation" next to its MAC address (Figure
6).
That is the IP address of the RPi. Keep record of it since we will need it to SSH
into our RPi.

*Share your PC's Internet Connection with the RPi*

If there is an unused Ethernet port on the Linux PC, it can be used to allow the
RPi to share
the network/internet connection that the Linux PC is connected to through another
WiFi /Ethernet port.

To create this network bridge, open the Network Manager application.


This can be done from the task bar and should open the "Edit Connections" dialog
shown in Figure 2.

Figure 2 Edit Connections

Select "Wired Connection 1" and click on the "Edit" button. If you do not have a
wired connection profile,
click the "Add" button.

Figure 3

Change the "Connection name" field to "Raspberry Pi Bridge".


In the "Device MAC address" drop down list, select the MAC address of the unused
Ethernet port
(eth0 in my case). Then go to the IPv4 settings tab and in the "Method" drop down
list, select
"Shared to other computers".

Figure 4.

Under the IPv6 settings tab and in the "Method" drop down list, select "Ignore".
and then press save.
Now Power up the RPi & connect it via Ethernet cable to the unused Ethernet port on
your PC.
Once the green "LNK" LED and the "10M" orange LED light up on the RPi board,
the Raspbian image has booted and an IP address has been assigned to the RPi.

Figure 5.

Now go back to the terminal and type "ifconfig -a".

Figure 6

Note how the IP address on the eth0 interface is now 10.42.0.1.


This implies that the Linux PC is basically acting as a router between the
10.42.0.0 network
( really only a point to point network ) on which the RPi and eth0 are attached,
and the
192.168.0.0 network, which is attached to the internet & PC via the wlan0
interface.
Also note that the mask for the 10.42.0.0 network is 255.255.255.0 .
This means that the IP address of the RPi is somewhere between 10.42.0.2 &
10.42.0.254.
To find the exact address we can use nmap "nmap -sP 10.42.0.2-254".
In my case, nmap reported that the my RPi has an IP address of 10.42.0.73 (Figure
6).
If nmap is not installed, you can easily install it with "apt-get install nmap".

Accessing the Raspberry Pi board remotely via SSH


--------------------------------------------------------------------------------

Now that we know the IP address of the RPi board, we we can login remotely via SSH.
SSH is an encrypted version of telnet (with a few additional goodies) that can give
us command
line access to the RPi over the network. To login into the Raspberry Pi over SSH
we need to type
in our terminal: "ssh 10.42.0.73 -l pi" (or ssh [email protected]). Basically we're
typing the name
of the command "ssh" followed by the IP address of the RPi, followed by the
username.
Remember the default username for the Raspbian Distribution is "pi" and the
password is "raspberry".
Choose yes if asked if this is a safe connection ( first time to ssh into the
RPi).
If all goes well, our terminal window is logged into the RPi.
Any commands that we type into that window from now on will affect the Raspberry Pi
and
not the Linux PC.

Figure 7. Logging into the RPi via SSH and typing "raspi-config"

Configuring your Raspberry Pi over SSH


--------------------------------------------------------------

The next step is to type "raspi-config". (see notice in Figure 7) Once you do this,
the raspi-config tool will run (figure 8).

Figure 8. ncurses based raspi-config tool

From the raspi-config menu, first select "8 Advanced Options" -> "A5 Update" & hit
enter.
This will update the raspi-config tool to the latest version.
The Raspbian image is designed to expand into 2GB space on your SD card.
This means that if you are using a larger SD Card, say 4GB or 8GB, the additional
space is not
part of the root file system partition.

To use all the space on your SD card select "1 Expand Filesystem" and hit enter.
This will expand the root file system partition to fill the entire SD card.
The actual partition expansion will happen on reboot.

The other major option is "8 Advanced Options" -> "A3 Memory split".
Hit "Enter" and then choose an appropriate memory split ratio.
I recommend using 64MB for the GPU, but you can change this depending on what you
are doing.

For the other options, I highly recommend that you explore them.....

I don't recommend overclocking the RPi ( "7 Overclock" option) beyond 800MHz and I
keep the
default for the "8 Advanced Options" -> "A4 SSH" (run SSH server on start up) .

For "3 Enable Boot to Desktop" I always choose to boot into the command line
first.

When you're done, use the right/left arrow keys (or tab key) to select <Finish>.

This will cause the RPi to reboot with all the requested changes.

This reboot might take an additional minute or two if you selected to expand the
root file system
partition. Note that when you reboot, you lose your SSH connection and your console
window will
now be associated with your Linux PC once more.

When the RPi reboots, SSH into it again via "ssh 10.42.0.73 -l pi" as before.

Once at the RPi prompt shown (Figure 7), type "apt-get update" followed by "apt-get
upgrade" or alternatively we can do both at the same time
"apt-get update && apt-get upgrade".
The first command consults the /etc/apt/sources.list and updates the database of
available packages.
The second command checks updates for all installed packages and then prompts to
download and
install them. When it does this accept the updates (type Y) and hit enter.
When the second command completes ,you will have the most up-to-date Raspbian
Linux OS available for the RPi.

-------------------------------------------------------------------------------
Remote login into the Raspberry Pi Using VNC
-------------------------------------------------------------------------------

SSH is great if you want to remotely access the RPi from the command line.
The Raspbian OS also comes with a Desktop GUI environment called LXDE.
If can access the LXDE desktop over HDMI by typing "startx" in the command line
window.

This will not work over SSH. Luckily we can still remotely access the LXDE Desktop
from the Linux PC,
using the VNC protocol.
First we need to install the VNC server software on the the RPi.

To do this, SSH into the Raspberry Pi and type "apt-get install tightvncserver".
This will install the VNC server software on the RPi.

Then type "tightvncserver" to configure the VNC server for the first time.
You will then be asked to enter a password (8 characters only) & confirm it.
I used "raspberr". You will then be prompted to enter an optional "view only
password".

This is not needed and you can choose to not set one by saying no.

the next step is to type the following into the RPi SSH session to start the VNC
server:

"vncserver :1 -geometry 1280x720 -depth 24".

This starts a VNC server on display number 1 with a resolution of 1280 by 720 and a
color depth of 24.

At this point the VNC server should be running on the Raspberry Pi.

Now open another console window on your Linux PC and install a VNC viewer (client)
on the
Linux PC with the command: "apt-get install xtightvncviewer ".

Then in the same console window (Linux PC) type "xtightvncviewer &".

The ampersand allows us the run the application in the background.

This will open the VNC viewer on our Linux PC (a small messagebox...see Figure 9).

Type in the VNC server address that you want to connect to i.e. the RPi IP address
& display
number "10.42.0.73:1".

You will then be prompted to enter your VNC password. Type that in and press enter.
You should see the window shown in Figure 10.

You now have full control over your Raspberry Pi via both the command line with SSH
and the
desktop environment over VNC.

Poi girano i seguenti processi


/usr/bin/vncserver-x11-core -service -pidFile /var/run/vncserver-x11-serviced.pid

/usr/bin/vncagent service 16
Xtightvnc :1 -desktop X -auth /root/.Xauthority -geometry 1024x768 -depth 24 -
rfbwait 120000
-rfbauth /root/.vnc/passwd -rfbport 5901
-fp /usr/share/fonts/X11/misc/,/usr/share/fonts/X11/Type1/,/usr/share/
fonts/X11/75dpi/,/usr/share/fonts/X11/100dpi/
-co /etc/X11/rgb
/bin/sh /root/.vnc/xstartup

La configurazione la trovo sotto; /usr/bin/tightvncserver

================================================================================
AZARTICOLO:Come far partire una sessione LXDE automaticamente dopo che il server
VNC e' salito in modo che sia pronta quando il vnclient si connette ?
================================================================================

I have system which is equipped with Intel Celeron processor 1.1 GHz s370 with 384
Mb of RAM
on Intel d815egew motherboard which supports wake-on-lan function.
I want to use such a PC for Internet sharing to the local network.
Also this PC is a DHCP+DNS server as well as router/gateway.
Based on above I decided to install Lubuntu as it is lightweight system.
I installed Lubuntu 10.04.4 LTS from alternate ISO. System has no auto login.
System boots and has acceptable performance.

Host PC has onboard 4 network adapters:

eth0 – ethernet controller which is used for Local Network connections. Has
static address 10.0.0.1
eth1 – ethernet controller which is not used and not configured so far, I plan
to connect printer here later on.
eth2 - ethernet controller which is used to connect to Internet, which we plan
to share for the local network
wlan0 – wireless controller, it is used in role of access poit for local
Network and has address 10.0.0.2

We want to control our gateway remotely.


So, we need to be able to power it on remotely.

To allow this I’ve done the following things:

cd /etc/init.d/
made a new file with command
vim wakeonlanconfig
Wrote the following lines to the newly created file, saved and closed it

#!/bin/bash
ethtool -s eth0 wol g
ethtool -s eth2 wol g
exit

Made the abovementioned file executable

chmod a+x wakeonlanconfig

Then included it into autostart sequence during boot.

update-rc.d -f wakeonlanconfig defaults

after system reboot we will be able to poweron system remotely.

Than we need to have a possibility to connect remotely to the host via SSH and VNC.
So, I installed following packets with the following commands:

apt-get update
apt-get install openssh-server tightvncserver

Add ssh daemon into autostart sequence during boot.


update-rc.d -f ssh defaults
Power off the host PC

halt
Then I went to remote place, send magic paket and powered the Host up. System
started...
And I connected to the host via Putty from remote system under Windows.
Than logged in and run the command to start vnc server.

tightvncserver -geometry 800x600 -depth 16 :2

VNC server successfully started and I got message like follows.

New 'X' desktop is gateway:2

Starting applications specified in


/root/.vnc/xstartup

Log file is

/root/.vnc/gateway:2.log

Using UltraVNC Viewer programm under windows I connected to the host's vnc server,
enterd the
password and.... sow only mouse cursor in form of cross on a grey background of
800x600 dots,
no desktop.

Here is my .vnc/xstartup file

#!/bin/sh

xrdb $HOME/.Xresources
xsetroot -solid grey
#x-terminal-emulator -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &
#x-window-manager &
# Fix to make GNOME work
export XKL_XMODMAP_DISABLE=1
/etc/X11/Xsession

The Question:
---------------------

What I have to change and where to make LXDE session start automatically after
tightvncserver
starts?

In your .vnc/xstartup file, replace /etc/X11/Xsession with

/usr/bin/startlxde

I looked in /usr/share/xsessions/LXDE.desktop to see what it did.


You can see how to start any of the session types in /usr/share/xsessions by
looking
in the desktop files.

In my ~/.vnc/xstartup file, I replaced /etc/X11/Xsession with


/usr/bin/startlubuntu.

But now the fallowin issue has arisen:


I started tigntvnc server on display :
2 and when I try to run Chromium browser via vnc client it starts on the
display :0.

How to cure this?

The solution is mentiond in a launchpad Bug #1241958,


which is to use lxsession -e LXDE -s Lubuntu instead of /etc/X11/Xsession.

I think if you install Lubuntu as the OS, then you get a slightly different
configuration than if you
installed lxde-desktop onto Ubuntu. In the first case /usr/bin/startlubuntu is
present,
in the second case likely /usr/bin/startlxde.

In Lubuntu 13.04, my ~/.vnc/xstartup looked like that shown earlier,and gives the
grey screen
with old-fashioned cursor - this indicates that the virtual desktop has been
created,
but there's nothing on the desktop.

Making the edit to remove /etc/X11/Xsession and insert /usr/bin/startlubuntu, and


restarting
tightserver, still gives the same thing.

Then adding the line:


lxpanel --profile Lubuntu

and restarting tightserver, gives the panel on the desktop, from which you can
launch apps.
Unfortunately these app windows are not rendered with a title bar or borders, and
no taskbar
button. A number of icons are different too.

I'm still groping my way towards a solution.

Why doesn't tightvncserver install as a service automatically in the first place ?


I mean, what use is a server that doesn't start up on boot?
I dare say there are a lot of installation variables for the package maintainers to
consider,
but rather them than people like me, who don't understand ANY of this stuff.

================================================================================
AZARTICOLO:Installare il VNC server.
================================================================================

Launch vncserver for the first time to set up a password.


Add the following file as /etc/init.d/vncserver (be sure to modify the USER,
GEOMETRY, NAME, etc. to your liking).
chmod +x /etc/init.d/vncserver
update-rc.d vncserver defaults

/etc/init.d/vncserver

#!/bin/sh -e
### BEGIN INIT INFO
# Provides: vncserver
# Required-Start: networking
# Default-Start: S
# Default-Stop: 0 6
### END INIT INFO
PATH="$PATH:/usr/X11R6/bin/"

# The Username:Group that will run VNC


export USER="mythtv"
#${RUNAS}

# The display that VNC will use


DISPLAY="1"

# Color depth (between 8 and 32)


DEPTH="16"

# The Desktop geometry to use.


#GEOMETRY="<WIDTH>x<HEIGHT>"
#GEOMETRY="800x600"
GEOMETRY="1024x768"
#GEOMETRY="1280x1024"

# The name that the VNC Desktop will have.


NAME="my-vnc-server"

OPTIONS="-name ${NAME} -depth ${DEPTH} -geometry ${GEOMETRY} :${DISPLAY}"

. /lib/lsb/init-functions

case "$1" in
start)
log_action_begin_msg "Starting vncserver for user '${USER}' on localhost:$
{DISPLAY}"
su ${USER} -c "/usr/bin/vncserver ${OPTIONS}"
;;

stop)
log_action_begin_msg "Stoping vncserver for user '${USER}' on localhost:${DISPLAY}"
su ${USER} -c "/usr/bin/vncserver -kill :${DISPLAY}"
;;

restart)
$0 stop
$0 start
;;
esac

exit 0

shareimprove this answer

Abilitazione allo startup:

systemctl enable vncserver.service

--------------------------------------------------------------------------------
root@azlampone:/etc/init.d# cat /etc/init.d/vncserver
--------------------------------------------------------------------------------

#!/bin/sh -e
### BEGIN INIT INFO
# Provides: vncserver
# Required-Start: networking
# Default-Start: S
# Default-Stop: 0 6
### END INIT INFO

PATH="$PATH:/usr/X11R6/bin/"

# The Username:Group that will run VNC


export USER="root"
#${RUNAS}

# The display that VNC will use


DISPLAY="1"

# Color depth (between 8 and 32)


DEPTH="24"

# The Desktop geometry to use.


#GEOMETRY="<WIDTH>x<HEIGHT>"
#GEOMETRY="800x600"
#GEOMETRY="1024x768"
GEOMETRY="1280x1024"

# The name that the VNC Desktop will have.


NAME="azlampone-vnc-server"

OPTIONS="-name ${NAME} -depth ${DEPTH} -geometry ${GEOMETRY} :${DISPLAY}"

. /lib/lsb/init-functions

case "$1" in
start)
log_action_begin_msg "Starting vncserver for user '${USER}' on localhost:$
{DISPLAY}"
su ${USER} -c "/usr/bin/vncserver ${OPTIONS}"
;;

stop)
log_action_begin_msg "Stoping vncserver for user '${USER}' on localhost:${DISPLAY}"
su ${USER} -c "/usr/bin/vncserver -kill :${DISPLAY}"
;;

restart)
$0 stop
$0 start
;;
esac

exit 0

---------------------------------------------------------------------------------
insserv: warning: script 'mathkernel' missing LSB tags and overrides
---------------------------------------------------------------------------------

I'm trying to run: update-rc.d avahi-daemon defaults


But i get the error: insserv: warning: script 'mathkernel' missing LSB tags and
overrides

If look at the /etc/init.d/skeleton script, in the beginning of it there are two


marks :
### BEGIN INIT INFO and ### END INIT INFO.

================================================================================
VNC Connect and Raspberry Pi (NUOVO)
================================================================================
https://www.realvnc.com/en/connect/docs/raspberry-pi.html

Premessa
--------------

Sometimes it is not convenient to work directly on the Raspberry Pi.


Maybe you would like to work on it from another device by remote control.

VNC is a graphical desktop sharing system that allows you to remotely control the
desktop
interface of one computer (running VNC Server) from another computer or mobile
device
(running VNC Viewer).

VNC Viewer transmits the keyboard and either mouse or touch events to VNC Server,
and
receives updates to the screen in return.

You will see the desktop of the Raspberry Pi inside a window on your computer or
mobile
device. You'll be able to control it as though you were working on the Raspberry Pi
itself.

Pi Desktop as seen from a mobile device

VNC Connect from RealVNC is included with Raspbian.

It consists of both VNC Server, which allows you to control your Raspberry Pi
remotely,
and VNC Viewer, which allows you to control desktop computers remotely from your
Raspberry Pi should you want to.

You must enable VNC Server before you can use it: instructions for this are given
below.
By default, VNC Server gives you remote access to the graphical desktop that is
running
on your Raspberry Pi, as though you were sitting in front of it.

However, you can also use VNC Server to gain graphical remote access to your
Raspberry Pi
if it is headless or not running a graphical desktop.

For more information on this, see Creating a virtual desktop, further below.

RealVNC have ported their VNC server and viewer applications to Pi, and they are
now integrated
with the system. To enable the server, select the option on the Interfaces tab in
Raspberry Pi
Configuration; you’ll see the VNC menu appear on the taskbar, and you can then log
in to your Pi
and control it remotely from a VNC viewer.

The RealVNC viewer is also included – you can find it from the Internet section of
the
Applications menu – and it allows you to control other RealVNC clients, including
other Pis.

Have a look here on RealVNC’s site for more information.

Please note that if you already use xrdp to remotely access your Pi, this conflicts
with the
RealVNC server, so you shouldn’t install both at once.

If you’re updating an existing image, don’t run the apt-get install realvnc-vnc-
server line
in the instructions below. If you want to use xrdp on a clean image, first
uninstall the
RealVNC server with apt-get purge realvnc-vnc-server before installing xrdp.

(If the above paragraph means nothing to you, then you probably aren’t using xrdp,
so you don’t have to worry about any of it!)

Also included is the new SenseHAT emulator, which was described in a blog post a
couple of weeks ago;
have a look here for all the details.

From the September 2016 version of Raspbian, VNC Server is built-in to the
Raspberry Pi,
licensed for non-commercial use and ready to use.

If you are using an earlier version of Raspbian or a different distribution, you


can manually
install VNC Server.

Getting connected to your Raspberry Pi


----------------------------------------------------------

If you have Raspbian Jessie with PIXEL, VNC Connect is included with your Raspberry
Pi.
It’s completely free for non-commercial use.

VNC Connect consists of two apps, VNC Server and VNC Viewer:

VNC Server enables you to connect to your Pi from a desktop computer or mobile
device,
watch its screen in real-time, and exercise control as though you were
sitting in front
of it.

VNC Viewer enables you to connect to and control a desktop computer (or another Pi)
from your Pi, should you want to.

If you have an earlier version of Raspbian, or a different Linux distribution, you


can install
VNC Connect yourself.

Setting up your Raspberry Pi


------------------------------------------

VNC Connect is included with Raspbian but you still have to enable it.

First, run the following commands to make sure you have the latest version of VNC
Server
and VNC Viewer:

apt-get update
apt-get install realvnc-vnc-server
apt-get install realvnc-vnc-viewer

If you’re already using an older version of VNC Server, restart it.

Enabling VNC Server graphically


------------------------------------------------

On your Raspberry Pi, boot into the graphical desktop.

Select Menu > Preferences > Raspberry Pi Configuration > Interfaces.


Ensure VNC is Enabled.

Enabling VNC Server at the command line


--------------------------------------------------------------

You can enable VNC Server at the command line using raspi-config:

raspi-config

Now, enable VNC Server by doing the following:

Navigate to Interfacing Options.


Scroll down and select VNC > Yes.

From now on, VNC Server will start automatically every time you boot your Raspberry
Pi. S

See how to stop VNC Server.

By default, VNC Server remotes the graphical desktop running on your Raspberry Pi.
However, if your Pi is headless (not plugged into a monitor) or not running a
graphical desktop,
VNC Server can still give you graphical remote access using a virtual desktop.

If you intend to run your Pi headless, additional configuration is required.


You may choose to create a virtual desktop in this case.

Getting connected to your Raspberry Pi


----------------------------------------------------------

There are two ways to connect; you can use either or both.
Please make sure you’ve downloaded our VNC Viewer app to computers or devices you
want to control from.

Establishing a direct connection


-------------------------------------------------

Direct connections are quick and simple providing you’re joined to the same private
local
network as your Raspberry Pi (for example, a wired or Wi-Fi network at home, school
or in the office).

If you’re connecting over the Internet, it’s much safer and more convenient to
establish
a cloud connection.

On your Raspberry Pi, discover its private IP address by double-clicking the VNC
Server
icon on the taskbar and examining the status dialog:

oppure semplicemente digitando ifconfig

On the device you'll use to take control, download VNC Viewer.

For best results, use the compatible app from RealVNC.

https://www.realvnc.com/en/connect/download/viewer/

On the device you will use to take control, run VNC Viewer and enter the IP address
in the search bar

Establishing a cloud connection


-----------------------------------------------

Cloud connections are convenient and encrypted end-to-end, and highly recommended
for connections over the Internet. There’s no firewall or router reconfiguration,
and you
don’t need to know the IP address of your Raspberry Pi, or provide a static one.

You’ll need a RealVNC account; it’s completely free to set up and only takes a few
seconds.
We’ll give you a special version of our Home subscription that enables both cloud
and direct
connectivity, and also in-session features such as system authentication, file
transfer, printing and chat.

You can apply your Home subscription to five Raspberry Pis and/or desktop computers
in total.
Please note you revert to the standard feature set for Windows, Mac and Linux
desktop computers.

Sign up for a RealVNC account by entering your email address in the box on this
page,
and following the instructions.

On your Raspberry Pi, select Licensing from the VNC Server status menu, choose
Sign in to your RealVNC account, and enter your new account email and password:

On the device you will use to take control, run VNC Viewer and sign in using the
same
account credentials.

In VNC Viewer, a connection to your Raspberry Pi automatically appears under the


name
of your team. Simply tap or double-click to connect:

Authenticating to VNC Server


--------------------------------------------

To complete either a direct or cloud connection you must authenticate to VNC


Server.
Enter the user name and password you normally use to log on to your user account on
the Raspberry Pi.
By default, these credentials are pi and raspberry, but hopefully you’ll have
changed them
to something more secure by now!

To complete either a direct or cloud connection, you must authenticate to VNC


Server.

If you're connecting from the compatible VNC Viewer app from RealVNC, enter the
user
name and password you normally use to log in to your user account on the Raspberry
Pi.
By default, these credentials are pi and raspberry.

If you're connecting from a non-RealVNC Viewer app, you'll first need to downgrade
VNC Server's authentication scheme, specify a password unique to VNC Server, and
then
enter that instead.

If you are in front of your Raspberry Pi and can see its screen, open the VNC
Server dialog
on your Raspberry Pi, select Menu > Options > Security, and choose VNC password
from
the Authentication dropdown.

Or if you're configuring your Raspberry Pi remotely from the command line, then to
make
the changes for Service Mode (the default configuration for the Raspberry Pi):

Open the /root/.vnc/config.d/vncserver-x11 config file.

Replace Authentication=SystemAuth with Authentication=VncAuth and save the file.


In the command line, run vncpasswd -service. This will prompt you to set a
password,
and will insert it for you in the right config file for VNC Server running in
Service Mode.

Restart VNC Server.

Playing Minecraft and other directly rendered apps remotely


-----------------------------------------------------------------------------------
------

VNC Server can remote the screen of Raspberry Pi apps that use a directly rendered
overlay,
such as Minecraft, the text console, the Pi camera module, and more.

You can remotely access apps which use a directly rendered overlay, such as
Minecraft,
the text console, the Raspberry Pi Camera Module, and more.

To turn this feature on:

On your Raspberry Pi, open the VNC Server dialog.

Navigate to Menu > Options > Troubleshooting and select


Enable experimental direct capture mode.

On the device you'll use to take control, run VNC Viewer and connect.
Note: existing connections must be restarted in order for these changes to take
effect.

Please note that direct screen capture is an experimental feature.


If you're connecting from a desktop computer and mouse movements seem erratic,
try pressing F8 to open the VNC Viewer shortcut menu and selecting Relative Pointer
Motion.

If performance seems impaired, try:

- On your Raspberry Pi, run raspi-config,


navigate to Advanced options > Memory Split, and ensure your GPU has at least
128MB.

- Reduce your Raspberry Pi’s screen resolution.

If you still encounter problems, please let us know.

Transferring files and printing remotely


-----------------------------------------------------------

You can transfer files to and from your Raspberry Pi providing you’re connecting
from
VNC Viewer running on a Windows, Mac or Linux desktop computer.

To transfer files to your Raspberry Pi, click the VNC Viewer toolbar button and
follow the
instructions. Detailed steps are here.

To transfer files from your Raspberry Pi, use VNC Viewer to open the VNC Server
dialog
remotely, select Menu > File transfer, and follow the instructions.

Detailed steps are here.


https://www.realvnc.com/en/connect/docs/file-transfer.html#file-transfer-from

It can be really useful to print to a printer attached to your Windows, Mac or


Linux
computer if no printer is set up for your Raspberry Pi. To do this, first run the
following
command on your Raspberry Pi to install cups (the Common Unix Printing System):

apt-get install cups

Then, use VNC Viewer to select File > Print remotely (or whatever the standard
command
is for the page or file you want to print). VNC Server directs the output to VNC
Viewer, and
spools it to your local printer. There’s more information about remote printing
here.

https://www.realvnc.com/en/connect/docs/printing.html#printing

Creating and remoting a virtual desktop


------------------------------------------------------------

If your Raspberry Pi is headless (that is, not plugged into a monitor) or embedded
in a robot,
it’s unlikely to be running a graphical desktop.

VNC Server can run in Virtual Mode to create a resource-efficient virtual desktop
on demand,
giving you graphical remote access even when there is no actual desktop to remote.
This virtual desktop exists only in your Raspberry Pi’s memory:

To do this:

On your Raspberry Pi, run the command vncserver.


Make a note of the IP address/display number printed to the console, for example
192.167.5.149:1.
On the device you will use to take control, enter this information in VNC Viewer.

A) Prima del lancio abbiamo:

4 S root /usr/bin/vncserver-x11-serviced -fg


4 S root /usr/bin/vncserver-x11-core -service

B) Lanciamo:

# vncserver

VNC(R) Server 6.2.0 (r29523) ARMv6 (Aug 3 2017 18:32:53)


Copyright (C) 2002-2017 RealVNC Ltd.

On some distributions (in particular Red Hat), you may get a better experience by
running vncserver-virtual in conjunction with the system Xorg server, rather
than the old version built-in to Xvnc.
More desktop environments and applications will likely be compatible.

For more information on this alternative implementation, please see:


https://www.realvnc.com/doclink/kb-546

Running applications in /root/.vnc/xstartup

VNC Server catchphrase: "Galileo money fiesta. Judge audio Jamaica."


signature: 98-1c-cc-2a-2a-9b-ab-90

Log file is /root/.vnc/raspi:1.log

New desktop is raspi:1 (192.168.1.5:1)

C) Dopo il lancio abbiamo la seguente situazione:

I vecchi processi:

4 S root /usr/bin/vncserver-x11-serviced -fg


4 S root /usr/bin/vncserver-x11-core -service

ed i l nuovo virtual server con la sessione X


1 S root vncserver
4 S root /usr/bin/Xvnc-core :1 -auth /root/.Xauthority -pn
-fp
/usr/share/fonts/X11/misc,

/usr/share/fonts/X11/100dpi/:unscaled,

/usr/share/fonts/X11/Type1,
/usr/share/fonts/X11/100dpi,built-ins
0 S root /bin/sh /root/.vnc/xstartup
4 S root /usr/bin/vncserverui virtual 14
0 S root /usr/bin/vncserverui -statusicon 6

Ovvero ha startato una sessione indipendente del vecchio Xvnc ed ha eseguito la


nostra
perwonalizzazione:

xrdb $HOME/.Xresources
xsetroot -solid grey
export XKL_XMODMAP_DISABLE=1
/etc/X11/Xsession

Stopping a virtual desktop


---------------------------------------

A virtual desktop persists until you explicitly destroy it. Run the following
command
when you are sure it is no longer needed:

vncserver -kill :<display-number>

Note this command will terminate any current connections without warning to those
users.

Dopo il kill i processi vnc tornano ad essere i soliti 2

Operating VNC Server at the command line


---------------------------------------------------------------

You can operate VNC Server exclusively at the command line or via SSH if you
prefer.

Common commands for Raspbian Jessie (which is based on Debian 8, and uses systemd)
are:

To start VNC Server now: systemctl start vncserver-x11-serviced.service

To start VNC Server at next boot, and every subsequent boot:


systemctl
enable vncserver-x11-serviced.service

To stop VNC Server: systemctl stop vncserver-x11-


serviced.service

To prevent VNC Server starting at boot:


systemctl
disable vncserver-x11-serviced.service

Troubleshooting VNC Server


-------------------------------------------

Changing the Raspberry Pi’s screen resolution

You may want to do this if:

Performance is impaired. A smaller screen resolution gives a more responsive


experience.
Your Raspberry Pi is headless (that is, not plugged into a monitor) and the default
initial
screen resolution is too small.

To change the resolution, run the command


raspi-config, navigate to Advanced Options > Resolution, and choose an option.

If this menu is not available, or you want more control, specify settings in the
/boot/config.txt file:

Setting Value Explanation

hdmi_force_hotplug 1 Tells your Pi an HDMI display is attached.


hdmi_ignore_edid 0xa5000080 Ignores EDID/display data.
hdmi_group 2 Defines the HDMI output group.
hdmi_mode 16 Forces (for example) 1024x768 at 60Hz.

See the Raspberry Pi documentation for more hdmi_mode options, and information on
/boot/config.txt in general. You will need to reboot your Raspberry Pi for any
changes to
take effect.

Note that settings you specify in this file override monitors you subsequently plug
in
(unless you revert hdmi_force_hotplug), so pick a ‘headless’ resolution compatible
with
your regular monitor.

Specifying a screen resolution for a virtual desktop


---------------------------------------------------------------------------

If you run VNC Server in Virtual Mode to create a virtual desktop, you can specify
the
screen resolution (geometry) at start up, for example:

vncserver -randr=1366x768

You can even specify multiple screen resolutions and cycle between them.

Optimizing for Raspberry Pi Zero and Pi 1


------------------------------------------------------------

If performance is impaired for direct connections to a Raspberry Pi Zero or Pi 1,


try turning
off encryption if you are sure your private local network is secure. This reduces
CPU usage.

You cannot turn off encryption for cloud connections.

On your Raspberry Pi, open the VNC Server dialog and select Menu > Options >
Expert.
Change the Encryption parameter to AlwaysOff.
Restart any existing connections.

If performance is still impaired, try reducing your Raspberry Pi’s screen


resolution.

================================================================================
AZARTICOLO: RealVNC : How do I use VNC Server in Virtual Mode
in conjunction with
the latest Xorg server?
================================================================================

By default under Linux, VNC Server in Virtual Mode uses a version of the Xorg
server built-in to Xvnc.
This is old, and hard to update.

On some platforms, modern desktop environments fail to load (resulting in a grey


screen),
and modern applications and extensions (particularly those using hardware
acceleration)
do not work.

From VNC Connect 6.2.0, you can configure VNC Server to utilise the latest version
of the
Xorg server present on your system instead. More desktop environments, applications
and extensions will likely be compatible out-of-the-box, giving a much better user
experience, especially on Red Hat-compatible distributions.

Note: If you are using Ubuntu, SUSE or Raspbian, you should continue to use Xvnc.

This means that under Ubuntu and SUSE you will still need to switch desktop
environment
in order to avoid the grey screen. There's no issue under Raspbian, however, as the
default
PIXEL desktop environment works well with Xvnc.

Requirements
---------------------

Xorg and the Xorg dummy video driver must be installed. For example:

Red Hat/CentOS 7: yum install xorg-x11-drv-dummy


Red Hat/CentOS 6: yum install xorg-x11-drv-dummy xorg-x11-drv-void

In addition, VNC Connect 6.2.0+ must be installed and licensed. Download.


Enabling the system Xorg server

To enable the system Xorg server for all users, run vncinitconfig -enable-system-
xorg as root.
Run without root privileges to enable just for you.

To disable the system Xorg server and use Xvnc again, run vncinitconfig -disable-
system-xorg.

Configuring VNC Server


----------------------------------

VNC Server parameters


-----------------------------------

VNC Server parameters can be specified in the following new configuration files:

/etc/vnc/config.d/vncserver-x11-virtual (for all users)


~/.vnc/config.d/vncserver-x11-virtual (just for you)

Note that the vncinitconfig -enable-system-xorg script offers to copy over existing
parameters
from /etc/vnc/config.d/Xvnc and ~/.vnc/config.d/Xvnc respectively for you.

Note: The RandR VNC Server parameter cannot enable users to switch between
available
screen resolutions. See Xorg configuration, below.

Xorg options
--------------------

Xorg server options can continue to be set in the following files:

/etc/vnc/config
/etc/vnc/config.custom
~/.vnc/config (ignored if the -config flag is used, below)

...or in a custom file identified by the vncserver-virtual -config FILE-PATH flag


at start-up.

These options are passed directly to the system Xorg server. Consult the Xorg man
page
for a list of valid options; invalid options cause errors.
Note that the following options supported by Xvnc are not supported:
-blackpixel, -whitepixel, -linebias, -pixdepths, -pixelformat, -screen.

Geometry and depth


-------------------------------

You can specify the -geometry WxH and -depth N options in any of the locations
specified
in Xorg options, above, or appended to vncserver-virtual at the command line.
By default, the initial geometry must be a standard resolution
(for example, 640x480, 800x600 or 1024x768); see Xorg configuration, below, for
specifying
non-standard resolutions. Consult the Xorg man page and your chosen desktop
environment
for supported depth values.

Xorg configuration
----------------------------

Custom Xorg settings can be specified in the new /etc/X11/vncserver-virtual.conf


file.
In particular, you can set non-standard screen resolutions by adding additional
ModeLine
entries to the Monitor section. For larger resolutions, you may also need to change
the
VideoRam entry in the Device section and add a Virtual entry under the Display
subsection
of the Screen section; see the Xorg.conf man page for more information.

Note the VNC Server RandR parameter cannot be used to enable a connected VNC Viewer
user to cycle between available screen resolutions during a remote control session.
The connected user should use the standard Screen Display or Monitor app instead.

Xstartup
------------
Xstartup scripts can continue to be used to specify desktop environments and
applications
for virtual desktops in the same way as for Xvnc.

Installing from a network share


------------------------------------------------

If you're following these instructions to install VNC Server on a central computer,


then perform the following operation after step 5 and before step 6:

5a) Run the command vncinitconfig -virtual-xorg-conf as root to generate a


/etc/X11/vncserver-virtual.conf file.

Known issues
----------------------

When using the Xfce or KDE desktop environments, some fonts may appear small,
depending
on the screen resolution.

To fix this for Xfce, navigate to Applications > Settings > Appearance and enable
Custom DPI
setting on the Fonts tab, making sure this is set to 96.

To fix this for KDE, navigate to System Settings > Application Appearance and
enable
Force fonts DPI on the Fonts tab, making sure this is set to 96.
================================================================================
Secure your connection
realjjaveweb edited this page on Mar 18, 2022 · 19 revisions
Pages 12
Find a page…
Home
Compiling TigerVNC for Windows
Debug Logs
Development
Development: DesktopSize
Development: Latency
Development: Making a Release
Development: SetDesktopSize Cleanup
Keyboard shortcuts
Secure your connection
What is a X.509 certificate?
Certificate from an External Certificate Authority
Create a self-signed certificate
Windows
Linux
Manage the certificates
Use the certificate with TigerVNC
Setup TigerVNC server (Windows)
Systemd unit for x0vncserver
Clone this wiki locally
https://github.com/TigerVNC/tigervnc.wiki.git
What is a X.509 certificate?
"X.509" is a standard type of certificate commonly used for websites. However, they
are also useful for securing TigerVNC.

Certificates allow two important security functions.

Certificates prove the identity of the computer you are viewing (the one with the
TigerVNC server).
Certificates keep private the contents of the communication between you and the
remote computer.
When it comes to obtaining a certificate, you can use an External Certificate
Authority if you own a domain name, or create a self-signed certificate.

Certificate from an External Certificate Authority


External Certificate Authorities issue certificates for public domain names but not
local network IP addresses. As a result you need to own a domain name (like
example.com). The basic setup would be something like the following.

If your public website is example.com, rename your local network to something like
local.example.com
Obtain a certificate for computer1.local.example.com. Assuming computer1 is not
available to the public internet, you need to use a DNS-01 challenge. (If you are
using Let's Encrypt, see https://letsencrypt.org/docs/challenge-types/#dns-01-
challenge)
When you want to connect to computer1 on your network, type the hostname as
computer1.local.example.com
Note: External Certificate Authorities have certificate transparency requirements
that post the details of every certificate publicly. So don't name your computers
after any secret company projects.

Once you obtain your certificate, see Use the certificate with TigerVNC

Create a self-signed certificate


If you do not own a domain name, or prefer not to use an external certificate
authority, you can create a self-signed certificate.

Creating a certificate differs a little depending on whether you are on Windows or


Linux. Jump to the heading that matches your system.

Windows
Unfortunately TigerVNC doesn't understand Windows-style certificates saved in the
Windows certificate store or that end with the file extension .pfx. However, you
can download OpenSSL to do the job.

On the computer with the TigerVNC server:

Find out the local IP address of the computer running the TigerVNC server. See
LifeHacker's instructions.
Visit
http://wiki.overbyte.eu/wiki/index.php/ICS_Download#Download_OpenSSL_Binaries_.28re
quired_for_SSL-enabled_components.29 (Of the binaries suggested by OpenSSL, this is
the simplest to run.)
Choose the latest .zip download that matches your computer system (probably the
first one labeled "Win-64")
Uncompress the zip file.
Go to the uncompress folder and double click openssl.exe.
If you have Windows Defender SmartScreen, you may have to choose More info > Run
anyway.
Type the following (replace both instances of "192.168.1.5" with the local IP
address you found in step 1 above) req -x509 -newkey rsa -days 365 -nodes -config
openssl.cnf -keyout vnc-server-private.pem -out vnc-server.pem -subj
'/CN=192.168.1.5' -addext "subjectAltName=IP:192.168.1.5"
Linux
Find out the local IP address of the computer running the TigerVNC server. See
Stackoverflow instructions.
Open Terminal (if you haven't already)
Install OpenSSL
On RedHat/CentOS/Fedora, type: sudo yum install openssl
On Debian/Ubuntu, type: sudo apt-get install openssl
Create a self-signed certificate. Type the following (replace both instances of
"192.168.1.5" with the local IP address you found in step 1 above) openssl req -
x509 -newkey rsa -days 365 -nodes -config openssl.cnf -keyout vnc-server-
private.pem -out vnc-server.pem -subj '/CN=192.168.1.5' -addext
"subjectAltName=IP:192.168.1.5"
On Ubuntu (and related distros), you may also need to change the path to
openssl.cnf to /usr/lib/ssl/openssl.cnf

Manage the certificates


The private key should remain private to your computer. If you have syncing
services (such as OneDrive, Dropbox, etc.), consider moving "vnc-server-
private.pem" to a location that isn't synced or backed up. If you ever loose the
private key, just create a new certificate and private key.

The certificate you created expires in 365 days. A year from now, you will need to
go through these steps again and create a new certificate.

Use the certificate with TigerVNC


On the computer with TigerVNC server:

Right click the TigerVNC icon in the system tray (bottom right in Windows) and
choose Options
Under "Session encryption" choose TLS with X.509 certificates, and uncheck None and
Anonymous TLS.
Choose Load X.509 Certificate. Browse to the public key file you saved above ("vnc-
server.pem").
Choose Load X.509 Certificate key. Browse to the private key file you saved above
("vnc-server-private.pem").
Choose Apply
Copy the public key file ("vnc-server.pem") to your remote computer. Save it in the
same folder as the TigerVNC viewer. This avoids some problems with the TigerVNC
viewer on Windows.
On the remote (client) computer:

Open the TigerVNC viewer


Type in the name or IP address of the computer you want to connect to.
Choose Options...
Choose the Security tab
Under Path to X509 CA certificate type the name of the your public key file you
just copied (e.g. "vnc-server.pem"). If you are on Windows, this file needs to be
located in the same folder as the viewer. Note: If you really want it in a
different folder, you can use Linux-style path names, except the path name can't
include spaces (and quotes around the path name don't work either).
Type the password and choose OK. If you get any error messages at this point, read
them carefully. If you skip over any error messages, you may bypass all the
security guarantees of using certificates.
On the computer with TigerVNC server you may have to choose Accept within 10
seconds. You can change this setting if needed.

================================================================================
AZARTICOLO: REALIZZAZIONE RETE
================================================================================
Tolto NetworManager connman wicd

Startup cavo scollegato:

~# ifconfig
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
loop txqueuelen 1 (Local Loopback)
RX packets 40 bytes 4751 (4.6 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 40 bytes 4751 (4.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500


inet 192.168.1.7 netmask 255.255.255.0 broadcast 192.168.1.255
ether b8:27:eb:72:dd:6c txqueuelen 1000 (Ethernet)
RX packets 940 bytes 96103 (93.8 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 853 bytes 130628 (127.5 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

-----------------------------------------------------------------------------------
-----------------------------------------------
root@raspi:/etc/network# cat interfaces
-----------------------------------------------------------------------------------
-----------------------------------------------
# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd


# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:


source-directory /etc/network/interfaces.d

#AZPATCH
auto lo wlan0
iface lo inet loopback

#allow-hotplug eth0
iface eth0 inet static
address 192.168.1.5
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
metric 1
#up route add default gw 192.168.1.1 metric 1 dev eth0
dns-nameservers 192.168.1.1 8.8.4.4

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface azcam inet static
address 192.168.1.7
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
wireless-power off
metric 2
#up route add default gw 192.168.1.1 metric 2 dev wlan0
#down route del default gw 192.168.1.1 metric 2 dev wlan0

dns-domain homenet.telecomitalia.it
dns-nameservers 192.168.1.1 8.8.8.8
iface default inet dhcp
-----------------------------------------------------------------------------------
-----------------------------------------------
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
-----------------------------------------------------------------------------------
-----------------------------------------------
update_config=1
country=IT

network={
ssid="CISCOWIFI"
psk="intrapam123$"
proto=WPA
key_mgmt=WPA-PSK
pairwise=TKIP
auth_alg=OPEN
id_str="azcam"
}
-----------------------------------------------------------------------------------
-----------------------------------------------

N.B. Se attacco il cavo non accade nulla !


Ma appena riconfiguro ifplugd sconnette la wlan0 e collega eth0
Alla risalita a cavo staccato sono abilitate ambedue le interfaccie anche se non ho
utilizzato la sua configurazione , e eth0 e' scollegato e wlan0 e' collegato

eth0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500


ether b8:27:eb:27:88:39 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500


inet 192.168.1.7 netmask 255.255.255.0 broadcast 192.168.1.255
ether b8:27:eb:72:dd:6c txqueuelen 1000 (Ethernet)
RX packets 268 bytes 32742 (31.9 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 306 bytes 42317 (41.3 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

ip link
----------

: eth0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN


mode DEFAULT group default qlen 1000
link/ether b8:27:eb:27:88:39 brd ff:ff:ff:ff:ff:ff

3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode


DORMANT group default qlen 1000
link/ether b8:27:eb:72:dd:6c brd ff:ff:ff:ff:ff:ff

ma dopo 5 min muore per cui occorre risolvere il problema del wifi poweroff

===================================================================================
========
AZARTICOLO Wireless and eth0 Static IP on Raspberry PI with Wi-Pi
===================================================================================
========

I just received my Raspberry PI and had a few problems configuring the static IP on
the
wireless connection. I use the Wi-Pi official WLAN USB module and I really need to
use
the Raspbery PI without any cables attached (except for the power suppy).

It is quite easy after you know how to do it, so here are the steps that will help
you
understand how to configure your Raspberry PI to use manual (static) IP and so get
rid of
the problem of having a new IP every time you reboot it.

First time you’ll have to connect to ssh, login and then use the following
commands:

1 – ifconfig – it will show you the network interfaces

raspberry pi ifconfig

2 – vi /etc/wpa_supplicant/wpa_supplicant.conf

– this second command will allow you to edit the wpa_supplicant.conf file

wpa_supplicant.conf
-------------------

You must change the text “home” in the ssid line with the one that you have
configured
on your wireless router, then change the password too.
The most important thing is to add the last line:

id_str="acasa"

This will be your WLAN id from now on (you may change its name to a different one,
I used acasa in my case).

After you finished editing the file press CTRL + O and then Enter to write your
code to the file then press CTRL + X to exit.

3 – vi /etc/network/interfaces

this is the third command and will show you the content of the interfaces
file where
you need to add the following text (edit the IP, gateway and netmask as you
desire)

auto lo
auto eth0

iface lo inet loopback


iface eth0 inet static
address 192.168.0.108
gateway 192.168.0.1
netmask 255.255.255.0

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface acasa inet static
address 192.168.0.104
netmask 255.255.255.0
gateway 192.168.0.1

iface default inet dhcp

raspberry pi interfaces

After you finished editing the file press CTRL + O and then Enter to write your
code to the f
ile then press CTRL + X to exit.

4 /etc/init.d/networking restart
– this is the last command and will restart your network.
If by bad luck your wi-fi connection doesn’t start up then use this command ifup
wlan0

raspberry pi Wi-Pi USB module

As you can see in the picture above the USB module is ON and if you succeeded too
then
you can enjoy the freedom of the wireless connection on your Raspberry Pi.

===================================================================================
=========
AZARTICOLO:BridgeNetworkConnectionsProxyArp
===================================================================================
=========

Translation(s): English

Bridging Network Connections with Proxy ARP

Indice

Bridging Network Connections with Proxy ARP


Introduction
Summary
DHCP Relay
Automating the Process
Installing the software
Known Issue with RTL8188CUS USB Wifi Adapter

Introduction
-------------------

This document describes a means to bridge IP traffic between two interfaces using
Proxy ARP, /32 host routes and standard Linux routing/forwarding.
For a Layer 2 solution - an ethernet bridge - refer to BridgeNetworkConnections.

The benefit of using an IP / Layer 3 solution is that it will work when the
outward-facing
interface is a wireless ethernet client, without using WDS and without resorting to
NAT.
Simple Layer 2 bridging does not work in this case due to the vagaries of wireless
AP
client behaviour; WDS may help but AP support can be patchy.
Using Proxy ARP permits the bridged clients to be part of the existing network and
supports bidirectional traffic, e.g. for a server or printer.
DHCP and mDNS will also work using the appropriate helpers.

One scenario is connecting a wired network to a wireless LAN using a host that has
both
wifi (wlan0) and ethernet (eth0) interfaces.

A specific example is using a Raspberry Pi with a USB wifi adapter to connect a


wired-ethernet printer to the WLAN.

No static configuration is required other than the wifi SSID and authentication for
the Pi -
the Pi and printer acquire DHCP addresses from the existing DHCP server, and the
printer
continues to be reachable via mDNS and otherwise operates as if it were patched to
a
wired port on the main network.

The term 'bridge' in this document refers to the host doing the proxy-arp and
routing
between the two networks, though keep in mind there is no layer 2 bridging
involved.
The 'outside' network is the existing network that hosts the DHCP server, gateway
router, etc.
The 'inside' network is the one with the hosts that need to be bridged and made to
appear
to be on the outside network.

Summary
----------------
Proxy ARP is a technique by which a device on a given network answers the ARP
queries
for a network address that is not on that network, that is to make the hosts on one
network
appear to be logically part of a different physical network.

The bridge host will proxy ARP requests from the inside network to the outside, and
respond to
ARPs from the outside network on behalf of inside hosts. Linux will only do this
for hosts that are
known via the routing table, so a /32 host route must be created pointing to the
inside host
(one for each inside host). The route is also required for IP forwarding to work,
i.e. when IP
traffic arrives after the ARP process has completed.

As an example, to manually configure and test this out where the primary LAN has a
network address of 10.42.0.0/24:

configure an inside client with a static IP of 10.42.0.11/24


on the bridge:

bridge# echo 1 > /proc/sys/net/ipv4/conf/all/proxy_arp


bridge# echo 1 > /proc/sys/net/ipv4/ip_forward
bridge# ip ro add 10.42.0.11/32 dev eth0

ping from the inside host to an outside host, and examine the ARP table:
insidehost$ ping -c 1 10.42.0.2
PING 10.42.0.2 (10.42.0.2) 56(84) bytes of data.
64 bytes from 10.42.0.2: icmp_req=1 ttl=64 time=14.7 ms

insidehost$ arp -n 10.42.0.2


Address HWtype HWaddress Flags Mask
Iface
10.42.0.2 ether b8:27:eb:6b:52:b9 C eth0
# b8:27:eb:6b:52:b9 is the MAC of eth0 - the inside interface - on the bridge

bridge$ arp -n 10.42.0.2


Address HWtype HWaddress Flags Mask
Iface
10.42.0.2 ether 00:08:9b:be:f8:a2 C wlan0
# 00:08:9b:be:f8:a2 is the MAC of eth0 on the outside host

bridge$ arp -n 10.42.0.11


Address HWtype HWaddress Flags Mask
Iface
10.42.0.11 ether 00:1b:a9:be:16:73 C eth0
10.42.0.11 (incomplete) wlan0
# 00:1b:a9:be:16:73 is the MAC of the inside host; the outside wlan0 entry if
present should always be incomplete

outsidehost$ # arp -n 10.84.42.11


Address HWtype HWaddress Flags Mask
Iface
10.84.42.11 ether 00:e0:4c:10:3c:75 C eth0
# 00:e0:4c:10:3c:75 is the MAC of wlan0 on the bridge

Note that no IP address is required on the bridge's inside ethernet interface for
proxy ARP
to work (though see below re. DHCP relay).

If you run tcpdump on the bridge's ethernet and wlan interfaces, you'll see the ARP
request from the inside host being proxied to the outside interface, with the ARP
source
being the bridge's outside-facing interface's MAC address. The ARP table on the
inside hosts
will show the bridge's inside interface MAC for all outside hosts, and similarly
for outside
hosts the MAC for all inside hosts will be the bridge's outside interface MAC.

DHCP Relay
------------------
DHCP is a Layer 2 protocol and can't traverse the Layer 3 'bridge' so we use the
dhcp-helper
utility to listen for DHCP requests from the inside network and relay them to the
DHCP server
on the outside network. The relayed DHCP request will contain the IP address of the
bridge's
inside interface in order for the DHCP server to know which network to allocate an

IP address for the new client from. We want the DHCP allocation to be from the same
network as the outside LAN, the simplest implementation is to reflect the outside
interface's IP address on to the inside interface. i.e. the bridge's inside and
outside interfaces will have the same IP address; though the inside interface's
network
will be a host /32 netmask so as not to upset routing.

Alternatively the bridge inside interface can be assigned a static IP from the
outside network,
in which case the post-up step in /etc/network/interfaces configuration below can
be omitted.

Automating the Process


------------------------------------
parprouted is designed to monitor the ARP table and both proxy ARP requests and
install
matching /32 host routes. Running parprouted with the inside and outside interfaces
handles
the ARP and routing completely automatically. Note that the kernel's proxy ARP
mechanism
(/proc/sys/net/ipv4/conf/all/proxy_arp) is not required.

parprouted does not handle packet forwarding nor DHCP or mDNS, so these features
need to be enabled separately.

Installing the software


----------------------------------

The following assumes wlan0 is the already-configured outside interface, eth0 the
unconfigured inside interface. Tested on Debian Wheezy 7.8 on 2015-08-02, on armv6l
(Raspberry Pi v1).

bridge$ apt-get install parprouted dhcp-helper avahi-daemon

Edit /etc/network/interfaces to configure the interfaces:

auto lo
iface lo inet loopback

auto eth0
allow-hotplug eth0
iface eth0 inet manual

auto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
post-up /usr/sbin/parprouted eth0 wlan0
post-down /usr/bin/killall /usr/sbin/parprouted
# clone the dhcp-allocated IP to eth0 so dhcp-helper will relay for the correct
subnet
post-up /sbin/ip addr add $(/sbin/ip addr show wlan0 | perl -wne 'm|^\s+inet
(.*)/| && print $1')/32 dev eth0
post-down /sbin/ifdown eth0

Edit /etc/sysctl.d/local.conf to enable IP forwarding:

net.ipv4.ip_forward=1

Enable DHCP relay: /etc/default/dhcp-helper

# relay dhcp requests as broadcast to wlan0


DHCPHELPER_OPTS="-b wlan0"
Edit /etc/avahi/avahi-daemon.conf to enable mDNS relaying:

[reflector]
enable-reflector=yes

Reboot, and hosts connected to the bridge's ethernet should acquire a DHCP address
and have full IP connectivity!

Known Issue with RTL8188CUS USB Wifi Adapter

Description of issue: When using an RTL8188CUS based wifi device, bridge


connectivity is very unreliable and most ARP requests to the bridge's wlan address
fail. This issue has minimal impact on a host that is configured as a normal client
and primarily sending traffic but has a significant impact when the host is acting
as a bridge.

Resolution: Edit /etc/modprobe.d/8192cu.conf

# disable power management and USB suspend


options 8192cu rtw_power_mgnt=0 rtw_enusbss=0

===================================================================================
===========
AZWAN:wpa_supplicant: GUI and wpa_action
===================================================================================
===========

SEP 18, 2008

I’ve made two new interesting discoveries about wpa_supplicant since writing my
last
blog post on the subject. (Actually, I pretty much made both of them while reading
documentation in order to write it, and have been lame about writing them up).

Using wpa_gui

It turns out that wpa_gui not only allows you to select existing networks, but also
to scan
for and add new networks to your configuration file. In addition, you can run it as
yourself,
without needing to it. In order to do so, you need to add two lines to

/etc/wpa_supplicant/wpa_supplicant.conf:

ctrl_interface_group=netdev
update_config=1

ctrl_interface_group selects a UNIX group that will be given permission to


read/write
the control socket. I chose netdev because it seems like it’s supposed to be
networking-related, and my login user was already in it on my Ubuntu machine.

update_config allows wpa_supplicant to write back to its conf file if instructed to


configure
new networks by a UI (wpa_cli or wpa_gui). Note that this will squash any comments
you have in the file.

wpa_action — a mostly-baked roaming solution


------------------------------------------------------------------------
The setup I described in the previous post causes wpa_supplicant to manage
associating
with access points, while Debian’s ifupdown request DHCP independently.
There’s no communication between the layer, so if you switch networks, or associate
sometime after we bring up the interface, nothing tells dhclient to request a new
lease.
It turns out we can turn this picture inside-out, and make wpa_supplicant
responsible for
bringing up and down a virtual interface, whenever it associates or loses
association.

To make this work, we’re going to need to edit /etc/network/interface again.


Our wpa_supplicant.conf can stay unchanged; Debian’s wrapper scripts do all the
magic.
Replace your ath0 block and add a virtual default interface as follows:

iface ath0 inet manual


wpa-driver wext
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf

iface default inet dhcp

The way this is going to work is that, whenever wpa_supplicant associates to a


network,
it will bring up the virtual default interface, causing ifupdown to spawn dhclient
and
request DHCP. When it loses association, it brings it down, killing the DHCP
daemon.

Furthermore, we can associate different virtual interfaces with different networks.


Suppose that I usually want DHCP, but at home (essid nelhage) I don’t run a DHCP
server,
and just want my laptop to always grab 10.0.1.100. I can add an interface to
wpa_supplicant.conf:

network={
ssid="nelhage"
id_str="nelhage"
key_mgmt=NONE
}
And then I add a new virtual interface to interfaces, corresponding to the id_str:

iface nelhage inet static


address 10.0.1.100
netmask 255.255.255.0
network 10.0.1.0
gateway 10.0.1.1

Now, if wpa_supplicant associates to the nelhage network, it will bring up the


nelhage
interface, binding ath0 to the static configuration there listed.

For documentation, check out the third section of


/usr/share/doc/wpasupplicant/README.modes.gz
on your Debian or Ubuntu machine.

In conclusion…

This setup actually seems pretty close to the correct design for a roaming wifi
architecture, to me.
Unfortunately, my experience is that it hasn’t worked well for me;
For some reason, when I put it in roaming mode, it fails to associate with networks
that it
otherwise works fine with. I suspect that this is related to madwifi suckage as
much as
wpa_supplicant suck, though, so I’d encourage everyone else who’s been fighting
with wifi
to try it out and report back if it works for them.

-----------------------------------------------------------------------------------
---------------------------------------------
AZARTICOLO: Disable power management on Raspberry Pi USB Wifi interface
-----------------------------------------------------------------------------------
---------------------------------------------

Too early to tell whther this solved my problem but recording for posterity anyway.
In theory this will stop my Raspberry Pi from dropping off the network after it has
been
idle for a while.

Before

pi@dashboard ~ $ iwconfig

wlan0 IEEE 802.11bgn ESSID:"Professor Ping"


Mode:Managed Frequency:2.437 GHz Access Point: B8:E6:25:9B:62:02
Bit Rate=39 Mb/s Tx-Power=20 dBm
Retry long limit:7 RTS thr:off Fragment thr:off
Power Management:on
Link Quality=43/70 Signal level=-67 dBm
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:70 Invalid misc:14 Missed beacon:0

lo no wireless extensions.

eth0 no wireless extensions.

Note: Power Management:on

Then

vi /etc/network/interfaces
add line: wireless-power off

After

pi@dashboard ~ $ iwconfig
wlan0 IEEE 802.11bgn ESSID:"Professor Ping"
Mode:Managed Frequency:2.437 GHz Access Point: B8:E6:25:9B:62:02
Bit Rate=26 Mb/s Tx-Power=20 dBm
Retry long limit:7 RTS thr:off Fragment thr:off
Power Management:off
Link Quality=43/70 Signal level=-67 dBm
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:29 Invalid misc:8 Missed beacon:0

lo no wireless extensions.
eth0 no wireless extensions.
Note: Power Management:off

OK, new theory: pm-utils is disabling the interface.

Based on pm-utils info on ArchWiki I found a hook invoking wpa_supplicant to


disable
the wifi interface:

cat /usr/lib/pm-utils/sleep.d/60_wpa_supplicant

#!/bin/sh

# /etc/pm/sleep.d/60_wpa_supplicant

# Action script to notify wpa_supplicant of pm-action events.

PATH=/sbin:/usr/sbin:/bin:/usr/bin

WPACLI=wpa_cli

case "$1" in
suspend|hibernate)
$WPACLI suspend
;;
resume|thaw)
$WPACLI resume
;;
esac

exit 0

To disable that hook I created a dummy hook in /etc/pm/sleep.d/`:

touch /etc/pm/sleep.d/60_wpa_supplicant
chmod 644 /etc/pm/sleep.d/60_wpa_supplicant
# Instructions said no exec flag

ne risulta :
-rw-r--r-- 1 root root 0 nov 5 19:16 60_wpa_supplicant

I rebooted for good measure. We'll see whether this one takes.

OK QUESTO TRUCCO FUNZIONA MA OCCORRE ANCHE AGIRE SUI PARAMETRI


TURBOMODE=Y E PACKETSIZE=2562 DEL DRIVER DEL WIFI

===================================================================================
=========
AZARTICOLO::How To : Use The Raspberry Pi As A Wireless Access Point/Router Part 1
===================================================================================
=========

Linux, Raspberry Pi, Tutorials 238 Responses »

** Quick Tip For The QuickLinks **

If you want a wifi router, ignore Part 2, and go from this part straight to Part 3.
Need internet access ? Part 2 or 3 is the go depending on your need

QuickLinks:

Part 2 – How to make your RPi into a Wireless Access Point


Part 3 – How to make your RPi into a Router

Also if you are using a RTL8188CUS based device check this forum thread

Update
-----------

Looks like the newest version of the Raspbian distro adds an extra line to
/etc/network/interfaces which needs to be removed or commented out.

The line is wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf

** Update – 2016-11-06 **
---------------------------------
As requested, I’ve added some information from the comments – courtesy of Jakimfett
To find out what driver your USB WiFi stick uses, you can use lshw -C network to
find out.
The driver info is shown under the configuration section.
If lshw is not installed, you can install it via apt-get – apt-get install lshw

Introduzione
--------------------

I recently bought a Wifi dongle for my Raspberry Pi – A Ralink RT5370.


While I was poking around, I noticed that the USB dongle could act as an Access
Point.
I haven’t tried with any others, but the way I found out about mine is by using the
iw utility.

Running iw list spat out a list of abilities.

This was a part of the list

Supported interface modes:

* IBSS
* managed
* AP
* AP/VLAN
* WDS
* monitor
* mesh point

So I decided to try it out.

I installed hostapd so that I could run an access point off the Raspberry Pi.

apt-get install hostapd

After I installed hostapd, I had to modify a few files before hostapd would run.

Before I go modifying the files though, I need to give my WiFi adapter a static IP
address.
In /etc/network/ there is a file called interfaces.
This file contains the details for the network adapters.

I have the lines below in order to set a static IP address.

iface wlan0 inet static


address 10.0.0.1
netmask 255.255.255.0

Now, we need to edit some files.

First up, I had to modify /etc/default/hostapd.


The DAEMON_CONF variable was not configured, so I pointed it to a configuration
file
that I was about to create.

DAEMON_CONF="/etc/hostapd/hostapd.conf"

After that, I created the configuration file in the location specified.


In the configuration file, I specified the following parameters

# First we configure the interface we'll be listening on


interface=wlan0 # The interface to listen on
driver=nl80211
# The driver that is being used by the WiFi adapter, this could be different for
everyone

ctrl_interface=/var/run/hostapd
ctrl_interface_group=0 # These 2 are just parameters so that the hostap daemon
runs.

# Now onto the important WiFi configuration


ssid=RaspAP
# First up, the SSID or Network name. This is what other devices will see when they
try to connect.
hw_mode=g
# I'm setting this to Wireless G mode. A, B, and G are available here.
channel=8
# This is setting the channel that the WiFi is on, valid channels are from 1-11, or
1-14 depending on location.

# Wifi Security Settings


wpa=2 # This sets the security settings to WPA2
wpa_psk=928519398acf811e96f5dcac68a11d6aa876140599be3dd49612e760a2aaac0e
# The line above sets the wpa passphrase to "raspiwlan", this is obtained via the
wpa_passphrase command.
# However, you can also set a passphrase like the line below.
#wpa_passphrase=raspiwlan

wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP
rsn_pairwise=CCMP
# I've set these to WPA-PSK to indicate that we are using a Pre-Shared Key with
CCMP encryption.
# Otherwise, hostapd also has a built in RADIUS server that we can use for
authentcation
# But I'll leave that to another post.
# Other settings
----------------------------

beacon_int=100 # This sets how often the WiFi will send a beacon out.
auth_algs=3
wmm_enabled=1

** Note ** You may need to strip out all the comments when you save your
configuration file as hostapd does not have consistent comment handling.

With the above configuration file saved, I downloaded dnsmasq in order to give my
Raspberry Pi the ability to hand out IP addresses to clients that connected to the
RaspAP.
apt-get install dnsmasq

For now, we’ll only do a base configuration of dnsmasq, just enough for it to hand
out IP addresses so we can test out our new RasAP.

interface=wlan0 # To get dnsmasq to listen only on wlan0.


dhcp-range=10.0.0.2,10.0.0.5,255.255.255.0,12h # This sets the available range from
10.0.0.2 to 10.0.0.5
# It also sets the subnet mask to 255.255.255.0 and specifies a lease time of 12
hours.

After the configuration file has been created in /etc/dnsmasq.conf, start up


hostapd and restart dnsmasq.
You should now be able to see the WiFi network “RaspAP” and be able to connect to
it and get an IP address.

In the next post, we will turn the Raspberry Pi into a bridge so that it can act as
a wireless access point.
If you have found this post useful, please consider donating by pressing on the
button below. Donating will help keep this site up and running 🙂

-----------------------------------------------------------------------------------
--------------------------------------------------
AZARTICOLO:How To : Use The Raspberry Pi As A Wireless Access Point/Router Part 2
-----------------------------------------------------------------------------------
-----------------------------------------------
In this part, we will turn the Raspberry Pi into a Wireless Access point.
-----------------------------------------------------------------------------------
---------------------------------------------------
All it will do is forward packets from the WiFi adapter to ethernet and vice versa.
It will allow you to access your network via WiFi without needing a WiFi router.

To do this, we need to bridge the ethernet and wifi connections, and tell hostapd
that we are now using a bridge connection.
In /etc/hostapd/hostapd.conf, we need to add the following line.

bridge=br0

Add the following lines into /etc/network/interfaces to define the bridge


connection.

#auto br0
iface br0 inet dhcp
bridge_ports eth0 wlan0
pre-up ifconfig eth0 0.0.0.0 up
pre-up ifconfig wlan0 0.0.0.0 up
pre-up brctl addbr br0
pre-up brctl addif br0 eth0
post-down ifconfig wlan0 0.0.0.0 down
post-down ifconfig eth0 0.0.0.0 down
post-down brctl delif br0 eth0
post-down brctl delbr br0

Notice the “auto br0” is commented out.


This is so the bridge does not come up automatically, as once the bridge is up, you
will not
be able to remotely access the Raspberry Pi until the bridge is brought down or
until the
bridge gets an IP address.

Once the lines are in /etc/network/interfaces, you can type in ifup br0 as root to
bring up the bridge. If you are ssh’ed into the Pi, this will drop your connection.
Once it’s up, the Raspberry Pi will forward anything from the WiFi to ethernet and
vice versa.

This let’s the Raspberry Pi act as a Wireless Access Point without any sort of
routing. On a WiFi device, you will be able to connect to RaspAP, and it will act
is if it was on the network, i.e. it will get an IP address from your normal
router.

-----------------------------------------------------------------------------------
--------------------------------------------------
AZARTICOLO:How To : Use The Raspberry Pi As A Wireless Access Point/Router Part 3
-----------------------------------------------------------------------------------
--------------------------------------------------

Linux, Raspberry Pi, Tutorials 86 Responses »

QuickLinks
Part 1 – How to create a wireless network on your RPi
Part 2 – How to make your RPi into a Wireless Access Point
Part 3A – Issues with HostAPD ? Click here
Part 3B – Issues with HostAPD ? Click here!

In Part 3, we will turn the Raspberry Pi into a router. The Pi will use the
ethernet port as the “WAN” port, and the wireless adapter as the “LAN” side of
things.
First thing we need to do is to enable packet forwarding.
In the file /etc/sysctl.conf, we need to uncomment the following line (should be
line 28).

#net.ipv4.ip_forward=1

After changing that, run this command to re-read the sysctl.conf file

sysctl -p

We will also need to install the iptables utilities if they are not already
installed, and alter the dnsmasq.conf file so that dnsmasq will assign a gateway to
the computers.

Firstly we install iptables.

apt-get install iptables


Then we will add this line to dnsmasq.conf.
The IP address is the same one we gave to the WiFi adapter back in Part 1

dhcp-option=3,10.0.0.1

We will need to create an iptables script to tell the Raspberry Pi to forward


packets from the WiFi interface to the LAN interface. This script will need to run
at startup in order for it to be a router.
I have created the following file in /etc/network/if-up.d/ called router. By
placing the script in that directory, it will be run every time the Raspberry Pi
comes online.
This file contains the following lines

iptables -F
iptables -X

iptables -A INPUT -i lo -j ACCEPT


iptables -A OUTPUT -o lo -j ACCEPT
iptables -A INPUT -i wlan0 -j ACCEPT
iptables -A OUTPUT -o wlan0 -j ACCEPT

iptables -A POSTROUTING -t nat -o eth0 -j MASQUERADE


iptables -A FORWARD -i wlan0 -j ACCEPT

After creating this file, make it executable by using this command

chmod +x /etc/network/if-up.d/router

Once that router.sh file has been run, it should start forwarding traffic from the
WiFi Interface to the LAN interface !

** UPDATE **
As a few people have found out, the IP address of the Pi does not get set correctly
until you take down wlan0 and bring it back up after hostapd starts.
I have not found out why yet, but the workaround I am currently using consists of
editing /etc/init.d/hostapd, and modifying the start case statement to include
ifdown wlan0 && ifup wlan0 at the end of it.
I failed to copy the statement I am talking about, but if you’re familiar with
scripting it shouldn’t be too hard to figure out. Otherwise I’ll get the code I
modified up here soon.

** UPDATE 2 **
Looks like a Pi user has successfully gotten hostapd running on the realtek
devices.
Info can be found here

-----------------------------------------------------------------------------------
----------
AZARTICOLO:Raspberry Pi As A Wireless Access Point/Router Part 3A!
-----------------------------------------------------------------------------------
------------
Linux, Raspberry Pi, Tutorials 1 Response »

So a few people have tried to follow Part 3 of this series of posts, and had issues
with the connections once everything is setup.
The main cause for that, was that hostapd would take away the IP address of wlan0
for some reason.
I worked around it by modifying the /etc/init.d/hostapd startup file.

In that file, there is a switch case statement which controls what the file does
depending on how you run the file.

The example below is what you will see part way down the file. What we need to do
is add in some commands into that block of code.

case "$1" in
start)
log_daemon_msg "Starting $DESC" "$NAME"
start-stop-daemon --start --oknodo --quiet --exec "$DAEMON_SBIN" \
--pidfile "$PIDFILE" -- $DAEMON_OPTS >/dev/null
log_end_msg "$?"
;;
stop)

The command we will need to add are :


ifup wlan0

Which brings up wlan0 with the specified IP address. The IP address should have
been setup in Part 3 of this series.

So the above block of code will now become –

case "$1" in
start)
log_daemon_msg "Starting $DESC" "$NAME"
start-stop-daemon --start --oknodo --quiet --exec "$DAEMON_SBIN" \
--pidfile "$PIDFILE" -- $DAEMON_OPTS >/dev/null
log_end_msg "$?"
ifup wlan0
;;
stop)

This will force wlan0 to come up after hostapd is started.

Alternatively to force wlan0 to use an ip.address, replace ifup wlan0 with this
ifconfig wlan0 10.0.0.1 netmask 255.255.255.0 up
Hopefully this helps everyone when they come to making their Pi a WiFi Router ! 😀

-----------------------------------------------------------------------------------
--------------------------------------------
AZARTICOLO:How To : Use The Raspberry Pi As A Wireless Access Point/Router Part 3…
B!
-----------------------------------------------------------------------------------
--------------------------------------------

So, I figured out why wlan0 doesn’t get an IP address when hostapd starts up.
ifplugd messes about with the interfaces when they go up and down, so the simplest
solution is to disable ifplugd for wlan0 !

in /etc/default/ifplugd, the default configuration is this

INTERFACES="auto"
HOTPLUG_INTERFACES="all"
ARGS="-q -f -u0 -d10 -w -I"
SUSPEND_ACTION="stop"
Simply changing it to this

INTERFACES="eth0"
HOTPLUG_INTERFACES="eth0"
ARGS="-q -f -u0 -d10 -w -I"
SUSPEND_ACTION="stop"

will ensure that wlan0 will not lose it’s static IP address that’s configured in
/etc/network/interfaces when wlan0 goes up.
-----------------------------------------------------------------------------------
--------------------------------------------
Il sottoscritto ha la seguente configurazione:

cat /etc/default/ifplugd

# Puo essere cambiata sia manualmente che via dpkg-reconfigure ifplugd


#
# N.B.: dpkg-reconfigure cancella tutto meno le variabili
# INTERFACES, HOTPLUG_INTERFACES, ARGS e SUSPEND_ACTION.
# Quando va in esecuzione utilizza il valore corrente di tali variabili per cui
tali valori
# vengono utilizzati solo se non definiti esternamente a runtime
# Tale file viene utilizzato sia dalo script lanciato da init /etc/init.d/ifplugd,
sia dallo script
# lanciato da /lib/udev/ifplugd.agent che difatti assegna i valori default
# Lo script init lancia una istanza di ifplugd per ciascuna delle intefaccie
definite in
# INTERFACES, ed udev lo fa per tutte quelle definite in HOTPLUG_INTERFACES.
# Lo speciale valore all indica di lanciare una istanza per tutte interfaccie
presenti nel
sistema

Io attualmente utilizzo :

INTERFACES="wlan0 eth0"
HOTPLUG_INTERFACES=""
ARGS="-q -f -u0 -d10 -w -I -b"
SUSPEND_ACTION="stop"

===================================================================================
=========
AWLAN : Principali Parametri del Daemon ifplug.
===================================================================================
=========

* -q Non esegue lo script quando il demone esce


* -f Ignora errori di rilevamento e riprova
* -u Specifica il ritardo per la configurazione dell'interfaccia
* -d Specifica il ritardo per la sconfigurazione dell'interfaccia
* -w Attende fino alla conclusione del fork del demone
* -I Non esce quando il programma eseguito restituisce nonzero

-a L'interfaccia non viene attivata automaticamente


-s Usa stderr al posto di syslog per il debug
** -b Non emette beep (-U/-D Non emettono il beep quando una interfaccia
viene attivata/disattivata)
-t Specifica l'intervallo di interrogazione in secondi (valore predefinito:
1)
-p Non esegue lo script all'avvio del demone
-l Esegue lo script "down" all'avvio se non rileva cavi
-W Attende fino alla morte del demone quando viene fermato
-M Usa il monitor delle interfacce

Argomenti di default: -q -f -u0 -d10 -w -I

===================================================================================
=========
/etc/wpa_supplicant/wpa_supplicant.conf DEFINITIVO
===================================================================================
=========

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=IT

network={
ssid="CISCOWIFI"
psk="intrapam123$"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
id_str="azcam"
}

===================================================================================
=========
/etc/network/inetrfaces DEFINITIVO
===================================================================================
=========

# interfaces(5) file used by ifup(8) and ifdown(8)


# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'
# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

#AZPATCH
#auto lo wlan0
auto lo
iface lo inet loopback
#allow-hotplug eth0
iface eth0 inet static
address 192.168.1.5
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
mtu 1492
metric 1
#up route add default gw 192.168.1.1 metric 1 dev eth0
#dns-nameservers 192.168.1.1 8.8.4.4

# AZPATCH andrebbe invertitito l'utilizzo!


#auto wlan0
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface azcam inet static
address 192.168.1.7
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
mtu 1492
wireless-power off
metric 2
#up route add default gw 192.168.1.1 metric 2 dev wlan0
#down route del default gw 192.168.1.1 metric 2 dev wlan0
dns-domain homenet.telecomitalia.it
dns-nameservers 192.168.1.1 8.8.4.4
iface default inet dhcp

N.B: DEROGA 1

===================================================================================
=========
/etc/ifplugd/action.d/ifupdown DEFINITIVO
===================================================================================
=========
#!/bin/sh
# AZPATCH Gestione della wlan0 demandata a wpa_action
set -e

case "$2" in
up)
# if [ "$1" == eth0 ]; then /sbin/ifdown wlan0 ; fi # Riga Inserita
/sbin/ifup $1
;;
down)
/sbin/ifdown $1
# if [ "$1" == eth0 ]; then /sbin/ifup wlan0 ; fi # Ruga Inserita
;;
esac

N.B: DEROGA 2

===================================================================================
=========
/etc/ifplugd/action.d# cat /etc/rc.local DEFINITIVO
===================================================================================
=========

#!/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.
#/var/www/command/player_wdog.sh startup & > /dev/null 2>&1
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket
DBUS_SESSION_BUS_PID=`cat /run/dbus/pid`
#pulseaudio --start
exit 0

N.B. Tale script viene eseguito una sola volta allo startup della macchina

==============================================================
AZARTICOLO:Switching between wired and wireless networks in Raspbian & Debian
==============================================================
http://www.aoakley.com/articles/2013-07-31-raspberry-pi-networking.php

Assunzioni
-----------------

Se il cavo di rete e' inserito si suppone che sono in casa e pertanto utilizzo un
indirizzo statico
Ignoro completamente il WIFI anche se ho il Dongle inserito

Se il cavo e' staccato ma sono in casa, utilizzo lo stesso indirizzo statico ma sul
WIFI

Pertanto in casa la Rasperry ha sempre lo stesso indirizzo indipendentemente se


collegata
con cavo o via WIFI

Se il cavo e' scollegato e non sono in casa il WIFI deve essere configurato con IP
Statico o
dinamico, in questo caso occorre un display o un network scanner per sapere quale
e'.

Il cav puo' essere scollegato anche durante il funzionamento, ma non si puo' fare
cosi con
il Dongle WIFI

Configurazione WIFI Statica e Dinamica


----------------------------------------------------------

Viene deciso attraverso il file /etc/wpa_supplicant/wpa_supplicant.conf file:


(settando la stringa id_str in)

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
ssid="aoakley-home"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=CCMP TKIP
psk="PASSWORD"
id_str="aoakley-home"
}

network={
ssid="PlusnetWireless9AAAA9"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=CCMP TKIP
psk="PASSWORD"
id_str="inlaws"
}

network={
ssid="aoakley-mifi"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=CCMP TKIP
psk="PASSWORD"
id_str="aoakley-mifi"
}

Nel file di esempio abbiamo tre reti tutte con sicurezza WPA-PSK security;

aoakley-home PlusnetWireless9AAAA9 e aoakley-mifi .

Ognuna possiede il suo id_str so in modo da potergli assegnare la propria


configurazione IP
nel file /etc/network/interfaces .

Nei casi piu' semplici posso avere anche una sola configurazione WIFI ma la stringa
identificativa
deve sempre esistere, la quale viene utilizzata nel file /etc/network/interfaces:

auto lo
iface lo inet loopback

(porre qui la configurazione di eth0 ...)

auto wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
iface aoakley-home inet static
address 192.168.0.5
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.254

Notare che la confurazione statica e' definita solo per aoakley-home .


Infatti tutte connessioni che possiedono un identificativo che non coincide con
nessuno
di quelli che nel file interfaces defiscono le diverse configurazioni ivi presenti,
utilizzeranno
la configurazioni di default descritta nella ultima riga:

iface default inet dhcp

ovvero assumeranno un indirizzo IP proveniente dal DHCP di rete

Per le configurazioni statiche occorre definire address, netmask, network,


broadcast e
gateway

Reboot con shutdown -r now ed il gioco e' fatto!


Possiamo un indirizzo statico se ci colleghiamo alla rete WIFI aoakley-home,
dinamico
se utilizziamo un diverso hotspot. Possiamo passare da un hotspot all'altro senza
bisogno
di riconfigurare alcunche'!

Spegnere il WIFI quando viene inserito il cavo rete


-------------------------------------------------------------------------

Vogliamo innanzitutto avere lo stesso indirizzo statico IP sia se ci connetiamo


viaa cavo
sia se lo facciamo tramite WIFI, ma per poterlo fare le due interfaccie non possono
essere
attive contemporaneamente, la rete si incepperebbe, a meno che non utilizziamo le
metriche come descritto in articolo "Linux route metrics"

La soluzione piu' semplice e' spegnere il WIFI se viene inserito il cavo.


Allo scopo viene utilizzato il daemon ifplugd che qualora l ' interfaccia
dichiarata
hot-pluggable sia eth0 esegue uno script speciale ogni volta che il cavo viene
inserito o
disinserito. Personalizziamo lo script per fare in modo che venga acceso o spenta
l'interfaccia
WIFI wlan0

In alcune distribuzioni di Raspbian ifplugd e' installato di default.

Se non esiste installarlo con

apt-get install ifplugd

ed e' possibile accettare la configurazione di default proposta, ovvero sono


definite
Volendo riconfigurarlo farlo tramite :

dpkg-reconfigure ifplugd

Occorre personalizzare lo script /etc/ifplugd/action.d/ifupdown:

#!/bin/sh
set -e

case "$2" in
up)
if [ "$1" == eth0 ]; then /sbin/ifdown wlan0 ; fi # Riga Inserita
/sbin/ifup $1
;;
down)
/sbin/ifdown $1
if [ "$1" == eth0 ]; then /sbin/ifup wlan0 ; fi # Ruga Inserita
;;
esac

Ovvero quando il kernel ci indica che eth0 e' su viene tirata su la configurazione,
viceversa
se il link cade l'interfaccia eth0 viene sconfigurata

DEROGA 2
----------------
La personalizzazione consiste nel fare anche l'esatto opposto per l'interfaccia
wlan0
Tuttavia io non ho proceduto a inserire tali righe perche' demando il compito della
gestione
di wlan0 a wpa_action

Ora occorre sincerarsi che eth0 sia definito come pluggabile ovvero occore
definire per essa
allow-hotplug nel file /etc/network/interfaces , oltre che assegnargli lo stesso
indirizzo
statico di wlan0:

allow-hotplug eth0

DEROGA 1
----------------

Anche questa personalizzazione non e' stata da me effettuata

auto lo
iface lo inet loopback

allow-hotplug eth0
iface eth0 inet static
address 192.168.1.5
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1

auto wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
iface aoakley-home inet static
address 192.168.0.5
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.254

NOTA: Non definire wlan0 come hot-pluggable, equivale a togliere ed reinserire il


Dongle
a caldo cosa che potrebbe portare al freeze della Raspberry ed anche alla fusione
del
Dongle! Tuttavia per la DEOROGA 1 a me accade con eth0 per cui ho invertito i
settaggi

Il problema e' che il WIFI USB consuma in maniera eccessiva, molto piu' di un mouse
o
di una keyboard e spegnerla ed accenderla crea una eccessiva fluttuazione di
amperaggio

N.B: Auto indica che l'interfaccia deve essere caricata al boot della macchina e
non spenta
fino allo shutdown
allow-hotplug permette agli script di gestione di portare l'interfaccia
nello stato di
on o off
Pertanto i due parametri non possono coesistere!

Effettua il reboot con Reboot con shutdown -r now , ed il gioco e' fatto!

N.B: Praticamente io ho invertito lo schema di funzionamento di eth0 e wlan0


ed adottata la variante wpa_action per la gestione di wlan0

==============================================================
AZARTICOLO:WPA ed eth0 entrambe attive (ma con subnet diverse)
==============================================================

L'obbietivo sarebeb utilizzare la LAN per andare verso la NAS con indirizzo statico
ed il
WIFI per collegarsi ad Internet

eth0: utilizza indirizzo statico e si connette solo alla LAN per andare verso
la NAS
pertanto non ha default gateway

wlan0: Concede l'accesso a Internet

Come fare in modo che quando eth0 e' su lo si anche wlan0 ?


Vediamo il file di interfaces:

cat /etc/network/interfaces

auto lo
iface lo inet loopback

auto eth0
allow-hotplug eth0
iface eth0 inet static
address 192.168.1.101
netmask 255.255.255.0

auto wlan0
allow-hotplug wlan0
iface wlan0 inet static
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
address 192.168.0.157
netmask 255.255.255.0
broadcast 192.168.0.255
gateway 192.168.0.1

iface default inet dhcp

Vediamo il file wpa_supplicant.conf :

cat /etc/wpa_supplicant/wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
ssid="****"
scan_ssid=1
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=CCMP TKIP
psk="****"
id_str="home"
priority=5
}

Occorre disabilitare il daemon di hotplugging di eth0 che disabilita device wlan0.


Pertanto disabilitare il restart del daemon:

cat /etc/default/ifplugd

INTERFACES="eth0"
HOTPLUG_INTERFACES="eth0"
ARGS="-q -f -u0 -d10 -w -I"
SUSPEND_ACTION="stop"

Poi Nel file che personalizza lo startup mi assicuro che wlan0 sia salito (a volte
non lo fa!)
ed uccido il processo ifplugd daemon :

cat /etc/rc.local

#!/bin/sh -e

# Print the IP address


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

# Uccidere il daemon ifplugd eth0


ifplugd eth0 --kill
# Abilitare l'interfaccia wifi wlan0
ifup wlan0
exit 0

E tutto funziona!

N.B. Io ho disabilitato lo start di pulseaudio!

N.B: Non occorre disabilitare del tutto ifplugd.

Difatti costui in conseguenza del cambio di stato del link dopo aver gestito di
conseguenza
l'interfaccia monitorata (eth0) manda in esecuzione tale script per compiere
l'azione
complementare sull altra interfaccia (che comunque puo' essere specificata) wlan0
Di conseguenza se cancello il link ifplugd non riesce piu' a mandare in esecuzione
lo script che gestisce l'altra interfaccia!

/etc/ifplugd/action.d/action_wpa -> /etc/wpa_supplicant/action_wpa.sh

Questo script esegue wpa_cli -i wlan0 reconnect se il cavo eth0 e' disconnesso
wpa_cli -i wlan0 disconnect se
il cavo eth0 e' connesso

Il link viene utilizzato proprio per chiamare tale script da dentro ifplugd quando
si
modifica lo stato di eth0
================================================================================
RASPBERRY:Boot options in config.txt
================================================================================

START_FILE, FIXUP_FILE

These options specify the firmware files transferred to the Videocore GPU prior to
booting.

start_file specifies the Videocore (VC4) firmware file to use.


fixup_file specifies the file used to fix up memory locations used in the
start_file to match
the GPU memory split. Note that the start_file and the fixup_file are a matched
pair - using
unmatched files will stop the board from booting. This is an advanced option, so
we advise
that you use start_x and start_debug rather than this option.

START_X, START_DEBUG

These provide a shortcut to some alternative start_file and fixup_file settings,


and are the
recommended methods for selecting firmware configurations.

start_x=1 implies start_file=start_x.elf fixup_file=fixup_x.dat


start_debug=1 implies start_file=start_db.elf fixup_file=fixup_db.dat

start_x=1 should be specified when using the camera module.


SAVED_ARGS=Enabling the camera via raspi-config will set this automatically.

DISABLE_COMMANDLINE_TAGS

Set the disable_commandline_tags command to 1 to stop start.elf from filling in


ATAGS (memory from 0x100) before launching the kernel.

CMDLINE

cmdline is the alternative filename on the boot partition from which to read the
kernel command line string; the default value is cmdline.txt.

KERNEL

kernel is the alternative filename on the boot partition to use when loading
the kernel. The default value on the Pi 1, Pi Zero, and Compute Module is
kernel.img, and on the Pi 2, Pi 3, and Compute Module 3 it is kernel7.img.
If kernel8.img is present on the Pi 3 or Compute Module 3, it will be loaded in
preference and entered in 64-bit mode.

KERNEL_ADDRESS

kernel_address is the memory address to which the kernel image should be loaded.
32-bit kernels are loaded to address 0x8000 by default,
and 64-bit kernels to address 0x80000. If kernel_old is set, kernels are loaded
to the address 0x0.

KERNEL_OLD

Set kernel_old to 1 to load the kernel to the memory address 0x0.


RAMFSFILE

ramfsfile is the optional filename on the boot partition of a ramfs to load. More
information is available here.

RAMFSADDR

ramfsaddr is the memory address to which the ramfsfile should be loaded.

INITRAMFS

The initramfs command specifies both the ramfs filename and the memory address to
which to load it. It performs the actions of both ramfsfile and ramfsaddr in one
parameter. Example values are: initramfs initramf.gz 0x00800000. NOTE: This option
uses different syntax from all the other options, and you should not use a =
character here.

INIT_UART_BAUD

init_uart_baud is the initial UART baud rate. The default value is 115200.

INIT_UART_CLOCK

init_uart_clock is the initial UART clock frequency. The default value is 48000000
(48MHz). Note that this clock only applies to UART0 (ttyAMA0 in Linux), and that
the maximum baudrate for the UART is limited to 1/16th of the clock. The default
UART on the Pi 3 and Pi Zero is UART1 (ttyS0 in Linux), and its clock is the core
VPU clock - at least 250MHz.

BOOTCODE_DELAY

The bootcode_delay command delays for a given number of seconds in bootcode.bin


before loading start.elf: the default value is 0.

This is particularly useful to insert a delay before reading the EDID of the
monitor, for example if the Pi and monitor are powered from the same source, but
the monitor takes longer to start up than the Pi. Try setting this value if the
display detection is wrong on initial boot, but is correct if you soft-reboot the
Pi without removing power from the monitor.

BOOT_DELAY

The boot_delay command instructs to wait for a given number of seconds in


start.elf before loading the kernel: the default value is 1. The total delay in
milliseconds is calculated as (1000 x boot_delay) + boot_delay_ms. This can be
useful if your SD card needs a while to get ready before Linux is able to boot from
it.

BOOT_DELAY_MS

The boot_delay_ms command means wait for a given number of milliseconds in


start.elf, together with boot_delay, before loading the kernel. The default value
is 0.

DISABLE_SPLASH

If disable_splash is set to 1, the rainbow splash screen will not be shown on boot.
The default value is 0.
===============================================================
DISABILITARE WIFI
===============================================================

This post seems to be talking about this.


The answer talks about disabling the drivers by editing the file
/etc/modprobe.d/raspi-blacklist.conf and adding:

blacklist brcmfmac
blacklist brcmutil

Alternatively, you could use crontab -e and add:

@reboot sudo ifdown wlan0


So that command runs at each boot.

The blacklist method worked for me.


Just created a /etc/modprobe.d/local-blacklist.conf file, instead of appending
to an existing file

As far as I know, the blacklist method is closer to administratively down'ing


the interface. It does not completely power down the interface.

sudo crontab -e

How would you use the blacklist method to disable the ethernet (eth0)?

To completely disable the onboard WiFi from the firmware on the Pi3, add

dtoverlay=pi3-disable-wifi

in /boot/config.txt.

Also, there is an overlay for disabling onboard bluetooth :


pi3-disable-bt.

Correct. /boot/config.txt is the cleanest possible way to disable WiFi,


and other peripherals

sudo iwconfig wlan0 txpower off

This should disable the wifi adapter.


no , actually it does permanenty close the adapter until you made it back on

to re-enable the wifi adapter you should write two times "sudo iwconfig wlan0
txpower auto".
but as a say you should write it two times otherwise it wont work
(i believe there is some glitch in the firmware)
Apart from blacklisting which has the risk of a lockout in case you need to
reboot and no ethernet is available, you can also unload the kernel module
as follows:

sudo modprobe -r -v brcmfmac

But I'm not sure unloading the device drivers is a good idea as I fear the
wlan0 device may still draw power and even more so if the device drivers'
power management features are not loaded, currently I keep drivers loaded
and simply make sure the default route via wlan0 is disabled:

ip route del default via <Gateway IP> dev wlan0

This will make sure all traffic will go via eth0 and (hopefully) be more stable
and so forth for example for the ntp daemon.
We have measured the RF from the Pi 3 (when used as a WiFi hotspot) and
confirmed that this statement disables the Pi's WiDi transmitter when used
as a hot spot:

Ifconfig wlan0 down


Y
ou can also easily create a clickable button on the taskbar to do this.
Instructions are found here:
http://orbisvitae.com/ubbthreads/ubbthreads.php?ubb=showflat&Number=81166#Post81166

I use the following command wpa_cli terminate, I have that command in my


/etc/rc.local
This disables the WPA client, so you basically shut down wireless connectivity
entirely.
I modified the rc.local using command sudo nano /etc/rc.local, and added
ifconfig wlan0 down in it.

it looks like as below,

_IP=$(hostname -I) || true


if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi

ifconfig wlan0 down

exit 0

Then save using CTRL + X and reboot.


It seems to work for me, as after reboot ifconfig does not give wlan0.

There is a difference between having an interface enabled, a device enabled


(which this question is about), and having an interface connected to a network,
which is what you are talking about.
I do not think the OP is concerned about that.
@goldilocks Well if Wifi is disconnected this way then it will always use
Ethernet and that is what OP is asking for

Or edit using sudo nano /etc/wpa_supplicant/wpa_supplicant.conf


for those wanting to use this method

===============================================================
README WIFI OVERLAY
===============================================================
https://github.com/raspberrypi/firmware/tree/master/boot/overlays

Introduction
==========

This directory contains Device Tree overlays. Device Tree makes it possible
to support many hardware configurations with a single kernel and without the
need to explicitly load or blacklist kernel modules. Note that this isn't a
"pure" Device Tree configuration (c.f. MACH_BCM2835) - some on-board devices
are still configured by the board support code, but the intention is to
eventually reach that goal.

On Raspberry Pi, Device Tree usage is controlled from /boot/config.txt. By


default, the Raspberry Pi kernel boots with device tree enabled. You can
completely disable DT usage (for now) by adding:

device_tree=

to your config.txt, which should cause your Pi to revert to the old way of
doing things after a reboot.

In /boot you will find a .dtb for each base platform. This describes the
hardware that is part of the Raspberry Pi board. The loader (start.elf and its
siblings) selects the .dtb file appropriate for the platform by name, and reads
it into memory. At this point, all of the optional interfaces (i2c, i2s, spi)
are disabled, but they can be enabled using Device Tree parameters:

dtparam=i2c=on,i2s=on,spi=on

However, this shouldn't be necessary in many use cases because loading an


overlay that requires one of those interfaces will cause it to be enabled
automatically, and it is advisable to only enable interfaces if they are
needed.

Configuring additional, optional hardware is done using Device Tree overlays


(see below).

GPIO numbering uses the hardware pin numbering scheme (aka BCM scheme) and
not the physical pin numbers.

raspi-config
==========

The Advanced Options section of the raspi-config utility can enable and disable
Device Tree use, as well as toggling the I2C and SPI interfaces. Note that it
is possible to both enable an interface and blacklist the driver, if for some
reason you should want to defer the loading.

Modules
=======

As well as describing the hardware, Device Tree also gives enough information
to allow suitable driver modules to be located and loaded, with the corollary
that unneeded modules are not loaded. As a result it should be possible to
remove lines from /etc/modules, and /etc/modprobe.d/raspi-blacklist.conf can
have its contents deleted (or commented out).

Using Overlays
==============

Overlays are loaded using the "dtoverlay" directive.


As an example, consider the popular lirc-rpi module,
the Linux Infrared Remote Control driver.

In the pre-DT world this would be loaded from /etc/modules, with an explicit
"modprobe lirc-rpi" command, or programmatically by lircd.
With DT enabled, this becomes a line in config.txt:
dtoverlay=lirc-rpi

This causes the file /boot/overlays/lirc-rpi.dtbo to be loaded.


By default it will use GPIOs 17 (out) and 18 (in), but this can be modified using
DT parameters:

dtoverlay=lirc-rpi,gpio_out_pin=17,gpio_in_pin=13

Parameters always have default values, although in some cases (e.g. "w1-gpio")
it is necessary to provided multiple overlays in order to get the desired
behaviour. See the list of overlays below for a description of the parameters
and their defaults.

===============================
The Overlay and Parameter Reference
===============================

Name: <The base DTB>


Info: Configures the base Raspberry Pi hardware
Load: <loaded automatically>
Params:

audio Set to "on" to enable the onboard ALSA audio interface (default
"off")
i2c_arm Set to "on" to enable the ARM's i2c interface
(default "off")
i2c_vc Set to "on" to enable the i2c interface usually reserved for the
VideoCore processor
(default "off")
i2c An alias for i2c_arm
i2c_arm_baudrate Set the baudrate of the ARM's i2c interface (default
"100000")
i2c_vc_baudrate Set the baudrate of the VideoCore i2c interface (default
"100000")
i2c_baudrate An alias for i2c_arm_baudrate
i2s Set to "on" to enable the i2s interface
(default "off")
spi Set to "on" to enable the spi interfaces
(default "off")
random Set to "on" to enable the hardware random number
generator (default "on")
sd_overclock Clock (in MHz) to use when the MMC framework requests
50MHz
sd_force_pio Disable DMA support for SD driver (default off)
sd_pio_limit Number of blocks above which to use DMA for SD card
(default 1)
sd_debug Enable debug output from SD driver
(default off)
uart0 Set to "off" to disable uart0 (default "on")
uart1 Set to "on" or "off" to enable or disable uart1
(default varies)
watchdog Set to "on" to enable the hardware watchdog (default
"off")
act_led_trigger Choose which activity the LED tracks.Use "heartbeat"
for a nice load indicator.
(default "mmc")
act_led_activelow Set to "on" to invert the sense of the LED (default "off")
N.B. For Pi3 see pi3-act-led overlay.
act_led_gpio Set which GPIO to use for the activity LED (in case you
want to connect it to an external device)
(default "16" on a non-Plus board, "47" on a Plus
or Pi 2)
N.B. For Pi3 see pi3-act-led overlay.

pwr_led_trigger
pwr_led_activelow
pwr_led_gpio As for act_led_*, but using the PWR LED.
Not available on Model A/B boards.

-----------------------------------------------------------------------------------
-----------
N.B. It is recommended to only enable those interfaces that are needed.
Leaving all interfaces enabled can lead to unwanted behaviour
(i2c_vc interfering with Pi Camera, I2S and SPI hogging GPIO pins, etc.)
Note also that i2c, i2c_arm and i2c_vc are aliases for the physical interfaces
i2c0 and i2c1. Use of the numeric variants is still possible but deprecated
because the ARM/VC assignments differ between board revisions.
The same board-specific mapping applies to i2c_baudrate, and the other
i2c baudrate parameters.

-----------------------------------------------------------------------------------
-----------
Name: adau1977-adc
Info: Overlay for activation of ADAU1977 ADC codec over I2C for control
and I2S for data.
Load: dtoverlay=adau1977-adc
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: adau7002-simple
Info: Overlay for the activation of ADAU7002 stereo PDM to I2S converter.
Load: dtoverlay=adau7002-simple,<param>=<val>

Parametri:
card-name Override the default, "adau7002", card name.

-----------------------------------------------------------------------------------
-----------
Name: ads1015
Info: Overlay for activation of Texas Instruments ADS1015 ADC over I2C
Load: dtoverlay=ads1015,<param>=<val>

Parametri:
addr I2C bus address of device. Set based on how the
addr pin is wired. (default=0x48 assumes addr
is pulled to GND)
cha_enable Enable virtual channel a. (default=true)
cha_cfg Set the configuration for virtual channel a.
(default=4 configures this channel for the
voltage at A0 with respect to GND)
cha_datarate Set the datarate (samples/sec) for this channel.
(default=4 sets 1600 sps)
cha_gain Set the gain of the Programmable Gain
Amplifier for this channel. (default=2 sets the
full scale of the channel to 2.048 Volts)

Channel (ch) parameters can be set for each enabled channel.


A maximum of 4 channels can be enabled (letters a thru d).
For more information refer to the device datasheet at:
http://www.ti.com/lit/ds/symlink/ads1015.pdf

-----------------------------------------------------------------------------------
-----------
Name: ads1115
Info: Texas Instruments ADS1115 ADC
Load: dtoverlay=ads1115,<param>[=<val>]

Parametri:
addr I2C bus address of device. Set based on how the
addr pin is wired. (default=0x48 assumes addr
is pulled to GND)
cha_enable Enable virtual channel a.
cha_cfg Set the configuration for virtual channel a.
(default=4 configures this channel for the
voltage at A0 with respect to GND)
cha_datarate Set the datarate (samples/sec) for this channel.
(default=7 sets 860 sps)
cha_gain Set the gain of the Programmable Gain
Amplifier for this channel. (Default 1 sets the
full scale of the channel to 4.096 Volts)

Channel parameters can be set for each enabled channel.


A maximum of 4 channels can be enabled (letters a thru d).
For more information refer to the device datasheet at:
http://www.ti.com/lit/ds/symlink/ads1115.pdf

-----------------------------------------------------------------------------------
-----------
Name: ads7846
Info: ADS7846 Touch controller
Load: dtoverlay=ads7846,<param>=<val>

Parametri:
cs SPI bus Chip Select (default 1)
speed SPI bus speed (default 2MHz, max 3.25MHz)
penirq GPIO used for PENIRQ. REQUIRED
penirq_pull Set GPIO pull (default 0=none, 2=pullup)
swapxy Swap x and y axis
xmin Minimum value on the X axis (default 0)
ymin Minimum value on the Y axis (default 0)
xmax Maximum value on the X axis (default 4095)
ymax Maximum value on the Y axis (default 4095)
pmin Minimum reported pressure value (default 0)
pmax Maximum reported pressure value (default 65535)
xohms Touchpanel sensitivity (X-plate resistance)
(default 400)

penirq is required and usually xohms (60-100) has to be set as well.


Apart from that, pmax (255) and swapxy are also common.
The rest of the calibration can be done with xinput-calibrator.
See: github.com/notro/fbtft/wiki/FBTFT-on-Raspian
Device Tree binding document:
www.kernel.org/doc/Documentation/devicetree/bindings/input/ads7846.txt
-----------------------------------------------------------------------------------
-----------
Name: akkordion-iqdacplus
Info: Configures the Digital Dreamtime Akkordion Music Player (based on the
OEM IQAudIO DAC+ or DAC Zero module).
Load: dtoverlay=akkordion-iqdacplus,<param>=<val>

Parametri:
24db_digital_gain Allow gain to be applied via the PCM512x codec
Digital volume control. Enable with
dtoverlay=akkordion-iqdacplus,24db_digital_gain
(The default behaviour is that the Digital
volume control is limited to a maximum of
0dB. ie. it can attenuate but not provide
gain. For most users, this will be desired
as it will prevent clipping. By appending
the 24db_digital_gain parameter, the Digital
volume control will allow up to 24dB of
gain. If this parameter is enabled, it is the
responsibility of the user to ensure that
the Digital volume control is set to a value
that does not result in clipping/distortion!)

-----------------------------------------------------------------------------------
-----------
Name: allo-boss-dac-pcm512x-audio
Info: Configures the Allo Boss DAC audio cards.
Load: dtoverlay=allo-boss-dac-pcm512x-audio,<param>

Parametri:
24db_digital_gain Allow gain to be applied via the PCM512x codec
Digital volume control. Enable with
"dtoverlay=allo-boss-dac-pcm512x-audio,
24db_digital_gain"
(The default behaviour is that the Digital
volume control is limited to a maximum of
0dB. ie. it can attenuate but not provide
gain. For most users, this will be desired
as it will prevent clipping. By appending
the 24db_digital_gain parameter, the Digital
volume control will allow up to 24dB of
gain. If this parameter is enabled, it is the
responsibility of the user to ensure that
the Digital volume control is set to a value
that does not result in clipping/distortion!)
slave Force Boss DAC into slave mode, using Pi a
master for bit clock and frame clock. Enable
with "dtoverlay=allo-boss-dac-pcm512x-audio,
slave"

-----------------------------------------------------------------------------------
-----------
Name: allo-digione
Info: Configures the Allo Digione audio card
Load: dtoverlay=allo-digione

Parametri:
<None>
-----------------------------------------------------------------------------------
-----------
Name: allo-piano-dac-pcm512x-audio
Info: Configures the Allo Piano DAC (2.0/2.1) audio cards.
(NB. This initial support is for 2.0 channel audio ONLY! ie. stereo.
The subwoofer outputs on the Piano 2.1 are not currently supported!)
Load: dtoverlay=allo-piano-dac-pcm512x-audio,<param>

Parametri:
24db_digital_gain Allow gain to be applied via the PCM512x codec
Digital volume control.
(The default behaviour is that the Digital
volume control is limited to a maximum of
0dB. ie. it can attenuate but not provide
gain. For most users, this will be desired
as it will prevent clipping. By appending
the 24db_digital_gain parameter, the Digital
volume control will allow up to 24dB of
gain. If this parameter is enabled, it is the
responsibility of the user to ensure that
the Digital volume control is set to a value
that does not result in clipping/distortion!)

-----------------------------------------------------------------------------------
-----------
Name: allo-piano-dac-plus-pcm512x-audio
Info: Configures the Allo Piano DAC (2.1) audio cards.
Load: dtoverlay=allo-piano-dac-plus-pcm512x-audio,<param>

Parametri:
24db_digital_gain Allow gain to be applied via the PCM512x codec
Digital volume control.
(The default behaviour is that the Digital
volume control is limited to a maximum of
0dB. ie. it can attenuate but not provide
gain. For most users, this will be desired
as it will prevent clipping. By appending
the 24db_digital_gain parameter, the Digital
volume control will allow up to 24dB of
gain. If this parameter is enabled, it is the
responsibility of the user to ensure that
the Digital volume control is set to a value
that does not result in clipping/distortion!)
glb_mclk This option is only with Kali board. If enabled,
MCLK for Kali is used and PLL is disabled for
better voice quality. (default Off)

-----------------------------------------------------------------------------------
-----------
Name: applepi-dac
Info: Configures the Orchard Audio ApplePi-DAC audio card
Load: dtoverlay=applepi-dac
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: at86rf233
Info: Configures the Atmel AT86RF233 802.15.4 low-power WPAN transceiver,
connected to spi0.0
Load: dtoverlay=at86rf233,<param>=<val>

Parametri:
interrupt GPIO used for INT (default 23)
reset GPIO used for Reset (default 24)
sleep GPIO used for Sleep (default 25)
speed SPI bus speed in Hz (default 3000000)
trim Fine tuning of the internal capacitance
arrays (0=+0pF, 15=+4.5pF, default 15)

-----------------------------------------------------------------------------------
-----------
Name: audioinjector-addons
Info: Configures the audioinjector.net audio add on soundcards
Load: dtoverlay=audioinjector-addons
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: audioinjector-wm8731-audio
Info: Configures the audioinjector.net audio add on soundcard
Load: dtoverlay=audioinjector-wm8731-audio
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: audremap
Info: Switches PWM sound output to pins 12 (Right) & 13 (Left)
Load: dtoverlay=audremap,<param>=<val>

Parametri:
swap_lr Reverse the channel allocation, which will also
swap the audio jack outputs (default off)
enable_jack Don't switch off the audio jack output
(default off)

-----------------------------------------------------------------------------------
-----------
Name: bmp085_i2c-sensor
Info: This overlay is now deprecated - see i2c-sensor
Load: dtoverlay=bmp085_i2c-sensor
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: dht11
Info: Overlay for the DHT11/DHT21/DHT22 humidity/temperature sensors
Also sometimes found with the part number(s) AM230x.
Load: dtoverlay=dht11,<param>=<val>

Parametri:
gpiopin GPIO connected to the sensor's DATA output.
(default 4)

-----------------------------------------------------------------------------------
-----------
Name: dionaudio-loco
Info: Configures the Dion Audio LOCO DAC-AMP
Load: dtoverlay=dionaudio-loco
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: dionaudio-loco-v2
Info: Configures the Dion Audio LOCO-V2 DAC-AMP
Load: dtoverlay=dionaudio-loco-v2,<param>=<val>

Parametri:
24db_digital_gain Allow gain to be applied via the PCM512x codec
Digital volume control. Enable with
"dtoverlay=hifiberry-dacplus,24db_digital_gain"
(The default behaviour is that the Digital
volume control is limited to a maximum of
0dB. ie. it can attenuate but not provide
gain. For most users, this will be desired
as it will prevent clipping. By appending
the 24dB_digital_gain parameter, the Digital
volume control will allow up to 24dB of
gain. If this parameter is enabled, it is the
responsibility of the user to ensure that
the Digital volume control is set to a value
that does not result in clipping/distortion!)

-----------------------------------------------------------------------------------
-----------
Name: dpi18
Info: Overlay for a generic 18-bit DPI display
This uses GPIOs 0-21 (so no I2C, uart etc.), and activates the output
2-3 seconds after the kernel has started.
Load: dtoverlay=dpi18
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: dpi24
Info: Overlay for a generic 24-bit DPI display
This uses GPIOs 0-27 (so no I2C, uart etc.), and activates the output
2-3 seconds after the kernel has started.
Load: dtoverlay=dpi24
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: dwc-otg
Info: Selects the dwc_otg USB controller driver which has fiq support. This
is the default on all except the Pi Zero which defaults to dwc2.
Load: dtoverlay=dwc-otg
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: dwc2
Info: Selects the dwc2 USB controller driver
Load: dtoverlay=dwc2,<param>=<val>

Parametri:
dr_mode Dual role mode: "host", "peripheral" or "otg"
g-rx-fifo-size Size of rx fifo size in gadget mode

g-np-tx-fifo-size Size of non-periodic tx fifo size in gadget


mode

-----------------------------------------------------------------------------------
-----------
[ The ds1307-rtc overlay has been deleted. See i2c-rtc. ]

-----------------------------------------------------------------------------------
-----------
Name: enc28j60
Info: Overlay for the Microchip ENC28J60 Ethernet Controller on SPI0
Load: dtoverlay=enc28j60,<param>=<val>
Params: int_pin GPIO used for INT (default 25)

speed SPI bus speed (default 12000000)

-----------------------------------------------------------------------------------
-----------
Name: enc28j60-spi2
Info: Overlay for the Microchip ENC28J60 Ethernet Controller on SPI2
Load: dtoverlay=enc28j60-spi2,<param>=<val>

Parametri:
int_pin GPIO used for INT (default 39)

speed SPI bus speed (default 12000000)

-----------------------------------------------------------------------------------
-----------
Name: fe-pi-audio
Info: Configures the Fe-Pi Audio Sound Card
Load: dtoverlay=fe-pi-audio
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: goodix
Info: Enables I2C connected Goodix gt9271 multiple touch controller using
GPIOs 4 and 17 (pins 7 and 11 on GPIO header) for interrupt and reset.
Load: dtoverlay=goodix,<param>=<val>

Parametri:
interrupt GPIO used for interrupt (default 4)
reset GPIO used for reset (default 17)

-----------------------------------------------------------------------------------
-----------
Name: googlevoicehat-soundcard
Info: Configures the Google voiceHAT soundcard
Load: dtoverlay=googlevoicehat-soundcard
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: gpio-ir
Info: Use GPIO pin as rc-core style infrared receiver input. The rc-core-
based gpio_ir_recv driver maps received keys directly to a
/dev/input/event* device, all decoding is done by the kernel - LIRC is
not required! The key mapping and other decoding parameters can be
configured by "ir-keytable" tool.
Load: dtoverlay=gpio-ir,<param>=<val>
Params:
gpio_pin Input pin number. Default is 18.
gpio_pull Desired pull-up/down state (off, down, up) Default is
"down".
rc-map-name Default rc keymap (can also be changed byir-keytable),
defaults to "rc-rc6-mce"

-----------------------------------------------------------------------------------
-----------
Name: gpio-poweroff
Info: Drives a GPIO high or low on poweroff (including halt). Enabling this
overlay will prevent the ability to boot by driving GPIO3 low.
Load: dtoverlay=gpio-poweroff,<param>=<val>

Parametri:
gpiopin GPIO for signalling (default 26)

active_low Set if the power control device requires a


high->low transition to trigger a power-down.
Note that this will require the support of a
custom dt-blob.bin to prevent a power-down
during the boot process, and that a reboot
will also cause the pin to go low.

-----------------------------------------------------------------------------------
-----------
Name: gpio-shutdown
Info: Initiates a shutdown when GPIO pin changes.
The given GPIO pin is configured as an input key that generates
KEY_POWER events.
This event is handled by systemd-logind by initiating a shutdown.
Systemd versions older than 225 need an udev rule enable listening to
the input device:

ACTION!="REMOVE", SUBSYSTEM=="input", KERNEL=="event*", \


SUBSYSTEMS=="platform", DRIVERS=="gpio-keys", \
ATTRS{keys}=="116", TAG+="power-switch"

This overlay only handles shutdown.


After shutdown, the system can be powered up again by driving GPIO3 low.
The default configuration uses GPIO3 with a pullup, so if you connect a
button between GPIO3 and GND (pin 5 and 6 on the 40-pin header),
you get a shutdown and power-up button.
Load: dtoverlay=gpio-shutdown,<param>=<val>

Parametri:

gpio_pin GPIO pin to trigger on (default 3)


active_low When this is 1 (active low), a falling
edge generates a key down event and a
rising edge generates a key up event.
When this is 0 (active high), this is
reversed. The default is 1 (active low).

gpio_pull Desired pull-up/down state (off, down, up)


Default is "up".

Note that the default pin (GPIO3) has an external pullup.

-----------------------------------------------------------------------------------
-----------
Name: hifiberry-amp
Info: Configures the HifiBerry Amp and Amp+ audio cards
Load: dtoverlay=hifiberry-amp
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: hifiberry-dac
Info: Configures the HifiBerry DAC audio card
Load: dtoverlay=hifiberry-dac
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: hifiberry-dacplus
Info: Configures the HifiBerry DAC+ audio card
Load: dtoverlay=hifiberry-dacplus,<param>=<val>

Parametri:
24db_digital_gain Allow gain to be applied via the PCM512x codec
Digital volume control. Enable with
"dtoverlay=hifiberry-dacplus,24db_digital_gain"
(The default behaviour is that the Digital
volume control is limited to a maximum of
0dB. ie. it can attenuate but not provide
gain. For most users, this will be desired
as it will prevent clipping. By appending
the 24dB_digital_gain parameter, the Digital
volume control will allow up to 24dB of
gain. If this parameter is enabled, it is the
responsibility of the user to ensure that
the Digital volume control is set to a value
that does not result in clipping/distortion!)
slave Force DAC+ Pro into slave mode, using Pi as
master for bit clock and frame clock.

-----------------------------------------------------------------------------------
-----------
Name: hifiberry-digi
Info: Configures the HifiBerry Digi and Digi+ audio card
Load: dtoverlay=hifiberry-digi
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: hifiberry-digi-pro
Info: Configures the HifiBerry Digi+ Pro audio card
Load: dtoverlay=hifiberry-digi-pro
Params: <None>
-----------------------------------------------------------------------------------
-----------
Name: hy28a
Info: HY28A - 2.8" TFT LCD Display Module by HAOYU Electronics
Default values match Texy's display shield
Load: dtoverlay=hy28a,<param>=<val>
Params:
speed Display SPI bus speed
rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}
xohms Touchpanel sensitivity (X-plate resistance)
resetgpio GPIO used to reset controller
ledgpio GPIO used to control backlight

-----------------------------------------------------------------------------------
-----------
Name: hy28b
Info: HY28B - 2.8" TFT LCD Display Module by HAOYU Electronics
Default values match Texy's display shield
Load: dtoverlay=hy28b,<param>=<val>
Params:

speed Display SPI bus speed


rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}
xohms Touchpanel sensitivity (X-plate resistance)
resetgpio GPIO used to reset controller
ledgpio GPIO used to control backlight

-----------------------------------------------------------------------------------
-----------
Name: i2c-bcm2708
Info: Fall back to the i2c_bcm2708 driver for the i2c_arm bus.
Load: dtoverlay=i2c-bcm2708
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: i2c-gpio
Info: Adds support for software i2c controller on gpio pins
Load: dtoverlay=i2c-gpio,<param>=<val>

Parametri:
i2c_gpio_sda GPIO used for I2C data (default "23")

i2c_gpio_scl GPIO used for I2C clock (default "24")

i2c_gpio_delay_us Clock delay in microseconds


(default "2" = ~100kHz)

-----------------------------------------------------------------------------------
-----------
Name: i2c-mux
Info: Adds support for a number of I2C bus multiplexers on i2c_arm
Load: dtoverlay=i2c-mux,<param>=<val>
Parametri:

pca9542 Select the NXP PCA9542 device


pca9545 Select the NXP PCA9545 device
pca9548 Select the NXP PCA9548 device
addr Change I2C address of the device (default 0x70)

[ The i2c-mux-pca9548a overlay has been deleted. See i2c-mux. ]

-----------------------------------------------------------------------------------
-----------
Name: i2c-pwm-pca9685a

Info: Adds support for an NXP PCA9685A I2C PWM controller on i2c_arm
Load: dtoverlay=i2c-pwm-pca9685a,<param>=<val>

Parametri:

addr I2C address of PCA9685A (default 0x40)

-----------------------------------------------------------------------------------
-----------
Name: i2c-rtc

Info: Adds support for a number of I2C Real Time Clock devices
Load: dtoverlay=i2c-rtc,<param>=<val>

Parametri:

abx80x Select one of the ABx80x family:


AB0801, AB0803, AB0804, AB0805,
AB1801, AB1803, AB1804, AB1805

ds1307 Select the DS1307 device


ds1339 Select the DS1339 device
ds3231 Select the DS3231 device
m41t62 Select the M41T62 device
mcp7940x Select the MCP7940x device
mcp7941x Select the MCP7941x device
pcf2127 Select the PCF2127 device
pcf8523 Select the PCF8523 device
pcf8563 Select the PCF8563 device
trickle-diode-type Diode type for trickle charge - "standard" or "schottky"
(ABx80x only)
trickle-resistor-ohms Resistor value for trickle charge (DS1339,ABx80x)
wakeup-source Specify that the RTC can be used as a wakeup source

-----------------------------------------------------------------------------------
-----------
Name: i2c-rtc-gpio
Info: Adds support for a number of I2C Real Time Clock devicesusing the
software i2c controller
Load: dtoverlay=i2c-rtc-gpio,<param>=<val>

Parametri:

abx80x Select one of the ABx80x family:


AB0801, AB0803, AB0804, AB0805,
AB1801, AB1803, AB1804, AB1805
ds1307 Select the DS1307 device
ds1339 Select the DS1339 device
ds3231 Select the DS3231 device
mcp7940x Select the MCP7940x device
mcp7941x Select the MCP7941x device
pcf2127 Select the PCF2127 device
pcf8523 Select the PCF8523 device
pcf8563 Select the PCF8563 device
trickle-diode-type Diode type for trickle charge - "standard" or"schottky"
(ABx80x only)
trickle-resistor-ohms Resistor value for trickle charge (DS1339, ABx80x)
wakeup-source Specify that the RTC can be used as a wakeup source
i2c_gpio_sda GPIO used for I2C data (default "23")
i2c_gpio_scl GPIO used for I2C clock (default "24")
i2c_gpio_delay_us Clock delay in microseconds (default "2" = ~100kHz)

-----------------------------------------------------------------------------------
-----------
Name: i2c-sensor
Info: Adds support for a number of I2C barometric pressure and temperature
sensors on i2c_arm
Load: dtoverlay=i2c-sensor,<param>=<val>

Parametri:
addr Set the address for the BME280, BMP280, TMP102,
HDC100X, LM75 or SHT3x

bme280 Select the Bosch Sensortronic BME280


Valid addresses 0x76-0x77, default 0x76
bmp085 Select the Bosch Sensortronic BMP085
bmp180 Select the Bosch Sensortronic BMP180
bmp280 Select the Bosch Sensortronic BMP280

Valid addresses 0x76-0x77, default 0x76

htu21 Select the HTU21 temperature and humidity sensor

lm75 Select the Maxim LM75 temperature sensor


Valid addresses 0x48-0x4f, default 0x4f

lm75addr Deprecated - use addr parameter instead

si7020 Select the Silicon Labs Si7013/20/21 humidity/temperature


sensor

tmp102 Select the Texas Instruments TMP102 temp sensor


Valid addresses 0x48-0x4b, default 0x48

hdc100x Select the Texas Instruments HDC100x temp sensor


Valid addresses 0x40-0x43, default 0x40

tsl4531 Select the AMS TSL4531 digital ambient light sensor

veml6070 Select the Vishay VEML6070 ultraviolet light sensor

sht3x Select the Sensiron SHT3x temperature and humidity sensor.


Valid addresses 0x44-0x45,default 0x44
-----------------------------------------------------------------------------------
-----------
Name: i2c0-bcm2708
Info: Enable the i2c_bcm2708 driver for the i2c0 bus.
Not all pin combinations are usable on all platforms.
Load: dtoverlay=i2c0-bcm2708,<param>=<val>

Parametri:

sda0_pin GPIO pin for SDA0 (deprecated - use pins_*)


scl0_pin GPIO pin for SCL0 (deprecated - use pins_*)
pins_0_1 Use pins 0 and 1 (default)
pins_28_29 Use pins 28 and 29
pins_44_45 Use pins 44 and 45
pins_46_47 Use pins 46 and 47

-----------------------------------------------------------------------------------
-----------
Name: i2c1-bcm2708
Info: Enable the i2c_bcm2708 driver for the i2c1 bus
Load: dtoverlay=i2c1-bcm2708,<param>=<val>

Parametri:
sda1_pin GPIO pin for SDA1 (2 or 44 - default 2)
scl1_pin GPIO pin for SCL1 (3 or 45 - default 3)
pin_func Alternative pin function (4 (alt0), 6 (alt2) - default 4)

-----------------------------------------------------------------------------------
-----------
Name: i2s-gpio28-31
Info: move I2S function block to GPIO 28 to 31
Load: dtoverlay=i2s-gpio28-31
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: iqaudio-dac
Info: Configures the IQaudio DAC audio card
Load: dtoverlay=iqaudio-dac,<param>

Parametri:
24db_digital_gain Allow gain to be applied via the PCM512x codec
Digital volume control. Enable with
"dtoverlay=iqaudio-dac,24db_digital_gain"
(The default behaviour is that the Digital
volume control is limited to a maximum of
0dB. ie. it can attenuate but not provide
gain. For most users, this will be desired
as it will prevent clipping. By appending
the 24db_digital_gain parameter, the Digital
volume control will allow up to 24dB of
gain. If this parameter is enabled, it is the
responsibility of the user to ensure that
the Digital volume control is set to a value
that does not result in clipping/distortion!)

-----------------------------------------------------------------------------------
-----------
Name: iqaudio-dacplus
Info: Configures the IQaudio DAC+ audio card
Load: dtoverlay=iqaudio-dacplus,<param>=<val>

Parametri:
24db_digital_gain Allow gain to be applied via the PCM512x codec
Digital volume control. Enable with
"dtoverlay=iqaudio-dacplus,24db_digital_gain"
(The default behaviour is that the Digital
volume control is limited to a maximum of
0dB. ie. it can attenuate but not provide
gain. For most users, this will be desired
as it will prevent clipping. By appending
the 24db_digital_gain parameter, the Digital
volume control will allow up to 24dB of
gain. If this parameter is enabled, it is the
responsibility of the user to ensure that
the Digital volume control is set to a value
that does not result in clipping/distortion!)
auto_mute_amp If specified, unmute/mute the IQaudIO amp when
starting/stopping audio playback.
unmute_amp If specified, unmute the IQaudIO amp once when
the DAC driver module loads.

-----------------------------------------------------------------------------------
-----------
Name: iqaudio-digi-wm8804-audio
Info: Configures the IQAudIO Digi WM8804 audio card
Load: dtoverlay=iqaudio-digi-wm8804-audio,<param>=<val>

Parametri:

card_name Override the default, "IQAudIODigi", card name.


dai_name Override the default, "IQAudIO Digi", dai name.
dai_stream_name Override the default, "IQAudIO Digi HiFi",
dai stream name.

-----------------------------------------------------------------------------------
-----------
Name: justboom-dac
Info: Configures the JustBoom DAC HAT, Amp HAT, DAC Zero and Amp
Zero audio cards
Load: dtoverlay=justboom-dac,<param>=<val>

Parametri:

24db_digital_gain Allow gain to be applied via the PCM512x codec


Digital volume control. Enable with "dtoverlay=justboom-dac,24db_digital_gain"
(The default behaviour is that the Digital volume control is limited to a maximum
of
0dB. ie. it can attenuate but not provide gain.
For most users, this will be desired as it will prevent clipping.
By appending the 24dB_digital_gain parameter, the Digital volume control
will allow up to 24dB of gain. If this parameter is enabled, it is the
responsibility
of the user to ensure that the Digital volume control is set to a value
that does not result in clipping/distortion!)

-----------------------------------------------------------------------------------
-----------
Name: justboom-digi
Info: Configures the JustBoom Digi HAT and Digi Zero audio cards
Load: dtoverlay=justboom-digi
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: lirc-rpi
Info: Configures lirc-rpi (Linux Infrared Remote Control for Raspberry Pi)
Consult the module documentation for more details.
Load: dtoverlay=lirc-rpi,<param>=<val>

Parametri:
gpio_out_pin GPIO for output (default "17")
gpio_in_pin GPIO for input (default "18")
gpio_in_pull Pull up/down/off on the input pin (default "down")
sense Override the IR receive auto-detection logic:
"0" = force active-high
"1" = force active-low
"-1" = use auto-detection (default "-1")

softcarrier Turn the software carrier "on" or "off" (default "on")


invert "on" = invert the output pin (default "off")
debug "on" = enable additional debug messages (default "off")

-----------------------------------------------------------------------------------
-----------
Name: mcp23017
Info: Configures the MCP23017 I2C GPIO expander
Load: dtoverlay=mcp23017,<param>=<val>

Parametri:
gpiopin Gpio pin connected to the INTA output of the
MCP23017 (default: 4)

addr I2C address of the MCP23017 (default: 0x20)

-----------------------------------------------------------------------------------
-----------
Name: mcp23s17
Info: Configures the MCP23S08/17 SPI GPIO expanders.
If devices are present on SPI1 or SPI2, those interfaces must be enabled
with one of the spi1-1/2/3cs and/or spi2-1/2/3cs overlays.
If interrupts are enabled for a device on a given CS# on a SPI bus, that
device must be the only one present on that SPI bus/CS#.
Load: dtoverlay=mcp23s17,<param>=<val>

Parametri:

s08-spi<n>-<m>-present 4-bit integer, bitmap indicating MCP23S08


devices present on SPI<n>, CS#<m>

s17-spi<n>-<m>-present 8-bit integer, bitmap indicating MCP23S17


devices present on SPI<n>, CS#<m>

s08-spi<n>-<m>-int-gpio integer, enables interrupts on a single


MCP23S08 device on SPI<n>, CS#<m>, specifies
the GPIO pin to which INT output of MCP23S08
is connected.
s17-spi<n>-<m>-int-gpio integer, enables mirrored interrupts on a
single MCP23S17 device on SPI<n>, CS#<m>,
specifies the GPIO pin to which either INTA
or INTB output of MCP23S17 is connected.

-----------------------------------------------------------------------------------
-----------
Name: mcp2515-can0
Info: Configures the MCP2515 CAN controller on spi0.0
Load: dtoverlay=mcp2515-can0,<param>=<val>

Parametri:

oscillator Clock frequency for the CAN controller (Hz)


spimaxfrequency Maximum SPI frequence (Hz)
interrupt GPIO for interrupt signal

-----------------------------------------------------------------------------------
-----------
Name: mcp2515-can1
Info: Configures the MCP2515 CAN controller on spi0.1
Load: dtoverlay=mcp2515-can1,<param>=<val>

Parametri:

oscillator Clock frequency for the CAN controller (Hz)


spimaxfrequency Maximum SPI frequence (Hz)
interrupt GPIO for interrupt signal

-----------------------------------------------------------------------------------
-----------
Name: mcp3008
Info: Configures MCP3008 A/D converters
For devices on spi1 or spi2, the interfaces should be enabled
with one of the spi1-1/2/3cs and/or spi2-1/2/3cs overlays.
Load: dtoverlay=mcp3008,<param>[=<val>]

Parametri:

spi<n>-<m>-present boolean, configure device at spi<n>, cs<m>


spi<n>-<m>-speed integer, set the spi bus speed for this device

-----------------------------------------------------------------------------------
-----------
Name: midi-uart0
Info: Configures UART0 (ttyAMA0) so that a requested 38.4kbaud actually
gets 31.25kbaud, the frequency required for MIDI
Load: dtoverlay=midi-uart0
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: midi-uart1
Info: Configures UART1 (ttyS0) so that a requested 38.4kbaud actually gets
31.25kbaud, the frequency required for MIDI
Load: dtoverlay=midi-uart1
Params: <None>
-----------------------------------------------------------------------------------
-----------
Name: mmc
Info: Selects the bcm2835-mmc SD/MMC driver, optionally with overclock
Load: dtoverlay=mmc,<param>=<val>

Parametri:
overclock_50
Clock (in MHz) to use when the MMC framework requests 50MHz

-----------------------------------------------------------------------------------
-----------
Name: mpu6050
Info: Overlay for i2c connected mpu6050 imu
Load: dtoverlay=mpu6050,<param>=<val>

Parametri:
interrupt GPIO pin for interrupt (default 4)

-----------------------------------------------------------------------------------
-----------
Name: mz61581
Info: MZ61581 display by Tontec
Load: dtoverlay=mz61581,<param>=<val>

Parametri:

speed Display SPI bus speed


rotate Display rotation {0,90,180,270}
fps Delay between frame updates
txbuflen Transmit buffer length (default 32768)
debug Debug output level {0-7}
xohms Touchpanel sensitivity (X-plate resistance)

-----------------------------------------------------------------------------------
-----------
Name: papirus
Info: PaPiRus ePaper Screen by Pi Supply (both HAT and pHAT)
Load: dtoverlay=papirus,<param>=<val>

Parametri:
panel Display panel (required):
1.44": e1144cs021
2.0": e2200cs021
2.7": e2271cs021

speed Display SPI bus speed

[ The pcf2127-rtc overlay has been deleted. See i2c-rtc. ]


[ The pcf8523-rtc overlay has been deleted. See i2c-rtc. ]
[ The pcf8563-rtc overlay has been deleted. See i2c-rtc. ]

-----------------------------------------------------------------------------------
-----------
Name: pi3-act-led

Info: Pi3 uses a GPIO expander to drive the LEDs which can only be accessed
from the VPU. There is a special driver for this with a separate DT
node, which has the unfortunate consequence of breaking the
act_led_gpio and act_led_activelow dtparams.
This overlay changes the GPIO controller back to the standard one and
restores the dtparams.
Load: dtoverlay=pi3-act-led,<param>=<val>

Parametri:
activelow Set to "on" to invert the sense of the LED
(default "off")

gpio Set which GPIO to use for the activity LED


(in case you want to connect it to an external
device)
REQUIRED

-----------------------------------------------------------------------------------
-----------
Name: pi3-disable-bt

Info: Disabilita Pi3 Bluetooth e restora UART0/ttyAMA0 su GPIOs 14 & 15


N.B. Per disabilitare il servizio systemd che inizializza il modem
in modo che tal UART non sia utilizzata, utilizzare il comando:
systemctl disable hciuart
Load: dtoverlay=pi3-disable-bt
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: pi3-disable-wifi

Info: Disable Pi3 onboard WiFi


Load: dtoverlay=pi3-disable-wifi
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: pi3-miniuart-bt

Info: Switch Pi3 Bluetooth function to use the mini-UART (ttyS0) and restore
UART0/ttyAMA0 over GPIOs 14 & 15.
Note that this may reduce the maximum usable baudrate.
N.B. It is also necessary to edit /lib/systemd/system/hciuart.service
and replace ttyAMA0 with ttyS0, unless you have a system with udev rules
that create /dev/serial0 and /dev/serial1, in which case use /dev/serial1
instead because it will always be correct. Furthermore, you must also
set core_freq=250 in config.txt or the miniuart will not work.
Load: dtoverlay=pi3-miniuart-bt
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: piscreen

Info: PiScreen display by OzzMaker.com


Load: dtoverlay=piscreen,<param>=<val>
Params:
speed Display SPI bus speed
rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}
xohms Touchpanel sensitivity (X-plate resistance)

-----------------------------------------------------------------------------------
-----------
Name: piscreen2r

Info: PiScreen 2 with resistive TP display by OzzMaker.com


Load: dtoverlay=piscreen2r,<param>=<val>

Parametri:

speed Display SPI bus speed


rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}
xohms Touchpanel sensitivity (X-plate resistance)

-----------------------------------------------------------------------------------
-----------
Name: pisound
Info: Configures the Blokas Labs pisound card
Load: dtoverlay=pisound
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: pitft22
Info: Adafruit PiTFT 2.2" screen
Load: dtoverlay=pitft22,<param>=<val>

Parametri:
speed Display SPI bus speed
rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}

-----------------------------------------------------------------------------------
-----------
Name: pitft28-capacitive
Info: Adafruit PiTFT 2.8" capacitive touch screen
Load: dtoverlay=pitft28-capacitive,<param>=<val>
Params:

speed Display SPI bus speed


rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}
touch-sizex Touchscreen size x (default 240)
touch-sizey Touchscreen size y (default 320)
touch-invx Touchscreen inverted x axis
touch-invy Touchscreen inverted y axis
touch-swapxy Touchscreen swapped x y axis

-----------------------------------------------------------------------------------
-----------
Name: pitft28-resistive
Info: Adafruit PiTFT 2.8" resistive touch screen
Load: dtoverlay=pitft28-resistive,<param>=<val>
Params:

speed Display SPI bus speed


rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}

-----------------------------------------------------------------------------------
-----------
Name: pitft35-resistive
Info: Adafruit PiTFT 3.5" resistive touch screen
Load: dtoverlay=pitft35-resistive,<param>=<val>

Params:

speed Display SPI bus speed


rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}

-----------------------------------------------------------------------------------
-----------
Name: pps-gpio
Info: Configures the pps-gpio (pulse-per-second time signal via GPIO).
Load: dtoverlay=pps-gpio,<param>=<val>

Params:

gpiopin Input GPIO (default "18")


assert_falling_edge When present, assert is indicated by a falling edge,
rather than by a rising edge

-----------------------------------------------------------------------------------
-----------
Name: pwm
Info: Configures a single PWM channel Legal pin,function combinations
for each channel:

PWM0: 12,4(Alt0) 18,2(Alt5) 40,4(Alt0) 52,5(Alt1)


PWM1: 13,4(Alt0) 19,2(Alt5) 41,4(Alt0) 45,4(Alt0) 53,5(Alt1)

N.B.:

1) Pin 18 is the only one available on all platforms, and


it is the one used by the I2S audio interface.
Pins 12 and 13 might be better choices on an A+, B+ or Pi2.
2) The onboard analogue audio output uses both PWM channels.
3) So be careful mixing audio and PWM.
4) Currently the clock must have been enabled and configured
by other means.

Load: dtoverlay=pwm,<param>=<val>

Params:

pin Output pin (default 18) - see table


func Pin function (default 2 = Alt5) - see above
clock PWM clock frequency (informational)
-----------------------------------------------------------------------------------
-----------
Name: pwm-2chan

Info: Configures both PWM channels Legal pin,function combinations for


each channel:
PWM0: 12,4(Alt0) 18,2(Alt5) 40,4(Alt0) 52,5(Alt1)
PWM1: 13,4(Alt0) 19,2(Alt5) 41,4(Alt0) 45,4(Alt0) 53,5(Alt1)

N.B.:
1) Pin 18 is the only one available on all platforms, and
it is the one used by the I2S audio interface.
Pins 12 and 13 might be better choices on an A+, B+ or Pi2.
2) The onboard analogue audio output uses both PWM channels.
3) So be careful mixing audio and PWM.
4) Currently the clock must have been enabled and configured
by other means.

Load: dtoverlay=pwm-2chan,<param>=<val>

Params:

pin Output pin (default 18) - see table


pin2 Output pin for other channel (default 19)
func Pin function (default 2 = Alt5) - see above
func2 Function for pin2 (default 2 = Alt5)
clock PWM clock frequency (informational)

-----------------------------------------------------------------------------------
-----------
Name: qca7000
Info: I2SE's Evaluation Board for PLC Stamp micro
Load: dtoverlay=qca7000,<param>=<val>
Params:

int_pin GPIO pin for interrupt signal (default 23)


speed SPI bus speed (default 12 MHz)

-----------------------------------------------------------------------------------
-----------
Name: raspidac3
Info: Configures the RaspiDAV Rev.3x audio card
Load: dtoverlay=raspidac3
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: rotary-encoder
Info: Overlay for GPIO connected rotary encoder.
Load: dtoverlay=rotary-encoder,<param>=<val>

Params:

rotary0_pin_a GPIO connected to rotary encoder channel A (default 4).


rotary0_pin_b GPIO connected to rotary encoder channel B (default 17).

-----------------------------------------------------------------------------------
-----------
Name: rpi-backlight
Info: Raspberry Pi official display backlight driver
Load: dtoverlay=rpi-backlight
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: rpi-cirrus-wm5102
Info: Configures the Cirrus Logic Audio Card
Load: dtoverlay=rpi-cirrus-wm5102
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: rpi-dac
Info: Configures the RPi DAC audio card
Load: dtoverlay=rpi-dac
Params: <None>

Name: rpi-display
Info: RPi-Display - 2.8" Touch Display by Watterott
Load: dtoverlay=rpi-display,<param>=<val>
Params:
speed Display SPI bus speed
rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}
xohms Touchpanel sensitivity (X-plate resistance)
swapxy Swap x and y axis

-----------------------------------------------------------------------------------
-----------
Name: rpi-ft5406
Info: Official Raspberry Pi display touchscreen
Load: dtoverlay=rpi-ft5406
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: rpi-proto
Info: Configures the RPi Proto audio card
Load: dtoverlay=rpi-proto
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: rpi-sense
Info: Raspberry Pi Sense HAT
Load: dtoverlay=rpi-sense
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: rpi-tv
Info: Raspberry Pi TV HAT
Load: dtoverlay=rpi-tv
Params: <None>
-----------------------------------------------------------------------------------
-----------
Name: rra-digidac1-wm8741-audio
Info: Configures the Red Rocks Audio DigiDAC1 soundcard
Load: dtoverlay=rra-digidac1-wm8741-audio
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: sc16is750-i2c
Info: Overlay for the NXP SC16IS750 UART with I2C Interface
Enables the chip on I2C1 at 0x48. To select another address,
please refer to table 10 in reference manual.

Load: dtoverlay=sc16is750-i2c,<param>=<val>
Params:
int_pin GPIO used for IRQ (default 24)
addr Address (default 0x48)

-----------------------------------------------------------------------------------
-----------
Name: sc16is752-spi1
Info: Overlay for the NXP SC16IS752 Dual UART with SPI Interface
Enables the chip on SPI1.
N.B.: spi1 is only accessible on devices with a 40pin header, eg:
A+, B+, Zero and PI2 B; as well as the Compute Module.

Load: dtoverlay=sc16is752-spi1,<param>=<val>
Params:

int_pin GPIO used for IRQ (default 24)

-----------------------------------------------------------------------------------
-----------
Name: sdhost
Info: Selects the bcm2835-sdhost SD/MMC driver, optionally with overclock.
N.B. This overlay is designed for situations where the mmc driver is
the default, so it disables the other (mmc) interface - this will kill
WiFi on a Pi3. If this isn't what you want, either use the sdtweak
overlay or the new sd_* dtparams of the base DTBs.
Load: dtoverlay=sdhost,<param>=<val>

Params:
overclock_50 Clock (in MHz) to use when the MMC framework
requests 50MHz
force_pio Disable DMA support (default off)
pio_limit Number of blocks above which to use DMA (default 1)
debug Enable debug output (default off)

-----------------------------------------------------------------------------------
-----------
Name: sdio
Info: Selects the bcm2835-sdhost SD/MMC driver, optionally with overclock,
and enables SDIO via GPIOs 22-27.
Load: dtoverlay=sdio,<param>=<val>

Params:

sdio_overclock SDIO Clock (in MHz) to use when the MMC


framework requests 50MHz
poll_once Disable SDIO-device polling every second
(default on: polling once at boot-time)
bus_width Set the SDIO host bus width (default 4 bits)

-----------------------------------------------------------------------------------
-----------
Name: sdio-1bit
Info: Selects the bcm2835-sdhost SD/MMC driver, optionally with overclock,
and enables 1-bit SDIO via GPIOs 22-25.
Load: dtoverlay=sdio-1bit,<param>=<val>
Params:

sdio_overclock SDIO Clock (in MHz) to use when the MMC framework
requests 50MHz
poll_once Disable SDIO-device polling every second
(default on: polling once at boot-
time)

-----------------------------------------------------------------------------------
-----------
Name: sdtweak
Info: Tunes the bcm2835-sdhost SD/MMC driver
N.B. This functionality is now available via the sd_* dtparams in the
base DTB.
Load: dtoverlay=sdtweak,<param>=<val>

Params:

overclock_50 Clock (in MHz) to use when the MMC framework requests 50MHz
force_pio Disable DMA support (default off)
pio_limit Number of blocks above which to use DMA (default 1)
debug Enable debug output (default off)

-----------------------------------------------------------------------------------
-----------
Name: smi
Info: Enables the Secondary Memory Interface peripheral. Uses GPIOs 2-25!
Load: dtoverlay=smi
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: smi-dev
Info: Enables the userspace interface for the SMI driver
Load: dtoverlay=smi-dev

Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: smi-nand
Info: Enables access to NAND flash via the SMI interface
Load: dtoverlay=smi-nand

Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: spi-gpio35-39
Info: Move SPI function block to GPIO 35 to 39
Load: dtoverlay=spi-gpio35-39

Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: spi-rtc
Info: Adds support for a number of SPI Real Time Clock devices
Load: dtoverlay=spi-rtc,<param>=<val>

Params:

pcf2123 Select the PCF2123 device

-----------------------------------------------------------------------------------
-----------
Name: spi0-cs
Info: Allows the (software) CS pins for SPI0 to be changed
Load: dtoverlay=spi0-cs,<param>=<val>

Params:

cs0_pin GPIO pin for CS0 (default 8)


cs1_pin GPIO pin for CS1 (default 7)

-----------------------------------------------------------------------------------
-----------
Name: spi0-hw-cs
Info: Re-enables hardware CS/CE (chip selects) for SPI0
Load: dtoverlay=spi0-hw-cs
Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: spi1-1cs
Info: Enables spi1 with a single chip select (CS) line and associated spidev
dev node. The gpio pin number for the CS line and spidev device node
creation are configurable.
N.B.: spi1 is only accessible on devices with a 40pin header, eg:
A+, B+, Zero and PI2 B; as well as the Compute Module.
Load: dtoverlay=spi1-1cs,<param>=<val>
Params:
cs0_pin GPIO pin for CS0 (default 18 - BCM SPI1_CE0).
cs0_spidev Set to 'disabled' to stop the creation of auserspace device
node /dev/spidev1.0 (default is 'okay' or enabled).

-----------------------------------------------------------------------------------
-----------
Name: spi1-2cs
Info: Enables spi1 with two chip select (CS) lines and associated spidev
dev nodes. The gpio pin numbers for the CS lines and spidev device node
creation are configurable.
N.B.: spi1 is only accessible on devices with a 40pin header, eg:
A+, B+, Zero and PI2 B; as well as the Compute Module.
Load: dtoverlay=spi1-2cs,<param>=<val>

Params:
cs0_pin GPIO pin for CS0 (default 18 - BCM SPI1_CE0).
cs1_pin GPIO pin for CS1 (default 17 - BCM SPI1_CE1).
cs0_spidev Set to 'disabled' to stop the creation of a
userspace device node /dev/spidev1.0 (default
is 'okay' or enabled).
cs1_spidev Set to 'disabled' to stop the creation of a
userspace device node /dev/spidev1.1 (default
is 'okay' or enabled).

-----------------------------------------------------------------------------------
-----------
Name: spi1-3cs
Info: Enables spi1 with three chip select (CS) lines and associated spidev
dev nodes. The gpio pin numbers for the CS lines and spidev device node
creation are configurable.
N.B.: spi1 is only accessible on devices with a 40pin header, eg:
A+, B+, Zero and PI2 B; as well as the Compute Module.
Load: dtoverlay=spi1-3cs,<param>=<val>

Params:

cs0_pin GPIO pin for CS0 (default 18 - BCM SPI1_CE0).


cs1_pin GPIO pin for CS1 (default 17 - BCM SPI1_CE1).
cs2_pin GPIO pin for CS2 (default 16 - BCM SPI1_CE2).
cs0_spidev Set to 'disabled' to stop the creation of auserspace device
node /dev/spidev1.0 (defaultis 'okay' or enabled).
cs1_spidev Set to 'disabled' to stop the creation of a userspace
device
node /dev/spidev1.1 (default is 'okay' or enabled).
cs2_spidev Set to 'disabled' to stop the creation of auserspace device
node /dev/spidev1.2 (default is 'okay' or enabled).

-----------------------------------------------------------------------------------
-----------
Name: spi2-1cs
Info: Enables spi2 with a single chip select (CS) line and associated spidev
dev node. The gpio pin number for the CS line and spidev device node
creation are configurable.
N.B.: spi2 is only accessible with the Compute Module.
Load: dtoverlay=spi2-1cs,<param>=<val>

Params:

cs0_pin GPIO pin for CS0 (default 43 - BCM SPI2_CE0).


cs0_spidev Set to 'disabled' to stop the creation of auserspace device
node /dev/spidev2.0 (default is 'okay' or enabled).

-----------------------------------------------------------------------------------
-----------
Name: spi2-2cs
Info: Enables spi2 with two chip select (CS) lines and associated spidev
dev nodes. The gpio pin numbers for the CS lines and spidev device node
creation are configurable.
N.B.: spi2 is only accessible with the Compute Module.
Load: dtoverlay=spi2-2cs,<param>=<val>

Params:
cs0_pin GPIO pin for CS0 (default 43 - BCM SPI2_CE0).
cs1_pin GPIO pin for CS1 (default 44 - BCM SPI2_CE1).
cs0_spidev Set to 'disabled' to stop the creation of a userspace
device node /dev/spidev2.0 (default is 'okay' or
enabled).
cs1_spidev Set to 'disabled' to stop the creation of a userspace
device
node /dev/spidev2.1 (default is 'okay' or enabled).

-----------------------------------------------------------------------------------
-----------
Name: spi2-3cs
Info: Enables spi2 with three chip select (CS) lines and associated spidev
dev nodes. The gpio pin numbers for the CS lines and spidev device node
creation are configurable.
N.B.: spi2 is only accessible with the Compute Module.
Load: dtoverlay=spi2-3cs,<param>=<val>

Params:

cs0_pin GPIO pin for CS0 (default 43 - BCM SPI2_CE0).


cs1_pin GPIO pin for CS1 (default 44 - BCM SPI2_CE1).
cs2_pin GPIO pin for CS2 (default 45 - BCM SPI2_CE2).
cs0_spidev Set to 'disabled' to stop the creation of a userspace device
node /dev/spidev2.0 (default is 'okay' or enabled).
cs1_spidev Set to 'disabled' to stop the creation of a userspace
device
node /dev/spidev2.1 (default is 'okay' or enabled).
cs2_spidev Set to 'disabled' to stop the creation of a userspace
device
node /dev/spidev2.2 (default is 'okay' or enabled).

-----------------------------------------------------------------------------------
-----------
Name: tinylcd35
Info: 3.5" Color TFT Display by www.tinylcd.com
Options: Touch, RTC, keypad
Load: dtoverlay=tinylcd35,<param>=<val>

Params:

speed Display SPI bus speed


rotate Display rotation {0,90,180,270}
fps Delay between frame updates
debug Debug output level {0-7}
touch Enable touch panel
touchgpio Touch controller IRQ GPIO
xohms Touchpanel: Resistance of X-plate in ohms
rtc-pcf PCF8563 Real Time Clock
rtc-ds DS1307 Real Time Clock
keypad Enable keypad

Examples:

Display with touchpanel, PCF8563 RTC and keypad:


dtoverlay=tinylcd35,touch,rtc-pcf,keypad

Old touch display:


dtoverlay=tinylcd35,touch,touchgpio=3
-----------------------------------------------------------------------------------
-----------
Name: uart1
Info: Enable uart1 in place of uart0
Load: dtoverlay=uart1,<param>=<val>

Params:

txd1_pin GPIO pin for TXD1 (14, 32 or 40 - default 14)


rxd1_pin GPIO pin for RXD1 (15, 33 or 41 - default 15)

-----------------------------------------------------------------------------------
-----------
Name: vc4-fkms-v3d
Info: Enable Eric Anholt's DRM VC4 V3D driver on top of the dispmanx
display stack.
Load: dtoverlay=vc4-fkms-v3d,<param>

Params:

cma-256 CMA is 256MB, 256MB-aligned (needs 1GB)


cma-192 CMA is 192MB, 256MB-aligned (needs 1GB)
cma-128 CMA is 128MB, 128MB-aligned
cma-96 CMA is 96MB, 128MB-aligned
cma-64 CMA is 64MB, 64MB-aligned

-----------------------------------------------------------------------------------
-----------
Name: vc4-kms-v3d
Info: Enable Eric Anholt's DRM VC4 HDMI/HVS/V3D driver. Running startx or
booting to GUI while this overlay is in use will cause interesting
lockups.
Load: dtoverlay=vc4-kms-v3d,<param>

Params:

cma-256 CMA is 256MB, 256MB-aligned (needs 1GB)


cma-192 CMA is 192MB, 256MB-aligned (needs 1GB)
cma-128 CMA is 128MB, 128MB-aligned
cma-96 CMA is 96MB, 128MB-aligned
cma-64 CMA is 64MB, 64MB-aligned

-----------------------------------------------------------------------------------
-----------
Name: vga666
Info: Overlay for the Fen Logic VGA666 board
This uses GPIOs 2-21 (so no I2C), and activates the output 2-3 seconds
after the kernel has started.
Load: dtoverlay=vga666

Params: <None>

-----------------------------------------------------------------------------------
-----------
Name: w1-gpio
Info: Configures the w1-gpio Onewire interface module.
Use this overlay if you *don't* need a GPIO to drive an external pullup.
Load: dtoverlay=w1-gpio,<param>=<val>
Params:
gpiopin GPIO for I/O (default "4")
pullup Non-zero, "on", or "y" to enable the parasitic power
(2-wire, power-on-data) feature

-----------------------------------------------------------------------------------
-----------
Name: w1-gpio-pullup
Info: Configures the w1-gpio Onewire interface module.
Use this overlay if you *do* need a GPIO to drive an external pullup.
Load: dtoverlay=w1-gpio-pullup,<param>=<val>
Params:

gpiopin GPIO for I/O (default "4")


pullup Non-zero, "on", or "y" to enable the parasitic power
(2-wire, power-on-data) feature
extpullup GPIO for external pullup (default "5")

-----------------------------------------------------------------------------------
-----------
Name: wittypi
Info: Configures the wittypi RTC module.
Load: dtoverlay=wittypi,<param>=<val>
Params:
led_gpio GPIO for LED (default "17")
led_trigger Choose which activity the LED tracks (default "default-on")

Troubleshooting
===============

If you are experiencing problems that you think are DT-related, enable DT
diagnostic output by adding this to /boot/config.txt:

dtdebug=on

and rebooting. Then run:

sudo vcdbg log msg

and look for relevant messages.

Further reading
=============

This is only meant to be a quick introduction to the subject of Device Tree on


Raspberry Pi. There is a more complete explanation here:

http://www.raspberrypi.org/documentation/configuration/device-tree.md
==============================================================
What is LIRC ?
==============================================================

http://www.lirc.org/

LIRC is a package that allows you to decode and send infra-red signals of
many (but not all) commonly used remote controls.

Recent linux kernels makes it possible to use some IR remote controls as


regular input devices. Sometimes this makes LIRC redundant.
However, LIRC offers more flexibility and functionality and is still the right
tool in a lot of scenarios.

The most important part of LIRC is the lircd daemon which decodes
IR signals received by the device drivers and provides the information on a
socket. It also accepts commands for IR signals to be sent if the hardware
supports this.

The user space applications allows you to control your computer with your
remote control. You can send X11 events to applications, start programs and
much more on just one button press.

The possible applications are obvious:

Infra-red mouse, remote control for your TV tuner card or CD-ROM,


shutdown by remote, program your VCR and/or satellite tuner with your
computer, etc. Using lirc on Raspberry Pie is quite popular these days.

Supported remote controls


----------------------------------

There are some config files for remote controls at the remotes database.
This is about 2500 devices and counting. These devices should work with
the general drivers or (if it lacks timing info) the driver used to create them.

If you can't find your remote control here it does not mean that your remote
control is not supported. It's just that there is no config file for it yet.
All remote controls that are supported by learning remote controls i.e.,
almost any, should also work with LIRC.

Supported capture devices


----------------------------------

Besides a remote control you also need a capture device to read the data
from the remote. Former versions focussed on home-brew capture hardware
connected to the serial or parallel port.

Descriptions how to build such hardware can be found here.

Current versions of LIRC also support a broad range of other hardware.


As a starter, you can use the kernel built-in support for many USB dongles
and similar. Besides this LIRC supports basically any conceivable way to
capture your data including serial devices, parallel ports, sound input etc.

You can see the complete list in the left pane.

Documentazione
http://www.lirc.org/html/index.html

Serve per ricevere l'input dal GPIO a cui ho connesso un IR Receiver

==============================================================
How to listen to Spotify on the Raspberry Pi
=================================================================

TOPICS:ChromiumRaspbianSpotify
How to listen to Spotify on the Raspberry Pi
POSTED BY: STEPHEN LOVELY JUNE 29, 2017

Raspbian is the dominant operating system on the Raspberry Pi, and for
good reason – it makes the tiny Raspberry Pi feel like a full-sized computer,
giving users access a web browser, utilities, and even games.

But Raspbian doesn’t support every program out of the box, and Spotify fans will be
disappointed to learn that their Raspberry Pi can’t play Spotify in the Chromium
web browser that comes standard on Raspbian. Luckily, we can perform a few tweaks
to make Spotify work on our Raspberry Pi and send music out over your choice of the
HDMI connection or the headphone jack, which is perfect for feeding into your
stereo system’s auxiliary input. Here’s how to listen to Spotify on the Raspberry
Pi.

How to listen to Spotify on the Raspberry Pi


For this project, you’ll need a Raspberry Pi and all of the basic peripherals: a
screen, a keyboard, a mouse, a power supply, and a microSD card. You’ll also need a
computer with an SD card slot. If you want to use the headphone jack to listen to
Spotify, you’ll need headphones or an aux cable.

We’ll be using Raspbian and the Chromium web browser in this project, but as we’ll
see, that’s not enough to start Spotify. What we have to do is download a specific
Chrome extension that will trick Spotify into thinking that we’re running
Microsoft’s Internet Explorer. With the help of this little white lie, Spotify will
work fine on Chromium.

Step 1: Install Raspbian


First things first: this entire project takes place on Raspbian, so grab the disk
image and put it on your microSD card. You can do this using the standard procedure
for installing any operating system on the Raspberry Pi. Don’t remember that
process? No problem – just check out our complete guide to installing Raspbian on
the Raspberry Pi.

Once you have Raspbian installed, you’ll have a great operating system that you can
use to perform basic computer functions (like word processing, web browsing, and
more) or as the starting point to any of the nearly countless Pi projects that use
Raspbian as their base. But one thing you won’t be able to do out of the box is use
the included Chromium web browser to access Spotify’s web player. If you try,
you’ll encounter a redirect or a screen that says: “Playback of protected content
is not enabled.”

Bummer! Luckily for us, though, we have three more steps left in which to right
this wrong. Let’s get started.

Step 2: Open Chromium and add the extension “User-Agent Switcher for Chrome”
Loyal readers will remember this extension from our guide to watching Netflix on
the Raspberry Pi. We’re using it for the same purpose this time around: we’ll be
tricking the website we want to use into thinking that we’re running one of their
supported browsers, even though we’re not. This is a Chrome extension, but like
many Chrome extensions, it works fine on the lighter-weight Chromium browser as
well.
Step 3: Pretend to be using Internet Explorer 10
Now we just need to choose our new “user agent” before we try to access Spotify’s
web player. Internet Explorer 10 will work, so let’s go ahead and do that: navigate
to Internet Explorer > Internet Explorer 10 in User-Agent Switcher for Chrome’s
settings.

Step 4: Listen to Spotify through your headphone jack or HDMI connection


Listening to Spotify on the Raspberry Pi

If you’re content to use the headphone jack, we’re really already done here! Now
that Spotify is blissfully unaware that we’re using the Chromium web browser, it
will play nice with us. By default, this project will send the audio out of your
Raspberry Pi’s headphone jack (rather than its HDMI port), which means you’ll have
to plug in an auxiliary cord or some headphones to enjoy your tunes. This makes it
perfect, though, for connecting to a larger stereo system!

If you want to use the HDMI connection instead, you just have one simple step left.
In your terminal, run the command sudo raspi-config. This will give you a menu in
your terminal window. Navigate to Advanced Options > A4 Audio > Choose the audio
output: 2 Force HDMI. That’s it!

==============================================================
Configurare un Cloud privato sul Raspberry Pi con ownCloud
==============================================================

L’utilizzo di uno spazio di archiviazione online tramite servizi cloud, come


Dropbox, Google Drive o
Amazon Drive, godono di una grande notorietà.
Grazie a questi servizi si possono salvare i dati su un Cloud e renderli
disponibili in ogni momento;
ciò di cui avete bisogno, oltre al software, è un computer o un dispositivo mobile
con accesso ad Internet.

La scelta di un provider per un Cloud hosting comporta però sempre alcune


riflessioni.
Viene spesso criticato che i clienti non sanno chi abbia accesso, oltre a loro, ai
dati salvati e se, dopo
aver disdetto il contratto, vengano anche davvero eliminate le informazioni dai
server del provider.
Questo punto è molto importante soprattutto per quanto riguarda l’archiviazione dei
dati sensibili.
Chi volesse mantenere il controllo completo dei suoi dati, allora farà meglio a
creare un Cloud privato
da gestire autonomamente.

In questo caso si può ricorrere a ownCloud, un software affermato, gratuito e


facile da usare.
Il Raspberry Pi rappresenta un’ottima soluzione, particolarmente indicata per
configurare ownCloud su
un server (host). Nel nostro tutorial scoprite cosa vi serve, oltre a questo mini
computer,
per realizzare il vostro Cloud e imparate ad impostarlo.

Indice

Perché utilizzare ownCloud sul Raspberry Pi?


Preparazione per realizzare un Cloud sul Raspberry Pi con ownCloud
Configurare ownCloud
Indicazioni per l’amministrazione
Perché utilizzare ownCloud sul Raspberry Pi?

ownCloud è un software gratuito per condividere i file, grazie al quale potete


creare uno spazio online personale. Tramite un’interfaccia web avete accesso ai
dati da ogni browser e potete anche caricare e scaricare i dati tramite desktop
client e app mobili (compresa la sincronizzazione dati). Oltre a funzionare come
file server, ownCloud presenta molte altre funzioni:

calendario e pianificazione degli appuntamenti;


rubrica dei contatti;
riproduzione di musica e video;
memorizzazione di file immagini, PDF e Microsoft Office;
editor per documenti OpenDocument;
gestione dei permessi degli utenti e dei gruppi.

Inoltre è possibile crittografare gli stessi dati, ma anche il processo di


trasferimento dei dati. ownCloud si presenta come un’alternativa interessante ai
grandi servizi Cloud e viene per questo apprezzato da molti utenti perché con il
software si salvano i dati su un server privato o sullo spazio web messo a
disposizione dal servizio e così, per poter avere accesso in ogni momento ai file,
non si memorizzano i file sugli hard disk di grandi aziende.

Per gestire i dati, vi servono un computer con il giusto software per il server,
con il quale trasferire i dati in rete. Ci sono molti motivi che sottolineano i
vantaggi dell’uso di un Raspberry Pi come host per ownCloud: da una parte il prezzo
di realizzazione per il computer e tutte le altre componenti è molto conveniente,
infatti difficilmente si troverà un miglior rapporto qualità-prezzo per un Cloud
gestito autonomamente. Dall’altra l’uso della corrente del piccolo computer è molto
basso, un punto senz’altro a favore per un server che dovrebbe rimanere sempre in
funzione.

In generale esistono molti diversi programmi e procedure tramite i quali si può


utilizzare un Raspberry Pi come host per ownCloud. Per il server con ownCloud
presentato di seguito, viene utilizzato un web server Apache nella versione 2
(Apache HTTP è ormai il server più utilizzato). Oltre al linguaggio di scripting
PHP 5 viene usato anche il database SQLite (rispetto ad altri database come quello
MySQL, SQLite ha il vantaggio di sfruttare meno le risorse del Raspberry Pi).

Preparazione per realizzare un Cloud sul Raspberry Pi con ownCloud


Per impostare un Cloud sul Raspberry Pi, oltre al mini PC, avete bisogno di un paio
di altri componenti. Inoltre dovete preventivamente applicare alcune impostazioni,
prima di cominciare con l’installazione e la configurazione vera e propria di
ownCloud 9.

Componenti necessari
-----------------

Un Raspberry Pi che funziona come server per ownCloud; si consiglia un Raspberry Pi


2 modello B o un modello più performante, perché altrimenti la velocità per
l’upload e il download dei file può risultare relativamente inferiore (ma ciò
dipende anche dal tasso di trasferimento dei dati della connessione Internet).

Una scheda microSD con uno spazio di archiviazione sufficiente (sono consigliati
almeno 8 GB). Di quanto spazio avete bisogno dipende ovviamente dal tipo e dalla
quantità di file che volete memorizzare e se volete immagazzinarli solo sulla
scheda o su un altro supporto collegato al Raspberry Pi. ownCloud può anche
utilizzare una memoria esterna su Internet (via FTP o WebDAV) e si possono pure
integrare altri servizi cloud come Dropbox o Amazon S3. In questo tutorial il
sistema operativo utilizzato è Raspbian Jessie, che deve essere installato sulla
scheda microSD. Se il vostro Raspberry Pi funziona ancora con la versione
precedente Wheezy, scaricate Jessie sul sito ufficiale, per seguire meglio questa
guida, e installatelo sul mini computer.
Una connessione ad Internet (meglio se tramite cavo di rete, altrimenti Wi-Fi).
Elettricità tramite cavo micro-USB.

L’uso di un altro supporto di memoria (un disco fisso esterno o una pen drive) è
opzionale, in quanto è essenziale solo per avere più spazio a disposizione per i
vostri file. Comunque deve essere configurato separatamente. Inoltre, in alcuni
casi, può essere utile una ventola o un refrigeratore passivo (meno potente e per
questo silenzioso), specialmente se praticate l’overcklocking sul piccolo computer
(possibile almeno nei modelli precedenti al Raspberry Pi 3 B). Ma anche se
utilizzate sempre il Raspberry Pi come host per ownCloud, un sistema di
raffreddamento non guasta.

Quasi come ogni server, anche quello presentato qui sotto può essere amministrato
“headless”, quindi senza schermo, tastiera o mouse. Dato che questa risulta la
soluzione più facile e a maggior risparmio energetico, è possibile apportare delle
modifiche al server tramite accesso SSH. Client SSH come WinSCP o PuTTY per Windows
e OpenSSH per i sistemi operativi UNIX consentono un pratico accesso remoto al
server dal computer o da uno smartphone: collegateli tra di loro, inserendo
l’indirizzo IPv4 nel client SSH del Raspberry Pi e attivando la connessione.

Configurare un indirizzo IP statico per il Raspberry Pi


--------------------------------------------
Per la maggior parte degli utenti conviene avere un Cloud privato, se l’host è
raggiungibile 24 ore su 24.
Solo così potete (ed eventualmente anche altri utenti) accedere ai vostri file
anche al di fuori della
vostra rete locale o caricarne di nuovi. Configurando un server locale, che deve
essere sempre raggiungibile,
solitamente si riscontra il seguente problema: la vostra connessione dispone solo
di un indirizzo IP dinamico,
che cambia generalmente dopo 24 ore. Perciò non è possibile garantire la
raggiungibilità del server allo stesso indirizzo.

Un indirizzo IP statico risolverebbe il problema, ma non è privo di costi e non


viene neanche offerto da
tutti i provider. Invece si può decidere di appoggiarsi ad un DNS dinamico (DDNS),
dove registrare un
nome di dominio e collegarlo con il vostro router o computer. Ciò è possibile
tramite un programma che
assegna automaticamente un nome di dominio all’indirizzo IP attuale della vostra
connessione e rende
così disponibile online il server permanentemente allo stesso nome.
Il DDNS viene offerto da diversi fornitori, a pagamento o gratuito. Se avete un
router Fritz!Box,
potete usarlo per il DDNS: qui la funzione di dynamic DNS è già preimpostata e deve
solo essere attivata.
Sulla pagina del router è spiegato come configurare un DDNS su Fritz!Box.

Se un Raspberry Pi è raggiungibile in rete ad uno stesso indirizzo tramite IP


statico o servizio DDNS,
potete accedere ad ownCloud comodamente dalla vostra rete. Ma anche in questo caso
può essere utile
un proprio file server, se ad esempio si volesse utilizzare la funzione di
sincronizzazione di tutti i file
presenti sul server.

Preparare il Raspberry Pi per l’installazione di ownCloud


--------------------------------------------
Prima di tutto dovreste assicurarvi che il vostro Raspberry Pi sia configurato
correttamente per l’uso come host con ownCloud. Per prima cosa dovreste
preoccuparvi di modificare il nome utente standard “Pi” e la password correlata
“Raspberry”, se non l’avete ancora fatto. Se si lasciano i dati di accesso
preimpostati, si incorre in un rischio per la sicurezza, visto che usando la
password standard, che si trova facilmente su Internet, chiunque potrebbe prendere
il controllo del server. Eseguite la modifica del nome utente e della password
tramite la configurazione del Raspberry Pi, che aprite nella console con il
seguente comando:

sudo raspi-config

Come accade prima di ogni installazione sul Raspberry Pi, anche per la
configurazione di ownCloud dovreste aggiornare il computer e i pacchetti
installati. Qui date i comandi corrispondenti dal terminale:

sudo apt-get update

sudo apt-get upgrade


Configurare ownCloud

Il Cloud privato sul Raspberry Pi non è composto solo dal software ownCloud, ma ci
sono anche diversi programmi che possono essere installati per gradi. Se non viene
specificato altro, inserite i comandi nella console del Raspberry Pi.

Installare Apache 2, PHP 5 e SQLite

Inizialmente si installa il server Apache HTTP tramite il comando seguente:

sudo apt-get install apache2

Per verificare se l’installazione del web server sia andata a buon fine, inserite
l’indirizzo IP del Raspberry Pi nella barra degli indirizzi del vostro browser: se
compare una pagina bianca con la frase “it works”, funziona tutto correttamente.

Per rendere raggiungibile il vostro ownCloud in rete, attivate sul vostro router il
port forwarding e inoltrate le richieste del router dalla porta 433 al Raspberry
Pi. Su ogni router funziona però diversamente, ma si possono trovare i giusti
tutorial per i diversi modelli. Una volta impostato correttamente il port
forwarding, il vostro Raspberry Pi è ora raggiungibile su Internet al suo indirizzo
IP (o al suo nome di dominio, qualora utilizziate il servizio DDNS). Senza il port
forwarding avete accesso solo alla rete locale sul web server.

Ora installate il PHP, SQLite e gli altri pacchetti necessari:

sudo apt-get install php5 php5-gd sqlite php5-sqlite php5-curl


Dopo aver terminato la configurazione di tutti i programmi, riavviate il web server
Apache:

sudo service apache2 restart

Installare ownCloud

Ora sono state prese tutte le misure necessarie per installare ownCloud sul
Raspberry Pi. Scaricate il software in formato .zip dalla sezione download del sito
ufficiale alla voce del menu “Archive File” e copiatelo sul Raspberry Pi.
Alternativamente potete installare il programma tramite la console, dove dovete
anche inserire la versione di ownCloud che vorreste impostare. In questo tutorial
viene utilizzato ownCloud 9.1.0.

wget https://download.owncloud.org/community/owncloud-9.1.0.zip

Potete installare un’altra versione, cambiando le cifre relative al nome della


versione ([…] community/owncloud-X.X.X.zip). L’ultima versione più stabile del
programma la trovate sempre nella sezione download di ownCloud, accedendo dal link
citato sopra.

Indipendentemente da quella che scegliate, dopo il download, dovete salvare e


decomprimere il file ownCloud-.zip nella giusta cartella:

sudo mv owncloud-9.0.4.zip /var/www/html


cd /var/www/html
sudo unzip -q owncloud-9.0.4.zip
Successivamente create una propria cartella per ownCloud e configurate i permessi:

sudo mkdir /var/www/html/owncloud/data


sudo chown www-data:www-data /var/www/html/owncloud/data
sudo chmod 750 /var/www/html/owncloud/data
Dopo questo passaggio, riavviate il Raspberry Pi:

sudo reboot

Configurare ownCloud
-----------------

Dopo aver installato il programma e aver creato la giusta struttura per le


cartelle,
occupatevi ora del vostro account ownCloud personale.
Per fare questo andate sul browser del vostro Raspberry Pi, inserite l’IP del mini
PC
nella barra degli indirizzi e aggiungete alla fine dell’indirizzo il percorso
“/owncloud” (192.168.X.X/owncloud).

Se utilizzate il server con un indirizzo DDNS, questo sostituisce l’indirizzo IP.

Ora dovrebbe comparire la schermata di login di ownCloud. Se d’ora in avanti


compare un “performance warning” relativo a SQLite, non dovete preoccuparvi, il
file server Raspberry Pi è già pronto per essere utilizzato. Registrate ora un
account admin, creando alla voce del menu giusta un nome utente e una password. Una
volta terminata l’installazione, il vostro ownCloud personale è disponibile sin da
subito con questo account. Potete caricare e scaricare i file alla voce “file”.

Indicazioni per l’amministrazione


------------------------

Se avete dotato inizialmente il vostro Raspberry Pi di un indirizzo statico, potete


ora accedere al vostro ownCloud personale ovunque voi siate con il giusto indirizzo
IP o quello DDNS. Comunque teoricamente può farlo anche qualsiasi altro utente, per
questo si consiglia di scegliere delle password sicure. Se il vostro server sul
Raspberry Pi è raggiungibile dall’esterno via Internet, dovreste occuparvi degli
aspetti relativi alla sua sicurezza e tenerlo costantemente aggiornato.

===================================================================
DISABILITA NTP SERVER
===================================================================
/etc/init.d/ntp start
/etc/init.d/ntp stop
systemctl disable systemd-timesyncd.service
apt-get ntpdate
ntpdate-debian

oppure
ntpdate 0.it.pool.ntp.org

server italiani

server 0.it.pool.ntp.org
#server 1.it.pool.ntp.org
#server 2.it.pool.ntp.org
#server 3.it.pool.ntp.org

li inserisco in /etc/ntp.conf anche se poi il servizio non lo uso!


ma devo configurare il programma che si attiva quando eth0 go up

root@raspi:/etc# cat default/ntpdate

# The settings in this file are used by the program ntpdate-debian, but not
# by the upstream program ntpdate.
# Set to "yes" to take the server list from /etc/ntp.conf, from package ntp,
# so you only have to keep it in one place.
#NTPDATE_USE_NTP_CONF=yes
NTPDATE_USE_NTP_CONF=no

# List of NTP servers to use (Separate multiple servers with spaces.)


# Not used if NTPDATE_USE_NTP_CONF is yes.
#NTPSERVERS="0.debian.pool.ntp.org 1.debian.pool.ntp.org 2.debian.pool.ntp.org
3.debian.pool.ntp.org"
NTPSERVERS="0.it.pool.ntp.org"

To stop ntpd:

/etc/init.d/ntp stop
o
service ntp stop

To prevent it from starting at boot:

update-rc.d -f ntp remove

With systemd, the two commands are:

systemctl stop ntp


systemctl disable ntp

Check:

systemctl is-enabled ntp


Output

ntp.service is not a native service, redirecting to systemd-sysv-install


Executing /lib/systemd/systemd-sysv-install is-enabled ntp
disabled

Uninstall ntpd if it is installed.


You will still have ntpdate installed. (It is difficult to remove.)
Prevent it from executing by adding exit 0 to /etc/default/ntpdate

----------------------------------------------------------------------------------
15.16. Configure ntpdate Servers
----------------------------------------------------------------------------------

The purpose of the ntpdate service is to set the clock during system boot.
This was used previously to ensure that the services started after ntpdate would
have the correct time and not observe a jump in the clock.

The use of ntpdate and the list of step-tickers is considered deprecated and so
Fedora uses the -g option to the ntpd command and not ntpdate by default.

The ntpdate service in Fedora is mostly useful only when used alone without ntpd.
With systemd, which starts services in parallel, enabling the ntpdate service will
not ensure that other services started after it will have correct time unless
they specify an ordering dependency on time-sync.target, which is provided by the
ntpdate service. The ntp-wait service (in the ntp-perl subpackage) provides the
time-sync target for the ntpd service.
In order to ensure a service starts with correct time, add After=time-sync.target
to the service and enable one of the services which provide the target
(ntpdate or sntp, or ntp-wait if ntpd is enabled).

Some services on Fedora have the dependency included by default


( for example, dhcpd, dhcpd6, and crond).

To check if the ntpdate service is enabled to run at system start, issue the
following command:

~]$ systemctl status ntpdate

To enable the service to run at system start, issue the following command as root:

~]# systemctl enable ntpdate

In Fedora the default /etc/ntp/step-tickers file contains 0.fedora.pool.ntp.org.


To configure additional ntpdate servers, using a text editor running as root,
edit /etc/ntp/step-tickers.
The number of servers listed is not very important as ntpdate will only use this
to obtain the date information once when the system is starting.
If you have an internal time server then use that host name for the first line.
An additional host on the second line as a backup is sensible.
The selection of backup servers and whether the second host is internal or
external depends on your risk assessment.
For example, what is the chance of any problem affecting the first server also
affecting the second server? Would connectivity to an external server be more
likely to be available than connectivity to internal servers in the event of a
network failure disrupting access to the first server?

------
KODITV
------

cat /etc/ntp/step-tickers
# List of NTP servers used by the ntpdate service.
ntp2.inrim.it
ntp1.inrim.it
ntpserver

--------------------------------------------------------------------------------
[root@koditv default]# systemctl stop ntpdate
[root@koditv default]# systemctl start ntpdate
[root@koditv default]# systemctl status ntpdate

ntpdate.service - Set time via NTP


Loaded: loaded (/usr/lib/systemd/system/ntpdate.service; enabled; vendor preset:
disabled)
Active: active (exited) since Fri 2019-12-20 09:36:05 CET; 6s ago
Process: 4168 ExecStart=/usr/libexec/ntpdate-wrapper (code=exited,
status=0/SUCCESS)
Main PID: 4168 (code=exited, status=0/SUCCESS)
CPU: 65ms

systemd[1]: Starting Set time via NTP...


ntpdate[4174]: step time server 193.204.114.232 offset 0.000017 sec
systemd[1]: Started Set time via NTP.

================================================================================
AZARTICOLO:How to enable auto-login?
================================================================================

First create a new service similar to [email protected]:

cp /lib/systemd/system/[email protected] /etc/systemd/system/[email protected]

ln -s /etc/systemd/system/[email protected]
/etc/systemd/system/getty.target.wants/[email protected]

then edit ExecStart, Restart and Alias values, like this:

...
ExecStart=-/sbin/mingetty --autologin USERNAME %I
Restart=no
...
Alias=getty.target.wants/[email protected]

and finally reload daemon and start the service:

systemctl daemon-reload systemctl start [email protected]

Note that if you exit tty2 session, you wont be able to use it until next reboot
or manual start by systemctl, except if you leave Restart as ‘always’, but
I highly recommend to avoid this according to security reasons.

source: fedoraproject.org/wiki

The simplest way I have found, if using Raspbian, is to edit the raspi-config file:
/etc/lightd/lightdm.conf and set the autologin-user= parameter.

Change: autologin-user=pi to autologin-user=username where username is your


username

N.B: /etc/lxdm/lxdm.conf per fedora 31


================================================================================
AZARTICOLO:Auto-login with GUI disabled in Raspbian
================================================================================

How can I make the RPi auto-login when booted, when the GUI is disabled?

You don't have to type a password, when logging in when GUI enabled, so there is
probably
an easy way of disabling the password prompt in the console.

Very dangerous, I missed the bit about not having a password and seemed to have
screwed
up the SD card. Be warned!

For Raspbian Wheezy:


--------------------

You should be able to edit the /etc/inittab file to enable autologin.

Find a line like this in /etc/inittab

1:2345:respawn:/sbin/getty --noclear 38400 tty1

This starts the getty process on tty1.


You can add the getty --autologin option to that line:

1:2345:respawn:/sbin/getty --autologin {USERNAME} --noclear 38400 tty1

Replace {USERNAME} with the user you want to login.

Note I have not tested this, check the manpage for getty for more details.

Update: Raspbian Jessie uses systemd so inittab is not used.

Here is a FAQ that may help for Jessie:

https://fedoraproject.org/wiki/
Systemd#How_do_I_set_automatic_login_on_a_virtual_console_terminal.3F

The FAQ is for Fedora but it should be very similar on Raspbian Jessie.

I have tested it; it works fine. Also, put something in ~/.bash_profile and that
will get run
automatically after you are logged in. – greggo Jan 18 '13 at 18:28

Please update the answer!

There is no /etc/inittab file in raspbian jessie.


-----------------------------------------------

No, I still get the login prompt upon boot.

The Raspbian Jessie solution doesn't work.


there is an easier way to do this using raspi-config this article explains it
http://www.opentechguides.com/how-to/article/raspberry-pi/5/raspberry-pi-auto-
start.html

showing :
how to auto login to the shell prompt (using a method similar to above)
Run scripts at startup
Auto start the desktop using raspi-config

this article shows how to auto login to the desktop using raspi-config, but the
question is asking how to auto login when there is no GUI or Desktop
(so bringing up the shell prompt).

However this article also shows how to auto login to the shell as well.

This worked for me with Jessie Lite:

-i
mkdir -pv /etc/systemd/system/[email protected]
nano /etc/systemd/system/[email protected]/autologin.conf

[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin pi --noclear %I 38400 linux

only catch is that I can't logon using SSH anymore - access denied. :-(
/etc/systemd/system/
A good answer should give an indication as to why it works.
What do the those two steps do?
Can you really say it works if it breaks SSH?

This doesn't work!

Still forces me to login at command line.

does using $TERM work for you?

ExecStart=-/usr/bin/agetty --autologin username --noclear %I $TERM – esharp Aug 1


'16 at 8:54
If you want auto-login to Raspberry Pi on Serial line, you need to edit the
/etc/inittab file
on pi with permissions.

Find a line like this in /etc/inittab

T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

Add the getty --autologin option to that line.

T0:23:respawn:/sbin/getty --autologin {username} -L ttyAMA0 115200 vt100

Save and Reboot.

I'm running NOOBS and had a slightly different inittab file.


Here's what I changed that combined both the "--autologin" on the T0 line and the
1:2345 line:

#1:2345:respawn:/sbin/getty --noclear 38400 tty1"


1:2345:respawn:/bin/login -f pi tty1 <dev/tty1 >/dev/tty1 2>&1
T0:23:respawn:/sbin/getty --autologin pi - L ttyAMA0 115200 vt100

so lightdm.conf method didnt work for me, after a bit of playing around the easiest
method
I found was below.

cd /etc/systemd/system/

from there type: ls

you will see [email protected]

just nano [email protected]

and change line ExecStart=-/sbin/agetty --autologin pi --noclear % I $TERM

to

ExecStart=-/sbin/agetty --autologin root --noclear % I $TERM

now I did have pi auto login working using the raspi-config setup,
but used the above method to change the autologin for a root user.
hope this helps

/etc/pam.d/lightdm-autologin
/etc/systemd/system/[email protected]
--------------------------------------------------------------------------------
Autologin is performed as part of systemd's getty target:

root@raspberrypi:/etc/systemd/system/getty.target.wants#

# pwd
/etc/systemd/system/getty.target.wants

[email protected] -> /lib/systemd/system/[email protected]

invece dvo porlo a:

ls -l
total 0
lrwxrwxrwx 1 root root 38 Sep 24 18:14 [email protected] ->
/etc/systemd/system/[email protected]

The raspi-config simply manipulates this symlink.


To switch to manual login, execute (as root):

ln -fs /lib/systemd/system/[email protected]
/etc/systemd/system/getty.target.wants/[email protected]

To switch back to automatic login, do:

ln -fs /etc/systemd/system/[email protected]
/etc/systemd/system/getty.target.wants/[email protected]

I wanted a system with no console prompt on tty1, so I removed this symlink


altogether.

=================================================================================
AZARTICOLO:Raspberry Pi: Extending the life of the SD card
=================================================================================

SD cards are said to have a finite life.


If you are planning on running a Raspberry Pi 24x7x365, there are some steps
that you can take with GNU/Linux to extend the life of the card: here are some
ideas.

Recently I posted about how I believe that the Raspberry Pi is the perfect small
server .
One question came up about the SD storage.
SD cards are said to have a finite amount of writes that are possible,
before they start to fail.

Is this an issue when using the Pi as a server?

It could be, even though posts about SD card failures are scattered but
not entirely conclusive. I started to look at ways to minimize the number of
writes to the SD card, which in theory should help extend its life.

Best Practices for running GNU/Linux on an SD card


----------------------------------------------------
Get a larger card. Writes are supposed to be spread out among the card, so the
larger the card, the less chance of it writing over the same area multiple times.
Most GNU/Linux distributions on the Pi can fit on a 4GB card, but 8GB and even
16GB cards are becoming more affordable.

Just going from a 4GB to 8 GB card will cut the number of writes to the same area
of the card in half.

Stick with name brands. There are a lot of posts that mention sticking to top
brands.
I didn't compile a list nor do I endorse any specific brands, but fortunately there
are enough posts out there that show the top brands and their failure rates.

Tweak GNU/Linux to write to RAM instead of the SD card. This uses a feature called
"tmpfs", which a really cool feature of GNU/Linux. Tmpfs can write to RAM as if
it was an ordinary filesystem.

It's fast, efficient, and easy to use. More details on that below.

Set the SD card to read-only mode.


This essentially makes GNU/Linux run in read-only mode, similar to how it works
booting from a Live CD. This avoids any writing to the SD card and in theory can
extend its life. There are some drawbacks to this though. First, it takes a bit
of work to set up, which is out of the scope of this article.
Second, changes that are made will be lost when the system is rebooted because
they are not written to the SD card. To me, running GNU/Linux in read-only mode
is overkill and I don't recommend going to this extreme.

Using Tmpfs
-----------

As I mentioned, tmpfs can write to RAM instead of the local disk


(in this case, the SD card). Using it is simple.

All that needs to be done is add an entry to the /etc/fstab file


(to mount the folder you wish to have written to RAM) and reboot
(so that each mount is cleanly mounted before services start writing files).

The kernel will do the rest for you by managing the writes to the RAM on this
virtual filesystem.
The really neat part about this is that the kernel will only use the amount of RAM
required for writing files, not the entire size of the mount.

So, for example, say we add this line to the /etc/fstab file:

tmpfs /var/log tmpfs defaults,noatime,nosuid,mode=0755,size=100m 0 0

The kernel will mount /var/log to RAM, however it will not use any RAM until files
are written to /var/log. When files are written to /var/log, the kernel will save
them to RAM and only use space to save the files. When files are removed from
/var/log,
the associated RAM to store them is freed up.

This means that it only uses what RAM it needs to in order to store the files,
which makes it very efficient.

In /etc/fstab, you can also specify the total size to allocate for each mount.
In the example above, we set "size=100m" so that /var/log can use up to 100 MB of
space and no more. This avoids a filesystem from using up all of the RAM which can
cause the system to slow down or even crash.
By running the "mount" command, we can see in the example above that /var/log is
mounted as a tmpfs volume to RAM, 100 MB in size.

Filesystem Size Used Avail Use% Mounted on


tmpfs 100M 596K 100M 1% /var/log

There are a variety of locations that GNU/Linux likes to make frequent writes.
This is a list of entries below that I use as a starting point that should fit
for most distributions.

tmpfs /tmp tmpfs defaults,noatime,nosuid,size=100m 0 0


tmpfs /var/tmp tmpfs defaults,noatime,nosuid,size=30m 0 0
tmpfs /var/log tmpfs defaults,noatime,nosuid,mode=0755,size=100m 0 0
tmpfs /var/run tmpfs defaults,noatime,nosuid,mode=0755,size=2m 0 0
tmpfs /var/spool/mqueue tmpfs
defaults,noatime,nosuid,mode=0700,gid=12,size=30m 0 0

As you can see I make use of the "size=" parameter to avoid using up huge amounts
of RAM in case something tries to save a huge amount of data.
The "noatime" and "nosuid" parameters are also recommended for security and
performance,
and "mode=" along with "gid=" matches the permissions and group of the original
filesystem
to what was located on the SD card originally.

Yep, tmpfs can also handle permissions. As usual, entries in /etc/fstab mount
over the top of what is on the SD card, as standard Unix/Linux types do.
So if for some reason the mounts fail, writes will still work to the SD card.

One additional point to keep in mind is that anything mounted with tmpfs will be
lost on a reboot.
So, logs in /var/log in the example above will be wiped out if the computer is shut
down or rebooted.
So you will not want to save any files with tmpfs that need to be persistent among
reboots.

I'm actively using these settings and so far having great results.
Time will tell how the Pi and/or SD card hold up, but there are a lot of posts
out there with some great uptimes, as we know GNU/Linux itself doesn't need
frequent

rebooting like other operating systems. The steps above should hopefully hold up,
especially if you intend to run the Pi 24x7x365.

Indicazioni per l’amministrazione


---------------------------------

Se avete dotato inizialmente il vostro Raspberry Pi di un indirizzo statico,


potete ora accedere al vostro ownCloud personale ovunque voi siate con il giusto
indirizzo IP o quello DDNS. Comunque teoricamente può farlo anche qualsiasi altro
utente, per questo si consiglia di scegliere delle password sicure.
Se il vostro server sul Raspberry Pi è raggiungibile dall’esterno via Internet,
dovreste occuparvi degli aspetti relativi alla sua sicurezza e tenerlo
costantemente
aggiornato.

===================================================================
AZARTICOLO:Introduction to XFS
===================================================================
http://landoflinux.com/linux_xfs_filesystem_introduction.html

XFS Filesystem and Linux

What is XFS?
------------

XFS is a highly scalable, high-performance file journalling file system which was
originally designed at Silicon Graphics, Inc in 1993. Originally XFS was used on
Silicon Graphics Inc s own operating system Irix, however, it was later ported to
the Linux kernel in 2001. Today XFS is supported by most Linux distributions and
has now become the default filesystem on RHEL (Red Hat Enterprise Linux),
Oracle Linux 7, CentOS 7 and many other distributions.
Originally XFS was created to support extremely large filesystems with sizes of

up to 16 exabytes and file sizes of up to 8 exabytes.

XFS supports metadata journalling allowing for quicker recovery after a system
crash.
The XFS file system can also be de-fragmented and enlarged while mounted and
active.
The XFS file system can not be reduced in size !

XFS features the following allocation schemes:

Extent based allocation


Stripe-aware allocation policies
Delayed allocation
Space pre-allocation
Delayed allocation and other performance optimizations affect XFS the same way
that they do ext4. Namely, a program s writes to a an XFS file system are not
guaranteed to be on-disk unless the program issues an fsync() call afterwards.

The XFS file system also supports the following:

Extended attributes (xattr), which allows the system to associate several


additional name/value pairs per file.
Quota journalling, which avoids the need for lengthy quota consistency checks after
a crash.
Project/directory quotas, allowing quota restrictions over a directory tree.
Subsecond timestamps

The Basic Layout of a XFS File System


--------------------------------------

An XFS filesystem can reside on a regular disk partition or on a logical volume.


An XFS filesystem has up to three parts:

a data section,
a log section,
and a real-time section.

Using the default mkfs.xfs options, the real-time section is absent, and the log
area is contained within the data section. The log section can be either separate
from the data section or contained within it.

The filesystem sections are divided into a certain number of blocks, whose size
is specified with the -b option of the mkfs.xfs command.

The data section contains all the filesystem metadata


(inodes, directories, indirect blocks) as well as the user file data for ordinary
(non-real-time) files and the log area if the log is internal to the data section.

The data section is divided into a number of allocation groups.

The number and size of the allocation groups are chosen by mkfs.xfs so that there
is normally a small number of equal sized groups. The number of allocation groups
controls the amount of parallelism available in file and block allocation.

It should be increased from the default if there is sufficient memory and a lot
of allocation activity. The number of allocation groups should not be set very

high, since this can cause large amounts of CPU time to be used by the filesystem,
especially when the filesystem is nearly full.

More allocation groups are added (of the original size) when xfs_growfs is run.
An example of this command in use can be seen in the xfs_growfs example below.

The log section (or area, if it is internal to the data section) is used to store
changes to the file system metadata while the file system is running until those
changes are made to the data section. Changes are written sequentially during
normal operation and read only during a mount.

When mounting a file system after a crash, the log is read to complete operations
that were in progress at the time of the crash.

The real-time section is used to store the data of real-time files.

These files have an attribute bit set through xfsctl after file creation, before
any data was written to the file. The real-time section is divided into a number
of extents of fixed size (specified at mkfs.xfs time). Each file in the real-time
section has an extent size that is a multiple of the real-time section extent size.

Each allocation group contains several data structures.


The first sector contains the superblock.
For allocation groups after the first, the superblock is just a copy and is not
updated after mkfs.xfs.

The next three sectors contain information for block and inode allocation within
the allocation group. Also contained within each allocation group are data
structures
to locate free blocks and inodes. These are located through the header structures.

Each XFS file system is labelled with a Universal Unique Identifier (UUID).
The UUID is stored in every allocation group header and is used to help distinguish
one XFS filesystem from another, therefore you should avoid using the "dd" utility
or any other block by block copying programs to copy XFS filesystems.

If two XFS filesystems on the same machine have the same UUID, xfsdump may become
confused when carrying out an incremental backup or a resumed dump.

xfsdump and xfsrestore are recommended for making copies of XFS filesystems.
(see also xfs_copy)

Creating a XFS File System


--------------------------

To create a XFS file system, you can use the command mkfs.xfs /dev/device.

When using mkfs.xfs on a block device containing an existing file system, you
should use the -f option to force an overwrite of that file system.

Below is an example of the mkfs.xfs command being issued on a CentOS 7 server.


Once the command has run successfully, we issued the mount command.
In this example, we are using a mount point of "xfs_test".
This was created by issuing the command "mkdir /xfs_test". (see output below)

# mkfs.xfs /dev/sdb1

meta-data=/dev/sdb1 isize=256 agcount=4, agsize=32704 blks


= sectsz=512 attr=2, projid32bit=1
= crc=0
data = bsize=4096 blocks=130816, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0
log =internal log bsize=4096 blocks=853, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
real-time =none extsz=4096 blocks=0, rtextents=0

# mount /dev/sdb1 /xfs_test

# df -hT

Filesystem Type Size Used Avail Use% Mounted on


/dev/mapper/centos-root xfs 6.7G 1.1G 5.7G 16% /
devtmpfs devtmpfs 492M 0 492M 0% /dev
tmpfs tmpfs 498M 0 498M 0% /dev/shm
tmpfs tmpfs 498M 6.6M 491M 2% /run
tmpfs tmpfs 498M 0 498M 0% /sys/fs/cgroup
/dev/sda1 xfs 497M 100M 398M 20% /boot
/dev/sdb1 xfs 508M 26M 482M 6% /xfs_test
Using LVM (Logical Volume Manager) to add space to an XFS file system
----------------------------------------------------------------------

Generally to increase space you would use LVM (Logical Volume Manager.
In the following example we will create a partition with a type of "8e" which
denotes LVM.

We will create a Physical Volume with the pvcreate command,


create a VolumeGroup and define a Logical Volume.
Next we will generate an XFS filesystem on the Logical Volume.
For more information regarding LVM, follow the LVM link: Introduction to LVM

An overview of the basic process involved can be seen below:

Create a Partition using fdisk


------------------------------

In this example, we are going to create a partition using the disk partitioning
tool
"fdisk". The commands used to create the partition can be seen in the output below:

# fdisk /dev/sdb
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Command (m for help): n


Partition type:
p primary (0 primary, 0 extended, 4 free)
e extended
Select (default p): p
Partition number (1-4, default 1): 1
First sector (2048-4194303, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-4194303, default 4194303):
Using default value 4194303
Partition 1 of type Linux and of size 2 GiB is set
Command (m for help): t
Selected partition 1
Hex code (type L to list all codes): 8e
Changed type of partition 'Linux' to 'Linux LVM'
Command (m for help): p

Disk /dev/sdb: 2147 MB, 2147483648 bytes, 4194304 sectors


Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x340b4c69

Device Boot Start End Blocks Id System


/dev/sdb1 2048 4194303 2096128 8e Linux LVM

Command (m for help): w


The partition table has been altered!

Calling ioctl() to re-read partition table.


Syncing disks.

From the above output we can see that a Primary partition was created on device
"/dev/sdb" with a partition number of "1" (/dev/sdb1).
Type "8e" was specified for use with Logical Volume Management.
The partition layout was then previewed using the option "p", and then our
changes were written using the "w" option.

Create Logical Volume Manager Components: PV, VG and LV


-------------------------------------------------------

Our next step is to create a Physical Volume comprising of the /dev/sdb1 partition.
Next we then create a Volume Group called "vg01" and finally we create a Logical
Volume
that will use all available space within our Volume Group.
The commands issued can be seen in the output below:

# pvcreate /dev/sdb1
Physical volume "/dev/sdb1" successfully created

# vgcreate vg01 /dev/sdb1


Volume group "vg01" successfully created

# lvcreate -n lv01 -l 100%VG vg01


Logical volume "lv01" created

You can use the command "pvs" and "vgs" commands to display PV (Physical Volume)

and VG (Volume Group) information:

# pvs

PV VG Fmt Attr PSize PFree


/dev/sda2 centos lvm2 a-- 7.51g 0
/dev/sdb1 vg01 lvm2 a-- 2.00g 0

# vgs

VG #PV #LV #SN Attr VSize VFree


centos 1 2 0 wz--n- 7.51g 0
vg01 1 1 0 wz--n- 2.00g 0

From the above output we can see that the "pvs" command displays our device
"/dev/sdb1" and its associated VG "vg01". The output from the "vgs" command
indicates that our PV is only associated with one Volume Group and has a size
of 2GB.

Create a XFS file system on a Logical Volume


---------------------------------------------

Before you can use the storage that has been created, you will need to create a
file system on the Logical Volume (LV). This is achieved using the "mkfs.xfs"
command.

# mkfs.xfs /dev/vg01/lv01
meta-data=/dev/vg01/lv01 isize=256 agcount=4, agsize=130816 blks
= sectsz=512 attr=2, projid32bit=1
= crc=0
data = bsize=4096 blocks=523264, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0
log =internal log bsize=4096 blocks=2560, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
real-time =none extsz=4096 blocks=0, rtextents=0

The "mkfs.xfs" command was issued against the path to the Logical Volume
"/dev/vg01/lv01".

Create a Mount Point


---------------------
Before you can start to use the file system, it first has to be mounted on a
mount point. In the example below, we are using the mount point of "xfs_test".
This mount point is created with the standard "mkdir" command.

[root@centos07a /]# mkdir xfs_test

Mount File system


-----------------

[root@centos07a /]# mount /dev/vg01/lv01 xfs_test/

Once the file system has been successfully mounted, it is available for use.

Display information about a mounted File System with the df command


--------------------------------------------------------------------

To display information about our mounted file system we can use the "df" command.
In the example below, we used the "-h" parameter to display sizes in MB, GB...
and the "-T" option displays the file system type. (In this example xfs)

[root@centos07a /]# df -hT

Filesystem Type Size Used Avail Use% Mounted on


/dev/mapper/centos-root xfs 6.7G 1.1G 5.7G 16% /
devtmpfs devtmpfs 492M 0 492M 0% /dev
tmpfs tmpfs 498M 0 498M 0% /dev/shm
tmpfs tmpfs 498M 6.6M 491M 2% /run
tmpfs tmpfs 498M 0 498M 0% /sys/fs/cgroup
/dev/sda1 xfs 497M 100M 398M 20% /boot
/dev/mapper/vg01-lv01 xfs 2.0G 33M 2.0G 2% /xfs_test

From the above output we can see that our xfs file system is 2GB in size and has
the mount point of "/xfs_test".

Add a File System to the mount table /etc/fstab


-----------------------------------------------

Generally when you create a file system, you will want your file system to be
automatically mounted after a system reboot. To auto mount your file system,
you will need to add a line similar to the one below into your mount table
"/etc/fstab":

Add an entry to "/etc/fstab"

/dev/sdb1 /xfs_test xfs defaults 0 0

In the above example, we have specified our device, its mount point, a type of
"xfs".
We are using the default settings and have specified no checking or dumping
options.
For more information regarding the mount table see our link: Mount Table

Extend xfs File System using LVM


---------------------------------

In next part of this example we are going to add an additional disk to our system.
Once this disk has been added, we will then add this space to the existing
Volume Group "vg01" and then extend the Logical Volume "lv01".

The commands used for this can be seen in the output below:

Create a New Partition on a newly added disk


--------------------------------------------
Once again, we are going to use the partition tool "fdisk" to create our new
partition for the new disk added. The commands used can be seen in the output
below:

# fdisk /dev/sdc
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Command (m for help): n


Partition type:
p primary (0 primary, 0 extended, 4 free)
e extended
Select (default p): p
Partition number (1-4, default 1): 1
First sector (2048-1048575, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-1048575, default 1048575):
Using default value 1048575
Partition 1 of type Linux and of size 511 MiB is set

Command (m for help): t


Selected partition 1
Hex code (type L to list all codes): 8e
Changed type of partition 'Linux' to 'Linux LVM'

Command (m for help): p

Disk /dev/sdc: 536 MB, 536870912 bytes, 1048576 sectors


Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x934cae77

Device Boot Start End Blocks Id System


/dev/sdc1 2048 1048575 523264 8e Linux LVM

Command (m for help): w


The partition table has been altered!

Calling ioctl() to re-read partition table.


Syncing disks.

Create a new Physical Volume


----------------------------
Next we create a new PV (Physical Volume using the device "/dev/sdc1".

# pvcreate /dev/sdc1
Physical volume "/dev/sdc1" successfully created

Add the new Physical Volume to an existing Volume Group


--------------------------------------------------------

Here we are adding our new space to the existing Volume Group "vg01".
This extra space will be then available to our Logical Volume.
The command to add the new partition to our Volume Group is "vgextend".

# vgextend vg01 /dev/sdc1


Volume group "vg01" successfully extended

SDA1 SDA2 SDB1 << ------------ FORMATTAZIONE


HDU HDU HDU
| | |
PV PV PV
| | |
------- |
| VG | <<--------
-------
|
-------
| LG | <<-------- DISCO LOGICO VISTO DALL UTENTE
-------

Check PV and VG
---------------

If we now issue the "pvs" and vgs" commands again, we will now see the new
additions:
# pvs
PV VG Fmt Attr PSize PFree
/dev/sda2 centos lvm2 a-- 7.51g 0
/dev/sdb1 vg01 lvm2 a-- 2.00g 0
/dev/sdc1 vg01 lvm2 a-- 508.00m 508.00m

# vgs
VG #PV #LV #SN Attr VSize VFree
centos 1 2 0 wz--n- 7.51g 0
vg01 2 1 0 wz--n- 2.49g 508.00m

From the above "pvs" command we can see that the new PV has been added with 508MB
of space. The "vgs" command is now indicating that there are now two Physical
Volumes
associated with the Volume Group "vg01".

Extend a Logical Volume


-----------------------

To extend the Logical Volume, we are going to use the "lvextend command.
In the example below we are extending the Logical Volume by 500MB.
The file system will be automatically resized because we are using the "-r" option.

[root@centos07a /]# lvextend /dev/vg01/lv01 -L +500M -r

Extending logical volume lv01 to 2.48 GiB


Logical volume lv01 successfully resized
meta-data=/dev/mapper/vg01-lv01 isize=256 agcount=4, agsize=130816 blks
= sectsz=512 attr=2, projid32bit=1
= crc=0
data = bsize=4096 blocks=523264, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0
log =internal bsize=4096 blocks=2560, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
real-time =none extsz=4096 blocks=0, rtextents=0
data blocks changed from 523264 to 651264

Use df to check File System


----------------------------

We can verify that the file system has now increased by issuing the "df" command.
The output from this can be seen below.

[root@centos07a /]# df -hT


Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/centos-root xfs 6.7G 1.1G 5.7G 16% /
devtmpfs devtmpfs 492M 0 492M 0% /dev
tmpfs tmpfs 498M 0 498M 0% /dev/shm
tmpfs tmpfs 498M 6.6M 491M 2% /run
tmpfs tmpfs 498M 0 498M 0% /sys/fs/cgroup
/dev/sda1 xfs 497M 100M 398M 20% /boot
/dev/mapper/vg01-lv01 xfs 2.5G 33M 2.5G 2% /xfs_test

We can now see from the above output that we have 2.5GB of space now available
to our xfs file system.

Important: You can not reduce a XFS filesystem, if you try you will get the
following message:

[root@centos07a /]# lvreduce /dev/vg01/lv01 -L -500M -r


fsadm: Xfs filesystem shrinking is unsupported
fsadm failed: 1
Filesystem resize failed.

----------------------------------------------------------------------
Method 2 for extending a XFS File System using the utility xfs_growfs
---------------------------------------------------------------------

The following method allows you to extend the file system by using the "xfs_growfs"
command.

The xfs_growfs command is used to increase the size of a mounted XFS file system
only if there is space on the underlying devices to accommodate the change.

The xfs_growfs command does not require LVM to extend the file system as per the
previous example.

The mount point argument that is passed is the pathname to the directory where the
filesystem is mounted. The xfs filesystem must be mounted first before it can be
grown.

The contents of the file system are undisturbed, and the added space is then made
available for additional file storage.

In the following example I am using a CentOS 7 server running in VirtualBox.


Initially the disk used "/dev/sdb" is set to a size of 500MB.

Our next step is to then create a XFS file system by issuing the "mkfs.xfs"
command.
The resulting file system can be seen after issuing the "df -hT" command.

(The -h option displays a human readable format in MB, GB etc..


and the -T option displays the type of file system (XFS in this example).

After the file system was initially created, I then increased the size of the
underlying disk by using the following VirtualBox command:

VBoxManage modifyhd "/home/john/VirtualBox VMs/CentOS_7/CentOS7_XFS_Test1.vdi" --


resize 2048

An outline of the steps involved for this example are below:

Create xfs file system on a 500MB Disk


---------------------------------------

Create the xfs file system using the "mkfs.xfs" command:

[root@centos07a /]# mkfs.xfs /dev/sdb1


meta-data=/dev/sdb1 isize=256 agcount=4, agsize=32000 blks
= sectsz=512 attr=2, projid32bit=1
= crc=0
data = bsize=4096 blocks=128000, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0
log =internal log bsize=4096 blocks=853, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
real-time =none extsz=4096 blocks=0, rtextents=0

Mount File System


-----------------

Next we need to mount the file system using the mount command
(syntax: mount /dev/device /mount_point)

[root@centos07a /]# mount /dev/sdb1 xfs_test/

Display XFS File System information


-----------------------------------

We can use the "df" command again to look at the size of our mounted xfs file
system:

[root@centos07a /]# df -hT


Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/centos-root xfs 6.7G 1.1G 5.7G 16% /
devtmpfs devtmpfs 492M 0 492M 0% /dev
tmpfs tmpfs 498M 0 498M 0% /dev/shm
tmpfs tmpfs 498M 6.6M 491M 2% /run
tmpfs tmpfs 498M 0 498M 0% /sys/fs/cgroup
/dev/sda1 xfs 497M 100M 398M 20% /boot
/dev/sdb1 xfs 497M 26M 472M 6% /xfs_test

KODITV
-------

df -hT
File system Tipo Dim. Usati Dispon. Uso% Montato su

/dev/mapper/fedora-root xfs 5,5G 4,7G 755M 87% /

/dev/mmcblk0p2 xfs 1014M 135M 880M 14% /boot


/dev/mmcblk0p1 vfat 599M 32M 568M 6% /boot/efi

/dev/sda2 ext4 6,9G 4,6G 2,0G 71% /run/media/root/DATA


/dev/sda1 ext4 488M 127M 326M 29% /run/media/root/BOOTLN

We can now see that our file system is mounted at mount point /xfs_test.
You may wish to add your disk/filesystem into "/etc/fstab" so that it will be
automatically mounted at system reboot.
To do this, simply add a line similar to the one below into the file "/etc/fstab".

Example /etc/fstab entry

/dev/sdb1 /xfs_test xfs defaults 0 0

KODITV
-------

dev/mapper/fedora-root / xfs defaults 0 0


UUID=983cb62e-687a-49e0-9a7c-b9a403fc4027 /boot xfs defaults 0 0
UUID=B7C7-D61F /boot/efi vfat umask=0077,shortname=winnt
0 2

Shutdown Partition and Increase underlying Disk size


-----------------------------------------------------

As we are using Oracle VirtualBox software, we need to shutdown the partition


first to increase the under lying disk.

The shutdown command "shutdown -h now" can be used to cleanly shutdown your
partition.
Unfortunately, VirtualBox only allows the disk to be increased when it is not in
use.
The following command will be issued from the host computer.
The "host" computer is the computer that is running the VirtualBox software.

VirtualBox - Increase Disk Size

The following command is issued to the host computer.

$ VBoxManage modifyhd "/home/john/VirtualBox VMs/CentOS_7/CentOS7_XFS_Test1.vdi" --


resize 2048
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%

The above command has now resized the virtual disk "CentOS7_XFS_Test1.vdi" to
a size of 2GB. Notice the double quotes around the path name.
Double quotes are needed as there are spaces within the path name name.
If you are unsure of the name of the Virtualdisk that you created originally
for your partition, you can "right click" on the name of your VM in the VirtualBox
manager and select the option to "Show in file manager".
Here you will see a list of all the virtual disks that have been allocated to your
server.

Restart Server and Delete Original Partition


--------------------------------------------

Once we have increased the under lying disk space, we will need to restart our
server. Next we are going to use fdisk to delete our original partition and then
recreate it again with more space. The disk in the example is known as "/dev/sdb".

Below are the steps taken using fdisk to accomplish the above task.

[root@centos07a /]# umount /xfs_test

[root@centos07a /]# fdisk /dev/sdb


Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Command (m for help): p

Disk /dev/sdb: 2147 MB, 2147483648 bytes, 4194304 sectors


Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x340b4c69

Device Boot Start End Blocks Id System


/dev/sdb1 2048 1026047 512000 83 Linux

Command (m for help): d


Selected partition 1
Partition 1 is deleted

Command (m for help): n


Partition type:
p primary (0 primary, 0 extended, 4 free)
e extended
Select (default p): p
Partition number (1-4, default 1):
First sector (2048-4194303, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-4194303, default 4194303):
Using default value 4194303
Partition 1 of type Linux and of size 2 GiB is set

Command (m for help): w


The partition table has been altered!

Calling ioctl() to re-read partition table.


Syncing disks.

Remount xfs File System


-----------------------

Before we can increase a xfs file system, it needs to be mounted first.

[root@centos07a /]# mount /dev/sdb1 /xfs_test

We can issue the "df" command again to display our file system information.

[root@centos07a /]# df -hT

Filesystem Type Size Used Avail Use% Mounted on


/dev/mapper/centos-root xfs 6.7G 1.1G 5.7G 16% /
devtmpfs devtmpfs 492M 0 492M 0% /dev
tmpfs tmpfs 498M 0 498M 0% /dev/shm
tmpfs tmpfs 498M 6.6M 491M 2% /run
tmpfs tmpfs 498M 0 498M 0% /sys/fs/cgroup
/dev/sda1 xfs 497M 100M 398M 20% /boot
/dev/sdb1 xfs 497M 26M 472M 6% /xfs_test

N.B:
From the above we can see that the file system on "xfs_test" is still indicating
its original size.

Issue xfs_growfs against mount point


------------------------------------

Next we are going to issue the "xfs_growfs" command:


[root@centos07a /]# xfs_growfs xfs_test/

meta-data=/dev/sdb1 isize=256 agcount=4, agsize=32000 blks


= sectsz=512 attr=2, projid32bit=1
= crc=0
data = bsize=4096 blocks=128000, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0
log =internal bsize=4096 blocks=853, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
real-time =none extsz=4096 blocks=0, rtextents=0
data blocks changed from 128000 to 524032

-------
KODITV
------

xfs_growfs /
meta-data=/dev/mapper/fedora-root isize=512 agcount=4, agsize=354560 blks
= sectsz=512 attr=2, projid32bit=1
= crc=1 finobt=1, sparse=1, rmapbt=0
= reflink=1
data = bsize=4096 blocks=1418240, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0, ftype=1
log =internal log bsize=4096 blocks=2560, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
data blocks changed from 1418240 to 1918976

The important information to look for when you issue this command can be found
within the last line of the output. You are looking for an increase in size
relating to data blocks.

We can now issue the "df" command again to verify that the xfs_growfs command
was successful:

[root@centos07a /]# df -hT


Filesystem Type Size Used Avail Use% Mounted on
/dev/mapper/centos-root xfs 6.7G 1.1G 5.7G 16% /
devtmpfs devtmpfs 492M 0 492M 0% /dev
tmpfs tmpfs 498M 0 498M 0% /dev/shm
tmpfs tmpfs 498M 6.6M 491M 2% /run
tmpfs tmpfs 498M 0 498M 0% /sys/fs/cgroup
/dev/sda1 xfs 497M 100M 398M 20% /boot
/dev/sdb1 xfs 2.0G 26M 2.0G 2% /xfs_test

This time we can see that the file system is now 2GB in size.

----------------------------------------------------------------
Overview of Options that can be passed to the xfs_growfs utility
----------------------------------------------------------------

SYNOPSIS
xfs_growfs [ -dilnrx ] [ -D size ] [ -e rtextsize ] [ -L size ] [ -m
maxpct ] [ -t mtab ] [ -R size ] mount-point
xfs_growfs -V

xfs_info [ -t mtab ] mount-point


xfs_info -V

Options that can be passed to the xfs_growfs utility

d | -D size

The "-d or -D" option is used to specify that the data section of the filesystem
should be grown. If the "-D" size option is passed, then the data section is grown
to the specified size. The "-d" option specifies that the data section is grown
to the largest possible size. The size is specified in file system blocks.

-e

Allows the real-time extent size to be specified.


This can also be specified with the mkfs.xfs command with the specified option
of "-r extsize=nnnn".

-l | -L size

Specifies that the log section of the filesystem should be grown, shrunk, or moved.
If the -L size option is given, the log section is changed to be that size, if
possible.
The size is expressed in file system blocks. The size of an internal log must be
smaller
than the size of an allocation group (this value is printed at mkfs time).
If neither -i nor -x is given with -l, the log continues to be internal or external
as it was before. [NOTE: These options are not implemented]

-m

Specify a new value for the maximum percentage of space in the file system that
can be allocated as inodes. In mkfs.xfs(8) this is specified with -i maxpct=nn.

-n

Specifies that no change to the filesystem is to be made.


The file system geometry is printed, and argument checking is performed, but no
growth occurs.

-r | -R size

Specifies that the real time section of the file system should be grown.

If the -R size option is given, the real time section is grown to that size,
otherwise the real time section is grown to the largest size possible with the
-r option. The size is expressed in filesystem blocks. The filesystem does not
need to have contained a real time section before the xfs_growfs operation.

-t

Specifies an alternate mount table file.

-V
Prints the version number and exits.
The mount point argument is not required with -V.

Summary of resizing a XFS file system


--------------------------------------

Although both of the methods used allowed you to increase the size of the XFS
file system. Neither of the methods allowed us to reduce the size.
The most common method of resizing a file system is to use the
LVM (Logical Volume Manager) approach. LVM gives you the advantage of being able
to add additional disk easily to an existing Volume Group and then use the
lvextend command to increase the size of your filesystem.

----------------------------------
An Overview of other xfs Utilities
----------------------------------

Repairing a XFS File System with xfs_repair


-------------------------------------------
Basic Syntax:

xfs_repair /dev/device

The xfs_repair utility is designed to repair file systems whether small or


large very quickly. Unlike other file system repair tools, xfs_repair does not
run at system boot time. xfs_repair replays its logs at mount time to ensure a
consistent file system. If xfs_repair encounters a dirty log, then it will not
be able to repair the file system. To rectify the file system, you will need to
first clear the relevant log, mount and then unmount the xfs file system.
You may use the option "-L" to force log zeroing if the log file is corrupt and
can not be replayed successfully. The command to issue for zeroing the log
is as follows:

xfs_repair -L /dev/device

For full details regarding the xfs_repair utility, please consult the relevant
man pages: man xfs_repair

XFS Quota Management - xfs_quota


--------------------------------

xfs_quota gives the administrator the ability to manage limits on disk space.
XFS quotas can control or report usage on users, groups or directory project level.
XFS quotas are enabled at mount time. You may specify the "noenforce" option which
allows reporting of usage, however, it does not enforce any limits.
For full details of XFS quotas see the relevant man page: man xfs_quota

Suspending a XFS File System with xfs_freeze


--------------------------------------------

The command to suspend access or resume write activity to a xfs file system is
"xfs_freeze". Generally this option is used for suspending write activity thus
allowing hardware based device snapshots to be used to capture the file system
in a consistent state.

The xfs_freeze utility is provided by the package "xfsprogs", note, this is only a
vailable to x86_64 architecture.

To freeze a XFS file system the basic syntax is:


xfs_freeze -f /mount/point

The -f flag requests that the specified XFS filesystem should be set to a state
of frozen, immediately stopping any modifications from being made.
When this option is selected, all ongoing transactions in the file system are
allowed to complete. Any new write system calls are halted.

To unfreeze a XFS file system the basic syntax is:

xfs_freeze -u /mount/point

The -u flag is used to unfreeze the file system and allow operations to continue
again. Any file system modifications that were blocked by the freeze option are
unblocked and allowed to complete.

If you are taking a LVM snapshot, then it is not necessary to run the "xfs_freeze"
utility as the LVM utility will automatically suspend the relevant xfs file system.

You can also use the "xfs_freeze" utility to freeze or unfreeze an ext3, ext4
and btrfs, file system.

xfs_copy
--------

Copy the contents of a XFS file system. xfs_copy should only be used to copy
unmounted file systems, read-only mounted file systems, or file systems that
have been frozen with the xfs_freeze utility.

The basic syntax of the utility is as follows:

xfs_copy [ -bd ] [ -L log ] source target1 [ target2 ... ]

OPTIONS
-d Create a duplicate (true clone) filesystem. This should be done
only if the new filesystem will be used as a replacement for the
original filesystem (such as in the case of disk replacement).

-b The buffered option can be used to ensure direct IO is not


attempted to any of the target files. This is useful when the
filesystem holding the target file does not support direct IO.

-L log Specifies the location of the log if the default location of


/var/tmp/xfs_copy.log.XXXXXX is not desired.

-V Prints the version number and exits.

xfs_fsr - File System re-organizer for XFS


------------------------------------------

The "xfs_fsr" utility is used to defragment mounted XFS file systems.


The reorganization algorithm operates on one file at a time, compacting or
otherwise improving the layout of the file extents (contiguous blocks of file
data).
When invoked with out any arguments, xfs_fsr will defragment all regular files in
all mounted xfs file systems. xfs_fsr uses the file "/etc/mtab" as its source of
mounted file systems. The xfs_fsr utility also allows a user to suspend a
defragmentation process at a specified time and then resume from where it last
left off. The current position of the defragmentation process is stored in the
file:

/var/tmp/.fsrlast_xfs

xfs_fsr can also be invoked to work with a single file:

xfs_fsr /path/to/file

When xfs_fsr is invoked, it will require sufficient free space to be available


as each file is copied to a temporary location whilst it is processed.
A warning message will be displayed if sufficient space is not available.

xfs_bmap
--------

Prints the map of disk blocks used by files in an XFS filesystem.


The map lists each extent used by the file, as well as regions in the file with
no corresponding blocks.

Each line of the listing takes the following form:


extent: [startoffset..endoffset]: startblock..endblock

[root@centos07a xfs_test]# xfs_bmap test.file


test.file:
0: [0..7]: 96..103

[root@centos07a xfs_test]# xfs_bmap -v test.file


test.file:
EXT: FILE-OFFSET BLOCK-RANGE AG AG-OFFSET TOTAL
0: [0..7]: 96..103 0 (96..103) 8

For further information regarding this utility, please consult the relevant man
page: man xfs_bmap

xfs_info
--------

To view your XFS file system information, the command "xfs_info" can be issued:

[root@centos07a /]# xfs_info /dev/sdc1


meta-data=/dev/sdc1 isize=256 agcount=17, agsize=32704 blks
= sectsz=512 attr=2, projid32bit=1
= crc=0
data = bsize=4096 blocks=524032, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=0
log =internal bsize=4096 blocks=853, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
real-time =none extsz=4096 blocks=0, rtextents=0

xfs_admin
----------

The xfs_admin command allows an administrator to changes parameters of a XFS


file system. The xfs_admin utility can only modify parameters of unmounted
devices/file systems. (Mounted devices can not be modified).
For a full list of parameters that can be changed, please consult the relevant
man page: man xfs_admin

xfs_metadump
-------------

xfs_metadump is a debugging tool that copies XFS file system metadata to a file.
The xfs_metadump utility should only be used to copy unmounted, read-only, or
frozen/suspended file systems; otherwise, generated dumps could be corrupted or
inconsistent. For a full list of available option please consult the relevant
man page: man xfs_metadump

xfs_mdrestore
--------------

xfs_mdrestore is used to restore a XFS metadump image to a filesystem image.


The source argument specifies the location of the metadump image and the target
argument specifies the destination for the filesystem image.
The target can be either a file or a device.

xfs_mdrestore [ -g ] source target

The "-g" parameter shows the restore progress on stdout.

xfs_db
------

A utility that can be used to debug a XFS file system.


For further information, please consult the relevant man page: man xfs_db.

xfs_estimate
------------

The xfs_estimate utility is used to estimate the amount of space that a xfs file
system will take.

[root@centos07a xfs_test]# xfs_estimate /var/tmp


/var/tmp will take about 4.4 megabytes

[root@centos07a xfs_test]# xfs_estimate -v /var/tmp


directory bsize blocks megabytes logsize
/var/tmp 4096 1138 4.4MB 4096000

xfs_estimate parameters:

[root@centos07a xfs_test]# xfs_estimate -h


Usage: xfs_estimate [opts] directory [directory ...]

-b blocksize (fundamental filesystem blocksize)


-i logsize (internal log size)
-e logsize (external log size)
-v prints more verbose messages
-V prints version and exits
-h prints this usage message
Note: blocksize may have 'k' appended to indicate x1024
logsize may also have 'm' appended to indicate (1024 x 1024)

xfs_mkfile
----------

xfs_mkfile is used to create a xfs file.


The file is padded with zeroes by default.
The default size is in bytes, but it can be flagged as kilobytes, blocks,
megabytes,
or gigabytes with the k, b, m, or g suffixes respectively.

Syntax: xfs_mkfile [ -v ] [ -n ] [ -p ] size[k|b|m|g] filename

Options that can be passed:

-v Verbose. Report the names and sizes of the created files.

-n No bytes. Create a holey file - that is, do not write out any
data, just seek to the end of the file and write a block.

-p Preallocate. The file is preallocated, then overwritten with


zeroes, it is then truncated to the desired size.

-V Prints the version number and exits.

xfs_io
------

xfs_io is a debugging tool similar to the utility xfs_db, but is aimed at


examining the regular file I/O paths rather than the raw XFS volume itself.
For a full list of all the parameters/options that can be passed,
please consult the relevant man page: man xfs_io

xfs_logprint
-------------

xfs_logprint prints the log of a XFS file system.


The device argument is the pathname of the partition or logical volume
containing the filesystem. The device can be a regular file if the "-f" option
is used. The contents of the file system remain undisturbed.

There are two major modes of operation in xfs_logprint:

One mode is better for filesystem operation debugging.


It is called the transactional view and is enabled through the "-t" option.
The transactional view prints only the portion of the log that pertains to
recovery. In other words, it prints out complete transactions between the tail
and the head. This view tries to display each transaction without regard to how
they are split across log records.

The second mode starts printing out information from the beginning of the log.
Some error blocks might print out in the beginning because the last log record
usually overlaps the oldest log record.
A message is printed when the physical end of the log is reached and when the
logical end of the log is reached. A log record view is displayed one record at
a time. Transactions that span log records may not be decoded fully.

Syntax: xfs_logprint [ options ] device

Options that can be passed:

-b Extract and print buffer information. Only used in transactional


view.

-c Attempt to continue when an error is detected.

-C filename
Copy the log from the filesystem to the file filename. The log
itself is not printed.

-d Dump the log from front to end, printing where each log record
is located on disk.

-D Do not decode anything; just print data.

-e Exit when an error is found in the log. Normally, xfs_logprint


tries to continue and unwind from bad logs. However, sometimes
it just dies in bad ways. Using this option prevents core
dumps.

-f Specifies that the filesystem image to be processed is stored in


a regular file at device (see the mkfs.xfs(8) -d file option).
This might happen if an image copy of a filesystem has been made
into an ordinary file with xfs_copy(8).

-l logdev
External log device. Only for those filesystems which use an
external log.

-i Extract and print inode information. Only used in transactional


view.

-q Extract and print quota information. Only used in transactional


view.

-n Do not try and interpret log data; just interpret log header
information.

-o Also print buffer data in hex. Normally, buffer data is just


decoded, so better information can be printed.
-s start-block
Override any notion of where to start printing.

-t Print out the transactional view.

-v Print "overwrite" data.

-V Prints the version number and exits.

xfs_rtcp
-------
xfs_rtcp copies a file to the real-time partition on a XFS file system.
If there is more than one source and target, the final argument (the target)
must be a directory which already exists.

Syntax: xfs_rtcp [ -e extsize ] [ -p ] source ... target

Options that can be used:

OPTIONS
-e extsize
Sets the extent size of the destination real-time file.

-p Use if the size of the source file is not an even multiple of


the block size of the destination filesystem. When -p is speci‐
fied xfs_rtcp will pad the destination file to a size which is
an even multiple of the filesystem block size. This is neces‐
sary since the real-time file is created using direct I/O and the
minimum I/O is the filesystem block size.

-V Prints the version number and exits.

xfs_ncheck
----------

The utility xfs_ncheck is used to generate a list of inode numbers along with path
names.

Syntax: xfs_ncheck [ -i ino ] ... [ -f ] [ -s ] [ -l logdev ] device

Options:

-f Specifies that the filesystem image to be processed is stored


in a regular file at device (see the mkfs.xfs -d file option).
This might happen if an image copy of a filesystem has been
made into an ordinary file.

-l logdev
Specifies the device where the filesystem external log
resides. Only for those filesystems which use an external
log. See the mkfs.xfs -l option, and refer to xfs(5) for a
detailed description of the XFS log.

-s Limits the report to special files and files with setuserid


mode. This option may be used to detect violations of secu‐
rity policy.

-i ino Limits the report to only those files whose inode numbers fol‐
low. May be given multiple times to select multiple inode
numbers.

-V Prints the version number and exits.

xfsdump
--------

xfsdump is a file system incremental dump utility that is used in conjunction


with xfsrestore. xfsdump backs up files and their attributes in a xfs file system.
The files can be dumped to storage media, a regular file, or to standard output.
Various dump options allow the administrator to create a full dump or an
incremental
dump. You may also specify a path to limit the files that are dumped.

To use the xfsdump utility, you first have to install it.


This can be easily achieved by issuing the following command:

yum install xfsdump

xfsrestore
----------

xfsrestore restores filesystems from dumps produced by xfsdump.


For a full list of all available parameters and options available to xfsdump and
xfsrestore, please consult the relevant man pages

================================================================================
AZARTICOLO: Migrating from LVM to partitions
================================================================================

Traditionally, linux systems were installed on disks which usually were


partitioned.
That is good sometimes, but not always.

So, the Linux Volume Manager (LVM) vas created, to overcome the limitations of the
traditional partitioned disk usage. Some of the limitations are: inability to
mirror or
span volumes, a maximum number of partitions which sometimes may be too small.
LVM has many advantages, such as ability to create a volume spanning many disk
drives,
ability to grow a voluume, ability to add more disks to the volume group.

But it has a big disadvantage: there aren't too many replication/cloning tools
available.

The major drawback of LVM is that it doesn't contain a filesystem, but logical
volumes
and each logical volume may be split across multiple phisical volumes.
This is the main reason why cloning applications such as Ghost, Clonezilla or
Acronis
TrueImage do not copy data stored on LVM as a filesystem, but as a raw data.
This process may be much slower than copying a filesystem.
Cloning tools must also be capable of understanding a specific filesystem to copy
it.
While NTFS, reiserfs, ext2 and ext3 are popular and supported by many cloning
tools,
ext4 is relatively new and at the time when I wrote this, the only tool able to
clone ext4
filesystems is Clonezilla.

Other tools may clone an ext4 filesystem, but using the raw copy method.

CentOS is a popular linux distribution, which by default uses LVM for storage
devices.
If someone wants to make a copy of the disk where the operating system is
installed,
it must use a disk equal to or larger than the one where the operating system is
installed.

Also, if the LVM configuration includes multiple disks, the cloning task is no
longer an option,
and other methods must be used. One of them is to use LVM's mirroring mechanism,
but this require strong knowledge of LVM and it's utilities.

If the storage requirements are modest, migrating from LVM to the traditional
partitioning scheme is a possible option.

Migrating (and resizing volumes) from LVM to partitions

For someone looking to clone fast a disk with Linux on it, using a cloning tool
like
Clonezilla or Acronis True Image may be much easier than using other methods.

Since many Linux installers prefer to use LVM, the user must manually partition the
disk at install time, or install it using the defaults and convert it from LVM to
partitions later.

This is the scenario below:


I have a CentOS Linux 6 installed with default options, and then I migrate it to a
partitioning scheme using custom sizes for the partitions and using ext3
filesystem
instead of the default ext4.

I want to create a supplemental /data partition, where I will store miscellaneous


files.
At this time, ext4 is not supported by as many tools as ext3.

After installation, I have:

The initial /etc/fstab file


---------------------------

# /etc/fstab
# Created by anaconda on Thu Aug 11 11:03:32 2011
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#

-----------------------------------------------------------------------------
File system Tipo Dim. Usati Dispon. Uso% Montato su
-----------------------------------------------------------------------------
/dev/mapper/VolGroup-lv_root / ext4 defaults 1 1
UUID=dbea6d02-7b89-4148-9ac1-da79af1c7027 /boot ext4 defaults 1 2
/dev/mapper/VolGroup-lv_swap swap swap defaults 0 0
-----------------------------------------------------------------------------

-------
KODITV
------

# /etc/fstab DISCO SDCARD


-----------------------------------------------------------------------------
File system Tipo Dim. Usati Dispon. Uso% Montato su
-----------------------------------------------------------------------------
/dev/mapper/fedora-root xfs 7,4G 4,8G 2,6G 65% /
/dev/mmcblk0p2 xfs 1014M 135M 880M 14% /boot
/dev/mmcblk0p1 vfat 599M 32M 568M 6% /boot/efi
-----------------------------------------------------------------------------

# /etc/fstab DISCO INTEL


-----------------------------------------------------------------------------
File system Tipo Dim. Usati Dispon. Uso% Montato su
-----------------------------------------------------------------------------
#LABEL=DATA3 / ext4
defaults 0 1
UUID="1ef3fadc-1fa9-454a-91a0-2438c25208d7" / ext4
defaults 0 1

#LABEL=BOOTLNX /boot ext4


defaults 0 2
#UUID="983cb62e-687a-49e0-9a7c-b9a403fc4027" /boot xfs
defaults 0 2
UUID="b2df9ee5-db0e-4d3f-a27f-a0eb87ac0811" /boot ext4
defaults 0 2

#LABEL="BOOTEFI"
#UUID=B7C7-D61F /boot/efi vfat
umask=0077,shortname=winnt 0 3
UUID=4B3E-8363 /boot/efi vfat
umask=0077,shortname=winnt 0 3

#/portatile2009.swp none swap


sw 0 0
LABEL=SWAPAREA none swap
discard=pages,nofail 0 4
#UUID=c6a3c9e0-4ea9-4723-824b-49ab89d1dfcb none swap
discard=pages,nofail 0 4

--------------------------------------------------------------------------------
blkid
--------------------------------------------------------------------------------
[root@koditv bin]# blkid

/dev/mmcblk0p1: UUID="B7C7-D61F" TYPE="vfat" PARTUUID="96c86d08-01"


/dev/mmcblk0p2: UUID="983cb62e-687a-49e0-9a7c-b9a403fc4027" TYPE="xfs"
PARTUUID="96c86d08-02"
/dev/mmcblk0p3: UUID="FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-ZtVX0e" TYPE="LVM2_member"
PARTUUID="96c86d08-03"
/dev/mapper/fedora-root: UUID="075aac84-b44e-4061-a6c2-0a91d5066a9e" TYPE="xfs"
/dev/sda1: LABEL_FATBOOT="BOOTEFI" LABEL="BOOTEFI" UUID="4B3E-8363" TYPE="vfat"
PARTUUID="e9c432b1-01"
/dev/sda2: LABEL="BOOTLNX" UUID="b2df9ee5-db0e-4d3f-a27f-a0eb87ac0811" TYPE="ext4"
PARTUUID="e9c432b1-02"
/dev/sda3: LABEL="DATA3" UUID="1ef3fadc-1fa9-454a-91a0-2438c25208d7" TYPE="ext4"
PARTUUID="e9c432b1-03"

--------------------------------------------------------------------------------
blkid /portatile2009.swp

/dev/zram0: UUID="b65a88ef-42de-444c-ba2b-9d0ea5dcd844" TYPE="swap"


/portatile2009.swp: UUID="6ebfe67c-6db4-4696-8d34-4567cbfa3f4f" TYPE="swap"
--------------------------------------------------------------------------------
A very important aspect regading /etc/fstab: the volume containing the root
filesystem and the swap are referenced by their logical volume name, the boot
partition is referenced by it's UUID.

Why is this important: on a running system is impossible to have accessible at a


specific time two different volumes with a specific volume group name and the same
volume name.

So, an exact replica of the LVM configuration from one disk to another can't be
done on a single system while both disks are accessible.

Copying LVM is possible with tools like modorescue, but the entire LVM
configuration
and data must be migrated from the local LVM to a remote machine or to an
intermediate storage medium.

And for the boot loader

/boot/grub/grub.conf
# grub.conf generated by anaconda
#
# Note that you do not have to rerun grub after making changes to this file
# NOTICE: You have a /boot partition. This means that
# all kernel and initrd paths are relative to /boot/, eg.
# root (hd0,0)
# kernel /vmlinuz-version ro root=/dev/mapper/VolGroup-lv_root
# initrd /initrd-[generic-]version.img
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title centos (2.6.32-71.el6.i686)
root (hd0,0)
kernel /vmlinuz-2.6.32-71.el6.i686 ro root=/dev/mapper/VolGroup-lv_root
rd_LVM_LV=VolGroup/lv_root rd_LVM_LV=VolGroup/lv_swap rd_NO_LUKS rd_NO_MD
rd_NO_DM LANG=en_US.UTF-8 SYSFONT=latarcyrheb-sun16 KEYBOARDTYPE=pc
KEYTABLE=us crashkernel=auto rhgb quiet
initrd /initramfs-2.6.32-71.el6.i686.img

------
KODITV
------

cat /boot/efi/EFI/fedora/grubenv
# GRUB Environment Block
kernelopts=root=/dev/mapper/fedora-root ro rd.lvm.lv=fedora/root LANG=it_IT.UTF-8
audit=0 ipv6.disable=1 audit=0 selinux=0 vconsole.keymap=it2 acpi=off
boot_success=0

n.b:
The boot loader configuration references the root file system location, which is
provided as a kernel parameter. rd_LVM_LV, a kernel parameter which instructs
LVM to initialize only the volume names referenced by rd_LVM_LV kernel parameters.

The migration from LVM to partitions procedure isn't quite simple.


--------------------------------------------------------------------------------
The target disk must be initialized, partitioned ahd the filesystems and swap
partitions
to be formatted, the data must be copied from LVM to partitions.

A boot loader must be installed on the target, the boot loader configuration must
be adjusted. As well, the /etc/fstab contents must be modified according to the
new coordinates of the filesystems.

n.b:
an important thing which must not be forgot:
on systems running with SeLinux enabled, after copying the data, an automatic
relabel must be triggered for the next boot.
Otherwise, the system may refuse to boot properly.

Partitioning the new disk


--------------------------------

The new disk must be added to the system.


After that, a live CD containing the tools required for partitioning must be used
to boot
the system.

A disk which is fine enough is the CentOS 6 DVD, used with the third boot option:
'Rescue installed system'. Afer keyboard selection, optional network configuration
and
startup, at the 'Rescue' dialog select 'Continue' if you want to find your linux
installation
mounted read-write on /mnt/sysimage. After that, a shell must be started.

Now, in the shell prompt, the first task is to identify the drives.
The /mnt/sysimage is mounted with the detected linux installation.

The new disk should have an empty partition table.


Now it's time to create the partition layout on the target disk.
cfdisk for this purpose.

I used the following layout:

Device mount size file system type


sdb1 /boot 512M ext3
sdb2 / 1024M ext3
extended
sdb5 swap 1024M swap
sdb6 /var 8192M ext3
sdb7 /tmp 2048M ext3
sdb8 /usr 4096M ext3
sdb9 /home 5192M ext3
sdb10 /data 5192M ext3
sdb11 /opt 5192M ext3

After partitioning, the filesystems must be formatted.


I also added labels to the filesystems, so they could be mounted later using the
label.

# mkfs.ext3 -L boot /dev/sdb1


# mkfs.ext3 -L root /dev/sdb2
# mkswap -L swap /dev/sdb5
# mkfs.ext3 -L var /dev/sdb6
# mkfs.ext3 -L tmp /dev/sdb7
# mkfs.ext3 -L usr /dev/sdb8
# mkfs.ext3 -L data /dev/sdb9
# mkfs.ext3 -L data /dev/sdb10
# mkfs.ext3 -L opt /dev/sdb11

Now it's time to copy the data to the new filesystems:

# mkdir /mnt/newdisk
# mount /dev/sdb2 /mnt/newdisk
# cd /mnt/newdisk; mkdir {dev,mnt,boot,opt,usr,var,tmp,home,data}
# mount /dev/sdb1 /mnt/newdisk/boot
# mount /dev/sdb6 /mnt/newdisk/var
# mount /dev/sdb7 /mnt/newdisk/tmp
# mount /dev/sdb8 /mnt/newdisk/usr
# mount /dev/sdb9 /mnt/newdisk/home
# mount /dev/sdb10 /mnt/newdisk/data
# mount /dev/sdb11 /mnt/newdisk/opt

And it's good to adjust the file modes for some entries:

# chmod +t /mnt/newdisk/tmp
# chmod go+rw /mnt/newdisk/tmp

The data from the old system is located on /mnt/sysimage.


Copy the data located on the new mount points:

# for dir in $(ls -1 /mnt/sysimage | grep '\(boot\|var\|tmp\|usr\|home\|opt\)'); do


\
> echo dir; \
> cp -v -ax /mnt/sysimage/$dir /mnt/newdisk/;\
> done;

And the data located on the root filesystem too, but exclude the contents of the
special directories /dev, /proc, /selinux and /sys:

# umount /mnt/sysimage/selinux
# for dir in $(ls -1 /mnt/sysimage | grep -v '\(boot\|var\|tmp\|usr\|home\|opt\|
sys\|proc\|dev\|mnt\|lost\)'); do \
> echo dir; \
> cp -v -ax /mnt/sysimage/$dir /mnt/newdisk/;\
> done;

Handle the /proc, /dev and /sys:

# mkdir /mnt/newdisk/{proc,sys,dev}
# chmod -w /mnt/newdisk/proc
# chmod go+w /mnt/newdisk/dev
# chmod +t /mnt/newdisk/dev

To make the target disk bootable, it's time to install the grub boot loader on it:

# mount -o bind /dev /mnt/newdisk/dev


# chroot /mnt/newdisk
# grub
> root (hd1,0)
> setup (hd1)
> quit
Because on the target disk LVM will not be required to boot, the kernel command
line
no longer requires the parameters rd_LVM_LV and these can be removed and replaced
by rd_NO_LVM. Also, pass on the command line the proper value for 'root='
parameter:

# vi /boot/grub/grub.conf

:s-/dev/mapper/VolGroup-lv_root-LABEL=root-g
:s-rd_LVM_LV=VolGroup/lv_root rd_LVM_LV=VolGroup/lv_swap-rd_NO_LVM-g
:wq

The new /boot/grub/grub.conf file now looks like:

# cat /boot/grub/grub.conf
# grub.conf generated by anaconda
#
# Note that you do not have to rerun grub after making changes to this file
# NOTICE: You have a /boot partition. This means that
# all kernel and initrd paths are relative to /boot/, eg.
# root (hd0,0)
# kernel /vmlinuz-version ro root=LABEL=root
# initrd /initrd-[generic-]version.img
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title centos (2.6.32-71.el6.i686)
root (hd0,0)
kernel /vmlinuz-2.6.32-71.el6.i686 ro

root=LABEL=root rd_NO_LVM
rd_NO_LUKS rd_NO_MD rd_NO_DM
LANG=en_US.UTF-8 SYSFONT=latarcyrheb-sun16
KEYBOARDTYPE=pc KEYTABLE=us crashkernel=auto rhgb quiet
initrd /initramfs-2.6.32-71.el6.i686.img

pertanto:

rd_LVM_LV=VolGroup/lv_root
root=/dev/mapper/VolGroup-lv_root

diventa
root=LABEL=root
aggiungo ma solo se non uso piu' LVM:
rd_NO_LVM
sparisce (perche' e' una partizione extended)
rd_LVM_LV=VolGroup/lv_swap

The contents of /etc/fstab from the target disk must be modified too:

# vi /etc/fstab
# the old mount point for / and swap location
#UUID=dbea6d02-7b89-4148-9ac1-da79af1c7027 /boot ext4 defaults
1 2
#/dev/mapper/VolGroup-lv_swap swap swap defaults 0 0
LABEL=root / ext3 defaults 1 1
LABEL=swap swap swap defaults 1 2
LABEL=boot /boot ext3 defaults 1 2
LABEL=home /home ext3 defaults 1 2
LABEL=var /var ext3 defaults 1 2
LABEL=tmp /tmp ext3 defaults 1 2
LABEL=usr /usr ext3 defaults 1 2
LABEL=opt /opt ext3 defaults 1 2
LABEL=data /data ext3 defaults 1 2

And finally, exit the chroot and schedule a complete filesystem selinux relabel,
otherwise the new installation won't be bootable:

# exit
# touch /mnt/newdisk/.autorelabel
# touch /mnt/newdisk/var/.autorelabel
# touch /mnt/newdisk/tmp/.autorelabel
# touch /mnt/newdisk/usr/.autorelabel
# touch /mnt/newdisk/home/.autorelabel
# touch /mnt/newdisk/opt/.autorelabel

Now it's time to power off the system, unplug the old disk, power on and boot from
the new disk.
On the first boot it will take a time for relabel to complete and it may require
a reboot.

After that, your new partitioned CentOS 6 system will be clonable and resizable
with standard imaging tools.

===================================================
SITUAZIONE INTERMEDIA
===================================================
Salito lasciando la sd-card inserita ed pertanto il boot originale, senza
ricompilare
grub ma semplicemente cambiando la linea di comando sul menu dell boot linux

]# mount
/dev/mapper/fedora-root on /run/media/root/075aac84-b44e-4061-a6c2-0a91d5066a9e
type xfs
(rw,nosuid,nodev,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota,uhelper=u
VECCHIA ROOT
/dev/mmcblk0p1 on /boot/efi type vfat
(rw,relatime,fmask=0077,dmask=0077,codepage=437,iocharset=ascii,shortname=winnt,err
ors=remount-ro) VECCHIO BOOT EFI
/dev/mmcblk0p2 on /boot type xfs
(rw,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota) VECCHIO BOOT

/dev/sda2 on / type ext4 (rw,relatime)


NUOVA ROOT
/dev/sda1 on /run/media/root/BOOTLNX type ext4
(rw,nosuid,nodev,relatime,uhelper=udisks2) NUOVO BOOT

================================================================================
AZARTICOLO:How to set up swap space?
================================================================================

Raspberry Pi has only 256 MB of RAM, so I would like to use swap space
(either on SD card or attached USB storage).
How do I set it up?
Swap on the Pi (and similar devices) can be painfully slow, and anything that
actually ends up using swap extensively will practically bring the system to
a standstill. Careful!

You know what would be good is a USB RAM drive


(not flash or SSD but actual volatile ram chip running at USB speeds)
It would do good for a such a swap pretty good.

The question is "How to set up swap space?"

Raspbian uses dphys-swapfile, which is a swap-file based solution instead of the


"standard" swap-partition based solution. It is much easier to change the size
of the swap.

The configuration file is:

/etc/dphys-swapfile

The content is very simple.


By default my Raspbian has 100MB of swap:

CONF_SWAPSIZE=100

cat /etc/dphys-swapfile
CONF_SWAPSIZE=1173
CONF_SWAPFILE=/var/swap

If you want to change the size, you need to modify the number and restart
dphys-swapfile:

/etc/init.d/dphys-swapfile stop
/etc/init.d/dphys-swapfile start

Edit: On Raspbian the default location is /var/swap, which is (of course) located
on the SD card.
I think it is a bad idea, so I would like to point out, that the /etc/dphys-
swapfile can have
the following option too: CONF_SWAPFILE=/media/btsync/swapfile

I only problem with it, the usb storage is automounted, so a potential race here
(automount vs. swapon)

This is the correct answer. None of other answers mentioned the dphys-swapfile.

You should not enable swap on the Raspberry Pi.


Although it is possible, it is not useful.
Even on a class 10 SDHC card, it is just too slow.
Also you will reduce the lifespan of the SD card.

On any flash-based storage device (SD card, SDD, USB thumb drives) you are also
likely to see system-wide pauses while a large group of flash blocks is erased.

Possible exceptions:

- If you connect a (magnetic) hard drive (though a USB-SATA or USB-IDE adapter)


- If you use ZRAM or something similar

no doubt swapping on a USB bey will kill your key very fast,
swapping on the SD card is also dangerous, even if newer ( class 10 )
SD cards could support it better.

- ZRAM is clearly the way to go if you need more RAM

You would think that with the ReadyBoost technology in Windows that someone would
make a USB Drive (or eSata, not sure if ReadyBoost can use that, would be of no
use
to raspberry pi, but would be interesting) that used actual RAM so you could boost
your computer performance.

Although it would probably be easier and cheaper to just buy a new motherboard
that supported the amount of RAM you need.

Why does this answer have so many upvotes?

There are plenty of reasons to use swap.

I used a swap file on an external drive to compile a large library over the course
of a few days.

It's slow as dead monkeys floating in molasses, but that doesn't meant that you
should "not do this at all."

You just have to be careful, and yes, there are usually better options, but
sometimes
you just do what you have to do.

You can set up swap space quite simply.

For example, if your USB drive is /dev/sdx, you would use (you must be root for
this):

$ mkswap /dev/sdx
$ swapon /dev/sdx

Note that this would use the whole device and you will probably lose all the
existing
data on it.

When you no longer need the swap file (if you want to eject the USB drive for
example),
you must use swapoff <device>. Not doing so will probably result in system crash.

You should be careful though.


SD cards have limited read/write limits and it will shorten its lifespan.
If you are using an external hard drive, you should be fine, but it will be very
slow.

I think you should change this to avoid users copy and pasting and accidentally
running mkswap on their root partition. I think sdx is a good convention.

Users who choose to enable SWAP may be interested in adjusting kernel swappiness.
Raspbian Jessie has swappiness 1 by default.

Raspbmc uses /etc/init/swap.conf to configure swap via /swap file.


It first checks for presence of /home/pi/.enable_swap.

If you delete /home/pi/.enable_swap then swap file is not created,


and then just recreate it with touch /home/pi/.enable_swap if you need swap turned
on and reboot.

It is a pity that the Raspberry Pis do not have GigaBit Ethernet but it is at least
theoretically possible to have swap space on a network device - the Linux Terminal
Server Project can offer it from the server to the clients according to this item
on their wiki.

You can also create a swap file (by using a loop device) like this:
dd if=/dev/zero of=/portatile2009.swp bs=1M count=1024 # For 1GB swap file

swapoff -a
chmod 600 /portatile2009.swp
mkswap /portatile2009.swp
swapon /portatile2009.swp

-----------------------------------------------------------------------------
swapoff -a
swapon -a

swapon --show=NAME,TYPE,SIZE,UUID,LABEL
NAME TYPE SIZE UUID LABEL
/portatile2009.swp file 1024M c6a3c9e0-4ea9-4723-824b-49ab89d1dfcb SWAPAREA

================================================================================
AZARTICOLO: How to migrate (move) logical volumes and volume groups from one disk
to another
disk online without reboot in Linux
================================================================================

In this article I will show you two methods to migrate a logical volume
/dev/rhel/lv1

from one disk to another without reboot assuming you have the extra disk already
available on your system.

Also in the end of the article a quick example to migrate all my logical volumes to
new partition (disk)

LVM Mirroring
LVM pvmove command

---------------------------------
Method 1: LVM Mirroring
--------------------------------

First of all let's check the mapped devices with the logical volumes,
here as you see my logical volume lv1 is residing on /dev/sdb1

[root@golinuxhub-server ~]# lvs -o+devices


LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
Devices
lv1 rhel -wi-a-----
1.00g /dev/sdb1(0)
root rhel -wi-ao----
<13.10g /dev/sda2(401)
swap rhel -wi-ao----
<1.57g /dev/sda2(0)

-----------------------------------------------------------------------------------
------------------------------
KODITV
-----------------------------------------------------------------------------------
-----------------------------
root@koditv bin]# lvs -o+devices

WARNING: scan found duplicate PVID FYXLlHypQ9nVWkzPIJoKEBzK40ZtVX0e on


/dev/mmcblk0p3
WARNING: Not using device /dev/sda1 for PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-
ZtVX0e.

WARNING: PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-ZtVX0e prefers device /dev/mmcblk0p3


because device is used by LV.
LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
Devices
root fedora -wi-ao----
7,32g /dev/mmcblk0p3(0)
[root@koditv bin]#
-----------------------------------------------------------------------------------
----------------------------

This logical volume is mounted on /lv1

[root@golinuxhub-server ~]# df -h

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/rhel-root 14G 7.0G 6.2G 54% / PARTIZIONE SYS


/dev/mapper/rhel-lv1 976M 2.6M 907M 1% /lv1 * PARTIZIONE DI TEST
/dev/sda1 1014M 160M 855M 16% /boot PARTIZIONE DI BOOT

-----------------------------------------------------------------------------------
-----------------------------
KODITV
-----------------------------------------------------------------------------------
-----------------------------

df -h

File system Dim. Usati Dispon. Uso% Montato su

/dev/mapper/fedora-root 5,5G 5,4G 22M 100% / PARTIZIONE SYS

/dev/mmcblk0p2 1014M 135M 880M 14% /boot PARTIZIONE DI BOOT


/dev/mmcblk0p1 599M 32M 568M 6% /boot/efi PARTIZIONE DI
BOOT EFI
-----------------------------------------------------------------------------------
-----------------------------

On this partition I have a single file which we will use to monitor our migration

[root@golinuxhub-server ~]# md5sum /lv1/myfile


5dd39cab1c53c2c77cd352983f9641e1 /lv1/myfile
[root@golinuxhub-server ~]# cat /lv1/myfile
This is a test file
Now introduce a new PV where we would like to move our new logical volume.
Hence I added a new virtual disk /dev/sdc

[root@golinuxhub-server ~]# lsscsi

[2:0:0:0] disk ATA VBOX HARDDISK 1.0 /dev/sda


[3:0:0:0] disk ATA VBOX HARDDISK 1.0 /dev/sdb
[4:0:0:0] disk ATA VBOX HARDDISK 1.0 /dev/sdc

So lets create a partition /dev/sdc1 on my newly added disk with partition type as
"Linux LVM"

[root@golinuxhub-server ~]# fdisk /dev/sdc


Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table


Building a new DOS disklabel with disk identifier 0x046a1def.

Command (m for help): n


Partition type:
p primary (0 primary, 0 extended, 4 free)
e extended
Select (default p): p
Partition number (1-4, default 1):
First sector (2048-4194303, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-4194303, default 4194303):
Using default value 4194303
Partition 1 of type Linux and of size 2 GiB is set

Command (m for help): t


Selected partition 1
Hex code (type L to list all codes): 8e
Changed type of partition 'Linux' to 'Linux LVM'

Command (m for help): p

Disk /dev/sdc: 2147 MB, 2147483648 bytes, 4194304 sectors


Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x046a1def

Device Boot Start End Blocks Id System


/dev/sdc1 2048 4194303 2096128 8e Linux LVM

Command (m for help): w


The partition table has been altered!

Calling ioctl() to re-read partition table.


Syncing disks.

Create a new physical volume using the new partition


[root@golinuxhub-server ~]# pvcreate /dev/sdc1
Physical volume "/dev/sdc1" successfully created.

Validate the newly created physical volume


[root@golinuxhub-server ~]# pvs
PV VG Fmt Attr PSize PFree
/dev/sda2 rhel lvm2 a-- <14.67g 4.00m
/dev/sdb1 rhel lvm2 a-- <1.94g 960.00m

/dev/sdc1 lvm2 --- <2.00g <2.00g

-----------------------------------------------------------------------------------
------------------------------
KODITV
-----------------------------------------------------------------------------------
-----------------------------

# pvs

WARNING: scan found duplicate PVID FYXLlHypQ9nVWkzPIJoKEBzK40ZtVX0e on


/dev/mmcblk0p3
WARNING: Not using device /dev/sda1 for PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-
ZtVX0e.
WARNING: PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-ZtVX0e prefers device /dev/mmcblk0p3
because device is used by LV.
PV VG Fmt Attr PSize PFree
/dev/mmcblk0p3 fedora lvm2 a-- 7,32g 0

-----------------------------------------------------------------------------------
------------------------------

Next extend the "rhel" volume group with the new physical volume
[root@golinuxhub-server ~]# vgextend rhel /dev/sdc1
Volume group "rhel" successfully extended

Use "-v" to enable the verbose option and see the list of partitions used for the
"rhel" volume group
[root@golinuxhub-server ~]# vgdisplay rhel -v

--- Volume group ---


VG Name rhel
System ID
Format lvm2
Metadata Areas 3
Metadata Sequence No 6
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 3
Open LV 3
Max PV 0
Cur PV 3
Act PV 3
VG Size 18.60 GiB
PE Size 4.00 MiB
Total PE 4762
Alloc PE / Size 4010 / 15.66 GiB
Free PE / Size 752 / <2.94 GiB
VG UUID W9RBxy-be7G-7Mai-unE9-CU1P-os6O-1IrAwg
--- Logical volume ---
LV Path /dev/rhel/swap
LV Name swap
VG Name rhel
LV UUID 5y06cM-RBdD-bP9o-XyTn-vODc-OkdS-1DCCj4
LV Write Access read/write
LV Creation host, time localhost, 2017-08-20 12:35:44 +0530
LV Status available
# open 2
LV Size <1.57 GiB
Current LE 401
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 8192
Block device 253:1

--- Logical volume ---


LV Path /dev/rhel/root
LV Name root
VG Name rhel
LV UUID 8XkPVc-spib-oNu8-3D5E-f1vT-6RpW-ivZvjL
LV Write Access read/write
LV Creation host, time localhost, 2017-08-20 12:35:44 +0530
LV Status available
# open 1
LV Size <13.10 GiB
Current LE 3353
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 8192
Block device 253:0

--- Logical volume ---


LV Path /dev/rhel/lv1
LV Name lv1
VG Name rhel
LV UUID 1B3itY-r46q-LMrz-Cby0-YqCt-XV1G-TmsqMx
LV Write Access read/write
LV Creation host, time golinuxhub-server.example, 2018-04-07 21:22:45 +0530
LV Status available
# open 1
LV Size 1.00 GiB
Current LE 256
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 8192
Block device 253:2

--- Physical volumes ---


PV Name /dev/sda2
PV UUID Qreqy9-GHr6-mlDN-D3ki-NU5k-3VUb-o2g34D
PV Status allocatable
Total PE / Free PE 3755 / 1

PV Name /dev/sdb1
PV UUID VqVvQi-I0BM-epGZ-lhpf-n48v-LM0u-yGGjgK
PV Status allocatable
Total PE / Free PE 496 / 240

PV Name /dev/sdc1
PV UUID 6Rzgfb-NOeK-MT5F-TrQ5-cM6i-si8v-192uWO
PV Status allocatable
Total PE / Free PE 511 / 511

-----------------------------------------------------------------------------------
------------------------------
KODITV
-----------------------------------------------------------------------------------
-----------------------------

<pre>[root@koditv bin]# pvs


WARNING: scan found duplicate PVID FYXLlHypQ9nVWkzPIJoKEBzK40ZtVX0e on
/dev/mmcblk0p3
WARNING: Not using device /dev/sda1 for PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-
ZtVX0e.
WARNING: PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-ZtVX0e prefers device /dev/mmcblk0p3
because device is used by LV.

PV VG Fmt Attr PSize PFree


/dev/mmcblk0p3 fedora lvm2 a-- 7,32g 0

[root@koditv bin]# vgdisplay fedora -v


WARNING: scan found duplicate PVID FYXLlHypQ9nVWkzPIJoKEBzK40ZtVX0e on
/dev/mmcblk0p3
WARNING: Not using device /dev/sda1 for PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-
ZtVX0e.
WARNING: PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-ZtVX0e prefers device /dev/mmcblk0p3
because device is used by LV.

--- Volume group ---


VG Name fedora
System ID
Format lvm2
Metadata Areas 1
Metadata Sequence No 7
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 1
Open LV 1
Max PV 0
Cur PV 1
Act PV 1
VG Size 7,32 GiB
PE Size 4,00 MiB
Total PE 1874
Alloc PE / Size 1874 / 7,32 GiB
Free PE / Size 0 / 0
VG UUID nuX1yZ-zMw7-Qd7p-Lxfh-qCnl-keR2-lyz7wf

--- Logical volume ---


LV Path /dev/fedora/root
LV Name root
VG Name fedora
LV UUID GJHzxN-WsnN-p8Ko-5owB-Im6E-URD2-K7njNe
LV Write Access read/write
LV Creation host, time localhost.localdomain, 2019-10-24 01:00:11 +0200
LV Status available
# open 1
LV Size 7,32 GiB
Current LE 1874
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 256
Block device 253:0

--- Physical volumes ---


PV Name /dev/mmcblk0p3
PV UUID FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-ZtVX0e
PV Status allocatable
Total PE / Free PE 1874 / 0
</pre>

-----------------------------------------------------------------------------------
-----------------------------

So everything looks correct, next again before starting with our migration last
time
lets again validate the partition used by our lv1 which is /dev/sdb1

[root@golinuxhub-server ~]# lvs -o+devices


LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy
%Sync Convert Devices
lv1 rhel -wi-ao---- 1.00g /dev/sdb1(0) BOOT PARTITION
root rhel -wi-ao---- <13.10g /dev/sda2(401) SYSTEM PARTITION
swap rhel -wi-ao---- <1.57g /dev/sda2(0) SWAP PARTITION

The same can be validated using below command

[root@golinuxhub-server ~]# dmsetup deps /dev/rhel/lv1


1 dependencies : (8, 17)

As you see we have only single dependency and it is mapped to 8,17 which you see
below is for /dev/sdb1

[root@golinuxhub-server ~]# ls -l /dev/ | grep sd

brw-rw---- 1 root disk 8, 0 Apr 7 21:25 sda


brw-rw---- 1 root disk 8, 1 Apr 7 21:25 sda1
brw-rw---- 1 root disk 8, 2 Apr 7 21:31 sda2

brw-rw---- 1 root disk 8, 16 Apr 7 21:25 sdb


brw-rw---- 1 root disk 8, 17 Apr 7 21:31 sdb1

brw-rw---- 1 root disk 8, 32 Apr 7 21:30 sdc


brw-rw---- 1 root disk 8, 33 Apr 7 21:31 sdc1

-----------------------------------------------------------------------------------
------------------------------
KODITV
-----------------------------------------------------------------------------------
-----------------------------
brw-rw---- 1 root disk 8, 0 19 dic 14.35 sda
brw-rw---- 1 root disk 8, 1 19 dic 14.36 sda1

brw-rw---- 1 root disk 179, 0 19 dic 14.36 mmcblk0


brw-rw---- 1 root disk 179, 1 19 dic 14.36 mmcblk0p1
brw-rw---- 1 root disk 179, 2 19 dic 14.36 mmcblk0p2
brw-rw---- 1 root disk 179, 3 19 dic 14.36 mmcblk0p3
-----------------------------------------------------------------------------------
-----------------------------

Let's start with the migration


--------------------------------------

We will create a single mirror using the below command

[root@golinuxhub-server ~]# lvconvert -m 1 rhel/lv1 /dev/sdc1

Are you sure you want to convert linear LV rhel/lv1 to raid1 with 2 images
enhancing resilience? [y/n]: y
Logical volume rhel/lv1 successfully converted.

Let's see if our file is still available


[root@golinuxhub-server ~]# cat /lv1/myfile
This is a test file

If we see the list of devices, it is a bit different because we are spanning two
underlying
devices as we are in a mirror formation

[root@golinuxhub-server ~]# lvs -o+devices

LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
Devices
lv1 rhel rwi-aor--- 1.00g 100.00
lv1_rimage_0(0),

lv1_rimage_1(0)
root rhel -wi-ao---- <13.10g
/dev/sda2(401)
swap rhel -wi-ao---- <1.57g
/dev/sda2(0)

The dmsetup should also show similar output as expected

[root@golinuxhub-server ~]# dmsetup deps /dev/rhel/lv1


4 dependencies : (253, 6) (253, 5) (253, 4) (253, 3)

Now we can break the mirror and get rid of old device which we wanted to remove
--------------------------------------

[root@golinuxhub-server ~]# lvconvert -m 0 rhel/lv1 /dev/sdb1


Are you sure you want to convert raid1 LV rhel/lv1 to type linear losing all
resilience? [y/n]: y
Logical volume rhel/lv1 successfully converted.

-----------------------------------------------------------------------------------
------------------------------
KODITV
-----------------------------------------------------------------------------------
-----------------------------
lvconvert -m 0 fedora/root /dev/mmcblk0p3

WARNING: scan found duplicate PVID FYXLlHypQ9nVWkzPIJoKEBzK40ZtVX0e on


/dev/mmcblk0p3
WARNING: Not using device /dev/sda1 for PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-
ZtVX0e.
WARNING: PV FYXLlH-ypQ9-nVWk-zPIJ-oKEB-zK40-ZtVX0e prefers device /dev/mmcblk0p3
because device is used by LV.
WARNING: fedora/root already has image count of 1.
Logical volume fedora/root successfully converted.

So the command executed sucessfully


-----------------------------------------------------------------------------------
----------------------------
Here you can see our logical volume lv1 is now residing on /dev/sdc1

[root@golinuxhub-server ~]# lvs -o+devices


LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
Devices
lv1 rhel -wi-ao----
1.00g /dev/sdc1(1)
root rhel -wi-ao----
<13.10g /dev/sda2(401)
swap rhel -wi-ao----
<1.57g /dev/sda2(0)

Same can be validated using dmsetup


[root@golinuxhub-server ~]# dmsetup deps /dev/rhel/lv1
1 dependencies : (8, 33)

[root@golinuxhub-server ~]# ls -l /dev/ | grep sd

brw-rw---- 1 root disk 8, 0 Apr 7 21:25 sda


brw-rw---- 1 root disk 8, 1 Apr 7 21:25 sda1
brw-rw---- 1 root disk 8, 2 Apr 7 21:38 sda2
brw-rw---- 1 root disk 8, 16 Apr 7 21:25 sdb
brw-rw---- 1 root disk 8, 17 Apr 7 21:38 sdb1
brw-rw---- 1 root disk 8, 32 Apr 7 21:30 sdc
brw-rw---- 1 root disk 8, 33 Apr 7 21:38 sdc1

The final test is to validate our file and its content which looks same as it was
before migration
[root@golinuxhub-server ~]# cat /lv1/myfile
This is a test file

[root@golinuxhub-server ~]# md5sum /lv1/myfile


5dd39cab1c53c2c77cd352983f9641e1 /lv1/myfile

Now since everything is done we don't need /dev/sdb1 anymore and can be safely
removed from "rhel" volume group
[root@golinuxhub-server ~]# vgreduce rhel /dev/sdb1
Removed "/dev/sdb1" from volume group "rhel"

Validate the same, as you see we no more have /dev/sdb1


[root@golinuxhub-server ~]# vgs -o+devices
VG #PV #LV #SN Attr VSize VFree Devices
rhel 2 3 0 wz--n- 16.66g 1.00g /dev/sda2(0)
rhel 2 3 0 wz--n- 16.66g 1.00g /dev/sda2(401)
rhel 2 3 0 wz--n- 16.66g 1.00g /dev/sdc1(1)

Method 2: Using pvmove


Here I will migrate our logical volume "lv1" from /dev/sdc1 to /dev/sdb1

Let us again extend our volume group with /dev/sdb1


[root@golinuxhub-server ~]# vgextend rhel /dev/sdb1
Volume group "rhel" successfully extended

Next monitor the device id using dmsetup and below command


[root@golinuxhub-server ~]# ls -l /dev | grep sd
brw-rw---- 1 root disk 8, 0 Apr 7 21:25 sda
brw-rw---- 1 root disk 8, 1 Apr 7 21:25 sda1
brw-rw---- 1 root disk 8, 2 Apr 7 21:40 sda2
brw-rw---- 1 root disk 8, 16 Apr 7 21:25 sdb
brw-rw---- 1 root disk 8, 17 Apr 7 21:40 sdb1
brw-rw---- 1 root disk 8, 32 Apr 7 21:30 sdc
brw-rw---- 1 root disk 8, 33 Apr 7 21:40 sdc1

[root@golinuxhub-server ~]# dmsetup deps /dev/rhel/lv1


1 dependencies : (8, 33)

Now time to migrate our logical volume from /dev/sdc1 to /dev/sdb1, the below
command may take some time
[root@golinuxhub-server ~]# pvmove -n lv1 /dev/sdc1 /dev/sdb1
/dev/sdc1: Moved: 1.56%
/dev/sdc1: Moved: 100.00%

So the migration is completed, validate this using dmsetup


[root@golinuxhub-server ~]# dmsetup deps /dev/rhel/lv1
1 dependencies : (8, 17)

[root@golinuxhub-server ~]# ls -l /dev | grep sd


brw-rw---- 1 root disk 8, 0 Apr 7 21:25 sda
brw-rw---- 1 root disk 8, 1 Apr 7 21:25 sda1
brw-rw---- 1 root disk 8, 2 Apr 7 21:40 sda2
brw-rw---- 1 root disk 8, 16 Apr 7 21:25 sdb
brw-rw---- 1 root disk 8, 17 Apr 7 21:40 sdb1
brw-rw---- 1 root disk 8, 32 Apr 7 21:30 sdc
brw-rw---- 1 root disk 8, 33 Apr 7 21:40 sdc1

[root@golinuxhub-server ~]# lvs -o+devices


LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
Devices
lv1 rhel -wi-ao----
1.00g /dev/sdb1(0)
root rhel -wi-ao----
<13.10g /dev/sda2(401)
swap rhel -wi-ao----
<1.57g /dev/sda2(0)

Everything looks perfect..


Lastly again re-validate your file content
[root@golinuxhub-server ~]# cat /lv1/myfile
This is a test file

[root@golinuxhub-server ~]# md5sum /lv1/myfile


5dd39cab1c53c2c77cd352983f9641e1 /lv1/myfile

A quick example migrating all my lvms to a new device /dev/sdd

Currently as you see my root and swap partition reside on /dev/sda which I intend
to move to /dev/sdd
[root@golinuxhub-server ~]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 15.7G 0 disk
├─sda1 8:1 0 1G 0 part /boot
└─sda2 8:2 0 14.7G 0 part
├─rhel-root 253:0 0 13.1G 0 lvm /
└─rhel-swap 253:1 0 1.6G 0 lvm [SWAP]
sdd 8:48 0 20G 0 disk
sr0 11:0 1 1024M 0 rom
sr1 11:1 1 1024M 0 rom

My volume group currently resides on /dev/sda2


[root@golinuxhub-server ~]# vgs -o+devices
VG #PV #LV #SN Attr VSize VFree Devices
rhel 2 3 0 wz--n- <16.61g 964.00m /dev/sda2(0)
rhel 2 3 0 wz--n- <16.61g 964.00m /dev/sda2(401)

Below are my two logical volumes which I intend to migrate


[root@golinuxhub-server ~]# lvs
LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
root rhel -wi-ao---- <13.10g
swap rhel -wi-ao---- <1.57g

Extend our "rhel" volume group with the new disk /dev/sdd
[root@golinuxhub-server ~]# vgextend rhel /dev/sdd
Volume group "rhel" successfully extended

[root@golinuxhub-server ~]# pvs


PV VG Fmt Attr PSize PFree
/dev/sda2 rhel lvm2 a-- <14.67g 4.00m
/dev/sdb1 rhel lvm2 a-- <1.94g 960.00m
/dev/sdd rhel lvm2 a-- <20.00g <20.00g

[root@golinuxhub-server ~]# pvmove -n root /dev/sda2 /dev/sdd


/dev/sda2: Moved: 0.03%
/dev/sda2: Moved: 100.00%

[root@golinuxhub-server ~]# pvmove -n swap /dev/sda2 /dev/sdd


/dev/sda2: Moved: 0.00%
/dev/sda2: Moved: 100.00%

As you see my root and swap logical volume is now residing on /dev/sdd
[root@golinuxhub-server ~]# lvs -o+devices
LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
Devices
root rhel -wi-ao----
<13.10g /dev/sdd(0)
swap rhel -wi-ao----
<1.57g /dev/sdd(3353)

Same for my volume group which now resides on /dev/sdd


[root@golinuxhub-server ~]# vgs -o+devices
VG #PV #LV #SN Attr VSize VFree Devices
rhel 4 3 0 wz--n- <38.60g 22.93g /dev/sdd(3353)
rhel 4 3 0 wz--n- <38.60g 22.93g /dev/sdd(0)

So both my root and swap partition are now migrated to /dev/sdd


[root@golinuxhub-server ~]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 15.7G 0 disk
├─sda1 8:1 0 1G 0 part /boot
└─sda2 8:2 0 14.7G 0 part
sdb 8:16 0 2G 0 disk
└─sdb1 8:17 0 2G 0 part
sdd 8:48 0 20G 0 disk
├─rhel-root 253:0 0 13.1G 0 lvm /
└─rhel-swap 253:1 0 1.6G 0 lvm [SWAP]
sr0 11:0 1 1024M 0 rom
sr1 11:1 1 1024M 0 rom

I hope the article was useful.


================================================================================
KODITV TUTTI I SERVIZI INSTALLATI
================================================================================

# systemctl -at service


UNIT
LOAD ACTIVE SUB DESCRIPTION
accounts-daemon.service
loaded inactive dead Accounts Service
alsa-restore.service
loaded inactive dead Save/Restore Sound Card State
alsa-state.service
loaded active running Manage Sound Card State (restore and store
atd.service
loaded active running Deferred execution scheduler
auditd.service
loaded inactive dead Security Auditing Service
auth-rpcgss-module.service
loaded inactive dead Kernel Module supporting RPCSEC_GSS
blk-availability.service
loaded inactive dead Availability of block devices
chronyd.service
loaded active running NTP client/server
dbus-broker.service
loaded active running D-Bus System Message Bus
dbxtool.service
loaded active exited Secure Boot DBX (blacklist) updater
dm-event.service
loaded inactive dead Device-mapper event daemon
dmraid-activation.service
loaded inactive dead Activation of DM RAID sets
dnf-makecache.service
loaded inactive dead dnf makecache
dracut-cmdline.service
loaded inactive dead dracut cmdline hook
dracut-initqueue.service
loaded inactive dead dracut initqueue hook
dracut-mount.service
loaded inactive dead dracut mount hook
dracut-pre-mount.service
loaded inactive dead dracut pre-mount hook
dracut-pre-pivot.service
loaded inactive dead dracut pre-pivot and cleanup hook
dracut-pre-trigger.service
loaded inactive dead dracut pre-trigger hook
dracut-pre-udev.service
loaded inactive dead dracut pre-udev hook
dracut-shutdown.service
loaded active exited Restore /run/initramfs on shutdown

emergency.service
loaded inactive dead Emergency Shell
● fcoe.service
not-found inactive dead fcoe.service
[email protected]
loaded active running Getty on tty1
[email protected]
loaded active running Getty on tty2
gssproxy.service
loaded active running GSSAPI Proxy Daemon
import-state.service
loaded active exited Import network configuration from initramf
initrd-cleanup.service
loaded inactive dead Cleaning Up and Shutting Down Daemons
initrd-parse-etc.service
loaded inactive dead Reload Configuration from the Real Root
initrd-switch-root.service
loaded inactive dead Switch Root
initrd-udevadm-cleanup-db.service
loaded inactive dead Cleanup udevd DB
irqbalance.service
loaded active running irqbalance daemon
● iscsi-shutdown.service
not-found inactive dead iscsi-shutdown.service
● iscsi.service
not-found inactive dead iscsi.service
● iscsid.service
not-found inactive dead iscsid.service
kmod-static-nodes.service
loaded active exited Create list of static device nodes for the
ldconfig.service
loaded inactive dead Rebuild Dynamic Linker Cache
● livesys-late.service
not-found inactive dead livesys-late.service
lm_sensors.service
loaded active exited Hardware Monitoring Sensors

● lvm2-activation-early.service
not-found inactive dead lvm2-activation-early.service
● lvm2-activation.service
not-found inactive dead lvm2-activation.service
lvm2-lvmpolld.service
loaded inactive dead LVM2 poll daemon
lvm2-monitor.service
loaded active exited Monitoring of LVM2 mirrors, snapshots etc.
lvm2-pvscan@179:3.service
loaded active exited LVM event activation on device 179:3

lxdm.service
loaded inactive dead LXDM (Lightweight X11 Display Manager)
mdmonitor.service
loaded inactive dead Software RAID monitoring and management
mlocate-updatedb.service
loaded inactive dead Update a database for mlocate
multipathd.service
loaded inactive dead Device-Mapper Multipath Device Controller
● network.service
not-found inactive dead network.service
● NetworkManager-wait-online.service
loaded failed failed Network Manager Wait Online
NetworkManager.service
loaded active running Network Manager
nfs-blkmap.service
loaded inactive dead pNFS block layout mapping daemon
nfs-convert.service
loaded inactive dead Preprocess NFS configuration convertion
nfs-idmapd.service
loaded inactive dead NFSv4 ID-name mapping service
nfs-mountd.service
loaded inactive dead NFS Mount Daemon
nfs-server.service
loaded inactive dead NFS server and services
nfs-utils.service
loaded inactive dead NFS server and client services
● nfsdcld.service
not-found inactive dead nfsdcld.service
● ntpd.service
not-found inactive dead ntpd.service
ntpdate.service
loaded active exited Set time via NTP
ostree-remount.service
loaded inactive dead OSTree Remount OS/ Bind Mounts
pcscd.service
loaded inactive dead PC/SC Smart Card Daemon
plymouth-quit-wait.service
loaded inactive dead Hold until boot process finishes up
plymouth-quit.service
loaded inactive dead Terminate Plymouth Boot Screen
plymouth-read-write.service
loaded inactive dead Tell Plymouth To Write Out Runtime Data
plymouth-start.service
loaded inactive dead Show Plymouth Boot Screen
plymouth-switch-root.service
loaded inactive dead Plymouth switch root service
polkit.service
loaded active running Authorization Manager
● rbdmap.service
not-found inactive dead rbdmap.service
rc-local.service
loaded inactive dead /etc/rc.d/rc.local Compatibility
rescue.service
loaded inactive dead Rescue Shell
rngd.service
loaded active running Hardware RNG Entropy Gatherer Daemon
rpc-gssd.service
loaded inactive dead RPC security service for NFS client and se
rpc-statd-notify.service
loaded active exited Notify NFS peers of a restart
rpc-statd.service
loaded inactive dead NFS status monitor for NFSv2/3 locking.
● rpc-svcgssd.service
not-found inactive dead rpc-svcgssd.service
rpcbind.service
loaded inactive dead RPC Bind
rsyslog.service
loaded active running System Logging Service
rtkit-daemon.service
loaded active running RealtimeKit Scheduling Policy Service
selinux-autorelabel-mark.service
loaded inactive dead Mark the need to relabel after reboot
● sntp.service
not-found inactive dead sntp.service
[email protected]
loaded inactive dead OpenSSH ecdsa Server Key Generation
[email protected]
loaded inactive dead OpenSSH ed25519 Server Key Generation
[email protected]
loaded inactive dead OpenSSH rsa Server Key Generation
sshd.service
loaded activating auto-restart OpenSSH server daemon
sssd-kcm.service
loaded inactive dead SSSD Kerberos Cache Manager
switcheroo-control.service
loaded inactive dead Switcheroo Control Proxy service
● syslog.service
not-found inactive dead syslog.service
systemd-ask-password-console.service
loaded inactive dead Dispatch Password Requests to Console
systemd-ask-password-plymouth.service
loaded inactive dead Forward Password Requests to Plymouth
systemd-ask-password-wall.service
loaded inactive dead Forward Password Requests to Wall
systemd-binfmt.service
loaded inactive dead Set Up Additional Binary Formats
systemd-boot-system-token.service
loaded inactive dead Store a System Token in an EFI Variable
systemd-firstboot.service
loaded inactive dead First Boot Wizard
systemd-fsck-root.service
loaded active exited File System Check on Root Device
systemd-hwdb-update.service
loaded inactive dead Rebuild Hardware Database
systemd-initctl.service
loaded inactive dead initctl Compatibility Daemon

systemd-journal-catalog-update.service
loaded inactive dead Rebuild Journal Catalog
systemd-journal-flush.service
loaded active exited Flush Journal to Persistent Storage
systemd-journald.service
loaded active running Journal Service
systemd-logind.service
loaded active running Login Service

systemd-machine-id-commit.service
loaded inactive dead Commit a transient machine-id on disk
systemd-modules-load.service
loaded active exited Load Kernel Modules
systemd-quotacheck.service
loaded inactive dead File System Quota Check
systemd-random-seed.service
loaded active exited Load/Save Random Seed
systemd-remount-fs.service
loaded active exited Remount Root and Kernel File Systems
systemd-rfkill.service
loaded inactive dead Load/Save RF Kill Switch Status
systemd-sysctl.service
loaded active exited Apply Kernel Variables
systemd-sysusers.service
loaded inactive dead Create System Users
systemd-timesyncd.service
loaded inactive dead Network Time Synchronization
systemd-tmpfiles-clean.service
loaded inactive dead Cleanup of Temporary Directories
systemd-tmpfiles-setup-dev.service
loaded active exited Create Static Device Nodes in /dev
systemd-tmpfiles-setup.service
loaded active exited Create Volatile Files and Directories
systemd-udev-settle.service
loaded active exited udev Wait for Complete Device Initializati
systemd-udev-trigger.service
loaded active exited udev Coldplug all Devices
systemd-udevd.service
loaded active running udev Kernel Device Manager

systemd-update-done.service
loaded inactive dead Update is Completed
systemd-update-utmp-runlevel.service
loaded inactive dead Update UTMP about System Runlevel Changes
systemd-update-utmp.service
loaded active exited Update UTMP about System Boot/Shutdown

systemd-user-sessions.service
loaded active exited Permit User Sessions
systemd-vconsole-setup.service
loaded inactive dead Setup Virtual Console
udisks2.service
loaded active running Disk Manager
unbound-anchor.service
loaded inactive dead update of the root trust anchor for DNSSEC
upower.service
loaded active running Daemon for power management
[email protected]
loaded active exited User Runtime Directory /run/user/0
[email protected]
loaded active running User Manager for UID 0
[email protected]
not-found inactive dead [email protected]
zram-swap.service
loaded active exited Enable compressed swap in memory using zra

systemd-fsck@dev-disk-by\x2duuid-983cb62e\x2d687a\x2d49e0\x2d9a7c\
x2db9a403fc4027.service loaded active exited File System Check on
/dev/disk/by-uuid/983
systemd-fsck@dev-disk-by\x2duuid-B7C7\x2dD61F.service
loaded active exited File System Check on /dev/disk/by-uuid/B7C

================================================================================
UBUNTU partition scheme for dual boot with android-x86
================================================================================

For an old Inspiron 1420 laptop, how can I dual boot (not VirtualBox) with
android-x86? What options do I select when installing Ubuntu 16.04 that the
partition scheme will work for both OS's.

GPT from Android x86 shows:

sda1 ext3 FUJITSUMHV2080B

However, I'm not terribly familiar with GPT and would have to do quite a bit of
reading to understand the codes it uses for different types of formatting.

dual-boot grub2 partitioning hard-drive android


shareimprove this question
edited Jun 5 '16 at 12:16
You'reAGitForNotUsingGit
12.7k88 gold badges3535 silver badges6767 bronze badges
asked Jun 5 '16 at 12:06
Thufir
3,3231111 gold badges5555 silver badges111111 bronze badges

FYI it'll probably not be a quick solution. – You'reAGitForNotUsingGit Jun 5


'16 at 12:17
if I wanted to dual boot ubuntu and fedora, that would be much easier? – Thufir
Jun 5 '16 at 22:00
Yes. Much, much easier. – You'reAGitForNotUsingGit Jun 6 '16 at 0:10

add a comment
1 Answer
active
oldest
votes
0

I believe this is adaptable for use on any Ubuntu distribution to dual boot with
Android X86 without having to use separate partitions for each OS.
This works thanks to the ability to use the same ext4 journaling file system for
both operating systems. It took me a couple days to compile this.
If your Ubuntu or Android X86 distribution are different, simply remember to make
the appropriate terminal command changes (Android X86 4.4 to 5.1 would look like;
initrd /android-4.4-r3/initrd.img} to initrd /android-5.1-r1/initrd.img}).
Check system for 64 bit support before downloading .ISO files.
If your system does not support 64 bit, use 32 bit, or 86 bit.

How to install dual boot of Android 4.4 x86 r3 and Ubuntu (on the same partition)
(Works with other revisions and versions of Android X86)

Things you will need:


Non-partitioned HDD (formatted)
(x2) USB flash drives 2GB or larger
Secondary PC to flash .ISO files to USB flash drives

Begin by downloading Unetbootin, and .ISO files for both Android x86, and Ubuntu.

Flash the .ISO files to each of the USB flash drives.

Enter BIOS on PC with formatted HDD and enable booting from USB/CD.

Reboot PC with USB flash drive inserted containing Ubuntu .ISO and complete a full
install.

Reboot PC with USB flash drive inserted containing Android x86 4.4 r3 and begin
install following these exceptions:

When prompted, select HDD sda1 and DO NOT format or select another file system.
When prompted, DO NOT install GRUB, or EFI GRUB 2.
When prompted, select as read and write.

Remove all media and boot the PC (it will automatically load Ubuntu).

Open the terminal and type:

sudo -i
nano /etc/grub.d/40_custom

Using the arrow keys, navigate the the line below the last current entry in the
custom boot loader menu and make the following four entries:

menuentry "Android-x86" {
set root='(hd0,1)'
linux /android-4.4-r3/kernel quiet root=/dev/ram0 androidboot.hardware=generic_x86
acpi_sleep=s3_bios,s3_mode SRC=/android-4.4-r3
initrd /android-4.4-r3/initrd.img}

Press and hold ctrl, x, then press y, and then press Enter

Type:

sudo chmod +x /etc/grub.d/40_custom


sudo update-grub
sudo reboot

Immediately after BIOS loads, press and hold the Shift key until GRUB loads.

Select which operating system you wish to use.

RECOMMENDED! Load Ubuntu first, and create a disk image (.ISO file) of your new
dual boot set-up and flash it to another USB flash drive and store it as a backup.
You can do this after you apply any updates, or install any programs you wish.

The result should be a dual booted Ubuntu and Android X86 utilizing the default
Ubuntu GRUB2 boot loader menu with the benefits of; no separate partition for
OS's, shared Linux swap space, same file system (ext4), space for installation of
Android applications limited ONLY to the space remaining on your HDD
(not a weak 2Gb-??Gb partition), and the ability to file browse between Ubuntu
and Android X86. Essentially you have installed Android X86 within Ubuntu.
note: Unetbootin now has a self contained application downloadable and compatible
with Windows.
================================================================================
dracut --regenerate-all --force -v
================================================================================

===================================================================================
===========
AZARTICOLO:Simple I/O device driver for RaspberryPi
===================================================================================
===========
https://www.codeproject.com/Articles/1032794/Simple-I-O-device-driver-for-
RaspberryPi

Introduction
------------

The fancy little gadget Raspberry Pi is for sure a nice toy to play with.
But running the wheezy Linux it also is a complete Linux embedded system running on
an ARM platform. That makes it quite interesting for programming and brought me to
the idea to implement an I/O device driver on it, just to set on and off a digital
output and
to read the state of a input.

To build a device driver on RaspberryPi is basically the same as building one on


another
Linux system. But there are some small differences that makes it worth sharing
it :-)

Building the environment


-------------------------

To compile a device driver on Linux there are some special source files necessary.
These files build the interface to the kernel and they are called kernel header
files.
These header files must be of the same version as the kernel the driver should work
whit later on and they are not included in the Wheezy distributions.

So they have to be downloaded from the Internet.


Here now already is a first little difference between Raspi and the rest of the
Linux world:

Normally the kernel header files can be obtained by the simple command (entered in
a XTerminal)

apt-get install linux-headers-$(uname -r)

This command reads the actual kernel version by “uname -r”, downloads the correct
header files and installs them in the correct directory.

But this does not work on Raspi.

By some reason the kernel header files that fit to the available Wheezy
distributions
cannot be found like this. Even though there are header files of almost the same
version
available, that should not be considered.
A kernel driver can be compiled whit these header files but it will not be
loadedinto the
Kernel if the version does not fit exactly.

So there is only one solution: A new Kernel must be compiled and installed.
That installs the suitable kernel header files as well.

On the RaspberryPi Page there are many good hints to be found. On

https://www.raspberrypi.org/documentation/linux/kernel/

There is a good description how the download, compile and install an new kernel
with
following commands:

Get the new source with


------------------------

git clone --depth=1 https://github.com/raspberrypi/linux


Add some missing dependencies by (Whatever this means :-))

apt-get install bc

Now there should be a directory “linux” in the working directory of the current
user.
Change to this directory by “cd linux” and from there the new kernel should be
configured
before it can be compiled. For this there are different opinions now:
The Raspi page recommends to use the default configuration by the command

make bcmrpi_defconfig
I did so and that worked fine.

In some descriptions they use the old configuration of the current kernel by

make oldconfig
This is basically possible.
But keep in mind: The new kernel will offer many new features that were not
configured
in the old configuration. So you might be asked many strange questions like

Support for paging of anonymous memory yes or no

System V IPC yes or no

And you have to make the right decision each time.


If you go wrong in one of these questions, Raspi will show that by an error message
after maybe 8 hours of compiling time.
That’s quite frustrating.
So better just make the default configuration :-)

Now the kernel compilation can be started and Raspy can be left on its one for a
while.
Call the commands

make
make modules
make modules_install
If everything goes well, a new file “Image” should be in the directory
“arch/arm/boot/”
something around 8 hours later. This is our new kernel.

This file should be renamed to “kernel.img” and copied into the “/boot” directory
of the
system by

cp arch/arm/boot/ kernel.img /boot/


Now we are ready to reboot the new kernel. After a reboot the new version should be
displayed at the command

uname –r
The kernel header files are installed now and can be found in the directory
“/lib/modules/”

Implementing the driver


-----------------------

A Linux device driver must have a defined structure that contains at least
following functions:

int init_module(void)
to load the driver

void cleanup_module(void)
to unload the driver.

Beside these two functions we need some more to read or write into our device and a
function to open and one close the device.

static ssize_t device_read(struct file *filp, char *buffer, size_t length, loff_t
* offset)
static ssize_t device_write(struct file *filp, const char *buff, size_t len, loff_t
* off)
static int device_open(struct inode *inode, struct file *file)
static int device_release(struct inode *inode, struct file *file)

These functions have to be registered in the kernel when the driver is loaded.
Therefore the structure file_operations is used. In this structure for each
function there is a pre-defined reference that gets a pointer to the corresponding
function. That looks like this

static struct file_operations fops = {


.owner = THIS_MODULE,
.open = device_open,
.release = device_release,
.read = device_read,
.write = device_write
};

init_module(void)

In the function init_module the driver will be registered in the kernel. It is


called automatically
when the driver is loaded into the kernel by the insmod command.
The registration is done by the command
Major = register_chrdev(0,DEVICE_NAME, &fops);

The register_chrdev function basically gets the Major number of the driver as first
parameter. For the kernel the Major number is the identifier of a driver and it
will be linked to the device name handed to the register_chrdev function as the
second parameter.

The Major number can be a fixed number or just a 0 as here. If it is 0, the kernel
will check what Major number is available on the system and give this to our driver
by self. This might be the best solution if a driver is meant to be distributed and
installed on different systems. On a small embedded system where the environment
does not change during its live time, the Major number can be set to a fixed number
as well. In this case an available Major number must be defined by the developer
himself. Therefore the file /proc/devices must be checked and a number that is not
already in use there must be found.

The last parameter given to register_chrdev is the file_operations structure.

If the registration succeeds, the function returns the Major number that has been
given to our device. This number must be kept as we need it again for unloading the
driver.

Now the driver needs to check whether the I/O region or the Mem region it wants to
read or write to is not occupied by somebody else and reserve this area for
himself. Therefore we have to have a look into the hardware of Raspi. Now there is
another small difference to at least the i86 world. On Raspi the I/O’s are kept in
the memory range and not in the I/O range and if that wouldn’t be enough. This
memory area is mapped to another area J

In the description under

https://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf

the control addresses of the GPIO port are explained like that.

But as I mentioned: That’s not where they really are. The address 0x7E20 0000 is
mapped to 0x2020 0000 and so on. So to check the memory area we need the command

check_mem_region(PORT, RANGE)
with

static unsigned PORT = 0x20200000;


static unsigned RANGE = 0x40;
and if that succeeds

request_mem_region(PORT, RANGE, DEVICE_NAME);


to reserve this region (in case of a I/O port area it would be check_region(PORT,
RANGE) and request_ region(PORT, RANGE, DEVICE_NAME)). If this also works, the
memory area is reserved and the driver can use it. That means the task of the
init_module function is done and it can return SUCCESS to indicate that.

cleanup_module(void)
The cleanup_module function is called when the driver is unloaded. It releases the
memory area and unregisters the driver. Therefore the commands

release_mem_region(PORT, RANGE);
unregister_chrdev(Major, DEVICE_NAME);
should be called (here we need the Major number again).

That’s for the loading and unloading of the driver. How exactly the loading and
unloading is done will be explained further down.

device_open(struct inode *inode, struct file *file)


Before we can write into or read from our memory area we have to open the device
that covers this “thing” now. The device_open function prepares the device for
being used. That means here we have to make sure that only one application can use
the device at once, make sure the driver cannot be unloaded while somebody is using
it and set up the I/O ports the way we want to use them. For the first check the
variable Device_Open is used. If the device will be opened this variable will be
incremented and at the entrance of the function we check whether it is 0 or not to
see if it is already in use or not. For the protection against unloading we use
try_module_get(THIS_MODULE). This function increments a internal counter that
prevents the driver from being unloaded as long as this counter is not 0. The
counter will be decremented again by module_put(THIS_MODULE) when der device is
closed later on.

If everything went fine so far, we can start using the device now. That means, we
can set up the ports the way we want to use them. Therefore we have to do another
remapping of the address range we want to use. The kernel function ioremap returns
the needed remapped address to a pointer.

addr = ioremap(PORT, RANGE);


Here it’s important to note, that our address pointer “addr” is a byte pointer of
the type u8 even if we want to write 32 bit values. We will set up a port by the
command

writel(cmd, (addr+4));
to the base address plus an offset of 4 we get to the “function select 1” register.
The offset 4 will be converted to 4 byte addresses because addr is a byte pointer.
That’s important to know. If addr would be of another type, that would have to be
considered in the addressing. In case we want to use a u32 pointer the offset found
in the hardware documentation needed to be divided by 4. Of course it is possible
and o.k. to do it like this, but it’s not too clear if one wants to see how things
work. So maybe better stay with the u8 pointer for the addressing :-)

Setting up the ports


To set up the function of each port Raspy uses the 4 “function select” registers.
Each of these registers controls 10 GPIO pins except the last one. That controls 8.
The function of each pin is bit coded in these registers. Each pin gets 3 bits to
set up its function. The coding is as follows

000 = GPIO Pin is an input


001 = GPIO Pin is an output
100 = GPIO Pin takes alternate function 0
101 = GPIO Pin takes alternate function 1
110 = GPIO Pin takes alternate function 2
111 = GPIO Pin takes alternate function 3
011 = GPIO Pin takes alternate function 4
010 = GPIO Pin takes alternate function 5
With my device driver I want to set just the GPIO pin 10 as output and read GPIO
pin 14 as input. So I have to write a set up command into the “function set 1”
register with offset 4. To get a clear situation I first set all GPIO pins 10 to 19
as inputs by the command

cmd = 0;
writel(cmd, (addr+4));
Then I can set up pin 10 as output by:

cmd = 1;
writel(cmd, (addr+4));
That’s all we have to do here.

static ssize_t device_write(struct file *filp, const char *buff, size_t len, loff_t
* off)
To set or clear our GPIO pin we implement the device_write function. Raspy provides
the “GPIO pin output set 0” and “GPIO pin output set 1” register to set an output.
We have to use the first one to set pin 10. The pins are set bit coded. That means
we have a 32 bit value and each bit represents one pin. Pin 10 is represented by
the bit 10 and to set pin 10 we can use the commends

cmd = 1 << 10;


writel(cmd, (addr+0x1c));
This command has to be carried out just once to set the pin. The pin will stay set
until a clear command is called. That’s a bit different from other peripherals
where an output has to be set by a static command.

To clear the pin we have to do the same on the “GPIO pin output clear 0” register.

cmd = 1 << 10;


writel(cmd, (addr+0x28));

static ssize_t device_read(struct file *filp, char *buffer, size_t length, loff_t *
offset)
Reading the state of the inputs is implemented in the device_read function. We can
read the state of the pins 0 to 31 in the “GPIO pin level 0” register. Here we get
the state of each pin bit coded again.

res = readl(addr+0x34);
returns the state into the u32 variable res. From this variable I extract the 4 u8
parts and copy them into the array buf by:

buf[0] = res & 0xFF;


buf[1] = (res >> 8) & 0xFF;
buf[2] = (res >> 16) & 0xFF;
buf[3] = (res >> 24) & 0xFF;
and, as we return this array in a char* buffer, we have to terminate buf by a 0.
buf[4] = 0;
To move this data from kernel space to user space we use the put_user function:

index = 4;
while (length && (index >= 0))
{
put_user(*(msg_Ptr++), buffer++);
length--;
index--;
bytes_read++;
}
return bytes_read;
Whth this implementation an application can read the bit coded state of all the
GPIO pins by one device_read call.

Compiling the driver


To compile a device driver module there is a kind of a special procedure. We have
to work with a make file and define the compiling in this file. There are several
kernel modules that have to be loaded during compilation. The only way to get this
done correctly is to use a make file. My make file contains of following 5 lines:

obj-m := raspy_io.o
all:
make -C /lib/modules/4.0.9+/build M=$(PWD) modules
clean:
make -C /lib/modules/4.0.9+/build M=$(PWD) clean
I’m using the Kernel version 4.0.9+ and the Kernel header files are in
/lib/modules/4.0.9+. From there the Kernel modules should be included. My own
source files are in the same directory as the make file is. Therefore I can just
set the current path as source path by “M=$(PWD)”. When we start compilation be the
command “make” (in the same directory), the compiler looks for the raspy_io.c file,
compiles and links it to a raspy_io.ko. This is the module that can by loaded into
the kernel.

Loading the driver into the kernel


To load the driver into the kernel is quite a task :-). We have to insert the
module into the kernel, then we have to create a device knot in the /dev directory
and for this knot we have to set the correct permission’s to make it loadable by an
application. But, step by step.

To insert the module into the kernel we can call

insmod raspy_io.ko
That’s quite easy.

But now the complicate part begins. To create the knot we need to know the “Major
number” of the device we implemented in our driver. There are two ways to get this
number now. One way is to set the Major number fix in the code of our driver in the
function register_chrdev that we have to call in the init_module function. But for
this we need to know a Major number that is available on the system we want to use
our driver. Basically we can look up all the used numbers in the file devices in
the /proc directory and us one that is not listed there. That could work on a small
embedded system that would remain as is for all the time. But as we probably want
to use our driver on a system where other drivers could be installed later on, we
should go the other way and let the system give us an available Major number
dynamically while inserting the driver into the Kernel and find out which one we
got by self. I implemented my driver in this way already.

The insmod command calls the init_module function and orders a Major number from
the Kernel. This number is listed in the /pro/devices file immediately and we can
read this number from the devices file. To do this I use the magnificent AWK tool.
AWK is a mighty tool, but a hell of complicate :-)

The command to get the Major number in a shell script looks like this:

module="raspy_io.ko"
device="io_dev"
major=`cat /proc/devices | awk "{if(\\$2==\"$device\")print \\$1}"`
The command cat /proc/devices lists all entries from devices an hands this to awk
as a table containing all the Major numbers in the first row and the device names
in the second row. Awk parses all lines now and checks if the value of the second
row (the $2) is our "io_dev". If yes, it thakes the value of the first row ($1) and
returns it to our “major” script variable. Using this major variable I first make
sure the knot I want to create is deleted and create it new by

rm -f /dev/${device} c $major 0
mknod /dev/${device} c $major 0
Now I have to set the permission’s to read and write the device by

chmod 666 /dev/${device}


and that’s it. The device can be used now. It has the name "io_dev" and all users
can read or write it.

I put this commands into a shell script named “load.sh”. This script can be called
as root and inserts and registers the device ready for use.

Using the driver


To use the device that we created we just have to open it first in read/write mode
by

int fd;
fd = open("/dev/io_dev", O_RDWR);
If this succeeds, fd will be > 0 and we can read or write by

char buf[4];
char wbuf[4];
read(fd, buf, sizeof(buf));
Set pin 14 by

wbuf[0] = 1;
wbuf[1] = 0;
write(fd, wbuf, sizeof(wbuf));
and clear it by

wbuf[0] = 0;
wbuf[1] = 0;
write(fd, wbuf, sizeof(wbuf));
At the end we have to release the driver again by
close(fd);
To compile an application using a device driver the fcntl.h mus be included by

#include <fcntl.h>
To edit the driver source and the test application is used Geany (to install “apt-
get install geany”). Geany is a handy little C-editor. The GCC compiler should be
pre-installed on Raspy. That’s all I needed :-)

Points of Interest
For deeper studies I recommend the book Linux Device Drivers by O’Reilly‘s. That’s
a very comprehensive book (as O’Reilly‘s books usually are :-) ) very helpful for
programming Linux Device Drivers.

License
This article, along with any associated source code and files, is licensed under
The Code Project Open License (CPOL)

Share
TWITTER
About the Author

Mosi_62
Software Developer (Senior) Güdel AG, Langenthal
Switzerland Switzerland
Computers are very straight... They always do exactly what we tell them to do...
Only, much too often what we tell them to do is not really what we want them to do
Smile | :)

Writing Software is one of the most creative tings one can do. I have been doing
this for more than ten years now and still having a lot of fun with it. Besides
doing software for HMI's on C# for business, I enjoy very much to implement
interesting algorithms and analyse the mathematics they are based on in my leisure
time Smile | :)

For more detailed descriptions and math visit me on my own page

www.mosismath.com

=================================================================================
===================================================================================
=========
AZARTICOLO:RPI vcgencmd usage
===================================================================================
=========
RPI vcgencmd usage
Verified commands

Command outputs are from firmware version 362371.

vcgencmd commands

Shows a list of possible commands.

root@raspberrypi:~# vcgencmd commands


commands="vcos, ap_output_control, ap_output_post_processing, vchi_test_init,
vchi_test_exit,
pm_set_policy, pm_get_status, pm_show_stats, pm_start_logging, pm_stop_logging,
version, commands,
set_vll_dir, led_control, set_backlight, set_logging, get_lcd_info,
set_bus_arbiter_mode,
cache_flush, otp_dump, codec_enabled, measure_clock, measure_volts, measure_temp,
get_config,
hdmi_ntsc_freqs, render_bar, disk_notify, inuse_notify, sus_suspend, sus_status,
sus_is_enabled,
sus_stop_test_thread, egl_platform_switch, mem_validate, mem_oom, mem_reloc_stats,
file,
vctest_memmap, vctest_start, vctest_stop, vctest_set, vctest_get"

(I've just checked on a more recent firmware version and there's now also
get_camera, get_mem
and hdmi_status_show commands)

vcgencmd measure_clock <clock>

Shows clock frequency, clock can be one of arm, core, h264, isp, v3d, uart, pwm,
emmc, pixel, vec, hdmi, dpi.

root@raspberrypi:~# \
> for src in arm core h264 isp v3d uart pwm emmc pixel vec hdmi dpi ; do \
> echo -e "$src:\t$(vcgencmd measure_clock $src)" ; \
> done
arm: frequency(45)=700000000
core: frequency(1)=250000000
h264: frequency(28)=0
isp: frequency(42)=250000000
v3d: frequency(43)=250000000
uart: frequency(22)=3000000
pwm: frequency(25)=0
emmc: frequency(47)=100000000
pixel: frequency(29)=154000000
vec: frequency(10)=0
hdmi: frequency(9)=163682000
dpi: frequency(4)=0

vcgencmd measure_volts <id>

Shows voltage.
id can be one of core, sdram_c, sdram_i, sdram_p, and defaults to
core if not specified.

root@raspberrypi:~# \
> for id in core sdram_c sdram_i sdram_p ; do \
> echo -e "$id:\t$(vcgencmd measure_volts $id)" ; \
> done
core: volt=1.20V
sdram_c: volt=1.20V
sdram_i: volt=1.20V
sdram_p: volt=1.23V

vcgencmd measure_temp
Shows core temperature of BCM2835 SoC.

root@raspberrypi:~# vcgencmd measure_temp


temp=42.8'C

vcgencmd codec_enabled <codec>

Shows if the specified codec is enabled, codec can be one of H264, MPG2, WVC1,
MPG4, MJPG, WMV9.
Please note this was run on a Pi with the MPG2 and VC1 licences enabled.

root@raspberrypi:~# \
> for codec in H264 MPG2 WVC1 MPG4 MJPG WMV9 ; do \
> echo -e "$codec:\t$(vcgencmd codec_enabled $codec)" ; \
> done
H264: H264=enabled
MPG2: MPG2=enabled
WVC1: WVC1=enabled
MPG4: MPG4=enabled
MJPG: MJPG=enabled
WMV9: WMV9=enabled

If you also follow the instructions in this Forum post then the codec options
for VP6 and VP8 (WEBM) also work, this is experimental and unsupported at present
so any changes are at your own risk.

vcgencmd get_config [config|int|str] Will print the configurations you have set.
Argument can ether be a specific option or int, showing all configs with number-
datatype,
or str showing all configurations with datatype sting (aka text).

root@raspberrypi:~# vcgencmd get_config int


arm_freq=1000
core_freq=500
sdram_freq=600
over_voltage=6
disable_overscan=1
force_pwm_open=1

vcgencmd get_mem arm/gpu

Shows how much memory is split between the CPU (arm) and GPU.

root@raspberrypi:~# vcgencmd get_mem arm && vcgencmd get_mem gpu


arm=448M
gpu=64M

vcgencmd version

Shows the firmware version

root@raspberrypi:~# vcgencmd version


Jan 13 2013 16:24:29
Copyright (c) 2012 Broadcom
version 362371 (release)
vcgencmd otp_dump

Displays the contents of the OTP (One Time Programmable) memory embedded inside the
SoC.

root@raspberrypi:~# vcgencmd otp_dump

Locations 28 and 30 store the Serial and Revision values that get displayed by
/proc/cpuinfo
(the Serial is also used to determine the Ethernet MAC address on Model B boards),
and location
32 stores the value of the warranty bit. Purpose of values in other locations is
unknown.

vcgencmd set_backlight
Currently unusable, might be used in the future to control the backlight of LCD
displays

vcgencmd render_bar
Debug function created by Dom, used in OMXPlayer

vcgencmd display_power 0
Turns off video output.

vcgencmd display_power 1
Turns on video output.

Parameters and function of other vcgencmd commands are not known.

Links

This list also lists and describes vcgencmd options

===================================================================================
=========
AZARTICOLO:Custom Conky on the Raspberry Pi 2
===================================================================================
=========

I thought I’d share my Conky configuration currently running on my Pi for anyone


interested,
as it’s a great tool for displaying useful system information on the desktop.
It’s designed for a 480×320 resolution screen, as it is running on this
touchscreen,
and it takes up all the available space on the Raspbian desktop, minus the menu bar
(26 pixels high).

One problem that took me quite a while to solve was how to actually get Conky to
launch at startup,
as none of the usual methods seemed to work. In the end I found two ways of calling
a startup script.
First, create a simple Bash script, like this:

startConky.sh

#!/bin/bash
sleep 10 && conky -c ~/Scripts/.conkyrc_raspberry-pi-2 -d
Save it e.g. as ~/Scripts/startConky.sh.

Then, make the script execute at startup in one of the following two ways:

Open the file /etc/xdg/lxsession/LXDE-pi/autostart


as, and add the following line to the end (solution found here):
@~/Scripts/startConky.sh

-----------------------
My Conky config:
----------------------

.conkyrc_raspberry-pi-2

# Conky config file

# Avoid flicker
double_buffer yes

# Window
# Own window to run simultaneous 2 or more conkys
own_window yes
own_window_type normal
own_window_hints undecorated, below, sticky, skip_taskbar, skip_pager
#own_window_transparent yes

# Borders
draw_borders no

# Shades
draw_shades yes

# Position
gap_x 0
gap_y 34
alignment top_middle

# Behaviour
update_interval 2

# Font
#font arial
use_xft yes
#xftfont arial:size=8
xftfont Bitstream Vera Sans Mono:size=8
#xftfont Terminus:size=8
xftalpha 1 # Text alpha when using Xft

# Colours
#default_color d1d3c9
#default_shade_color 000000
own_window_colour 2B2B2B

# Prevent window from moving


use_spacer none

# Minimum size of window


minimum_size 464 280
# Maximum width of window
maximum_width 464

TEXT
${font Arial:size=12}${color #ddaa00}${time %I:%M %p}${font} $alignc$
{color #9fb6cd}UpTime: ${color }$uptime $alignr${color #9fb6cd}Temp.: ${color
ff0000}${execi 2 vcgencmd measure_temp | sed 's/[^0-9.]*//g'} °C
${color }${hr}
${color #9fb6cd}CPUs${color }
${color #9fb6cd}1: ${color }${cpugauge cpu1 30, 60} ${cpugraph cpu1, 30, 125
ffff00 ff0000 -t} $alignr${color #9fb6cd}2: ${color }${cpugauge cpu2 30, 60} $
{cpugraph cpu2, 30, 125 ffff00 ff0000 -t}
${color #9fb6cd}3: ${color }${cpugauge cpu3 30, 60} ${cpugraph cpu3, 30, 125
ffff00 ff0000 -t} $alignr${color #9fb6cd}4: ${color }${cpugauge cpu4 30, 60} $
{cpugraph cpu4, 30, 125 ffff00 ff0000 -t}
${color }${hr}
${color #9fb6cd}MEM
${color }${memgauge 30, 60} $alignr${memgraph 30, 380 0000ff ffff00 -t}
${color }${hr}
${color #9fb6cd}UP $alignc${color #9fb6cd}IP: ${color }${addr wlan0} $alignr${color
#9fb6cd}DOWN
${color }${upspeedgraph wlan0 30, 220 0000ff ff0000 -t} $alignr${downspeedgraph
wlan0 30, 220 0000ff 00ff00 -t}
--------------------------------------------------------------------------------
cd /root/.conky
cat conky-startup.sh

#!/bin/sh
# No widgets enabled!
## =============================================================================
## Openbox autostart (OK)
## =============================================================================
# Run the system-wide support stuff
# . $GLOBALAUTOSTART
#export LC_CTYPE=it_IT.utf8
#export XMODIFIERS=@im=SCIM
#export GTK_IM_MODULE=scim
#export QT_IM_MODULE=scim
## =============================================================================
## Note*: some programs, such as 'nm-applet' are run via XDG auto-start.
## Run '/usr/lib/openbox/openbox-xdg-autostart --list' to list any
## XDG autostarted programs.
## GNOME PolicyKit and Keyring
# /usr/lib/polkit-1-gnome/polkit-gnome-authentication-agent-1 &
# eval $(gnome-keyring-daemon -s --components=pkcs11,secrets,ssh,gpg) &
# xfce4-power-manager &
# Start the Clipboard manager after 3 <span class="IL_AD"
id="IL_AD10">seconds</span> wait
# clipit &
# start volume manager after 3 seconds
# volti &
# Programs to launch at startup
#hsetroot ~/wallpaper.png &
#xcompmgr -c -t-5 -l-5 -r4.2 -o.55 &
# SCIM support (for typing non-english characters)
#scim -d &
# Programs that will run after Openbox has started
#tint2 &
#fbpanel -p fbpanel &
#feh -F --bg-scale /root/Immagini/cubi.jpg

pcmanfm --desktop &

## =============================================================================
#xset -dpms &
#xset r rate 200 25 &
#thunar --daemon &
#xfdesktop -W &
#xfce4-panel -d &

conky -c /etc/conky/conky.conf -d &


exit 0

viene lanciato perche\' inserito nel file ~/.config/autostart/conky.desktopche


contiene le seguenti linee:

cat conky.desktop
---------------

[Desktop Entry]
Type=Application
Exec=sh "/root/.conky/conky-startup.sh"
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_IN]=Conky
Name=Conky
Comment[en_IN]=
Comment=
[root@koditv autostart]#
[Desktop Entry]
Name=conky
Type=application
Exec=/home/pi/Scripts/startConky.sh

sotto tale directory posta pure una copia di backup:


cp /etc/conky/conky.conf ./

===================================================================================
==
Raspberry Pi Documentation DOCUMENTAZIONE UFFICIALE
===================================================================================
=
https://www.raspberrypi.org/documentation/

DOCUMENTATION > CONFIGURATION


Configuration
Some basic guides to configuring your Raspberry Pi.

Contents
---------
raspi-config
The Raspberry Pi configuration tool in Raspbian, which allows you to easily enable
features
such as the camera, and to change your specific settings such as keyboard layout
config.txt
The Raspberry Pi configuration file

TCP/IP networking
Configuring the TCP/IP network stack on the Raspberry Pi

Connect to a wireless network


Configuring your Pi to connect to a wireless network using the Raspberry Pi 3's or
Pi Zero W's
inbuilt wireless connectivity, or a USB wireless dongle

Wireless access point


Configuring your Pi as a wireless access point using Raspberry Pi 3 or Raspberry Pi
Zero W's inbuilt
wireless connectivity, or a USB wireless dongle

Using a proxy
Setting up your Pi to access the internet via a proxy server

HDMI Config
Setting up your HDMI device, including custom settings

Screen Layout Editor


Setting up your display devices using the provided graphical editor

Audio config
Switching your audio output between HDMI and the 3.5mm jack

Camera config
Installing and setting up the Raspberry Pi camera board

External storage config


Mounting and setting up external storage on a Raspberry Pi

Localisation
Setting up your Pi to work in your local language and time zone

Default pin configuration


Changing the default pin states.

Device Trees config


Device Trees, overlays, and parameters

Kernel command line


Setting options in the kernel command line

UART configuration
Setting up the on-board UARTs

Firmware warning icons


Description of warning icons displayed if the firmware detects issues

LED warning flash codes


Description of LED warning flashes that are shown if a Pi fails to boot or has to
shut down

Securing your Raspberry Pi


Some basic advice for making your Raspberry Pi more secure
Screensaver
Configuring the screen saver and screen blanking

The boot folder


What it's for and what's in it

Network File System (NFS)


How to set up a NFS and connect clients to it

---------------------------------------------------------------------------------
Raspbian
---------------------------------------------------------------------------------
https://www.raspberrypi.org/documentation/raspbian/

Raspbian is the recommended operating system for normal use on a Raspberry Pi.

Raspbian is a free operating system based on Debian, optimised for the Raspberry Pi
hardware.
Raspbian comes with over 35,000 packages: precompiled software bundled in a nice
format for
easy installation on your Raspberry Pi.

Raspbian is a community project under active development, with an emphasis on


improving the
stability and performance of as many Debian packages as possible.

Contents
---------

Installing Raspbian
Installing software in Raspbian
Updating/Upgrading Raspbian
Configuring Raspbian

raspi-config
config.txt
screensaver
Applications
Camera
OMXPlayer
vcgencmd
vcdbg
tvservice

--------------------------------------------------------------------------------
DOCUMENTATION > RASPBIAN > APPLICATIONS > OMXPLAYER
--------------------------------------------------------------------------------

OMXPlayer: An accelerated command line media player

Installed on Raspbian is a command line media player, called OMXPlayer.


This is HW accelerated, and can play back many popular audio and video file
formats.

OMXPlayer was developed by the Kodi project's Edgar Hucek.

OMXPlayer uses the OpenMAX (omx) hardware acceleration interface (API) which is the
officially
supported media API on the Raspberry Pi.
Basic usage
----------
The simplest command line is omxplayer <name of media file>.
The media file can be audio or video or both.
For the examples below, we used an H264 video file that is included with the
standard
Raspbian installation.

omxplayer /opt/vc/src/hello_pi/hello_video/test.h264

By default the audio is sent to the analog port.


If you are using a HDMI-equipped display device with speakers, you need to tell
omxplayer to
send the audio signal over the HDMI link.

omxplayer --adev hdmi /opt/vc/src/hello_pi/hello_video/test.h264


When displaying video, the whole display will be used as output.
You can specify which part of the display you want the video to be on using the
window option.

omxplayer --win 0,0,640,480 /opt/vc/src/hello_pi/hello_video/test.h264

You can also specify which part of the video you want to be displayed: this is
called a crop window.
This portion of the video will be scaled up to match the display, unless you also
use the window option.

omxplayer --crop 100,100,300,300 /opt/vc/src/hello_pi/hello_video/test.h264

If you are using the Raspberry Pi Foundation's touchscreen display, and you want to
use it for
video output, use the display option to specify which display to use.

n is 5 for HDMI,
4 for the touchscreen.

With the Raspberry Pi 4 you have two options for HDMI output.

n is 2 for HDMI0
and 7 for HDMI1.

omxplayer --display n /opt/vc/src/hello_pi/hello_video/test.h264

Options available during playback


--------------------------

There are a number of options available during playback, actioned by pressing the
appropriate key.
Not all options will be available on all files. The list of key bindings can be
displayed using
omxplayer --keys:

1 decrease speed
2 increase speed
< rewind
> fast forward
z show info
j previous audio stream
k next audio stream
i previous chapter
o next chapter
n previous subtitle stream
m next subtitle stream
s toggle subtitles
w show subtitles
x hide subtitles
d decrease subtitle delay (- 250 ms)
f increase subtitle delay (+ 250 ms)
q exit omxplayer
p / space pause/resume
- decrease volume
+ / = increase volume
left arrow seek -30 seconds
right arrow seek +30 seconds
down arrow seek -600 seconds
up arrow seek +600 seconds

All command line options


--------------------

This is a full list of options available in the build from 23rd September 2016,
displayed using omxplayer --help:

-h --help Print this help


-v --version Print version info
-k --keys Print key bindings

-n --aidx index Audio stream index : e.g. 1


-o --adev device Audio out device : e.g.
hdmi/local/both/alsa[:device]

-i --info Dump stream format and exit


-I --with-info dump stream format before playback
-s --stats Pts and buffer stats

-p --passthrough Audio passthrough

-d --deinterlace Force deinterlacing


--nodeinterlace Force no deinterlacing
--nativedeinterlace let display handle interlace
--anaglyph type convert 3d to anaglyph
--advanced[=0] Enable/disable advanced deinterlace for HD videos
(default enabled)
-w --hw Hw audio decoding
-3 --3d mode Switch tv into 3d mode (e.g. SBS/TB)
-M --allow-mvc Allow decoding of both views of MVC stereo stream
-y --hdmiclocksync Display refresh rate to match video (default)
-z --nohdmiclocksync Do not adjust display refresh rate to match video
-t --sid index Show subtitle with index
-r --refresh Adjust framerate/resolution to video
-g --genlog Generate log file
-l --pos n Start position (hh:mm:ss)
-b --blank[=0xAARRGGBB] Set the video background color to black (or optional
ARGB value)
--loop Loop file. Ignored if file not seekable
--no-boost-on-downmix Don't boost volume when downmixing
--vol n set initial volume in millibels (default 0)
--amp n set initial amplification in millibels (default 0)
--no-osd Do not display status information on screen
--no-keys Disable keyboard input (prevents hangs for certain
TTYs)
--subtitles path External subtitles in UTF-8 srt format
--font path Default:
/usr/share/fonts/truetype/freefont/FreeSans.ttf
--italic-font path Default:
/usr/share/fonts/truetype/freefont/FreeSansOblique.ttf
--font-size size Font size in 1/1000 screen height (default: 55)
--align left/center Subtitle alignment (default: left)
--no-ghost-box No semitransparent boxes behind subtitles
--lines n Number of lines in the subtitle buffer (default: 3)
--win 'x1 y1 x2 y2' Set position of video window
--win x1,y1,x2,y2 Set position of video window
--crop 'x1 y1 x2 y2' Set crop area for input video
--crop x1,y1,x2,y2 Set crop area for input video
--aspect-mode type Letterbox, fill, stretch. Default is stretch if win is
specified, letterbox otherwise
--audio_fifo n Size of audio output fifo in seconds
--video_fifo n Size of video output fifo in MB
--audio_queue n Size of audio input queue in MB
--video_queue n Size of video input queue in MB
--threshold n Amount of buffered data required to finish buffering [s]
--timeout n Timeout for stalled file/network operations (default 10s)
--orientation n Set orientation of video (0, 90, 180 or 270)
--fps n Set fps of video where timestamps are not present
--live Set for live tv or vod type stream
--layout Set output speaker layout (e.g. 5.1)
--dbus_name name default: org.mpris.MediaPlayer2.omxplayer
--key-config <file> Uses key bindings in <file> instead of the default
--alpha Set video transparency (0..255)
--layer n Set video render layer number (higher numbers are on top)
--display n Set display to output to
--cookie 'cookie' Send specified cookie as part of HTTP requests
--user-agent 'ua' Send specified User-Agent as part of HTTP requests
--lavfdopts 'opts' Options passed to libavformat, e.g. 'probesize:250000,...'
--avdict 'opts' Options passed to demuxer, e.g., 'rtsp_transport:tcp,...'
--------------------------------------------------------------------------------
FastestTube YouTube downloader tool
--------------------------------------------------------------------------------
https://kwizzu.com/construct.html
1.Why do I need to download video and audio files separately?
2.Merging audio and video using ffmpeg
3.Watching separate video and audio files
4.How do I convert the downloaded audio file to mp3?
5.How do I convert WebM video to the MP4?
Why do I need to download video and audio files separately?
A while back YouTube started to use DASH format (Dynamic Adaptive Streaming over
HTTP) for 1080p and 480p videos. DASH is an adaptive bitrate streaming technology
where a multimedia file is partitioned into one or more segments and delivered to a
client using HTTP. Now instead of single multimedia file, there are at least 2
separate files: one with the audio line, the other — video. At the moment
FastestTube can’t merge them automatically. However we added the facility to
download both audio/video files so you can combine them later into a single one
with ffmpeg or similar tools.

Custom filename is not yet supported, therefore both audio/video files are
downloaded as "videoplayback". The audio file has the mime-type: "audio/mp4" and
therefore should have the file extension: "m4a" or "mp4" but some browsers may
require you to add the extension manually.

Merging audio and video using ffmpeg


Once you have downloaded both video and audio files (‘videoplayback.mp4’ and
‘videoplayback.m4a’ respectively), here’s how you can merge them into a single
file:

Download and install ffmpeg.


Open a Command Prompt window in your downloads folder and run the following command
In case of MP4 format (all, except 1440p 60fps & 2160p 60fps):
ffmpeg -i videoplayback.mp4 -i videoplayback.m4a -c:v copy -c:a copy output.mp4
In case of WebM format (1440p 60fps and 2160p 60fps):
ffmpeg -i videoplayback.webm -i videoplayback.m4a -c:v copy -c:a copy output.mkv
Wait until ffmpeg finishes merging audio and video into a single file named
"output.mp4".
Watching separate video and audio files
VLC media player allows you to watch the video with an external audio track.

On Windows you need to:

Go to Media Open Multiple Files....


In the Open Media window, click Add....
In the Select one or multiple files window, select the desired video file. Click
Open.
In the Open Media window, tick Show more options, then tick Play another media
synchronously. Click Browse....
In the second Open Media window, click Add....
In the Select one or multiple files window, select the desired file that contains
the audio which will be played on top of the video previously selected. Click Open.
In the second Open Media window, click Select.
In the first Open Media window, click Play.
If you have more than one audio track available, go to Audio Audio Track and pick
the one that corresponds to the desired audio overlay.
On Mac OS X:

Go to File Advanced Open File....


In the Open Source window, click Browse....
In the appeared dialog window, select the desired video file. Click Open.
Tick Play another media synchronously. Click Choose....
In the Open window, select the desired file that contains the audio which will be
played on top of the video previously selected. Click Open.
In the Open Source window, click Open.
If you have more than one audio track available, go to Audio Audio Track and pick
the one that corresponds to the desired audio overlay.
This manual is also available at the VideoLAN wiki.

How do I convert the downloaded audio file to mp3?


YouTube uses an uncommon codec called Dash for their audio files and some media
players can't play it. You can convert the Dash audio format to a more common
format using one of the many online services available like this one or that one.

Otherwise you can always manually convert the Dash audio file to any format with
ffmpeg. To do so, you need to know your audio's bitrate, which was shown in the
download menu. If you don’t remember the bitrate you can check it by running
ffprobe INPUT_FILE
in the Command Prompt window. Just replace INPUT_FILE with the downloaded audio
file name.
Then you need to convert the bitrate from kbit/s to bit/s. To do so just add three
zeroes after the bitrate (ex.: 128 kbit/s audio would be 128000 bit/s). Thereafter
you need to execute the following command in the Command Prompt window:
ffmpeg -i INPUT_FILE -ab BITRATE -vn OUTPUT_FILE

INPUT_FILE — a path to the downloaded audio;


BITRATE — audio bitrate (only the numeric value is allowed);
OUTPUT_FILE — new file's name. Note that you have to use a valid audio format
extension for the output file (like .mp3 or .m4a).
Example:
ffmpeg -i videoplayback.m4a -ab 128000 -vn music.mp3
How do I convert WebM video to the MP4
For some qualities Youtube provides videos only in WebM format. WebM could be
converted in MP4 with the following ffmpeg command

ffmpeg -i video.webm -i audio.m4a -c:v libx264 -c:a copy out.mp4


Please note that such a conversion may take a very long time.

--------------------------------------------------------------------------------
AZARTICOLO: HOWTO Convert video files
--------------------------------------------------------------------------------
https://linuxreviews.org/HOWTO_Convert_video_files

HOWTO Convert video files


HOWTO Dump video streams from the Internet
HOWTO Merge video files
HOWTO record your desktop with ffmpeg

Converting video files between common file containers and codecs can easily be done
from the
command-line on Linux systems. Starting a conversion job can be done quicker than
graphical tools
when you know the basic commands.

Note: This article is about video conversion and manipulation using the command-
line in terminal.
Take a look at avidemux and VLC if you want a graphical program which lets you
quickly convert
from one format to another.

See kdenlive and Pitivi if you are looking for a full-featured timeline video
editor

Contents
1 When to convert
1.1 Sometimes file-size matters
1.2 Playability
2 The Basic Tools for ALL Your Video Conversion Needs
3 ffmpeg for beginners
3.1 Specifying audio and video format
3.2 Moving on to more advanced encoding
3.3 "strict experimental"
3.4 Encoding options for H264 / MPEG-AVC video
3.5 Encoding options for VP9
3.6 Resizing a video to lower resolutions
3.6.1 Resizing a video to higher resolutions
3.7 HOWTO Make a VideoCD/VCD
4 Special use-cases
4.1 Making a .webm to post on that image-board
4.2 HOWTO make animated .gif files
5 Corner-case errors
6 Questions?
When to convert
There are many good reasons to convert video files you made yourself - or video
files forwarded to you which you plan to distribute. Good reasons to change a video
file can be:

Playability across devices


Size
This HOWTO will to introduce to you some of the basic commands to use the most
common Linux command-line program to convert video files from one format to
another.

Sometimes file-size matters


Size is important, specially when publishing video on the web.

A video-file reduced by 100 MB will save you 100 GB of bandwidth if 1000 people
download it;
The reduction of 100 MB per. file will save you 1 GB of hard-drive space if you
host 10 video-files on a web-server.
This adds up. You will likely want files to be as small as possible without
reducing the video quality.

Playability
If you are distribution your video on the web to a general audience then
proprietary H264 (MPEG/AVC) video with AAC is the best choice for maximum
playability.
If your audience is primarily Linux-focused then VP9 video with Opus audio in
a .webm container is the best choice.
iToddlers can't play Webm and Apple appears to be hell-bent on keeping it that way.
You will see your shareholder value decrease if you only provide videos in Webm
format on your website if it is targeting a broad audience.

The Basic Tools for ALL Your Video Conversion Needs


There is one basic GNU/Linux tool you absolutely must learn and that is: ffmpeg

Three other tools do exist: mencoder, ffmpeg2theora and transcode. They are wildly
outdated and not worth your time. mencoder has been barely updated to ensure it
still compiles the last decade. transcode hasn't even got that much attention.
ffmpeg2theora is no longer relevant since VP9 has deprecated the theora video
format.

You need to enable rpmfusion to get a fully featured version of ffmpeg on Fedora
due to imaginary property laws in the US.

ffmpeg for beginners


The most basic use of ffmpeg is simply:

Shell command:
ffmpeg -i YourAwesomeMovie-Input.dv YourAwesomeMovie-Output.webm
That's it. This is, ffmpeg -i input.ext output.ext is all you need do remember when
it comes to the most basic use-case. ffmpeg detect the input file automatically and
will look at the output file extension and try to intelligently decide what audio
and video codecs to use.

You can specify the audio and video codecs used by input files. There is rarely a
need, the built-in input detection does work perfectly in 99% of all cases.
An output filename with the .mp4 extension will make ffmpeg assume that you want a
file with H.264/AVC video and AAC 2.0 audio. These happen to be the correct choices
for HTML5 web video files which can be played on all devices.
An output file with the .webm extension will use VP9 video and Opus audio. This is
a great choice for videos posted on websites that are not visited by too many
Apple-users.
An output filename signalling the .mkv container will get h264 video and vorbis
audio. This is likely NOT what you want in a .mkv file.
Specifying audio and video format
Add -c: and a for audio or v for video to set the audio and video codecs (-c:v for
video and -c:a).

If you want VP8 video with vorbis audio in a .webm container you use -c:v libvpx -
c:a libvorbis like this:

Shell command:
ffmpeg -i wjsn-save-you-save-me.mp4 -c:v libvpx -c:a libvorbis wjsn-is-the-best-we-
love-them.webm
Kemonomimi rabbit.svg Note: ffmpeg supports a large variety of encoders depending
on how it was compiled. You can get a very large list of all the encoders your
version supports by running ffmpeg -encoders. You probably want to pipe it to a
pager like less, ffmpeg -encoders
Moving on to more advanced encoding
The secret ffmpeg manual page is very long. It contains lots of detailed
information about the numerous options available when using this tool. Whole books
can be are being written about the advanced options listed in the manual page.

Things you may want to tune when encoding include:

-r to change the frame rate


-b:v to set the video bitrate
-b:a to set the audio bitrate
These options can have a huge impact on the quality and the file-size of the
resulting file.

A general rule is: You can have low file-size OR high picture quality, but you can
NOT have both. You will have to compromise.

This may give you an acceptable quality video file on lower resolutions like 720p:

Shell command:
ffmpeg -i YourAwesomeMovie.dv -r 25 -b:a 128k -b:v 4000k YourAwesomeMovie.mp4
..and this will absoltely NOT, because 256k is not enough bandwidth for acceptable
quality even at tiny resolutions:

Shell command:
ffmpeg -i YourAwesomeMovie.dv -r 25 -b:a 64k -b:v 256k YourAwesomeMovie.mp4
"strict experimental"
Some versions of ffmpeg will refuse to use certain codecs unless you specify -
strict experimental

Try adding it if ffmpeg refuses to do something when your options should work.

Encoding options for H264 / MPEG-AVC video


libx264 as in -c:v libx264 is the codec for H264/MPEG-AVC video.

Output quality can be adjusted in many ways. We recommend sticking with the
Constant Rate Factor encoding option set by -crf. The -crf switch values worth
considering are 20 to 30 where 20 produces very high quality and produces 30
acceptable quality. You can use lower values for even better quality or higher
values for worse; the allowed range is 0-51. 20-30 is what you want to use.

You should also add a -preset option and the choices are ultrafast, superfast,
veryfast, faster, fast, medium (default), slow, slower and veryslow. The presets
allow you to choose encoding speed at the cost of size. Thus; if you use a fixed
quality setting like crf you will get the exact same quality with superfast and
veryslow but the file size will be bigger when using superfast. The medium default
is fine.

Do note that -preset will change quality if you are using fixed constant bitrate
encoding.

An example of encoding H264 with a Constant Rate Factor of 21: An example of using
-crf to set quality would be:

Shell command:
ffmpeg -i inputfile.mkv -c:v libx264 -preset slow -crf 21 output.mp4
You might want to make a simple script for encoding a format you use frequently
such as:

File: $HOME/bin/ffmpeg-encode-h264-hq.sh
#!/bin/bash
inputf="$*"
inputnoext="${inputf%.*}"
outputf="${inputnoext}.hq.mp4"

nice -n 19 ffmpeg -i "$*" \


-strict experimental \
-c:v libx264 -preset slow -crf 21 \
-c:a aac -b:a 196k \
-ac 2 \
"${outputf}"
exit 0
With that you could just run

Shell command:
ffmpeg-encode-h264-hq.sh inputfile.mkv
and get a H264 file named inputfile.hq.mp4.

You can obviously throw in more options such as -vf scale if you, for example,
convert video to 720p regularly:

File: $HOME/bin/ffmpeg-encode-h264-720p.sh
#!/bin/bash
inputf="$*"
inputnoext="${inputf%.*}"
outputf="${inputnoext}.hq.mp4"

nice -n 19 ffmpeg -i "$*" \


-strict experimental \
-c:v libx264 -preset slow -crf 21 \
-c:a aac -b:a 196k \
-vf scale="'if(gt(iw,1280),1280,iw)':-1" \
-ac 2 \
"${outputf}"
See trac.ffmpeg.org H.264 Video Encoding Guide for more options.

Encoding options for VP9


ffmpeg needs the libvpx-vp9 codec specified with -c:v libvpx-vp9 to produce VP9
video. It defaults to average bitrate encoding by default. This mode is not ideal
or good for visual quality but may be preferred when streaming to bandwidth-
restricted devices. You likely do not want to use it.

For libvpx-vp9 Constant Quality or Constrained Quality are the best choices. The
difference is that Constrained Quality allows you to set a roof for how high the
variable bitrate required for the constant quality you selected goes. These modes
are invoked by the switch -crf with a value between 0-63 together with -b:v and
bitrate cap. This cap must be specified as 0 if you want no cap.

CRF values for VP9 differ x264. Lower values mean better quality, higher worse. The
CRF value required for good visual quality is variable when using libvpx-vp9. 30 is
a good choice for 1080p, 33 is a good choice for 720p and 16 works fine at 4K.

An example of Constant Quality VP9 encoding would be:

Shell command:
ffmpeg -i WJSN-LaLaLa.mp4 -c:v libvpx-vp9 -crf 30 -b:v 0 -c:a opus WJSN-LaLaLa.webm
And Constrained Quality mode is archived by setting -b:v to a bitrate value instead
of 0:

Shell command:
ffmpeg -i WJSN-LaLaLa.mp4 -c:v libvpx-vp9 -crf 30 -b:v 9000k -c:a opus WJSN-
LaLaLa.webm
libvpx-vp9 is very single-threaded when using the default options. You will
probably want to use all of these options in addition to -crf when encoding:

threads 4
row-mt 1
tile-columns 6
frame-parallel 1
auto-alt-ref 1
lag-in-frames 25
What do all those options do? Nobody knows, mystery remains unsolved. The sum of
them a) does produce slightly better quality and b) makes ffmpeg encode using more
than just one core. The threads option will obviously limit how many.

You may want to script this in a file such as:

File: $HOME/bin/ffmpeg-encode-VP9.sh
#!/bin/bash
inputf="$*"
inputnoext="${inputf%.*}"
outputf="${inputnoext}.webm"

nice -n 19 ffmpeg -i "$*" \


-c:v libvpx-vp9 -crf 30 -b:v 9000k \
-threads 4 -row-mt 1 \
-tile-columns 6 -frame-parallel 1 \
-auto-alt-ref 1 -lag-in-frames 25 \
-ac 2 -c:a libopus -b:a 256k \
-strict experimental \
-f webm "${outputf}"
Quick note on Opus audio: Some claim that Opus is so good that -b:a 64k is fine for
audio. The percentage of a video file used to store the audio is negligible and
there is no good reason to sacrifice audio bitrate. None. 256k is fine.

Resizing a video to lower resolutions


The -vf for "video filter" option allows you to invoke scale and the scale filter
can be used in many ways. This is a efficient way to use it to get a 720P video -
which has a width of 1280:

-vf scale="'if(gt(iw,1280),1280,iw)':-1"

This makes ffmpeg decide the correct height based on the aspect ratio and the
width.

You can use this in a full command like:

Shell command:
ffmpeg -i 4kvideofile.mkv -vf scale="'if(gt(iw,1280),1280,iw)':-1" -c:v libvpx-vp9
-c:a opus downscaledto720p.webm
Resizing a video to higher resolutions
Doing so would simply be foolish as you gain nothing in terms of quality while the
file-size would be increased dramatically.

HOWTO Make a VideoCD/VCD


This information is left here because some are still interested in making VCDs for
some reason. If you are a zoomer wondering what a VCD is: It was a disc shaped
storage-medium used to distribute movies before the Internet.

ffmpeg can make VCD mpeg video files using -target where the target can be "vcd",
"svcd", "dvd", "dv", "pal-vcd", "ntsc-svcd". These switches will set the output
format options (bitrate, codecs, buffer sizes) automatically.

The default vcd switch makes a PAL vcd.

Shell command:
ffmpeg -i myfile.avi -target vcd /tmp/vcd.mpg
A ntsc vcd:

Shell command:
ffmpeg -i myfile.avi -hq -target ntsc-vcd /tmp/vcd.mpg
Converting a file for VCD format using a and b frames for MPEG 2:

Shell command:
ffmpeg -i myfile.avi -target ntsc-vcd -bf 2 /home/user/Video/vcd.mpg
Special use-cases
Making a .webm to post on that image-board
That image-board will not accept webm files with VP9 videos.

Container must be .webm


Video must be VP8
There can be no audio (except for specific boards where it is allowed)
File-size must be below 3M
With these restrictions a command for converting cute-kpop-queen-dancing.mp4 could
be

Shell command:
ffmpeg -i cute-kpop-queen-dancing.mp4 -map 0:0 -c:v libvpx -b:v 1.4M -threads 4
cutekpopqueen.webm
The important options here are:

-map 0:0 specifies that only the video track (0:0) from the input should be
included.
-c:v libvpx specifices VP8 video.
-b:v 1.4M specifies a bitrate of 1.4M. This is low. File-size restrictions do
apply. You may want to convert a few times starting with -b:v 1M or -b:v 2M. Adjust
the bitrate up or down depending on how close you are to the end-result being
within the (3M on "that" imageboard) required limit.
HOWTO make animated .gif files
The outdated video-player mplayer combined with the image manipulation toolbox lets
you convert short video files to .gif files.

Make sure your video file is short. This is highly important as you do want to make
sure your animated .gif ends up being reasonably small.
Convert your video file to a very small resolution. Again, a 20 MB .mp4 file is
alright, a 20 MB .gif file is NOT.
First, use mplayer's -vo option to produce a series of images, either png or jpg.

Shell command:
mplayer -vo png myvideoclip.mp4
or

Shell command:
mplayer -vo jpeg myvideoclip.mp4
You should now have a folder full of incriminating images. You can use them all or
delete a few (every 4 images, for example).

It is now time to use the awesome power of imagemagick's convert tool (secret
convert manual page) to merge all the png (or jpg) images into one big
animated .gif file:

Shell command:
convert *.png animation.gif
Beware that convert has a secret -delay option which could be used to set the time
between images in the animated .gif file.

Corner-case errors
Too many packets buffered for output stream 0:1.
[libopus @ 0x562117d06100] 1 frames left in the queue on closing
This can happen when trying to convert some files created with OBS. It can happen
if the file has sparse audio or video frames. Adding this parameter to ffmpeg will
solve it:

-max_muxing_queue_size 400

While it's somewhat unclear why this seemingly randomly happens the -
max_muxing_queue_size 400 option appears to solve it every time.

Questions?

Enable comment auto-refresher

avatar
Anonymous user #1

6 months ago
Score 0++
Avdshare Video Converter is just the professional MP4 to XviD converter that we
will recommend. Avdshare Video Converter can convert any MP4 file with any codec or
obtained from any source to XviD codec for the XviD compatible devices or players.
Permalink | Reply

avatar
Anonymous user #2

one month ago


Score 0 You
Avdshare Video Converter, as the most powerful MP4 to H.264 converter, plays very
well to convert MP4 to H.264.
Permalink | Reply

Add your comment


LinuxReviews welcomes all comments. If you do not want to be anonymous, register or
log in. It is free.

Topic: Audio and Video HOWTOs


Audio

HOWTO Convert audio files


HOWTO splitt lossless audio files (ape, flac, wv, wav) using .cue files
HOWTO Dump audio streams from the Internet
HOWTO Dump audio streams from a video file
Video

HOWTO Convert video files


HOWTO Make a video DVD
HOWTO Make a video (S)VCD
HOWTO Merge video files
HOWTO download video on websites
HOWTO Dump video streams from the Internet
See also: Music players | Media/Video players | video editing software
--------------------------------------------------------------------------------
HOWTO Merge video files
Jump to navigationJump to search
Merging two video files into one is easy or impossible depending on what tool you
use for the job and what kind of files you want to merge. It's super-easy if
resolution as well as audio format, video format and container match. It gets dicey
very quickly if they don't.

Introduction
Video file merging requires that the files you want to merge have the same
resolution and file format. You have to convert if they don't, see HOWTO Convert
video files.

Merging MPEG2 files founds on DVDs etc


This is actually the simplest of the simple examples of how files can be merged.
Multiple MPEG2 files of the same resolution can simply be squished into one file
with cat. If you have mounted a DVD on say /mnt/tmp/ you will have a
/mnt/tmp/VIDEO_TS/ folder with MPEG2-formatted files called VTS_01_0.VOB,
VTS_01_1.VOB and so on. You can simply cat these into one file:

cat VTS_01_0.VOB VTS_01_1.VOB > $HOME/MyDVDRIPedFile.mpg

Merging video files with ffmpeg


ffmpeg has an option called concat for joining two files which have identical
formats. It's used like this:

ffmpeg -i "concat:file1.mp4|file2.mp4|file3.mp4" MyFineOutput.mp4

This will only work if the files have the same resolution and the same video and
audio formats.
The concat filter is required if they do not have the same video format or audio
format or container:

ffmpeg -i videofile1.mp4 -i videofile2.mkv -filter complex "[0:v:0] [0:a:0] [1:v:0]


[1:a:0] concat=n=2:v=1:a=1 [v] [a]" -map "[v]" -map "[a]" MyFineOutput.mp4

Kemonomimi rabbit.svg Note: complex filter still requires that the files have the
same frame-rate and resolution. You can't just merge some 720p with a 1080p file
using this method. You will have to convert the file(s) so that they have the same
frame-rate and resolution.
Do notice how the complex works: You need to add a video and an audio option for
each file and a number option to concat=. You need to add more if you want to merge
say 3 files:

ffmpeg -i videofile1.mp4 -i videofile2.mkv -i videofile3.mkv -filter complex


"[0:v:0] [0:a:0] [1:v:0] [1:a:0] [2:v:0] [2:a:0] concat=n=3:v=1:a=1 [v] [a]" -map
"[v]" -map "[a]" MyFineOutput.mp4

You can go on adding these options and merge 10 files but at that point you're
better off considering a video editor like kdenlive or pitivi.

=================================================================================
AZARTICOLO:Che cos'è la risoluzione video 4K
=================================================================================

Che cos'è un video 4K


Dove scaricare il video 4K
Cos'è una playlist di YouTube
Correzioni per VEVO
Come eliminare

4K è una nuovo standard per la risoluzione realizzato per il cinema digitale e la


grafica per computer.
Il suo vantaggio è quello di fornire una qualità della definizione dell'immagine
più alta, immagini
più dettagliate e offre la miglior visbilibilità e velocità di riproduzione su
grandi formati.

E' chiamato 4k perchè la risoluzione orizzontale è approssimativamente di 4.000


pixel mentre le
risoluzioni 1080p e 720 sono chiamate così per la loro risoluzione verticale.
Il nuovo standard ha una risoluzione quattro volte maggiore rispetto allo stamndard
1080p.

Confronta la qualità dei formati dei video


----------------------------------

Questo formato non modifica la risoluzione orizzontale, ma modifica il rapporto di


scala attraverso
la risoluzione verticale. Ad esempio 4096x2304 è la dimensione del frame 16:9 e
4096x3072 è la
dimensione del frame 4:3. Alcuni esempi di risoluzioni di video digitali:

Full Aperture 4k 4096 x 3112 12,746,752 pixels


Academy 4k 3656 x 2664 9,739,584 pixels
Digital Cinema Aperture 4k 3996 x 2160 8,631,360 pixels
Digital Cinema 4k 4096 x 1714 7,020,544 pixels

Youtube ha introdotto il supporto dei video 4K a Luglio del 2010.


E' il formato alla massima risoluzione disponibile nel mercato consumer, e ha un
grosso potenziale.
E' molto facile che questo formato incrementerà in un prossimo futuro la domanda di
nuovi video
digitali Youtube.

Se vuoi scaricare video 4K da YouTube o servizi similari, leggi la dettagliata


guida nel nostro sito web.

Come scaricare un video 4K


-----------------------

Attualmente si sono solo poche sorgenti da cui puoi scaricare 4K video. La più
popolare è YouTube,
dove si trova un contenuto con una super-risoluzione sempre più elevata.
Sfortunatamente,
Google e YouTube non permettono di scaricare video direttamente dal sito.
Ma ciò non vuole dire che sia impossibile.

Problemi risolti per scaricare i video VEVO da YouTube


-----------------------------------------------

YouTube ha recentemente aggiornato l'algoritmo per il download dei video VEVO a un


massimo di
3 volte a settimana, allo scopo di proteggere questi video dal download. Per
scaricare ulteriori
Video VEVO è necessaria una nuova installazione. Con 4K Video Downloader non c'è
bisogno di
effettuare questa operazione perché ora il programma aggiorna il codice
automaticamente ogni
volta che YouTube genera il nuovo algoritmo per il download dei video VEVO.
Gli sviluppatori di 4K Video Downloader possono creare soluzioni al problema
piuttosto velocemente,
ma a volte ci vogliono comunque alcune ore.

Quindi, per riassumere, se hai problemi con lo scaricamento dei video VEVO da
YouTube, aspetta
un po' e noi ripareremo il problema

================================================================================
AZARTICOLO:How to Upgrade Raspbian Stretch to Raspbian Buster
================================================================================
https://pimylifeup.com/upgrade-raspbian-stretch-to-raspbian-buster/
by Emmet Jul 10, 2019 Guides

In this guide, we will show you how to upgrade Raspbian Stretch to Raspbian Buster.

How to Upgrade Raspbian Stretch to Raspbian Buster


---------------------------------------------

Raspbian Buster is the latest release of the Raspbian operating system.


This release brings numerous behind the scenes fixes as well as access to more
modern packages.
Updating to Raspbian Buster is a reasonably straightforward process and mainly
requires modifying
two simple files and then running an upgrade.

Before upgrading your Raspberry Pi from Raspbian Stretch to Buster you should first
make a
backup of your SD Card. There is always a chance that this upgrade process will
break your
existing installations.

If you have some critical software running on your Raspberry Pi, it’s best to do a
quick search
to ensure there aren’t any compatibility issues on the latest release.

Preparing Raspbian Stretch for Buster


-------------------------------

1. We need first to ensure that our current Raspbian operating system is entirely
up to date.

Upgrading all the currently installed packages ensures that we will have a cleaner
upgrade path to
Raspbian Buster.

Let’s first update all the currently installed packages by running the following
command.

sudo apt update


sudo apt dist-upgrade -y

We utilize “dist-upgrade” instead of the plain “upgrade” command to force Raspbian


to upgrade
to the latest available versions of all packages regardless of whether they need to
update.

2. Next, let’s go ahead and also update the Raspberry Pi’s firmware.

We can do that by running the command below on our Raspbian installation.

rpi-update

Once all the update processes have completed, we can now proceed to upgrade the
Raspbian
installation from Stretch to Raspbian Buster.

Updating Raspbian Stretch to Raspbian Buster


---------------------------------------

1. Now that we have prepared our Raspbian Stretch installation, we can now start
the process of
moving to Buster.

To do this, we will need to modify the “/etc/apt/sources.list” file.

Begin modifying the sources file by running the following command.

vi /etc/apt/sources.list

2. Within this file, find the following line and change “Stretch” to “Buster“.

This change will allow the package manager to search the Raspberry Pi package
repository under
the “Buster” distribution instead of the “Stretch” distribution.

Find
deb http://raspbian.raspberrypi.org/raspbian/ stretch main contrib non-free rpi
Replace With
deb http://raspbian.raspberrypi.org/raspbian/ buster main contrib non-free rpi

Once you have replaced all occurrences of “stretch” within the file you can save it
by pressing CTRL + X
then Y followed by ENTER.

3. Next we also need to modify the “/etc/apt/sources.list.d/raspi.list” file by


running the following command.

sudo nano /etc/apt/sources.list.d/raspi.list


4. In this file, you need to go ahead and find the following text and change
“Stretch” to “Buster“.

Find

deb http://archive.raspberrypi.org/debian/ stretch main


Replace With
deb http://archive.raspberrypi.org/debian/ buster main

Once you have again finished switching “Stretch” to “Buster“, you can save the file
by pressing
CTRL + X then Y and then ENTER.

5. Now before we do the final push to Raspbian Buster, we will first remove the
“apt-listchanges”
package.

The reason for removing this package is to give us a faster and smoother upgrading
process.
Without removing this package, the Raspbian operating system will have to load a
fairly large
changelog file which will slow down your upgrade process considerably.
Feel free to re-install this package after the upgrade process has completed.
Run the command below to uninstall the “apt-listchanges” package.

apt-get remove apt-listchanges

6. Finally, with the source files now modified to mention the “Buster” build
instead of “Stretch”
we are now ready to begin the upgrade process.

The first command will update the package lists stored on the Raspberry Pi.
The second command will then update all the packages to their Raspbian Buster
versions.

apt update
apt dist-upgrade

Please note that this process can take considerable time as there are a fair few
packages that
will need to be updated.

Additionally, you may be required to answer prompts, so don’t stray too far from
your Raspberry Pi.

7. Once the Buster upgrade process has completed, we will need to get rid of some
new applications
that will automatically be installed.

These packages are not supported by the Raspberry Pi foundation and are recommended
to be removed.

We can remove these packages by running the following command on your Raspberry Pi.

apt purge timidity lxmusic gnome-disk-utility deluge-gtk evince wicd wicd-gtk


clipit usermode
gucharmap gnome-system-tools pavucontrol

8. Next, we need to run a few more commands to ensure we have cleaned up everything
leftover
from the upgrade.

The first command that we will be running is the package managers “autoremove”
command.
This command will remove any packages that have been marked as no longer needed
due to
changed dependencies.

Run the following command to remove these no longer required packages.

apt autoremove -y

9. Now we need to run the apt package managers “autoclean“.

This autoclean command will clear out the package cache.


It automatically removes any package files that are no longer available for
download and thus are
largely useless.

Use the command below to begin the cleaning process.

apt autoclean

10. The final thing we should do is restart our Raspberry Pi.


Restarting ensures that the Raspberry Pi will load in all the new Buster packages
and clear out
any old data sitting in memory.

Run the following command to reboot the Raspberry Pi.

reboot

--------------------------------------------------------------------------------
How to Upgrade Raspbian Stretch to Raspbian Buster
--------------------------------------------------------------------------------
by Emmet Jul 10, 2019 Guides
In this guide, we will show you how to upgrade Raspbian Stretch to Raspbian Buster.

How to Upgrade Raspbian Stretch to Raspbian Buster


Raspbian Buster is the latest release of the Raspbian operating system. This
release brings numerous behind the scenes fixes as well as access to more modern
packages.

Updating to Raspbian Buster is a reasonably straightforward process and mainly


requires modifying two simple files and then running an upgrade.
Before upgrading your Raspberry Pi from Raspbian Stretch to Buster you should first
make a backup of your SD Card. There is always a chance that this upgrade process
will break your existing installations.

If you have some critical software running on your Raspberry Pi, it’s best to do a
quick search to ensure there aren’t any compatibility issues on the latest release.

Preparing Raspbian Stretch for Buster


1. We need first to ensure that our current Raspbian operating system is entirely
up to date.

Upgrading all the currently installed packages ensures that we will have a cleaner
upgrade path to Raspbian Buster.

Let’s first update all the currently installed packages by running the following
command.

sudo apt update


sudo apt dist-upgrade -y
We utilize “dist-upgrade” instead of the plain “upgrade” command to force Raspbian
to upgrade to the latest available versions of all packages regardless of whether
they need to update.

2. Next, let’s go ahead and also update the Raspberry Pi’s firmware.

We can do that by running the command below on our Raspbian installation.

sudo rpi-update
Once all the update processes have completed, we can now proceed to upgrade the
Raspbian installation from Stretch to Raspbian Buster.

Updating Raspbian Stretch to Raspbian Buster


1. Now that we have prepared our Raspbian Stretch installation, we can now start
the process of moving to Buster.

To do this, we will need to modify the “/etc/apt/sources.list” file.

Begin modifying the sources file by running the following command.

sudo nano /etc/apt/sources.list


2. Within this file, find the following line and change “Stretch” to “Buster“.

This change will allow the package manager to search the Raspberry Pi package
repository under the “Buster” distribution instead of the “Stretch” distribution.

Find

deb http://raspbian.raspberrypi.org/raspbian/ stretch main contrib non-free rpi


Replace With

deb http://raspbian.raspberrypi.org/raspbian/ buster main contrib non-free rpi


Once you have replaced all occurrences of “stretch” within the file you can save it
by pressing CTRL + X then Y followed by ENTER.

3. Next we also need to modify the “/etc/apt/sources.list.d/raspi.list” file by


running the following command.

sudo nano /etc/apt/sources.list.d/raspi.list


4. In this file, you need to go ahead and find the following text and change
“Stretch” to “Buster“.

Find

deb http://archive.raspberrypi.org/debian/ stretch main


Replace With

deb http://archive.raspberrypi.org/debian/ buster main


Once you have again finished switching “Stretch” to “Buster“, you can save the file
by pressing CTRL + X then Y and then ENTER.

5. Now before we do the final push to Raspbian Buster, we will first remove the
“apt-listchanges” package.

The reason for removing this package is to give us a faster and smoother upgrading
process. Without removing this package, the Raspbian operating system will have to
load a fairly large changelog file which will slow down your upgrade process
considerably.

Feel free to re-install this package after the upgrade process has completed.

Run the command below to uninstall the “apt-listchanges” package.

sudo apt-get remove apt-listchanges


6. Finally, with the source files now modified to mention the “Buster” build
instead of “Stretch” we are now ready to begin the upgrade process.

The first command will update the package lists stored on the Raspberry Pi. The
second command will then update all the packages to their Raspbian Buster versions.

sudo apt update


sudo apt dist-upgrade
Please note that this process can take considerable time as there are a fair few
packages that will need to be updated.

Additionally, you may be required to answer prompts, so don’t stray too far from
your Raspberry Pi.

7. Once the Buster upgrade process has completed, we will need to get rid of some
new applications that will automatically be installed.

These packages are not supported by the Raspberry Pi foundation and are recommended
to be removed.

We can remove these packages by running the following command on your Raspberry Pi.

sudo apt purge timidity lxmusic gnome-disk-utility deluge-gtk evince wicd wicd-gtk
clipit usermode gucharmap gnome-system-tools pavucontrol
8. Next, we need to run a few more commands to ensure we have cleaned up everything
leftover from the upgrade.

The first command that we will be running is the package managers “autoremove”
command. This command will remove any packages that have been marked as no longer
needed due to changed dependencies.

Run the following command to remove these no longer required packages.

sudo apt autoremove -y


9. Now we need to run the apt package managers “autoclean“.

This autoclean command will clear out the package cache. It automatically removes
any package files that are no longer available for download and thus are largely
useless.

Use the command below to begin the cleaning process.

sudo apt autoclean


10. The final thing we should do is restart our Raspberry Pi.
Restarting ensures that the Raspberry Pi will load in all the new Buster packages
and clear out any
old data sitting in memory.

-------------------------------------------------------------------------------
Reducing SD Card Writes With Raspbian
--------------------------------------------------------------------------------
A common concern of those running applications on a Raspberry Pi is SD Card
exhaustion.
It seems that after some amount of write activity, some SD cards fail to record
further data.
I first noticed this on an APRS system when system updates disappeared upon reboot.

The systemd journal is a useful tool that has largely replaced the syslog in modern
Linux systems. It can also be redirected from the SD card to volatile memory.
Note that by changing this you will reduce the number of SD card writes but your
journal will not survive reboots.

The key to changing the storage location of the journal is found in


/etc/systemd/journald.conf. Look for this line:

[Journal]
#Storage=auto

Uncomment the line by removing the #. Change auto to volatile:

[Journal]
Storage=volatile

---------------------------------------------------------------------------------
Disable unwanted Raspbian Services
---------------------------------------------------------------------------------

Notes on reducing unwated services on a Raspbian (Jessie - v8) based Rapberry Pi 3.

Disable loading wireless drivers


Disable loading the drivers for bluetooth and WiFi. As well as reducing the number
of interfaces it may reduce power usage.

# cat > /etc/modprobe.d/raspi-blacklist.conf <<EOF

# WiFi
blacklist brcmfmac
blacklist brcmutil

# Bluetooth
blacklist btbcm
blacklist hci_uart
EOF
Disable bluetooth
The bluetooth service is not required

# systemctl disable bluetooth


# systemctl stop bluetooth
Disable avahi
The Pi is going to use simple uni-cast DNS - multi-cast DNS support is not
required.

# systemctl disable avahi-daemon


# systemctl stop avahi-daemon
Disable TriggerHappy
The Pi isn't being used with button. Disable the TriggerHappy daemon (not that it
is a init.d service)

# systemctl disable triggerhappy


# systemctl stop triggerhappy
Links
https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=138610
http://www.raspbian.org/
Appendices
pstree
After shutting down unwated services pstree shows

dhcpd (wired LAN)


ntp
systemd─┬─agetty
├─cron
├─dbus-daemon
├─dhcpcd
├─ntpd
├─rsyslogd─┬─{in:imklog}
│ ├─{in:imuxsock}
│ └─{rs:main Q:Reg}
├─sshd───sshd───sshd───bash───pstree
├─systemd-journal
├─systemd-logind
└─systemd-udevd

Run the following command to reboot the Raspberry Pi.

sudo reboot
At this point, you should now have successfully updated your Raspberry Pi from
Raspbian Stretch
to Raspbian Buster. You can now go do some more projects using the Raspberry Pi
using your newly
updated version of Raspbian.

================================================================================
AZARTICOLO:Raspberry Pi Networking - Switching between wired and wireless networks
================================================================================

Quite often I want to run my Raspberry Pis "headless" - that is to say, without a
keyboard, mouse or monitor. That means I have to manage without the desktop tools
to configure the network; I have to use the command-line network tools over an SSH
connection.
Another problem I have is that I want the Raspberry Pi to use a static IP if it's
in my house - with no monitor, I can't read the IP address off the screen, so the
IP address needs to stay the same so I know where to connect to. However if I'm
taking it elsewhere, I want to be able to quickly and easily configure it for
another wireless network.

Here's my assumptions:

If the network cable is plugged in, assume that we must be at home, and use a
static IP. Meanwhile, ignore WiFi completely regardless of whether the USB WiFi
nano dongle is plugged in or not.
If the network cable is unplugged, and we are at home, use the same static IP on
WiFi that I would otherwise be using through the ethernet cable.
So if I'm at home, no matter whether the network cable is plugged or unplugged, the
Raspberry Pi will always be on the same IP.
If the network cable is unplugged, and we are not at home, use any configured WiFi,
which may be configured with a static IP but more likely will use a dynamic IP.
I'll have to either plug the Pi in to a display to find out the dynamic IP, or use
a network scanner.
I may "hot-plug" the network cable by plugging it or unplugging it whilst the
Raspberry Pi is running. However I will never remove or insert the USB nano WiFi
adaptor whilst the Pi is running - that usually ends up with the Pi rebooting
anyway. So the network cable may come and go whilst the Pi is switched on, but the
WiFi adaptor is either always there, or never there.

You have a backup of your SD card (or you don't care about making mistakes), you're
happy editing files using Nano or our favourite text editor, and you understand
that all of this work will be done as root (use sudo su - to get a root prompt ;
exit to go back to being a normal user).
Static IP on some WiFi connections but dynamic on others

Let's deal with the easy problem first; static IPs on some WiFi connections but
dynamic on others. This is done by setting an id_str in the
/etc/wpa_supplicant/wpa_supplicant.conf file:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
ssid="aoakley-home"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=CCMP TKIP
psk="PASSWORD"
id_str="aoakley-home"
}

network={
ssid="PlusnetWireless9AAAA9"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=CCMP TKIP
psk="PASSWORD"
id_str="inlaws"
}
network={
ssid="aoakley-mifi"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
group=CCMP TKIP
psk="PASSWORD"
id_str="aoakley-mifi"
}

In the wpa_supplicant.conf file above, we have three known WiFi networks, all with
WPA-PSK security; aoakley-home , PlusnetWireless9AAAA9 and aoakley-mifi . Each has
been given an id_str so they can be identified in the /etc/network/interfaces file.
For aoakley-home and aoakley-mifi I've set the id_str the same as the ssid , but
for ease of identification, I've set the id_str of the Plusnet connection at my
wife's parents' house to id_str="inlaws" (there are a lot of Plusnet WiFi routers
out there - no doubt another will join my list soon).

You'll need to customise this wpa_supplicant.conf file to represent your known WiFi
networks. If your Pi never leaves home, then you'll probably just have one WiFi
network listed - but make sure it has an id_str.

We can then refer to this id_str in the /etc/network/interfaces file:

auto lo
iface lo inet loopback

(your eth0 setup stays here)

auto wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
iface aoakley-home inet static
address 192.168.0.5
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.254

You'll notice in the settings above, that I have defined a static IP for aoakley-
home , but nothing for any of the other id_strs. Any id_str which is not mentioned
in /etc/network/interfaces will use the default setting, which in my config is
DHCP: iface default inet dhcp

You'll need to customise the address, netmask, network, broadcast and gateway
settings so that they are suitable for your home LAN. For example, your LAN might
use 192.168.1.xxx rather than 192.168.0.xxx . You can usually find this information
in your broadband router manual.

Reboot with shutdown -r now and it's job done. We now have a static IP for the
aoakley-home WiFi network, but dynamic IP everywhere else, and we can quickly and
easily add new WiFi networks to wpa_supplicant.conf without having to reconfigure
anything else.

Turning off WiFi when a wired network cable is plugged in

I want the same static IP at home regardless of whether I'm using WiFi or a wired
network cable. However, if both the eth0 and wlan0 interfaces try to use the same
IP address at the same time, this can cause a lot of problems; usually an
unresponsive network.

There are a gazillion ways around this problem. Look up "Linux route metrics" if
you want to learn the hard-core way of doing it. My solution is a lot more simple:
turn off WiFi if a wired network cable is inserted.

The ifplugd daemon provides a neat foundation that we can build on. If your eth0
interface is declared as hot-pluggable, ifplugd runs a special script whenever a
cable is inserted or removed. We can customise this script to turn the wlan0
interface off or on.

Recent distributions of Raspbian have ifplugd installed by default. If you don't


have it (for example, if type ifplugd tells you "not found"), you can use apt-get
install ifplugd to install it. If the installer prompts you to configure it, accept
the default configuration values of auto for static interfaces and all for
hotplugged interfaces. If you mess this up, you can use dpkg-reconfigure ifplugd to
correct the configuration at any time.

Let's start by customising the /etc/ifplugd/action.d/ifupdown script:

#!/bin/sh
set -e

case "$2" in
up)
/sbin/ifup $1
if [ "$1" == eth0 ]; then /sbin/ifdown wlan0 ; fi # This is a new bit
;;
down)
/sbin/ifdown $1
if [ "$1" == eth0 ]; then /sbin/ifup wlan0 ; fi # Another new bit
;;
esac

Next, we need to make sure that eth0 is defined as allow-hotplug in


/etc/network/interfaces file, and set up the static IP address for eth0 to be the
same as the wlan0 interface.

auto lo
iface lo inet loopback

allow-hotplug eth0
iface eth0 inet static
address 192.168.0.5
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.254

auto wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
iface aoakley-home inet static
address 192.168.0.5
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 192.168.0.254

I'll repeat my previous bit of advice here: don't set the wlan0 interface as hot-
pluggable, as in any case, most attempts to remove or re-insert a USB WiFi adaptor
whilst your Raspberry Pi is switched on, will probably result in your Pi rebooting
(or worse, not rebooting... ever... and a puff of magic smoke). My guess is that
this is because a USB WiFi adaptor consumes a lot more milliamps than a mouse or a
keyboard, and the Pi is already pretty sensitive to amperage fluctuations. It's a
twenty-five quid computer; if you need to remove or insert the WiFi adaptor, just
shut down the Pi first. The auto parameter for wlan0 defines the WiFi interface as
something that should be brought up at boot time and not disconnected until
shutdown. However if the dongle isn't there, the Pi will continue to boot without
it.

Reboot with shutdown -r now , and you should be done.

If it all goes wrong, restore your backup, or connect a screen to see what's
happening, or put the SD card in a desktop/laptop Linux PC and examine the /etc
files there.

By the way, this setup has also been tested on a Raspberry Pi Model A which doesn't
have an eth0 interface at all. It'll boot up and connect to WiFi just fine, so if
you have lots of Raspberry Pis, you can use this recipe for all of them.

================================================================================
AZARTICOLO:How to configure Wifi and USB wifi dongles from command-line
================================================================================

Contents

How to configure Wifi and USB wifi dongles from command-line


Easy way
Step-by-step guide for advanced users
Advanced topics
How to encrypt wifi password from command-line
How to enable both WiFi and Ethernet Interfaces
How can I set up a USB Wifi Dongle
What to do if the Shake doesn’t recognize your device
What to do if there are two wlan devices
How can I check if my USB Wifi Dongle sees the wifi networks
How can I configure my USB Wifi Dongle if my Wifi is “hidden”
Warning We do not recommend using the built-in Raspberry Shake 3 Model B’s wifi,
but it is available. Be aware that using the built-in Wifi (as opposed to Ethernet
or Wifi from a USB adapter) will introduce high amplitude RF noise into the
Raspberry Shake, often seriously compromising the seismic signal by introducing
high amplitude low-frequency spikes. This appears to be a result of the proximity
of the Wifi antenna to the Raspberry Shake board itself. External/ USB wifi
solutions are not as problematic because the wifi antenna is further from the
Raspberry Shake board. The Raspberry Pi Zero “W” and Raspberry 3 Model B+, supplied
by the end user (we ship with the 3 Model B), do not appear to suffer from this
same problem and can be safely used in native wifi mode.
Note The Raspberry Pi 3 Model B’s wifi, which we do not recommend using, is limited
to 2.4 GHz wifi connections. So “5G” connections, for example, will not work.
Easy way

Configure wifi from your Raspberry Shake’s internal web configuration page
http://rs.local

Step-by-step guide for advanced users


------------------------------------------------------------

To configure the wifi from the command-line, start by opening a terminal and
opening a connection to your Shake Pi:

$ ssh [email protected]
For SSH instructions, see: How to access your Raspberry Shake’s computer via ssh.
If you are a Windows user, you would use PuTTY for this step.

First confirm that the WiFi interface is enabled

$ cat /etc/network/interfaces
And verify that the following lines exist

allow-hotplug wlan0
iface wlan0 inet dhcp
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
If they aren’t there, edit the file, add the lines above, and save

$ sudo nano /etc/network/interfaces


Then edit the wpa_supplicant.conf

$ sudo nano /etc/wpa_supplicant/wpa_supplicant.conf


Paste the following lines at the end of the file and add your WiFi Connection
Details (ssid and psk):

network={
ssid="SSID of your wifi"
psk="password of your wifi"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
}
The ” are necessary. If you want to connect to a WiFi network with no password, use
this configuration:

network={
ssid="SSID of your wifi"
key_mgmt=NONE
}
Now reboot your shake:

$ sudo reboot
Advanced topics
How to encrypt wifi password from command-line
Execute this commmand:

$ wpa_passphrase <your_wifi_ssid_here> <your_wifi_password_here>


For example,

$ wpa_passphrase mywifi mypasswd


This will generate the following:

network={
ssid="mywifi"
#psk="mypasswd"
psk=175c63e5acd5b9bb66cfe2f89857db9060f2edf3989c89c19e5a54e5044cd2a4
}
Copy this output to /etc/wpa_supplicant/wpa_supplicant.conf and remove the #psk
line to make it fully encrypted

How to enable both WiFi and Ethernet Interfaces


-------------------------------------------------------------------------
When your Shake Pi boots, if it detects that an Ethernet interface is active, WiFi
will be turned off
by default. This is how Ethernet and WiFi network connections work with each other:

If an ethernet cable is plugged in, and the setting in the configuration file is
off, WiFi drivers will be automatically turned off at system boot to avoid
unnecessary spikes in the signal.
If no ethernet cable is plugged in, and if WiFi is properly configured, a
connection will be made to the WiFi network; the setting in the WiFi configuration
file is ignored.
If an ethernet cable is plugged in, and the end-user wants a dual network
connection over a WiFi network, then WiFi must be properly configured and the
setting in the WiFi configuration file must be set to ON (see below).
Per #3, if you wish to enable both WiFi and Ethernet interfaces, changing the
configuration file at /opt/settings/user/enable-wifi.conf will allow you to do so.
By default this file contains the following lines:

# WiFi enablement configuration file


# should contain a single line not beginning with #
# specifying either ON or OFF

OFF
Edit this file

$ sudo nano /opt/settings/user/enable-wifi.conf


Modify the last line from OFF to ON.

Reboot your shake:

$ sudo reboot
How can I set up a USB Wifi Dongle
First you’ll need to verify if your USB was tested on Raspberry Pi computer (RPi):
https://elinux.org/RPi_USB_Wi-Fi_Adapters

Then plug your USB Dongle into your RPi and see if the RPi recognizes the device.
For example,

$ sudo dmesg -T | grep usb


If your device was succesfully recognized, the OS will answer with something
similar to this:

$...
[Fri Aug 3 13:45:11 2018] usb 1-1.4: new high-speed USB device number 4 using
dwc_otg
[Fri Aug 3 13:45:11 2018] usb 1-1.4: New USB device found, idVendor=0bda,
idProduct=8176
[Fri Aug 3 13:45:11 2018] usb 1-1.4: New USB device strings: Mfr=1, Product=2,
SerialNumber=3
[Fri Aug 3 13:45:11 2018] usb 1-1.4: Manufacturer: Realtek
[Fri Aug 3 13:45:11 2018] usb 1-1.4: SerialNumber: 00e04c000001
[Fri Aug 3 13:45:12 2018] usbcore: registered new interface driver rtl8192cu
Now try this command and see if the RPi mounts the Dongle as wlan

$ iwconfig
eth0 no wireless extensions.

docker0 no wireless extensions.

vethba76434 no wireless extensions.

wlan0 unassociated Nickname:"<WIFI@REALTEK>"


Mode:Auto Frequency=2.412 GHz Access Point: Not-Associated
Sensitivity:0/0
Retry:off RTS thr:off Fragment thr:off
Power Management:off
Link Quality:0 Signal level:0 Noise level:0
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:0 Invalid misc:0 Missed beacon:0

lo no wireless extensions.

vetheb6d057 no wireless extensions.


As you can see, the RPi’s OS sees our Dongle as wlan0. But why wlan0 if RpiZw and
Rpi3 have their own wifi module inside? This is because, by default, wlan0 is
disabled on Raspberry Shake.

The next step will be to adjust your config file to match your wifi parameters and
reboot your RPi.

What to do if the Shake doesn’t recognize your device


If you are having trouble with your WiFi dongle, the Shake may have the wrong
driver (or no driver at all) for your dongle. This used to be a very frustrating
problem until we discovered a bash script that downloads and installs the correct
driver for your device automatically based on its USB code. The script is at
http://downloads.fars-robotics.net/wifi-drivers/install-wifi. Although it is
generally not a good idea to run code directly from the web, this process has never
failed us when all else does. To run the script, you need to save it somewhere on
your path. Follow these instructions to download and make it executable:

$ sudo wget http://downloads.fars-robotics.net/wifi-drivers/install-wifi -O


/usr/bin/install-wifi
$ sudo chmod +x /usr/bin/install-wifi
$ sudo install-wifi
Essentially this script checks the lsusb codes of USB devices against a compiled
list, then downloads and installs the correct driver for any devices it recognizes
as a WiFi dongle.

What to do if there are two wlan devices


Sometimes the USB dongle activation process will result in both the internal and
USB wifi modules on at the same time. This will look similar to the following:

$ iwconfig

eth0 no wireless extensions.

docker0 no wireless extensions.

vethba76434 no wireless extensions.

wlan0 IEEE 802.11 ESSID:off/any


Mode:Managed Access Point: Not-Associated Tx-Power=31 dBm
Retry short limit:7 RTS thr:off Fragment thr:off
Power Management:on

wlan1 unassociated Nickname:"<WIFI@REALTEK>"


Mode:Auto Frequency=2.412 GHz Access Point: Not-Associated
Sensitivity:0/0
Retry:off RTS thr:off Fragment thr:off
Power Management:off
Link Quality:0 Signal level:0 Noise level:0
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:0 Invalid misc:0 Missed beacon:0

lo no wireless extensions.

vetheb6d057 no wireless extensions.


In this case, wlan0 is the internal device and wlan1 is the USB dongle. This could
be switched based on your setup, and may change after a restart.

This defeats the purpose of using the USB WiFi, because the internal module will
generate radiofrequency noise that will affect the data, which is what we are
trying to avoid by using the dongle in the first place.

To disable internal WiFi:

Disable the internal module in the boot config:

$ sudo nano /boot/config.txt


Then paste the following line into the file, save, and exit:

dtoverlay=pi3-disable-wifi
Add the internal module to the modprobe blacklist:

$ sudo nano /etc/modprobe.d/raspi-blacklist.conf


Then paste the following lines into the file, save, and exit:

blacklist brcmfmac
blacklist brcmutil
Now, restart the Shake, run iwconfig, and check to make sure that only the wlan0
device appears.

How can I check if my USB Wifi Dongle sees the wifi networks
You can use the following command

$ sudo iwlist wlan0 scanning


The OS will reply

$ wlan0 Scan completed :


Cell 01 - Address: 00:15:6D:9E:D7:01
ESSID:"thediscoverwifi"
Protocol:IEEE 802.11bg
Mode:Master
Frequency:2.412 GHz (Channel 1)
Encryption key:on
Bit Rates:54 Mb/s
Extra:rsn_ie=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(you will see a
numer/character string)
IE: IEEE 802.11i/WPA2 Version 1
Group Cipher : TKIP
Pairwise Ciphers (2) : CCMP TKIP
Authentication Suites (1) : PSK
Quality=97/100 Signal level=49/100
The results will be different acording to your wifi network.

How can I configure my USB Wifi Dongle if my Wifi is “hidden”


You will need to specify an extra option in your wpa_supplicant.conf file

$ network={
ssid="yourHiddenSSID"
scan_ssid=1
psk="Your_wifi_password"
}

================================================================================
AZARTICOLO:Connect the UART GPS Module u-blox NEO 6M on the Raspberry Pi 3 B - part
1
================================================================================

[22:18, 24/9/2021] angelo zinnai: FULVIO GUARDA CHE ARTICOLO FAVOLOSO, QUELLO CHE
VOLEVI TU
http://satsignal.eu/ntp/Raspberry-Pi-NTP.html
[22:18, 24/9/2021] angelo zinnai: MI PRUDONO LE MANI !
[22:27, 24/9/2021] angelo zinnai: UNITO CON QUESTO HAI FATTO BINGO
https://www.hackster.io/bhushanmapari/interfacing-u-blox-neo-6m-gps-module-with-
raspberry-pi-3d15a5
[22:41, 24/9/2021] angelo zinnai: GRANDE FELIPE
https://felipeogutierrez.blogspot.com/2018/08/connect-uart-gps-module-u-blox-neo-
6m.html

part 1 - Connect the UART GPS Module u-blox NEO 6M on the Raspberry Pi 3 B
part 2 - Publishing gps data from Raspberry Pi to an IoT gateway (ThingsBoard)
part 3 - Using gpsd library to retrieve data from Raspberry Pi in Java
part 4 - Using gpsd library to retrieve data from Raspberry Pi in C

Raspberry Pi uses the GPIO pins to communicate with other devices. These pins work
over 3 different protocols (e.g.: I2C, SPI, and UART). This post describes how to
connect a GPS device based on the UART protocol to a Raspberry Pi B 3.

1. Hardware requirements
-------------------------------------

Waveshare Wireless UART GPS Module u-blox NEO-6M onboard [1]


Raspberry Pi 3 Model B [2]
4 female-female jumpers

By default, the UART transmit and receive pins are on GPIO 14 and GPIO 15
respectively, which are pins 8 and 10 on the GPIO header.
Gps module VCC to Raspberry Pi Pin 1 (3.3V)
Gps module GND to Raspberry Pi Pin 6 (Gnd)
Gps module RX to Raspberry Pi Pin 8, which is TX (GPIO14)
Gps module TC to Raspberry Pi Pin 10, which is RX (GPIO15)

You may find other links requesting you to connect the VCC pin from the gps module
to the Pin 2 or 4 on you raspberry Pi (5.0 volts). I didn’t test it because the
original documentation of the gps module says it uses only 3.3v [3]. So I recommend
you to not use 5v.

2. Software requirements
----------------------------------
Update the Raspberry Pi OS and install the clients.
I am using Raspbian GNU/Linux 9 (stretch) and I didn’t test with other versions.

sudo apt-get update


sudo apt-get dist-upgrade
sudo apt-get install gpsd gpsd-clients python-gps

3. Disable gpsd service

You will need to disable the gpsd systemd service by running the following
commands:

sudo systemctl stop gpsd.socket


sudo systemctl disable gpsd.socket

4. Disable Serial Port Terminal Shell Output


--------------------------------------------------------------
You need to disable Serial Port Terminal Shell Output on the Raspberry Pi.
I didn’t find this information on any tutorial, and I could figure out only by
reading forum posts.
If you don’t disable the “Serial Port Terminal Shell Output”, the GPS will not
receive any data

sudo raspi-config

Go to [5] interfaces option > Find serial [P6] > Select it and turn off
Would you like a login shell to be accessible over serial? > Select NO
Would you like the serial port hardware to be enable > Select YES
The serial login shell is disabled
The serial interface is enabled > OK > Finish > Reboot
If you need visual help on this section use this link [8].

5. Turn Off the Serial Console

You need to remove the strings “console=ttyAMA0,115200” from the file


“/boot/cmdline.txt”. Make sure that you have a backup of this file before to remove
something.

1
cp /boot/cmdline.txt /boot/cmdline.txt.bkp

After removing the string the file “/boot/cmdline.txt” will contain only this
content.

dwc_otg.lpm_enable=0 console=tty1 root=PARTUUID=c99b8a0b-02 rootfstype=ext4


elevator=deadline fsck.repair=yes rootwait

6. Setting the data rate of the module


------------------------------------------------------
We have to set the module that it should work with a baud rate of 9600.
I am using the /dev/serial0. You may find another tutorials that are using
/dev/ttyAMA0 [4] [5]
or /dev/ttyUSB0 if you have USB-female jumpers [6].
stty -F /dev/serial0 9600
cat /dev/serial0

Through the last command you already can see that the /dev/serial0 port is
listening values. So now we just start the GPSD on that serial port.

gpsd -n /dev/serial0 -F /var/run/gpsd.sock

The original site [7] documentation says the module can take up to 30 minutes to
receive data when it is running for the first time. The red light will blink when
the module is receiving data. You can already start the gpsmon interface to see if
it is receiving data or the cgps -s.

7. Visualizing the gps data


---------------------------------------
Open the client interface gpsmon.

https://felipeogutierrez.blogspot.com/2018/08/connect-uart-gps-module-u-blox-neo-
6m.html

You can use the "cgps" command to show this client interface of the gps or emit the
values on
your terminal using the "gpspipe -r -p -P -n 10" command line.

=================================================================================
AZARTICOLO:Publishing gps data from Raspberry Pi to an IoT gateway (ThingsBoard) -
part 2
================================================================================
part 1 - Connect the UART GPS Module u-blox NEO 6M on the Raspberry Pi 3 B
part 2 - Publishing gps data from Raspberry Pi to an IoT gateway (ThingsBoard)
part 3 - Using gpsd library to retrieve data from Raspberry Pi in Java
part 4 - Using gpsd library to retrieve data from Raspberry Pi in C

This is a use case to publish data from a GPS sensor at an IoT gateway. The GPS
sensor is connected to a Raspberry Pi B3. The IoT gateway is used as a graphical
interface to the latitude and longitude. The Raspberry Pi B3 sends data through
MQTT protocol using a publish and subscriber policy. The IoT gateway used is an
open-source software called ThingsBoard.

ThingsBoard is an open-source IoT platform for data collection, processing,


visualization, and device management. It enables device connectivity via industry
standard IoT protocols - MQTT, CoAP and HTTP and supports both cloud and on-
premises deployments. ThingsBoard combines scalability, fault-tolerance and
performance so you will never lose your data.

1. Publishing static data on ThingsBoard

To start the use case you can implement the static mode of publishing data to the
IoT gateway. You will need only 3 files. Two of them comprise the data to publish
and the third is the script which uses MQTT client. The online reference is from
the original ThingsBoard website.

This is the attributes-data.json file

{"firmware_version":"1.0.1", "serial_number":"SENSE2"}

This is the telemetry-data.json file


{"latitude":52.520008, "longitude":13.304954, "temperature":31.5, "active": false}

This is the mosquitto.sh file which sends the Json data to the ThingsBoard IoT
gateway.

#!/bin/sh

# Set ThingsBoard host to "demo.thingsboard.io" or "localhost"


THINGSBOARD_HOST="192.168.1.100"
# Replace YOUR_ACCESS_TOKEN with one from Device credentials window.
ACCESS_TOKEN="IHAUD6kvW6C1Zp10uJm4"
# Publish serial number and firmware version attributes
mosquitto_pub -d -h "$THINGSBOARD_HOST" -t "v1/devices/me/attributes" -u
"$ACCESS_TOKEN" -f "attributes-data.json"
# Publish timeseries data as an object without timestamp (server-side timestamp
will be used)
mosquitto_pub -d -h "$THINGSBOARD_HOST" -t "v1/devices/me/telemetry" -u
"$ACCESS_TOKEN" -f "telemetry-data.json"

2. Publishing dynamic data on ThingsBoard

However, as you can see in the previous post we already have real and dynamic data
been generated by a neo 6 M GPS sensor. What we have to build now is a scheduler
which reads the gps data from the Raspberry Pi and sends it to the IoT gateway. We
also are going to use MQTT protocol to send data but now using the Eclipse Paho
library. The Eclipse Paho project provides open-source client implementations of
MQTT and MQTT-SN messaging protocols aimed at new, existing, and emerging
applications for the Internet of Things (IoT).

Here is how the Mqtt client looks like. We have the methods connect, publish, and
disconnect. The connect method needs a client Id, the token of the device where we
desire to publish the message, the name of the device, the IP of the device (it
uses TCP connection and port 1883), and some kind of persistence. For now we are
using memory persistence. This is the link for the source code.

package org.cloud.sense.client;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

@Slf4j
public class MqttClient {

Logger log = LoggerFactory.getLogger(MqttClient.class);

public static final ObjectMapper MAPPER = new ObjectMapper();

@Getter
private final String deviceToken;
@Getter
private final String deviceName;
@Getter
private final String clientId;
private final MqttClientPersistence persistence;
private final MqttAsyncClient client;

public MqttClient(String uri, String deviceName, String deviceToken) throws


Exception {
this.clientId = MqttAsyncClient.generateClientId();
this.deviceToken = deviceToken;
this.deviceName = deviceName;
this.persistence = new MemoryPersistence();
this.client = new MqttAsyncClient(uri, clientId, persistence);
}

public boolean connect() throws Exception {


MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(deviceToken);
try {
client.connect(options, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken iMqttToken) {
log.info("[{}] connected to Thingsboard!", deviceName);
}

@Override
public void onFailure(IMqttToken iMqttToken, Throwable e) {
log.error("[{}] failed to connect to Thingsboard!", deviceName,
e);
}
}).waitForCompletion();
} catch (MqttException e) {
log.error("Failed to connect to the server", e);
}
return client.isConnected();
}

public void disconnect() throws Exception {


client.disconnect().waitForCompletion();
}

public void publishAttributes(JsonNode data) throws Exception {


publish("v1/devices/me/attributes", data, true);
}

public void publishTelemetry(JsonNode data) throws Exception {


publish("v1/devices/me/telemetry", data, false);
}

private void publish(String topic, JsonNode data, boolean sync) throws


Exception {
MqttMessage msg = new
MqttMessage(MAPPER.writeValueAsString(data).getBytes(StandardCharsets.UTF_8));
IMqttDeliveryToken deliveryToken = client.publish(topic, msg, null, new
IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
log.trace("Data updated!");
}

@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception)
{
log.error("[{}] Data update failed!", deviceName, exception);
}
});
if (sync) {
deliveryToken.waitForCompletion();
}
}
}

Additionally, we also need the scheduler to read the gps data from the Raspberry
Pi.
We use the command line "gpspipe -r -n 50" to collect the gps data and take the
average of it.
This schedule only run 10 times, just for test porpuses. The link for the source
code can be found here.

package org.cloud.sense.device;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import org.cloud.sense.client.MqttClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class GpsPublish {

Logger log = LoggerFactory.getLogger(GpsPublish.class);


public final ObjectMapper MAPPER = new ObjectMapper();
@Getter
private MqttClient mqttClient;

public static class Coordinates<Lat, Lng> {


public Lat latitude;
public Lng longitude;

public Coordinates(Lat latitude, Lng longitude) {


this.latitude = latitude;
this.longitude = longitude;
}
}

public GpsPublish() {
}

public GpsPublish(String uri, String deviceName, String deviceToken) {


try {
this.mqttClient = new MqttClient(uri, deviceName, deviceToken);
} catch (Exception e) {
log.error("Failed to create Mqtt client! [{}]", uri, e);
e.printStackTrace();
}
}

public boolean connect() throws Exception {


return this.mqttClient.connect();
}

public void disconnect() throws Exception {


this.mqttClient.disconnect();
}

public void publishData(String jsonString) {


try {
JsonNode data = MAPPER.readTree(jsonString);
this.mqttClient.publishTelemetry(data);
} catch (Exception e) {
e.printStackTrace();
}
}

public void publishData(String lat, String lng) {


try {
publishData("{\"latitude\":" + lat + ", \"longitude\":" + lng + "}");
} catch (Exception e) {
e.printStackTrace();
}
}

public void publishData(Coordinates coordinates) {


try {
publishData("{\"latitude\":" + coordinates.latitude +
", \"longitude\":" + coordinates.longitude + "}");
} catch (Exception e) {
e.printStackTrace();
}
}

public Coordinates getGpsData() {


Runtime runTime = Runtime.getRuntime();
List<Double> latitudes = new ArrayList<Double>();
List<Double> longitudes = new ArrayList<Double>();
try {
final Process p = runTime.exec("gpspipe -r -n 25");

new Thread(new Runnable() {


public void run() {
BufferedReader input = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String line = null;

try {
while ((line = input.readLine()) != null) {
// log.info(line);
if (line != null && line.contains("GPGGA")) {
log.info(line);
String[] arr = line.split(",");
log.info(arr[2] + " - " + arr[4]);
latitudes.add(Double.parseDouble(arr[2]));
longitudes.add(Double.parseDouble(arr[4]));
} else if (line != null && line.contains("GPRMC")) {
log.info(line);
String[] arr = line.split(",");
log.info(arr[3] + " - " + arr[5]);
latitudes.add(Double.parseDouble(arr[3]));
longitudes.add(Double.parseDouble(arr[5]));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

p.waitFor();

} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!latitudes.isEmpty() && !longitudes.isEmpty()) {
Double latitudeAvg = latitudes.stream().mapToDouble(i ->
i).average().getAsDouble();
Double longitudeAvg = longitudes.stream().mapToDouble(i ->
i).average().getAsDouble();

log.info(String.valueOf(latitudeAvg));

log.info("Publishing latitude: " + latitudeAvg + " and longitudes: " +


longitudeAvg);

Coordinates coo = convertDMSToCoordinate(latitudeAvg.toString(), true,


longitudeAvg.toString(), true);

return coo;
}
log.error("No coordinates found.");
return new Coordinates(0, 0);
}

/**
* Convert Degree Minute Second (DMS) to coordinates (latitude and longitude)
* Degree +minutes /60+seconds /3600/10000
*
* @return
*/
public Coordinates convertDMSToCoordinate(String dmsLat, boolean dmsLatNorth,
String dmsLng, boolean dmsLngEast) {

String[] latArr = dmsLat.split("\\.");


String[] lngArr = dmsLng.split("\\.");
double latDegree = Double.parseDouble(latArr[0].substring(0, 2));
double latMinute = Double.parseDouble(latArr[0].substring(2));
double latSecond = Double.parseDouble(latArr[1]) * 60;
double lngDegree = Double.parseDouble(lngArr[0].substring(0, 2));
double lngMinute = Double.parseDouble(lngArr[0].substring(2));
double lngSecond = Double.parseDouble(lngArr[1]) * 60;
System.out.println(latDegree + " " + latMinute + " " + latSecond);
System.out.println(lngDegree + " " + lngMinute + " " + lngSecond);

Double latitude = latDegree + latMinute / 60 + latSecond / 3600 / 10000;


Double longitude = lngDegree + lngMinute / 60 + lngSecond / 3600 / 10000;
System.out.println(latitude + " " + longitude);

return new Coordinates(latitude, longitude);


}

public static void main(String[] args) throws Exception {

GpsPublish gpsPublisher = new GpsPublish("tcp://192.168.1.100:1883",


"SENSE2", "IHAUD6kvW6C1Zp10uJm4");
gpsPublisher.connect();
for (int i = 0; i < 10; i++) {
//
gpsPublisher.publishData("{\"latitude\":52.555558, \"longitude\":13.304444, \"tempe
rature\":35.2, \"active\": false}");
gpsPublisher.publishData(gpsPublisher.getGpsData());
Thread.sleep(10000);
}
gpsPublisher.disconnect();
}
}

================================================================================
AZARTICOLO:Using gpsd library to retrieve data from Raspberry Pi in Java - part 3
================================================================================
part 1 - Connect the UART GPS Module u-blox NEO 6M on the Raspberry Pi 3 B
part 2 - Publishing gps data from Raspberry Pi to an IoT gateway (ThingsBoard)
part 3 - Using gpsd library to retrieve data from Raspberry Pi in Java
part 4 - Using gpsd library to retrieve data from Raspberry Pi in C

It is possible to get the values from the gps sensor using the gpsd library.
According to the
documentation, you can build a client which connects direct to the host through the
port 2947.
This is the same approach that gpspipe, gpsmon, and cgps do. So, you can create a
client that
connects to the gpsd daemon service of the Raspberry Pi. The documentation explains
how to create client using C programming language and Python.

I show in this post a client implemented in Java which retrieves more relevant data
from the gpsd library.
The gpsd library retrieves data from the gps sensor according to some mode which
goes from 0 to 3.

MODE_NOT_SEEN 0 mode update not seen yet


MODE_NO_FIX 1 none
MODE_2D 2 good for latitude/longitude
MODE_3D 3 good for altitude/climb too
If the gpsd daemon is on mode 2 or 3 means that we can also retrieve values
regarding of latitude,
longitude, altitude, horizontal and vertical speed, and time. Here I show a client
in Java which uses
the gpsd4j library. The source code of this gps client can be found here.

package org.cloud.sense.device;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ivkos.gpsd4j.client.GpsdClient;
import com.ivkos.gpsd4j.client.GpsdClientOptions;
import com.ivkos.gpsd4j.messages.DeviceMessage;
import com.ivkos.gpsd4j.messages.enums.NMEAMode;
import com.ivkos.gpsd4j.messages.reports.SKYReport;
import com.ivkos.gpsd4j.messages.reports.TPVReport;
import lombok.Getter;
import org.cloud.sense.client.MqttClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

import static com.codahale.metrics.MetricRegistry.name;

public class GpsPublishIvkos {

Logger log = LoggerFactory.getLogger(GpsPublishIvkos.class);


public final ObjectMapper MAPPER = new ObjectMapper();
@Getter
private MqttClient mqttClient;
private DateTimeFormatter formatter;
private final MetricRegistry metrics = new MetricRegistry();
private Timer responsesGpsStart = null;
private Timer responsesGpsSendCommand = null;
private ConsoleReporter reporter;

public static class Coordinates<Lat, Lng> {


public Lat latitude;
public Lng longitude;

public Coordinates(Lat latitude, Lng longitude) {


this.latitude = latitude;
this.longitude = longitude;
}
}

public GpsPublishIvkos() {
}

public GpsPublishIvkos(String uri, String deviceName, String deviceToken) {


try {
this.mqttClient = new MqttClient(uri, deviceName, deviceToken);
this.formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
this.responsesGpsStart = this.metrics.timer(name(GpsPublishIvkos.class,
"responsesGpsStart"));
this.responsesGpsSendCommand =
this.metrics.timer(name(GpsPublishIvkos.class, "responsesGpsSendCommand"));
this.reporter = ConsoleReporter.forRegistry(metrics)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
this.reporter.start(10, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("Failed to create Mqtt client! [{}]", uri, e);
e.printStackTrace();
}
}

public boolean connect() throws Exception {


return this.mqttClient.connect();
}

public void disconnect() throws Exception {


this.mqttClient.disconnect();
}

public void publishData(String jsonString) {


try {
JsonNode data = MAPPER.readTree(jsonString);
this.mqttClient.publishTelemetry(data);
} catch (Exception e) {
log.error("Could not Publish GPS data: [{}]", e.getMessage());
e.printStackTrace();
}
}

public void publishGpsData(Double lat, Double lng, Double alt, Double speed,
LocalDateTime t) {
try {
String value = "{";

if (lat != null && lng != null && !Double.isNaN(lat) && !


Double.isNaN(lng)) {
value = value + "\"latitude\":" + lat + ", \"longitude\":" + lng;
}
if (alt != null && !Double.isNaN(alt)) {
if (value.length() > 5) value = value + ", ";
value = value + "\"altitude\":" + alt;
}
if (speed != null && !Double.isNaN(speed)) {
if (value.length() > 5) value = value + ", ";
value = value + "\"speed\":" + speed;
}
if (t != null) {
System.out.println(t);
if (value.length() > 5) value = value + ", ";
value = value + "\"timestamp\":" + "\"" + t.format(formatter) +
"\"";
}

value = value + "}";


log.info("Publishing GPS data: [{}]", value);
publishData(value);
} catch (Exception e) {
log.error("Could not Publish GPS data: [{}]", e.getMessage());
e.printStackTrace();
}
}

public void publishSatelliteData(int satellites) {


try {
String value = "{";
if (satellites != 0) {
value = value + "\"satellites\":" + satellites;
}
value = value + "}";
log.info("Publishing Satellite data: [{}]", value);
publishData(value);
} catch (Exception e) {
log.error("Could not Publish Satellite data: [{}]", e.getMessage());
e.printStackTrace();
}
}

public void getGpsData() {


try {

// You can pass an options object if you wish to configure connection


handling
GpsdClientOptions options = new GpsdClientOptions()
.setReconnectOnDisconnect(true)
.setConnectTimeout(3000) // ms
.setIdleTimeout(30) // seconds
.setReconnectAttempts(5)
.setReconnectInterval(3000); // ms

// Create a client for connecting to the gpsd server at localhost, port


2947
GpsdClient gpsClient = new GpsdClient("localhost", 2947, options)
.addErrorHandler(System.err::println) // Adds a handler that
prints received gpsd errors to stderr
.addHandler(TPVReport.class, tpv -> { // Adds a message handler
that handles incoming TPV messages
Double lat = tpv.getLatitude();
Double lon = tpv.getLongitude();
Double altitude = tpv.getAltitude();
Double speed = tpv.getSpeed();
LocalDateTime t = tpv.getTime();
log.info("TPV: {}", tpv);

if (NMEAMode.TwoDimensional.equals(tpv.getMode()) ||
NMEAMode.ThreeDimensional.equals(tpv.getMode())) {
publishGpsData(lat, lon, altitude, speed, t);
} else {
log.info("GPS data not available");
}
})
.addHandler(SKYReport.class, sky -> {
log.info("We can see [{}] satellites",
sky.getSatellites().size());
publishSatelliteData(sky.getSatellites().size());
});

gpsClient.setSuccessfulConnectionHandler(client -> {
DeviceMessage device = new DeviceMessage();
device.setPath("/dev/serial0");
device.setNative(true);

Timer.Context context = null;


try {
context = responsesGpsSendCommand.time();
client.sendCommand(device);
} finally {
context.stop();
}

client.watch(); // Send a command to the server to enable dumping


of messages
});

Timer.Context context = null;


try {
context = responsesGpsStart.time();
gpsClient.start(); // After you have created a client and
(optionally) added handlers, you can start it
} finally {
context.stop();
}
Thread.sleep(60000);

// To stop the client:


gpsClient.stop();

} catch (InterruptedException e) {
log.error("Could not receive data from GPS sensor. Reason: [{}]",
e.getMessage());
e.printStackTrace();
} catch (Exception e) {
log.error("Could not Publish GPS data: [{}]", e.getMessage());
e.printStackTrace();
}
}

public static void main(String[] args) throws Exception {

GpsPublishIvkos gpsPublisher = new


GpsPublishIvkos("tcp://192.168.1.100:1883", "SENSE2", "IHAUD6kvW6C1Zp10uJm4");
gpsPublisher.connect();
gpsPublisher.getGpsData();
gpsPublisher.disconnect();
}
}

In order to improve the use case of part 2 I have add more gadgets monitors on the
ThingsBoard dashboard. Besides the map, you can see the altitude and speed of the
gps sensor. The first chart depicts how many satellites the gps sensor is receiving
data.
=================================================================================
AZARTICOLO:Using gpsd library to retrieve data from Raspberry Pi in C - part 4
================================================================================
part 1 - Connect the UART GPS Module u-blox NEO 6M on the Raspberry Pi 3 B
part 2 - Publishing gps data from Raspberry Pi to an IoT gateway (ThingsBoard)
part 3 - Using gpsd library to retrieve data from Raspberry Pi in Java
part 4 - Using gpsd library to retrieve data from Raspberry Pi in C

In this post, I show a piece of code written in C which uses the gpsd library to
connect to a GPS device. I connected the GPS device to a Raspberry Pi B 3 through
the UART port (Universal asynchronous receiver-transmitter). This port uses only 2
pins of the Raspberry Pi. The table below you can see the comparison of the three
protocols available at a Raspberry Pi (e.g.: I2C, SPI, and UART).
===================================================================================

Summarizing the code, it uses mainly three functions of the library. gps_open to
open a connection to the sensor. gps_stream to subscribe to a channel of the
library which gives a stream of GPS data. gps_waiting blocks the thread until the
gps device sends new data, which comes in about 1 second. gps_read to read the
data. The github repository of this code is here.

/*
* gpsClient.h
*
* Created on: Aug 24, 2018
* Author: felipe
*/

#ifndef GPS_GPSCLIENT_H_
#define GPS_GPSCLIENT_H_

int runGpsStreamClient();

#endif /* GPS_GPSCLIENT_H_ */

/*
* gpsClient.c
*
* command line to compile the source code
* # gcc -o gpsClient gpsClient.cpp -lm -lgps
*
* Created on: Aug 22, 2018
* Author: felipe
*/

#include <gps.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <sys/time.h>

#include "gpsClient.h"
#include "../utils/metrics.h"
int runGpsStreamClient() {
int rc;
int count = 0;
clock_t cpu_start;
struct timeval user_start;
struct gps_data_t gps_data;

gettimeofday(&user_start, NULL);
cpu_start = clock();
if ((rc = gps_open("localhost", "2947", &gps_data)) == -1) {
printf("code: %d, reason: %s\n", rc, gps_errstr(rc));
return EXIT_FAILURE;
}
get_cpu_and_user_time(cpu_start, user_start, "gps_open");

gettimeofday(&user_start, NULL);
cpu_start = clock();
gps_stream(&gps_data, WATCH_ENABLE | WATCH_JSON, NULL);
get_cpu_and_user_time(cpu_start, user_start, "gps_stream");

while (count < 60) {

gettimeofday(&user_start, NULL);
cpu_start = clock();
/* wait for 2 second to receive data */
if (gps_waiting(&gps_data, 20000000)) {
get_cpu_and_user_time(cpu_start, user_start, "gps_waiting");

gettimeofday(&user_start, NULL);
cpu_start = clock();
int rc = gps_read(&gps_data);
get_cpu_and_user_time(cpu_start, user_start, "gps_read");

/* read data */
if (rc == -1) {
printf(
"error occurred reading gps data. code: %d, reason: %s\n",
rc, gps_errstr(rc));
} else {

/* Display data from the GPS receiver. */


double lat = gps_data.fix.latitude;
double lon = gps_data.fix.longitude;
double alt = gps_data.fix.altitude;
double speed = gps_data.fix.speed;
double climb = gps_data.fix.climb;
int status = gps_data.status;
int mode = gps_data.fix.mode;
time_t seconds = (time_t) gps_data.fix.time;

/**
* MODE_NOT_SEEN 0 mode update not seen yet
* MODE_NO_FIX 1 none
* MODE_2D 2 good for latitude/longitude
* MODE_3D 3 good for altitude/climb too
*/
if ((status == STATUS_FIX)
&& (mode == MODE_2D || mode == MODE_3D)
&& !isnan(lat) && !isnan(lon)) {
printf("GPS data OK - ");
printf("status[%d], ", status);
printf("mode[%d], ", mode);
printf("latitude[%f], ", lat);
printf("longitude[%f], ", lon);
printf("altitude[%f], ", alt);
printf("speed[%f], ", speed);
printf("v speed[%f]\n", climb);
print_time(seconds);
print_current_time();
printf("\n");
} else {
printf("GPS data NOK.\n");
}
}
} else {
get_cpu_and_user_time(cpu_start, user_start, "gps_waiting");
printf(
"counter[%d]. Timeout to retrieve data from gpsd. Maybe increase gps_waiting.\
n",
count);
}
count++;
// sleep(1);
}

/* When you are done... */


gps_stream(&gps_data, WATCH_DISABLE, NULL);
gps_close(&gps_data);

return EXIT_SUCCESS;
}

The piece of code below just shows how to retrieve the time difference of the CPU
and user on the Operating System.

/*
* metrics.h
*
* Created on: Aug 27, 2018
* Author: felipe
*/

#ifndef UTILS_METRICS_H_
#define UTILS_METRICS_H_

void get_cpu_time(clock_t start_cpu, char* func_name);


void get_user_time(struct timeval start_user, char* func_name);
void get_cpu_and_user_time(clock_t start_cpu, struct timeval start_user,
char* func_name);
void print_current_time();
void print_time(time_t seconds);

#endif /* UTILS_METRICS_H_ */

/*
* metrics.c
*
* Created on: Aug 27, 2018
* Author: felipe
*/

#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/timeb.h>
#include <math.h>

#include "metrics.h"

void get_cpu_and_user_time(clock_t start_cpu, struct timeval start_user,


char* func_name) {
get_cpu_time(start_cpu, func_name);
get_user_time(start_user, func_name);
}

void get_cpu_time(clock_t start_cpu, char* func_name) {


clock_t t = clock() - start_cpu;
double time_taken = (((double) t) / CLOCKS_PER_SEC) * 1000; // milliseconds
printf("CPU time [%s] %.10f milliseconds.\n", func_name, time_taken);
}

void get_user_time(struct timeval start_user, char* func_name) {


struct timeval stop;
gettimeofday(&stop, NULL);
double start_ms = (double) start_user.tv_sec * 1000000
+ (double) start_user.tv_usec;
double stop_ms = (double) stop.tv_sec * 1000000 + (double) stop.tv_usec;
double millisec = ((double) stop_ms - (double) start_ms) / 1000;
printf("User time [%s] %.10f milliseconds.\n", func_name, millisec);
}

void print_current_time() {
char buffer[100];
int millisec;
struct tm* tm_info;
struct timeval tv;

gettimeofday(&tv, NULL);

millisec = lrint(tv.tv_usec / 1000.0); // Round to nearest millisec


if (millisec >= 1000) { // Allow for rounding up to nearest second
millisec -= 1000;
tv.tv_sec++;
}

tm_info = localtime(&tv.tv_sec);

strftime(buffer, 100, " Current time %Y-%m-%d %H:%M:%S", tm_info);


printf("%s.%03d \n", buffer, millisec);
}

void print_time(time_t seconds) {


char buffer[100];

long ms; // Milliseconds


struct timespec spec;

clock_gettime(CLOCK_REALTIME, &spec);
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
if (ms > 999) {
ms = 0;
}

strftime(buffer, 100, " GPS time %Y-%m-%d %H:%M:%S",


localtime(&seconds));
printf("%s.%03ld \n", buffer, ms);
}

The table below shows the comparison between the C and Java code in milliseconds.
Afterward, I show the measurement of the C code. The gpsd library collects raw data
from the gps sensor and emits it every second. If you want to reduce the time of
this publishing mechanism you have to change the baud rate configured at part 1 of
these posts. However, the vendors do not advise for that because it can lead to
precision errors on the measurements. Considering that, the waiting time the
listener receives new data from the gpsd library is pretty good (~1000
milliseconds). The only bottleneck is to connect to the gpsd library, which is 3
milliseconds with C code and ~2480 milliseconds using Java code.

CPU time [gps_open] 3.1360000000 milliseconds.


User time [gps_open] 3.2640000000 milliseconds.
CPU time [gps_stream] 0.1050000000 milliseconds.
User time [gps_stream] 0.1390000000 milliseconds.
CPU time [gps_waiting] 0.0380000000 milliseconds.
User time [gps_waiting] 0.0650000000 milliseconds.
CPU time [gps_read] 0.1210000000 milliseconds.
User time [gps_read] 0.1520000000 milliseconds.
GPS data NOK.
CPU time [gps_waiting] 0.0130000000 milliseconds.
User time [gps_waiting] 0.0760000000 milliseconds.
CPU time [gps_read] 0.1670000000 milliseconds.
User time [gps_read] 0.3610000000 milliseconds.
GPS data NOK.
CPU time [gps_waiting] 0.0050000000 milliseconds.
User time [gps_waiting] 0.0270000000 milliseconds.
CPU time [gps_read] 0.0520000000 milliseconds.
User time [gps_read] 0.1130000000 milliseconds.
GPS data NOK.
CPU time [gps_waiting] 0.0340000000 milliseconds.
User time [gps_waiting] 45.6240000000 milliseconds.
CPU time [gps_read] 0.1760000000 milliseconds.
User time [gps_read] 0.2530000000 milliseconds.
GPS data OK - status[1], mode[3], latitude[52.515141], longitude[13.327208],
altitude[66.185000], speed[0.319000], v speed[-0.241000]
GPS time 2018-08-29 19:38:51.003
Current time 2018-08-29 19:38:52.003

CPU time [gps_waiting] 0.0430000000 milliseconds.


User time [gps_waiting] 1000.3330000000 milliseconds.
CPU time [gps_read] 0.1700000000 milliseconds.
User time [gps_read] 0.1990000000 milliseconds.
GPS data OK - status[1], mode[3], latitude[52.515135], longitude[13.327206],
altitude[66.175000], speed[0.390000], v speed[-0.238000]
GPS time 2018-08-29 19:38:52.004
Current time 2018-08-29 19:38:53.004

CPU time [gps_waiting] 0.0370000000 milliseconds.


User time [gps_waiting] 998.9380000000 milliseconds.
CPU time [gps_read] 0.1710000000 milliseconds.
User time [gps_read] 0.2020000000 milliseconds.
GPS data OK - status[1], mode[3], latitude[52.515133], longitude[13.327205],
altitude[66.249000], speed[0.340000], v speed[-0.234000]
GPS time 2018-08-29 19:38:53.003
Current time 2018-08-29 19:38:54.004

CPU time [gps_waiting] 0.0410000000 milliseconds.


User time [gps_waiting] 998.6580000000 milliseconds.
CPU time [gps_read] 0.1730000000 milliseconds.
User time [gps_read] 0.2040000000 milliseconds.
GPS data OK - status[1], mode[3], latitude[52.515131], longitude[13.327201],
altitude[66.304000], speed[0.322000], v speed[-0.233000]
GPS time 2018-08-29 19:38:54.003
Current time 2018-08-29 19:38:55.003

CPU time [gps_waiting] 0.0380000000 milliseconds.


User time [gps_waiting] 1001.1970000000 milliseconds.
CPU time [gps_read] 0.1740000000 milliseconds.
User time [gps_read] 0.2050000000 milliseconds.
GPS data OK - status[1], mode[3], latitude[52.515129], longitude[13.327200],
altitude[66.454000], speed[0.235000], v speed[-0.223000]
GPS time 2018-08-29 19:38:55.004
Current time 2018-08-29 19:38:56.004

References

[1] Raspberry Pi I2C / SPI / UART Communications


[2] source code

Posted by Felipe
Enviar por e-mail
Postar no blog!
Compartilhar no Twitter
Compartilhar no Facebook
Compartilhar com o Pinterest
Labels: C, gps, gpsd, IoT, Raspberry Pi, sensors
Location: Berlin, Germany
Nenhum comentário:
Postar um comentário

================================================================================
AZARTICOLO:Navigation with navit on RaspberryPi
================================================================================
https://github.com/navit-gps/raspbian-ua-netinst
https://github.com/navit-gps/navit peodotto completo incluso Android
http://libresmartphone.com/navigation-system-with-the-ultimate-gps-and-raspberry-
pi/

Navigation system with the ultimate gps and raspberry pi


This article describes, how to setup a Raspberry Pi with open source project
navit as a navigation software. It could be setup in a car and if e.g. attached
to a monitor with touch interface, it could be used as a navigation system
with up-to-date maps from OpenStreetMap.

I've tested it and it works pretty cool, this is why I finally documented it here.

Prerequisites
------------------

This project requires the setup of an GPS-Module


(e.g. from adafruit Ultimate GPS from adafruit), if this is done, the gpsd
has to be up an running.

The gpsd is the daemon which is connected by navit to get the current position.

Preparation
----------------

Before starting to implement it helps to get some packages preinstalled,


which wil be used during the installation steps:

sudo apt-get update


sudo apt-get upgrade

sudo apt-get install gpsd gpsd-clients cmake subversion build-essential


espeak freeglut3-dev imagemagick libdbus-1-dev libdbus-glib-1-dev libdevil-dev
libfontconfig1-dev libfreetype6-dev libfribidi-dev libgarmin-dev libglc-dev
libgps-dev libgtk2.0-dev libimlib2-dev libpq-dev libqt4-dev libqtwebkit-dev
librsvg2-bin libsdl-image1.2-dev libspeechd-dev libxml2-dev ttf-liberation

Installation of navit
--------------------------

As the installation of the precompiled package (which is existing) is


somehow too old, it's ok to just build it on your own on the Raspberry Pi.
So if you are really lazy you just install the precompiled package
(which is not recommended):

apt-get install navit

But if you want to get an up-to-date version, you can easily build it on
your own, by just grabbing a copy of the current version from the subversion
repository (as also recommend by the team!) an compile it on your own:

svn co https://navit.svn.sourceforge.net/svnroot/navit/trunk/navit/
navit_repository
cd navit_repository
mkdir build
cd build
cmake ..
make

The “make” takes about 30 minutes on the Raspberry Pi an then you are
done so far. Finally just copy the folder with the build-result to a destination
of your choice, which can be found now in “~/navit_repository/build/navit”.
I copied mine to pi's home, so mine can be accessed now by going to:

cd ~/navit

If you have a look in the final build result, the folder should look somehow
like this one:

pi@gpsraspberrypi ~/navit $ ls -al --color=auto ~/navit


drwxr-xr-x 16 pi pi 4096 Aug 14 16:48 .
drwxr-xr-x 11 pi pi 4096 Aug 14 16:34 ..
drwxr-xr-x 3 pi pi 4096 Aug 14 12:14 binding
-rw-r--r-- 1 pi pi 83 Aug 14 16:46 bookmark.txt
-rw-r--r-- 1 pi pi 1723 Aug 14 12:14 builtin.c
drwxr-xr-x 8 pi pi 4096 Aug 14 12:15 CMakeFiles
-rw-r--r-- 1 pi pi 4934 Aug 14 12:15 cmake_install.cmake
-rw-r--r-- 1 pi pi 91 Aug 14 16:50 destination.txt
drwxr-xr-x 3 pi pi 4096 Aug 14 12:15 fib-1.1
drwxr-xr-x 3 pi pi 4096 Aug 14 12:14 font
drwxr-xr-x 7 pi pi 4096 Aug 14 12:14 graphics
drwxr-xr-x 5 pi pi 4096 Aug 14 12:14 gui
-rw-r--r-- 1 pi pi 3178680 Aug 14 12:21 libnavit_core.a
-rw-r--r-- 1 pi pi 55724 Aug 14 12:15 Makefile
drwxr-xr-x 9 pi pi 4096 Aug 14 12:14 map
drwxr-xr-x 3 pi pi 4096 Aug 14 16:32 maps
drwxr-xr-x 3 pi pi 4096 Aug 14 12:36 maptool
-rwxr-xr-x 1 pi pi 1568620 Aug 14 12:21 navit
-rw-r--r-- 1 pi pi 5447 Aug 14 12:21 navit.dtd
-rw-r--r-- 1 pi pi 298194 Aug 14 11:46 navit.xml
drwxr-xr-x 3 pi pi 4096 Aug 14 12:14 osd
drwxr-xr-x 5 pi pi 4096 Aug 14 12:14 speech
drwxr-xr-x 3 pi pi 4096 Aug 14 12:14 support
drwxr-xr-x 6 pi pi 4096 Aug 14 12:14 vehicle
-rw-r--r-- 1 pi pi 53 Aug 14 12:15 version.h
drwxr-xr-x 3 pi pi 69632 Aug 14 12:44 xpm

Before starting the first time, a map of the current GPS region is needed,
so that there is something to see at the current GPS-position.

Grabbing and installing a map


--------------------------------------

The big advantage here is, that maps from the open street map project
can be taken. The part of the map can easily be chosen as required,
which is really cool! That gives a high flexibility in regards of the size of
the used SD-card and the region I'm interested in.

To grab a map, just use the offered navit service Navit Planet Extractor.

Just mark a region and save the binary mapfile of the marked region on
the RaspberryPi. In this example is a region chosen, covering the south of
Danmark and the north of Germany (that's currently enough for me,
but I could also choose the world, which has a size of 15GB today).

By clicking on “Get Map” a binary map of the section is downloaded.


I renamed the file to osm_soutdk_sh.bin an put it on the Raspberry Pi in
the navit folder “maps”.

Size of my chosen map is 356MB, which is pretty small in size for such a
big area with really(!) up-to-date map data right from yesterday!
pi@gpsraspberrypi ~ $ ls -alh --color=auto ~/navit/maps/insgesamt 360M

drwxr-xr-x 3 pi pi 4,0K Aug 14 16:32 .


drwxr-xr-x 16 pi pi 4,0K Aug 14 17:42 ..
drwxr-xr-x 3 pi pi 4,0K Aug 14 12:15 CMakeFiles
-rw-r--r-- 1 pi pi 1,2K Aug 14 12:15 cmake_install.cmake
-rw-r--r-- 1 pi pi 6,8K Aug 14 12:15 Makefile
-rw-r--r-- 1 pi pi 1,2M Aug 14 12:45 osm_bbox_11.3,47.9,11.7,48.2.bin
-rw-r--r-- 1 pi pi 2,0M Aug 14 12:44 osm_bbox_11.3,47.9,11.7,48.2.osm.bz2
-rw-r--r-- 1 pi pi 84 Aug 14 12:45 osm_bbox_11.3,47.9,11.7,48.2.xml
-rw-r--r-- 1 pi pi 356M Aug 13 23:54 osm_soutdk_sh.bin

Finally some sections inside the navit.xml has to be updated, to point to


the new map. Just edit the navit.xml by using an editor of your choice with
the following changes.

Find the section with “<map type=“binfile” […]” and modify to your needs:

<!-- Mapset template for openstreetmaps -->


<mapset enabled="yes">
<map type="binfile" enabled="no" data="/media/mmc2/MapsNavit/osm_europe.bin"/>
<map type="binfile" enabled="yes" data="/home/pi/navit/maps/osm_soutdk_sh.bin"/>
</mapset>

Set all other mapsets to “no”, to ensure, that only the new OSM-map is loaded an
used:

<mapset enabled="no">
[...]

That's it :-).

Run navit
--------------
If all former steps are done, navit could be started.
There are two options, one is running on local X-session and another is by
using the ssh connection from another linux (or system running an X-server).

Just connect the RaspberryPi with ssh by forwarding X (param -X) and
skipping forwarding to X11 SECURITY extension controls (param -Y):

ssh -X -Y [email protected]

Change into navit folder an run navit:

cd navit
./navit

==============================================================
AZARTICOLO:Navigating with Navit on the Raspberry Pi
==============================================================

Mark Williams

navit running on a Raspberry Pi

Navit is an open source navigation system with GPS tracking.


It works great with a Raspberry Pi, a GPS module and a small TFT with touch, jut
like the
official Raspberry Pi Display or PiScreen.

In this guide, we will be using;

A Raspberry PI 3
The official Raspberry Pi Display
BerryGPS-IMU
SmartPi Touch

Setting up the GPS


----------------

Navit can be installed without a GPS connected to your Raspberry Pi, but you will
not be able to
use the real-time turn by turn navigation. You will however be able to browse maps.
If you are
not going to use a GPS, you can skip to the next step.

As we are using the BerryGPS-IMU, we will be following the guide in the link below.
As most GPS modules use serial to communication, this guide can be followed for
other GPS modules.

BerryGPS Setup Guide for the Raspberry Pi

The images below shows how we have connected the BerryGPS-IMU to the Raspberry Pi 3
whilst it is in the SmartPi Touch case.

Raspberry Pi Navit GPS

Raspberry Pi Navit GPS

If you plan on testing this out in your car, you need to be mindfully of where you
place your BerryGPS. In my setup and I have placed it in the air vent as shown
below, and BerryGPS gets a good strong signal.

Raspberry Pi GPS

If you are using an external antenna, then there is no need to worry about where
your BerryGPS is placed.

navit-gif
Navit

Apply any updates;


pi@raspberrypi ~/ $ apt-get update
pi@raspberrypi ~/ $ apt-get upgrade

Install Navit;
pi@raspberrypi ~/ $ apt-get install navit espeak

We will copy the default Navit config folder under the home directory.
pi@raspberrypi ~/navit-build $ mkdir ~/.navit
pi@raspberrypi ~/navit-build $ cp /etc/navit/navit.xml .navit/navit.xml

You can now run Navit;


pi@raspberrypi ~/navit-build $ navit
If there is no GPS signal, Navit will default to Munich as shown below. If you
have a GPS signal, you will most likely have a blank screen as Navit has moved to
the coordinates from your GPS and there is no map install for that location
(yet).Navit Map

Download Maps

Navit can use Garmin or OpenStreetMaps(OSM). In this guide we are using OSM.

Go to http://maps9.navit-project.org/ and download your map.

The file will be named something silimiar to this; osm_bbox_151.1,-33.9,151.3,-


33.7.bin
We will rename it so it is easier to read. And place it under /home/pi/maps
pi@raspberrypi ~/ $ mv osm_bbox_151.1,-33.9,151.3,-33.7.bin sydney.bin
pi@raspberrypi ~/ $ mkdir ~/maps
pi@raspberrypi ~/ $ mv sydney.bin maps/

The Navit config file needs to be edited to include the new map. While we are there
we will also disable the sample map that came with the source.
pi@raspberrypi ~/ $ vi ~/.navit/navit.xml

To disable the sample map, look for;

<!-- If you dont want to use the sample map, either set enabled="no" in the next
line or remove the xml file from the maps directory -->
<mapset enabled="yes">
<xi:include href="$NAVIT_SHAREDIR/maps/*.xml"/>
</mapset>

And changed enabled to “no”

<!-- If you dont want to use the sample map, either set enabled="no" in the next
line or remove the xml file from the maps directory -->
<mapset enabled="no">
<xi:include href="$NAVIT_SHAREDIR/maps/*.xml"/>
</mapset>

To enable the map which was just downloaded, look for;

<!-- Mapset template for openstreetmaps -->


<mapset enabled="no">

<map type="binfile" enabled="yes" data="/media/mmc2/MapsNavit/osm_europe.bin"/>


</mapset>

And set it to enabled and specify the location of the bin file which was just
downloaded. And set enabled to yes.

<!-- Mapset template for openstreetmaps -->


<mapset enabled="yes">

<map type="binfile" enabled="yes" data="/home/pi/maps/sydney.bin"/>


</mapset>
BerryGPS Raspberry Pi GPS
Enable Speech

Navit can also read out the directions when navigating.


Look for;

<speech type="cmdline" data="echo 'Fix the speech tag in navit.xml to let navit
say:' '%s'" cps="15"/>

and change it to;

<speech type="cmdline" data="espeak '%s'" cps="15"/>


Change Locale

The default locale is set to United Kingdom/English. Which means that the default
country when searching for an address will be United Kingdom.
If you are not in the United Kingdom, then it is best to change this.
In navit.xml, look for

<config xmlns:xi="http://www.w3.org/2001/XInclude">

And change it to your specific locale;

<config xmlns:xi="http://www.w3.org/2001/XInclude" language="en_AU">

As I am in Australia, I have set it to en_AU. Now when I search for an address the
default country is Australia.

Some other examples are;


language=”en_US”
language=”fr_FR”,
language=”de_FR”,
language=”pl_PL”

Open Full Screen

To force Navit to open in full screen, look for;

<gui type="internal" enabled="yes"><![CDATA[

and change it to

<gui type="internal" enabled="yes" fullscreen="1"><![CDATA[


Follow Vehicle

When using Navit in navigation mode, we want the screen to update as the vehicle
moves.
By default, the screen will only update once the vehicle reaches the edge of the
screen.

<vehicle name="Local GPS" profilename="car" enabled="yes" active="1"


source="gpsd://localhost" gpsd_query="w+xj">

and change it to

<vehicle name="Local GPS" profilename="car" enabled="yes" active="1"


source="gpsd://localhost" gpsd_query="w+xj" follow="2">

A value of 2 would refresh the screen every two seconds.

Customise Navit
-------------

With the default config file, Navit is hard to use with a touchscreen, an example
of this is
in the screenshot with Munich above.

One of the good features of Navit is that it almost everything is configurable.


We want to add some buttons and some routing information like next instruction,
distance,
speed, etc.. And hopefully it will look like the below screenshot

navit0

The config for Navit is found in ~/.navit/navit.xml


We will edit this file so that the display looks as shown above. You will also need
to download the customs icons.

Download the configs needed for navit.xml


If you are using the Raspberry Pi official display, download this config file or
use wget;
pi@raspberrypi ~/ $ wget ozzmaker.com/downloads/navit-OSD-800-480.txt

If you are using a 3.5″ TFT, like PiScreen or PiTFT, download this config file or
use wget;
pi@raspberrypi ~/ $ wget ozzmaker.com/downloads/navit-OSD-480-320.txt

Then download the icons;


pi@raspberrypi ~/ $ wget ozzmaker.com/downloads/navit_icons.zip

Extract the icons from the zip file into the directory where Navit stores icon
images;
pi@raspberrypi ~/ $ unzip navit_icons.zip -d /usr/share/navit/icons/

No we will added the config from the downloaded text file to the Navit config file.
Open the config file;
pi@raspberrypi ~/ $ vi ~/.navit/navit.xml

Insert the new config in just before the lines below;

<!-- for a debug log -->


<log enabled="no" type="textfile_debug" data="debug_%Y%m%d-%i.txt"
flush_size="1000" flush_time="30"/>

The next time you start Navit, it should look as shown in the above screenshot.
Other Useful Navit Modifications
Width & Height
To specify the width and height of the Navit window, look for this

<graphics type="gtk_drawing_area"/>

And change it to something like this;

<graphics type="gtk_drawing_area" w="600" h="400"/>

Disable Points of Interest


To permanently disable points of interest, look for;

<layer name="POI Symbols">

And disable it as shown;

<layer name="POI Symbols" enabled="no">

=================================================================================
https://github.com/lucadentella/raspberry-dgc.git
=================================================================================

Installation floppy_disk

0. Upgrade the raspbian distribution

sudo apt update


sudo apt upgrade
sudo reboot

1. Enable the Pi Camera

sudo raspi-config

2. Install Python libraries

sudo apt-get install python3-opencv libzbar0 libzbar-dev


sudo apt-get install libqt4-test python3-sip python3-pyqt5 libqtgui4 libjasper-dev
libatlas-base-dev
pip3 install opencv-contrib-python zbarlight

3. Clone the Github repository

sudo git clone https://github.com/lucadentella/raspberry-dgc

4. Install NodeJS libraries

cd validatorServer
npm install

5. Run the applications

cd validatorServer
node app.js

cd cameraClient
python3 cameraClient.py
--------------------------------------------------------------------------------
USB Auto mount - Raspbian Stretch Lite [Solved]
--------------------------------------------------------------------------------

/dev/sdb1: LABEL="CHIAVETTA" UUID="94FE-3F9E" TYPE="vfat" PARTUUID="5203f89a-01"

Hi all,

I have a Raspberry PI 2 running the newest version of Raspbian Stretch Lite in


Command Line environment.
Out of the box my external USB hard/flash drives are not auto-mounted when plugged
into the Raspberry Pi.

The ultimate goal is to have any USB drive to auto-mounting when plugged into the
Raspberry PI 2.
If it is not possible to achieve this for all drives, then as a worst case scenario
I would be ok to
auto-mount specific HDDs by specifying their UUIDs.

I have been looking into this for hours, but I could not find a solid and simple
solution online.
I would truly appreciate if someone could please post a working solution in here.
Moreover, below you can see the output of my sudo blkid.
In this case I want the USB hdd assigned to /dev/sda1 tblk0: PTUUID="896c5641"
PTTYPE="dos"
/dev/sda1: UUID="93ddc2e0-48e1-457c-9d59-f6a34596e6e1" TYPE="ext4" PARTLABEL="SSD-
120GB" PARTUUID="9eea6391-2399-4983-889c-d5a651c73952"

PS I find it very inconvenient that such functionality is not built into Raspbian
out of the box for the
Command Line environment (I know that auto-mount works when in desktop
environment).

Thank you!

man fstab
man mount
then
Code: Select all

cat /etc/fstab

Taking your current /dev/sda1 as an example, you'd do something like this:


Create a mount point:
Code: Select all

sudo mkdir /media/SSD-120GB


Backup your existing /etc/fstab e.g.:
Code: Select all

sudoi cp /etc/fstab /etc/fstab.bak


Open /etc/fstab in your favourite text editor e.g.:
Code: Select all

sudo nano /etc/fstab


Add a line similar to this, tweaking mount options and mount point as required:
Code: Select all
UUID=93ddc2e0-48e1-457c-9d59-f6a34596e6e1 /media/SSD-120GB ext4 defaults,nofail 0 0
Use UUID rather than the device node (/dev/sda1) as the device node can change
across reboots especially if drives are added or removed.
Include "nofail" in the mount options to prevent the Pi hanging if it is booted
without the drive attached.
Save and close /etc/fstab
Connect the HDD and reboot
Repeat for as many drives/partitions as you need but be aware that they each need
their own mount point.

The above method won't automount if you hot plug a drive but the easy way around
that is either
Code: Select all

sudo mount /path/to/mount-point


or
Code: Select all

sudo mount -a
It might be possible to mount a hot plugged drive with systemd and/or udev but I'
don't know enough to help you with that. Disconnecting a USB drive without first
unmounting it is definitely not a good idea.

Edit:
A quick google for "udev mount" returned this:
https://www.axllent.org/docs/view/auto- ... b-storage/ No idea if it actually wokrs
though.
I'm a volunteer. Take me for granted or abuse my support and I will walk away

All advice given is based on my experience. it worked for me, it may not work for
you.
Need help? https://github.com/thagrol/Guides
reinis
Posts: 5
Joined: Fri Mar 11, 2016 12:34 pm
Re: USB HDD Auto Mount - Raspbian Stretch
Sat Feb 10, 2018 6:45 am

Thanks a lot for the input. The problem is that I tried fstab 10x times but it did
not work for me. I tried it with UUID and LABEL - still would not mount the drive
on boot. It returns exit code error 32. A quick google search show why - it seems
that raspberry pi 2 simply does not manage to detect the usb drive before fstab is
executed. You can read about it [ur=viewtopic.php?f=28&t=99491l]here[/url] and
here.

The good news is that I found a very simple alternative (at least in terms of
installation, not sure about how "native" the solution is) - a package called
usbmount. I can confirm that with usbmount I can auto-mount on boot and hot-plug
any USB device in Raspbian Stretch Lite on my Raspberry Pi 2!

Installation steps of usbmount:

1. Install the package:


Code: Select all

sudo apt-get install usbmount


2. Make sure it works in Stretch by changing MountFlags=slave to MountFlags=shared
here:
Code: Select all

sudo nano /lib/systemd/system/systemd-udevd.service


3. Reboot and it works!

Best,
Reinis
spectre-nz
Posts: 2
Joined: Sat Nov 25, 2017 9:43 am
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Sat Apr 07, 2018 4:22 am

Great thanks!
Worked for me on a Pi 3 Model B+ after it stopped recognising USB drives.
yuvarajoo
Posts: 2
Joined: Sat Apr 28, 2018 12:35 pm
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Sun Apr 29, 2018 6:22 am

Thanks. It solved for me as well... :D


Anyway maybe anyone have native solution can advise as well...
donbrew
Posts: 85
Joined: Sun Sep 04, 2016 2:32 pm
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Sun Jun 17, 2018 8:56 pm

The problem with using fstab is it won't boot if the drive is not plugged in first.
The system gets stuck looking for it.

My bet is you forgot the 0 0 at the end of the fstab line.

usbmount seems to be the native fix on Lite. A lot of packages need to be


installed, like samba, nfs, ntfs-3g etc.
User avatarthagrol
Posts: 6363
Joined: Fri Jan 13, 2012 4:41 pm
Location: Darkest Somerset, UK
Contact: Website
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Sun Jun 17, 2018 10:22 pm

donbrew wrote: ↑
Sun Jun 17, 2018 8:56 pm
The problem with using fstab is it won't boot if the drive is not plugged in first.
The system gets stuck looking for it.
There's an easy fix for that: add "nofail" to the mount options in your fstab
entry.
I'm a volunteer. Take me for granted or abuse my support and I will walk away

All advice given is based on my experience. it worked for me, it may not work for
you.
Need help? https://github.com/thagrol/Guides
DaveL17
Posts: 1
Joined: Sat Jan 26, 2019 7:44 pm
Re: USB HDD Auto Mount - Raspbian Stretch
Sat Jan 26, 2019 7:50 pm

thagrol wrote: ↑
Sat Feb 10, 2018 12:11 am
[*]Backup your existing /etc/fstab e.g.:
Code: Select all

sudoi cp /etc/fstab /etc/fstab.bak


Small typo in the instructions above. `sudoi` should be `sudo`.

Cheers,
Dave
lekso
Posts: 1
Joined: Wed Mar 20, 2019 11:20 pm
Re: USB HDD Auto Mount - Raspbian Stretch
Wed Mar 20, 2019 11:29 pm

reinis wrote: ↑
Sat Feb 10, 2018 6:45 am
Thanks a lot for the input. The problem is that I tried fstab 10x times but it did
not work for me. I tried it with UUID and LABEL - still would not mount the drive
on boot. It returns exit code error 32. A quick google search show why - it seems
that raspberry pi 2 simply does not manage to detect the usb drive before fstab is
executed. You can read about it [ur=viewtopic.php?f=28&t=99491l]here[/url] and
here.

The good news is that I found a very simple alternative (at least in terms of
installation, not sure about how "native" the solution is) - a package called
usbmount. I can confirm that with usbmount I can auto-mount on boot and hot-plug
any USB device in Raspbian Stretch Lite on my Raspberry Pi 2!

Installation steps of usbmount:

1. Install the package:


Code: Select all

sudo apt-get install usbmount


2. Make sure it works in Stretch by changing MountFlags=slave to MountFlags=shared
here:
Code: Select all

sudo nano /lib/systemd/system/systemd-udevd.service


3. Reboot and it works!

Best,
Reinis
This solution not only solved my usb self-loading issues, but also the automatic
start of my VNC server. Thank you!
Oh!Lee
Posts: 14
Joined: Fri Jun 10, 2016 8:58 am
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Thu Mar 21, 2019 9:17 am

spectre-nz wrote: ↑
Sat Apr 07, 2018 4:22 am
Great thanks!
Worked for me on a Pi 3 Model B+ after it stopped recognising USB drives.
Does NOT work for me on my Pi 3 Model B+ :?
followed the instructions, but when I want to copy a file
the error occurs "cp: cannot create regular file '/media/usb/test.bla': Permission
denied".

Any idea?
Oh!Lee
Posts: 14
Joined: Fri Jun 10, 2016 8:58 am
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Fri Mar 22, 2019 1:26 pm

Problem indentified:
On my systemin /etc/usbmount/usbmount.conf the variable FS_MOUNTOPTIONS was not
set.

I changed it to
FS_MOUNTOPTIONS="-fstype=vfat,gid=users,dmask=0007,fmask=0117"
and it works perfectly now!
Beric_
Posts: 10
Joined: Mon May 29, 2017 7:14 am
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Thu Jun 13, 2019 7:54 am

Hello,

Im having the same problem. I just install a new image of Raspian Strech. These are
the steps that I followed:
Code: Select all

sudo apt-get update

sudo apt-get install usbmount

apt-get install 3g ntfs

sudo nano /lib/systemd/system/systemd-udevd.service

MountFlags=slave to MountFlags=shared
In this point, doesnt work. I followed the instructions of this post and try this:
Code: Select all

FS_MOUNTOPTIONS="-fstype=vfat,gid=users,dmask=0007,fmask=0117"
And This
Code: Select all

FS_MOUNTOPTIONS="-fstype=auto,gid=users,dmask=0007,fmask=0117"

But stil doesnt work.

How can i active debug to usbmount ? Is there another log hat can help me?

Best regards !
User avatarthagrol
Posts: 6363
Joined: Fri Jan 13, 2012 4:41 pm
Location: Darkest Somerset, UK
Contact: Website
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Thu Jun 13, 2019 11:12 am

Beric_ wrote: ↑
Thu Jun 13, 2019 7:54 am
Code: Select all

apt-get install 3g ntfs


Was that an error in transcription or was that what you actually tried?

As written, it would have failed as 1. it wasn't run as root, 2. you asked it to


install the wrong things, and 3. there are no packages named "3g" or "ntfs"

Try this instead:


Code: Select all

sudo apt-get install ntfs-3g


I'm a volunteer. Take me for granted or abuse my support and I will walk away

All advice given is based on my experience. it worked for me, it may not work for
you.
Need help? https://github.com/thagrol/Guides
Beric_
Posts: 10
Joined: Mon May 29, 2017 7:14 am
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Thu Jun 13, 2019 11:30 am

It was a writing error, i installed ntfs-3g correctly.


Beric_
Posts: 10
Joined: Mon May 29, 2017 7:14 am
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Mon Jun 17, 2019 6:38 am

So, no more help ?


Beric_
Posts: 10
Joined: Mon May 29, 2017 7:14 am
Re: USB Auto mount - Raspbian Stretch Lite [Solved]
Fri Jun 21, 2019 6:44 am

================================================================================
AZARTICOLO:GUIDA RASPBERRY
================================================================================
Computers
Getting started
Raspberry Pi OS
Configuration
The config.txt file
The Linux kernel
Remote access
Introduction to Remote Access
How to Find your IP Address
Setting up an SSH Server
Set up your Local Network
Enabling the Server
Secure Shell from Linux or Mac OS
Secure Shell from Windows 10
Passwordless SSH Access
Checking for Existing SSH Keys
Generate new SSH Keys
Copy your Key to your Raspberry Pi
Adjust Directory Permissions
Using Secure Copy
Copying Files to your Raspberry Pi
Copying Files from your Raspberry Pi
Copying Multiple Files
Copying a Whole Directory
Using rsync
Network File System (NFS)
Setting up a Basic NFS Server
Configuring an NFS Client
A More Complex NFS Server
Troubleshooting
Samba (SMB/CIFS)
Installing Samba Support
Mount a Folder Shared from Windows
Sharing a Folder from your Raspberry Pi
Virtual Network Computing (VNC)
Installing VNC on Raspberry Pi
Enabling the VNC Server
Connecting to your Raspberry Pi
Using Directly Rendered Applications
Creating a Virtual Desktop
Setting up an Apache Web Server
Installing Apache
Test the Web Server
Installing PHP for Apache
Network boot your Raspberry Pi
Client Configuration
Ethernet MAC address
Server Configuration
Using pxetools
Network booting using IPv6
How it works
Test Setup
Debugging
Camera software
Raspberry Pi hardware
Compute Module hardware
Processors
Remote access

Introduction to Remote Access


------------------------------------------------

Sometimes you need to access a Raspberry Pi without connecting it to a monitor.


Perhaps the Raspberry Pi is embedded in something like a robot, or you may want to
view some
information from it from elsewhere. Or perhaps you simply don’t have a spare
monitor!

You can connect to your Raspberry Pi from another machine.


But in order to do so you’ll need to know its IP Address.

Any device connected to a Local Area Network is assigned an IP address.


In order to connect to your Raspberry Pi from another machine using SSH or VNC, you
need to
know the Raspberry Pi’s IP address. This is easy if you have a display connected,
and there are
a number of methods for finding it remotely from another machine on the network.

How to Find your IP Address


-------------------------------------------

It is possible to find the IP address of your Raspberry Pi without connecting to a


screen using
one of the following methods:

NOTE

If you are using a display with your Raspberry Pi and if you boot to the command
line instead of
the desktop, your IP address should be shown in the last few messages before the
login prompt.
Otherwise open a Terminal window and type

hostname -I

which will reveal your Raspberry Pi’s IP address.

Router devices list


----------------------------

In a web browser navigate to your router’s IP address e.g. http://192.168.1.1,


which is usually
printed on a label on your router; this will take you to a control panel.
Then log in using your credentials, which is usually also printed on the router or
sent to you in
the accompanying paperwork.

Browse to the list of connected devices or similar (all routers are different), and
you should see
some devices you recognise. Some devices are detected as PCs, tablets, phones,
printers, etc.
so you should recognise some and rule them out to figure out which is your
Raspberry Pi.
Also note the connection type; if your Raspberry Pi is connected with a wire there
should be
fewer devices to choose from.

Resolving raspberrypi.local with mDNS


-----------------------------------------------------------

On Raspberry Pi OS, multicast DNS is supported out-of-the-box by the Avahi service.

If your device supports mDNS, you can reach your Raspberry Pi by using its hostname
and the
.local suffix. The default hostname on a fresh Raspberry Pi OS install is
raspberrypi,
so by default any Raspberry Pi running Raspberry Pi OS responds to:

ping raspberrypi.local
If the Raspberry Pi is reachable, ping will show its IP address:
PING raspberrypi.local (192.168.1.131): 56 data bytes
64 bytes from 192.168.1.131: icmp_seq=0 ttl=255 time=2.618 ms

If you change the system hostname of the Raspberry Pi (e.g., by editing


/etc/hostname),
Avahi will also change the .local mDNS address.

If you don’t remember the hostname of the Raspberry Pi, but have a system with
Avahi installed,
you can browse all the hosts and services on the LAN with the avahi-browse command.

nmap command

The nmap command (Network Mapper) is a free and open-source tool for network
discovery,
available for Linux, macOS, and Windows.

To install on Linux, install the nmap package e.g. apt install nmap.

To install on macOS or Windows, see the nmap.org download page.

To use nmap to scan the devices on your network, you need to know the subnet you
are connected to.
First find your own IP address, in other words the one of the computer you’re using
to find your
Raspberry Pi’s IP address:

On Linux, type hostname -I into a terminal window

On macOS, go to System Preferences then Network and select your active network
connection
to view the IP address

On Windows, go to the Control Panel, then under Network and Sharing Center, click
View
network connections, select your active network connection and click View status of
this
connection to view the IP address

Now you have the IP address of your computer, you will scan the whole subnet for
other devices.
For example, if your IP address is 192.168.1.5, other devices will be at addresses
like 192.168.1.2,
192.168.1.3, 192.168.1.4, etc. The notation of this subnet range is 192.168.1.0/24
(this covers 192.168.1.0 to 192.168.1.255).

Now use the nmap command with the -sn flag (ping scan) on the whole subnet range.
This may take a few seconds:

nmap -sn 192.168.1.0/24


Ping scan just pings all the IP addresses to see if they respond.
For each device that responds to the ping, the output shows the hostname and IP
address like so:

Starting Nmap 6.40 ( http://nmap.org ) at 2014-03-10 12:46 GMT


Nmap scan report for hpprinter (192.168.1.2)
Host is up (0.00044s latency).
Nmap scan report for Gordons-MBP (192.168.1.4)
Host is up (0.0010s latency).
Nmap scan report for ubuntu (192.168.1.5)
Host is up (0.0010s latency).
Nmap scan report for raspberrypi (192.168.1.8)
Host is up (0.0030s latency).
Nmap done: 256 IP addresses (4 hosts up) scanned in 2.41 seconds

Here you can see a device with hostname raspberrypi has IP address 192.168.1.8.
Note, to see the hostnames, you must run nmap as root by prepending sudo to the
command.

Getting IPv6 addresses by pinging from a second device


First find your own IP address(es), in other words the one of the computer you’re
using to find your Raspberry Pi’s IP address by hostname -I

fd00::ba27:ebff:feb6:f293 2001:db8:494:9d01:ba27:ebff:feb6:f293

The example shows two IP addresses. The first one is a so called unique local
unicast address(fc00::/7). The second one is the global unicast address(2000::/3).
It is also possible to see only one of them depending on your network (router)
configuration. Both addresses are valid for reaching the Raspberry Pi within your
LAN. The address out of 2000::/3 is accessible world wide, provided your router’s
firewall is opened.

Now use one of IPs from the first step to ping all local nodes:

ping -c 2 -I 2001:db8:494:9d01:ba27:ebff:feb6:f293 ff02::1


ping -c 2 -I 2001:db8:494:9d01:ba27:ebff:feb6:f293 ff02::1%eth0
-c 2 stands for sending two echo requests

-I with the IP address, it sets the interface and the source address of the echo
request, it is necessary to choose the interface’s IP address, eth0 isn’t
sufficient - the answer would be the local link address(fe80::/10), we need the
global or local unicast address

ff02::1 is a well known multicast address for all nodes on the link, so it behaves
like a local broadcast,
usually it is defined in /etc/hosts so you can also use the name (ip6-allnodes or
ipv6-allnodes)
instead of the literal address

Some newer systems expect the interface ID behind the multicast address.

ping -c 2 -I 2001:db8:494:9d01:ba27:ebff:feb6:f293 ip6-allnodes


PING ip6-allnodes(ip6-allnodes (ff02::1)) from
2001:db8:494:9d01:ba27:ebff:feb6:f293 : 56 data bytes

64 bytes from 2001:db8:494:9d01:ba27:ebff:feb6:f293: icmp_seq=1 ttl=64 time=0.597


ms
64 bytes from witz.fritz.box (2001:db8:494:9d01:728b:cdff:fe7d:a2e): icmp_seq=1
ttl=255 time=1.05 ms (DUP!)
64 bytes from raspberrypi4.fritz.box (2001:db8:494:9d01:dea6:32ff:fe23:6be1):
icmp_seq=1 ttl=64 time=1.05 ms (DUP!)
64 bytes from 2001:db8:494:9d01:da37:beff:fefd:f09d
(2001:db8:494:9d01:da37:beff:fefd:f09d): icmp_seq=1 ttl=255 time=1.05 ms (DUP!)
64 bytes from fusion.fritz.box (2001:db8:494:9d01:1e6f:65ff:fec9:8746): icmp_seq=1
ttl=255 time=2.12 ms (DUP!)
64 bytes from fritz.box (2001:db8:494:9d01:464e:6dff:fe72:8a08): icmp_seq=1 ttl=64
time=2.62 ms (DUP!)
64 bytes from raspberrypi.fritz.box (2001:db8:494:9d01:ba27:ebff:feb6:f293):
icmp_seq=2 ttl=64 time=0.480 ms

--- ip6-allnodes ping statistics ---


2 packets transmitted, 2 received, +5 duplicates, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.480/1.283/2.623/0.735 ms
This should result in replies from all the nodes on your (W)LAN link, with
associated DNS names.

Exclude your own IP( here 2001:db8:494:9d01:ba27:ebff:feb6:f293 ), then check the


others by trying to connect them via SSH.

ssh pi@2001:db8:494:9d01:dea6:32ff:fe23:6be1
The authenticity of host '2001:db8:494:9d01:dea6:32ff:fe23:6be1
(2001:db8:494:9d01:dea6:32ff:fe23:6be1)' can't be established.
ECDSA key fingerprint is SHA256:DAW68oen42TdWDyrOycDZ1+y5ZV5D81kaVoi5FnpvoM.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '2001:db8:494:9d01:dea6:32ff:fe23:6be1' (ECDSA) to the
list of known hosts.
pi@2001:db8:494:9d01:dea6:32ff:fe23:6be1's password:
Linux raspberrypi4 4.19.75-v7l+ #1270 SMP Tue Sep 24 18:51:41 BST 2019 armv7l

...

pi@raspberrypi4:~ $

Getting the IP address of a Raspberry Pi using your smartphone


-----------------------------------------------------------------------------------
---------------

The Fing app is a free network scanner for smartphones. It is available for Android
and iOS.

Your phone and your Raspberry Pi have to be on the same network, so connect your
phone to
the correct wireless network.

When you open the Fing app, touch the refresh button in the upper right-hand corner
of the screen.
After a few seconds you will get a list with all the devices connected to your
network.
Scroll down to the entry with the manufacturer "Raspberry Pi".
You will see the IP address in the bottom left-hand corner, and the MAC address in
the bottom
right-hand corner of the entry.

Network File System (NFS)


-----------------------------------------

Edit this on GitHub

Network File System (NFS) allows you to share a directory located on one networked
computer with other computers or devices on the same network. The computer where
the directory is located is called the server, and computers or devices connecting
to that server are called clients. Clients usually mount the shared directory to
make it a part of their own directory structure. The shared directory is an example
of a shared resource or network share.

For smaller networks, an NFS is perfect for creating a simple NAS (Network-attached
storage) in a Linux/Unix environment.

An NFS is perhaps best suited to more permanent network-mounted directories, such


as /home directories or regularly-accessed shared resources. If you want a network
share that guest users can easily connect to, Samba is better suited to the task.
This is because tools to temporarily mount and detach from Samba shares are more
readily available across old and proprietary operating systems.

Before deploying an NFS, you should be familiar with:

Linux file and directory permissions

mounting and unmounting filesystems

Setting up a Basic NFS Server


Install the packages required using the command below:

sudo apt install nfs-kernel-server


For easier maintenance, we will isolate all NFS exports in single directory, into
which the real directories will be mounted with the --bind option.

Suppose we want to export our users' home directories, which are in /home/users.
First we create the export filesystem:

sudo mkdir -p /export/users


Note that /export and /export/users will need 777 permissions, as we will be
accessing the NFS share from the client without LDAP/NIS authentication. This will
not apply if using authentication (see below). Now mount the real users directory
with:

sudo mount --bind /home/users /export/users


To save us from retyping this after every reboot, we add the following line to
/etc/fstab:

/home/users /export/users none bind 0 0


There are three configuration files that relate to an NFS server:

/etc/default/nfs-kernel-server

/etc/default/nfs-common

/etc/exports

The only important option in /etc/default/nfs-kernel-server for now is


NEED_SVCGSSD. It is set to "no" by default, which is fine, because we are not
activating NFSv4 security this time.

In order for the ID names to be automatically mapped, the file /etc/idmapd.conf


must exist on both the client and the server with the same contents and with the
correct domain names. Furthermore, this file should have the following lines in the
Mapping section:

[Mapping]

Nobody-User = nobody
Nobody-Group = nogroup
However, note that the client may have different requirements for the Nobody-User
and Nobody-Group. For example, on RedHat variants, it is nfsnobody for both. If
you’re not sure, check via the following commands to see if nobody and nogroup are
there:

cat /etc/passwd
cat /etc/group
This way, server and client do not need the users to share same UID/GUID. For those
who use LDAP-based authentication, add the following lines to the idmapd.conf of
your clients:

[Translation]

Method = nsswitch
This will cause idmapd to know to look at nsswitch.conf to determine where it
should look for credential information. If you have LDAP authentication already
working, nsswitch shouldn’t require further explanation.

To export our directories to a local network 192.168.1.0/24, we add the following


two lines to /etc/exports:

/export 192.168.1.0/24(rw,fsid=0,insecure,no_subtree_check,async)
/export/users 192.168.1.0/24(rw,nohide,insecure,no_subtree_check,async)
Portmap lockdown (optional)
The files on your NFS are open to anyone on the network. As a security measure, you
can restrict access to specified clients.

Add the following line to /etc/hosts.deny:

rpcbind mountd nfsd statd lockd rquotad : ALL


By blocking all clients first, only clients in /etc/hosts.allow (added below) will
be allowed to access the server.

Now add the following line to /etc/hosts.allow:

rpcbind mountd nfsd statd lockd rquotad : <list of IPv4s>


where <list of IPv4s> is a list of the IP addresses of the server and all clients.
(These have to be IP addresses because of a limitation in rpcbind, which doesn’t
like hostnames.) Note that if you have NIS set up, you can just add these to the
same line.

Please ensure that the list of authorised IP addresses includes the localhost
address (127.0.0.1), as the startup scripts in recent versions of Ubuntu use the
rpcinfo command to discover NFSv3 support, and this will be disabled if localhost
is unable to connect.

Finally, to make your changes take effect, restart the service:

sudo systemctl restart nfs-kernel-server


Configuring an NFS Client
Now that your server is running, you need to set up any clients to be able to
access it. To start, install the required packages:

sudo apt install nfs-common


On the client, we can mount the complete export tree with one command:

mount -t nfs -o proto=tcp,port=2049 <nfs-server-IP>:/ /mnt


You can also specify the NFS server hostname instead of its IP address, but in this
case you need to ensure that the hostname can be resolved to an IP on the client
side. A robust way of ensuring that this will always resolve is to use the
/etc/hosts file.
Note that <nfs-server-IP>:/export is not necessary in NFSv4, as it was in NFSv3.
The root export :/ defaults to export with fsid=0.

We can also mount an exported subtree with:

mount -t nfs -o proto=tcp,port=2049 <nfs-server-IP>:/users /home/users


To ensure this is mounted on every reboot, add the following line to /etc/fstab:

<nfs-server-IP>:/ /mnt nfs auto 0 0


If, after mounting, the entry in /proc/mounts appears as <nfs-server-IP>:// (with
two slashes), then you might need to specify two slashes in /etc/fstab, or else
umount might complain that it cannot find the mount.

Portmap lockdown (optional)


Add the following line to /etc/hosts.deny:

rpcbind : ALL
By blocking all clients first, only clients in /etc/hosts.allow (added below) will
be allowed to access the server.

Now add the following line to /etc/hosts.allow:

rpcbind : <NFS server IP address>


where <NFS server IP address> is the IP address of the server.

A More Complex NFS Server


NFS user permissions are based on user ID (UID). UIDs of any users on the client
must match those on the server in order for the users to have access. The typical
ways of doing this are:

Manual password file synchronisation

Use of LDAP

Use of DNS

Use of NIS

Note that you have to be careful on systems where the main user has root access:
that user can change UIDs on the system to allow themselves access to anyone’s
files. This page assumes that the administrative team is the only group with root
access and that they are all trusted. Anything else represents a more advanced
configuration, and will not be addressed here.

Group permissions
A user’s file access is determined by their membership of groups on the client, not
on the server. However, there is an important limitation: a maximum of 16 groups
are passed from the client to the server, and if a user is member of more than 16
groups on the client, some files or directories might be unexpectedly inaccessible.

DNS (optional, only if using DNS)


Add any client name and IP addresses to /etc/hosts. (The IP address of the server
should already be there.) This ensures that NFS will still work even if DNS goes
down. Alternatively you can rely on DNS if you want - it’s up to you.

NIS (optional, only if using NIS)


This applies to clients using NIS. Otherwise you can’t use netgroups, and should
specify individual IPs or hostnames in /etc/exports. Read the BUGS section in man
netgroup for more information.
First, edit /etc/netgroup and add a line to classify your clients (this step is not
necessary, but is for convenience):

myclients (client1,,) (client2,,) ...


where myclients is the netgroup name.

Next run this command to rebuild the NIS database:

sudo make -C /var/yp


The filename yp refers to Yellow Pages, the former name of NIS.

Portmap lockdown (optional)


Add the following line to /etc/hosts.deny:

rpcbind mountd nfsd statd lockd rquotad : ALL


By blocking all clients first, only clients in /etc/hosts.allow (added below) will
be allowed to access the server.

Consider adding the following line to /etc/hosts.allow:

rpcbind mountd nfsd statd lockd rquotad : <list of IPs>


where <list of IPs> is a list of the IP addresses of the server and all clients.
These have to be IP addresses because of a limitation in rpcbind. Note that if you
have NIS set up, you can just add these to the same line.

Package installation and configuration


Install the necessary packages:

sudo apt install rpcbind nfs-kernel-server


Edit /etc/exports and add the shares:

/home @myclients(rw,sync,no_subtree_check)
/usr/local @myclients(rw,sync,no_subtree_check)
The example above shares /home and /usr/local to all clients in the myclients
netgroup.

/home 192.168.0.10(rw,sync,no_subtree_check) 192.168.0.11(rw,sync,no_subtree_check)


/usr/local 192.168.0.10(rw,sync,no_subtree_check)
192.168.0.11(rw,sync,no_subtree_check)
The example above shares /home and /usr/local to two clients with static IP
addresses. If you want instead to allow access to all clients in the private
network falling within a designated IP address range, consider the following:

/home 192.168.0.0/255.255.255.0(rw,sync,no_subtree_check)
/usr/local 192.168.0.0/255.255.255.0(rw,sync,no_subtree_check)
Here, rw makes the share read/write, and sync requires the server to only reply to
requests once any changes have been flushed to disk. This is the safest option;
async is faster, but dangerous. It is strongly recommended that you read man
exports if you are considering other options.

After setting up /etc/exports, export the shares:

sudo exportfs -ra


You’ll want to run this command whenever /etc/exports is modified.

Restart services
By default, rpcbind only binds to the loopback interface. To enable access to
rpcbind from remote machines, you need to change /etc/conf.d/rpcbind to get rid of
either -l or -i 127.0.0.1.

If any changes are made, rpcbind and NFS will need to be restarted:

sudo systemctl restart rpcbind


sudo systemctl restart nfs-kernel-server
Security items to consider
Aside from the UID issues discussed above, it should be noted that an attacker
could potentially masquerade as a machine that is allowed to map the share, which
allows them to create arbitrary UIDs to access your files. One potential solution
to this is IPSec. You can set up all your domain members to talk to each other only
over IPSec, which will effectively authenticate that your client is who it says it
is.

IPSec works by encrypting traffic to the server with the server’s public key, and
the server sends back all replies encrypted with the client’s public key. The
traffic is decrypted with the respective private keys. If the client doesn’t have
the keys that it is supposed to have, it can’t send or receive data.

An alternative to IPSec is physically separate networks. This requires a separate


network switch and separate Ethernet cards, and physical security of that network.

Troubleshooting
Mounting an NFS share inside an encrypted home directory will only work after you
are successfully logged in and your home is decrypted. This means that using
/etc/fstab to mount NFS shares on boot will not work, because your home has not
been decrypted at the time of mounting. There is a simple way around this using
symbolic links:

Create an alternative directory to mount the NFS shares in:

sudo mkdir /nfs


sudo mkdir /nfs/music
Edit /etc/fstab to mount the NFS share into that directory instead:

nfsServer:music /nfs/music nfs auto 0 0


Create a symbolic link inside your home, pointing to the actual mount location. For
example, and in this case deleting the Music directory already existing there
first:

rmdir /home/user/Music
ln -s /nfs/music/ /home/user/Music

Samba (SMB/CIFS)
----------------------------

Edit this on GitHub

Samba is an implementation of the SMB/CIFS networking protocol that is used by


Microsoft Windows devices to provide shared access to files, printers, and serial
ports.

You can use Samba to mount a folder shared from a Windows machine so it appears on
your Raspberry Pi, or to share a folder from your Raspberry Pi so it can be
accessed by your Windows machine.

Installing Samba Support


By default, Raspberry Pi OS does not include CIFS/Samba support, but this can be
added. The following commands will install all the required components for using
Samba as a server or a client.

sudo apt update


sudo apt install samba samba-common-bin smbclient cifs-utils
Mount a Folder Shared from Windows
First, you need to share a folder on your Windows device. This is quite a
convoluted process!

Turn on sharing
Open the Networking and Sharing Centre by right-clicking on the system tray and
selecting it

Click on Change advanced sharing settings

Select Turn on network discovery

Select Turn on file and printer sharing

Save changes

Share the folder


You can share any folder you want, but for this example, simply create a folder
called share.

Create the folder share on your desktop.

Right-click on the new folder, and select Properties.

Click on the Sharing tab, and then the Advanced Sharing button

Select Share this folder; by default, the share name is the name of the folder

Click on the Permissions button

For this example, select Everyone and Full Control (you can limit access to
specific users if required); click OK when done, then OK again to leave the
Advanced Sharing page

Click on the Security tab, as we now need to configure the same permissions

Select the same settings as the Permissions tab, adding the chosen user if
necessary

Click OK

The folder should now be shared.

Windows 10 Sharing Wizard


On Windows 10 there is a Sharing Wizard that helps with some of these steps.

Run the Computer Management application from the Start Bar

Select Shared Folders, then Shares

Right-click and select New Share, which will start up the Sharing Wizard; click
Next

Select the folder you wish to share, and click Next


Click Next to use all the sharing defaults

Select Custom and set the required permissions, and click OK, then Finish

Mount the folder on the Raspberry Pi


Mounting in Linux is the process of attaching a folder to a location, so firstly we
need that location.

mkdir windowshare
Now, we need to mount the remote folder to that location. The remote folder is the
host name or IP address of the Windows PC, and the share name used when sharing it.
We also need to provide the Windows username that will be used to access the remote
machine.

sudo mount.cifs //<hostname or IP address>/share /home/pi/windowshare -o


user=<name>
You should now be able to view the content of the Windows share on your Raspberry
Pi.

cd windowshare
ls
"Host is down" error
This error is caused by a combination of two things: A SMB protocol version
mismatch, and the CIFS client on Linux returning a misleading error message. In
order to fix this a version entry needs to be added to the mount command. By
default Raspberry Pi OS will only use versions 2.1 and above, which are compatible
with Windows 7 and later. Older devices, including some NAS, may require version
1.0:

sudo mount.cifs //IP/share /mnt/point -o user=<uname>,vers=1.0


You may need to try different versions to match up with the server version.
Possible values are:

Version Description
1.0

Classic CIFS/SMBv1 protocol

2.0

The SMBv2.002 protocol. Windows Vista Service Pack 1, and Windows Server 2008

2.1

The SMBv2.1 protocol. Microsoft Windows 7 and Windows Server 2008R2

3.0

The SMBv3.0 protocol. Microsoft Windows 8 and Windows Server 2012

3.02

The SMBv3.0.2 protocol. Microsoft Windows 8.1 and Windows Server 2012R2

3.11

The SMBv3.1.1 protocol. Microsoft Windows 10 and Windows Server 2016

3
The SMBv3.0 protocol version and above

Sharing a Folder from your Raspberry Pi


Firstly, create a folder to share. This example creates a folder called shared in
the home folder of the current user, and assumes the current user is pi.

cd ~
mkdir shared
chmod 0740 shared
Now we need to tell Samba that there is a pi user when accessing that folder. When
asked, enter the password of the pi user - this can be the default password, but
that is well known and should be changed for better security.

sudo smbpasswd -a pi
Now we need to tell Samba to share this folder, using the Samba configuration file.

sudo nano /etc/samba/smb.conf


At the end of the file, add the following to share the folder, giving the remote
user read/write permissions:

[share]
path = /home/pi/shared
read only = no
public = yes
writable = yes
In the same file, find the workgroup line, and if necessary, change it to the name
of the workgroup of your local Windows network.

workgroup = <your workgroup name here>


That should be enough to share the folder. On your Windows device, when you browse
the network, the folder should appear and you should be able to connect to it.

Virtual Network Computing (VNC)


---------------------------------------------------
Edit this on GitHub

Sometimes it is not convenient to work directly on the Raspberry Pi.


Maybe you would like to work on it from another device by remote control.

VNC is a graphical desktop sharing system that allows you to remotely control the
desktop interface
of one computer (running VNC Server) from another computer or mobile device
(running VNC Viewer).
VNC Viewer transmits the keyboard and either mouse or touch events to VNC Server,
and receives
updates to the screen in return.

You will see the desktop of the Raspberry Pi inside a window on your computer or
mobile device.
You’ll be able to control it as though you were working on the Raspberry Pi itself.

VNC Connect from RealVNC is included with Raspberry Pi OS. It consists of both VNC
Server,
which allows you to control your Raspberry Pi remotely, and VNC Viewer, which
allows you to
control desktop computers remotely from your Raspberry Pi should you want to.

You must enable VNC Server before you can use it.
By default, VNC Server gives you remote access to the graphical desktop that is
running on
your Raspberry Pi, as though you were sitting in front of it.

However, you can also use VNC Server to gain graphical remote access to your
Raspberry Pi
if it is headless or not running a graphical desktop. For more information on this,
see
Creating a virtual desktop, further below.

Installing VNC on Raspberry Pi


------------------------------------------------

VNC is already installed on the full Raspberry Pi OS image, and can be installed
via Recommended
Software from the Preferences menu on other versions.

If you are not using a desktop you can install it from the command line as follows:

sudo apt update


sudo apt install realvnc-vnc-server realvnc-vnc-viewer
Enabling the VNC Server
You can do this graphically or at the command line.

Enabling VNC Server graphically


---------------------------------------------------

On your Raspberry Pi, boot into the graphical desktop.

Select Menu › Preferences › Raspberry Pi Configuration › Interfaces.

Ensure VNC is Enabled.

Enabling VNC Server at the command line


------------------------------------------------------------------
You can enable VNC Server at the command line using raspi-config:

sudo raspi-config
Now, enable VNC Server by doing the following:

Navigate to Interfacing Options.

Scroll down and select VNC › Yes.

Connecting to your Raspberry Pi


--------------------------------------------------
There are two ways to connect to your Raspberry Pi. You can use either or both,
depending on what works best for you.

Establishing a direct connection


--------------------------------------------------
Direct connections are quick and simple providing you’re joined to the same private
local network
as your Raspberry Pi. For example, this might be a wired or wireless network at
home, at school,
or in the office.

On your Raspberry Pi (using a terminal window or via SSH) use these instructions or
run ifconfig
to discover your private IP address.

On the device you’ll use to take control, download VNC Viewer.


For best results, use the compatible app from RealVNC.

Enter your Raspberry Pi’s private IP address into VNC Viewer:

Establishing a cloud connection


------------------------------------------------

You are entitled to use RealVNC’s cloud service for free, provided that remote
access is for
educational or non-commercial purposes only.

Cloud connections are convenient and encrypted end-to-end.


They are highly recommended for connecting to your Raspberry Pi over the internet.
There’s no firewall or router reconfiguration, and you don’t need to know the IP
address of your
Raspberry Pi, or provide a static one.

Sign up for a RealVNC account here: it’s free and it only takes a few seconds.

On your Raspberry Pi, sign in to VNC Server using your new RealVNC account
credentials:

On the device you’ll use to take control, download VNC Viewer. You must use the
compatible app from RealVNC.

Sign in to VNC Viewer using the same RealVNC account credentials, and then either
tap or click to connect to your Raspberry Pi:

Authenticating to VNC Server


-----------------------------------------------
To complete either a direct or cloud connection, you must authenticate to VNC
Server.

If you’re connecting from the compatible VNC Viewer app from RealVNC, enter the
user name
and password you normally use to log in to your user account on the Raspberry Pi.
By default,
these credentials are pi and raspberry.

If you’re connecting from a non-RealVNC Viewer app, you’ll first need to downgrade
VNC Server’s
authentication scheme, specify a password unique to VNC Server, and then enter
that instead.

If you are in front of your Raspberry Pi and can see its screen, open the VNC
Server dialog on
your Raspberry Pi, select Menu › Options › Security, and choose VNC password from
the
Authentication dropdown.

Or if you’re configuring your Raspberry Pi remotely from the command line, then to
make the
changes for Service Mode (the default configuration for the Raspberry Pi):

Open the /root/.vnc/config.d/vncserver-x11 config file.


Replace Authentication=SystemAuth with Authentication=VncAuth and save the file.

In the command line, run sudo vncpasswd -service.


This will prompt you to set a password, and will insert it for you in the right
config file for
VNC Server running in Service Mode.

Restart VNC Server.


-----------------------------

Using Directly Rendered Applications


You can remotely access apps which use a directly rendered overlay such as; the
text console,
the Raspberry Pi Camera Module, and others.

To turn this feature on:

On your Raspberry Pi, open the VNC Server dialog.

Navigate to Menu › Options › Troubleshooting and select Enable experimental direct


capture mode.

On the device you’ll use to take control, run VNC Viewer and connect.

NOTE
Existing connections must be restarted in order for these changes to take effect.
Please note that direct screen capture is an experimental feature.
If you’re connecting from a desktop computer and mouse movements seem erratic,
try pressing F8 to open the VNC Viewer shortcut menu and selecting Relative Pointer
Motion.

Creating a Virtual Desktop


---------------------------------------

If your Raspberry Pi is headless (i.e. not plugged into a monitor) or controlling a


robot, it is
unlikely to be running a graphical desktop.

VNC Server can create a virtual desktop for you, giving you graphical remote access
on demand.
This virtual desktop exists only in your Raspberry Pi’s memory:

To create and connect to a virtual desktop:

On your Raspberry Pi (using Terminal or via SSH), run vncserver.


Make note of the IP address/display number that VNC Server will print to your
Terminal (e.g. 192.167.5.149:1).

On the device you’ll use to take control, enter this information into VNC Viewer.

To destroy a virtual desktop, run the following command:

vncserver -kill :<display-number>


This will also stop any existing connections to this virtual desktop.

Setting up an Apache Web Server

Edit this on GitHub


Apache is a popular web server application you can install on the Raspberry Pi to
allow it to serve web pages.

On its own, Apache can serve HTML files over HTTP, and with additional modules can
serve dynamic web pages using scripting languages such as PHP.

Installing Apache
First, update the available packages by typing the following command into the
Terminal:

sudo apt update


Then, install the apache2 package with this command:

sudo apt install apache2 -y


Test the Web Server
By default, Apache puts a test HTML file in the web folder. This default web page
is served when you browse to http://localhost/ on the Raspberry Pi itself, or
http://192.168.1.10 (whatever the Raspberry Pi’s IP address is) from another
computer on the network. To find the Raspberry Pi’s IP address, type hostname -I at
the command line (or read more about finding your IP address).

Browse to the default web page either on the Raspberry Pi or from another computer
on the network and you should see the following:

Apache success message


This means you have Apache working!

Changing the Default Web Page


This default web page is just an HTML file on the filesystem. It is located at
/var/www/html/index.html.

Navigate to this directory in a terminal window and have a look at what’s inside:

cd /var/www/html
ls -al
This will show you:

total 12
drwxr-xr-x 2 root root 4096 Jan 8 01:29 .
drwxr-xr-x 12 root root 4096 Jan 8 01:28 ..
-rw-r--r-- 1 root root 177 Jan 8 01:29 index.html
This shows that by default there is one file in /var/www/html/ called index.html
and it is owned by the root user (as is the enclosing folder). In order to edit the
file, you need to change its ownership to your own username. Change the owner of
the file (the default pi user is assumed here) using sudo chown pi: index.html.

You can now try editing this file and then refreshing the browser to see the web
page change. If you know HTML you can put your own HTML files and other assets in
this directory and serve them as a website on your local network.

Installing PHP for Apache


To allow your Apache server to process PHP files, you’ll need to install the latest
version of PHP and the PHP module for Apache. Type the following command to install
these:

sudo apt install php libapache2-mod-php -y


Now remove the index.html file:

sudo rm index.html
and create the file index.php:

sudo nano index.php


Put some PHP content in it:

<?php echo "hello world"; ?>


Now save and refresh your browser. You should see "hello world". This is not
dynamic but still served by PHP. Try something dynamic:

<?php echo date('Y-m-d H:i:s'); ?>


or show your PHP info:

<?php phpinfo(); ?>


Network boot your Raspberry Pi
Edit this on GitHub

You can set up a DHCP/TFTP server which will allow you to boot a Raspberry Pi 3 or
4 from the network.

The instructions assume that you have an existing home network, and that you want
to use a Raspberry Pi for the server. You will also need an additional Raspberry Pi
3 or 4 as a client to be booted. Only one SD Card is needed because the client will
be booted from the server after the initial client configuration.

NOTE
Due to the huge range of networking devices and routers available, we can’t
guarantee that network booting will work with any device. We have had reports that,
if you cannot get network booting to work, disabling STP frames on your network may
help.
Client Configuration
Raspberry Pi 3 Model B
NOTE
This section only applies to the Raspberry Pi 3 Model B, as network boot is enabled
on the Raspberry Pi 3 Model B+ at the factory.
Before the Raspberry Pi 3 Model B will network boot it needs to be booted from an
SD Card with a config option to enable USB boot mode. This will set a bit in the
OTP (One Time Programmable) memory in the Raspberry Pi SoC that enables network
booting. Once this is done, the Raspberry Pi 3B will attempt to boot from USB, and
from the network, if it cannot boot from the SD card.

Install Raspberry Pi OS Lite, or Raspberry Pi OS with desktop, on the SD card in


the usual fashion. Next, enable USB boot mode with the following command:

echo program_usb_boot_mode=1 | sudo tee -a /boot/config.txt


This adds program_usb_boot_mode=1 to the end of /boot/config.txt. Reboot the
Raspberry Pi with sudo reboot. Once the client Raspberry Pi has rebooted, check
that the OTP has been programmed with:

vcgencmd otp_dump | grep 17:


17:3020000a
Ensure the output 0x3020000a is correct.

The client configuration is almost done. The final thing to do is to remove the
program_usb_boot_mode line from config.txt. You can do this with sudo nano
/boot/config.txt, for example. Finally, shut the client Raspberry Pi down with sudo
poweroff.

Raspberry Pi 4 Model B
Network boot can be enabled on the Raspberry Pi 4 using the raspi-config tool.
First, run raspi-config as follows:

sudo raspi-config
Within raspi-config, choose Advanced Options, then Boot Order, then Network Boot.
You must then reboot the device for the change to the boot order to be programmed
into the bootloader EEPROM. Once the Raspberry Pi has rebooted, check that the boot
order is now 0xf21:

vcgencmd bootloader_config
For further details of configuring the Raspberry Pi 4 bootloader, see Raspberry Pi
4 Bootloader Configuration.

Ethernet MAC address


Before configuring network boot, make a note of the serial number and mac address
so that the board can be identified by the TFTP/DHCP server.

On Raspberry Pi 4 the MAC address is programmed at manufacture and there is no link


between the MAC address and serial number. Both the MAC address and serial numbers
are displayed on the bootloader HDMI diagnostics screen.

To find the Ethernet MAC address:

ethtool -P eth0
To find the serial number:

grep Serial /proc/cpuinfo | cut -d ' ' -f 2 | cut -c 8-16


Server Configuration
Plug the SD card into the server Raspberry Pi, and then boot the server. The client
Raspberry Pi will need a root file system to boot from: we will use a copy of the
server’s root filesystem and place it in /nfs/client1:

sudo mkdir -p /nfs/client1


sudo apt install rsync
sudo rsync -xa --progress --exclude /nfs / /nfs/client1
Regenerate SSH host keys on the client filesystem by chrooting into it:

cd /nfs/client1
sudo mount --bind /dev dev
sudo mount --bind /sys sys
sudo mount --bind /proc proc
sudo chroot .
rm /etc/ssh/ssh_host_*
dpkg-reconfigure openssh-server
exit
sudo umount dev sys proc
Find the settings of your local network. You need to find the address of your
router (or gateway), which can be done with:

ip route | awk '/default/ {print $3}'


Then run:

ip -4 addr show dev eth0 | grep inet


which should give an output like:

inet 10.42.0.211/24 brd 10.42.0.255 scope global eth0


The first address is the IP address of your server Raspberry Pi on the network, and
the part after the slash is the network size. It is highly likely that yours will
be a /24. Also note the brd (broadcast) address of the network. Note down the
output of the previous command, which will contain the IP address of the Raspberry
Pi and the broadcast address of the network.

Finally, note down the address of your DNS server, which is the same address as
your gateway. You can find this with:

cat /etc/resolv.conf
Configure a static network address on your server Raspberry Pi via the systemd
networking, which works as the network handler and DHCP server.

To do that, you’ll need to create a 10-eth0.netdev and a 11-eth0.network like so:

sudo nano /etc/systemd/network/10-eth0.netdev


Add the following lines:

[Match]
Name=eth0

[Network]
DHCP=no
Then create a network file:

sudo nano /etc/systemd/network/11-eth0.network


Add the following contents:

[Match]
Name=eth0

[Network]
Address=10.42.0.211/24
DNS=10.42.0.1

[Route]
Gateway=10.42.0.1
At this point, you will not have working DNS, so you will need to add the server
you noted down before to systemd/resolved.conf. In this example, the gateway
address is 10.42.0.1.

sudo nano /etc/systemd/resolved.conf


Uncomment the DNS line and add the DNS IP address there. Additionally, if you have
a fallback DNS server, add it there as well.

[Resolve]
DNS=10.42.0.1
#FallbackDNS=
Enable systemd-networkd and then reboot for the changes to take effect:

sudo systemctl enable systemd-networkd


sudo reboot
Now start tcpdump so you can search for DHCP packets from the client Raspberry Pi:

sudo apt install tcpdump dnsmasq


sudo systemctl enable dnsmasq
sudo tcpdump -i eth0 port bootpc
Connect the client Raspberry Pi to your network and power it on. Check that the
LEDs illuminate on the client after around 10 seconds, then you should get a packet
from the client "DHCP/BOOTP, Request from …"

IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from b8:27:eb...


Now you need to modify the dnsmasq configuration to enable DHCP to reply to the
device. Press CTRL + C to exit the tcpdump program, then type the following:

echo | sudo tee /etc/dnsmasq.conf


sudo nano /etc/dnsmasq.conf
Then replace the contents of dnsmasq.conf with:

# Note: comment out port if you want DNS services for systems on the network.
port=0
dhcp-range=10.42.0.255,proxy
log-dhcp
enable-tftp
tftp-root=/tftpboot
pxe-service=0,"Raspberry Pi Boot"
Where the first address of the dhcp-range line is, use the broadcast address you
noted down earlier.

Now create a /tftpboot directory:

sudo mkdir /tftpboot


sudo chmod 777 /tftpboot
sudo systemctl enable dnsmasq.service
sudo systemctl restart dnsmasq.service
Now monitor the dnsmasq log:

tail -F /var/log/daemon.log
You should see something like this:

raspberrypi dnsmasq-tftp[1903]: file /tftpboot/bootcode.bin not found


Next, you will need to copy the contents of the boot folder into the /tftpboot
directory.

First, press CTRL + C to exit the monitoring state. Then type the following:

cp -r /boot/* /tftpboot
Since the tftp location has changed, restart dnsmasq:

sudo systemctl restart dnsmasq


Set up NFS root
This should now allow your Raspberry Pi client to attempt to boot through until it
tries to load a root file system (which it doesn’t have).

At this point, export the /nfs/client1 file system created earlier, and the TFTP
boot folder.

sudo apt install nfs-kernel-server


echo "/nfs/client1 *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a
/etc/exports
echo "/tftpboot *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a
/etc/exports
Restart RPC-Bind and the NFS server in order to have them detect the new files.

sudo systemctl enable rpcbind


sudo systemctl restart rpcbind
sudo systemctl enable nfs-kernel-server
sudo systemctl restart nfs-kernel-server
Edit /tftpboot/cmdline.txt and from root= onwards, and replace it with:

root=/dev/nfs nfsroot=10.42.0.211:/nfs/client1,vers=4.1,proto=tcp rw ip=dhcp


rootwait
You should substitute the IP address here with the IP address you have noted down.
Also remove any part of the command line starting with init=.

Finally, edit /nfs/client1/etc/fstab and remove the /dev/mmcblk0p1 and p2 lines


(only proc should be left). Then, add the boot partition back in:

echo "10.42.0.211:/tftpboot /boot nfs defaults,vers=4.1,proto=tcp 0 0" | sudo tee -


a /nfs/client1/etc/fstab
Good luck! If it doesn’t boot on the first attempt, keep trying. It can take a
minute or so for the Raspberry Pi to boot, so be patient.

Using pxetools
We have created a Python script that is used internally to quickly set up Raspberry
Pis that will network boot.

The script takes a serial number, which you can find in cat /proc/cpuinfo, an owner
name and the name of the Raspberry Pi. It then creates a root filesystem for that
Raspberry Pi from a Raspberry Pi OS image. There is also a --list option which will
print out the IP address of the Raspberry Pi, and a --remove option.

NOTE
The following instructions describe how to set up the environment required by the
script starting from a fresh Raspberry Pi OS lite image. It might be a good idea to
mount a hard disk or flash drive on /nfs so that your SD card isn’t providing
filesystems to multiple Raspberry Pis. This is left as an exercise for the reader.
sudo apt update
sudo apt full-upgrade -y
sudo reboot

wget https://datasheets.raspberrypi.com/soft/prepare_pxetools.sh
bash prepare_pxetools
When prompted about saving iptables rules, say no.

The prepare_pxetools script should prepare everything you need to use pxetools.

We found that we needed to restart the nfs server after using pxetools for the
first time. Do this with:

sudo systemctl restart nfs-kernel-server


Then plug in your Raspberry Pi and it should boot!

Network booting using IPv6


Edit this on GitHub

There are 4 stages to booting a Raspberry Pi computer over the network:

The bootloader negotiates to get an IP address and the details of a TFTP server
using DHCP.

The bootloader loads the firmware via TFTP and hands over the boot process to the
firmware, passing it the details of the network.

The firmware loads the kernel and command line via TFTP.

The kernel boots the rest of the system, loading the root filesystem (rootfs) via
NFS or some other mechanism.

The bootloader and firmware (stages 1 to 3) have been enhanced to support booting
over IPv6.
IMPORTANT
IPv6 netboot is an experimental alpha feature and depending on feedback, we may
need to change how it works in future. This only works on Raspberry Pi 4 and
Compute Module 4.
How it works
To boot via IPv6 you need an updated version of the firmware (e.g. start4.elf) and
the bootloader. Using the Bullseye release of Raspberry Pi OS and the latest stable
bootloader should be sufficient.

NOTE
The commonly used dnsmasq DHCP server doesn’t currently support the network boot
parameters required for IPv6 network boot, so for the time being you will have to
use a different DHCP server such as ISC DHCP.
To mount rootfs over the network the IPv4 netboot tutorial suggests using nfsroot.
This doesn’t support IPv6, so another method is needed to mount rootfs over the
network.

If your ISP and router don’t support IPv6 you will be limited in what you can do.

Network addresses
The first thing the bootloader does is send a router solicitation to get the
details of the network. The router responds with an advertisement packet
identifying its ethernet address, which the bootloader might need if the TFTP
server is on a different network.

The router advertisement includes a flag which tells it whether to use stateful
(managed) or stateless (unmanaged) configuration for its IP address. Stateless
configuration means that the device configures its own IP address. Currently the
bootloader generates an address derived from its ethernet MAC address and a network
prefix supplied by the router.

If the router indicates that stateful configuration is enabled DHCP is used to


obtain the IP address of the device. This involves the device sending a
solicitation request to a DHCP server which responds with an advertisement. The
client then requests the address before getting a reply acknowledgement from the
server.

DHCP Servers and clients identify themselves with variable length DUID (Device
Unique ID). On the Raspberry Pi this is derived from the MAC address (DUID_LL).

TFTP address
Whether using stateless or stateful configuration, the DHCP server is used to
obtain the TFTP server address. This is encoded in the BOOTFILE-URL parameter. We
send the client architecture type value 0x29 to identify a device.

See RFC 5970 and the IANA Dynamic Host Configuration Protocol for IPv6
documentation.

Boot process
The device should now have an IP address and TFTP details. It downloads the
firmware binary start4.elf from the TFTP server and continues running with this.
The firmware is passed the IP address and TFTP server details so it can download
the kernel and boot the rest of the system.

Kernel Boot
With IPv4 netboot, nfsroot is used to mount rootfs over the network. This doesn’t
support IPv6 so another solution is required. It might involve a small RAM file
system that can mount the appropriate network location before switching to the
proper rootfs contents.

NOTE
A mechanism to boot the Linux kernel with NFS via IPv6 is still to be demonstrated.
Test Setup
If you want to try this out you will need another Raspberry Pi to act as the TFTP
and DHCP server.

The TFTP server can in theory be on any routable network but the DHCP server has to
be on the same network as the devices it will serve.

TFTP Server
If you have a working IPv4 network boot setup you can reuse the TFTP server in
dnsmasq to supply the files (it can talk to both IPv4 and IPv6).

Alternatively you can use a standalone TFTP server like tftpd-hpa.

$ sudo apt-get install tftpd-hpa


$ sudo systemctl start tftpd-hpa
DHCP Server
DHCP in IPv6 has changed a lot. We need DHCP to at least tell us the address of the
TFTP server, which in this case is the same machine.

$ sudo apt-get install isc-dhcp-server


Modify the configuration in /etc/default/isc-dhcp-server

DHCPDv6_CONF=/etc/dhcp/dhcpd6.conf
INTERFACESv6="eth0"
In /etc/dhcp/dhcpd6.conf you need to specify the TFTP server address and setup a
subnet. Here the DHCP server is configured to supply some made up unique local
addresses (ULA). The host test-rpi4 line tells DHCP to give a test device a fixed
address.

not authoritative;

# Check if the client looks like a Raspberry Pi


if option dhcp6.client-arch-type = 00:29 {
option dhcp6.bootfile-url "tftp://[fd49:869:6f93::1]/";
}

subnet6 fd49:869:6f93::/64 {
host test-rpi4 {
host-identifier option dhcp6.client-id
00:03:00:01:e4:5f:01:20:24:0b;
fixed-address6 fd49:869:6f93::1000;
}
}
Your server has to be assigned the IPv6 address in /etc/dhcpcd.conf

interface eth0
static ip6_address=fd49:869:6f93::1/64
Now start the DHCP server.

$ sudo systemctl restart isc-dhcp-server.service


Bootloader
Modify the configuration to tell it to attempt network boot via IPv6 rather than
IPv4.

BOOT_ORDER=0xf21 # 2=Network boot


USE_IPV6=1 # Enable IPv6 network boot
BOOT_UART=1 # Debug
To revert to IPv4 network boot just remove the USE_IPV6 line from boot.conf.

Router
To use IPv6 you really need a router and ISP that supports IPv6. There are sites on
the internet that can check this for you or alternatively run the following
command.

sudo apt-get install ndisc6


rdisc6 -1 eth0
This sends a router solicitation to your router asking for your network details
such as the network prefix, router ethernet address and whether to use DHCP for
addressing. If there’s no response to this command it’s likely your network and ISP
only supports IPv4. If IPv6 is supported it’s most likely that it will be
configured to use stateless configuration where clients generate their own
addresses.

Soliciting ff02::2 (ff02::2) on eth0...


Hop limit : 64 ( 0x40)
Stateful address conf. : No
Stateful other conf. : Yes
Mobile home agent : No
Router preference : medium
Neighbor discovery proxy : No
Router lifetime : 180 (0x000000b4) seconds
Reachable time : unspecified (0x00000000)
Retransmit time : unspecified (0x00000000)
You might be able to configure your router for stateful configuration, which means
it will use DHCP to obtain an IP address.

Hop limit : 64 ( 0x40)


Stateful address conf. : Yes
Stateful other conf. : Yes
Mobile home agent : No
Router preference : medium
Neighbor discovery proxy : No
Router lifetime : 180 (0x000000b4) seconds
Reachable time : unspecified (0x00000000)
Retransmit time : unspecified (0x00000000)
Debugging
Logs and Traces
If the boot uart is enabled you should see something like this from the serial
port. The lines starting RX6 indicate that IPv6 is in use.

Here dc:a6:32:6f:73:f4 is the MAC address of the TFTP server and it has an IPv6
address of fd49:869:6f93::1. The device itself has a MAC address e4:5f:01:20:24:0b
and an IPv6 address of fd49:869:6f93::1000

Boot mode: NETWORK (02) order f


GENET: RESET_PHY
PHY ID 600d 84a2
NET_BOOT: e4:5f:01:20:24:0b wait for link TFTP6: (null)
LINK STATUS: speed: 100 full duplex
Link ready
GENET START: 64 16 32
GENET: UMAC_START 0xe45f0120 0x240b0000
RX6: 12 IP: 1 MAC: 1 ICMP: 1/1 UDP: 0/0 ICMP_CSUM_ERR: 0 UDP_CSUM_ERR: 0
NET fd49:869:6f93::1000 tftp fd49:869:6f93::1
RX6: 17 IP: 4 MAC: 4 ICMP: 2/2 UDP: 2/2 ICMP_CSUM_ERR: 0 UDP_CSUM_ERR: 0
TFTP_GET: dc:a6:32:6f:73:f4 fd49:869:6f93::1 ab5a4158/start4.elf

RX6: 17 IP: 4 MAC: 4 ICMP: 2/2 UDP: 2/2 ICMP_CSUM_ERR: 0 UDP_CSUM_ERR: 0


RX6: 18 IP: 5 MAC: 5 ICMP: 2/2 UDP: 3/3 ICMP_CSUM_ERR: 0 UDP_CSUM_ERR: 0
TFTP_GET: dc:a6:32:6f:73:f4 fd49:869:6f93::1 ab5a4158/config.txt
Finally the bootloader hands over to firmware which should load the kernel.

Stateful configuration
You can examine network activity with tcpdump.

$ sudo tcpdump -i eth0 -e ip6 -XX -l -v -vv


Below is an extract of a TCP dump where the router is configured to use stateful
(DHCP) network configuration.

Device sends a router solicitation.

12:23:35.387046 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:00:00:02 (oui Unknown),


ethertype IPv6 (0x86dd), length 70: (hlim 255, next-header ICMPv6 (58) payload
length: 16) fe80::e65f:1ff:fe20:240b > ip6-allrouters: [icmp6 sum ok] ICMP6, router
solicitation, length 16
source link-address option (1), length 8 (1): e4:5f:01:20:24:0b
0x0000: e45f 0120 240b
Router sends a response telling the device to use stateful configuration.

12:23:35.498902 60:8d:26:a7:c1:88 (oui Unknown) > 33:33:00:00:00:01 (oui Unknown),


ethertype IPv6 (0x86dd), length 110: (hlim 255, next-header ICMPv6 (58) payload
length: 56) bthub.home > ip6-allnodes: [icmp6 sum ok] ICMP6, router advertisement,
length 56
hop limit 64, Flags [managed, other stateful], pref medium, router lifetime
180s, reachable time 0ms, retrans timer 0ms
rdnss option (25), length 24 (3): lifetime 60s, addr: bthub.home
0x0000: 0000 0000 003c fe80 0000 0000 0000 628d
0x0010: 26ff fea7 c188
mtu option (5), length 8 (1): 1492
0x0000: 0000 0000 05d4
source link-address option (1), length 8 (1): 60:8d:26:a7:c1:88
0x0000: 608d 26a7 c188
Device sends a DHCP solicitation.

12:23:35.502517 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:01:00:02 (oui Unknown),


ethertype IPv6 (0x86dd), length 114: (hlim 255, next-header UDP (17) payload
length: 60) fe80::e65f:1ff:fe20:240b.dhcpv6-client > ff02::1:2.dhcpv6-server: [udp
sum ok] dhcp6 solicit (xid=8cdd56 (client-ID hwaddr type 1 e45f0120240b) (IA_NA
IAID:0 T1:0 T2:0) (option-request opt_59) (opt_61) (elapsed-time 0))
The DHCP server replies with an advertisement.

12:23:35.510478 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown),


ethertype IPv6 (0x86dd), length 172: (flowlabel 0xad54d, hlim 64, next-header UDP
(17) payload length: 118) fe80::537a:52c:c647:b184.dhcpv6-server >
fe80::e65f:1ff:fe20:240b.dhcpv6-client: [bad udp cksum 0xd886 -> 0x6d26!] dhcp6
advertise (xid=8cdd56 (IA_NA IAID:0 T1:3600 T2:7200 (IA_ADDR fd49:869:6f93::1000
pltime:604800 vltime:2592000)) (client-ID hwaddr type 1 e45f0120240b) (server-ID
hwaddr/time type 1 time 671211709 dca6326f73f4) (opt_59))
The device sends a request for an address and TFTP details to the DHCP server.

12:23:35.510763 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:01:00:02 (oui Unknown),


ethertype IPv6 (0x86dd), length 132: (hlim 255, next-header UDP (17) payload
length: 78) fe80::e65f:1ff:fe20:240b.dhcpv6-client > ff02::1:2.dhcpv6-server: [udp
sum ok] dhcp6 request (xid=8cdd56 (client-ID hwaddr type 1 e45f0120240b) (server-ID
hwaddr/time type 1 time 671211709 dca6326f73f4) (IA_NA IAID:0 T1:0 T2:0) (option-
request opt_59) (opt_61) (elapsed-time 1))
The DHCP server replies, opt_59 is used to pass the address of the TFTP server.

12:23:35.512122 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown),


ethertype IPv6 (0x86dd), length 172: (flowlabel 0xad54d, hlim 64, next-header UDP
(17) payload length: 118) fe80::537a:52c:c647:b184.dhcpv6-server >
fe80::e65f:1ff:fe20:240b.dhcpv6-client: [bad udp cksum 0xd886 -> 0x6826!] dhcp6
reply (xid=8cdd56 (IA_NA IAID:0 T1:3600 T2:7200 (IA_ADDR fd49:869:6f93::1000
pltime:604800 vltime:2592000)) (client-ID hwaddr type 1 e45f0120240b) (server-ID
hwaddr/time type 1 time 671211709 dca6326f73f4) (opt_59))
The device sends a neighbour solicitation to the FTP server because it needs its
MAC address.

12:23:36.510768 e4:5f:01:20:24:0b (oui Unknown) > 33:33:ff:00:00:01 (oui Unknown),


ethertype IPv6 (0x86dd), length 86: (hlim 255, next-header ICMPv6 (58) payload
length: 32) fe80::e65f:1ff:fe20:240b > ff02::1:ff00:1: [icmp6 sum ok] ICMP6,
neighbor solicitation, length 32, who has fd49:869:6f93::1
source link-address option (1), length 8 (1): e4:5f:01:20:24:0b
0x0000: e45f 0120 240b
The FTP server replies with its MAC address.

12:23:36.510854 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown),


ethertype IPv6 (0x86dd), length 86: (hlim 255, next-header ICMPv6 (58) payload
length: 32) fd49:869:6f93::1 > fe80::e65f:1ff:fe20:240b: [icmp6 sum ok] ICMP6,
neighbor advertisement, length 32, tgt is fd49:869:6f93::1, Flags [solicited,
override]
destination link-address option (2), length 8 (1): dc:a6:32:6f:73:f4
0x0000: dca6 326f 73f4
TFTP requests are made by the device which should now boot over the network.

12:23:36.530820 e4:5f:01:20:24:0b (oui Unknown) > dc:a6:32:6f:73:f4 (oui Unknown),


ethertype IPv6 (0x86dd), length 111: (hlim 255, next-header UDP (17) payload
length: 57) fd49:869:6f93::1000.61785 > fd49:869:6f93::1.tftp: [udp sum ok] 49 RRQ
"ab5a4158/start4.elf" octet tsize 0 blksize 1024
Stateless configuration
Below is an extract of a tcp dump for a stateless (non-DHCP) network configuration.

The device sends a router solicitation.

12:55:27.541909 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:00:00:02 (oui Unknown),


ethertype IPv6 (0x86dd), length 70: (hlim 255, next-header ICMPv6 (58) payload
length: 16) fe80::e65f:1ff:fe20:240b > ip6-allrouters: [icmp6 sum ok] ICMP6, router
solicitation, length 16
source link-address option (1), length 8 (1): e4:5f:01:20:24:0b
0x0000: e45f 0120 240b
The router replies with the network details.

12:55:27.834684 60:8d:26:a7:c1:88 (oui Unknown) > 33:33:00:00:00:01 (oui Unknown),


ethertype IPv6 (0x86dd), length 174: (hlim 255, next-header ICMPv6 (58) payload
length: 120) bthub.home > ip6-allnodes: [icmp6 sum ok] ICMP6, router advertisement,
length 120
hop limit 64, Flags [other stateful], pref medium, router lifetime 180s,
reachable time 0ms, retrans timer 0ms
prefix info option (3), length 32 (4): 2a00:23c5:ee00:5001::/64, Flags
[onlink, auto, router], valid time 300s, pref. time 120s
0x0000: 40e0 0000 012c 0000 0078 0000 0000 2a00
0x0010: 23c5 ee00 5001 0000 0000 0000 0000
prefix info option (3), length 32 (4): fd4d:869:6f93::/64, Flags [onlink,
auto, router], valid time 10080s, pref. time 2880s
0x0000: 40e0 0000 2760 0000 0b40 0000 0000 fd4d
0x0010: 0869 6f93 0000 0000 0000 0000 0000
rdnss option (25), length 24 (3): lifetime 60s, addr: bthub.home
0x0000: 0000 0000 003c fe80 0000 0000 0000 628d
0x0010: 26ff fea7 c188
mtu option (5), length 8 (1): 1492
0x0000: 0000 0000 05d4
source link-address option (1), length 8 (1): 60:8d:26:a7:c1:88
0x0000: 608d 26a7 c188
The device sends an information request to the DHCP multicast address asking for
the TFTP details.

12:55:27.838300 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:01:00:02 (oui Unknown),


ethertype IPv6 (0x86dd), length 98: (hlim 255, next-header UDP (17) payload length:
44) fe80::e65f:1ff:fe20:240b.dhcpv6-client > ff02::1:2.dhcpv6-server: [udp sum ok]
dhcp6 inf-req (xid=e5e0a4 (client-ID hwaddr type 1 e45f0120240b) (option-request
opt_59) (opt_61) (elapsed-time 0))
The DHCP server replies with the TFTP server details (opt_59).

12:55:27.838898 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown),


ethertype IPv6 (0x86dd), length 150: (flowlabel 0xd1248, hlim 64, next-header UDP
(17) payload length: 96) fe80::537a:52c:c647:b184.dhcpv6-server >
fe80::e65f:1ff:fe20:240b.dhcpv6-client: [bad udp cksum 0xd870 -> 0x78bb!] dhcp6
reply (xid=e5e0a4 (client-ID hwaddr type 1 e45f0120240b) (server-ID hwaddr/time
type 1 time 671211709 dca6326f73f4) (opt_59))
The device asks for the TFTP server MAC address since it can tell it’s on the same
network.

12:55:28.834796 e4:5f:01:20:24:0b (oui Unknown) > 33:33:ff:1d:fe:2a (oui Unknown),


ethertype IPv6 (0x86dd), length 86: (hlim 255, next-header ICMPv6 (58) payload
length: 32) fe80::e65f:1ff:fe20:240b > ff02::1:ff1d:fe2a: [icmp6 sum ok] ICMP6,
neighbor solicitation, length 32, who has 2a00:23c5:ee00:5001:57f1:7523:2f1d:fe2a
source link-address option (1), length 8 (1): e4:5f:01:20:24:0b
0x0000: e45f 0120 240b
The FTP server replies with its MAC address.

12:55:28.834875 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown),


ethertype IPv6 (0x86dd), length 86: (hlim 255, next-header ICMPv6 (58) payload
length: 32) 2a00:23c5:ee00:5001:57f1:7523:2f1d:fe2a > fe80::e65f:1ff:fe20:240b:
[icmp6 sum ok] ICMP6, neighbor advertisement, length 32, tgt is
2a00:23c5:ee00:5001:57f1:7523:2f1d:fe2a, Flags [solicited, override]
destination link-address option (2), length 8 (1): dc:a6:32:6f:73:f4
0x0000: dca6 326f 73f4
The device starts making TFTP requests.

12:55:28.861097 e4:5f:01:20:24:0b (oui Unknown) > dc:a6:32:6f:73:f4 (oui Unknown),


ethertype IPv6 (0x86dd), length 111: (hlim 255, next-header UDP (17) payload
length: 57) 2a00:23c5:ee00:5001:e65f:1ff:fe20:240b.46930 >
2a00:23c5:ee00:5001:57f1:7523:2f1d:fe2a.tftp: [udp sum ok] 49 RRQ
"ab5a4158/start4.elf" octet tsize 0 blksize 1024

================================================================================
Come rendere Raspberry Pi 3 Boot da USB
================================================================================

Per saperne di più, è ora possibile rinunciare all'avvio da microSD e avviare il


computer da un
dispositivo USB. Potrebbe trattarsi di una penna flash, un SSD con un adattatore
USB o persino
un disco rigido USB di dimensioni standard.

Inizia: installa Raspbian e aggiungi nuovi file

È meglio iniziare questo progetto con una nuova copia di Raspbian, quindi scaricare
l'ultima
versione (stiamo usando Raspbian Jessi in seguito il rilascio di Debian Jessie a
luglio,
la comunità Raspberry Pi è stata benedetta con una nuova versione della variante
Raspbian,
basata sulla distro "madre" Leggi di più) e installarlo nel solito modo

Come installare un sistema operativo sul tuo Raspberry Pi

Ecco come ottenere un nuovo sistema operativo installato e funzionante sul tuo Pi -
e come
clonare la tua configurazione perfetta per un rapido disaster recovery.

Leggi di più . Appena fatto, rimuovi la scheda dal PC in modo sicuro, inseriscila
nel Raspberry Pi
inattivo e avvia la connessione remota tramite SSH

Configurazione del tuo Raspberry Pi per l'uso senza testa Con SSH

Il Raspberry Pi può accettare comandi SSH quando è connesso a una rete locale
(tramite Ethernet o Wi-Fi), consentendo di configurarlo facilmente.

Accedi (a meno che tu non abbia cambiato le tue credenziali predefinite

quindi esegui i seguenti comandi, che sostituiranno i file start.elf e bootcode.bin


predefiniti con
le alternative appena scaricate:

apt-get update BRANCH=next rpi-update


Questo aggiornamento consegna i due file nella directory /boot .
Con i file scaricati, procedere per abilitare la modalità di avvio USB con:

echo program_usb_boot_mode=1 | tee -a /boot/config.txt


Questo comando aggiunge l'istruzione program_usb_boot_mode=1 alla fine del file
config.txt .

Terminale Linux Boot Raspberry Pi 3 con USB

Avrai bisogno di riavviare il Pi una volta fatto.

Il passo successivo è verificare che l'OTP - una memoria programmabile una sola
volta -
sia stata cambiata. Controlla questo con:

vcgencmd otp_dump | grep 17:

Se il risultato è rappresentativo dell'indirizzo 0x3020000a (ad esempio 17:3020000a


), tutto è buono finora.

In questa fase, se desideri rimuovere la riga program_usb_boot_mode=1 dal file


config.txt, puoi farlo.
Il Pi ora è abilitato per l'avvio USB, e potresti voler usare la stessa scheda
microSD in un altro Raspberry Pi 3,
con la stessa immagine, quindi rimuovere la linea è una buona idea.

Questo è fatto facilmente modificando config.txt in nano:

nano /boot/config.txt

Elimina o commenta la riga corrispondente (con un # precedente).

Preparare il dispositivo di avvio USB

Quindi, collega una chiavetta USB formattata (o pronta per essere eliminata) in una
porta di
riserva sul tuo Raspberry Pi 3. Con questo inserito, procederemo a copiare il
sistema operativo.

Inizia identificando la tua chiavetta USB, con il comando lsblk .

In questo esempio, la scheda SD è mmcblk0 mentre la chiavetta USB è sda (la


partizione formattata è sda1 ).
Se sono collegati altri dispositivi di archiviazione USB, la chiavetta USB potrebbe
essere sdb, sdc, ecc.
Dopo aver stabilito il nome della chiavetta USB, smontare il disco e utilizzare lo
strumento parted
per creare una partizione da 100 MB (FAT32) e una partizione Linux:

umount /dev/sda
parted /dev/sda

# parted /dev/sda
GNU Parted 3.4
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print all
Model: Generic Flash Disk (scsi)
Disk /dev/sda: 8053MB
Sector size (logical/physical): 512B/512B
Partition Table: loop
Disk Flags:

Number Start End Size File system Flags


1 0,00B 8053MB 8053MB fat32

Model: SD 00000 (sd/mmc)


Disk /dev/mmcblk0: 1019MB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:

Number Start End Size Type File system Flags


1 1049kB 1018MB 1017MB primary fat32 boot, lba

fdisk -l /dev/sda
Disk /dev/sda: 7,5 GiB, 8053063680 bytes, 15728640 sectors
Disk model: Flash Disk
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00000000

Device Boot Start End Sectors Size Id Type


/dev/sda1 8192 532479 524288 256M c W95 FAT32 (LBA)
/dev/sda2 532480 15728639 15196160 7,2G 83 Linux

Al prompt (parted), inserire:

mktable msdos

Se si incontrano problemi qui, potrebbe essere necessario passare al desktop


(manualmente o tramite VNC

Come eseguire un desktop remoto su Raspberry Pi con VNC

Cosa fare se è necessario accedere al desktop Raspberry Pi dal tuo PC o laptop,


senza dover
collegare una tastiera, un mouse e un monitor? Ecco dove entra VNC. Leggi altro)

e conferma che il disco è smontato, prima di entrare nel comando mdtable msdos in
un comando
con finestra linea.

Procedi in separazione con quanto segue:

mkpart primary fat32 0% 100M


mkpart primary ext4 100M 100%

mkpart primary fat32 0% 1017M


mkpart primary ext4 1017M 100%
print

Questo produrrà alcune informazioni riguardanti il disco e le nuove partizioni.


Procedere all'uscita parted con Ctrl + C, prima di creare il file system di avvio
e il filesystem di root:

mkfs.vfat -n BOOT -F 32 /dev/sda1


mkfs.ext4 /dev/sda2

È quindi necessario montare i filesystem di destinazione, prima di copiare il


sistema operativo
Raspbian corrente sul dispositivo USB.

mkdir /mnt/target
mount /dev/sda2 /mnt/target/
mkdir /mnt/target/boot
mount /dev/sda1 /mnt/target/boot/

apt-get update;
apt-get install rsync
rsync -ax --progress /boot /mnt/target

Quest'ultimo è l'ultimo comando che copia tutto, e quindi ci vorrà un po 'per


completare.

Terminale Linux Boot Raspberry Pi 3 con copia USB

Successivamente, è necessario aggiornare le chiavi dell'host SSH, per mantenere la


connessione
con il Raspberry Pi riconfigurato dopo un imminente riavvio:

cd /mnt/target
mount --bind /dev dev
mount --bind /sys sys
mount --bind /proc proc
chroot /mnt/target
rm /etc/ssh/ssh_host*
dpkg-reconfigure openssh-server
exit
umount dev
umount sys
umount proc

Terminale Linux Boot Raspberry Pi 3 con USB SSH

Si noti che dopo sudo chroot (il quinto comando sopra) si passa a root, quindi
l'utente passerà da pi @ raspberrypi a root @ raspberrypi finché non si entra exit
on line 8.

Preparati per il riavvio da USB!


Ancora un paio di cose da risolvere prima che il tuo Raspberry Pi sia pronto per
l'avvio da USB. Dobbiamo modificare nuovamente cmdline.txt dalla riga di comando
con:

sudo sed -i "s, root=/dev/mmcblk0p2, root=/dev/sda2, "


/mnt/target/boot/cmdline.txt
Allo stesso modo, è necessario apportare le seguenti modifiche a fstab:

sudo sed -i "s, /dev/mmcblk0p, /dev/sda, " /mnt/target/etc/fstab


Sei pronto per smontare i filesystem prima di spegnere il Pi:

cd ~ sudo umount /mnt/target/boot sudo umount /mnt/target sudo poweroff


Si noti che questo utilizza il nuovo comando poweroff come alternativa shutdown .

Quando il Pi si è spento, scollegare l'alimentazione prima di rimuovere la scheda


SD. Quindi, ricollega l'alimentatore: il tuo Raspberry Pi dovrebbe ora essere
avviato dal dispositivo USB!

Hai provato questo? Incuriosito dalle possibilità di un avvio USB piuttosto che
dalla scheda SD? Stai pianificando di provarlo? Diteci nei commenti!

You might also like