How-To: Raspberry Pi media SERVER (easy)

by jelleke60 » Fri Sep 20, 2013 8:59 pm

In this tutorial I will attempt to explain how to turn your Raspberry Pi in a media SERVER to stream media to your home network or even remote network.

This setup will allow the following:
    -> Stream movies/photo's/music TO your home network and remote network.
    -> Stream to any device (PC/laptop/XBMC/WD Live/Popcorn/Android/...)
    -> SRT support for movies
    -> HD support
    -> Using samba share and FTP share methods

You will need:
    -> Raspberry Pi with the latest Raspbian image installed http://www.raspberrypi.org/downloads
    -> internet connection to your PI
    -> External USB HDD with media content (ordered in seperate folders)
    -> Another device to stream the content to such as a laptop,media box, ...[/url]

Let's get started

You can use SSH to acces your terminal on the RPI from another device or use the terminal on the device itself by using a monitor/keyboard with the RPI.
In your terminal type the following:

Update your Repo's
CODE: SELECT ALL
sudo apt-get update

If you are going to use a NTFS based external hard drive (most are) (TIP: ext4 file systems are the fastest)
CODE: SELECT ALL
sudo apt-get install ntfs-3g

Now insert your usb hard drive in the RPI and wait untill it gets mounted. If it's mounted type the following
CODE: SELECT ALL
sudo df

A list of installed hard drives will appear. Write down your external HD's location. Mine was /dev/sda1. Type the following commands. (You might want to CHMOD your HDD folder permissions if you get permission errors later)
CODE: SELECT ALL
cd /media
sudo mkdir HDD
sudo nano /etc/fstab

A file will open, on the bottom of the file type the following and then exit and save the file (ctrl+x, Y, enter, enter). Remember to replace /dev/sda1 with your HDD location. Also replace ntfs-3g with vfat if your have a fat based HDD or ext4 for a ext4 filesystem. Whitespaces areTABS
CODE: SELECT ALL
/dev/sda1         /media/HDD       ntfs-3g     defaults,noatime      0        0

Back in terminal, type these commands
CODE: SELECT ALL
sudo umount /dev/sda1
sudo mount /dev/sda1

Your external Hard drive should now always be mounted in the folder HDD. So far so good, now lets install samba and vsftpd.
CODE: SELECT ALL
sudo apt-get install samba samba-common-bin
sudo apt-get install vsftpd
sudo apt-get install hdparm
sudo hdparm -S 240 /dev/sda1 ##DO THIS ONLY if you want to spindown your external hard drive when it's inactive for 20min, handy if you always want to keep everything powered.

Configure Samba, for home network share (skip if you only want a remote share)
CODE: SELECT ALL
cp /etc/samba/smb.conf /etc/samba/smb.conf.bak  //Make a backup of the config file
nano /etc/samba/smb.conf

when the file opens scroll to the bottom and paste the following, then save and exit
CODE: SELECT ALL
[media] 
comment = Media share
path = /media/HDD
valid users = @users
force group = users
create mask = 0660
directory mask = 0771
read only = no

Now make an extra account to log into samba on another device
CODE: SELECT ALL
sudo service samba restart
sudo useradd ChooseUsernameHere -m -G users
sudo passwd TheChosenUsername //after this choose a password for the new user
sudo smbpasswd -a TheChosenUsername //after this enter passwd again

All set! Scroll to the bottom to see how to stream movies on another device now in the home network if you want to skip remote streaming.

Configure remote streaming
First make an extra user (if you skipped samba setup)
CODE: SELECT ALL
sudo useradd ChooseUsernameHere -m -G users
sudo passwd TheChosenUsername //after this choose a password for the new user

Configure vsftpd
CODE: SELECT ALL
sudo nano /etc/vsftpd.conf

##Edit or uncomment the following lines ::::
Anonymous_enable=NO
Local_enable=YES
Write_enable=YES
Ascii_upload_enable=YES
Ascii_download_enable=YES

##ADD the following lines to the bottom of the file!
pasv_enable=YES
listen_port=64000
pasv_min_port=64001
pasv_max_port=64040
pasv_address=YOUR REMOTE IP ADDRESS (lookup my ip on google)
pasv_address_resolve=YES
local_root=/media/HDD

important! Now go into your Router settings and forward port 64000 to 64040, to the local IP of your raspberry. Make sure everything has a static address, if you don't know how to do it then lookup another tutorial, there are plenty.
CODE: SELECT ALL
sudo service vsftpd restart

All done on the Raspberry Pi side! Now take your laptop/XBMC/mediabox!

On a PC/XBMC mediabox where you want to stream to

Note: it really helps if your video files on the HDD are properly ordered and in seperate folders with movie title.
If you are on a laptop/pc then install XBMC for windows/linux http://xbmc.org/download/.

