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

   퍼미션(권한)이란?

Owner

Group

Other

Owner와 Group은 파일소유자자신과 자신이 속한그룹. Other은 제3자, 웹사이트 방문객은 제3자로 nobody로 취급.

r

w

x

r

w

x

r

w

x

r은 파일 읽기(4), w는 파일 쓰기(2), x는 파일 실행(1)

7

5

5

파일소유자는 그것을 읽고 쓰고 실행시킬 수 있지만, 제3자는 읽고 실행만 시킬 수 있다.

7

7

7

제3자도 쓰기 권한이 주어진다.

*.html  *.cgi, *.pl *.txt등의 파일은 업로드시 반드시 ascii로 하고 나머지 그림(*.gif *.jpg)이나 자바 애플릿(*.class), 실행파일(*.exe *.zip *.rar)등은 binary mode로 업로드 할 것.

   리눅스 기본명령어

명령어

사 용 법

login

사용자 인증과정

리눅스 시스템은 기본적으로 multi-user 개념에서 시작하였기 때문에 시스템을 이용하기 위해서는 반드시 로그인을 하여야 합니 다. 로그인은 PC 통신에서도 많이 사용되어져 왔기 때문에 그 개 념  설정에 그다지 어려움이 없을 것입니다. 흔히 말하는 ID를 입력하는 과정입니다. 

passwd

패스워드 변경

리눅스, 특히 인터넷의 세계에서는 일반 컴퓨팅 상황에 비하여 훨씬 해킹에 대한 위험이 높습니다. 패스워드는 완성된 단어 보다는 단어 중간에 숫자나 키보드의 ^, #, ' 등과 같은 쉽게 연상 할 수 없는 기호를 삽입하여 만들어 주는 것이 좋습니다

du

하드사용량 체크(chkdsk)

자신의 하드공간을 알려면
# du
특정 디렉토리의 사용량을 알려면
# du -s diretory_name

ls

파일 리스트 보기(dir)

F : 파일 유형을 나타내는 기호를 파일명 끝에 표시
    (디렉토리는 '/', 실행파일은 '*', 심볼릭 링크는 '@'가 나타남).
l  : 파일에 관한 상세 정보를 나타냅니다.
a : dot 파일(.access 등)을 포함한 모든 파일 표시.
t  : 파일이 생성된 시간별로 표시
C : 도스의 dir/w명령과 같 이 한줄에 여러개의 정보를 표시
R : 도스의 dir/s 명령과 같이 서브디렉토리 내용까지.

(예)
# ls -al  
# ls -aC
# ls -R

cd

디렉토리를 변경

# cd cgi-bin     : 하부 디렉토리인 cgi-bin으로 들어감.
# cd  ..             : 상위디렉토리로 이동
# cd 또는 cd ~  : 어느곳에서든지 자기 홈디렉토리로 바로 이동
# cd /webker     : 현재 작업중인 디렉토리의 하위나 상위 디렉토리가
                          아닌 다른 디렉토리(webker)로 이동하려면 /로
                          시작해서 경로이름을 입력하면 된다.

cp

화일 복사(copy)

# cp index.html index.old
     : index.html 화일을 index.old 란 이름으로 복사.

# cp /home/test/*.*  .
     : test 디렉토리내의 모든 화일을 현 디렉토리로 복사.

mv

파일이름(rename) / 위치(move)변경

# mv index.htm index.html
     : index.htm 화일을 index.html 로 이름 변경

$ mv file  ../main/new_file
     : 파일의 위치변경

mkdir

디렉토리 생성

# mkdir download  : download 디렉토리 생성

rm

화일삭제

# rm test.html : test.html 화일 삭제
# rm -r <디렉토리> : 디렉토리 전체를 삭제
# rm -i a.*
     : a로 시작하는 모든 파일을 일일이 삭제할 것인지 확인하면서 삭제 

rmdir

디렉토리 삭제

# rmdir cgi-bin : cgi-bin 디렉토리 삭제

pwd

현재의 디렉토리 경로를 보여주기

pico

리눅스용 에디터

put

ftp 상태에서 화일 업로드

> put  guestbook.tar.gz

get

ftp 상태에서 화일 다운로드

> get  guestbook.tar.gz

mput 또는 mget

여러개의 화일을 올리고 내릴때 (put,get과 사용법동일)

chmod

화일 permission 변경

