I am totally new to C++ programming on gcc. I wanted to add color to my text on the output on the console. Since there is no conio.h on linux, I researched and found that ncurses.h could do the trick. Now the only problem is that I do not know how to download it and then add the library. Can someone please describe the method?

Also, if anybody can describe whether ncurses.h is a better option than curses.h or if I am completely wrong in using curses.h?

shareimprove this question

on ubuntu:

install ncurses library (packages for developers has "-dev" postfix)

sudo apt-get install libncurses5-dev

for each package, in /usr/share/doc/{package name}/ you can find documentation.

Open this URL file:///usr/share/doc/libncurses5-dev/html/index.html in your browser.

Have fun.

shareimprove this answer


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.


led는 안다리가 짧은게 vcc

'Hardware' 카테고리의 다른 글

SPI(Serial Peripheral Interface Bus)  (0) 2015.08.04
I2C(Inter Integrated Circuit)  (0) 2015.08.04
UART란?  (0) 2015.08.04
How to Build an 8-Bit Computer by spel3o  (0) 2015.03.14
간단한 레귤레이터 만들기 11V->5V  (0) 2014.12.30
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!




'Hardware' 카테고리의 다른 글

SPI(Serial Peripheral Interface Bus)  (0) 2015.08.04
I2C(Inter Integrated Circuit)  (0) 2015.08.04
UART란?  (0) 2015.08.04
How to Build an 8-Bit Computer by spel3o  (0) 2015.03.14
led는 안다리가 짧은게 vcc  (0) 2015.01.03

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

Tutorial - How to give your Raspberry Pi a Static IP Address

July 19, 2013

Tutorial - How to Give your Raspberry Pi a Static IP Address
 
To log in to your Raspberry Pi remotely, you'll need the IP of the Raspberry Pi – this is basically like your house address and tells the host computer where to look for it on the network. By default, the Raspberry Pi will be given an IP automatically by the router (called Dynamic IP and denoted by DHCP) when you connect to a network. However, this can change whenever you remove the Pi from the network e.g. turn it off.
 
Having a static IP isn't essential, however it will make repeated access to the Raspberry Pi via SSH much simpler, as you'll always know that the Raspberry Pi has the same address. Imagine how much trouble your postman would have if your house constantly changed location :)
 
This task assumes that you have the official Raspian OS release installed. This is available in the NOOBS distribution and can be downloaded from http://www.raspberrypi.org/downloads. This guide also assumes that you've connected your Pi to a network via Ethernet. If you're going to be logging into your Pi remotely for most tasks, then I recommend it's easiest and fastest to plonk it next to your router, and use ethernet to access the internet anway!
 
A. Checking Set Up
 
Boot into Raspian and log in (Username. pi, Password. raspberry), this will all be command line stuff, so no need to log in to the GUI.
 
First, we need to list the network interface we currently have available:
 
cat /etc/network/interfaces
 
 
The line . . . . 
 
iface eth0 inet dhcp
 
Implies that we're currently getting out IP address via DHCP, meaning it's being dynamically registered by the router. This is what we want to change!
 
B. Gathering Information
 
Fist of all we need to grab some information from our router and Pi. There's a couple of command we need to run to get this info. Have a pen and paper handy! . . . 
 
ifconfig
 
 
This reveals your router information, the bit you want is after eth0 (the ethernet connection). . . .
 
eth0      Link encap:Ethernet  HWaddr b8:27:eb:b3:fc:2c
               inet addr:192.168.1.81  Bcast:192.168.1.255  Mask:255.255.255.0
 
Write down the following information. . .
 