Open XBMC and do the following (for video streaming on the HOME network)
    -> videos -> files -> add videos...
    Click browse and choose Windows network (SMB) (You could even map the share into a drive first in windows)
    -> Choose the raspberry out of the list and then the folder where your files are
    -> next choose movie scraper and make sure settings are ok, then scan the content, when it's done you should be able to stream movies from your RPI!

For REMOTE streaming
    -> videos -> files -> add videos...
    Click browse and choose Add network location
    -> protocol = FTP
    -> Address = your remote IP (the one from google)
    -> port = 64000
    -> username = the extra user you made before 
    -> pass = the users passwd
    -> click OK and then select it, now choose movie scraper and check the settings

Done! I hope you enjoy your new streaming device! 

For me, this works like a charm, i was able to watch HD movies in a Hotel abroad on my laptop, streaming from my RPI at home.
XBMC installs on almost everything (RPI, PC,Linux,Android) so you would be able to stream to all those devices using the above method.

Let me know what you think and ask questions if you like! Greets
Last edited by jelleke60 on Tue Oct 21, 2014 4:19 pm, edited 3 times in total.


'Linux > RaspberryPi' 카테고리의 다른 글

ftp명령어  (0) 2015.06.29
ftp확인  (0) 2015.06.29
raspberry pi network status  (0) 2015.06.29
라즈베리파이에 FTP서버 구축  (0) 2015.06.29
Raspberry Pi – Enabling Telnet  (0) 2015.06.29

The IP address 192.120.43.250 is the eth0 for my server. When I run the command

sudo vsftpd /etc/vsftpd.conf

I get the error:

500 OOPS: could not bind listening IPv4 socket

To check to see what was running on port 21, I ran the command:

sudo netsat -tulpn

And saw that vsftpd process id was 29383 so I issued the command:

sudo killserver 29383

And checked again. The vsftpd was still there, but with a different PID. Running the command:

sudo killall vsftpd

and

sudo killall -9 vsftpd

Does the same thing. I have already tried reinstalling. Anyone know what is going on and how to fix it?

'Linux > RaspberryPi' 카테고리의 다른 글

/etc/vsftpd.conf 설정 참조글  (0) 2015.06.29
ftp확인  (0) 2015.06.29
raspberry pi network status  (0) 2015.06.29
라즈베리파이에 FTP서버 구축  (0) 2015.06.29
Raspberry Pi – Enabling Telnet  (0) 2015.06.29

Testing

just go to the vsftpd directory and launch it
cd /storage/opt/vsftpd
./vsftpd vsftpd.conf

let's try a connection :
telnet 127.0.0.1 21
HELO
QUIT

'Linux > RaspberryPi' 카테고리의 다른 글

/etc/vsftpd.conf 설정 참조글  (0) 2015.06.29
ftp명령어  (0) 2015.06.29
raspberry pi network status  (0) 2015.06.29
라즈베리파이에 FTP서버 구축  (0) 2015.06.29
Raspberry Pi – Enabling Telnet  (0) 2015.06.29

Just to add to this useful advice you can see which process is listening at which port by using the command as root :

Code:
netstat -apn


'Linux > RaspberryPi' 카테고리의 다른 글

ftp명령어  (0) 2015.06.29
ftp확인  (0) 2015.06.29
라즈베리파이에 FTP서버 구축  (0) 2015.06.29
Raspberry Pi – Enabling Telnet  (0) 2015.06.29
Raspberry Pi에서 Java 설치하기!  (0) 2015.06.25
Home » 산딸기 서버 » 라즈베리파이 서버 활용 강좌 : 라즈베리파이에 FTP서버 구축

안녕하십니까.. 산딸기 마을에 이장 나무꾼 입니다.

오늘은 라즈베리파이 서버군 중 파일서버의 한 종류인 FTP Server 를 설치 및 환경설정을 해 보도록 하겠습니다.

 

라즈베리파이 FTP Server 구축하기

 

0. 파일서버의 정의

위키디피아 에서는 파일서버에 대한 정의를 아래와 같이 표현하고 있습니다.

컴퓨팅 환경에서 파일 서버(file server)는 워크스테이션이 접근할 수 있는 컴퓨터 파일(문서, 사운드 파일, 사진, 영화, 그림, 데이터베이스 등)을 공유하고 있는 기억 공간의 위치를 제공하는 것이 주 목적을 가진 네트워크에 추가된 컴퓨터를 말한다.”서버”(server)라는 용어는 클라이언트 서버 구조로 된 기기의 역할을 강조하며 여기서 클라이언트는 이 기억 공간을 사용하는 워크스테이션을 말한다.
파일 서버는 일반적으로 어떠한 계산도 수행하지 않으며 클라이언트의 중간에 어떠한 프로그램도 실행하지 않는다. 데이터의 빠른 저장과 워크스테이션이 중대한 계산을 제공하는 데이터 수신이 파일 서버의 주된 설계 목적이다.