리눅스에서는 각 화일과 디렉토리에 사용권한을 부여.

예) -rwxr-xr-x   guestbookt.html
rwx  :처음 3개 문자 = 사용자 자신의 사용 권한
r-x  :그다음 3개 문자 = 그룹 사용자의 사용 권한
r-x  :마지막 3개 문자 = 전체 사용자의 사용 권한

읽기(read)---------- 화일 읽기 권한
쓰기(write)---------- 화일 쓰기 권한
실행(execution)---------- 화일 실행 권한
없음(-)---------- 사용권한 없음

명령어 사용법
chmod [변경모드] [파일]

# chmod 666  guestbook.html
     : test.html 화일을 자신에게만 r,w,x 권한을 줌

# chmod 766  guestbook.html
     : 자신은 모든 권한을 그룹사용자와,전체사용자에게는
       읽기와 쓰기 권한만 줌

alias

" doskey alias" 와 비슷하게 이용할 수 있는 쉘 명령어 alias는 말그대로 별명입니다. 사용자는 alias를 이용하여 긴 유 닉스 명령어를 간단하게 줄여서 사용할 수도 있습니다.
이들 앨리어스는 [alias ls 'ls -al'] 같이 사용하시면 되는데, 한 번 지정한 alias를 계속해서 이용하시려면, 자신의 홈디렉토리에 있는
.cshrc(Hidden 속성)을 pico등의 에디터를 이용하여 변경시 키면 됩니다.

cat

파일의 내용을 화면에 출력하거나 파일을 만드는 명령( 도스의 TYPE명령)

# cat filename

more

cat 명령어는 실행을 시키면 한 화면을 넘기는 파일일 경우 그 내용을 모두 볼수가 없다. 하지만 more 명령어를 사용하면 한 화면 단위로 보여줄 수 있어 유용.

# more <옵션>
옵션은 다음과 같습니다.

Space bar : 다음 페이지
Return(enter) key : 다음 줄
v : vi 편집기로 전환
/str : str 문자를 찾음
b : 이전 페이지
q : more 상태를 빠져나감
h : 도움말
= : 현재 line number를 보여줌

who

현재 시스템에 login 하고 있는 사용자의 리스트를 보여줍니다.

# who

whereis

소스, 실행파일, 메뉴얼 등의 위치를 알려줍니다

# whereis perl : perl의 위치를 알려준다

vi,
touch,
cat

새로운 파일을 만드는 방법

# vi newfile :  vi 편집기 상태로 들어감
# touch newfile : 빈 파일만 생성됨
# cat > newfile  : vi 편집기 상태로 들어감, 문서 작성후 Ctrl+D로 빠져나옴

cat,
head,
tail

파일 내용만 보기

# cat filename         : 파일의 내용을 모두 보여줌
# head -n filename : n줄 만큼 위세서부터 보여줌
# tail -n filename     : n줄 만큼 아래에서부터 보여줌

 

   압축명령어 사용법

압축 명령어

사 용 법

tar .tar, _tar로 된 파일을 묶거나 풀때 사용하는 명령어
(압축파일이 아님)

# tar cvf [파일명(.tar, _tar)] 압축할 파일(또는 디렉토리): 묶을때
# tar xvf [파일명(.tar, _tar)]  :  풀 때
   (cf) cvfp/xvfp 로 하면 퍼미션 부동 
compress 확장자 .Z 형태의 압축파일 생성

# compress    [파일명]     : 압축시
# uncompress [파일명]    : 해제시
gzip 확장자  .gz, .z 형태의 압축파일 생성

#  gzip     [파일명]    : 압축시
#  gzip -d [파일명]   : 해제시
기타 .tar.Z
이것은 tar로 묶은 후에 compress를 사용하여 압축한 것으로 uncompress를 사용해서 압축을 푼 다음,
다시 tar를 사용해서 원래의 파일들을 만들어내면 됩니다.
아니면 다음과 같이 한 번에 풀 수도 있다.
# zcat  [파일명].tar.Z  : 해제시

.tar.gz또는 .tar.z
# gzip -cd [파일명]    : 해제시

.tar.gz 또는 .tar.z .tgz
gzip을 사용해서 푼 다음 다시 tar를 사용해서 원래 파일을 만들어 낼 수 있으나,
하지만 다음과 같이 하면 한 번에 처리를 할 수 있다.