inet addr – 192.168.1.81 (Pi's Current IP Address)
Bcast –  192.168.1.255 (The Broadcast IP Range)
Mask –  255.255.255.0 (Subnet Mask Address)
 
We need a little more information before we proceed. Use the command. . . 
 
netstat -nr
(route -n will give you the same info.)
 
 
We need:
 
'Gateway' Address – 192.168.1.254
'Destination' Address – 192.168.1.0
 
C. Editing Network Configuration
 
We now need to plug this information into the Pi's network configuration file using a text editor. I always use nano text editor. . . 
 
sudo nano /etc/network/interfaces
 
 
Simply change the line that reads:
 
iface eth0 inet dhcp
 
to
 
iface eth0 inet static
 
Then directly below this line enter the following (Please Note. You will need your own addresses we gathered in Part B, more details below). . . . 
 
address 192.168.1.81
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.254
 
To clarify what each part means. . . . 
 
address – The address you want to give your Pi, this can be any IP in the network range, but it's usually advisable to go higher rather than lower, or you could end up logging different devices to the same IP! I've selected 192.168.1.81, as we're already registered to that address (denoted by 'inet addr'), but this can be any IP address from the range192.168.1.1 to 192.168.1.255.
 
netmask – The 'Mask' address we wrote down earlier.
 
network – The router IP address, this is the 'Destination' Address was found earlier. You can also grab this off your router, it will say on the side somewhere.
 
broadcast – The 'Bcast' address we wrote down earlier. 
 
gateway – This is the 'Gateway' address we found earlier.
 
 
So, it should look something like the above, but with your values! Remember to save before exit, CTRL+X (exit) then yes to save changes!
 
D. Re-check Static IP Configuration
 
Then we'll need to reboot and check your changes. . . 
 
sudo reboot
 
Log back in and run 
 
ifconfig
 
Which should reveal your new settings. . 
 
 
To double checks all is working as it should, ping your 'Gateway' Address. . . 
 
ping 192.168.1.254 -c 10
 
(the -c 10 command simply denotes that you want to ping it 10 times, if you forget to add this, it will ping the address continuosly. To stop it press CTRL+C)
 
 
This should ping successfully and all packets should be recieved. If something's not right double check through all your IP addresses, and make sure you're pinging the right address too. Remember you can always revert back to DHCP by reversing the steps. The 'network' router IP address is sometimes a little fiddly, so check that if you're still having issues!
 
Hopefully however, your Raspberry Pi is now set up with a static IP address!

 

출처 : https://www.modmypi.com/blog/tutorial-how-to-give-your-raspberry-pi-a-static-ip-address 

A big part of Raspberry Pi's usefulness comes from its size. A lot of those benefits get lost when you need an external display and keyboard (and mouse maybe) to actually do anything with it. In this post I'll quickly cover how you can set up your Raspberry Pi (A, but B would work too, it'd actually be a little bit easier) to automatically connect to your wireless network and obtain a static IP. All you need is a WiFi-dongle.

Because the Raspberry Pi A only has one USB-port, there'll be a lot of USB switching.

Setting up WiFi connection

Start by booting the Raspberry Pi, connected to a display and a keyboard. Open up the terminal and edit the network interfaces file:

$ sudo nano /etc/network/interfaces

This file contains all known network interfaces, it'll probably have a line or two in there already.

Change the first line (or add it if it's not there) to:

auto wlan0

Then at the bottom of the file, add these lines telling the Raspberry Pi to allow wlan as a network connection method and use the/etc/wpa_supplicant/wpa_supplicant.conf as your configuration file.

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

(ctrl-X, then type Y to quit and save)

The next step is to create this configuration file.

Configuring WiFi connection

Open up the wpa_supplicant.conf file in the editor.

$ sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

Again, some lines might already be present, just add the following.

network={
ssid="YOUR_NETWORK_NAME"
psk="YOUR_NETWORK_PASSWORD"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
}

The other parameters are network specific, I can't tell you what you need. If you boot Raspbian to desktop, you can launc the wpa_gui (WiFi config) application and click 'Scan'. You'll find a list that has your network too with all flags you need. To do this on a RPi A you'll have to disconnect your keyboard and connect your dongle once the scanning list is open.

  • proto could be either RSN (WPA2) or WPA (WPA1).
  • key_mgmt could be either WPA-PSK (most probably) or WPA-EAP(enterprise networks)
  • pairwise could be either CCMP (WPA2) or TKIP (WPA1)
  • auth_alg is most probably OPEN, other options are LEAP and SHARED

Make sure it works

Reboot the Raspberry Pi and it should connect to the wireless network. If it doesn't, repeat above steps or get help from an adult.

A static IP

Since the goal of this tutorial is to be able to work with the RPi without external keyboard or display, you want to be ssh into it. The best way is to make sure it'll always have a static IP on your network.

Doing so is simple. Open the /etc/network/interfaces file again and add the following changes:

Change iface wlan0 inet dhcp into iface wlan0 inet static. This changes the wlan0 interface from DHCP to static.

Add the following lines before the wpa-conf line:

address 192.168.1.155 # Static IP you want 
netmask 255.255.255.0
gateway 192.168.1.1 # IP of your router

The Raspberry Pi will still be able to connect to the internet.

Wrapping up

With these changes you'll be able to always connect to your Raspberry Pi over your wireless network via ssh at the same, static IP. This means you can disconnect keyboard, mouse and display and have it plugged in a wall socket, anywhere, taking almost no space.

As an overview, my interfaces- and wpa_supplicant-files:

1234567891011121314
# /etc/network/interfaces
 
auto wlan0
 
iface lo inet loopback
iface eth0 inet dhcp
 
allow-hotplug wlan0
iface wlan0 inet static
address 192.168.1.155
netmask 255.255.255.0
gateway 192.168.1.1
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
12345678910111213
# /etc/wpa_supplicant/wpa_supplicant.conf
 
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
 
network={
ssid="NYO_WWWP"
psk="topsecret"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
}
Written by Pieter Beulque


+ Recent posts