간단히 표현하자면 내부 또는 외부에서 파일서버가 구축되어 있는 네트워크 공간으로 접속을 하여 파일을 전달 받을 수 있는 컴퓨터 구성환경 이다.

그럼, 이제 본격적으로 사용 중인 R-Pi에 FTP Server 를 설치 해보도록 하겠습니다.

 

1. 준비 사항.

o Raspberry Pi 본체
o Pre-install Raspbian SD 메모리카드

 

2. vsftpd 설치하기 

apt-get install 설치실행 명령어로 FTP Server 프로그램 중 vsftpd 을 설치합니다.

sudo apt-get install vsftpd
vftpd_1그림 2-1)

 

3. vsftpd.conf 파일 설정하기

2번에서 처럼 vsftpd 프로그램이 정상적으로 설치가 되었다면, 외부 또는 내부에서 FTP접속이 가능하도록 /etc/vsftpd.conf 파일을 열어 일부 내용을 수정을 합니다.

sudo nano /etc/vsftpd.conf

vftpd_2

그림 3-1) 

vftpd_3

그림 3-2) 
# anonymous 사용자의 접속 허용 여부, 즉 anonymous ftp (default = YES)
# 공개된 형태의 FTP 서버로 운영할 것이 아니라면 NO로 한다.
 anonymous_enable=NO
# 로컬 계정 사용자의 접속 허용 여부 (default = NO)
 local_enable=YES
# write 명령어 허용 여부 (defualt = NO)
write_enable=YES
# 로컬 계정 사용자용 umask (default = 077)
local_umask=022
# anonymous 사용자가 파일을 업로드 할 수 있는지 여부 (default = NO)
# anon_upload_enable=YES
# anonymous 사용자의 디렉토리 생성 허용 여부 (default = NO)
# anon_mkdir_write_enable=YES
# 파일 전송 로그를 남길 것인지 여부 (default = YES)
 xferlog_enable=YES
# xferlog 표준 포맷으로 로그를 남길지 여부 (기본 설정파일은 YES)
# 아래에서 NO로 설정했을 때를 설명함
 xferlog_std_format=YES
# 파일 전송 로그 파일명
xferlog_file=/var/log/vsftpd.log
# FTP 서버 접속할 때 로긴 메시지 (default = vsFTPd 버전번호)
# 한글 사용 가능
# ftpd_banner=Welcome to blah FTP service.
# 사용자의 홈디렉토리를 벗어나지 못하도록 제한하기 위한 설정 (default=NO)
# 제한이 필요할 경우 YES로 바꾼 후 제한할 사용자 ID를 chroot_list_file= 에 설정한 파일에
# 지정한다.
# chroot_local_user= 설정과 관련이 있으니 '3. 문제 해결'을 꼭 읽어보라.
#
# chroot_list_enable=YES
# chroot_list_file=/etc/vsftpd.chroot_list
# ----------------------------------------------------------------
# 기본 설정 파일에는 없는 설정값으로 필요한 설정만 추가한다.
# ※ 중요한 설정은 굵은 글씨로 표시
# ----------------------------------------------------------------
# PAM 파일명을 지정 (설치할 때 /etc/pam.d/vsftpd명으로 복사함)
pam_service_name=vsftpd
# wtmp에 로그 남기기 (YES로 해야만 last 명령어로 접속 여부 확인 가능)
session_support=YES
# 사용자가 자신의 home directory를 벗어나지 못하도록 설정
chroot_local_user=YES
# 새로운 디렉토리에 들어갔을 때 뿌려줄 환경 메시지를 저장한 파일명
# message_file=.message
# xferlog 형식으로 log를 남기려면 (위에서 이미 YES로 했음)
# xferlog_std_format=NO
#
# - xferlog 표준 포맷은 로긴, 디렉토리 생성등의 로그를 남기지 않음
# 그러나 vsftpd 스타일 로그는 이를 포함한 보다 상세한 로그를 남김
# - vsftpd 스타일 로그 예
#
# Sun Jul 12 01:38:32 2003 [pid 31200] CONNECT: Client "127.0.0.1"
# Sun Jul 12 01:38:34 2003 [pid 31199] [truefeel] FAIL LOGIN: Client "127.0.0.1"
# Sun Jul 12 01:38:38 2003 [pid 31199] [truefeel] OK LOGIN: Client "127.0.0.1"
# Sun Jul 12 01:38:41 2003 [pid 31201] [truefeel] OK MKDIR: Client "127.0.0.1", "/mp3"
# Sun Jul 12 01:39:06 2003 [pid 31201] [truefeel] OK UPLOAD: Client "127.0.0.1", "/델리
# 스파이스 5집 - [04]키치죠지의 검은 고양이.mp3", 6855473 bytes, 3857.39Kbyte/sec
# 전송속도 제한 (0은 제한없음, 단위는 초당 bytes)
 anon_max_rate=0
 local_max_rate=0
 trans_chunk_size=0