# gzip -cd 파일.tar.gz | tar xvf -  또는
# tar xvzf 파일.tar.gz
# tar xvzf 파일.tgz

 

   리눅스 필수명령어

Linux/Unix 명령어

설 명

MS-DOS 비교

./x

x 프로그램 실행
(현재 디렉토리에 있는 것)

x

/

이전에(↑) / 다음에(↓) 입력했던 명령어

doskey

cd x (또는 cd /x)

디렉토리 X로 가기

cd

cd .. (또는 cd ../ 또는 cd /..)

한 디렉토리 위로 가기

cd..

x 다음 [tab] [tab]

x 로 시작하는 모든 명령어 보기

-

adduser

시스템에 사용자 추가

/

ls (또는 dir)

디렉토리 내부 보여주기

dir

cat

터미널 상의 텍스트 파일 보기

type

mv x y

파일 x를 파일 y로 바꾸거나 옮기기

move

cp x y

파일 x를 파일 y로 복사하기

copy

rm x

파일 지우기

del

mkdir x

디렉토리 만들기

md

rmdir x

디렉토리 지우기

rd

rm -r x

디렉토리 x를 지우고 하위도 다 지우기

deltree

rm p

패키지 지우기

-

df (또는 df x)

장치 x의 남은 공간 보여주기

chkdsk ?

top

메모리 상태 보여주기(q는 종료)

mem

man x

명령어 x에 관한 매뉴얼 페이지 얻기

/

less x

 텍스트 파일 x 보기
(리눅스에서는 더 많은 필터 적용 가능)

type x | more

echo

어떤 것을  echo 화면에 인쇄한다.

echo

mc

UNIX를 위한 노턴 커맨더

nc

mount

장치 연결(예: CD-ROM, 연결을 해제하려면 umount)

-

halt

시스템 종료

-

reboot ([ctrl] + [alt] +[del])

시스템  다시 시작하기

[ctrl] + [del] + [del]

    고급명령어

 고급 명령어

 

chmod <권한> <파일>

파일 권한(permissions) 변경

ls -l x

파일 x의 자세한 상황을 보여줌

ln -s x y

 x에서 y로 심볼릭 링크를 만들어 줌

find x -name y -print

디렉토리 x안에서 파일 y를 찾아서 화면에 그 결과를 보여줌

ps

지금 작동중인 모든 프로세스들을 보여줌

kill x

 프로세스 x를 종료 (x는 ps 명령으로 알 게 된 PID)

[alt] + F1 - F7

 터미널 1-7까지 바꾸기 (텍스트 터미널에서; F7은 X-윈도우(시작될때))

lilo

 부트 디스크를 만듦

 

용어

 

symlink

다른 파일이나 디렉토리로 심볼릭 링크. 윈도유98의 바로가기 같은 것

shell script

여러 명령어들을 차례로 수행하게 한 것. MS-DOS의 배치 파일 같은 것

How to uninstall and remove Apache2 on Ubuntu or Debian

It turns out that uninstalling Apache2 web server is not as straightforward as installing it. You will need to remove Apache2 package itself, as well as other dependent packages and its associated configurations. Here is how you remove Apache2 cleanly on Ubuntu and Debian.

The first step is to stop any running instance of Apache2, because Apache2 will not be properly removed while it is running.

$ sudo service apache2 stop

 

Then uninstall Apache2 and its dependent packages. Use purge option instead of remove with apt-get command. The former option will try to remove dependent packages, as well as any configuration files created by them. In addition, use autoremove option as well, to remove any other dependencies that were installed with Apache2, but are no longer used by any other package.

$ sudo apt-get purge apache2 apache2-utils apache2.2-bin apache2-common
$ sudo apt-get autoremove

 

Finally, check if there is any configuration files or manual pages belonging to Apache2, which are still not removed.

$ whereis apache2
apache2: /etc/apache2

In this example, /etc/apache2 directory still exists. Since this directory (as well as any configuration files in it) is no longer necessary, go ahead and remove it manually.

$ sudo rm -rf /etc/apache2

'Linux' 카테고리의 다른 글

how can I add an application to the "open with" menu ubuntu 11.10  (0) 2015.12.29
리눅스 웹 한글깨짐  (0) 2015.10.16
alias를 이용한 단축명령 만들기  (0) 2015.10.11
vim syntax, indent, linenumber 설정  (0) 2015.06.25
Linux commands  (0) 2015.06.24

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.