# 최대 접속 설정 (단 xinetd를 통하지 않고 standalone으로 동작할 때만 사용 가능)
# standalone을 위해서는 listen=YES 추가하고 별도로 vsftpd를 띄워야 함
#
# max_clients=최대 접속자 수, max_per_ip=IP당 접속 수
# max_clients=100
# max_per_ip=3
# Standalone 으로 운영할 때 listen=YES. 포트 변경을 원할 경우 listen_port 설정
# 디폴트 포트는 21번 포트이다.
# listen=YES
# listen_port=21

 

[ 참고사이트]

https://security.appspot.com/vsftpd.html
http://jobdahan.net/server_linux/651905


'Linux > RaspberryPi' 카테고리의 다른 글

ftp확인  (0) 2015.06.29
raspberry pi network status  (0) 2015.06.29
Raspberry Pi – Enabling Telnet  (0) 2015.06.29
Raspberry Pi에서 Java 설치하기!  (0) 2015.06.25
Setting Up VNC  (0) 2015.06.24

Raspberry Pi – Enabling Telnet

In the next step in my series in using the Raspberry Pi for Network Engineers, I will cover the installation of Telnet on the RPi. Telnet is not secure and shouldn’t be used in a production environment unless there is no other choice. You start the process of installing Telnet by using the command sudo apt-get install telnetd. After Telnet has been installed, you will need to get the service starts. You can do it by using the command sudo /etc/init.d/openbsd-inetd restart or by rebooting the RPi.

Once you have the service ready, you can verify this by using the netstat -a command. You should see something like this from the RPi –

pi@raspberrypi:~$ netstat -a | grep telnet (with no telnet session on RPi active)
tcp 0 0 *:telnet *:* LISTEN

If you repeat the command with a telnet session active on the RPI, your should see this –

pi@raspberrypi:~$ netstat -a | grep telnet (with an active telnet session on RPi)
tcp 0 0 *:telnet *:* LISTEN
tcp 0 0 raspberrypi.loca:telnet 192.168.15.161:49610 ESTABLISHED

In a production environment, you should limit who can access the RPi via Telnet. You can do so with the /etc/hosts.allow file. Using this example (changing the ip address for the address of the workstation you are testing from) will block access to that workstation on Telnet –

add a line like this to /etc/hosts.allow to block a specific host –
in.telnetd : 192.168.15.161 : deny

Finding the name of the process to put in the hosts.allow file involved looking at the/var/log/syslog file to identify the running process involved. That is what told me that I needed to use in.telnetd instead of telnet or telnetd that I had first tried. Anytime that you make a change to the hosts.allow file, you will need to restart the inetd process – sudo /etc/init.d/openbsd-inetd restart.

If you want to allow only a specific workstation to get in via Telnet and block all others, you would use something like this –

in.telnetd : 192.168.15.162 : allow
in.telnetd : 192.168.15. : deny

Using only 192.168.15. acts like a wildcard and blocks all workstations that didn’t match on the earlier rule.

If you want to remove Telnet, you will use sudo apt-get remove telnet.

To see more of my posts about the Raspberry Pi, please go tohttp://www.ronnutter.com/category/raspberry-pi/


'Linux > RaspberryPi' 카테고리의 다른 글

raspberry pi network status  (0) 2015.06.29
라즈베리파이에 FTP서버 구축  (0) 2015.06.29
Raspberry Pi에서 Java 설치하기!  (0) 2015.06.25
Setting Up VNC  (0) 2015.06.24
시작시 Auto running programs  (0) 2015.01.03

Raspberry Pi에서 Java 설치하기!

sudo apt-get update && sudo apt-get install oracle-java7-jdk

'Linux > RaspberryPi' 카테고리의 다른 글

라즈베리파이에 FTP서버 구축  (0) 2015.06.29
Raspberry Pi – Enabling Telnet  (0) 2015.06.29
Setting Up VNC  (0) 2015.06.24
시작시 Auto running programs  (0) 2015.01.03
(cpp)wiringpi활용  (0) 2015.01.03

Setting Up VNC

While the Raspberry Pi does provide a superb picture over hdmi, there are a lot of scenarios where one might not need a display, and connecting remotely via VNC will suffice.  For instance, any programming could be done remotely, while still having access to the physical hardware.  It's also particularly useful when the TV is in use and getting it back to "play on" isn't an option.

EDIT 25/04/2012: Ive now identified how to enable SSH automatically - see below (thanks Abishur!!)

EDIT 20/08/2012: I've worked out how to start VNC automatically on bootup - see my other post here http://myraspberrypiexperience.blogspot.co.uk/2012/08/start-vnc-automatically.html

Pre-requisites
As a bit of background, I'm using the latest Debian image (19/04/2012) and I'm connecting from my Windows 7 laptop.  To connect I've installed UltraVNC on my laptop - you can download a free copy from here:
UltraVNC Downloads Page

Now, once  the VNC server is up and running on the Pi you can VNC from your laptop into your Pi without doing anything on the Pi first.  If you've just turned it on however, you'll need to first start the VNC server on the Pi.  And if you're using this as a truly headless box, that can be a little difficult.  To get around this I've used the PuTTY SSH client, which you can download here:
PuTTY Downloads Page

The last thing you need to know is the IP Address.  If you've configured your Pi with a static IP Address, that's great.  If you have access to your router to look this up that's fine too.  You might however be in a situation where you have no way to look up the IP Address (like me) - for this I needed a utility to scan the network for all machines.  For this I used:
Advanced IP Scanner
This will scan your network listing all devices it can find.  Simply look through the list of devices and find your Rashberry Pi. It'll have a fairly obvious name, like "RaspberryPi".

Alternatively, if you have access to your wireless router, you might be able to connect to this and see a list of all devices that have connected to it, including your Raspberry Pi.  As each wireless router differs, I'll leave this up to you to figure out :-)

Starting SSH on the Pi
First off - what is SSH?  It's a process that can be run in Linux that will allow you to access your Raspberry Pi remotely.  You'll be able to run anything that you would normally run from the command line on your Raspberry Pi, remotely from an SSH client - i.e. Putty.  #

I've found that the latest Debian image doesn't come with SSH enabled by default.  If you have a monitor and keyboard attached, once you've logged in you can start SSH by typing sudo /etc/init.d/ssh start as shown below:



Now, the idea of SSH is that we can connect remotely without a display, so you don't necessarily want to have to do this every time you boot up. 



EDIT 28/01/2013: There are two approaches to enabling SSH.


First option
For older images like Debian there is a file in place that can be used to do this - boot_enable_ssh.rc.  This file is on the boot partition of the SD card - i.e. the partition that can be read by Windows.  So - put the card into your PC card reader and open it up:


Now rename boot_enable_ssh.rc to boot.rc:
 


Once you've done this put the card back into the Pi and boot up - SSH will now be automatically enabled.
 


Second option
If you're using a newer distro like Raspbian Wheezy, when you first boot up the image you'll be taken to a config screen. From here you'll be able to enable SSH (along with a number of other useful options!).



Connecting via SSH
As mentioned above, to be able to connect into the Pi using VNC you first need to start the VNC server, and without a display connected you need to start this remotely.  SSH provides this mechanism.  To start with, we take our SSH Client - PuTTY.  Once you've downloaded it, simply launch it - it's a standalone exe - you'll be presented with this screen:

Simply type in Raspberry Pi IP Address in the Host Name field that you found earlier and click open.  Once Putty has connected to the SSH process running on the Pi, a terminal window will pop up and you'll be prompted with a login.  

I still have my UN & PW set to pi and raspberry, so just typed that in.  Once logged in I'm taken to the standard terminal prompt.  From here you can run pretty much any command you want on the Raspberry Pi.

Setting up VNC Server via SSH
Now that you're connected, you need to start the VNC server.  If this is the first time you're doing this, you'll also need to install VNC first.  I've assumed you'll have internet access as this will be required to install this.  To do this, run the following command:
sudo apt-get install tightvncserver

As mentioned above, the Putty SSH Client lets you run commands on your Pi directly, so by doing this you're installing a VNC application on your Pi.

NOTE: during the install you'll be prompted to install without verification - type y here. 

Once installed, you'll need to start the VNC server.  The command I've used here is vncserver :1 -geometry 1280x800 -depth 16 -pixelformat rgb565:

This will start the VNC server process on the Pi.  What this means is that it will start a virtual X session (a virtual instance of the Raspberry Pi GUI) on your Pi, in a very similar way to when you run startx when your Pi is connected to a display.  When you VNC into your Pi you will be connecting to this X session.

So - the important port of this command is :1.  This defines the port that the VNC process will be started on - you can make this whatever you want, but will need to remember it to ensure you connect to the right port.  You'll see more details on this below.  As for the resolution (-geometry) this will be the resolution that the X session will run under - you can make this pretty much whatever you want 