Jul132013

 

RasPiTV-RPi.GPIO-EXIT

You might think I’m going about this series in a funny way. You’d be right! I am. That’s because I’m trying to highlight the bits that people don’t read about in other tutorials/documentation/manuals/books. These bits are useful, important and often overlooked.

If I covered inputs and outputs first, you might not get to the rest because you’d already “know all I need”. That’s only partially true though. Although you can get away with not knowing or using this stuff, it’s muchbetter and safer if you know it and use it.

So today we’re focussing on how to exit cleanly from a program that uses RPi.GPIO
I know – I’m bonkers! I haven’t even told you how to use RPi.GPIO yet and I’m already showing you how to exit cleanly. Bear with me! It makes sense. You need to know this stuff.

Correct use of GPIO.cleanup()

RPi.GPIO provides a built-in function GPIO.cleanup() to clean up all the ports you’ve used. But be very clear what this does. It only affects any ports you have set in the current program. It resets any ports you have used in this program back to input mode. This prevents damage from, say, a situation where you have a port set HIGH as an output and you accidentally connect it to GND (LOW), which would short-circuit the port and possibly fry it. Inputs can handle either 0V (LOW) or 3.3V (HIGH), so it’s safer to leave ports as inputs.

Here’s a simple example of how to use GPIO.cleanup()

  1. import RPi.GPIO as GPIO  
  2.   
  3. # the rest of your code would go here  
  4.   
  5. # when your code ends, the last line before the program exits would be...  
  6. GPIO.cleanup()  
  7.   
  8. # remember, a program doesn't necessarily exit at the last line!  

If you use this, and the program exits normally, all the ports you’ve used will be cleaned up and ready for use straight away. But life’s not often as simple as that is it? More on that in a minute. First I want to show you…

Incorrect use of GPIO.cleanup()

I have seen people using GPIO.cleanup() wrongly at the start of a program , thinking it will clean up all the ports on the Pi. It does no such thing.1 If you put it at the top of your script, it’s just a wasted line of code. It does nothing until you’ve set up some ports for input or output (which we’re covering soon).

Use GPIO.cleanup() on exit, as I’ve shown above, and in slightly more complex situations, as I will show below…

Reasons for a program exit

There are at least three reasons, that I can think of, for exiting a program…

  1. Natural, controlled end – the program finished doing what it was written to do. Hurrah! It worked :)
  2. Error – something went wrong and the program “throws a wobbly” and “errors out”. Either a process failed in an unforeseen way, or there was a coding error in the program.
  3. Keyboard Interrupt – you pressed CTRL+C to stop the program. This is called a Keyboard Interrupt.

Both 2 & 3 are types of “exceptions”.

So what?

The problem is that, unless you code for these situations, any ports which are in use at the time of an error or Keyboard Interrupt will stay set exactly as they were, even after the program exits.

That’s an out of control situation – unacceptable, when you’re trying to take over the world with GPIO programming! Everything has to be under control.

If you then try to run the program again, when you try to set up the ports that are “still set” you’ll get warnings that the ports are “already in use”.

Switch off the warnings?

You can switch off the warnings, but that’s the “chicken’s way out”. It hides the problem, but doesn’t solve it. Still, you may choose to do it, so here’s how you do. Just place…

GPIO.setwarnings(False)

…near the top of your script, before you start setting up any ports.

Let’s try: a better way

My preferred method to catch errors and Keyboard Interrupts uses a try: except: block.
If you put your main piece of code in a try: block, it won’t “bomb straight out” of the program if an exception occurs (something doesn’t go according to plan).

You can specify different types of exceptions, including KeyboardInterrupt, and/or have a general one to catch every exception. There’s a list of Python Exceptions here . I’ve only ever used a couple of them.

Have a look at the code below to see how the exceptions are coded…

  1. import RPi.GPIO as GPIO  
  2.   
  3. # here you would put all your code for setting up GPIO,  
  4. # we'll cover that tomorrow  
  5. # initial values of variables etc...  
  6. counter = 0  
  7.   
  8. try:  
  9.     # here you put your main loop or block of code  
  10.     while counter < 9000000:  
  11.         # count up to 9000000 - takes ~20s  
  12.         counter += 1  
  13.     print "Target reached: %d" % counter  
  14.   
  15. except KeyboardInterrupt:  
  16.     # here you put any code you want to run before the program   
  17.     # exits when you press CTRL+C  
  18.     print "\n", counter # print value of counter  
  19.   
  20. except:  
  21.     # this catches ALL other exceptions including errors.  
  22.     # You won't get any error messages for debugging  
  23.     # so only use it once your code is working  
  24.     print "Other error or exception occurred!"  
  25.   
  26. finally:  
  27.     GPIO.cleanup() # this ensures a clean exit  