The first time you launch VNCServer you'll be prompted for a password - you'll need this to connect in using VNC.

You'll also be asked for a view-only password (optional).  When providing the password via VNC the remote use will only have read-only access to the Raspberry Pi:


Connecting via UltraVNC 
Once VNC server has been started the only thing left to do is connect.  Start up UltraVNC, type in the IP Address (or machine name) with a port of 1 and connect.  
NOTE:  This port is the port you used when starting the VNC process above:

And that's it - connected!


EDIT 06/05/2012: I've found out there are two potential desktops you might see, and this is determined by the user that launches vncserver (or startx for that matter).  Using sudo will give you the LXDE desktop above.  Launching it without sudo will give the intended Raspberry Pi desktop as shown below.
 


'Linux > RaspberryPi' 카테고리의 다른 글

Raspberry Pi – Enabling Telnet  (0) 2015.06.29
Raspberry Pi에서 Java 설치하기!  (0) 2015.06.25
시작시 Auto running programs  (0) 2015.01.03
(cpp)wiringpi활용  (0) 2015.01.03
(python)GPIO 끄기: GPIO cleanup()  (0) 2015.01.03

Auto running applications in the GUI

See here 

Auto running terminal applications (non GUI)

First ensure your program is executable by finding it in the file manager.  Right click on the file and select properties.  Select the permissions tab, check the ‘Make the file executable’ box and press OK.  Or from the command line use:


sudo chmod +x /home/pi/projects/my_project.a

Or using a different tool set its chmod to 755 (rwxr-xr-x).  It doesn't matter if the user is root.

Doesn't work?

We've found that when copying a new file to the rpi using WinSCP, changing its properties to 755 and verifying all is OK that if we kill the power and power up again the executable doesn't run.  However if we use sudo reboot at the command line it works as it should.  It seems there is some sort of caching action going on so after doing this use sudo reboot the first time rather than cycling the power!

You can setup the auto run using a script (see here), or you can do it directly by editing the rc.local file:


sudo nano /etc/rc.local

 

After the initial comments (lines beginning with '#') add the following lines:


# Auto run our application
sudo /home/pi/projects/my_project.a &

"sudo" assumes you want your application run with root user privileges (remove if not) and the "&" says do it in the background.

Save it by pressing Ctrl+X, " Y", ENTER

Re-boot your RPi and it will run.

To kill the program

If you need to kill your program running in the background you can use this


sudo killall my_project.a

 

Running multiple things and also programs as a non root user

You can use brackets around multiple commands each separated by a ';' followed by the '&' to run the set of commands all in the background.

If you use the '&' you can also run multiple lines as each is run in the background.

Finally, by default rc.local runs as the root user.  You can change to a different user using su – USERNAME -c before the command and surrounding it with quotes.

In the example below the following occurs:

After a 2 second pause my_project.a us run in the background.

After a 5 second delay VLC is started to stream the raspberry pi video camera.  VLC won't run as the root user so su -c is used to make it run as the user "pi"


#Auto run our application
(sleep 2;sudo /home/pi/projects/my_project/my_project.a)&
#Auto run VLC video streaming
(sleep 5;su - pi -c "raspivid -o - -t 0 -n -w 640 -h 480 -fps 15 | cvlc -vvv stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8554/}' :demux=h264")&

 


'Linux > RaspberryPi' 카테고리의 다른 글

Raspberry Pi에서 Java 설치하기!  (0) 2015.06.25
Setting Up VNC  (0) 2015.06.24
(cpp)wiringpi활용  (0) 2015.01.03
(python)GPIO 끄기: GPIO cleanup()  (0) 2015.01.03
RaspberryPi GPIO+WiringPi  (0) 2014.12.30

Functions (API)

Some of the functions in the WiringPi library are designed to mimic those in the Arduino Wiring system. There are relatively easy to use and should present no problems for anyone used to the Arduino system, or C programming in-general.

The main difference is that unlike the Arduino system, the main loop of the program is not provided for you – you need to write it yourself. This is often desirable in a Linux system anyway as it can give you access to command-line arguments and so on. See the examplespage for some simple examples and a Makefile to use.

Before using the WiringPi library, you need to include its header file:

#include <wiringPi.h>

You may also need to add

-I/usr/local/include -L/usr/local/lib -lwiringPi

to the compile line of your program depending on the environment you are using. The important one is -lwiringPi

Setup Functions

There are three ways to initialise wiringPi.

  • int wiringPiSetup (void) ;
  • int wiringPiSetupGpio (void) ;
  • int wiringPiSetupSys (void) ;

One of the setup functions must be called at the start of your program. If it returns -1 then the initialisation of the GPIO has failed, and you should consult the global errno to see why.

The differences between the setup functions are as follows:

  • wiringPiSetup(void) ;

This initialises the wiringPi system and assumes that the calling program is going to be using the wiringPi pin numbering scheme. This is a simplified numbering scheme which provides a mapping from virtual pin numbers 0 through 16 to the real underlying Broadcom GPIO pin numbers. See the pins page for a table which maps the wiringPi pin number to the Broadcom GPIO pin number to the physical location on the edge connector.

This function needs to be called with root privileges.

  • wiringPiSetupGpio(void) ;

This is identical to above, however it allows the calling programs to use the Broadcom GPIO pin numbers directly with no re-mapping.

As above, this function need to be called with root priveledges

  • wiringPiSetupSys(void)

This initialises the wiringPi system but uses the /sys/class/gpio interface rather than accessing the hardware directly. This can be called as a non-root user provided the GPIO pins have been exported before-hand using the gpio program. Pin number in this mode is the native Broadcom GPIO numbers.

Note: In this mode you can only use the pins which have been exported via the /sys/class/gpio interface. You must export these pins before you call your program. You can do this in a separate shell-script, or by using the system() function from inside your program.

Also note that some functions (noted below) have no effect when using this mode as they’re not currently possible to action unless called with root privileges.

General wiring functions

  • void pinMode (int pin, int mode) ;

This sets the mode of a pin to either INPUTOUTPUT, or PWM_OUTPUT. Note that onlywiringPi pin 1 (BCM_GPIO 18) supports PWM output. The pin number is the number obtained from the pins table.

This function has no effect when in Sys mode.

  • void digitalWrite (int pin, int value) ;

Writes the value HIGH or LOW (1 or 0) to the given pin which must have been previously set as an output.

  • void digitalWriteByte (int value) ;

This writes the 8-bit byte supplied to the 8 GPIO pins. It’s the fastest way to set all 8 bits at once to a particular value, although it still takes twi write operations to the GPIO hardware.

  • void pwmWrite (int pin, int value) ;

Writes the value to the PWM register for the given pin. The value must be between 0 and 1024. (Again, note that only pin 1 (BCM_GPIO 18) supports PWM)

This function has no effect when in Sys mode (see above)

  • int digitalRead (int pin) ;

This function returns the value read at the given pin. It will be HIGH or LOW (1 or 0) depending on the logic level at the pin.

  • void pullUpDnControl (int pin, int pud) ;

This sets the pull-up or pull-down resistor mode on the given pin, which should be set as an input. Unlike the Arduino, the BCM2835 has both pull-up an down internal resistors. The parameter pud should be; PUD_OFF, (no pull up/down), PUD_DOWN (pull to ground) orPUD_UP (pull to 3.3v)

This function has no effect when in Sys mode. If you need to activate a pull-up/pull-down, then you can do it with the gpio program in a script before you start your program.

PWM Control

PWM can not be controlled when running in Sys mode.

  • pwmSetMode (int mode) ;

The PWM generator can run in 2 modes – “balanced” and “mark:space”. The mark:space mode is traditional, however the default mode in the Pi is “balanced”. You can switch modes by supplying the parameter: PWM_MODE_BAL or PWM_MODE_MS.

  • pwmSetRange (unsigned int range) ;

This sets the range register in the PWM generator. The default is 1024.

  • pwmSetClock (int divisor) ;

This sets the divisor for the PWM clock.

To understand more about the PWM system, you’ll need to read the Broadcom ARM peripherals manual.

Timing functions

  • unsigned int millis (void)

This returns a number representing the number if milliseconds since your program called one of the wiringPiSetup functions. It returns an unsigned 32-bit number which wraps after 49 days.

  • void delay (unsigned int howLong)

This causes program execution to pause for at least howLong milliseconds. Due to the multi-tasking nature of Linux it could be longer. Note that the maximum delay is an unsigned 32-bit integer or approximately 49 days.

  • void delayMicroseconds (unsigned int howLong)

This causes program execution to pause for at least howLong microseconds. Due to the multi-tasking nature of Linux it could be longer. Note that the maximum delay is an unsigned 32-bit integer microseconds or approximately 71 minutes.

Program/Thread Priority

  • int piHiPri (int priority) ;

This attempts to shift your program (or thread in a multi-threaded program) to a higher priority and enables a real-time scheduling. The priority parameter should be from 0 (the default) to 99 (the maximum). This won’t make your program go any faster, but it will give it a bigger slice of time when other programs are running. The priority parameter works relative to others – so you can make one program priority 1 and another priority 2 and it will have the same effect as setting one to 10 and the other to 90 (as long as no other programs are running with elevated priorities)