If you let the program run for ~22 seconds, it will count up to 9 million, tell you it reached its target, clean up any GPIO ports you've used and exit normally. This is the code within the try: block (lines 8-13).

The code in the except KeyboardInterrupt: block (lines 15-18) covers the CTRL+C situation. So when you press CTRL+C, it prints the current value of counter, cleans up any GPIO ports you've used, and exits.

The code in the except: block (lines 20-24) covers all other exceptions - including program errors. So if another exeption occurs, it warns you, cleans up any GPIO ports you've used, and exits.

This program will run until it finishes, or a keyboard interrupt or other exception occurs. Whichever of these occurs, the finally:block (lines 26-27) will run, cleaning up the GPIO ports on exit.

Also note, that we haven't actually used any GPIO ports here, so the cleanup isn't really doing anything yet, but this is a template you can use when we do start using ports.

If you want to try it out, it's a bit long for a live Python session, so you could retype it, or cut and paste it into a program as we did in the first post in this series...

Now you know how to exit an RPi.GPIO program cleanly, without leaving a trail of uncontrolled ports behind you.

That's about it for the preliminaries

So now we've covered...

  1. How to check what RPi.GPIO version you have
  2. How to check what Pi board Revision you have
  3. How to Exit GPIO programs cleanly, avoid warnings and protect your Pi

What next?

Tomorrow, we're actually going to set up the GPIO, talk about different pin/port numbering schemes and take a look at reading inputs.


 
_____________________________
1 If it did clean up all the ports, this would mean you could have major conflicts between different programs, which might not even be trying to use the same ports. Clearly, not a desirable situation!


Raspberry Pi Model B+ GPIO Header Pin-out

gpio1


Raspberry Pi Model B+ GPIO Header Pin-out

모터드리아버:모 / 라즈베리파이:라



모1:라19

모2:라21

모3:라16

모4:라18


모9:라VCC

모10:라GND


'Linux > 공순이 project' 카테고리의 다른 글

스템모터를 C언어로 stepping.c  (0) 2014.12.30

#include <stdio.h>
#include <wiringPi.h>

#define OUT1 12      //BCN_GPIO 10
#define OUT2 13      //BCM_GPIO 9
#define OUT3 4       //BCM_GPIO 23
#define OUT4 5       //BCM_GPIO 24

void setsteps(int w1, int w2, int w3, int w4)
    {
         pinMode(OUT1,OUTPUT);
         digitalWrite(OUT1,w1);
         pinMode(OUT2,OUTPUT);
         digitalWrite(OUT2,w2);
         pinMode(OUT3,OUTPUT);
         digitalWrite(OUT3,w3);
         pinMode(OUT4,OUTPUT);
         digitalWrite(OUT4,w4);
     }

 void forward (int del,int steps)
     {
          int i;
          for(i=0;i<=steps;i++)
          {
                  setsteps(1,1,0,0);
                  delay(del);
                  setsteps(0,1,1,0);
                  delay(del);
                  setsteps(0,0,1,1);
                  delay(del);
                  setsteps(1,0,0,1);
                  delay(del);
          }
      }

void backward (int del,int steps)
      {
           int k;
           for(k=0;k<=steps;k++)
           {
                   setsteps(1,0,0,1);
                   delay(del);
                   setsteps(0,0,1,1);
                   delay(del);
                   setsteps(0,1,1,0);
                   delay(del);
                   setsteps(1,1,0,0);
                   delay(del);
           }
      }

int main(void)
{
    if(wiringPiSetup() == -1)
    return 1;

        for(;;)
        {
            forward(5,10);
          //  delay(1000);
          //  backward(50,10);
          //  delay(1000);
          }

    return 0;
}

 

'Linux > 공순이 project' 카테고리의 다른 글

스텝모터 드라이버 설명  (0) 2014.12.30

+ Recent posts