The return value is 0 for success and -1 for error. If an error is returned, the program should then consult the errno global variable, as per the usual conventions.

Note: Only programs running as root can change their priority. If called from a non-root program then nothing happens.

Interrupts

With a newer kernel patched with the GPIO interrupt handling code, (ie. any kernel after about June 2012), you can now wait for an interrupt in your program. This frees up the processor to do other tasks while you’re waiting for that interrupt. The GPIO can be set to interrupt on a rising, falling or both edges of the incoming signal.

Note: Jan 2013: The waitForInterrupt() function is deprecated – you should use the newer and easier to use wiringPiISR() function below.

  • int waitForInterrupt (int pin, int timeOut) ;

When called, it will wait for an interrupt event to happen on that pin and your program will be stalled. The timeOut parameter is given in milliseconds, or can be -1 which means to wait forever.

The return value is -1 if an error occurred (and errno will be set appropriately), 0 if it timed out, or 1 on a successful interrupt event.

Before you call waitForInterrupt, you must first initialise the GPIO pin and at present the only way to do this is to use the gpio program, either in a script, or using the system() call from inside your program.

e.g. We want to wait for a falling-edge interrupt on GPIO pin 0, so to setup the hardware, we need to run:

gpio edge 0 falling

before running the program.

  • int wiringPiISR (int pin, int edgeType,  void (*function)(void)) ;

This function registers a function to received interrupts on the specified pin. The edgeType parameter is either INT_EDGE_FALLINGINT_EDGE_RISINGINT_EDGE_BOTH orINT_EDGE_SETUP. If it is INT_EDGE_SETUP then no initialisation of the pin will happen – it’s assumed that you have already setup the pin elsewhere (e.g. with the gpio program), but if you specify one of the other types, then the pin will be exported and initialised as specified. This is accomplished via a suitable call to the gpio utility program, so it need to be available.

The pin number is supplied in the current mode – native wiringPi, BCM_GPIO or Sys modes.

This function will work in any mode, and does not need root privileges to work.

The function will be called when the interrupt triggers. When it is triggered, it’s cleared in the dispatcher before calling your function, so if a subsequent interrupt fires before you finish your handler, then it won’t be missed. (However it can only track one more interrupt, if more than one interrupt fires while one is being handled then they will be ignored)

This function is run at a high priority (if the program is run using sudo, or as root) and executes concurrently with the main program. It has full access to all the global variables, open file handles and so on.

See the isr.c example program for more details on how to use this feature.

Concurrent Processing (multi-threading)

wiringPi has a simplified interface to the Linux implementation of Posix threads, as well as a (simplified) mechanisms to access mutex’s (Mutual exclusions)

Using these functions you can create a new process (a function inside your main program) which runs concurrently with your main program and using the mutex mechanisms, safely pass variables between them.

  • int piThreadCreate (name) ;

This function creates a thread which is another function in your program previously declared using the PI_THREAD declaration. This function is then run concurrently with your main program. An example may be to have this function wait for an interrupt while your program carries on doing other tasks. The thread can indicate an event, or action by using global variables to communicate back to the main program, or other threads.

Thread functions are declared as follows:

PI_THREAD (myThread)
{
  .. code here to run concurrently with
        the main program, probably in an
        infinite loop
}

and would be started in the main program with:

x = piThreadCreate (myThread) ;
if (x != 0)
  printf ("it didn't start\n")

This is really nothing more than a simplified interface to the Posix threads mechanism that Linux supports. See the manual pages on Posix threads (man pthread) if you need more control over them.

  • piLock (int keyNum) ;
  • piUnlock (int keyNum) ;

These allow you to synchronise variable updates from your main program to any threads running in your program. keyNum is a number from 0 to 3 and represents a “key”. When another process tries to lock the same key, it will be stalled until the first process has unlocked the same key.

You may need to use these functions to ensure that you get valid data when exchanging data between your main program and a thread – otherwise it’s possible that the thread could wake-up halfway during your data copy and change the data – so the data you end up copying is incomplete, or invalid. See the wfi.c program in the examples directory for an example.

Misc. Functions

  • piBoardRev (void) ;

This returns the board revision of the Raspberry Pi. It will be either 1 or 2. Some of the BCM_GPIO pins changed number and function when moving from board revision 1 to 2, so if you are using BCM_GPIO pin numbers, then you need to be aware of the differences.

  • wpiPinToGpio (int wPiPin) ;

This returns the BCM_GPIO pin number of the supplied wiringPi pin. It takes the board revision into account.

  • setPadDrive (int group, int value) ;

This sets the “strength” of the pad drivers for a particular group of pins. There are 3 groups of pins and the drive strength is from 0 to 7. Do not use this unless you know what you are doing.


+ Recent posts