
_Raspberry Pi Insider Guide: From Beginner to Expert_

By Bruce Smith

Smashwords Edition

Copyright 2015 Bruce Smith

**Smashwords Edition, License Notes**

This ebook is licensed for your personal enyoyment only. This ebook may not be re-sold or given away to other people. If you would like to share this book with another person, please purchase an additional copy for each recipient. If you're reading this book and did not purchase it, or it was not purchased for your use only, then please return to Smashwords.com or your favourite retailer and purchase your own copy. Thank you for respecting the hard work of this author.
Read Me!

About this eBook

This is a free-flow eBook. As such the on-screen formatting is almost totally decided by your eBook reader default settings.

This may be important in chapters such as those in _Section Four: Programming_ where the formatting of programs is critical, especially Python (Chapter 19). You are therefore encouraged to download the program files from the website (see Companion Website section below) and view these in the appropriate editor for the language (explained in the corresponding chapter) and refer to them whilst reading the text.

Please remember, if you have an early generation eReader, you can obtain free eReading devices for use on PCs and Macs which are capable of rendering the formats used in this book if they do not display as intended on your particular eReader.

About the Author

Bruce Smith purchased his first computer — an Acorn Atom — in 1980. He was immediately hooked, becoming a regular contributor to the mainstream computer press, including 'Computing Today' and 'Personal Computer World'. With the arrival of the BBC Micro his magazine work expanded into books and his 1982 title 'Interfacing Projects for the BBC Micro' (published by Addison Wesley) has become regarded as a classic of the time, as the first book showing home users how to connect the computer to the outside world. He was one of the first to write about the ARM chip when it was released on the Acorn Archimedes in 1987.

Well over 100 books later Bruce has written about all aspects of computer use. His friendly, lucid style of writing caused one reviewer to write, 'This is the first computer book I have read in bed for pleasure rather than to cure insomnia!' Bruce's books have been translated into many languages and sold across the world.

Bruce also writes about sport and his publishers have included BBC Books, Virgin Books, Rough Guides, Headline and Mainstream Publishing. He has been a regular contributor for BBC local and national radio and has appeared on Channel 4's The Big Breakfast and BBC World Service.

Follow Bruce on Twitter: @brucefsmith or Facebook: authorbrucesmith and check out his occasional blog Alan Turing Rocks which can be found on the website.

Errata

No book is perfect and I doubt this one is either. Whilst we have tried as hard as possible to ensure that this book is as accurate as possible before going to press, because of its technical and complex nature errors may exist. Thankfully due to the world of digital media they can be rectified and corrections implemented quickly. If you think something isn't quite right then please visit the book errata page at www.brucesmith.info. Click on the book icon and locate the link to the errata page — you will be able to see if any issues are already known. If you do not see something covered and feel that you may have discovered an error or anomaly then please email me directly via the Contacts Page on my website. That way I can confirm or otherwise and if the former is the case, provide you with an acknowledgment and make the change.

Companion Website

Go to www.brucesmith.info and locate the page for _Raspberry Pi Insider Guide_. Here you will find links to additional resources in support of the book. This includes additional reading material, examples from the book — including programs — and direct links to websites of places mentioned in the book, plus others you might also find interesting.

Second Edition

This book has been updated and revised to include coverage of the 24 December 2014 release of Raspbian. This release made numerous aesthetic changes to the way the Desktop (detailed in Chapter 8) looked and how certain options were accessed by the user. Functionally, in terms of software operation, little changed. The original Chapter 8, as well as the new revised Chapter 8, are included in this eBook.
SECTION ONE: IN THE BEGINNING

There's a first time for everyone, at everything, and learning to use a microcomputer is no different. In these early chapters you'll learn how to make your small investment come to life and make it ready for the exciting things that lie ahead. The skills you'll learn here will provide you with a perfect foundation for things to come.

The _Insider_ skills you'll have at the end of this section will enable you to:

  * understand what you can use the Raspberry Pi for and gain some insight into what your own goals and targets might be.
  * be clear about the difference between hardware and software.
  * know and understand the basic items you will need to get your Raspberry Pi working.
  * understand the purpose and function of the Raspberry Pi components.
  * be able to choose and download the Raspbian Operating System.
  * confidently plug together your components to create a working Raspberry Pi

1: Welcome Home

You have or are about to get a Raspberry Pi, awesome! You are about to embark on an amazing journey of exploitation and enlightenment. The Raspberry Pi opens up a world of possibilities — and in this chapter learn about just some of the things you could be doing with your Raspberry Pi very quickly.

_'Taking you from beginner to expert'_. That statement is on the cover of this book. It's quite a bold one, but it's well intentioned and readily achievable by _you_. The definition I'm using for expert is: _'A person who is very knowledgeable about or skilful in a particular area.'_

So, after reading this book you won't know everything there is but you'll have enough knowledge to be very confident with your Raspberry Pi and have the ability to find out more in the particular areas that interest you.

What you do with your Raspberry Pi will be driven by your interests and perhaps the interests of your family. My aim is that you will combine learning, experimentation and enjoyment. Here's a quick look at some of the things you could be using your Raspberry Pi for. Many of these we'll have a closer look at during the course of this book and I'll show you how to do them for yourself.

Information Centre

At the very least you can use the Raspberry Pi to surf the web — look at pages on the Internet or watch free television services from around the world.

Administration

With a vast range of high quality software available to you free of charge you can use your Raspberry Pi to do all your home or business administration. Create great looking letters and documents, get your accounts into order with state-of-the-art spreadsheets and produce stunning colour graphics and illustrations. All this is possible, including the ability to produce files compatible with industry standard software such as Microsoft Office.

Media and Photo Hub

You can watch High Definition output on your HDMI compatible TV from an Internet service or by reading files from an attached USB device. Or take stunning pictures using an (additional) attached Camera Module and display the results.

Learn to Program

Raspberry Pi comes with industry standard programming languages. Learn about them and how to use them to write your own programs and customise others for your own needs.

Play Games

Many classic games are available to play on the Raspberry Pi, and more will become available. While away the hours with your favourite pastime. Some of the retro classics are from the Atari, Commodore and Sinclair classic library.

Learn Electronics and Control the World

There are many extra bits you can plug onto your Raspberry Pi that allow you to control a variety of external devices. Some of these are ready to go. Others you can build from scratch. From turning a light on and off to home automation programs — it is all possible and relatively simple if you have a bit of practical ability and a willingness to 'give-it-a-go'.

Security and Monitoring Systems

Add a camera and record video or take time-lapse photographs to monitor an area — or just see what the dog gets up to while you are out of the house! The Raspberry Pi also makes a great baby monitoring system so you can record what your bub does when the door is closed!

Of course these are really only a few of the things you might want to do with your Raspberry Pi. There are many, many more things you can do and I'll also show you the best places to look to find out about these.

Need to Learn

After the surge of interest in home or hobbyist computing in the 80s many of the popular computers of the time such as the BBC Micro, Commodore 64, Amiga, Spectrum and Atari found themselves curiously superseded by relatively low cost industry standard PCs. The home computer hobbyists still existed but their numbers diminished and with them the number of people learning about computers and their operation, especially school children. We had moved from being computer programmers to computer users. Where was the innovation to come from?

The Raspberry Pi Foundation set out to right that wrong, and did so by launching the Raspberry Pi in February 2012. It had created a low cost computer, capable of using industry standard parts with access to vast amounts of free software, and crucially, it was supported by a sector of the industry creating expansion and add on boards that furthered the capabilities of the product. So much so that the Raspberry Pi had passed the three million sales by the middle of 2014.

The Raspberry Pi is a little different from other computers you may be used to. Most notably it isn't a complete system. You may be used to computers that come in one box: for example, a laptop where everything you need is in a single package. Or a PC which is supplied with a main unit (often mistakenly called the 'hard disk' although this is just one of the components inside it), a monitor, keyboard and mouse. In contrast the Raspberry Pi comes in a small electrostatic bag and it's up to you to bring everything else it needs together to get going. This is where the _Raspberry Pi Insider Guide_ comes in: it will guide you through that process and take you on a journey that shows you how to install and use the software and in turn use it to create a working environment that you might never have dreamed possible before.

So how do _you_ learn about the Raspberry Pi? In the first place be prepared to make some time to do so. If you get the 'bug' then making the time will not be an issue for what will become a rewarding experience. Be prepared to get a bit frustrated at times. You will make mistakes, but one of the most rewarding things you'll find is that working out what the mistake was and solving it is incredibly satisfying. There are plenty of things to do and resources to use, and after a while it will all come together. What this book provides, I hope, is some real down-to-earth tuition, in one place, that shows you all the neat things that you can do and probably will want to do. Hopefully by the end of the book you will be a confident Raspberry Pi user who can show the light to other newbies. Then they will consider you to be an expert!

How to Use This Book

If you have a skim through the Contents pages you'll see that the _Raspberry Pi Insider Guide_ is arranged into specific sections. I've tried to organise things logically so that you can progress from one aspect to another with enough information to make what follows intelligible and understandable.

If you work through the book systematically then you will have taken the journey from beginner to expert in your stride. That said, you might want to jump around a bit. For example Section Five is entitled Home and Office and in here you can find some nifty software and projects to get started with. At this stage of the book some assumptions have been made, but that is not to stop you working through the text as is and using the contents list to directly access the pages that allow you to brush up on things you might need to know. Section Four is about Programming. You will really need to know what went on in the early chapters to get through the chapters here as the basic concepts are important.

Jargon and Assumptions

One of the biggest hindrances to beginners understanding technology is the jargon — the words and terms often applied to the use of computers seem as though they themselves have come from a degree course on computers!

Unfortunately these items of jargon are part and parcel of the learning process. However, many in themselves have become everyday terms. If you are interested in devices such as smart phones, TVs and DVD players then you will probably be familiar with many of them already, even if you don't know exactly what they do. For example, USB or HDMI.

So, my intention in this book is to keep it simple with a motto of 'Don't use one word when three are clearer'. That's not to pad the book out but simply to keep it easy to read — the last thing you want is to be working out the meaning of some nine-letter word while trying to learn a new concept. (Besides I'm not that clever.)

I'll also try to avoid the chicken and egg syndrome as much as possible. To that end there may be the occasional white lie. Well, not so much a lie as an over-simplification or slight stretching of the truth — but necessary when you need to know two new concepts in one to understand one other. But I'll own up at the appropriate point!

What you will need to do is to read through the chapters as they happen. Although I've implied that you may want to jump around a bit, it is probably preferable to tackle the chapters in turn, or you may miss out on some important 'building block' material. The main thrust of the first part of the book is to move you through the familiarity minefield — get you used to using and occasionally abusing your computer. From there we'll look into what you can do with it and, most important just how to use it. And, providing you join in and try the examples given and then create a few of your own, you'll soon be wondering what all the fuss was about.

The above is easy to write but often difficult to put into practice, so there have been a few assumptions made. For example, I'm assuming you have a basic understanding of what a computer is and know how to use a keyboard and mouse— even if you don't do so regularly. You also know about the Internet, and will probably have dabbled with email and might even have your own email account.

I am also assuming that you have never gone past the above points, so that will be where we start. Even if you have, just like reading a review of something you have already bought, reassurance is a great thing.

So let's get started!
2: Bare Essentials

Making sure you have the right components to connect up your Raspberry Pi is essential for a smooth start. One way of achieving this is to buy a starter kit; the other is to gather up items that you might already have to hand. But what are these bare essentials?

Just how difficult is it to get a Raspberry Pi up and running, and by running I mean getting it working so you can start using it? I would allow an hour or so, although in reality it should take you a lot less. It you have all the components you need then it will only take a few minutes to plug them together. It is actually bringing it to 'life' and getting it to work that may need a bit more time and a bit of patience on your behalf. Frustration is your biggest enemy here, so it is important to get yourself in the right frame of mind. Everything you will do as part of the set-up process is quite logical and systematic. So one-step-at-a-time is your guiding mantra here.

Bear in mind that millions of Raspberry Pi machines have been sold, and each one has had to be set up in this way. So it works!

Mobile Phones

(Bear with me on this one guys.) It is pretty likely that you or someone in your family has a mobile phone. Most likely it's a smart phone — this is a phone that can do more than make phone calls.

There are lots of different types of phones — iPhones, Galaxy, HTCs, Nokia and so the list goes on. These names pretty much describe the maker of the phone (iPhone is Apple, Galaxy is Samsung...) and this physical part of the phone is the hardware. The phone unit itself comes with a charger (the power supply), sometimes a keyboard, a lead to connect it to a computer and other accessories such as headphones and maybe a CD or DVD disk.

What really distinguishes the phones from one another though is the software or _Operating System_ they run. iPhones run iOS, Galaxys and a lot of other phones run Android and various versions of Android. This software defines how they operate, what they can do, and how they go about doing it.

It is the same with the Raspberry Pi. To use the hardware you must select the Operating System you want to run on it. This will define how you use it and what you can do with it. On the Raspberry Pi you are spoilt for choice and there are several Operating Systems — or OSs — you can select from. That said there are versions that are more popular than other ones. We'll look at a couple of these in due course, giving you the opportunity to decide which one you want to use.

The Operating Systems are accessible and available to us in two ways. The first is already pre-installed on something called a NOOBS Card which can be purchased with the Raspberry Pi (or bought separately from the same or similar outlet). The second can be downloaded from the Internet and then copied onto a memory card that is not too dissimilar to the one you have in your smart phone or camera — an SD Card. In this case the software is free but you may need to purchase a memory card to copy it onto if you don't already have one. By the way, NOOBS is pronounced 'New-bs' and is an acronym for New Out Of the Box Software.

Bare Essentials

With the above in mind, this would be your bare essential shopping list — the absolute minimum number of things you need to get your Raspberry Pi up-and-running and usable. We'll examine each in turn shortly. Here's the list:

  * USB Power Supply
  * USB Keyboard
  * USB Mouse
  * HDMI compatible Monitor
  * HDMI cable
  * SD Card and adaptor (potentially a NOOBS Card)

If you don't have a NOOBS Card then you will also need a means of downloading the software and putting it onto the SD Card, and this requires one or two more items to do:

  * A PC or Apple Computer with Internet access
  * SD Card Reader/Writer (if your computer does not have one already in-built)

You don't need the additional computer to physically connect to your Raspberry Pi — or even have it in the same city as your Raspberry Pi (!) — you just need access to it. You may already have access to a computer (PC or Apple Mac) at home or work or via a friend or neighbour and you only require its use for ten minutes or so. The final item is an SD Card Reader/Writer — unless your 'other' computer has one in-built.

SD Card Reader/Writers only cost a few dollars and it is worth investing in one of these.

These physical components are what are often referred to as the _hardware_. Anything that you can physically touch and feel and can exist on its own is called hardware. The hardware is used to operate or allow the software to operate. Software is the programs (sometimes called the applications) that you run on the computer hardware to do things with. An example of a piece of software is a word processor which can be used to write documents such as letters and reports.

We need access to the PC or Apple computer to be able to select and choose the software we want to run on the Raspberry Pi and this Operating Software is written using the SD Card Reader/Writer.

An important point here: you do need a PC or an Apple Mac, a tablet device such as an iPad or Android machine will _not_ be suitable and won't work.

It's Different

If you have used a PC or Apple Mac or something similar before then you will realise that the Raspberry Pi looks a lot different. For a start the small board is just that — a small board and it is bare and exposed to the elements. With a PC or an Apple the computer board is neatly packaged inside a box specific to the type of computer it is.

However, if you were to look inside a PC or Apple case you would find that it contains a lot of — well — space. In some instances this is so you can add in extra bits and pieces to expand its capabilities, but also because computer components can generate a lot of heat and this needs room to be dissipated.

Unless you have purchased your Raspberry Pi as part of a starter kit then you will be dealing with just the bare Raspberry Pi board itself. You can purchase boxes or cases for the Raspberry Pi (you can even make them from cardboard or Lego) but for the time being we'll assume you don't have one. As such you need to handle it with care — although they are quite robust you should treat it with respect.

One of the big enemies of computers is static electricity — if you get a discharge when you touch a Raspberry Pi board you might damage the components on the board. Although the Raspberry Pi isn't immune to static electricity it is pretty robust and I would have to say you would be very unlucky to damage your Raspberry Pi this way. But forewarned is forearmed! (This is why the Raspberry Pi and other associated add-ons come supplied in a protective anti-static bag)

If you happen to purchase the add-on Camera Module for the Raspberry Pi, then this is susceptible to static electricity so these few words of warning and details of avoidance measures are in order.

Static Electricity

Static electricity refers to the build-up of electric charge on the surface of objects. If the surfaces are both insulators, they'll build up an electrical charge. One object will have a positive charge (because it has lost electrons) and one will have a negative charge (because it has gained electrons). If one of the charged objects then touches a conductor, like a piece of metal, the charge will neutralise itself, causing a static shock.

After removing an item of clothing or rubbing against a fabric, if you occasionally get what feels like an 'electric shock' when you touch a surface in your house or office — this is the spark of static electricity discharging — so you should then certainly be wary. For example, when you walk on a wool carpet, your shoes react with it and your body then builds up a charge. Then, when you touch a metal doorknob, you know what happens. You don't want the discharge to happen when you touch the Raspberry Pi board. To avoid this happening to you, if you think you have accumulated a charge, before you handle the Raspberry Pi make sure you 'Earth' yourself first by touching a metal object that is 'earthed', like a water pipe.

Making Jam

Raspberry Pi users around the world meet regularly at aptly-named _Jams_. There are Jams meeting everywhere and I have attended them in London and Sydney — just about opposite ends of the world! I would encourage you to find out where your local Jam is and try and get there for a meeting. The Jams are generally run by bright people 'in the know' and they will welcome you with open arms. Jams are great for beginners and you'll find they often have themes and goals for each meeting. In addition to being learning platforms they are a great way to find people who are willing to help you if you are stuck and to get questions answered. Installing an Operating System is a daunting task when you are new to it all, and although it really is relatively straightforward (when you know how!), local Jammers can give you the benefit of hands-on experience or provide access to the computer you might need to create it with.

To find your local Jam just search the Internet for:

Raspberry Pi Jam 'CITY'

Where 'CITY' is your nearest point of reference.

Another great source of information for newcomers is the The MagPi. This is a monthly magazine specifically for all things Raspberry Pi and it is available free of charge to download at www.themagpi.com. You can also download all the back issues and have an instant encyclopaedia of neat Raspberry Pi things. You might even come across the odd article by yours truly!

_Figure 2a. The MagPi is a free magazine for Raspberry Pi users and should be considered essential reading._

I will also direct you to my website at www.brucesmith.info where you will find additional material for this book in the form of projects from it, as well as additional written material to support the contents here and which couldn't make it into the final pages for reasons of space.
3: Board Anatomy

The Raspberry Pi has gone through a few changes since it was released. The Raspberry Pi B+ should be considered as the standard Raspberry Pi and is the one supplied by default. However the original Models B and A (shown below) are still available. In this chapter we'll look at all of them and explain what all the bits and pieces do!

The Raspberry Pi Model B+ is now the standard Raspberry Pi and has been shipping since its release in July 2014. The B+ was released as an upgrade to the original Model B, and contained significant enhancements which were aimed at rectifying some of the usability issues inherent with the original Model B. 'Issues' is perhaps a strong word, but the Model B+ provided end users with what you might call the perfect piece of pi! Production of the Model B was due to continue as long as demand remained — this is to assist those who had integrated the Model B as an essential part of their businesses. The differences between the two will become obvious shortly, but from a learning point of view there is not much between them so whether you happen to have a Model B+ or a B, this book is still 100% applicable.

As you might rightly assume, a Model A and A+ also exist and these again are virtually identical operationally, although they have less of the connection capabilities of the B+/B and they cost a few dollars less accordingly.

If you have not purchased yet and are undecided as to which model to get then I would suggest you go for the Model B+ over the Model B and Model A/A+. At the time of writing the Model B and B+ cost the same, while the cost increment of B+ over A+ is really insignificant in pure bang-for-bucks terms, especially when only purchasing one or two. However, if you plan to purchase a lot and don't need the extra functionality of Model B+ then it would make monetary sense to purchase Model A+.

As I have intimated, in terms of operation and usage the boards are almost identical. Differences only exist when it comes to physical arrangements. I'll identify these when and where they come about.

The following page breaks down the various component parts of the Raspberry Pi B+ and Raspberry Pi B and also provides some brief descriptions of what each part does.

You may find it useful to invest in a small plastic box or container as you will find you ultimately end up with an assortment of leads and cables, and will need somewhere to store them. Wrapping an elastic band around leads is also a handy way of ensuring they don't get tangled, but make sure not to fold them over too much otherwise you may damage the fibres in the leads themselves.

Around the Boards

The Raspberry Pi measures just 8.6cm long by 5.4cm wide, making it a little bit bigger than a credit card. Figure 3a shows the Model B+ and Figure 3b the Model B, and even a quick glance will show you that there are some physical differences between the two. The B+ has some additional sockets which allows you to connect more devices to it at once, and which are arranged in such a way that the plugs that go into the sockets are limited to single sides of the board rather than all the sides.

_Figure 3a. The Raspberry Pi Model B+ has been revised to include additional sockets and a more streamlined layout._

The small black square in the centre of each board is a critically important chip. This is what makes the whole Raspberry Pi device work. Indeed this 'chip', which is called an _ARM microprocessor_ , is so powerful that it is used by virtually every smart phone and tablet device available today and also forms the heart of many of the satellites that orbit our planet. The Raspberry Pi is a seriously clever device!

_Figure 3b. The Raspberry Pi Model B with the original connection layout._

The various components are labelled in Figures 3a and 3b — here's a brief description of each:

SD Card Slot

This is mounted on the underside of the Raspberry Pi board and is where you insert the SD Card. On a Model B+ it is a micro SD Card while on the Model B it is a standard SD Card.

Micro USB Power Socket:

Connect your 5V Power Supply here.

HDMI Socket

Plug an HDMI cable here to connect to your HDMI Monitor.

Camera Connector

The Camera Module board (if you have one) plugs in here.

Network Port — Ethernet R45 Socket

You can connect your Internet or LAN cable here.

USB Ports

These allow you to connect standard USB devices such as keyboard and mouse. On the Model B+ there are four; on the Model B there are two.

Status LEDs

Small lights that indicate what your Raspberry Pi is doing!

GPIO Pins

Connect all your external projects here. The Model B+ has a 40-pin connector; the Model B a 26-pin connector.

Audio Video Combined (Composite) Jack

Model B+ only, combines an RCA Monitor and 3.5mm Audio plug. Connect either or both of the two items below here.

3.5mm Audio Jack

Connect headphones or a speaker here. Model B only.

Composite Video Jack

Connect to an old RCA monitor or TV. Model B only.

SD Card

The SD Card plugs into the SD Card Slot. SD Cards are memory cards — they have (almost) no moving parts and they are identical to the type of card you may use to store photos on if you have a digital camera of some sort. There are many types of SD Cards and you can purchase them in electrical stores and camera shops — even in general high street stores! Depending on which model Raspberry Pi you are using you will require a specific SD Card:

Model A+ and B+: Micro SD Card

Model A and B: Standard SD Card

Figure 3c illustrates these two cards. A micro SD Card is very small — the size of a finger nail perhaps, whilst a standard SD Card is much bigger. As the image shows, there are adaptors the size of a standard SD card that micro SD cards can fit into and this is to allow you to use them in other devices. Many PCs have in-built SD Card readers which would not take a micro SD Card directly. Although these cards are physically different, there is absolutely no difference in the way you use them.

_Figure 3c. A micro SD Card (left) and a standard SD Card. The SD Card label indicates its size and class. Notice that it is also possible to physically lock the card against read/write operations by shifting the lock slider located on one side of the card._

If you have used other computers before then the SD Card on the Raspberry Pi pretty much replaces the hard drive. The SD Card is used to hold the Operating System that you choose to use on your Raspberry Pi. It also has enough space for you to save your own files and programs.

SD Cards come in different memory sizes and an 8GB card might currently be considered the best size and value for money. The GB stands for Gigabyte, being a measurement of memory space.

SD Cards are also rated according to the quality of the components used which affect the speed of the card — this is how fast they can be accessed. For the Raspberry Pi you should buy a Class 4 SD Card. This is the one that works the best. Some people swear by Class 6 cards and others use even higher class cards. But these are more expensive and might not offer any performance improvement in this environment.

As previously mentioned the SD Card is used to replace the function of a hard drive in a normal office computer. It is on here that you will copy the software you want to use and also where you will save and store any information, programs or data that you create for future use.

You only really need one card, but if you are really going to experiment with your Raspberry Pi I would recommend that you get at least three, so you can have SD Cards pre-prepared and ready to use for different tasks. You can totally change how your Raspberry Pi works simply by changing what is on the SD Card inserted into it!

USB Power Supply

The Raspberry Pi does not come with any form of power supply. You need a 5V DC regulated supply and this is generally the kind that most smart phones utilise. For example, if you have a Samsung Galaxy phone charger it will almost certainly work right away. If you have an iPhone charger — the type where the lead itself can be detached, then this will almost certainly work. You will just need to substitute the iPhone cable for a micro USB to Standard USB cable (These can be bought for just a few dollars at most general electrical retail and phone accessory stores). Note that not all phone chargers can supply 5V so you should take time out to read the detail on the case of the charger. Do not use a charger that is not 5V — anything less would result in your Raspberry Pi behaving in strange ways while anything more would almost certainly fry it! An AC or unregulated supply is a definite no-no!

_Figure 3d. A phone charger such as the one illustrated should be able to power your Raspberry Pi. Just make sure you get a cable long enough to reach from the power socket to the computer!_

The power supply should also be rated to deliver at least 750 mA — many are rated at 1 amp and this is perfect — again you should find this information in the very small print on the charger.

Several power supplies have been produced specially for the Raspberry Pi and you may wish to look at purchasing one of these specifically. They have the advantage of being produced to meet the exact power requirements of the Raspberry Pi.

One more word of warning: do not try and power your Raspberry Pi by using the USB outlet port on a computer or other device. It will not work as it does not have enough power.

HDMI connector

There are two ways to connect the video output from your Raspberry Pi. Using the HDMI socket is possibly the more elegant of the two, not least because this interface also gives you sound through the TV as well. HDMI stands for High-Definition Multimedia Interface and is commonly used to connect most television sets to DVD players and Set-Top boxes. Indeed most TV sets have several HDMI sockets built into them nowadays. So unless your TV set is quite old the chances are that you would be able to plug your Raspberry Pi straight into it if you wanted to — provided you have the correct cable. Most flat screen monitors also have an HDMI connection point as well.

_Figure 3e. HDMI cables can be expensive so it pays to shop around. They are also very easy to connect. They come in various lengths so make sure you get one long enough for your requirements!_

Spare HDMI cables are not generally the sort of thing you have lying around so you may want to invest in one specifically for this purpose. eBay is a good place to find well-priced cables as they can be somewhat overpriced.

If you have a monitor which doesn't have an HDMI connector but does have a DVI-D or DVI-I input then you could utilise this by purchasing an HDMI-to-DVI adaptor cable. This will work well enough for most purposes. (If you do not have the original monitor cable then have a look at the markings on the monitor to see what types of connections are available — they normally have a legend of some sort in place).

Note that the VGA connectors that used to be the most common way to connect computers to monitors in days gone by are not directly compatible. You can purchase a converter to transform the signal for you but these are not cheap and the image quality is often compromised, so they are best avoided. An adaptor for the Model B+ has been designed and further information can be found at: www.raspberrypi.org and search for "gert vga adapter".

_Figure 3f. A HDMI-to-DVI cable can also help you connect to a monitor with a DVI connector._

Composite Video and Audio

On the B+ there is a 3.5mm jack plug that combines audio and video. On the B these are separate connectors with video pushed through an old RCA style socket. Note that the RCA output is composite video, not RF, so it cannot be connected directly to the antenna input of a TV. Both PAL and NTSC TVs are supported.

The images will not be anywhere near as sharp as those produced when you use the full HDMI interface but it is a perfectly acceptable way to connect up to do some programming! However, if your Raspberry Pi is not displaying information correctly it may require some tweaking of the Operating System software on the SD Card.

Once you plug an HDMI cable into the output on the Raspberry Pi then the output to the RCA socket will be disabled. So, you can't have two monitors working at once!

If you have an amplified speaker or speakers then you can connect them to the jack on the Raspberry Pi and listen to the sound. You can also use the 3.5 mm output to connect headphones to. They should work fine but you may need to pass the audio output through an amplifier first if you want to ramp up the volume without distorting the sound quality.

Ethernet

The Ethernet RJ45 socket allows you to connect your Raspberry Pi to a network and/or the Internet (via a router/modem). To do this you will need an Internet cable (these are normally blue in colour) and one of a suitable length to reach from your Raspberry Pi to your nearest connection point. You would typically plug the other end of the Ethernet cable into a router. The router is often associated with the modem that you use to connect to the telephone line to get your Internet connection (ADSL or for the very lucky — fibre!).The Ethernet connection is often called a RJ45 connector.

If you are using your Raspberry Pi in an office environment then you will almost certainly be able to 'plug' into an Ethernet socket. If you are operating at home then you probably won't have Internet sockets built into your house (although a few homes do have them). If this is the case, the best way for you to connect to the Internet is via a USB Wi-Fi adaptor. We'll discuss this a bit more below.

USB

The Model B+ has four USB sockets, whilst the Model B has two. Four USB sockets should be ample to get you up and running, and although two is fine to start with you might be looking for some expansion sockets soon.

You will use two sockets to connect a keyboard and mouse. Most standard USB keyboards and mice will work with the Raspberry Pi and they can be purchased very cheaply nowadays. You might even find that friends, relatives or even work have the spares that you can have on loan to try out. With regards to the keyboard — keep it simple. The keyboard and mouse both get their power to work from the Raspberry Pi, so fancy multi-featured keyboards are best avoided.

If you are not connected to the Internet via your ADSL router then you can do it wirelessly using a USB Wi-Fi connector. This can be plugged into the third USB socket on a B+. On a B there is no other option other than to purchase an expander device that allows you to add more USB sockets for use. You can also obtain boards that plug into your Raspberry Pi and provide additional USB sockets. We'll look at these extras of this sort in Chapter 13.

_Figure 3g. The two USB formats used on the Raspberry Pi are Micro (left) and Standard (right). The micro connector is used for the power supply only on the Raspberry Pi._

There are not many electronic devices these days that don't use a USB connector of some sort. Not just computers like the Raspberry Pi but also DVD Players, Blu Ray Players and, of course, mobile phones. USB stands for Universal Serial Bus (USB) and this was developed in the mid-1990s specifically to replace the old multipin serial port connections and to standardise the connection of computer peripherals such as keyboards and mice. Today almost anything that plugs into a computer does so using a USB connection.

Because the Raspberry Pi uses this USB connection standard, you should find it very easy to attach things to your Raspberry Pi. That said, you should be aware that there are three or four different types of USB connectors and the Raspberry Pi uses two of these. Figure 3g shows the two types: Micro and Standard (left to right). The Raspberry Pi uses the Micro and Standard plugs. We'll see where these are located in the next chapter, although if you have your Raspberry Pi handy you can probably see yourself!

Others

Although not essential for getting your Raspberry Pi going, there are a few other items highlighted on the Raspberry Pi board description, so I'll just mention them now for completeness and we'll certainly look at them later in the book.

Camera Module Connector — You can purchase Camera Modules that allow you to take high definition pictures using your Raspberry Pi. This module — which is a separate board with an optical sensor and lens mounted on it — plugs in through the camera connector. Chapter 16 is dedicated to the use of the Camera Module.

Status LEDs — These are small lights that indicate what your Raspberry Pi is doing! They flash when it powers up and also to indicate things are working correctly.

GPIO Pins — These pins allow you to attach devices to them, or plug other connections into them. They can be used for all sorts of projects and also to add expansion boards to your Raspberry Pi that you can buy commercially or make yourself! Again we'll look at the GPIO port much later in the book — Chapter 35 to be precise.

Model A

The Raspberry Pi Model A is shown in Figure 3h. Notice that the Ethernet connector is not present and that the USB Port is now only a single version rather than a twin version. The Model A comes with 256MB of memory compared to 512MB of memory of the Model B/B+. Model A consumes a third less energy than Model B. Everything else is the same.

Having only the one USB port presents problems in connecting a mouse and keyboard together unless you have a USB Hub of sorts, and with no Ethernet connection that is the only way you can actually get Internet access. For this reason, the Model A Raspberry Pi is generally purchased with more specific tasks in mind rather than for general learning and programming use.

At the time of writing a Model A+ was in preparation for release and features the same cut down features in relation to the Model B+.

_Figure 3h. The Raspberry Pi Model A._
4: Distro Bution!

With the hardware components gathered together you need to provide them with something to work with and give you the means to control everything the Raspberry Pi does. Your Raspberry Pi needs an Operating System.

Before you plug the hardware together — and you'll see how to do that in the next chapter — you need to obtain the software that makes the Raspberry Pi tick. This is the Operating System or OS. It is also often referred to as the 'distro' which is short for distribution. You can obtain your OS in two ways, purchase a NOOBS Card which has the most common distros pre-installed so you can select the one you want to use, or download your OS of choice from the Raspberry Pi website and install it yourself.

There is no right or wrong here. However, if you are able, downloading and installing your own OS is something you really should learn to do as it is fundamental to the Raspberry Pi way of life. And there aren't really too many mistakes you can make. If you do make a mistake you can just erase what you have done and start again — you can reuse SD Cards!

Remember also that Raspberry Pi Jams are springing up everywhere; if you have computer access problems or need a hands-on tutorial you will certainly be able to get help and assistance at one of these meets.

OS Options

The main source for Operating Systems available for the Raspberry Pi can be found on the official Raspberry Pi website itself. This is located at: www.raspberrypi.org

When the Home page loads up look for the 'Downloads' tab at the top and click on this. If you prefer you can enter the full address of the page in one go: www.raspberrypi.org/downloads/

As you will see there are a number of options. Figure 4a lists those that were available at the time of writing. In truth this list doesn't change much from time to time as the desire is to have a fairly stable suite of Operating Systems.

_Figure 4a. Common Operating System images available from the Raspberry Pi website._

The bulk of this book assumes you are using the Raspbian OS. It is the most commonly used by Raspberry Pi users and therefore the one that is the best supported. It is generally regarded as the 'official unofficial' (!) OS for the Raspberry Pi. Behind this would be RISC OS, which is one of my favourites. We'll look at some of these distros in more detail in later chapters of this book (actually Section Six), including showing you how to create a media centre (Chapter 26) and gain access to a lot of additional video and TV content! For now we'll concentrate on Raspbian.

One pointer: If you look at your SD Card (or micro SD Card adaptor) on one side you will see a very small slider which allows you to lock the card so that it cannot be accidentally overwritten. Ensure the slider is in the 'Unlock' position.

Don't be tempted to lock the SD Card, because if you do you won't be able to save files and data to it when you are using it. The lock is really only to protect the SD card when you have used it to store valuable data you don't want to lose. The lock assumes you will not be deliberately writing to the SD Card.

The next section shows you how to download and install a distro. If you are using a NOOBS Card then you can skip over the next few sections as you already have everything you need on the SD Card.

Downloading a Distro

To download a recommended Operating System on a second computer (PC or Mac), go to the Raspberry Pi Downloads page at: www.raspberrypi.org/downloads/

And scroll to the details of the image you are looking for — here Raspbian.

_Figure 4b. Accessing the Raspbian download at raspberrypi.org_

You can download the Operating System as a single file. There are two methods and the simplest is as a ZIP file. (A ZIP file is a file that has been compressed so that it takes up less space — this also makes it quicker to download as it is smaller. However, once downloaded you have to un-ZIP it to its original form so that you can use it! ZIP files are common so most computers can understand and read their format.)

If you click on the 'Download ZIP' button associated with the Operating System of your choice it will display a download window, which on a Windows PC system will look similar to that one shown below in Figure 4c.

_Figure 4c. The download window._

Make a note of the filename proffered in the window, which here is given as:

2014-09-09-wheezy-raspbian.zip

Click on the 'Save File' option and press the 'OK' button. (The filename will change as new versions of the Operating Systems are released, so expect yours to be different). The file will now be loaded to the PC's Downloads folder.

If you open the Downloads folder you should be able to locate the file, and you may then wish to drag this to a folder location where you can keep your Raspberry Pi Downloads. If you double-click on the file it will open and you will see other file or files inside. One of these will have the postfix '.img' (illustrated in Figure 4d). This file is the image file for the Operating System and the one you will be looking to write or 'flash' to the SD Card.

_Figure 4d. Locating the '.img' file in the Downloads folder._

Once you have downloaded your Operating System file you will be ready to flash it to the SD Card. For this you will need to copy the .img file from the ZIP file to another folder. Place this at a convenient location as you will need to access the file to write to the SD Card.

On the Mac you can also unzip the archived file by clicking on the file and selecting 'Open With>>Archive Utility' from the pop-up menu.

Now jump to the section relevant to the type of computer you will be using to flash the SD Card, namely:

Flash Windows

Flash Mac

Flash Linux

Flash Windows

To write an OS image to an SD card using Windows on a PC I would recommend a piece of free software called Win32DiskImager. You can download this from: https://launchpad.net/win32-image-writer

When downloaded, follow the install instructions — which are very simple, as is actually using it.

Remember: If you are using a micro SD Card then you should insert it into an SD Adaptor Card, unless your SD Card Reader/Writer has a micro SD Card slot.

Place your SD Card in your SD Card Reader/Writer. The Card will only go in one way so don't force it. Open a Directory window so that you can see a list of what disk drives are available on your PC. Then insert the device into a USB socket on the PC and make a note of the name it has when it appears under the 'Computer' listing.

Figure 4e shows how it might typically appear — here it shows up as 'Removable Disk (G:)' on my PC. As a safety measure you should unplug (remove) from your PC any additional drives that are not 'fixed' so that there is less chance for error.

_Figure 4e. The USB SD card Reader/Writer will show up as an additional drive when it is inserted into a USB port on the computer. Make a note of the drive number assigned to it — here it is G:. It will vary from computer to computer._

Run the Win32DiskImager software. You should run the utility as Administrator or agree to do so if it asks you. (To run a file as Administrator, right-click on the file and select 'Run as Administrator' from the drop-down menu that appears.) If you are asked by the program for permission to make modifications to the computer, allow it as this is the writing process.

_Figure 4f. Using Win32 Disk Imager to write the .img file._

Click on the folder icon and browse to the location of the Raspbian image file, and under 'Device' ensure the drive letter is the same as you noted earlier for your SD Card — G: in the above example. Be careful to select the correct drive; if you get the wrong one you could overwrite another disk drive on your computer.

Click Write and wait for the transfer to complete. This will take a few minutes and you can watch the progress on the screen.

That's it. On completion remove the USB device and the SD Card from it. Then use a thin (!) marker to label the SD Card — 'Raspbian' — so you know what is on it. They all look the same when you have a few lying around. I use small zip lockable sandwich bags to store my SD Cards so they don't go missing. If you are using a micro SD Card then some come in a plastic sleeve that you can label and use to store them in.

Flash Mac

PiWriter is one of many applications written for the Mac that allows you to write Operating System image files to an SD card. There are many others available but this is a good one to use first time out, although this version (1.0.4) does not work on Mac OS X Mavericks. You can need to download PiWriter from:

http://sourceforge.net/projects/piwriter/

When it has downloaded (probably to your Downloads folder) open the folder where it is and copy the PiWriter file into your Applications directory. Run PiWriter by double-clicking on it — note at this stage that your SD Card should not be inserted into your Mac! You may get a message that PiWriter cannot be launched as it was not installed from an authenticated site. Click on the 'Help' icon that's in this window and it provides a couple of simple instructions that you can do to authenticate (ie, vouch for) the software and make it clickable to run.

The PiWriter window will open. On the left hand side use the menu to navigate to the Operating System img file that you previously un-zipped. Click on the file and press the 'Open' button. PiWriter will then display the screen illustrated in Figure 4g.

_Figure 4g. The screen will say 'Disconnect your SD Card', but it shouldn't have been inserted at this point anyway!_

At this point the SD Card should not be attached to the Mac. Remember: If you are using a micro SD Card then you must insert it into an SD Adaptor Card, unless your SD Card Reader/Writer has a micro SD Card slot.

Now click 'OK' and a window asking you to insert your SD Card will be displayed. Insert your SD Card into the SD Card Reader/Writer. The Card will only go in one way so don't force it. Then insert the SD Card Reader/Writer into a spare USB socket. Note that some Macs have in-built SD Card ports which you can insert the SD Card directly into and therefore don't need the USB device.

Once inserted, a window will be displayed saying that PiWriter is allowing the SD Card to settle. This takes a few seconds during which the software is detecting which port your SD card is in. Once the system has identified this it will display a new window advising you of the fact. The window is similar, but maybe not identical to that shown in Figure 4h.

This process will erase the SD Card contents (if it has any) by overwriting the contents of the device it is pointing to — this should be your SD Card, so if you are in any doubt double check. Once you are happy click 'Install' and the image file will be written to the SD Card. This will take quite a long time — up to 30 minutes for an 8GB SD Card.

When the process has finished you will get an affirmative message and you can quit the software and then remove the flashed SD Card from the Mac.

_Figure 4h. PiWriter should detect the correct port address for your SD Card although this may take a dozen seconds to do._

A newer drag-and-drop style PiWriter, version 2, is also available and you might also like to try this version and any further updates that are available. Check it out at the PiWriter website.

Flash Linux

If you are using Ubuntu you can use the ImageWriter tool to write an Operating System to an SD Card. Go to the Ubuntu Software Centre (this is one of the icons in the side toolbar) and install the ImageWriter tool. Make sure you enter the name as one word so the USC finds the software. You will need to provide your Administrator password as part of the process.

Ensure you have extracted the Operating System img file to a convenient location so you know where to find it when it comes to selecting it. Place the SD Card in your SD Card Reader/Writer. The Card will only go in one way so don't force it. Then insert the SD Card Reader/Writer into a spare USB socket. Ubuntu may automatically open a window onto the SD Card.

Remember: If you are using a micro SD Card then you should insert it into an SD Adaptor Card, unless your SD Card Reader/Writer has a micro SD Card slot.

Open Dash on the side toolbar, locate ImageWriter and double-click on the icon. The software will launch and request your password once again. If you have not inserted the SD Card then the software will inform you that there is no writable USB drive present (assuming that is indeed the case).

The window that opens should present two drop-down boxes. On the left is one labelled 'Write image:' Click on the small folder by the window, navigate to the .image file and open it. The address of the file will be copied into the window.

_Figure 4i. The Ubuntu ImageWriter window, showing the image filename and destination path in place._

On the right hand side is another drop-down. Click here, when the location of the USB containing the SD Card should pop into place (your device will be something like '/dev/mmcblk0' or '/dev/sdc'). Figure 4i earlier illustrates the Ubuntu ImageWriter window with these two locations in place.

Click the 'Write to device' button. Progress will be shown on the progress bar and a message will be displayed when writing is completed. You can then close the window and remove the SD Card from the PC ready to use on the Raspberry Pi.

Note: If the .img filename should contain a space then it can sometimes create difficulties where the file will fail to write. Check that the image file does not contain any spaces and if it does simply edit them out. Spaces are not normally included in the Raspberry Pi website download filenames, so this should not be an issue with those.

Reusing Cards

SD Cards can be reused — so if you decide you do not want to use the information or Operating System on a particular SD Card you can simply erase it and use the card for other purposes. If you are using a PC for writing to your SD card you can simply use ImageWriter to write a new image to the SD Card and it will automatically overwrite the original data on the SD Card for you. However, if you want a clean blank card or are using a Mac as your writing device then you should use a free piece of software called SDFormatter which you can download from:

<https://www.sdcard.org/downloads>

But SD cards don't last forever and continual rewriting on them will eventually cause the medium to degrade and become unreliable. For this reason always keep backups of your important data and information if you want to keep your working environment safe. One of the easiest ways of doing this is to use a USB Memory Stick, as we'll see in Chapters 8 and 9.

OS Updates

One reason you may wish to re-write an SD Card is to update the Operating System of your choice. Raspbian, RISC OS and other distros undergo continual development and like most software new versions are released. One of the simplest ways to get a new version is to simply download the updated distro from the Raspberry Pi website and install it on your SD Card.

If you look at the available distros on the Downloads page at:

www.raspberrypi.org

you will see that each has a version number and release date, so an occasional check will tell you when a new version is available.

Of course updating the distro in this way will overwrite any information or software you may have saved on your SD Card – so you may want to use a new SD Card. However, Raspbian and other distros allow you to update the software on them in situ and we'll see how to do this as well in Chapter 11.
5: Ready, Set...

So now you have all the hardware you need and you've created an SD Card that holds the Raspbian Operating System. Time to go Live and see how it all comes together!

Combining all the parts, connecting all the leads and finally adding power will bring your Raspberry Pi to life. The Raspbian Operating System will start to make the various components on the Raspberry Pi operate — it will drive the screen so you can see output and it will provide the necessary functions to recognise movement of the mouse and input at the keyboard. In the background it will also start to check for other components that may have been attached to it (although there won't be any at this point).

That said, when we turn on and use Raspbian for the first time we need to configure its settings so that they match your local requirements. It's rather like when you get a new TV: you go through a set-up process where you not only tune in channels but also define what sort of sound and picture you want displayed. In this case it's information about where you are located in the world (for date and time settings) and the type of keyboard you are using. So nothing too taxing.

Sum of the Parts

It's very easy to connect all the bits together to create a working Raspberry Pi. It can seem daunting but this is one of those situations where you just need to be careful that the right plug is going into the right socket, which includes trying to put it in the right way up (or down)! Most of the plugs can only go in one way, so if an item doesn't slide in simply double check that it's orientated the right way. I for one am forever trying to insert USB plugs upside down! The Raspberry Pi is a bare circuit board so hold it carefully, ideally at the edges with the board suspended between your fingers and spanning the palm of your hand. I use my thumb and two adjacent fingers, and this works well for me. Don't forget static electricity precautions!

Your monitor position and the location of your power points will probably determine just where your Raspberry Pi will be sited when it is connected up. Make sure there is enough room for the leads and that they are all long enough to reach where they are going. This may take a bit of work until you formalise a home for your computer — meanwhile the Pi won't complain if it is spending a bit of time on its edge, for example.

Make sure the surface it is being placed on is safe. Unless you have placed your Pi in an enclosure, do not use a metal table top as this will probably cause the board to 'short' and render it useless. If I am working with a bare board I normally put a magazine or book under it (more to protect the desk top in all honesty!). You could also use the anti-static bag it was shipped in for this purpose.

There is no hard and fast order in which to connect the parts of your Raspberry Pi. However, I would suggest that the power connection is always the last thing to complete. Also, it is good to start with the SD Card as that can be the trickiest and also it is on the underside of the board.

Inserting the SD Card

The first thing to do is insert the SD Card that has the Raspbian OS installed on it. Hold the board so that the 'bottom' is facing up (this means the Raspberry Pi logo on the board is facing down towards the palm of your hand).

Raspberry Pi Model B+ and A+

You will need to remove the micro SD Card from the SD Card adaptor and then insert it into the card holder under the board. The card will only fit in one way, with the silver pins facing towards the board and going into the socket first. You will feel a physical click when the card is locked in place. The micro SD Card is not completely flush with the Raspberry Pi board; there is a small protrusion. To remove the card just push the card in — it should unlock and you will be able to pull it out.

_Figure 5a. Once inserted correctly on the B+ there is not a lot to see of the micro SD Card._

Raspberry Pi Model B and A

On one short edge you will see a plastic socket — this is where the SD Card slides into. If you look into the socket you will see tags that line up with the metal connectors on the SD Card. Note also that there's a small spring. Take care with this as handling it roughly can cause it to break and make it difficult to 'snap-in' the SD Card.

With the label on the SD Card facing up (away from the board) slide the notched end (the one with the metal tabs on — which should be facing towards the board) into the socket. Note that the SD Card will not go in the whole way and some of the SD Card will be left hanging out. You will feel resistance once the SD Card is inserted correctly.

If you are not sure, pull the SD Card out. Now, looking into the SD Card socket you should be able to see how far the card will go in by placing it over the top of the fixture.

Flip the Raspberry Pi back over so that the logo is now facing upwards. You will see the SD Card sticks out a little way. This is normal.

_Figure 5b. Ensure the SD Card is correctly orientated before plugging it in to the Model B._

Sound and Vision

HDMI leads tend to be thicker than most and therefore less flexible. As such you might find it easier to connect one end of the lead to your monitor or television first. This will then define how far away your Raspberry Pi can be placed — and it gives you an early opportunity to reposition the display if you need to. If you are using a DVI adaptor then you should tighten the screws on the adaptor into the TV end to ensure that it's secure.

The HDMI connectors will only go in one way due to their shape, so a visual check should allow you to orientate everything correctly and slide the plug into place. Normally the long flat side of the plug faces up.

If you have the option of alternative media connectors you should use the HDMI interface for the best results (remember it also provides sound output through the attached television or monitor inbuilt speakers).

On the original Model A and B there are separate RCA and Audio jacks. The B+ has a single composite lead. The RCA lead should be plugged into the Video In socket on your TV — it will not work with the Antenna In socket.

As mentioned earlier you can plug headphones or speakers into the 3.5mm jack to listen to sound output. Remember also that you cannot have two working monitors connected to the Raspberry Pi — in fact, you could have two connected but only the HDMI connected one will work if you try! If you check out Gert's VGA adaptor card for the B+ by searching at www.raspberrypi.org you will read that it may be possible to have two monitors working in tandem. This was currently in development at the time of writing. Check out the book support pages at www.brucesmith.info as well.

_Figure 5c. On the Model B+ you can use a composite lead — here the standard is yellow for video out, red for audio right out, and white for audio left out._

Keyboard and Mouse

Your keyboard and mouse can be directly connected into the USB sockets. There is no rule as to which one should go into which socket. However, if you have a Model B you might want to put the keyboard in the top socket. I will explain the reason for this in due course.

Internet

If you are connecting to the Internet through the RJ45 Ethernet socket then the blue Ethernet leads plug in only one way up, with one end into the back of your router and the other into the corresponding socket on the Raspberry Pi. On the Raspberry Pi you will see that the raised pip on the plug needs to be face down towards the board to slide into the recess for it there.

If you are using a router then it needs to be one that supports DHCP (Dynamic Host Configuration Protocol) which is basically what routers for use at home are. So you should be fine.

As discussed previously, if this option is not open to you then you can use a wireless connection but this will require using a USB socket for the purpose. We'll discuss this in Chapter 13 as it requires a bit of knowledge to set up. It is not essential for you to have an Internet connection to use your Raspberry Pi; it just makes it easier if you can.

Powering Up!

The last thing to do is to connect the plug of the micro USB power lead into the socket on the Raspberry Pi. This can be the fiddliest operation as the socket is very small and can be tight to insert. Do this before you plug the power socket end into the mains power point, making sure that the power is off at this wall socket. The Raspberry Pi has no on/off switch so the switch at the power point is your only control. If you are using an extension lead then bear this in mind, ensuring that your last actions are plugging into the power point and then switching on. As I tend to use a power plug that has a disconnecting lead (see Figure 5d below), I remove the lead from the plug before inserting the plug into the extension lead — and use the lead as my power control.

_Figure 5d. Many phone-style power supply units now allow you to disconnect the USB lead from the power supply itself. This provides an effective way to disconnect the power from your Raspberry Pi._

Once you are sure all the leads are inserted correctly, position your Raspberry Pi so that it is well placed and there is no stress on any of the leads. This is also a good time to ensure that the keyboard and mouse are positioned sensibly and that leads are not tangled.

Time to switch on! When you apply the power you will notice that the small led marked PWR — short for power — comes on and the other LEDs on the Raspberry Pi light and may flash. Also, the screen might show a wash of colour before lines of text start to rapidly scroll down it. This scrolling text contains the various commands that the Raspbian Operating System is executing automatically — instructions to perform various set-up tasks, which we call housekeeping.

In time you will come to understand what these all mean and will start to use them yourself. For now though you can just let it happen. After a few minutes it will stop (although it may pause occasionally) and as a final act it will launch a program called 'raspi-config'. This is where you make those configuration choices I mentioned earlier.

Installing NOOBS

If you are using a NOOBS Card then when you turn the power on you will be presented with a screen that lists the Operating Systems available to you on your Raspberry Pi. Locate Raspbian and click the box next to it to select the software. Then press the 'Start' button and the software will begin to load. If you are using an 8GB or larger SD Card you can also copy other distros onto your SD Card for later use. However, at this stage I would not recommend this. Section Six of this book covers some of the other Operating Systems, so it's a subject we'll return to later. Be aware also that there is an option called 'Raspbian — Boot to Scratch'; don't select this option — use the 'Raspbian [Recommended]' option. Select Raspbian and then click on the 'Install' icon at the top to start copying the Operating System onto your SD Card.

As Raspbian is copied you will see information about the OS displayed on the screen. Once the transfer is complete Raspbian will be launched and you will arrive at the configuration screen.

Troubleshooting

What happens if your Raspberry Pi doesn't start? What can you do? This is unlikely if you have followed all the instructions carefully. But, sometimes these things do happen. Then the first thing to do is to identify where the problem is.

For example, when you flicked the power on did any of the LED lights flash? If not it would suggest that no power is getting to the board. Check the power lead connections. If this doesn't solve the issue then try a different power supply if you can or simply recycle the power (turn it off and then on again) at the wall socket.

Did the screen show information or a display at any point? If not then perhaps the leads you are using for the screen need to be checked. Are they inserted correctly? If you are using a TV for the HDMI connection, does the TV set have its source input set to the HDMI channel?

If the LED lights came on but there was no other activity, you may need to check the SD Card. Is it inserted correctly and pushed all the way in (this should not be a problem on the B+ but can be an issue on the A/B). Turn the power off, and then take out and re-inset the SD Card. Turn the power back on and try again. If this gives no success then it may be the SD Card itself — if you have another then install the Operating System on it and try again.

It is very unusual for one of these solutions not to work. It is certainly unlikely (but not impossible) for there to be a fault with the Raspberry Pi itself as post-production quality checks are excellent and the boards are pretty robust! In such cases you should definitely contact your local Jam, as people here will be able to help you at their next meet-up.
6: Configuration

The first time your Raspberry Pi loads the Raspbian OS you will be presented with a Configuration screen. From here you can set some basic information about your environment and place of work, which will ensure Raspbian is in sync with you! (And don't worry — you can always change things later!)

When Raspbian has finished its start-up process for the very first time you should be presented with the raspi-config screen, which will look similar to that one illustrated in Figure 6a (overleaf). It may not be identical because as the software evolves so some of the options on the screen may change or be ordered differently. That said, the basic options do not change that much so the screen should offer fundamentally the same choices.

The thing to bear in mind here is that each option generally leads to a second screen of choices from which you can select an option. Often the right choice will be obvious; if it isn't then you can try leaving it at the default value as this will probably work. And if it doesn't or if you want to edit your changes at a later date then you can always do so.

The other thing to note here is that this menu system is keyboard driven — you will not be able to use the mouse to move around the screens. You can use the <UP> and <DOWN> arrow keys to move vertically through the options and the left and right keys to move in those directions when the menu requires it. As you step from item to item they will be highlighted. The <ENTER> key will confirm a choice and the <TAB> key is often used to select other items on the screen such as OK or Cancel.

_Figure 6a. The raspi-config screen will look a little similar to that one illustrated although it may not be identical._

Menus explained

Some of the options listed on any given menu will have obvious meanings. I'll go through each of the options as listed on the screen displayed in Figure 6a above. They don't require you to read them in order, so you can also use this section as a bit of a reference should you need to come back to it. But now it is worth reading right through as you will learn some valuable things about your Raspberry Pi in the process!

1. Expand Filesystem

This is a useful utility that allows you to get the maximum storage room possible from your SD Card for files. If you are using a 4GB SD Card then your operating image can fit comfortably inside this with room to spare. If you are using an 8GB SD Card then there is plenty of room left on the card. However, the Raspbian OS will not use all this space automatically; it will limit itself to a smaller amount. This tool allows you to make all the space available to Raspbian which means you can store more on the SD Card, so it is something your should definitely do.

It is very easy to use. Highlight the 'menu' option and press <ENTER>. That's it. You will need to re-boot your Raspberry Pi for this action to take effect. This is something you will do when you have made all the setting adjustments here. When the Operating System next completes its start-up process the full capacity of the SD Card will be available to you. On completion you will be left with a screen telling you about the resize. Press <ENTER> to return to the main screen.

2. Change User Password

Once all the configuration has completed and you boot into the Raspbian Operating System itself you will be required to enter a password. By default the password is 'raspberry'. This option allows you to change what the password is. Like most password change options you have to enter the new password twice to confirm it is correct. At this stage I would suggest you do not change it unless you feel you really have to.

3. Enable Boot to Desktop/Scratch

This option can be quite useful as it allows you to determine what the Raspbian Operating System does when it finishes booting. It can go straight to the Desktop environment (this is a window-type environment) or it can go straight to an educational programming language called Scratch. At the moment leave this setting but feel free to come back here and change it later when you have learnt about the desktop and Scratch.

4. Internationalisation Options

Selecting this screen brings you to another screen with three options:

Change Locale

This defines the language setting and by default is English — so no need to enter here unless you want to have a look around or parlay in another tongue!

Change Timezone

This is an option you should select and change. From here you select your location in the world and therefore the time zone you are located in. This can be important for calendars and ensuring that files have the correct dates of creation and modification on them. When you enter here first select a region and then choose the city that matches your time zone — the nearest one if your exact location is not listed.

Once you have done this and saved the settings, then when you turn Raspbian on each time, and provided you have an Internet contention, the time and date will be automatically set to your location for you.

Change Keyboard Layout

You may not realise it but there are many different types of keyboards — probably hundreds! While they all have a standard character set, this includes a number of keys with alternative functions such as the choice of currency, and most have additional keys and options; some also might have a numeric keypad.

When you look at this option you will see there is a scrolling list of keyboard types available to you. Essentially you need to look through this and select the keyboard you have. If you do not know then have a look on the underside of the keyboard, there is often a legend identifying the type there. If you cannot locate the keyboard type then you should try sticking with the default option which is 'Generic 105-key (Int) PC'.

There are other options you can select but these are all quite specific and in general, unless you have a very fancy keyboard, the default configuration will normally work perfectly well.

5. Enable Camera

This option allows you to configure the Camera Module to work with your Raspberry Pi. This will be of no concern if you do not have the Camera Module. However, Chapter 16 discusses the Camera Module and using it, so we'll return to this option then.

6. Add to Rastrack

Rastrack is a map of the world showing where Raspberry Pi systems are located — or at least those that have been registered. This option allows you to add your Raspberry Pi to the Rastrack database.

7. Overclock

A computer runs at a certain speed and this is defined by an internal clock. If you _overclock_ a computer it makes it run faster and this option allows you to do that. Chapter 33 discusses overclocking, so don't change this option at present. Beware that overclocking can overheat the CPU and may reduce the life of your Raspberry Pi.

8. Advanced Options

Selecting this menu item displays a sub-menu with several more options:

A1. Overscan

This option controls the screen size on your monitor or how it is positioned on the screen. You can use this option to control the width of any border that is displayed around the edge of the display. For example, if when you boot into Raspbian the screen does not fill the monitor display and has a black border around it, you can come back to this option and select an 'overscan' option which should remove the problem and allow full use of the display.

A2. Hostname

This allows you to give your Raspberry Pi a name that will be displayed if it is connected to a network. By default this is 'raspberrypi'.

A3. Memory Split

This is another option I would suggest you leave at its default setting for now. Essentially this option allows you to control how much of the available memory is allocated to different parts of the hardware system.

A4. SSH

This setting allows you to have two computers connected together, normally with one controlling the other. This is not covered in this book so for our current purposes you should ignore this option.

A5. SPI

Some devices — such as PiFace — require that this option be set to automatic as devices such as this use the SPI (Serial Peripheral Interface) to talk to the Raspberry Pi. Again this is an advanced use of the Raspberry Pi that we won't be covering in this book, so leave the setting as it is.

A6. Audio

By default sound will always go through the HDMI socket if an HDMI device is connected (Auto). This option allows you to override the Auto setting and select the audio output. This is covered in Chapter 24.

A7. Update

This option allows you to install the latest version of raspi-config, if one has been issued. You will need an Internet connection in order to check for this and to download it. However, as you have just installed what will be the latest version of Raspbian available, there is unlikely to be an update at this point, so this is also an option you can ignore for the time being.

9. About raspi-config

Not really an option, this takes you to a few lines about the purpose of rasp-config tool which you can quickly read. Press <ENTER> to come back to the main menu.

To exit raspi-config and apply any changes you have made you need to highlight the <FINISH> button. Do this by pressing the right key until you get there, and then press <ENTER>.

You will then be asked if you want to re-boot your Raspberry Pi. Select 'Yes' and watch the process take place. Remember, if you have opted to 'Expand Filesystem' on your SD Card this re-boot may take a few minutes and there may appear to be periods of no activity. Just give it a bit of time.

Log On

When Raspbian has finished re-starting you will be asked to provide a login and a password.

By default, unless you have changed the password in the setup, they are:

Login: pi

Password: raspberry

You will need to type these in at the keyboard and press <ENTER> at the end of each line. These are like any other user name and password in that they are case sensitive — so 'password' and 'PASSWORD' and 'Password' would be seen as three distinct words.

When you type in your response for the password you will not get any visual feedback on the screen — not even the normal row of asterisks. You have to trust your typing. If you press the <ENTER> key and you have made a mistake you will be asked to enter the login and password details again. Don't be discouraged — you will eventually succeed! (One valid reason to change your password is to make it shorter and therefore easier to type in — but this is a decision for you!)

When you have entered both correctly, the following will appear on the screen:

pi@raspberrypi ~ $ _

The '_' at the end of the line is in fact a blinking 'underscore' line and this line is called the prompt. The prompt shows you where text will appear as you type at the keyboard. The detail in the line also has some other significance which we'll look at shortly.

Now you can wait as long as you want, as Raspbian is waiting for you to give it something to do — a command — and it will continue to wait until you do so! Because this is where you enter commands this line is referred to as the _command line_ or command prompt, and we'll have a look at it in the next chapter.

Respecting Pi

Just before we press on with some programming, it is worth saying a few things about turning your Raspberry Pi off and the changing of leads and SD Cards. The two things you should always do first are:

Log out of the Operating System you are using, and close it down if required.

Turn power off at the power switch to switch off your Raspberry Pi.

Logging out of the Operating System (Raspbian or otherwise) is important as it allows the software to ensure all your data and any associated files have been correctly saved and for the OS to finalise any additional housekeeping it requires to do. This ensures the integrity of the Operating System, your work, and the security of your data and any other work. It's surprising how many people don't do this and just flick the power switch. We'll look at how to shut Raspbian down correctly in the next chapter.

So don't just turn the power off at the power switch before having logged out! Avoid the temptation to just pull the plug from socket on the board as this can do damage in a variety of ways. Once you have logged out and the power is safely off you can disconnect leads as you wish.

As a rule of thumb you should never change any of the other leads while the power is applied to the Raspberry Pi. And definitely never ever try to replace an SD Card with the Raspberry Pi switched on as you may corrupt the data on it and possibly damage the Raspberry Pi.

Generally it's OK to change the audio leads if required and also the USB leads and the Ethernet cable — just be careful how you handle the Raspberry Pi when doing so, as dislodging the power cable might have undesirable consequences. If you think you will need to swap leads during your use of the Raspberry Pi then it would be better to set yourself up with some external connections that take the focus away from dealing directly with the Raspberry Pi.
SECTION TWO: MAKING THINGS SING!

You're up and running and ready to rock 'n roll. Arguably you have taken the biggest steps already. Now the fun begins and you will start to make the Raspberry Pi work according to your needs as you learn to issue commands and download and run new programs.

The _Insider_ skills you'll have at the end of this section will enable you to:

  * feel comfortable using Raspbian in both command and desktop modes.
  * navigate your way around the Raspbian filing system structure and understanding its layout and function.
  * create files and directories, and moving them as required.
  * interpret and understand information produced by Raspbian.
  * open and work the LXDE Desktop environment.
  * use important tools such as web browsers and text editors.
  * use the Pi Store to download and configure programs.
  * use the command line to install and update software.
  * turn your Raspberry Pi off correctly.

7: Raspbian Welcome

There are two ways you can interact with the Raspbian Operating System — through the command line using the keyboard and through a graphical interface using the mouse and keyboard. In this chapter we'll start by utilising our typing skills!

The Shell is the name given to the environment you find yourself in after you have entered your password. You will also hear the term 'Bash' used a lot and this is another term used for this environment. They provide you with a place where you can type in commands. These 'Bash commands' will either return information or perform a specific action. Learning these commands and what they can and cannot do is fundamental to making good use of the Shell.

Your communication interface is the prompt — the flashing line on your screen. The prompt is the start of everything you do and from here you can type commands that the Shell will implement for you. The prompt provides you with information about where you are within the structure of Raspbian and within the SD Card itself, and is where you are 'located' in your virtual world.

When you first launch Raspbian and entered your login user name and password the default prompt should look like this:

pi@raspberrypi ~ $ _

Let's dissect it.

pi

This is the name of the user logged in. You will recall that when you were prompted to login you entered 'pi'. Your _user name_ is pi.

@

This symbol is to denote the finish of the user name and separate it from the rest of the prompt.

raspberrypi

This is the _host name_ of the computer that Raspbian is running on and can be used to identify it from other computers that may connect with it — for example, if you are connected to a network.

~

The tilde character has a special meaning in that it signifies you are working in what is called your _own directory_ which is called pi (the name of the logged in user). This is a special area on the SD Card that is available to you to use. It is sometimes referred to as your ' _home' directory_ where you store your own work. Bear with me for a moment!

$

The dollar symbol indicates that you are logged on as a normal user — there is also a super-user, which as you might expect will give you special powers. There are occasions you will need to become a _super-user_ — though sadly you will not be able to leap tall buildings in a single bound.

_

This is the flashing cursor and is simply an indicator of where anything you type at the keyboard will appear. It's your old friend the prompt.

Everything you access in Raspbian and any files that you create using it have to be stored somewhere. Physically they are on the SD Card in the form of data files. A computer file itself has a particular format that is often unique to the software that created it. You don't need to know what the format is — just that it exists. There can be literally hundreds of files on the SD Card, so each one needs to be individually identified with a unique name. These files are then grouped together and placed in uniquely named directories. All the files and directories you create will be placed inside your Home directory.

You can think of the Home directory as a drawer and each of the folders in the drawer are the directories while the sheets of paper in the folders are the files. But in turn, sometimes the folders may themselves contain other folders and then even these folders in turn may contain folders, each of these folders with their own files! What we end up with is known as a _hierarchical_ filing system. The location of a particular file is given by its name and the folder (directory) it is held in.

For example, your filing system at home might contain a folder that is labelled 'Bills'. This in turn may contain a folder (or divider) called 'Electricity' and in here you place your Dec2014 electricity bill. You could tell someone that the location or address of a particular bill you are looking for was:

home.bills.electricity.Dec2014

This exact same structure is used to organise files in Raspbian. At the prompt, type the following two letters exactly as it is at the keyboard and press <ENTER>:

ls

This is what Raspbian responded with on my Raspberry Pi:

python_games

This indicates that the Home directory contains one file — called 'python_games'. Only this is not a file it is a _directory_ , a folder which may contain other folders and files. I know this because it is listed in blue whilst files are shown in other colours such as pink. But you can confirm this for yourself using the 'file' command. Type this at the prompt:

file python_games

Again, note the use of lower case for the 'file' command and also note how the exact spelling of 'python_games' is matched. Raspbian will respond with something like:

python_games: directory

This indicates that python_games is actually a directory (folder) and in turn probably contains other folders and files. You can use the 'file' command to get information about anything that is listed.

Directory Ins and Outs

We can dip into a directory and look at its contents by using a change directory command. Type this, again paying attention to the character case:

cd python_games

(From this point you should assume that you always press the <ENTER> key at the end of the line to 'execute' the command).

You will notice that the command line prompt changes to:

pi@raspberrypi ~/python_games $

The fact that we are now 'in' the python_games directory is signified in the prompt. Therefore the prompt always shows where we are located in the overall hierarchy of the Raspbian filing system. It is important to know this because, unless we specify otherwise, any commands we type at the prompt are executed on the contents of the _currently selected directory_ (CSD). To prove the point, enter the 'ls' command again. The type of output you see will be a listing of files and directories stored in the python_games directory. These files are coloured to indicate they are different types of files. You can find out about any of them by using the 'file' command agaian, being careful to use the correct spelling and character case. For example:

file boy.png

We used the 'cd' command to move down a directory level. We can also use the 'cd' command to move up a directory level thus:

cd ..

Note that there is a space between the 'cd' and the two dots — and by the way, the dots are not some sort of optional punctuation: they are critical. The two dots mean 'go back up' a directory. The prompt changes to reflect that we are back in the home pi directory. You can use the 'cd' command in this way to navigate your way around the directory structure of your SD Card. You can't do any harm using that particular command in this way so you might like to experiment and investigate further.

The home directory is not the top of the directory chain. If you type:

cd ..

Again you will find the prompt changes to:

pi@raspberrypi /home $

This indicates that we are now in the Home directory. This is not to be confused with your pi directory (which is the home of your work). The Home directory is used to store all the separate directories of the various users of this computer. From this you'll understand that you can have several different users of the Raspberry Pi. This is no different from any other computer you may have used, where you can have different users.

There is one final directory that exists above this and it is called the root directory. So if you type:

cd ..

The prompt will change to:

pi@raspberrypi / $

The '/' signifies 'root'. The _root directory_ is special and is covered in Chapter 11.

Each time you change directory you can use the 'ls' command to list the contents of the directory. The root directory contains quite a few directories that have special functions and we'll learn about these as we progress.

You can also use compound addresses if you wish. So if you wanted to get back to your pi directory from the root directory you could give the 'cd' command the full path to change directly to it thus:

cd /home/pi

This would take you back to where you started. However, as we saw in our original dissection of the prompt, the tilde ('~') character represents the pi directory and we can also use it in the file path thus:

cd ~

If you wanted to move up two levels in one go then you could use the double dots to do so thus:

cd ../..

In fact there are a whole host of command combinations you can use with the 'cd' command to move you up and down the directory structure of your SD Card.

Because a filing system can have many branches and in turn sub-branches for these then it is often referred to as a tree structure which, conveniently, has its root at the base.

Hierarchical Filing Systems

An example of the tree-like structure of a hierarchical filing system is shown below in Figure 7a. Each folder or directory is represented by a named box. The first of these — Home — is in the root directory of this structure as everything comes from it.

Home contains two sub-directories called Banking and Services. If you are in Banking you cannot go directly to Services — you must go via Home. Services also has sub-directories which are Electricity and Gas.

The relationship between particular directories with a filing system is often referred to as _parent-sibling_. Home is the parent of Banking and Services. Banking is a sibling of Services. Electricity and Gas are the child directories of Services.

_Figure 7a. The tree-like structure of a hierarchical filing system._

Command Line Memory

The command line has an inbuilt memory feature. If you have tried some of the examples listed above, now try pressing the <UP> and <DOWN> arrow keys. Each time you enter a command and press the <ENTER> key the line you have entered is 'remembered' by Raspbian. So rather than having to re-enter a line of text each time you can simply 'scroll' to it using the <UP> arrow key. Once you have reached the line you can use the <LEFT> and <RIGHT> arrow keys to move the cursor along the line. In this way you can edit it if required. This is a very useful short cut and can save you a lot of typing.

Is It Linux?

When you are using Raspbian you will often come across a lot of other terms used in relation to it. These terms include but not necessarily limited to Linux and Debian Wheezy. These are both Operating Systems which very are similar but not identical.

Linux is the name of an original all-encompassing Operating System. It was first released in 1991 by Linus Torvalds (hence Linux) and has a unique place in the computer community in that it is free of charge.

Linux is today released under something called the GNU General Public License. Whilst most software licenses take away the end user's ability to alter and adapt software, the GNU licence by contrast protects and guarantees your freedom to make any changes and share them as you feel fit.

This means that all upgrades to the software are free of charge. It also means that people can use the software to create their own versions of Linux specific to their own needs or requirements, and that these versions can be freely distributed.

One of the most popular derivatives of Linux is Ubuntu. Another is Debian, and Debian-Wheezy is a release version of Debian (in fact it is the codename for Debian 7.0). Raspbian is a derivative of Debian-Wheezy that has been re-worked specifically for use on the Raspberry Pi. Pidora is another Linux derivative and is another Operating System available for the Raspberry Pi (covered in Chapter 31).

Switching Off

You may not be finished with your programming session yet, but if you did want to finish off and close Raspbian down safely you would use the following command at the prompt:

sudo halt

Raspbian will respond with some lines of information on the screen informing you that it is doing as you requested. Finally the screen will go blank. The lights on your Raspberry Pi will also flash a bit until the Power indicator light is the only one illuminated. At this point you can disconnect the power.

The next and subsequent times you turn your Raspberry Pi on the boot-up process for Raspbian will be the same, and will go straight to the Shell prompt ready for action.

If you have used a NOOBS Card to install Raspbian, then when you re-start you will encounter a screen prior to arriving at the Shell, telling you to hold down the <SHIFT> key if you want to enter recovery mode. This is a way of being able to re-install your Operating System should it become corrupted.
8A: The Desktop

Raspbian also provides you with the option of running a Windows or Mac-style desktop environment, using your mouse to control and select files and programs. This may be the way you prefer to use your Raspberry Pi from now on, although your learning process should not neglect the Shell.

At the time of writing the desktop environment shipped with the Raspberry Pi for the foreseeable future is called LXDE. If you have used a Windows-based PC or a Mac then you will be quite familiar with the concepts here. If you have used a Linux-based PC then you may have used something very similar before; this is because Raspbian is based on Linux, as we read in the last chapter.

However, LXDE, which stands for 'Lightweight X11 Desktop Environment', requires software called X-Windows for it to work. X-Windows is relatively large and clunky for the Raspberry Pi and although Raspbian has been released with the Pi in mind, it is still not fully optimised to work on it. This means that it can, in some cases, be a bit slow when doing certain tasks. With this in mind the Raspberry Pi Foundation are working on a replacement for X-Windows and a new desktop called Maynard. Maynard is being developed for the Raspberry Pi. The aim is for a desktop that runs faster and be more efficient using an underlying piece of software called Wayland which will replace X-Windows. Chapter 12 contains details of Maynard and also shows how you can download and try the development version for yourself.

Which LXDE?

Since the original edition of this book was published (November 2014) a more refined version of the Desktop has been released. This chapter has since been revised to cover the 'new-look' Desktop. Thus if your version of Raspbian is dated '24 December 2014' or later and looks like the image on the previous page, you will be totally up-to-date with content.

The original edition of the book covered earlier versions of Raspbian where the 'look and feel' of the Desktop use was different. There is no change to functionality and the software installed. If you intend to continue using an earlier edition of Raspbian then there is a second Chapter 8 in this book which is specific to the earlier versions of Rapbian. You can continue reading about the New Desktop here or you can jump ahead and read about the Old Desktop in Chapter 8B by clicking Here.

The plan is for the new 2015-look Desktop to be continually improved and enhanced. These changes will be reflected as quickly as possible and will be explained in the book support pages at www.brucesmith.info. Go the the home page and click on the book icon to find your way to any updated information.

First Screening

To start X-Windows, at the command line prompt enter:

start

The screen might go blank but not for long and after a few seconds the desktop environment will appear.

On my Raspberry Pi it is similar to what is shown below in Figure 8a.

_Figure 8a. The 2015 Desktop is refined and uncluttered._

As you can see this is a very different look to the Shell, but bear in mind this is running on top of the Shell and we can still access the Shell and execute Bash commands if we wish. Indeed, a lot of the things we do in the desktop environment are simply graphical visualisations of Bash commands.

It is very rare nowadays that people have not previously used a graphical user interface (GUI) like this, be it on a computer, a tablet or phone so you should have no trouble navigating your way around the screen. Keep in mind you will be using the mouse (and sometimes keyboard) to perform your actions. If you move your mouse you should see the pointer move around the screen in response.

The LXDE screen is divided into two distinct areas. First there is the large image of the Raspberry Pi logo position in the middle. This is just decoration and is often referred to as 'wallpaper'. Most computer desktop environments have this kind of decoration. This is your main work area and you will open directories and files onto this.

Across the top of the screen is the Menu Bar (sometimes called the 'Task Bar') and this allows you to access many other features of the Desktop. From here you can run other programs, and you can also manipulate files and directories.

_Figure 8b. The Menu Bar with its program menu button and five default Launchers._

By default there are six icons (shown in Figure 8b) and from left to right these are:

Menu

Click on this to display a drop down menu which lists a number of other menu options. From here you can access a range of programs and utilities packed into Raspbian. I'll examine this 'Program Manager' in detail shortly.

Epiphany Web Browser

This allows you to 'open' a web browser you can use to surf the Internet. Full details in Chapter 10.

File Manager

This icon looks like a filing cabinet and it provides access to the File Manager. This is your starting point to access your files and directories.

Mathematica & Wolfram

Not so long ago these very specialised programs were only available on high specification computers — now they are available on the Raspberry Pi! One is a command-line version of the Wolfram Language. And the second is Mathematica which provides a document-based way of interacting with the Wolfram Language. These are not discussed any further in this book but the following website is a great source of information on the project:

<http://blog.wolfram.com/>

Look for the Raspberry Pi link.

LXTerminal

Th screen icon opens a window that provides you with access to the Shell so you can enter Bash commands from the Desktop. We'll use this shortly. I'll often refer to this as the 'Terminal Window'.

Opening Icons

To 'open' a Menu Bar icon you must move the mouse pointer over it — this 'highlights' it — then click on it. The term 'click' means pressing the left mouse button once the icon has become highlighted. This will 'open' the item, and may be used to display a second menu. If the menu option has a '>' to the side of it this indicates a sub-menu as illustrated in Figure 8c.

_Figure 8c. Selecting options from a sub menu._

Another term often used is 'double-clicking' — this means that you click the left mouse button twice in quick succession. This action is usually indicated by the shortened form 'double-click on the xxx icon' where 'xxx' is the name of the icon in question. Just a reminder — there can be a slight delay from double-clicking to the program appearing, so wait a second or two. The temptation is to double-click again as you think nothing has happened — but what happens then is you get several versions of the window or program appearing!

Window Anatomy

Windows are the staging areas for almost everything that you'll be doing in the desktop environment and give or take they are all structured in pretty much the same way, so if you can use one window you can use them all. You access windows through the File Manager icon (the one that looks like a filing cabinet) in the Menu Bar. Click on the File Manager launcher icon and a window similar to that shown in Figure 8d. will be displayed.

_Figure 8d. The Home Folder window is always opened first when you select the File Manager._

Across the top of all windows is the Name Bar. This is where the name of the window that is open is displayed. The 'pi' directory is opened by default — the same directory we looked at in the previous chapter. The name bar also includes four important icons — one on the left and three on the right.

Figure 8d. Most windows have the same structure, which makes using them easy.

To move a window around the Desktop click in the name bar and keep the left mouse button depressed. Move the mouse and the window will move in the same direction (this is called 'dragging' the window). Once then window is in the correct position release the mouse button.

To close a window click the 'X' button at the far right hand side of the window.

To toggle the size of a window from current size to full screen and then back again use the 'square' icon called the 'maximise' button.

Use the 'underline' icon ('_') to minimise your window and place it on the Menu Bar at the top of the screen. Click on its name in the Menu Bar to re-open the full window on the Desktop.

To resize your window move the mouse pointer to the edge of the window until it changes shape (it will change to an arrow pointing to a line in the direction you are going to move). Then click and hold down the left mouse button and drag the windows in or out until it reaches the size you want.

Most windows — such as the one illustrated in Figure 8d — also have a resize icon in the bottom right hand corner (note the dotted triangle). This allows you to click, hold and drag out or in to resize the window.

The top left hand corner of the Name Bar will normally contain an icon that looks like a folder. If you left click this it displays a menu of options, as shown in Figure 8e.

_Figure 8e. Menu options available from the Name Bar._

'Send to Desktop' allows you to send the window to an alternative Desktop to the one you are using, or to copy it to both Desktops! Both? Yes, you can have more than one Desktop work area and you can switch freely between them — a bit like changing channels on the TV. The new channel has something different, but the old one is still there if you want to go back to it. More later in this Chapter.

The 'Layer' option allows you to define whether you want your window to always be the top one or the one that is always at the bottom. The Move and Resize options provide easy ways of resizing and positioning your window. Iconify and Maximize have the same effects as described above. Roll up/Down can reduce your window to just the Name Bar on the Desktop. Click the Maximise icon to get the full window back. Un/Decorate removes the Name Bar from the window. 'Close' closes the window.

Using LX Terminal

You can access Bash and the command line directly from the Desktop. Click on the 'LXTerminal' icon in the Menu Bar — it's the one that looks like a computer screen. After a few seconds the Terminal window will appear. Inside this you should see the familiar prompt.

Click inside the window and enter commands in the normal way. (The Terminal window must be selected otherwise your typing will not appear inside it.) Because it is a window you have the added bonus of being able to use the scroll bar at the right-hand side to scroll up and down through previous output. You can also open additional windows or new windows as tabs. This means you could have several windows open and each one could have a different currently selected directory, allowing you to work in different places at the same time. Use the 'File Menu' option at the top of the window to do this.

_Figure 8f. Enter commands inside the LXTerminal Window. Here is a window with a listing of the root directory._

Using the Edit Menu, you can copy sections of output as well. The Edit Menu also provides a 'Preferences' option that allows you to customise your window display.

Although having several Terminal windows open at once is a good idea if you need to see several things together. It is much neater to have the one window with each directory display being one in a separate 'tab'. You can manage tabs from the Tab Menu and this even allows you to name the tabs individually for ease of reference.

_Figure 8g. You can access menu items using hot key actions._

Many of the menu items have key combinations associated with them. These are the keys you can press on the keyboard to action the menu function. The designated keys need to be pressed at the same time. In the image below for the Tabs Menu, if you want to name a tab you can select the 'Name Tab' option from the menu or you can press the <SHIFT>, <CTRL> and <I> keys together for the same outcome.

Program Manager

As mentioned the Menu button contains the Program Manager. This allows you to access, from the Desktop, numerous programs and utilities. If you left click on this you will get a pop-down menu through which you can access grouped selections.

_Figure 8h. The Program Menu allows you to access other programs. Programs are arranged by their category type._

The items on the menu give you a clue as to the type of programs you will find. Move your mouse over each of the menu options in turn and a sub-menu will pop up to the right of it, showing the programs available to you. To start (or run) a particular program, move the mouse over the required item (it will be highlighted) and click the left mouse button.

The Program Manager is divided into five sections each separated by a line across the menu. The top portion, and largest section, is where you can find applications and games to run. These are ordered into 'Programming', 'Internet', 'Games', and Accessories'. We'll explore many of these in detail during the course of this Insider Guide.

The 'Help' Menu, which follows next provides two options. 'Debian Reference' opens a web browser window which allows you to access information about Raspbian, or more correctly a specific version of the Debian distribution of Linux, from which Raspbian is created. We'll look at this in the next Chapter when we delve back into Raspbian. The 'Raspberry Pi Help' option will open a web browser window on the Raspberry Pi website Help page and therefore requires an internet connection.

The 'Preferences' option provides a suite of applications which you can use to configure the Desktop to suit your own tastes and requirements. There is quite a lot here, so we'll go into more detail later in this chapter.

The 'Run' option will display a simple window into which you can type a Bash command to be executed. This option is no good for commands such as 'ls' as there is no window for them to display their output. This option is used when you want to run a specific command to do something that doesn't require any interaction with the user.

Click the 'Shutdown' option to start the close process. This will present you with three options allowing you to 'Shutdown' completely, 'Reboot' or just to 'Logout'. If you select the 'Reboot' option you will be returned to the command line login after the Raspberry Pi has shutdown and restarted.

Playing Python

There is a good selection of simple games that you can start to play with from the Desktop right now! Even if you are not a games fan, have a look at this and get used to using the interface.

These games are all written in a language called Python and this is available for you to use on the Raspberry Pi. In fact it is one of the most popular programming languages in use today. To try an installed Python game, select the 'Python Games' icon from the Games Menu in the in the Program Manager. After a few seconds you will be presented with a menu to select your audio output option — use the default 'Leave as is' and then select OK to go to the games listing — similar to that shown below in Figure 8i.

_Figure 8i. The Python Games window._

All you need to do is select the game you are interested in by clicking on the menu item and then double-click on the 'OK' button. The menu window will disappear and the game window will appear.

Some games contain details of what you need to do or at the very least you are prompted with what keys you should use. When you finish the game, close the window and the games menu will reappear.

My young son loves 'The Spot Game' — his name for Four-In-A-Row. It is a good exercise if you are looking to teach others how to control the mouse pointer and drag things around the screen. It helps with hand-eye co-ordination. Much later in this book we'll look at how to modify this program to create either an easier or harder game!

_Figure 8j Four-In-A-Row is a popular board game you can play._

Menu Bar Take 2

The right hand side of the Menu Bar contains icons that display status information. The most interesting of these is the 'CPU Usage icon'. CPU is short for Central Processing Unit which is the ARM chip in the centre of the Raspberry Pi board. This icon shows you just how hard — or not! — it is working. It will say 1% when nothing is happening and may well get up to 100% when it is going flat out! Keep an eye on it as you launch more programs and notice how it can get quite busy.

The digital clock is self-explanatory and if you click on the time you will get a calendar for the month displayed below it.

You can add and remove your own icons to the Menu Bar as well. For example, personally I'm very unlikely to be using the Mathematica or Wolfram programs so I could remove these from the Menu Bar and add more appropriate icons for me should I wish. If you right-click on one of the icons in the Menu Bar it will display a pop-up menu. From this select 'Application Launch Bar Settings'. Figure 8k shows how this looked on my Raspberry Pi.

_Figure 8k. Application Launch Bar Settings window._

The left hand side of the window lists the installed 'Launchers'. You can select the ones you don't want and click the 'Remove' button. To install one you do want — locate it in the 'Installed Applications' window on the right and press the 'Add' button. You can also use the 'Up' and 'Down' buttons to re-arrange the positions of the launchers on the Menu Bar.

The Web Browser icon launches Epiphany Web, which is a web browser. If you have used Microsoft Explorer, Firefox or Chrome on a PC or Mac before then this will be very familiar to you. If you have a number of windows (of any type) open on your Desktop then you can minimise them all in one go simply by clicking on the Minimiser button. The windows will be replaced by a small rectangle in the central portion of the task bar. The program doesn't stop operating when it is minimised and to restore it to a full window on the Desktop just click on the associated window button in the Menu Bar — the buttons are named when the windows are minimised so you will see which is which.

Panel Settings

The Menu Bar can be configured to suit your own working requirements. You do this via the Panel Preferences window which you access by left-clicking anywhere in the Menu Bar itself. The window is shown in Figure 8l.

_Figure 8l. The Panel Preferences window gives access to four tabs._

The Geometry Tab allows you to define where the Menu Bar is displayed on-screen and how much space it occupies. By default this is the 'Top' but, if you prefer you can have it at the 'Bottom', 'Left' or 'Right'. Select the button under Position. The other settings on this tab allow you to define how the icons within the Menu Bar are arranged and to alter other elements of its size.

The Appearance Tab allows to you adjust the look and feel of the Menu Bar. 'System theme' is the default, but if you select 'Solid colour', for instance, the Menu Bar blends into the Desktop and is quite a nice effect.

The Panel Applets Tab is where you can define what appears in the Menu Bar, specifically to the right of the Launcher area. Click on the 'Add' button to display a menu of available applets, click on the one you require and click 'Add'. Your chosen applet will appear in the right hand side of the Menu Bar. For example, to add a volume control, scroll to 'Volume Control' and highlight it, then click on 'Add'. A speaker icon will appear on the right. If you click on the speaker icon a volume control will appear and allow you to adjust the level of sound output. The 'Spacer' and 'Separator' applets allow you to add padding between applets on the Menu Bar.

Conversely you can remove applets from the Menu Bar by selecting the applet in question and clicking on the 'Remove' button.

The final tab, 'Advanced' allows you to define important properties and set what applications are used for machine critical applications. These should be left alone

If you avoid the Advanced Tab then there is plenty to experiment with in the other three tabs of the Panel Preferences. Just make a note of your initial settings and you can play with the options therein without fear and safe in the knowledge you can get back to your original starting point.

Program Preferences

One of the later options on the Programs Manager is 'Preferences'. This menu option allows you to customise your working environment — both in terms of look and feel and also in how it responds to your actions. Each of the options can be tested before you apply the changes so at this point you have a good chance to experiment and cancel if you don't want to go ahead. Note also some changes that you make will not actually take effect until your next login to X-Windows. A brief outline of each option is given below.

Audio Jack Control

This option opens a window that provides the ability to control the audio output on the composite jack plug. The subject of sound is covered in Chapter 24.

Keyboard and Mouse Settings

This option allows you to change things like the keyboard autorepeat rate and the sensitivity and acceleration of the mouse across the screen. You do this by clicking either side of the slider to move it left or right. If you are left handed you can also swap the action of the mouse buttons around.

Monitor Settings

This opens a window which displays information about your current monitor resolution and refresh rate.

Screensaver

Allows you to set up a screen saver that displays after the Raspberry Pi has been left idle for a pre-determined amount of time. Screen savers originated to help protect old CRT displays from being burnt with the image of an unattended desktop. Nowadays modern screens do not suffer from this and in-reality a screen saver is not required, and screens should be turned off when not used to reduce their energy consumption. You can select the 'Blank Screen Only' mode option to achieve this.

Desktop Session Settings

These are quite advanced options so I would strongly suggest you do not go anywhere near these options until you are sure you are much more comfortable using the Desktop.

WiFi Configuration

This opens a window where you can set up and connect to a wireless network. Chapter 13 explains how to do this.

Windows Settings

This opens a window titled 'Openbox Configuration Manager'. This window supplies a number of interesting tabs that allow you to change the overall colour scheme and appearance of the Desktop.

Theme and Appearance Settings

This opens a window entitled 'Customise Look and Feel'. There are a number of items you can change here. One is the appearance of widgets — these are the tabs and action items that appear in your windows. The default is Mist. You can look at other styles by selecting other named styles. Click on the tabs at the top of the window to investigate other style areas.

_Figure 8m. The Customise window provides several tabs which contain settings you can adjust to suit you._

Desktop Preferences

You can adjust the look and feel of your Desktop by editing the Desktop Preferences settings. Right click anywhere on the Desktop and select the Desktop Preferences option. This displays a window with three tabs — Appearance, Desktop Icons and Advanced. Under Background in the Appearance tab you can change the images and adjust how it is used as the Desktop wallpaper. In addition you can change the font used for labelling.

File Manager

The File Manager provides all the tools you need to manage your files and directories. If you have experience using a PC or a Mac then you will find this quite familiar. As we saw earlier you click on the 'File Manager' launcher icon on the Menu Bar you will be presented with a window similar to that shown in Figure 8r.

When you look in the main part of the file window you will see several icons. You may recall that the 'python_games' folder was present when we used the 'ls' command in Cahpter 7. 'Desktop' is creade when you use the 'startx' command for the first time. In addition there is 'New' which is a file I have created this). Note how the directories have icons that look like folders, which is really useful in distinguishing them from files such as 'New'.

Immediately above these icons is a small window that displays the currently selected directory in terms of its full path, which is '/home/pi'. In the Name Bar at the top of the window this is also reflected — pi. On the left hand side is an area labelled 'Places' and under this 'Home Folder' (which is 'pi') is selected. This has a house as an icon because it is our 'home' directory.

Double-click on the 'Desktop' icon. A few changes will occur in the File Manager window. Above it the path will have changed to reflect where you are. The Name Bar will have changed to Desktop. And in the Places area the 'Desktop' icon will have been highlighted. Click on the python_games icon to see the result, which is the Desktop output of the directory listing we did using Bash in the last chapter

_Figure 8n. The File Manager window._

In the Places pane click on 'Applications'. The main window will change to show icons that reflect what we saw in the Programs Menu. Double-click on the Accessories icon and you will see icons for each of the programs we encountered before. Double-click on 'Calculator' and watch a digital calculator pop up on your screen! (The small arrows in the top right hand corner of each icon indicate that the icons in view are actually likes — or shortcuts — to the actual applications, ie, these icons are not the application files themselves.)

To return to your home area click the 'Home Folder' icon in the Places pane.

To the left of the small window containing the currently selected directory path you will see some arrow shaped icons. Those bearing left and right arrows can be used to move through the directory structure (but only if you have previously opened the directories as described above). The up arrow icon moves the setting to the parent directory of the one currently displayed. As you click on each of these arrows, the display in the main pane and Places pane will change accordingly. The small down triangle situated in between the other arrow icons is the 'Folder History' icon. If you click and hold this down you will get a list of all the locations you have been to. You can simply scroll down to one of those in the list and click to select that as the CSD (currently selected directory). (Note that this history is only for the current Desktop session and is wiped when you exit X-Windows).

The icon that looks like a folder with a star creates a new tab when it is clicked and this allows you to have several folders open at once in the main window. Once you have created a new tab, click on it to select the folder in question and then you are free to navigate to a new directory without affecting what is open in the first and any other tabs.

Creating with Folders and Files

Using the mouse and the various buttons and icons provided, it is easy to navigate your way through the Raspbian structure. If you want to create and access other areas then you will need to use the File Manager menus to assist you in this.

_Figure 8o. The File Manager menus._

There are seven menus in all and you can see these in Figure 8s. It is worth investigating these and spending some time experimenting with them. This is because many of the other software packages you will use also have menus and many are organised just like these. By being consistent in arranging menus and menu content they are much easier to use as you have already been through the learning curve.

File Menu offers a range of options that allow you to control the way you see things and the ability to create new directories and files. The first two options allow you to create a new File Manager window as a separate window or as a tab. Having two separate windows open is convenient if you want to move files from one place to another. You can simply select the file or directory in one window (keeping the left mouse button pressed down) and drag it into the new window. When you release the mouse button the item will be moved across to that position. (Note here that the item is moved and not copied, so the original item does not remain in the source directory). Using Tabs is good if you just need to access different directories as everything remains in one window and reduces the clutter on the screen.

The 'Create New' option allows you to create a new Folder or a blank Empty File — this was used to create the 'New' file illustrated in Figure 8r earlier. Ensure that your current selected directory is 'Home Folder' and then use this option to create a new file. A window will appear asking you to name the folder. You can enter a new name or leave it as is before clicking the 'OK' button. This will then appear in the icon area. (If you now open a Terminal window and type 'ls' you will see that the 'New' file appears in your listing).

Close Tab and Close Window work as you would expect although in either case you can use the close window 'X' on the right hand corner of the window or tab to the same effect.

The 'Folder Properties' option will display statistical information about the currently selected folder. This includes data like its size and the number of files it contains.

Using Files and Folders

The first four options on the Edit Menu are Cut, Copy, Paste and Delete. You can use these functions on any of the icons that appear in a window. Copy and Paste in combination allow you to make duplicates of items across windows. You should first single click on the item, and then select the menu option and select 'Copy' and then 'Paste'. If you try and paste to the same directory then a window appears asking you if you want to overwrite the existing item or rename the new item. Generally you would rename the new file otherwise you wouldn't be doing this operation! If you use Cut and Paste then the original item selected is removed once it has been pasted to the new destination. A word of warning — be very careful when you rename a file. If you do not do it correctly you can create some issues especially regarding the system's ability to know what type of file it is. Important: Before you attempt to rename a file, read the last section of this chapter which discusses the naming of files.

The Move To and Copy To options provide the same function as using the Copy-Paste and Cut-Paste options. The difference here is when you have selected your item to copy and then selected one of the options, a second File Manager window opens and allows you to use the interface to select your location before pressing the 'OK' button to effect the command.

You can rename a file or directory by selecting the item and then choosing Rename from the Edit Menu. Type in the new name and press the 'OK' button (or press <ENTER>). The 'Select All' option selects all the items in the current directory. If you want to select multiple items rather than all items then this can be achieved by holding down the <CTRL> key and then single clicking each icon you want to select. You can then perform any action you wish on these selected files through the menu options. The 'Invert Selection' option inverts the section on the screen, so for example if you had three files, two of which were selected, inverting would leave you with one file selected and the other two not selected.

The final option on the Edit Menu is a 'Preferences' selection, which allows you to define defaults for Behaviour, Display and Volume Management. There is also an Advanced Tab which is probably best to avoid until you have a deeper understanding of what is happening. The other tabs are worth experimenting with as you can always reset things. Note also that Volume management isn't about sound and loudness! It is about how the system reacts when you insert external storage devices like a USB Stick. Chapter 13 details the use of external devices.

Go and Bookmarks

The first three options on the Go Menu perform the same options as the green icon arrow keys described earlier, allowing you to navigate through folder (directory) history. Those below are almost identical to those you find in the Places pane by default. However, additional items include Network places (if you are attached to a network), and Devices, which displays any attached file systems - covered in Chapter 14.

In addition there is an option called 'Rubbish Bin'. If you delete files (when working in the Desktop only) then they are placed in a special directory called Rubbish Bin (This is the Wastebasket icon displayed on the Desktop). If you select Rubbish Bin then any deleted files will be displayed. This is handy if you want to get back a previously deleted file. When you are in the Rubbish Bin you can click on the 'Rubbish Bin' icon (in the Places pane) to delete all items in the Rubbish Bin. If you do this you cannot get them back — it's like throwing away the contents of the rubbish bin for good!. So before you take such a drastic step make sure you don't need them.

Another option here is 'Go to Location'. If you select this, you can enter an address in the address bar. For example, sleect and enter a backslash, '/'. Press and you will display the root directory and all the folders in root, the functions of which I will outline in Chapter 11.

Bookmarks

If you have several folders that you go to regularly you can bookmark them. This means you can assign a name to the directory path and this then appears in the Places pane. When you want to go to that directory just click on the name you assigned to it.

The Way Things Look

The View Menu allows you to control how your files and folders are displayed inside the main File Manager pane. It also provides you with the option of seeing special files that are normally hidden from view!

By default the File Manager window displays files in what is called Icon View. The View Menu offers a couple of variations on this whereby icons are displayed in Thumbnail or Compact views. One is essentially larger than the other and the Compact View is certainly useful if you have a lot of folders and files in the currently selected directory. However, a more useful choice is the Detailed List View which displays files as a list and provides information about each of the items on display. Figure 8p shows this for the 'python_games' folder.

_Figure 8p. The Detail List View displays useful information about the files it is displaying in the 'python_games' folder._

In addition to showing the name of each file this list details what type of file it is (recall the 'file' command from Chapter 7) along with the size of the file — that is the amount of space it occupies, as well as the date the item was created or was last changed (modified). You can use the 'Sort Files' option to re-arrange your files in this view in a number of ways and it is worth taking the time to experiment with this — only the display changes; the files themselves are not changed in any way. As well as arranging files alphabetically (ascending or descending — A-Z or Z-A), you can list them by size, type or time they were last modified.

Figure 8p also shows how changing the 'Side Panel' option to 'Directory Tree' alters the appearance of the Places pane. It actually changes to a Directory Tree pane so you can see the overall structure of where you are working.

One of the areas we have discussed is the very bottom information bar across the base of the File Manager window. On the right hand side you have details of how much total memory you have and also how much free memory you have for your files. In Figure 8t you can see that there is a total of 7.1GB available of which 4.4GB is free for use. This space relates to the SD Card. If you have an 8GB memory card then these figures will reflect that too. So this is a good way to keep track of how congested your SD Card is becoming.

On the left hand side information is given about files. In the example above 78 items. Sometimes it will refere ti a umber of hidden files, these are used by the Operating System. If you want to see all the files, including the hidden ones, select the 'Show Hidden' option from the View Menu. Do not delete or do anything with these hidden files — they are used by the other programs. Good to know they are there, but re-hide them once you have had a gander.

There is a final menu called 'Tools'. The first option here allows you to open a terminal window for the currently selected directory whilst a second option allows you to 'Run a Command in Current Folder'.

Keyboard Shortcuts

Many of the windows that you open in LXDE give you the ability to implement actions from the keyboard. This is indicated by having a letter in a tab or menu title underlined. For example in the File Menu on File Manager the F of File is underlined. This means you can open the File Menu by pressing the F key in combination with the <ALT> key. This would be represented as <ALT>-F in this text.

When the File Menu pops up the listing also contains some key combinations. For example pressing <CTRL>-N will open a new window. Note that the new window will not be created if the drop-down menu is present. So rather than going to the File Menu you can simply press <CTRL>-N to create a new window. These short cuts become quite intuitive and you will soon memorise them just by using them.

File Names

We have already encountered several different types of files in the 'python_games' directory. You may recall these files ended with '.png', '.wav' and '.ogg' Some of the image files detailed in Figure 8t end with '.png'; these are pictures of various kinds. The various filename endings are called the filetype and they define what sort of files they are. The '.png' is a graphics file, files that end with '.wav' are sound files and Python files end in '.py'. In fact there are a whole host of file types and you will get to know these as you use your Raspberry Pi. This is not just indicative of the Raspberry Pi — you will find the use of file types on just about all computers. You may even be aware of some already.

If you look through some directories using the Detailed List View of File Manager you will be able to see from the Description column what filetypes are which. You can also group files by file types by sorting them by File Type through the View Menu.

Therefore when you rename a file using the 'Rename' option you must be careful to preserve the file type — those last two or three letters after the full stop. If not then you will confuse the Operating System. If you rename a '.png' file to a '.txt' file then the program that opens .'txt' files will not be able to do so and you will possibly also wonder why. So this is the reason I warned you earlier about being careful if you rename a file. The suffix should remain unchanged.

On the subject of naming files and directories (the latter does not have a file type) try and keep your names simple. You will recall that names are case dependent so you may find it easier to use all lower case letters for your filenames so it makes typing them simple. Never use spaces in your filenames (makes using them in the Shell difficult) and avoid punctuation marks as well as these can be confusing when working in the Shell.

Ultimately you will set up a way of working that suits you. I must admit that I tend to capitalise the first letter in a directory name so that these are always instantly distinguishable from a filename. But that's a personal convention — you can choose what suits your typing skills best!

Wastebasket

The Desktop contains a single icon by default — Wastebasket. This is also referred to as 'Rubbish Bin' in some of the folder views we have seen earlier. When you 'delete' a file it is moved to the Wastebasket (Rubbish Bin). This is a special folder where deleted files are held — as a safety net — in case you change your mind. If you do you can open the Wastebasket folder by double-clicking it and simply drag the files you want to preserve out into another folder.

If you are sure you are done with the files then open the folder, right click in the file window, and select 'Empty Rubbish Bin' from the pop-up menu.

If you do not want the Wastebasket on the Desktop right-click on its icon and select the 'Remove from Desktop' option.

Multiple Desktops

LXDE supports multiple Desktops: by default there is one, however you can implement more. This can be really helpful when you are using a small monitor or are perhaps multi-tasking yourself and want to keep two work streams separate. Or maybe you want to keep games and work separate. So think of these as two very independent work areas. The multiple Desktops operate independently of one another, so you can have a number of windows open on one Desktop and then switch to the another Desktop and have a completely different range of windows or programs open here. When you switch between Desktops, the Desktop you have left keeps working.

To enable additional Desktops, go to Program Menu by clicking on the Menu button and select Windows Settings from the Preferences Menu. Then click on the 'Desktops' button on the ensuing window. The control 'Number of desktops' will show '1'. Click the control to increase the number to '2' or '3' for example.

I suggest you don't go overboard with this option as you will be increasing the amount of memory used and also probably slowing the operation of X-Windows down. If you click on the '(unnamed desktop)' item listed you can actually name each 'Desktop' if you wish. So it could be DT1, DT2 and so forth or more exactly 'Work' and 'Games'

_Figure 8q. Installing multiple Desktops._

Click the 'Close' button to save. If you have a mouse that have a wheel in the cnter, click on the Desktop and rotate the wheel. You will see the names appearing in the centre of the screen. Unless you have windows open and displayed it may not appear that anything is happening.

You can move windows and programs from one Desktop to another quite simply. Select the window or program you want to move and drag it to the right side of the monitor so that it starts to go 'off-screen'. As you do this the number of the Desktop you are moving to appears in the centre of the window. Just release and the transfer is complete. Alternatively, left click on the icon in the top left hand corner of the window you want to move and the first item on that menu list will allow you to transfer the window.

The Panel Settings window (left click in Menu Bar) includes an applet called 'Desktop Pager' that you can add to provide you access to multiple Desktop.

But be aware that each Desktop does use memory and Raspberry Pi resources, so using both extensively can slow things down.

Adding to the Desktop

Earlier versions of the Desktop (prior to Dec 2014) had icons installed on the Desktop itself. These were pre-defined by what was programmed into the distro. Now only the Wastebasket is ëoní the Desktop, and you can remove this if you wish by right clicking on it and selecting the 'Remove from Desktop' option

.

You can add you own Desktop icons simply enough. For example, to add 'Python Games' to the Desktop, click on 'Menu' to open the Program Manager, select 'Games' and then 'Python Games', then left-click and choose the 'Add to desktop' option. You can even change the wallpaper to something more pleasing if you wish, via Desktop Preferences!

_Figure 8r. Adding to and changing the Desktop._

Next Chapter

The next chapter is Chapter 8B which discusses the pre-Dec 2014 Desktop. If you are using the Desktop detailed in this chapter then you can skip straight onto Chapter 9 by clicking Here
8B: The Old Desktop

Raspbian also provides you with the option of running a Windows or Mac-style desktop environment, using your mouse to control and select files and programs. This may be the way you prefer to use your Raspberry Pi from now on, although your learning process should not neglect the Shell.

At the time of writing the desktop environment shipped with the Raspberry Pi is called LXDE . If you have used a Windows-based PC or a Mac then you will be quite familiar with the concepts here. If you have used a Linux-based PC then you may have used something very similar before; this is because Raspbian is based on Linux, as we read in the last chapter.

However, LXDE requires software called X-Windows for it to work. X-Windows is relatively large and clunky for the Raspberry Pi and although Raspbian has been released with the Pi in mind, it is still not fully optimised to work on it. This means that it can, in some cases, be a bit slow when doing certain tasks. With this in mind the Raspberry Pi Foundation are working on a replacement for X-Windows and a new desktop called Maynard. Maynard is being specifically developed for the Raspberry Pi with the aim of running faster and more efficiently using an underlying piece of software called Wayland which itself replaces X-Windows. Chapter 12 contains details of Maynard and also shows how you can download and try the development version for yourself.

However, LXDE will continue to be used by Raspberry Pi users. It provides some excellent features to use and experiment with. In these chapters we'll look at using X-Windows. In subsequent chapters I will often refer to using a desktop environment and this means it will be applicable for use with LXDE and Maynard. Bearing the above in mind it might make you smile to learn that LXDE stands for 'Lightweight X11 Desktop Environment'!

To start X-Windows at the command line prompt enter:

startx

The screen might go blank but not for long and after a few seconds the desktop environment will appear. On my Raspberry Pi it is similar to what is shown in Figure 8a.

_Figure 8a. The LXDE Desktop environment._

As you can see this is a very different look to the Shell, but bear in mind that this is running on top of the Shell and that we can still access the Shell and execute Bash commands if we wish. Indeed, a lot of the things we do in the desktop environment are simply graphical visualisations of Bash commands.

It is very rare nowadays that people have not previously used a graphical user interface (GUI) like this, be it on a computer, a tablet or phone so you should have no trouble navigating your way around the screen. The thing to bear in mind is that you will be using the mouse (and sometimes keyboard) to perform your actions. If you move your mouse you should see the pointer move around the screen in response.

First Screening

The LXDE screen is divided into three very distinct areas. First there is the large image of the Raspberry Pi logo position in the middle. This is just decoration and is often referred to as 'wallpaper'. Most computer desktop environments have this kind of decoration. This is your main work area and you will open directories and files onto this.

Down the left hand side — in two columns as shown on previous page — are a number of small images which are known as icons. Clicking on these allows you to instantly access programs and tools on the Raspberry Pi. We can add icons here and take icons away, so in this respect it is possible to customise the desktop. You may recall in the last chapter that we came across files which ended in '.desktop' — those files are in effect these icons.

Finally, across the bottom of the screen is the Task Bar and this allows you to access many other features of X-Windows. From here you can run other programs that do not have an icon, and you can also manipulate files and directories.

To 'open' an icon you must move the mouse pointer over it, and then double-click on it. The term 'double-click' means pressing the left mouse button twice in quick succession. This action is usually indicated by the shortened form 'double-click on the xxx icon' where 'xxx' is the name of the icon in question. Just a reminder — there can be a slight delay from double-clicking to the program appearing, so wait a second or two. The temptation is to double-click again as you think nothing has happened — what happens then is you get several versions of the program appearing!

On my Raspberry Pi, which was the 'September 2014' release, there were 15 icons on the screen. That's how many could be on your screen as well, but bear in mind things change and by the time you read this you may be using a later version of the software, so yours could be different. Equally you may be using an earlier version of the software which will not include several of these items (but we'll look at how to install them as we visit them). Nevertheless, my 15 and their function are as follows (in no particular order):

Pi Store

We'll talk about the Pi Store in Chapter 10. But this opens a window that allows you to locate lots of both free and purchasable programs for your Raspberry Pi.

Python Games

These are some games you can play which demonstrate the use of a programming language called Python. Interestingly enough one of the games is a snake game! We'll try an example before the end of this chapter!

Epiphany Web Browser

This is a web browser you can use for surfing the Internet. Details in Chapter 10.

Shutdown

Click this to start the shutdown process. You will be asked to confirm the shutdown after which the system will turn off. Allow at least five seconds before turning the Raspberry Pi off at the mains.

Wolfram and Mathematica

Not so long ago these very specialised programs were only available on high specification computers — now they are available on the Raspberry Pi! The first is a command-line version of the Wolfram Language. And the second is _Mathematica_ which provides a document-based way of interacting with the Wolfram Language. The former is quite fast on the Raspberry Pi but Mathematica can be quite slow and requires a bit of patience. These are very specific software packages, and I won't cover this any more in this book. However, within the programs there are links to the documentation and the following website is a great source of information on the project:

http://blog.wolfram.com/

And look for the Raspberry Pi link as.

LXTerminal

This opens a window that provides you with access to the Shell so you can enter Bash commands from the Desktop. We'll use this shortly, and I'll often refer to this as the 'Terminal Window'.

Scratch

This is a great little programming language that is ideal for kids of all ages. The idea of Scratch is that you can create games and animations using 'blocks'. Scratch is covered in Chapter 20 and is within a section all about programming on your Raspberry Pi.

IDLE and IDLE 3:

Another programming language available on your Raspberry Pi is called Python and this is very popular. These icons provide access to software you can use to program in Python. This is discussed in the programming section and specifically in Chapter 19.

OCR Resources

This is a link to the OCR website and contains access to a range of documentation about using the Raspberry Pi. This is worth investigating. The Oxford, Cambridge and RSA Examinations are one of five examination boards that sets examinations in England, Wales and Northern Ireland.

Wi-Fi Config

This program helps you set up a wireless Internet connection — providing you have access to one. You would use this if you are using a USB Wi-Fi dongle. Chapter 13 details this.

Debian Reference

Raspbian is a specific version of the Debian distribution of Linux. This link opens a web-site like display of using Raspbian. We'll look at this in the next Chapter when we delve back into Raspbian.

Minecraft

Possibly the most successful game ever! Free for you to play on the Raspberry Pi. Chapter 28 has full details.

Window Anatomy

Windows are the staging areas for most things that you'll be doing in the desktop environment and give or take they are all structured in pretty much the same way. Across the top of virtually all windows is the Name Bar. This is where the name of the program being run in the window is displayed. It also includes four important icons — one on the left and three on the right.

To move a window around the Desktop click in the name bar and keep the left mouse button depressed. Move the mouse and the window will move in the same direction (this is called 'dragging' the window). Once the window is in the correct position release the mouse button.

To close a window click the 'X' button at the far right hand side of the window.

To toggle the size of a window from current size to full screen and then back again use the 'square' icon called the 'maximise' button.

Use the 'underline' icon ('_') to minimise your window and place it on the Task Bar at the bottom of the screen.

To resize your window move the mouse pointer to the edge of the window until it changes shape (it will change to an arrow pointing to a line in the direction you are going to move). Then click and hold down the left mouse button and drag the windows out or in until it reaches the size you want.

Some windows — such as the one illustrated in Figure 8b — also have a resize icon in the bottom right hand corner (note the dotted triangle). This allows you to click and hold and drag out or in to resize the window.

_Figure 8b. Most windows have the same structure, which makes using them easy._

The top left hand corner of the Name Bar will normally contain an icon similar to the one you may have seen on the Desktop. If you left click this it displays a menu of options, as shown in Figure 8c.

_Figure 8c. Menu options available from the Name Bar._

'Send to Desktop' allows you to send the window to the alternative Desktop to the one you are using, or to copy it to both Desktops! Both? Yes, you can have more than one Desktop work area and you can switch freely between them — a bit like changing channels on the TV. The new channel has something different, but the old one is still there if you want to go back to it. More later in this Chapter.

The 'Layer' option allows you to define whether you want your window to always be the top one or the one that is always at the bottom. The Move and Resize options provide easy ways of resizing and positioning your window. Iconify and Maximize have the same effects as described above. Roll up/Down can reduce your window to just the Name Bar on the Desktop. Click the Maximise icon to get the full window back. Un/Decorate removes the Name Bar from the window. Close closes the window.

Using LX Terminal

You can access Bash and the command line directly from the Desktop. To do this, double-click on the 'LXTerminal' icon. After a few seconds the Terminal window will appear. Inside this you should see the familiar prompt.

Click inside the window and enter commands in the normal way. (The Terminal window must be selected otherwise your typing will not appear inside it). Because it is a window you have the added bonus of being able to use the scroll bar at the right-hand side to scroll up and down through previous output. You can also open additional windows or new windows as tabs. This means you could have several windows open and each one could have a different currently selected directory, allowing you to work in different places at the same time. Use the 'File Menu' option at the top of the window to do this.

_Figure 8d. Enter commands inside the LXTerminal Window. Here is a window with a listing of the root directory._

Using the Edit Menu, you can copy sections of output as well. The Edit Menu also provides a 'Preferences' option that allows you to customise your window display.

Although having several Terminal windows open at once is a good idea if you need to see several things together. It is much neater to have the one window with each directory display being one in a separate 'tab'. You can manage tabs from the Tab Menu and this even allows you to name the tabs individually for ease of reference.

Many of the menu items have key combinations associated with them. These are the keys you can press on the keyboard to action the menu function. The designated keys need to be pressed at the same time. In the image below for the Tabs menu, if you want to name a tab you can select the 'Name tab' option from the menu or you can press the <SHIFT>, <CTRL> and <I> keys together for the same outcome.

_Figure 8e. You can access menu items using hot key actions._

Playing Python

There is a good selection of simple games that you can start to play with right now! Even if you are not a games fan, have a look at this to get yourself used to using the interface.

These games are all written in a language called Python and this is available for you to use on the Raspberry Pi. In fact it is one of the most popular programming languages in use today. To try an installed Python game, double-click on the 'Python Games' icon on the desktop. After a few seconds you will be presented with a menu to select your audio output option — use the default 'Leave as is' and then select OK to go to the games menu — similar to that shown below in Figure 8f.

All you need to do is select the game you are interested in by clicking on the menu item and then double-click on the 'OK' button. The menu window will disappear and the game window will appear.

Some games contain details of what you need to do or at the very least you are prompted with what keys you should use. When you finish the game, close the window and the games menu will reappear.

_Figure 8f. The Python Games window._

My young son loves 'The Spot Game' — his name for Four-In-A-Row. It is a good exercise if you are looking to teach others how to control the mouse pointer and drag things around the screen. It helps with co-ordination as well. Much later in this book we'll look at how to modify this program to create either an easier or harder game!

Task Bar

Across the bottom of the screen stretches the Task Bar. The Task Bar is segmented into three distinctive areas. If you look you will see a selection of small icons on the far left and far right of the bar. In between these two is an area where windows can be minimised. The left side portion of the Task Bar allows you to access additional programs and features whilst the right hand side provides you with information and the ability to shut your Raspberry Pi down.

_Figure 8g. Shows the icons on the left side of the Task Bar._

On my installation of Raspbian there were six icons. From the left, the first two of these are ones you will be using regularly. They are the Programs Menu and the File Manager which we'll deal with shortly.

The Web Browser icon launches Epiphany Web, which is a web browser. (If you have an earlier version of Raspbian it may actually launch Midori which has now been superceded.) Chapter 10 contains more details about this. If you have used Microsoft Explorer, Firefox or Chrome on a PC or Mac before then this will be very familiar to you. If you have a number of windows open on your Desktop then you can minimise them all in one go simply by clicking on the Minimiser button. The windows will be replaced by a small rectangle in the central portion of the task bar. The program doesn't stop operating when it is minimised and to restore it to a full window on the Desktop you just need to click on the associated button in the Task Bar — the buttons are named when the windows are minimised so you will see which is which.

LXDE supports two Desktops: Desktop 1 by default and Desktop 2 as an option. This can be really helpful when you are using a small monitor or are perhaps multi-tasking yourself and want to keep two work streams separate. Or maybe you want to keep games and work separate. So think of these as two very independent work areas. The two Desktops operate independently of one another, so you can have a number of windows open on one Desktop and then switch to the other Desktop (by clicking on the icon) and have a completely different range of windows or programs open here. When you switch between Desktops, the Desktop you have left keeps working.

When you switch between Desktops, a message is displayed in the centre of the screen informing you which Desktop you are entering. You can move windows and programs from one Desktop to another quite simply. Select the window or program you want to move and then just drag it to the left side of the monitor so that it starts to go 'off-screen'. As you do this the number of the Desktop you are moving to appears in the centre of the window. Just release and the transfer is complete. Alternatively, left click on the icon in the top left hand corner of the window you want to move and the first item on that menu list will allow you to transfer the window.

But be aware that each Desktop does use memory and Raspberry Pi resources, so using both extensively can slow things down.

Task Bar Take 2

The right hand side of the Task Bar contains icons that display status information. The most interesting of these is the 'CPU Usage icon'. The CPU is short for Central Processing Unit which is the ARM chip in the centre of the Raspberry Pi board. This icon shows you just how hard — or not! — it is working. The more green that fills the black window the harder the chip is working. In the example above the CPU is not working very hard at all. Keep an eye on it as you launch more programs and notice how it can get quite busy.

_Figure 8h. The Status area of the Task Bar._

Even when you are not using your Raspberry Pi there will always be some green activity in the icon as the CPU is always running a number of programs or 'tasks' in the background maintaining your computer as it waits for you to call on its capabilities!

When the icon is completely green, your Raspberry Pi will be slower to respond to any action you take or command you issue.

Clock is self-explanatory whilst the 'Logout' button will drop you out of the Desktop and back to the command line prompt in the shell. Note that although it has the same icon as the Shutdown icon on the Desktop it has a very different outcome!

The 'Screen Lock' icon allows you to lock your screen and implement a screen saver if you have one installed. On my installation of Raspbian it was not installed automatically but only needed a little help to get it going — here's how if you are interested.

Program Manager

The icons on the Desktop are there as an initial base selection for you. But there are a whole heap of programs and utilities packed into Raspbian that you can use, and the best way to get at these is to use the Program Manager. This is the leftmost icon that looks a bit like the Star Trek badge. If you left click on this you will get a pop-up menu through which you can access grouped selections.

_Figure 8i. The Program Menu allows you to access other programs. Programs are arranged by their category type._

The items on the menu give you a clue as to the type of programs you will find. Move your mouse over each of the menu options in turn and a sub-menu will pop up to the right of it, showing the programs available to you.

The Accessories Menu contains some programs that have icons already on the Desktop plus others that don't. To start (or run) a particular program, move the mouse over the required item (it will be highlighted) and then simply click the left mouse button.

Program Preferences

One of the first options on the Programs Menu is 'Preferences'. This menu allows you to customise your Desktop environment — both in terms of look and feel and also in how it responds to your responses. Each of the options can be tested before you apply the changes so at this point you have a good chance to experiment with things and to cancel if you don't want to go ahead. Note also that some changes that you make will not actually take effect until your next login to X-Windows. A brief outline of each option is given below.

Customise Look and Feel

There are a number of items you can change here. One is the appearance of widgets — these are the tabs and action items that appear in your windows. The default is Mist. You can look at other styles by selecting other named styles. Click on the tabs at the top of the window to investigate other style areas.

_Figure 8j. The Customise window provides several tabs which contain settings you can adjust to suit you._

Desktop Session Settings

These are quite advanced options so I would strongly suggest you do not go anywhere near this option until you are sure you know what you are doing!

Keyboard and Mouse

This option allows you to change things like the keyboard autorepeat rate and the sensitivity and acceleration of the mouse across the screen. You do this by clicking either side of the slider to move it left or right. If you are left handed you can also swap the mouse buttons over.

Monitor Settings

This is not implemented and will result in an 'Unable to get monitor information' message.

Openbox Configuration Manager

This window supplies a number of interesting tabs that allow you to change the overall colour scheme and appearance of the Desktop. There is also one tab called 'Desktop' which allows you to change the number of Desktops you can have. The default is 2 but you can increase or decrease this number here if you wish. I suggest you don't go overboard with this option as you will be increasing the amount of memory used and also probably slowing the operation of X-Windows down. If you click on the '(unnamed desktop)' item listed you can actually name each 'Desktop' if you wish. So it could be DT1, DT2 and so forth or more exactly 'Work' and 'Games'

Installing Screensaver

If you want to use the screen saver then the software and screen saver formats must be downloaded from the Internet and installed. This is actually quite easy to do (assuming you are connected to the Internet).

Open an LX Terminal window and at the prompt type:

sudo apt-get install xscreensaver

This will start the process off. You may be asked if you wish to continue — if you do, press the Y (for Yes) key. The download and installation will take a few minutes so be patient as a lot of text output is displayed on the screen. The 'sudo' command is a special command and is explained in Chapter 11. For now just be careful to enter the line correctly.

When the installation is complete — indicated by the return of the command line prompt — click on the Program Manager icon (bottom left in Task Bar), select Preferences and then select Screensaver. I'll show this type of action as 'Preferences>>Screensaver' in future. Figure 8k shows how the window looked on my Raspberry Pi.

At the first time of running you may get a warning box saying that the Screensaver isn't running. If that is the case then click the 'OK' button to set it into motion.

On the left is a long list of possible screen savers to select from. Not all are installed so you will need to flip through and pick one that tickles your fancy. I quite like Galaxy. Above the list you have a short drop-down menu that allows you to decide if you want a randomly chosen screen saver to be used or only one, or maybe none. Within the preferences dialogue you can also choose the idle time before the screen saver starts and if/when the system requires a password to unlock.

_Figure 8k. Screensaver Preferences window._

You can preview the screen saver by selecting the 'Preview' button (click the mouse to go back to the main screen) and the 'Settings' button gives you access to other aspects relating to how the chosen screensaver appears.

The 'Advanced' tab gives you access to even more detail about how it appears and you can even add some text to display. The 'Help' tab gives you access to further documentation should you need it.

When you are finished close the window (click the 'X' on the top right of the window to close it). To set the screen saver off just click the screensaver icon on the bottom right hand corner of the task bar. When you want to return to work you will need to provide your user name and password, as you do when you initially log on to your Raspberry Pi.

As soon as the screen saver is running the screen lock icon should function correctly.

File Manager

The File Manager provides all the tools you need to manage your files and directories. If you have experience using a PC or a Mac then you will find this quite familiar. If you click on the 'File Manager' icon on the Task Bar you will be presented with a window similar to that shown in Figure 8l.

_Figure 8l. The File Manager window._

When you look in the main part of the file window you will see three icons. You may recall that these are identical to the items we listed when we used the 'ls' command in Chapter 7. 'Desktop' and 'python_games' are directories and 'ocr-pi.png' is a file. Note how the directories have icons that look like folders, which is really useful in distinguishing them from files.

Immediately above these icons is a small window that displays the currently selected directory in terms of its full path, which is '/home/pi'. In the Name Bar at the top of the window this is also reflected — pi. On the left hand side is an area labelled 'Places' and under this 'pi' is selected. This has a house as an icon because it is our 'home' directory.

Double-click on the 'Desktop' icon. A few changes will occur in the File Manager window. Firstly in the central display area you will see images of all the icons on your desktop. Above it the path will have changed to reflect where you are. The Name Bar will have changed to Desktop. And in the Places area the 'Desktop' icon will have been highlighted. Again, these reflect what we experienced in Chapter 7 when working in the Shell.

In the Places pane click on 'Applications'. The main window will change to show icons that reflect what we saw in the Programs Menu. Double-click on the Accessories icon and you will see icons for each of the programs we encountered before. Double-click on 'Galculator' and watch a digital calculator pop up on your screen!

To return to your home area click the 'pi' icon in the Places pane.

To the left of the small window containing the currently selected directory path you will see some round green icons with arrows in them. Those bearing left and right arrows can be used to move through the directory structure (but only if you have previously opened the directories as described above). The up arrowed green icon moves the setting to the parent directory of the one currently displayed. As you click on each of these arrows, the display in the main pane and Places pane will change accordingly. The small down triangle situated in between the green icons is the 'Folder History' icon. If you click and hold this down you will get a list of all the locations you have been to. You can simply scroll down to one of those in the list and click to select that as the CSD (currently selected directory). (Note that this history is only for the current Desktop session and is wiped when you exit X-Windows).

Creating with Folders and Files

Using the mouse and the various buttons and icons provided, it is easy to navigate your way through the Raspbian structure. If you want to create and access other areas then you will need to use the File Manager menus to assist you in this.

There are seven menus in all and you can see these in Figure 8r. It is worth investigating these and spending some time experimenting with them. This is because many of the other software packages you will use also have menus and many are organised just like these. By being consistent in arranging menus and menu content they are much easier to use as you have already been through the learning curve.

File Menu offers a range of options that allow you to control the way you see things and the ability to create new directories and files. The first two options allow you to create a new File Manager window as a separate window or as a tab. Having two separate windows open is convenient if you want to move files from one place to another. You can simply select the file or directory in one window (keeping the left mouse button pressed down) and drag it into the new window. When you release the mouse button the item will be moved across to that position. (Note here that the item is moved and not copied, so the original item does not remain in the source directory). Using Tabs is good if you just need to access different directories as everything remains in one window and reduces the clutter on the screen.

The 'Create New' option allows you to create a new Folder or a Blank File. Ensure that your current selected directory is Pi and then use this option to create a new folder. A window will appear asking you to name the folder. Enter 'Test'. This will then appear in the icon area. (If you now open a Terminal window and type 'ls' you will see that the 'Test' folder appears in your listing).

Close Tab and Close Window work as you would expect although in either case you can use the close window 'X' on the right hand corner of the window or tab to the same effect.

Using Files and Folders

The first four options on the File Menu are Cut, Copy, Paste and Delete. You can use these functions on any of the icons that appear in a window. Copy and Paste in combination allow you to make duplicates of items across windows. You should first single click on the item, and then select the menu option and select 'Copy' and then 'Paste'. If you try and paste to the same directory then a window appears asking you if you want to overwrite the existing item or rename the new item. Generally you would rename the new file otherwise you wouldn't be doing this operation! If you use Cut and Paste then the original item selected is removed once it has been pasted to the new destination. A word of warning — be very careful when you rename a file. If you do not do it correctly you can create some issues especially regarding the system's ability to know what type of file it is. Important: Before you attempt to rename a file, read the last section of this chapter which discusses the naming of files.

The Move To and Copy To options provide the same function as using the Copy-Paste and Cut-Paste options. The difference here is that when you have selected your item to copy and then selected one of the options, a second File Manager window opens and allows you to use the interface to select your location before pressing the 'OK' button to effect the command.

You can rename a file or directory by selecting the item and then choosing Rename from the Edit menu. Type in the new name and press the 'OK' button (or press <ENTER>). The 'Select All' option selects all the items in the current directory. If you want to select multiple items rather than all items then this can be achieved by holding down the <CTRL> key and then single clicking each icon you want to select. You can then perform any action you wish on these selected files through the menu options. The 'Invert Selection' option inverts the section on the screen, so for example if you had three files, two of which were selected, inverting would leave you with one file selected and the other two not selected.

The final option on the File Menu is a 'Preferences' selection, which allows you to define defaults for Behaviour, Display and Volume Management. There is also an advanced tab which is probably best to avoid until you have a deeper understanding of what is happening. The other tabs are worth experimenting with as you can always reset things. Note also that Volume management isn't about sound and loudness! It is about how the system reacts when you insert external storage devices like a USB Stick. Chapter 13 details the use of external devices.

Go and Bookmarks

The first three options on the Go Menu perform the same options as the green icon arrow keys described earlier, allowing you to navigate through folder (directory) history. Those below are almost identical to those you find in the Places pane by default. However, additional items include Network places (if you are attached to a network) and the Rubbish Bin. If you delete files then they are placed in a special directory called Rubbish Bin. If you select Rubbish Bin then any deleted files will be displayed. This is handy if you want to get back a previously deleted file. When you are in the Rubbish Bin you can click on the 'Rubbish' icon (in the Places pane) to delete all items in the Rubbish Bin. If you do this you cannot get them back — it's like throwing away the contents of the rubbish bin for good!. So before you take such a drastic step make sure you don't need them.

Another option here is 'Computer'. If you select this, an icon of a disk drive will appear in the main window. Click on this to see the entire root directory and all the folders in root, the functions of which I outlined previously.

Bookmarks

If you have several folders that you go to regularly you can bookmark them. This basically means that you can assign a name to the directory path and this then appears in the Places pane. When you want to go to that directory you just need to click on the name you assigned to it.

The Way Things Look

The View Menu allows you to control how your files and folders are displayed inside the main File Manager pane. It also provides you with the option of seeing special files that are normally hidden from view!

By default the File Manager window displays files in what is called Icon View. The View Menu offers a couple of variations on this whereby icons are displayed in Thumbnail or Compact views. One is essentially larger than the other and the Compact View is certainly useful if you have a lot of folders and files in the currently selected directory. However, a more useful choice is the Detailed List View which displays files as a list and provides information about each of the items on display. Figure 8m shows this.

_Figure 8m. The Detail List View displays useful information about the files it is displaying._

In addition to showing the name of each file this list details what type of file it is (recall the 'file' command from the Chapter 7) along with the size of the file — that is the amount of space it occupies, as well as the date the item was created or was last changed (modified). You can use the 'Sort Files' option to re-arrange your files in this view in a number of ways and it is worth taking the time to experiment with this — only the display changes; the files themselves are not changed in any way. As well as arranging files alphabetically (ascending or descending — A-Z or Z-A), you can list them by size, type or time they were last modified.

Figure 8m also shows how changing the 'Side Pane' option to 'Directory Tree' alters the appearance of the Places pane. It actually changes to a Directory Tree pane so you can see the overall structure of where you are working.

One of the areas we have discussed is the very bottom information bar across the base of the File Manager window. On the right hand side you have details of how much total memory you have and also how much free memory you have for your files. In Figure 8m you can see that there is a total of 6.0GB available of which 2.2GB is free for use. This space relates to the SD Card. If you have an 8GB memory card then these figures will reflect that too. So this is a good way to keep track of how congested your SD Card is becoming.

On the left hand side information is given about files. In the example above 27 items are there but also 24 hidden items. The 27 items are clear and the hidden files are ones used by the Operating System. If you want to see all the files, including the hidden ones, select the 'Show Hidden' option from the 'Files' Menu. Do not delete or do anything with these files — they are used by the other programs. Good to know they are there, but re-hide them once you have had a gander.

There is a final menu called 'Tools'. The first option here allows you to open a terminal window for the currently selected directory whilst the second option allows you to open it as root user. We'll be examining what root user is in Chapter 11, which will explain more about this option.

Keyboard Shortcuts

Many of the windows that you open in LXDE give you the ability to implement actions from the keyboard. This is indicated by having a letter in a tab or menu title underlined. For example in the File Menu on File Manager the F of File is underlined. This means you can open the File Menu by pressing the F key in combination with the <ALT> key. This would be represented as <ALT>-F in this text.

When the File Menu pops up the listing also contains some key combinations. For example pressing <CTRL>-N will open a new window. Note that the new window will not be created if the drop-down menu is present. So rather than going to the File Menu you can simply press <CTRL>-N to create a new window. These short cuts become quite intuitive and you will soon memorise them just by using them.

File Names

We have already encountered several different types of files. You may recall the files in the Pi directory that ended with '.desktop' and we saw how these were icon files that showed up on the Desktop when we started X-Windows. In one of the previous examples we have seen the OCR image and saw how this file ends with '.png'. Some of the image files detailed in Figure 8m end with '.jpg'; these are JPEG images — pictures of various kinds. The various filename endings are called the _filetype_ and they define what sort of files they are. The '.png' is a graphics file, files that end with '.txt' are text files and Python files end in '.py'. In fact there are a whole host of file types and you will get to know these as you use your Raspberry Pi. This is not just indicative of the Raspberry Pi — you will find the use of file types on just about all computers. You may even be aware of some already.

If you look through some directories using the Detailed List View of File Manager you will be able to see from the Description column what filetypes are which. You can also group files by file types by sorting them by File Type through the View Menu.

Therefore when you rename a file using the 'Rename' option you must be careful to preserve the file type — those last two or three letters after the full stop. If not then you will confuse the Operating System. If you rename a '.png' file to a '.txt' file then the program that opens .'txt' files will not be able to do so and you will possibly also wonder why. So this is the reason that I warned you earlier about being careful if you rename a file. The suffix should remain unchanged.

On the subject of naming files and directories (the latter does not have a file type) try and keep your names simple. You will recall that names are case dependent so you may find it easier to use all lower case letters for your filenames so it makes typing them simple. Never use spaces in your filenames (makes using them in the Shell difficult) and avoid punctuation marks as well as again these can be confusing when working in the Shell.

Ultimately you will set up a way of working that suits you. I must admit that I tend to capitalise the first letter in a directory name so that these are always instantly distinguishable from a filename. But that's a personal convention — you can choose what suits your typing skills best!
9: Having a Bash

You can use a Desktop environment to undertake many — if not most — of the things you want to do when it comes to using the Raspberry Pi. However, the Raspberry Pi is about learning to program so in this chapter we'll step back into the Shell and give it a real Bash!

You have seen how you can use Bash from the Shell and also from within the desktop environment using the LXTerminal program. Bash is so called as it is an acronym for Bourne Again Shell — its predecessor being the Bourne Shell. Apart from wanting to learn Bash there are several reasons why it is useful to have an understanding of its functions, not least because it is often easier and certainly faster to do things like installing and upgrading software.

Directories

In the last chapter we saw how to use the File Manager to create a directory called Test. In Bash the 'mkdir' command is used to make a directory. You use it like this:

mkdir Books

This would create a directory called 'Books' and it would be created in the currently selected directory — as defined by the prompt.

Raspbian has a feature whereby you can follow a command with several items, each separated by a space, and it will action each one in turn. For example, if you typed:

mkdir Letters Bills

Then individual directories called Letters and Bills would be created in the currently selected directory.

You can also use the 'mkdir' command to create a directory structure, or at least a branch, in a single command line. For example the following command:

mkdir -vp Work/Admin/Invoices

Would cause Raspbian to respond with:

mkdir: created directory 'Work'

mkdir: created directory 'Work/Admin'

mkdir: created directory 'Work/Admin/Invoices'

So mkdir has created the Work directory inside which it created the subdirectory 'Admin' which itself has a subdirectory 'Invoices' inside.

You will notice that the command line above had an extra element, namely 'vp'. This is an example of what are called 'options' and these are always preceded with a hyphen. Options are case sensitive and can be used together to create or control a series of actions. Many Bash commands allow you to use them as modifiers of the way the command works normally. As you may appreciate, they can be very useful and we'll be looking at them shortly. Here the 'v' stands for 'verbose' which tells Bash to report the action it has undertaken, and thus the listing response. The 'p' stands for create parent directory and ensures that the necessary structure is put together.

To delete or remove a directory we use the rmdir command. For example:

rmdir Books

Would delete the directory called 'Books' if you had created it in the example above. If the directory doesn't exist then you will get a message to that effect. Equally, if you had files inside this directory the 'rmdir' command would fail — thus acting as a safety net.

To delete the directory structure created above (and assuming there are no files or other directories within them) use:

rmdir Work/Admin/Invoices Work/Admin Work

Here we start with the lowest directory in the hierarchy and work our way up through each parent directory.

There is a less painful way to do this — but one that must be used with care, because of its potentially destructive nature. If you want to delete a directory and any files or directories inside which it may contain then use the 'rm' command with an 'rf' option thus:

rm -rf Work

This will delete the Work/Admin/Invoices structure. The 'r' is a recursive switch and 'f' is for force. Here 'recursive' means that it will work its way through any and all sub-directories with the named directory – so everything within!

Files

The 'rm' command is in fact the command to remove files and by default it does not remove directories unless you use the 'rf' option outlined above. This command requires the file's filename including the file type extension:

rm report.txt

This will remove the file called 'report.txt' in the pi directory, if it exists. Figure 9a gives some of the options you can use with the 'rm' command.

_Figure 9a. Options that can be used with the rm command._

By typing:

rm --help

you can get more information on other options for this command. In fact this is true of all Bash commands.

Listing Options

The list or 'ls' command was one of the first commands we looked at when I first introduced the Shell. We'll return to it now because it has great flexibility when combined with associated options and it can be used to provide information about your files and directories.

By using these options to examine the files on your SD Card you will start to learn a lot about its structure and operation. Figure 9b lists some of the more useful options for use with ls. Note that they are case sensitive, for example 'R' is not the same as 'r'.

_Figure 9b. Options for use with the ls command._

These options can be used singularly or combined to create output listings to suit your requirements. Let's work through some examples to show you how to get the best from them and learn a bit more about files and directories in the process.

Long Format

The 'l' option for the 'ls' command is the long format option and it's one of the most useful as it provides detailed information on your files. (Be careful not to confuse ' -l' (el) with '' (one) as they look very similar).

If you type 'ls –l' in your home directory (pi) then the output should look something like that illustrated in Figure 9c (the files and diectories might be different depending on what you have been doing!).

_Figure 9c. Typical output of ls -l in the pi directory._

This listing shows the names of the folders and files in the currently selected directory. There are a number of columns of information about the directory contents. Immediately obvious are the names of the items in the directory on the right of the listing. But what of the other information? Working through these from left to right: The first set of letters, which seem to consist of r, w, s and -'s are called _permissions_ and they tell you what you can and cannot do with each file or directory. They may look random but they are not — they are important and are covered below.

The numeric value that follows the permissions is the number of links inside the directory (for a file it is always 1). Immediately following that is the user and the group that owns that file or directory. In Figure 9c the 'pi pi' indicates the user and the group owner of the directory is pi or yourself.

The next field contains a number and this represents the size of the file in bytes. So in the case of Figure 9c the report.txt file is 6771 bytes in size.

The following details are the date and time the file or directory was created or last modified. For older files the year is used to replace the time if the date happens to be a previous year to the one you are in. Type:

ls -la

The listing for the same directory will be longer — this is because the 'a' option forces all files to be listed, including hidden system files. If you still have 'pi' as your currently selected directory then some of the additional files you see will probably mean something to you now. Note also how there is now a hidden file for 'pi' and 'root'.

If you use the 'r' option, ie:

ls -lar

Then the listing order is reversed. Type:

ls -lah

The 'h' stands for human. When you run the command you should see that the file sizes are not expressed in terms of bytes (numbers can get quite large) but in a more standard format. In the case of the above on the pi directory — in terms of kilo bytes (or K).

The recursive listing option (-R) can be quite useful for displaying files in the directories within your CSD:

ls -R

From the pi directory this would list all the files in Desktop and 'python_games'.

Try experimenting with some of the other options to see the effect they have. Remember, for the most part you can combine the options in any order to create detailed lists of information and you can filter the output by being clever and ingenuous in the use of the commands. Don't be afraid to have a poke around inside the other directories and remember you can include path names in the 'ls' command if you don't want to set and reset your CSD:

ls -l /sys

Bytes and More

We have used a few terms like byte and Gigabyte without explaining too much about them. So let's do an overview of these terms that you might use freely when discussing your camera or smart phone. These terms are usually used in the world of computing to describe disk space, or data storage space, and system memory — we talked of SD Card size earlier in terms of 4GB and 8GB.

You can think of a byte as being the amount of space needed to hold one character. So the letter 'A' could be stored in one byte (of memory). The expression 'Raspberry Pi' would need 12 bytes of memory (the space between the two words is also regarded as a character).

If you refer back to Figure 9c you'll see that the two directories both show sizes of 4096 bytes. Directories always have this as their file size as for naming purposes on the listing they are treated like files. However, the contents of directories can differ vastly so what this value does not tell you is how big the contents of the directory are.

Figure 9d lists some of the more common multiples in use today.

_Figure 9d. Common memory unit terms in use today._

A kilobyte or KB is really 1024 bytes. Why 1024 rather than 1000 bytes? Without going into detail, it is because of the way numbers are organised within a computer at a binary level. In everyday use when referring to computer storage it is common to round to 1000 rather than 1024 — but there are different schools of thought.

A Megabyte is approximately 1,000 Kilobytes and if you purchase music on-line (from iTunes for example) then a single music track would be about 4-5MB in size (a CD would hold around 600MB of digital music). A high definition image taken with a state-of-the-art camera would be between 8MB-12MB in size.

A Gigabyte is approximately 1,000 Megabytes and as you know the smallest SD Card you would contemplate using for your Raspberry Pi would be 4GB in size. A Terabyte is 1000 Gigabytes and the biggest capacity disk drives you might purchase at your local office store could currently be in the order of 4TB in size — though who knows how this may grow!

Understanding Permissions

Each file and directory has a set of associated permissions. These are settings that define what can and cannot be done with the item in question and by whom. For example, you can set the permission of a file so that it can only be read but cannot be written to. You can set the permission of a file so that it cannot be deleted. In fact there's a wide range of options and it is good to be aware of them.

There are 10 option settings and these are subdivided into four groups of settings. In the output above from the base pi directory (Figure 9c), the permissions for Desktop break down as follows (from left to right):

d File type

rwx Owner

r-x Group

r-x World

The file type character indicates what type of file is being listed. There are only two possible settings. A 'd' indicates a directory and a hyphen ('-') indicates a file.

The next three groups are all handled in the same way in that their component options can have one of three settings. These are:

r Read permission

w Write permission

x Execute permission

The read permission allows you to open and look at the contents of a file or to catalogue a directory. The write permission allows you to create or delete a file or directory and also to edit the file's contents — which can mean adding or deleting from it. The execute permission means that you can run a file (assuming it can be 'run') or enter into a directory using the 'cd' command. There is a fourth option which is a hyphen '' which indicates that permission has not been granted.

The owner of a file or directory is the person who created it. A group can be a number of people combined into a workplace. For example you might create a group in a business called Accounts which only your accounts staff has access to. World is just that — anyone and everyone!

Referring back to the Desktop we can tell from its permissions that:

  * it is a directory.
  * the owner can read, write and execute (enter) it.
  * both Group and World users can enter and look at its files, but not create or delete files.

The above is a lot to take in, and no one is expecting you to immediately know and remember all of it. As with many things, your Raspberry Pi journey includes becoming aware of where things are. When you do need to know the detail, you have enough information — ie, you'll know where to look for it.

Changing Permissions

Changing permissions should be done with care, because it can have irreversible effects if you are not careful. Bash provides the 'chmod' command which stands for change mode, mode here meaning permissions. The command is quite complex to use so it is not my intention to cover it here. That said, if you do want to change the permissions of a file or directory then the best way to do it is from the Desktop.

For example in LXDE open File Manager and right click on the file or directory in question to display the pop-up menu and then select the Properties option. This brings up a window which has two tabs. The 'General' tab tells you information about the file, much like the information displayed using 'ls –l'. The second tab is 'Permissions'. Click on this and you will see the permissions information displayed as a series of boxes, where you can either edit or select options from the drop-down menus. Once you have made the settings that you require, press the 'OK' button to save and implement them.

In Chapter 18 we'll need to change the permissions that apply to a file to allow us to use it like a Bash command — for that we will use the chmod command.

Copying Files

As we saw in Chapter 8, copying files or directories in a desktop environment is simply a matter of dragging the file/directory icon from one folder location to another (and this is true of a few other commands we'll be looking at here). A reminder too that directory and folder mean the same thing. If the item being copied is on the same file system, it will effectively be moved from one location to the other; if it is on a different file system it will make a copy leaving the original intact. (We'll discuss file systems in Chapter 14 but for now think of this operation as moving from one physical location to a separate physical location).

While it is easy to perform simple file manipulations in a desktop environment, complicated tasks can be much easier using the command line. In Bash copying a file from one location to another requires you to know where the source file is and where its intended destination is. And of course you need to know the name of the file.

The command for copy is 'cp' and the format of the command is:

cp [options] <Source> <Destination>

This is a standard way of showing how a command is constructed. 'cp' is the command — copy in this case. [options] as they are in square brackets are optional. We have used options before with some of the other commands we have looked at. Items in angled brackets are generally required items. Here we have the source filename and the destination address.

Try this to see the command at work. In the home pi directory create the directory Test to see that it doesn't already exist:

mkdir Images

Then copy the Raspberry Pi logo file into it, taking care to enter the line exactly as shown:

cp /usr/share/raspberrypi-artwork/raspberry-pi-log.png Images

When the prompt returns:

ls Images

Will show that the file has been copied. Note that a copy has been made — the original source file still exists in the pi directory. (This is a bit different to the Desktop method where it would actually move the file as it was on the same file source).

If you want to copy and give the file a new name, you can do this as well:

cp /usr/share/raspberrypi-artwork/raspberry-pi-log.png Images/pilogo.png

This would make another copy of the file renaming it picture in the process.

ls Test

This will confirm the fact.

You only need to specify the full path when you are working in different directories. If you wanted to duplicate a file inisde a directory you only have to state the new name, so long as the directory is your currently sleected directory:

cd Images

cp pilogo.png duplicate.png

Figure 9e lists some of the options available to use in conjunction with cp. You can get a full list of them by typing:

cp --help

_Figure 9e. Some options for use with the Copy command._

There are quite a lot so if you do want to investigate options for the command, or any other Bash command, it is quite useful to do it inside a Terminal window in the Desktop environment. This is because you can then use the scroll bar on the right hand side of the window to move up and down through the list that is generated!

One thing you should be aware of with the 'copy' command is that by default it overwrites any file with the same name at the destination address. You can combat this effect by using a combination of options. For example using -i will prompt you if you want to overwrite an existing file. Press the Y key to do so and the N key not to.

Here are a couple more examples:

cp -avr Work/Business/Letters Backup

In this example the Letters directory (and its contents) will be copied into the Backup directory — note that only the Letters directory will be copied, the Work and Business directories are not duplicated. Three options here: -a preserves the attributes of the directory, -v explains what is happening and -r copies directories recursively.

cp -r python_games/* Backup/Pygames

This would copy recursively all the files and directories in the 'python_games' directory to a directory called Pygames in the backup directory. The destination directory called Pygames must already exist. In this example the asterisk '*' is used as a special symbol called a wildcard and means 'everything'. So if you tried this example and looked in the Pygames directory, you would find all the files from inside the 'python_games' directory. (Wildcards are discussed in Chapter 12.)

In these examples — and some that follow — we are assuming that everything is on the SD Card. However, you will want to be able to copy to external devices that you plug into your Raspberry Pi. Commands such as 'cp' are able to deal with this. We'll see exactly how to do this in Chapter 14.

Moving and Renaming Files

You can move files using the mv command. This command takes the form:

mv [options] <Source> <Destination>

As you can see, this is very similar to the format of 'cp'. Here though the <Source> file is removed leaving you with it at <Destination>. Here's a couple of examples:

mv ~/pilogo.png ~/Test

This would move the 'pilogo.png' file from the home directory to a directory called 'Test' and the file would cease to exist in the home directory. To move it back use:

mv ~/Test/pilogo.png ~

In both the above examples I have used the '~' character (this is called the tilde). This has a special meaning and represents the home directory. In addition, in the first instance above it assumes that the directory 'Test' exists. If it doesn't exist then the 'mv' command will assume that you want to rename the file to 'Test' and place it in the home directory! And with that you can immediately see how we rename files in the Shell — we use the 'mv' command! If you tried the above and then listed the contents of the directory then 'Test' would not be colour coded as a file. This is because it does not have a file extension. To get it to list correctly use:

mv Test Test.png

Figure 9f lists some of the options available with the 'mv' command. Note there is no 'recursive' option.

_Figure 9f. Some options for use with the mv (move) command._

Config Revisited

Now that you have had a chance to play with Raspbian in its various guises and also a chance to understand a bit more about how your hardware works with it and the manner in which commands work, you may wish to make some changes to your original configuration settings. If you do then you can re-run the configuration setup program at any time by entering the following command at the command line prompt:

sudo raspi-config

You can now change any of the options as outlined in Chapter 6. You can come back to the configuration tool at anytime you want to make changes. For example, perhaps you have updated your keyboard and need to change this. Or perhaps now you don't want to boot into the Shell and would rather go directly to Desktop environment using the 'Enable Boot to Desktop' option. The choice is yours!

Manual Pages

Raspbian comes with some detailed documentation about the various Bash commands and the various functions of the Operating System. These descriptions can at best be terse but they are really useful for an online resource to the options available with each of the commands. So as a memory aid they are pretty useful. These are all accessible via the 'man' (short for manual) command which has the following format:

man [options] command

For example to interrogate information about the 'ls' command use:

man ls

Information is displayed on screen one page at a time. It starts with a definition of the command, and is followed by the command format and then a section which includes the options available for use with the command. Press <SPACE> to scroll to the next page of information. You can exit the 'man' description by pressing 'q'.

The 'man' display can be controlled in a number of ways and you can access these details by pressing 'h' for help during output. For a really detailed description of 'man' use:

man man

Of course!

Reading information on screen in this way is at best difficult. Another option is to save the 'man' output as a text file that you can then read at your leisure using a text editor such as vi or Leafpad (we have not discussed these programs as of yet). For example to save the 'man' output for 'ls' you could use:

man ls > ls.txt

The '>' is called a re-direction operator. When you use this, rather than the output going to the screen it sends it to a file called, in this case, ls.txt in the current directory. The file extension txt is used signifying a text file.

If you pop back to your Desktop environment and locate the file, double-click on it and it will open in a text editor (typically Leafpad) where you can browse the contents.

Less is More

We have seen that some Bash commands like 'ls' can generate a lot of information which can whiz past on the screen without allowing you any chance of really examining it. And while output can be sent to a file with re-direction, or you can use a Terminal window to scroll back and forward in your Desktop environment, these are time consuming, especially if you are just looking at one or two items from the Shell. It is possible to get commands to work in a paged-mode that allows you to examine their output a screenfull (page) at a time. You can use the 'less' command for this.

For example if you enter:

ls -l /bin

The listing on screen will shoot pass. Now try this:

ls -1 /bin | less

When the screen is full the listing will stop — a colon will be the last item on the screen. The '|' (pronounced 'bar' or 'pipe') character is another special operator recognised by Bash. You are now able to move through the listing one line at a time using the up and down cursor keys. Alternatively you can move one page at a time using the <PageUp> and <PageDown> keys.

You exit the listing output by pressing the 'q' or 'Q' key.

You can use the 'less' command to view the contents of a .txt file as well. So to use this same technique to look at the ls.txt file that was created earlier you would use:

less ls.txt

The 'less' command also allows you to search a file by pressing the backslash key (/) and then entering the word (or any character) you are looking for. Once you press <ENTER>, provided the string is found in the file all occurrences are highlighted.

Useful Commands

We'll be looking at some more Bash commands in Chapter 12, but here are a few simple ones that you might find useful to know:

clear

Clears the screen of everything and leaves the cursor sitting at the top of the screen.

cal

Displays the calendar for the current month on the screen.

cal -y

Displays the calendar for the current year on the screen.

pwd

Prints the current working directory (which is the currently selected directory).

users

Lists the names of users who are currently logged in.

!!

Runs the last command you executed.

Shutting Down

Once you have finished with your Raspberry Pi for now and want to turn it off you should type the following at the command line:

sudo halt

Raspbian will then do some internal housekeeping duties and then turn itself off, which takes just a few seconds. Once the screen goes blank you can safely turn the power off at the switch. As mentioned before, don't be tempted to pull the micro USB plug out of the Raspberry Pi itself.

If you simply want to reboot your system rather than turning it off and then powering it up again, you can use:

sudo reboot
10: Essential Tools

There is an enormous choice of software available for you to use already installed on your Raspberry Pi. In this chapter we'll look at some of the applications available to you and show you how to get the best from them.

There is so much free software available on the Raspberry Pi that sometimes knowing where to look for it and which to choose is a challenge in itself. Equally there is some very good software you can purchase quite cheaply and get plenty of enjoyment from. Knowing where, when and what is often a major accomplishment in itself. The Pi Store is one such source of software and it also provides an in-built management system to allow you to install and delete software with the minimum of fuss.

The Internet is another option and using search tools will allow to you find reviews of software and see what other people think of it. In addition the web is a great source of information and news, so selecting the right web browser for the Raspberry Pi is important.

Many of the things you might want to do on your Raspberry Pi, such as programming and making notes, will require you to use a text editor of some sort into which you can type, edit and save your work. There are a few text editors available. The advantages and disadvantages of these are explained here as well.

Surfing the Web

If you want to view pages from the Internet and generally look around the web then you need to use a program called a 'browser'. This acts as your portal and you reach various resources by entering the locations of websites, which is normally accomplished by using a name-like address called the uniform resource locator or URL. Browsers are all slightly different, but essentially they operate in the same way — they all allow you to 'surf' the Internet and access different websites. Figure 10a below shows a typical browser and identifies its key parts.

_Figure 10a. The components of a typical web browser — the Epiphany Web Browser in operation and open at the Raspberrypi.org website._

To look at the web page you want to view, just type in its web address (in the space at the top of the window) and then press the <ENTER> button. The official Raspberry Pi website can be found at www.raspberrypi.org. This address takes you to the Raspberry Pi Foundation's 'home page'. A home page is a bit like the front page of a newspaper where you get all the headlines and from which you are directed to other pages. This is achieved by the use of links, which are usually identified by being underlined or highlighted. You click on the link with the left mouse button and you will be taken to the webpage it links to. These links are also called hyperlinks. Images on the screen often have hyperlinks in them, so that when you click on the image it will whisk you off to that page.

The address of a website is an exact art. If you make a mistake in typing, your browser won't be able to locate the page. So if you don't end up where you expect, check the spelling of what you've typed.

A web browser may often only show a small part of a total web page, so to see the rest of the page you either enlarge the web browser window (you can maximise it unless it already fills the screen) or you can use the scroll bars to the left and bottom of the screen to scroll around the page. There may also be left and right arrow buttons in the menu bar and this allows you move to pages you may have looked at previously.

Browsing Options

You have plenty of options for browsing the Internet on your Raspberry Pi, as there are several pre-installed as part of the Raspbian Operating System and there are several more you can download. The September2014 release of Raspbian included Epiphany Web Browser as the default browser. Prior releases of Raspbian have installed Midori as the default web browser. However, this was slow because it wasn't well suited to X-Windows on the Raspberry Pi and unable to open popular websites such as Facebook and YouTube because of software compatibility issues.

Having launched the Model B+ the Raspberry Pi Foundation turned its attention to the improvement of software for the Raspberry Pi. I have already mentioned Maynard as a longer term project. Epiphany Web Browser was developed to especially for the Raspberry Pi with the ability to overcome the shortcomings of Midori and be compatible with the future release of Maynard.

Prior to the 24 December 2014 release of Raspbian all the websites mentioned here can be opened using the Programs Menu and selecting the 'Internet' option. For the 24 December 2014 and later releases only the Epiphany Web broswer is available from the Internet Menu.

Epiphany Web Browser

Figure 10a (earlier) shows the Epiphany Web Browser in operation and open at the Raspberrypi.org website. The cleanness of this browser is one of its most striking features and you can have multiple pages open at one time inside the single browser by having them opened in 'tabs'. You add a new tab by clicking on the tab button immediately to the right of the address bar. The 'sun' button provides access to a drop-down menu through which there are a range of options you can select. This includes a 'Preferences' option via which you can personalise the way in which you want the browser to behave. This is all very intuitive.

_Figure 10b. Epiphany browsers open at my Alan Turing Rocks blog._

Epiphany Web is HTML5-capable which is an industry way of saying that it should be able to support everything you throw at it in terms of web page, although until Maynard is released it might still be a little slow. This includes the ability to access sites such as Facebook and YouTube.

If you are using a pre September 2014 release of Raspbian you will probably have Midori as you default browser. To move to Epiphany Web, which I strongly recommend you do, you can download it and install it using the following three lines at the command line:

sudo apt-get update

sudo apt-get dist-upgrade

sudo apt-get install epiphany-browser

NetSurf

Netsurf started life under RISC OS over a decade ago. Netsurf is quick in operation but it doesn't support JavaScript and therefore more complex websites, so it's a choice between speed and functionality. The Preferences window can be accessed through the File menu. Here you can select options under Content Blocking to stop advertisements and pop-up windows displaying. This will speed up page loading.

Dillo

Dillo is the least sophisticated of the web browsers offered with Raspbian. It does not support JavaScript either and generally does not render pages in their designed layout. For instance, menus that are normally displayed in a block across the top of the page are displayed as a simple list. That said, if you are interested in information and accessing it reasonably quickly and if you are not worried about associated images, then Dillo is a functional option you could consider.

Luakit

This web browser is not — at the time of writing at least — part of the standard Raspbian distro. However, you can install it separately and it has the advantage of being extremely lightweight. This means that it does not provide a lot of the menus and items you might consider as standard, but it is quick. Equally, if you open a website that has a mobile option it will open the mobile site. This gives you the functionality of the mobile site and also the speed!

_Figure 10c. Luakit opens the mobile website if the option is available._

There are no scroll bars in Luakit, so use the <UP> and <DOWN> arrow keys to scroll. Also, you enter web addresses in the bottom line of the browser instead of the top.

Installing Luakit is straightforward; the following command at the command line will do it:

sudo apt-get install luakit

Installation is discussed in Chapter 11. Once installed it will be available in your Desktop environment via the Program Manager.

Terminal Browsing with Lynx

If you find yourself becoming a command line junkie and decide to live a simpler life then you can actually use text-based web browsers directly from the Shell. Lynx is one of these and is easy to use, albeit a very different experience. To install Lynx use:

sudo apt-get install lynx

When installed you can go straight to your website of choice by typing its web-address after the lynx command:

lynx bbc.co.uk

This would start lynx and open the BBC website.

Instructions are provided but basically use the cursor keys to move around the screen.

Pi Store

The Pi Store was launched at the end of 2012 and contains games, applications, tools and utilities that you can download and use on your Raspberry Pi. It doesn't contain every bit of software available for the Raspberry Pi but it does contain some of the most useful and interesting that are around. One of the original aims was for the Pi Store to become a one-stop shop for Raspberry Pi software. It probably hasn't achieved that at the time of writing, but if you are a beginner then it is certainly an excellent launch pad for you to experience software, from downloading, to using, to removing.

Pi Store comes as part of the standard Raspbian Operating System image and requires you to use the Desktop environment. There may already be an icon for it on the Desktop. If not, look for it in the Programs Manager under the 'Internet' option.

Before you can download anything for the Pi Store you will need to register your details with the shop. This requires you to have an email account. Press the 'Register' button and then enter your email address and a password for the site (not your email password!). Remember the password (and which email address you used if you have more than one!) as you will need to log-in each time you start Pi Store.

If you don't have an email account then you should consider one essential just in terms of getting information and additional support for your Raspberry Pi experience. There are plenty of 'free' options out there to choose from so search — but cautiously!

When you enter Pi Store you will see that it is arranged by categories across the top and by tags down the side. There is also a search box across the top where you can enter a keyboard and search for it — although the results returned are not always conclusive.

It is worth browsing around each of these tabs and see what is available, and to keep checking in from time to time to see what additional items have been added. The information given includes the price or whether the software is free and also what rating other users have given the software — from none to five stars.

The Media tab is interesting as you can download copies of The MagPi magazine for the Raspberry Pi. This has some great contents so it is worth downloading from the MagPi website to look at either on your Raspberry Pi or on an alternative computer.

Installing Software from Pi Store

There are plenty of free options to try and experiment with. As an example the Flip Clock Pi provides updates on local weather as well as the time. You can find this in the 'Apps' tab or enter 'Flip Clock Pi' in the search bar to source it.

_Figure 10d. The Pi Store screen showing Flip Clock Pi._

Click on Download (if you haven't yet logged in or registered you will be asked to do so at this point). The screen will show the 'My Library' tab and this is where you use and manage your downloaded software from. The 'Flip Clock Pi' icon should be in the library and it may contain a percentage counter showing how far the download has progressed. At the end of this process a Terminal screen will appear and once the installation is completed you will be asked to press any key to continue.

Select the 'Flip Clock Pi' icon by clicking once and details will then be displayed on the right hand side of the screen. The 'Details' button will take you to a new screen with additional information including an explanation on how to run the clock without opening the Pi Store.

In the 'My Library' screen click on the 'Launch' button and after a few moments the Flip Clock and local weather details will appear on the screen. Press the <ESC> key to exit at any time and to go back to the Desktop. The weather details displayed on the screen are determined by the location set for the clock. By default this is unlikely to be your location. So one of the things you will need to do is set your location as the default. This is easy to do but requires the use of a Text Editor; we'll see how to do this shortly. Note also that you must have an active Internet connection for the clock to be able to read your local weather.

To delete software you have installed, select the software icon from the 'My Library' tab and then double-click on the 'Delete' button located in the pane to the right.

Text Editors

A text editor is a program that allows you to create, write and edit plain text files. The phrase 'plain text files' essentially means that you should not expect to be able to use fancy fonts or format the text in any special way.

Text editors come in many shapes and guises but the simplest versions are very easy to use. Even the most complex ones can be easy to use once you are familiar with them and they offer a lot more options for the user. Text editors can be used for almost any sort of text or document creation scenario. From writing short notes to long documents there is no restriction on what you can write. However, text editors deal with plain text documents which means you do not have at your disposal the ability to format and create documents that contain a variety of fonts and image as you might with a fully fledged word processor program (we'll look at a word processor you can use in Chapter 23).

If you are working in the Desktop environment then Leafpad is a good choice to use. From the command line Nano and Vi are worth investigation.

Leafpad

Leafpad is the default text editor for LXDE, so any text file that you double-click on in the Desktop should be loaded automatically and displayed by Leafpad. Otherwise Leafpad can be found in the 'Accessories Menu' of the Program Manager. When opened it presents in a window ready for you to start typing.

There are five drop-down menu options across the top of the Leafpad window, and the contents of each of these should be straightforward to use. The File menu allows you to save your work and open existing files that you may have created, as well as giving you access to printing your work and an option to preview how the printed output will look. When you save work for the first time you are automatically taken to the Save As screen. Here you enter a filename and can navigate to a different directory if you wish. In the bottom right hand corner are additional selections you can make in regards to Character Coding. Leave these at their defaults until such time you have an understanding of what they are all about (something for you to investigate in the future!).

_Figure 10e. Leafpad open showing a txt file from the python_games directory that explains the StarPusher game._

The Edit menu allows you to cut, copy and paste text — and you can do this from other sources as well. For example you might have a few Leafpad windows open, each containing different files and use these options to copy and paste between the windows.

The Search menu provides you with the means to locate a particular word or words within the text. The 'Match case' button defines where the word has to be matched on character case or for character case to be ignored. For example, if you searched for 'Leafpad' with Match case not selected then instances of 'leafpad' and 'leafPad' would be displayed. If 'Match case' was selected then these instances would be ignored and only those matching the word exactly would be found. You can opt to replace occurrences of a word with an alternative as well. You can opt to replace all in one go or to step through them one at a time to make your decision. This search and replace feature highlights all occurrences in yellow, and the one you are currently looking at in blue.

The 'Line numbers' option provides line numbers down the left hand side of the Leafpad window. If a line of text wraps around onto the next line then it is deemed to be on the same line. A new line number is generated only when you press <ENTER>. Line numbers are not saved as part of your text and they are used to allow you to reference individual lines, which is particularly useful if you are using a text editor to write a program — something we'll look at in future chapters.

The Options menu allows you to make a few customisations to your work platform. Font allows you to select the font (or typeface style) you want to use in Leafpad. This is a global change, so any change you make is applied to any and all text in the editor. If you have a connected printer then you may want to test this option out in combination with your printed output to see which font gives the best results. Leafpad isn't really built with the printer in mind so output can be a bit spindly.

Selecting Word Wrap will ensure that your text wraps round onto the next line when you reach the rightmost side of the Leafpad window. If this option is not selected then the text will continue across the line until you press the <ENTER> key to create a new line. If not and it extends past the windows edge then you will need to use the slider bar across the base of the window to see the rest of the text — or use the right cursor key. The 'auto-indent' option means that if you decide to indent the start of a line, perhaps by pressing the <TAB> or <SPACE> keys, this will automatically be applied to subsequent lines until such time as you edit it out of the line. This will not affect previous lines which have had indents applied.

Nano

Command line text editors are a personal thing. Everyone seems to have one in particular they especially like and swear by it. In this section we'll look at one of many — Nano. Raspbian also comes with Vi and I particularly like the upgraded version of Vi called Vim. The choice is yours to be explored!

Like Leafpad. besides basic text editing Nano offers features like interactive search and replace, go to line (and column number) and auto-indentation, but it also goes further.

The command format for Nano is:

nano [options] <filename>

So if you have a text file already available you can simply specify its name (including directory path if it is not in the currently selected directory), otherwise you can just type 'Nano' and a new edit window will be displayed. Figure 10f lists some of the options available with Nano. This is not the full list by any means.

You can also use Nano from the Desktop if you wish by opening an LXTerminal window and running Nano inside it.

When Nano is running the screen is divided into three sections. The title bar is the line displayed at the top. The section on the left displays the version of Nano being used. The current filename, or 'New Buffer' if the file has not yet been named, is displayed in the middle whilst the section on the right will display 'Modified' if the file has been modified since it was last saved or opened. In terms of terminology here 'Buffer' is used to indicate an area of memory where the text of the text editor is being held. So if the program asks if you want to 'Save modified buffer' you should answer 'Y' for yes or loose all you changes.

_Figure 10f. Options that can be used when starting Nano._

Across the bottom two lines of the screen various options are displayed. You access these by pressing <CTRL> with the indicated key. On the screen the caret (^) character represents the CTRL key.

<CTRL>-G will provide on-screen help. If you look at the Help screen then you will see there are also Function Keys (The F keys numbered across the top of your keyboard, that you can press to access commands). Above these two lines is a third line — the status line — where information is relayed. In between the two areas and filling most of the screen is the buffer area where text can be entered, edited and manipulated. Figure 10g lists some of the more useful shortcut options that you can use, the appropriate Function key is listed where it exists.

_Figure 10g. Function key options available with Nano._

Note that pressing <F12> provides access to a spell checker if available. The spell checker is not there by default under Raspbian. You can install the spell program by entering the following at the command line:

sudo apt-get install spell

When you next open Nano a spell check will be available to you. Press <CTRL>-T to invoke the spell checker. It will compare each word of the text to its in-built dictionary. Any word that it does not recognise it will highlight and, in the status line at the base of the screen, allow you to edit the queried word. No alternative words are offered and you will need to type the word of your choice. You can then select whether to replace just this occurrence of the word or all other occurrences.

Nano supports cut and paste. <CTRL>-K cuts the entire line where the cursor is located. To paste the line, move the cursor to where you want to insert the line and press <CTRL>-U. The line remains in the a special buffer so if you press <CTRL>-U again it will be pasted again (and again...). If you need to cut a single word or a text fragment, move the cursor to the start of the text then press <CTRL>-6. Move the cursor (using the right arrow key) and notice that the text becomes highlighted as you do so. When you have highlighted the text that you want, press <CTRL>-K to cut it. You can paste using <CTRL>-U as just shown.

Performing a search in Nano is just as easy: Press <CTRL>-W, and in the status line you will be prompted to enter the Search string and press <ENTER>. The cursor will be placed at the first occurrence of the string. To perform a search and replace press <CTLR>-\, specify a search string and its replacement, and press <ENTER>. Then you can choose whether you want to replace only the first match found or all occurrences of the search string.

Line numbers in Nano are not displayed as a column down one edge; instead the current position of the cursor is displayed in the status bar in terms of line and column position. To turn this on use the 'c' option when you load a file:

nano -c <filename>

The great thing about text editors is once you are fluent with one it is pretty easy to turn your hands to others. The only differences are the exact key combinations required to action particular tasks — that said, some of them are the same in various text editors. I strongly suggest you investigate other options as there are so many (certainly check out Vi which is part of the installation, and the upgraded version Vim) and use their interactive help-pages and on-line cheat sheets to assist you.

Text Editors as Configuration Editors

One of the things you will want to do is personalise your use of the Raspberry Pi software and third-party software by making changes to their configuration.

Typically these configuration settings are held in text files that are read by the software when it starts up. Generally it is quite safe to edit configuration files but you should always double check any changes you make to ensure that you don't make errors or do anything untoward that will inhibit the operation of your software. In this respect it is always good practice, before you do anything else, to make a backup of the file you are going to edit by making a copy of it. That way if you make a mistake you can replace the edited file with the original one.

At the start of this chapter we looked at how to install the Flip Clock Pi application from Pi Store. This comes with some default settings and one of those is the geographical location. It would be a great coincidence if this default setting matched your location, so one of the things we can do is to edit the Flip Clock Pi configuration file so that it holds your location.

We need to know where the configuration file is. These details are given in the information provided when the 'Details' button was pressed as described earlier in this chapter. Just under the heading 'Developer's Description' it said the file was located at:

/usr/local/bin/indiecity/InstalledApps/flip-clock-pi/Full/

Open File Manager and navigate to this location by clicking on the directory until you have come to the 'Full' directory. Do not open this by double-clicking it. Instead go to the 'Tools' menu on File Manager and select the 'Open Current Folder as Root' option. We are going to make changes inside here so we need to act as a super-user and this is how we do it from the File Manager.

One of the files inside the Full directory is 'FlipClockPi.conf' and if you double-click on this it will open in Leafpad. Look through this and under the '[weather]' label you will see something like this:

location_code=ASI|TW|TE018|TAINAN ; see WeatherLocationDatabase.txt

The configuration file indicates that the file 'WeatherLocationDatabase.txt' has a list of settings. This file is also located in Full, so double-clicking on it will open it in another Leafpad window. This provides a very long list of locations. Just scroll through the list to find your nearest location, if not the city you are in. Once you have located it make a note of the data you required. I am based in Sydney, Australia so scrolling to Sydney I just copied:

OCN|AU|NSW|SYDNEY

over the TAINAN setting and saved the changes. If you get a screen saying you don't have permission to do so, then you have not correctly opened the folder as root. Abandon changes, move back outside the Full directory and try again.

Next time you launch Flip Clock Pi you should see the effect of the changes you made. If you look inside the configuration file you will see there are plenty of options you can play around with. You could see the temperature in Fahrenheit rather than Centigrade if you wished. You could change the background image if you wanted — a whole host of stuff really.

At the very worst, if you did something that wouldn't work you can either replace the configuration file with your back up or open Pi Store, remove the application and then re-install. It's that easy!
11: Root Causes

Wannabe a super-user? If so, understanding root and the structure of Raspbian will be critical to you as will be the ability to install programs and update the ones you already have. The complete package is here!

In Raspbian super-users are special users that have all-access privileges that allow them to make any changes they want. If you use computers at work for instance you will probably have a member of the IT personnel who is known as the Administrator. This is the same thing. On the Raspberry Pi the super-user is also called the root user. When you set up Raspbian on your Raspberry Pi, your user name is 'pi' and, even though it is your Raspberry Pi and your installation of the Operating System, you are not the root user and you are not a super-user. The reason for this is to prevent you making changes to Raspbian which might make it unusable. However, you probably are the main user of your Raspberry Pi and as such will from time to time need to perform administration tasks. So if you are not a super-user how can you install software and make significant changes when you need to? So far this structure is inhibiting your use of Raspbian. There is a solution.

Sudo Command

The 'sudo' command allows you to execute super-user commands. We have used the 'sudo' command in a couple of examples previously, once to exit Raspbian using 'sudo halt'. With sudo you can do almost anything you want but the most common use of the 'sudo' command is to allow you to update and install new programs. This is something only a super-user can do. Note that not all users are necessarily sudo privileged users. The installation of Raspbian on your SD Card sets you up as a sudo privileged user, but users can have their own privileges set in the same way that files can, and this may not include having sudo access privileges. We also saw at the very end of the last chapter how you can access privileged areas using the File Manager.

Installing Software

In Raspbian, software programs are commonly called 'packages' and they are managed using a Package Manager. On the Raspberry Pi the Package Manager is called 'apt' — this stands for Advanced Package Tool. Some software requires other bits of software to function and one of the functions of the Package Manager is to ensure that all these _dependencies_ are also installed when you are installing a new item of software. All this information is held in an information repository. This is held offline and is accessed by the Package Manager when it is seeking to install or update software. It does this for you automatically.

When you are looking to install a new piece of software it is good practice to update this repository to ensure that the Package Manager has the most up-to-date information on package sources and dependencies. To do this enter:

sudo apt-get update

Note that you must have a working Internet connection to do any updates or install software, as it is all sourced from the Internet. All installation and update commands work in a verbose mode so you will be able to see exactly what is happening and when. Be patient as sometimes your Raspberry Pi may seem to go to sleep — it is merely thinking or waiting on information!

The command:

sudo apt-cache pkgnames | less

will display a list of available package names on the screen a page at a time. It can be a very long list so when you get fed up scrolling through it press the 'q' key to exit. The cache is an area where this information is stored, and in particular information in relation to Raspbian.

If you are looking for something in particular you can try searching for it in the cache. For example, if you like the tetris type game:

sudo apt-cache search tetris | less

This produced a list of 26 Tetris related games when I entered it. The names to the left before the hyphen are the program names you would need to download and install the file. One of the first was 'atris':

sudo apt-get install atris

Most programs like this require you to be in the Desktop environment and you will find them by going to the Program Manager. Installing atris added a new category to the Program Manager on my Raspberry Pi — Games. Double-clicking on the entry started the game, which has the benefit of allowing you to use the mouse to configure play via an on-screen menu. Once running, use the <LEFT> and <RIGHT> cursor keys to move pieces. The <UP> key rotates the item and the <DOWN> arrow key drops the piece immediately.

Atris is also a game you can run from the command line. You simply type in the package name at the prompt:

atris

You will notice that from the command line the game appears much bigger on the screen. The mouse and keyboard work exactly the same as detailed above.

You can find out more about a particular package by using the following command:

apt-apt-cache show <name>

where <name> is the name of the package. This is useful to see if there is a support website for further information — if there is then it will be listed here.

There are plenty of other games that you can try out — but it is worth a search on-line on the Internet to ensure they work OK. Chapter 28 contains information on some games you can download and play on the Raspberry Pi.

When you are installing software of any sort then sometimes additional packages are loaded that you don't need. You can remove any unwanted stuff by using:

sudo apt-get autoremove

If you want to remove a specific package then use:

sudo apt-get remove <name>

where <name> is the name of the package.

Remember that every time you add a package you are eating up space on your SD Card so always remove unwanted files — it's good housekeeping. In fact this command only removes the associated program files and not any configuration or data files. If you want to get rid of everything then use:

sudo apt-get purge <name>

Upgrading Software

Keeping the repository up-to-date is advised as it can be used by the Package Manager to check if you have the latest versions of the software. There are two ways you can upgrade — you can upgrade programs individually or you can choose to upgrade all the programs on your Raspberry Pi. The latter option is a good policy but it can take some time to do, so you might choose it as a background process while you are working on other things locally.

To check if there is an upgrade for a specific piece of software, issue the whole 'sudo apt-get install' option once again, when 'apt-get' will read the package lists and compare them with what it has. If you have the latest version you will get a message to that effect, otherwise it will update the relevant packages to give the latest version.

To update all programs use:

sudo apt_get upgrade

What's Installed?

A basic Raspbian installation comes with a plethora of packages already installed. If you want to see these you can use the following command:

dpkg -l

You might want to use a 'less' pipe to slow the output down so you can examine it more closely:

dpkg -l | less

This provides an alphabetical listing along with the version number and a brief description of the file itself.

Raspbian Structure

Now that you have the ability to whiz your way around the directory structure of Raspbian and indeed interrogate the many files that exist on your SD Card, it is worth looking at the infrastructure of Raspbian itself and in particular the contents of the root directory.

When you wrote the Raspbian image to the SD Card you installed an array of directories and files that Raspbian needs to operate. You must always take care to maintain the integrity of these directories and files, otherwise you may find that the Operating System becomes corrupted. This will mean that you may not be able to boot from the SD Card again. That opens another can of worms as it may also make it difficult to get to other files on the SD Card that you may have created yourself.

Although you will probably never have any need to access these directories yourself it is useful to have an understanding of what each one does, so we'll go through them in alphabetical order. It should be said that these directories and files are not generally for modifying unless you are sure you know what you are doing!

If you were a root super-user then you could access and manipulate all the files in all the directories on your SD Card. As the pi user, although you can look at many of those directories and files you don't have carte blanch to do with them as you might wish. The 'sudo' command allows you to act as a root super-user as previously seen.

/bin:

Short for binaries, this directory contains the programs for many of the commands you execute in the Shell. This includes the likes of ls, mkdir and rmdir to name a few. (Have a look inside the directory for yourself to see what is here.) The term binaries is often used for programs because they are operating at the most fundamental level of the computer and that boils down to 1s and 0s (see Chapter 22) which are binary numbers — also referred to as machine code.

/boot:

This is where the core of the Raspbian Operating System sits and especially the files to get the Operating System during start-up (boot). This is often referred to as the _kernel_. The configuration settings are also stored here in a file called config.txt and you can edit this to change your configuration of your system.

/dev:

This directory contains essential system files and drivers. Drivers are files that are required by other bits of hardware, such as disk drives, to allow them to work and communicate with the Raspberry Pi. This is quite an important directory because it reflects the way Raspbian works in that everything connected to your Raspberry Pi is treated by Raspbian as a file or directory. This may seem strange but if you compare the characteristics of files to that of your hardware they do appear fundamentally similar in that both can be read from and written to. If you bear this in mind then you will start to find it easier to explore Raspbian. We'll see a great example of this when we discuss connecting USB memory sticks in Chapter 14.

/etc:

System configuration files are stored here, often in appropriate sub-directories. Users often refer to this directory as the 'nerve centre of the system'. It is the home for the file 'bash.bashrc' which defines a lot about the way the Shell starts up. It also contains configuration information, for example the file 'timezone' has the name of the timezone you set with raspi-config.

/home:

We've discussed this directory before — it is where the system creates a directory for each user which can be used to store data created by the user. In our case the user is 'pi'.

/lib:

This is the library and here you will find all the common files and programs that are shared by other programs. This includes those needed to boot the Operating System and those that are used by programs when operating.

/lost+found:

This directory is used by the Operating System as a store for any corrupt, non-working programs that it may have recovered.

/media:

Any external media devices that you connect to your Raspberry Pi, such as a USB drive, have their details stored here.

/mnt:

This directory (mount) is not unlike /media:, however, it is used to keep track of details of removable storage devices that are mounted by the user. The subject of mounting devices is covered in Chapter 14.

/opt:

This directory is often where optional software is installed; that is, software you decide to add to your system. These programs are often called third-party applications as they are not part of the original system — neither are they your own work. That said, most software you add to the Raspberry Pi is in files that are stored in a directory in the usr: folder which is detailed below.

/proc:

This is a special directory in that is contains pseudo-files about the status of the Operating System, and it is being continually updated. As you become more advanced at using Raspbian you will find exploring the information here quite interesting.

/root:

As the user pi you don't have permission to change this directory as it's for the sole use of the root user. If you try and access it you will get a 'Permission denied' message.

/run:

This directory can be used by programs to place data they want to preserve and which is saved across reboots of the system.

/sbin:

Software that is specifically used by the root user is stored here.

/selinux:

This directory is normally empty and is only used by a special version of Linux which is security enhanced — thus the 'se' prefix.

/srv:

This location is sometimes used for storing data directories that have been copied over the Internet using a method known as FTP. Generally this directory is empty.

/sys:

This stands for system and is used by the Operating System to store its system files. These should not be touched or modified in any way otherwise you may crash your Operating System.

/tmp:

Stands for temporary and this directory is used by programs to save transient files. These temporary files are normally only required when the software creating them is running, and they do not need to be saved across sessions (reboots). Generally programs should tidy up or delete their temporary files when the program shuts down but sometimes this does not happen when a program is terminated 'illegally' or crashes.

/usr:

Programs that all other users (non root) use and their files are stored here. As such this tends to be one of the largest directories (in memory size) on any system.

/var:

This directory is where variable content is stored. This includes files like logs, database information and output 'spool' files for printers. There are many other types of variable files.

When you first start Raspbian a lot of these directories may not have much in them, but as you install more software and use more programs then they will grow. Equally as you use Raspbian more and more, the contents of these directories will become more familiar to you and you will get used to seeing them referred to.
12: More Bash

In this penultimate chapter about Bash we look at some of the fundamental aspects of its structure and also ways of customising its operation to suit personal needs.

In a later chapter (and final chapter in relation to Bash and the Shell) we'll have a look at how we can create fully fledged Bash programs to automate tasks and streamline the use of the Raspberry Pi. Before we get there we'll look at some useful features of the Shell that can streamline its use and which are fundamental to any good Operating System.

Alias Commands

If a command isn't quite working as you would like it to, you can to a degree change what it is doing. For example, you might always want a long listing when you enter the 'ls' command. But every time you do it you forget to add the 'l' option onto the end of the command. By creating an alias for the 'ls' command you can make it do this by default. Similarly you might prefer to always use the 'rm' command in interactive mode. You can ensure this happens by creating an alias for the 'rm' command, which I illustrate below.

You should be aware that Raspbian has already created a number of aliased changes to Bash commands. So, while you can still create a new alias for a command, you should be aware that it will automatically replace anything that has previously been created.

To see what alias commands may have already been defined just type:

alias

at the command line. On my Raspberry Pi this returned a few items which included:

alias ls='ls --color=auto'

This shows that the 'ls' command has already been defined with an alias, which is to display a colour output when the command is used.

To define an alias for the 'ls' command to automatically produce a long format listing when you enter it type:

alias ls="ls -l"

If you now enter 'ls' at the command line you will get a long listing. However, the colour output will have been removed. Therefore, to keep the long listing and colour output we should issue the following at the command line:

alias ls="ls -l --color=auto"

If you didn't want the colour option or didn't like having to use the 'l' option to get a long listing you could create a new command called 'll' (long listing) to facilitate this:

alias ll= "ls -l"

To ensure that the 'rm' command is always used in interactive mode use the following:

alias rm="rm -i"

Another really practical use for aliases is to assist you in your typing. I for one am a sloppy typist so I will often type 'ld' instead of 'ls' for a listing. Rather than having to re-enter the command each time I get this error I can just create an alias for it:

alias ld="ls -1"

While:

alias LS="ls -l"

This would help me when I get the Caps Lock key confused.

To remove an alias previously defined, just use the alias command:

unalias ls

This would remove any alias created for 'ls'. Whilst:

unalias -a

would remove all alias definitions.

You can also create aliases to make it easier to type in long sequences. For example if you find yourself adding software a lot then you may wish to simplify the 'sudo apt-get update' and 'sudo apt-get autoremove' commands to 'agu' and 'agr' by using aliases.

What you need to remember is that when you log out of Raspbian or switch your Raspberry Pi off, any aliases you have entered are forgotten. So the next time you turn your system on you would need to re-enter the aliases again if you wanted to use them again. The way around this is to create a script file for them and this is something we will do in Chapter 18.

Wildcards

Another way of not just speeding up your use of the Shell but also helping you to narrow down the amount of information you see is to use wildcards. A wildcard is a bit like a Joker in a card game — it can be used to represent anything. In Bash there are a couple of wildcard characters, the asterisk (*) and the question mark (?). You can also use square brackets to signify a data range as well.

Asterisks

The '*' can be used to represent anything, from one character to as many as might be possible in what you are searching for. Thus:

report*

would mean the word 'report' followed by any number of characters. Typing:

ls report*

at the command line would list all the files that it contains that start with the filename 'report' no matter what came after 'report'. So the following files if they existed, would all be listed:

report01.txt

reportoverview

reportsummary.txt

It would not list anything that did not start with 'report' even it it might have the word 'report' elsewhere in the filename. To search for such an instance you could use:

ls *report*

This would list the following files if they existed in the current directory:

overduereport.txt

quick_report01.txt

The asterisk can also be placed at the start of the line, so:

ls *.txt

would list all files that had the file extension .txt.

Question Mark

The '?' is used when you only want a single character to be treated as a wildcard. In the above example we might only want to see copies of a report that ended with a single character, so:

ls report?.txt

Would list the following text files if they existed:

report1.txt

report2.txt

reportX.txt

You can use more than one instance of the '?' thus:

ls report??.txt

This would list files such as:

report12.txt

reportAB.txt

if they existed. While:

ls *.???

would list all the files in the current directory that have a file extension of three characters in length.

Square Brackets Wildcard

Square brackets can be used to represent a range of characters or one of a set of specific characters. Following our earlier examples, if we wanted to list all copies of the txt file report that end with a 0, 1, 2, 3 or 4 we could use:

ls article1[0-4]

The '[ ]' represents a range from which any character can be present, and the range start and end are separated by a hyphen. This range can be something like [2-8] or [1-9] or [10-50] in case of numbers — the range can be anything. Letters could also be selected such as [a-g] or [F-Z] or [A-Z]. However, remember that Raspbian sees 'a' and 'A' as being two totally different characters (which they are in computer terms).

ls report[123].txt

This would list all the txt files that begin with the letter sequence 'report' and end with either a 1, 2 or 3.

The sequences can be even more complex and wildcards themselves may be mixed and matched:

ls [a-d,A-D]*.txt

This would list all the files that have an extension '.txt' and have as their first letter either a, b, c, d, A, B, C or D . The '[ , ]' implies that the range includes a letter which can be from any of the two given sub-ranges. If you wanted to specify the range for two characters in the filenames then you would use the following:

ls report[0-9][0-9].txt

Redirection

We touched on redirection and the use of pipes very briefly in an earlier chapter. In a nutshell redirection means taking the output from one source and sending it somewhere else. Here is a typical example that you can type at the command line:

ls -l > list.txt

The '>' is the redirection operator in this case and redirects the output of the 'ls' command from the screen into a file called 'list.txt'. The file does not have to pre-exist — the redirection operator will create it if required. When the prompt returns you should see the new file in the current directory. You can open this in a text editor to look at it or display its contents on the screen using:

cat list.txt

Each time the command above is repeated, list.txt will be totally overwritten. If you want the new results to be appended to the file instead, use '>>' like this:

ls >> list.txt

When the results are appended, the new results are added to the end of the file, thus making the file longer each time the command is repeated. As before if the file does not exist the first time it is used Bash will create the file.

In Bash standard these streams are pre-connected input and output streams. The three standard streams in Raspbian are called standard input (stdin), standard output (stdout) and standard error (stderr). The former two relate directly to keyboard and screen while the third will normally be directed to the screen.

This terminology is a throwback to the days when computers always contained individual components such as a keyboard, keyboard and screen (then called the console). Nowadays it is used less now that integrated systems have become more common.

These standard streams also have numbers 0, 1, and 2 directly associated with them. Figure 12a lists the standard stream information:

_Figure 12a. Standard streams._

Although the example above uses the output from a command redirection it is not limited to a command — it can be output from just about anywhere. As you learn more about Bash you will see redirection used regularly as it is a useful aid in programming.

The descriptor values can also be used as part of the redirection definition, for example:

<command> 2> <file>

Here Bash redirects any errors generated by the '<command>' used to a file called <file>, the '2' here being referenced from Figure 12a above.

As well as writing to a file redirection also allows you to read from a file by utilising the '<' character. For example:

sort < list.txt

Here the 'sort' command is used to process the contents of list.txt. In this example, the results are output to the display since the standard output is not redirected. We could redirect standard output to another file like this:

sort < list.txt > sorted.txt

Here the command has had both its input and output redirected. The order of the redirection does not matter. The only requirement is that the redirection operators (the '<' and '>' ) must appear after the other options and arguments in the command.

It is also possible to open a stream so that you can read and write to it as you wish. You can type the following at the command line to see how it works:

echo "Raspberry Pi" > text.txt

exec 5<>text.txt

read -n 9 word <&5

echo $word

The first line writes the text 'Raspberry Pi' to the file text.txt. The second line opens text.txt for reading and writing and assigns it a 'descriptor' of 5 (more shortly). The 'read' command is used to read the first nine characters from the file into a variable called 'word'. Finally we can display the contents of the variable $word.

When we open a file in this way it becomes a stream to use and therefore we identify it by assigning it a descriptor value. The values 0, 1 and 2 are already allocated and that leaves 3-9 for us to use. We then refer to the numeric file descriptor whenever we want to use it in the future.

Continue with these lines at the command line:

echo -n X >&5

exec 5>&-

cat text.txt

The second line here is used to close the stream as we have finished with it, and again the descriptor is used to identify the exact stream. The final line will show you what happened in the first line. We used it to write an 'X' to the space in the middle of the text. The position in the stream had been set when we used the 'read' command earlier.

One of the most useful things you can do with redirection is to connect multiple commands together with _pipes_ , represented by the character '|' (usually shift-\ on your keyboard). As we have seen already, with pipes, the standard output of one command is fed into the standard input of another. Here's a very common example that is used to slow the listing output down to make it more manageable to read:

ls -l | less

The '|' character is used to represent the pipe, the 'ls' command is on the left and the 'less' command is on the right. The output of the 'ls' command is fed into 'less'. In this way you can make any command have scrolling output. In the following example, the output of a test file is reported and all duplicate lines are deleted before the new file is saved:

cat text.txt | sort | uniq > sorted.txt

Debian Reference

You can find a lot more out about the use of Bash by consulting the documentation supplied in the Debian Reference manual that you can access by clicking the icon link on the Desktop. This will open up a navigable document in your default web browser that contains hyperlinks for each section. You can move through this as though it was a normal website.

If you would like to look at the files separately then you can find them at:

/usr/share/doc/debian-reference-common/html/

Once here you can view the web files as individual text files, in order to see how the pages are constructed — something you might find useful after reading Chapter 18. Alternatively you could read the text file in Leafpad by double-clicking on the 'Gzip' archive file (choose 'View>>Detail List View' to see the file description to locate this file) and then select the file in the resultant window and right click to select Open With and choose Leafpad. Once in Leafpad you might want to save the file locally for easy reference.

Maynard

Maynard will be released in a final version as the default Raspberry Pi Desktop and will replace LXDE as the standard desktop for Raspbian. While the user interface is different it will appear a lot less cluttered as well as more intuitive. At the time of writing there was no release date scheduled for Maynard, so monitor www.raspberrypi.org for this announcement.

The development version of Maynard can be downloaded and installed on your Raspberry Pi. As the development version is updated then you will almost certainly see improvements in speed and more applications installed.

The download and installation takes about 30 minutes in all and I would strongly recommend that you dedicate a new SD Card to the process of experimentation such as this just in case there are any unforeseen problems that corrupt or damage the installation.

Two commands are required to install Maynard. You should be in the Shell, when you can type the following two lines:

wget http://raspberrypi.collabora.co.uk/setup-maynard.sh

bash ./setup-maynard.sh

Once you have entered the second line the installation will begin. You will need to respond with a 'Y' to the warning prompt that appears, and after that the download and install process will get underway. You may need to respond with another 'Y' just to confirm the download size, so look out for that. As I said this can take up to 30 minutes, maybe longer if you have a slower Internet connection. Do not be fooled by the countdown clock in the bottom right hand corner — once this has ticked away to zero there is still plenty more to do.

Once you have set the process in motion you can leave it to its own devices until it has completed, which you will know by return of the prompt which will ask you to reboot your system to complete the process.

_Figure 12b. The Maynard Desktop environment._

To start Maynard just type:

maynard

at the command line. The ensuing screen will be similar to that shown in Figure 12b. The Task Bar for Maynard is situated on the right of the screen and as you move the cursor over that area the panel rolls out to reveal all the main programs installed in Maynard. This is like a visual version of the Program Manager in LXDE. Clicking on any of the icons will load the program in question. The clock and date is presented digitally at the top of the panel and the Settings Menu can also be accessed here.

To exit Maynard open a Terminal and use:

sudo halt

or:

sudo reboot
SECTION THREE: NEW ADDITIONS

The Raspberry Pi hardware is just the beginning — it's ready to be expanded by you in so many ways. This section looks at some of the essentials you will need to know and how to get them working.

The _Insider_ skills you'll have at the end of this section will enable you to:

  * decide if you need a USB Hub and look at the selection requirements.
  * configure a USB Wi-Fi Adaptor and access the Internet.
  * understand the different file systems on the Raspberry Pi.
  * use external storage devices such as a USB Stick to back-up important files.
  * access cloud-based storage devices.
  * add a printer and get hard copies of your important documents.
  * install and use the Camera Module and capture great pictures and video.
  * use a standard Webcam to take and manipulate pictures.

13: Hardware Revisited

A USB expansion board of some form should be considered an essential addition for your Raspberry Pi. There are some options to consider before parting with your cash. Also, do you need a case for your Pi? This chapter also shows you how to use a USB Wi-Fi adaptor in one of those new USB ports!

_Figure 13a. A USB expansion board such as the Raspiado simply piggy-backs onto the Raspberry Pi main board and provides an additional five USB sockets._

USB Hubs

USB ports are at a premium on the Raspberry Pi. With a keyboard and mouse required as standard that is the total USB connector capacity of a Model B Raspberry Pi gone in one hit! You can hot swap if required — this is why at an earlier point in this book I suggested you always plug the keyboard in at the top on a Model B. This way if you did want to use some other USB device quickly, you could unplug the keyboard and replace it with your short-term requirement. The fact that you have the mouse still plugged in should allow you to click a few buttons and use drop-down menus if required. (This is assuming you are using the Desktop of course.) On completion you can swap the keyboard back in. This is fine for short term, but it is not the best long term solution.

Ideally one of the first peripherals you should purchase should be a USB Hub or expansion board. An expansion board such as the Raspiado pictured in Figure 13a, piggy-backs onto the base B+ or B board and immediately makes a further five USB sockets available.

_Figure 13b. A typical USB Hub for the Raspberry Pi must have its own separate power supply._

A USB Hub is a device that expands a single USB port into several so that there are now more ports available to connect devices to a host system. It is effectively an extension block. They come in various shapes and sizes so pick one that fits your needs. The hub will have a USB lead that plugs into the Raspberry Pi and on the main hub itself offers multiple sockets — all of which you can use. The more sockets on the hub the more expensive the item; as a rule a four socket device should be considered the minimum.

There is only one requirement for a USB Hub to use with the Raspberry Pi — but it is a very important one. The USB Hub you choose must be a powered hub which is one that comes with its own power lead and transformer. This is because the Raspberry Pi itself is not designed to power USB devices other than those on the main board. As for USB versions, USB version 2.0 is still the most common and this will be fine.

Plug your USB Hub into the bottom socket on the Raspberry Pi and then either keyboard or mouse in the other. Remember to turn the USB Hub power on — this can be a common cause for things not working — no power!

The Raspiado comes with an up-rated power supply, to power not just these additional USB sockets but also your Raspberry Pi.

There are pros and cons with both approaches. The Raspiado is a much neater and more elegant solution and doesn't add any additional plugs to your set-up, given that it's power supply replaces the Raspberry Pi power supply. However, if you are continually accessing or changing USB devices plugged into the Raspiado then you will be continually handling the Raspberry Pi, which is not desirable. However, if you hardly ever access you USB ports then it is certainly a great solution. A USB Hub can be positioned away from the Raspberry Pi which may make it more practical if you are swapping USB devices a lot. On a Model B+ there is less need for any form of expansion because of the four sockets available — but add a printer and external storage and they are all gone. As always, I suspect the best answer is to have both options available to you then you can plug the USB Hub into the Raspiado!

Cases

There are an extensive range of cases you can purchase to enclose your Raspberry Pi. However, you should think carefully about how and what you are going to use your Raspberry Pi for before splashing the cash. The reason for this is that there are so many things you can get to add onto your mini micro (the Pi!) that your chosen case might get in the way with your add-on attached. So, when looking you need to go beyond what tickles your fancy and consider the practicality of the case. And a case for the Model B+ requires a different configuration to that for a Model B.

It begs the question also, do you need a case at all? Of my four Raspberry Pis only one is in a case, and this is the one that I use as a media centre (Chapter 26 is all about creating a media centre). I use it to safely hide everything away fixed to the back of the TV, with only the infrared detector slyly poking into view from one side. If you get to the stage where you are using a Raspberry Pi for a specific application or purpose, at that stage there is a perfect opportunity to find the right enclosure and shut the Pi away.

Perhaps the most innovative case is the SmartiPi (shown in Figure 13c)which is for the B+ and is and has a Lego-compatible mounting plate which offers access to a wide range of mounting options including GoPro® mounts. It also has a It also has an optional holder for the Camera Module, which is perfect if your intentions are to use the Raspberry Pi as a photographic device.

Without a case the Raspberry Pi is exposed to the elements and the knocks and bangs, but in several Raspberry Pi years of exposed use, none of my systems have been damaged and banished to the bin. In some circumstances the cost of two cases can exceed that of the Raspberry Pi. So unless you regularly hold meetings of the National Elephant Tap Dancing Society, I am not sure they are a necessity in this day and age of the disposable computer.

_Figure 13c. Make sure that any case you purchase is fit-for-purpose. This SmartiPi case is designed for the Model B+ and has a Camera Module hosing and the top plate is Lego compatible!_

USB Wi-Fi Adaptors

If you plan to use a USB Wi-Fi adaptor for connecting to a router to access the Internet then you will find setting it up is very easy.

You will definitely need a USB Hub if you are using one of these adaptors on a Model B as you will need a minimum of three USB connections: the adaptor, keyboard and mouse. On a B+ simply plug the adaptor into a spare USB socket — you'll still have one spare!

You will also need the password for your network — this is the code that you use to connect other devices to your network, such as a mobile phone or tablet.

With the adaptor in place, turn on your Raspberry Pi and launch the Desktop. You will find the option WiFi Configuration in the Prefrences Menu of the Porgram Manager. (or run the program called 'wpa_gui' via the 'Internet' option in the Programs Menu if you have an older version of Raspbian). This will open a window inside which you will see two drop-down menus. The adaptor box should be displaying the default name of your Wi-Fi adaptor. The Network box will be empty and you have to enter the name of the network (or router) into this box.

_Figure 13d. Clicking the Scan button should locate your network._

Click on the 'Scan' button at the lower right of the window and then 'Scan' again in the subsequent window that appears. This will scan for any Wi-Fi connections it can find. The name of your Wi-Fi network should appear in here — others may also appear if people nearby have Wi-Fi networks running.

Double-click on the name of your own network and this will display a further window which contains details of this. The 'PSK' box will be empty — here you need to add the password for your network. Make sure you enter it exactly, matching character case where relevant (upper and lower case letters).

_Figure 13e. Once completed your network name should be displayed in the network box._

Press the 'Add' button. The name of your network should now appear in the original window. Close the 'Scan Results' window. On the 'Manage Network' tab make sure the named network has 'Enabled' already selected (it should do this automatically). That should be enough to get you up and running with a Wi-Fi connection and allow access to any connected Internet.
14: External Storage

Your SD Card is where you are most likely to store the files and projects that you create on your Raspberry Pi. But this storage is limited, so if you want to make backups or transfer information you will need to use external storage devices. In this chapter we look at the options and explain how to use these devices.

USB storage devices are by far the best and the most convenient way to move your data around and to keep things backed-up locally. You can purchase 32GB USB Sticks quite cheaply now and these should provide plenty of room to save your important files.

Other options, which are useful for backing up all-important files, are network storage devices (if your Raspberry Pi is connected to a network) or an on-line or cloud storage site. We'll look at each of these in turn and see how to use them.

This chapter will deal mainly with the use of the command line to manage external drives and to move files around between them, but we will also examine the use of the Desktop.

USB Devices

There are two types of USB devices you can use: the small plug-in devices often called flash drives or memory sticks, the others being external hard drives. The USB memory sticks tend to have capacities ranging from 2GB to 32GB and are very handy for transferring data. The USB external hard drives are much bigger than this and can offer vast amounts of storage for not many dollars. Just be aware of the power requirements for larger USB drives — these can be purchased with the intention of being powered from the USB socket itself, and normally work fine in combination with a PC or Mac. However, they will probably not work with the Raspberry Pi due to the limited amount of power available at the Pi's USB socket. Therefore always ensure that you use hard drives with own power supplies.

_Figure 14a. A USB memory stick is perhaps the most convenient external storage medium for use with the Raspberry Pi._

USB Sticks come in all shapes and sizes nowadays, but given the tight profile of the USB ports on the Raspberry Pi, unless you have an expansion hub it is best to keep to the plain low-profile versions like that illustrated above in Figure 14a.

Desktop Environment

If you are working in the Desktop then when you plug in a USB Stick of any sort it will automatically be _mounted_ (this means it will be seen and identified as a usable device by the Operating System) and will pop up a window similar to the one shown in Figure 14b below:

_Figure 14b. When you insert a USB Stick into the Raspberry Pi you will be asked whether you wish to open the device in File Manager._

Selecting the 'OK' button will open the File Manager. This is illustrated in Figure 14c. Note that the USB Stick is named in the Places pane and the bottom of the window shows how much storage there is on the USB Stick. (Note that I will use the term 'USB Stick' to refer to a memory stick or flash drive to distinguish it from an externally powered USB hard drive.)

_Figure 14c. The USB stick opening in File Manager._

The name assigned to the USB Stick (USBSTICK in the example above) is how the device was originally named by the manufacturer or previous user. The upwards pointing triangle to the right of the name is the 'eject' button. If you click on this the device will be ejected from the computer. This does not mean it will pop out of your Raspberry Pi or USB Hub like a DVD from a DVD Player — simply that the device will now be 'unmounted' or no longer recognised and therefore that it is safe for you to unplug. You should always eject your memory stick or drive in this way before physically unplugging it.

If you get an error message along the lines of:

Error starting job: Failed to execute child process 'eject' (No such file or directory)

Then this is easily solved. Open a Terminal window and execute:

sudo apt-get install eject

This will install the 'eject' command and ensure that the operation works correctly in future.

Copying, moving and generally manipulating files on the USB Stick can be performed simply by dragging files to and from the device into another File Manager window open at the directory where you want the files to end up. From your point of view it is no different than moving other files around between directories using File Manager. The difference is that when you unplug the USB drive you can then plug it in somewhere else (another Raspberry Pi, a PC or Mac) and use the files there.

USB Sticks In the Shell

If you are operating at the command line then when you plug a device in you will not get any automatic response or message as you do in the Desktop environment. When you insert a USB Stick you have to issue commands to identify it to the Shell. This process is called _mounting_.

If you have already opened your USB Stick in the Desktop — as in the example above — then your device will already be available for use in the Shell. It will have already been mounted. To show you how to do this and use the USB Stick in the Shell you will need to unmount it. To do this, enter the following at the command line:

sudo umount /media/USBSTICK

Substitute the name of your own device if it is not called USBSTICK. In the examples that follow USBSTICK will be used as the device name so substitute with the name of your particular device at these points. If your name contains a space, for instance 'USB STICK' then you will need to enclose the name in double quotes when you use it so that the device is recognised, eg, "USB STICK". Also ensure that you use matching capitalisation.

With the command line ready, insert the USB Stick. You can find out what devices are plugged into your Raspberry Pi using the 'blkid' command thus:

sudo blkid

Typical output is shown in Figure 14d. Note that the first two items refer to your SD Card. The third item on the list identifies the USB device in this case and its name is given in the third line — USBSTICK. From our point of view it is the beginning of the line we are interested in and the sda number. Here it is 'sda1'. Note also that the line gives the TYPE as 'vfat'. (I'll explain things like 'vfat' and some other things that will pop up shortly in due course — just bear with me for the moment.)

_Figure 14d. Output at the command line listing attached devices._

To be able to mount a USB Stick we need to make an entry for it in the '/media' directory. This entry is in fact the creation of a directory with the name of the device. So enter:

sudo mkdir /media/USBSTICK

Because the media directory is in root, we need to use the 'sudo' command to enable us to create the directory.

To mount the device use (all one line):

sudo mount -t vfat -o uid=pi,gid=pi /dev/sda1 /media/USBSTICK/

The memory stick is now ready for use.

If you refer back to Figure 14c and look at the URL for the USBSTICK in the File Manager you will see that it is set to:

/media/USBSTICK

When you mount a drive in this way Raspbian looks at the files on the drive and copies their details into the directory you have created. So to look at any files on the drive you can use:

ls /media/USBSTICK

In these examples we have used the same name for the directory as was assigned to the label or name for the USB Stick. You don't have to do this. You can use any name you like — what is important is that you use the correct device name — which in these examples was 'sda1'. Instead of using 'USBSTICK' I could have used 'USB' or 'usb' or whatever.

Note also that a USB Stick may not always be associated with 'sda1' as its device — it could be something else such as 'sdb1' for instance, if you added a second device. So always check and do not assume.

Mounting File Systems

Let's now look at some of those options used in the 'mount' command above. The purpose of the 'mount' command is to allow access to information on file systems. A file system can be thought of as an Operating System for storage devices — and it specifies and defines how data is stored on the devices that use that particular file system.

There are two main file systems used with Raspbian on the Raspberry Pi — these are FAT32 and NTFS. You don't need to understand their inner workings or what makes them different; you should know they exist though. In general most USB memory stick drives use the FAT32 system, and larger hard disk drives normally use NTFS. You can happily copy files between these types using your Raspberry Pi, as the software knows about the file system differences, so they are transparent to you as the user.

Referring back to the command we used on the previous page — when we mount a device we need to specify the file type. This is done with the 't' option. In the mount example I showed earlier it was specified as 'vfat' which indicates FAT32. To mount a NTFS drive then the file type is 'ntfs-3g'. We'll look at this in an example later in this chapter.

The next part of the line starts with 'o' which specifies options. These options are: 'uid=pi', or 'gid=pi' which is telling that the user that pi is mounting with read and write permissions. This assumes you are logged in as pi. If not substitute your user name.

The final part of the line lists the mount source for the device (/dev/sda1) as previously identified and then the directory path in root linked to the device.

Copying Externally

Copying, moving or listing files is performed in exactly the same way as we have used previously — all you need to know is where the external files are stored, or more correctly the associated directory name in '/media'. For example, to copy the entire contents of the python_games directory onto the USBSTICK I could use:

cp ~/python_games/* /media/USBSTICK

If the USB Stick had a file called 'drive2.png' on it that I wanted to copy into the Backup directory in my home file I could use:

cp /media/USB/drive2.png ~/Backup/

As you can see, you treat an external drive as though it was another directory in your environment, but it is based out of '/media'.

You use the same process to copy between two external sticks or drives.

Unmounting Drives

You can unmount a drive in one of two ways, either by specifying the media directory it is associated with or by unmounting the device name. So if USBSTICK was assigned 'sda1' as its device both the following would work:

sudo umount /media/USBSTICK

sudo umount /dev/sda1

Note the spelling of the command here in that there is no 'n', it is 'umount' and not 'unmount'!

If the drive will not unmount then you can force it to do so using the 'f' option:

sudo umount -f /dev/sda1

Hard Drives in the Shell

The process for mounting and accessing larger USB Hard Drives in the Shell is essentially the same. In fact, apart from a possible change of file system, not much else changes. When you use a new drive for the first time always check its file system with:

sudo blkid

If it is vfat or FAT32 then you can continue to use the method outlined above. However, you may find yourself looking at NTFS or ntfs-3g or something similar, in which case you need to assign the type as ntfs-3g (note the following is entered on a single line):

sudo mount -t ntfs-3g -o uid=pi,gid=pi /dev/sda1 /media/usbhard/

Here 'usbhard' is the directory assigned to the hard drive.

If you get an error message stating that ntfs-3g is an unknown file type then you will need to install it with:

sudo apt-get install ntfs-3g

If you want to see a bit more information about external devices attached to your Raspberry Pi then use the 'fdisk' command thus:

sudo fdisk -1

This will also show you how big each drive is.

Web Based Cloud Storage

There are a good number of on-line secure storage options you can take advantage of. Many of these offer a significant amount of storage at no charge. In the short term this is to get you to try them out and in the long term they hope you use so much that you will purchase additional 'cheap' storage options. How cheap is cheap? Well, at the time of writing, the provider I use provides a total of 100GB for $25 per annum, but also offers 50GB of storage for free.

All you need to do is to go on line and search 'cloud storage' and then look around for the option that suits you best. Loading files up and down eats into your monthly quota so if you are doing a lot of file transfer make sure you have a big enough Internet plan, or purchase a data pack to get you there if you are not prepared to manage the initial file upload over a period of time.

With these web-based storage interfaces the upload and download of files is managed from within the web browser and is straightforward. If nothing else, use some of the free storage to save all your on-line photos and pictures and be secure in the knowledge that you have a backup should your own local copies ever suffer a disaster!

Services such as Dropbox are very popular and also allow you to transfer files between computers and third parties.

Backing Up Files and SD Cards

Maintaining your files and keeping them safe is entirely your responsibility. Documents, photos, images, videos and anything you create can suffer corruption or accidental deletion. Ask yourself what files you have that would create pain or a lot of trouble should you lose them for ever — these are the files you need to create duplicates of straight away. Yes, it can be time consuming but consider it an essential chore.

The easiest way in these circumstances is to use your medium of choice and then just copy the folders and file across onto it. Create a backup folder and include the date in its name. This way you know when the last backup was. Ideally you should have a couple of backup drives and should keep one of them 'off-site' just in case... Another off-site method is to use cloud storage as mentioned. I also have a GMAIL account where I send all my important documents and files. This makes them instantly available from anywhere I happen to be.

This protects the files that you produce — however, not your working environment! You will spend a good amount of time installing software that you like and configuring it to work just as you want. If you lose all this through a corrupt SD Card then your working environment is gone in a flash. This can be equally annoying as losing files. However, you can save an image of your working environment (and everything on your SD Card) that you can copy onto other SD Cards as and when you need to. And you can do this by using the same process you used to write your OS to your SD Card in the first place!

In Chapter 4 we used software called 'Win32DiskImager' to write the Raspbian .img file to the SD Card. You can use this (and any other software you might have used to undertake this process) to save an image of the SD Card as it is now. To do this, turn your Raspberry Pi off and then remove the SD Card that you want to back up. Place this into the SD Card slot on your other computer (for example, your PC) and run Win32DiskImager.

In the 'Image File' box, enter the path of your soon-to-be image file along with its name. I recommend incorporating the date into the name.

_Figure 14e. Select a name for the image file and click the 'Read' button to make a copy._

Under the 'Device' box, select your SD Card if that is not already automatically selected. Then click the 'Read' button to create the image file from your card.

When the system has finished creating the image file, you can eject your SD Card and put it back in your Raspberry Pi. Keep the .img file in a safe place and use it to write new copies of the Raspbian Operating System to SD Cards with everything in place. You may find it useful to update your software when you plug the new SD Card back into your Raspberry Pi.
15: Printers

If you intend to use your Raspberry Pi in a home office or to learn programming you're sure to want to print out your results. In this chapter we look at the software to use, how to configure it and even how to print from the command line. You will need a printer of course!

One of the few areas where the Raspberry Pi has been a little disappointing is in the use of printers and the associated printer support. Most Operating Systems attack the issue of printers head-on but Raspbian is not one of these. Installing and configuring printers has become a bit of a black art and has been for many years, not least because there are so many makes and models of printer. Often the real trick is picking the correct printer from the lists that are presented by the system. It is important that you know the exact make and model of your printer as the software that translates the information from the page you are printing to ensure the correct output onto paper is dependent on this. This software is called the _printer driver_.

The printing of a page — especially one containing graphics and a plethora of data — is a processor intensive operation and so, for anything other than text, it can be a tad slow on the Raspberry Pi. It would not be unfair to say that if you were looking to select a computer to handle all required printing needs then the Raspberry Pi would not be at the top of your list. That said, it can certainly handle printing and is capable of handling any documents that you may create using third-party software.

Printing With Cups

Before starting out with your printer installation make sure your system is fully up-to-date by using:

sudo apt-get update

Then ensure that your printer is switched on and available. There are three possible connection types you could have — through the USB and on the local network — either wireless or cabled. The setup process is the same in each case. In the worked example that follows I have a Samsung ML-2580N printer connected via a router on my home network.

You will need to download and install the CUPS (Common Unix Printing System) software. The command to do this is:

sudo apt-get install cups

The process can take a good half hour and you will need about 75MB of free space on your SD Card for it. Part of this installation program includes installing all the possible printer drivers you might need. Of course at the end of the day you are likely to only need one or two of these!

CUPS uses the group 'lpadmin' to determine who is authorised to administer printers. You will need to add the lpadmin group to your user profile to enable you to administer the printers. This can be done by issuing:

sudo usermod -a -G lpadmin pi

This assumes that your user name is still pi; replace pi with your own user name if you have changed it.

The rest of the setup can be done through a web browser. In your Desktop environment open your preferred web browser. In the URL bar enter:

http://127.0.0.1:631

and after a moment or two the 'CUPS' screen should appear, looking similar to that shown in Figure 15a.

_Figure 15a. The opening CUPS Screen._

As this is also the screen you will need to come to if you want to change settings or add new printers in the future it makes good sense to Bookmark it at this point.

There are a number of tabs running across the top. Click on Administration and then select 'Add Printer'. At this stage you will be prompted for your username and password — enter your normal Raspbian login name and password.

CUPS will then search for printers that are locally connected and any it can see on the network. This may take a few minutes. Figure 15b shows the results from my Add Printer search.

_Figure 15b. Results from using Add Printer._

As you can see in Figure 15b, CUPS has found my network printer 'Samsung ML-2580N'. In fact in this example it's found it a few times. Here I just clicked on the button beside the first entry to select it. It also reported that it found HP printers — I ignored this as I didn't want to use them. Once you are happy with your selection click the 'Continue' button. (If you have a printer attached via USB then it should be listed under the 'Local Printers' option.)

The next window allows you to edit the name and location of the printer, as seen in Figure 15c. If you have only one printer the fields can usually be left at their defaults, but it's nice to personalise things:

_Figure 15c. Edit name and location of printer._

One field that you may consider if you have a local printer is the 'Sharing' option. This is not normally required for a network printer where you can connect direct from the computer to a printer, but here it would allow you to share a USB printer across the network if required.

Once you select 'Continue' CUPS will search through its database and come up with a list of potential printer drivers for your printer. You should scroll through these options until you find the one for your printer — ie, the one that exactly matches the name and model number of your printer.

If there is not an exact match then there are a couple of options. Firstly, if there is a make and model number that is very similar try this or if there is a generic driver for your make of printer, this would probably work as well — even if it doesn't support all the printer features. Alternatively, try searching the Internet with something like: 'Linux printer driver XXX' where 'XXX' is the name and model of your printer.

Once you have selected your printer click 'Add printer'. The next page allows you to set the default options for your printer. It isn't really necessary to do this at this exact point as you'll tend to do this from the application when printing.

Now that you've followed these steps, in any program that you use in future you should be able to go to the 'File>>Print' option and select the page or pages you want to produce. Printing can be a bit of a slow process, but it generally gets there in the end.

Printer Troubleshooting

Printing is quite a complex process so it's hard to provide details of everything that could go wrong and how to fix it — but here are a few pointers. You can choose to Print a Test page from the Maintenance menu at the end of setup. That said, I couldn't get a test page to print, but I opened a .txt file in Leafpad on the Desktop and this printed perfectly. So it wasn't a massive issue as I was still able to print most things I wanted.

Other things can create printing problems. Overload is one of them and if the Raspberry Pi is trying to do too much or has some memory constraints then this can create a situation where the printing software thinks nothing is happening so it 'times out' — stops. That said, as with most things pi, be patient as it can take time. Otherwise try quitting any program or application you are not using and try again.

Printing From the Command Line

Printing from the command line requires some thought. Although you will have used the CUPS browser to set up and install your printer, the printer information doesn't magically transfer into the Shell. So, there is some housekeeping you need to do before you can print.

The first step is to set the default printer for use. For this you will need the name assigned to the printer previously installed. If you refer back to Figure 15b the information you require is that listed after 'Name'. In my example it was: Samsung_Samsung_NL-2580N. Then use:

lpadmin -d "Samsung_Samsung_NL-2580N"

You can check that this has been set correctly using:

lpstat -d

You could then print a test file successfully using:

lpr Text.txt

This assumes there is a file called 'Test.txt' in the currently selected directory.

You can use the same command with a 'p' option to print out the details and status of attached printers:

lpstat -p

You can print a graphics file in exactly the same way as you would print the above .txt file:

lpr pilogo.png

On my printer it printed the 'ocr_pi' image (which should be in the pi directory) in very large format, occupying the entire sheet of A4. Or by using:

lpr -o scaling=50 pilogo.png

the printout was half the size. You can use other values for scaling — defining the percentage of the original size — the original size being 100. If an image is too big to fit on a page you can force it to fit by using:

lpr -o fit-to-page <filename>

If you have more than one printer attached to your Raspberry Pi then you can define which printer the file gets set to by using the 'd' option thus:

lpr -d <printer> <filename>

where <printer> is the name of the printer (as defined previously) and <filename> is the name of the file to print.

Printer Options

In the example above the 'o' option was used to scale a graphics file. There are many other options available for use with the 'o' prefix. These are not generally listed as part of the standard command help output so I'll list the ones I am aware of here and then provide a few examples. Note that your printer may not support all options so you will need to check to see; equally some options can take multiple values:

landscape

scaling

media

collate

orientation-requested

sides

lpr -o landscape -o media=A4 <filename>

Here the command is requesting that the page is printed in landscape view and that the paper (media) is A4 size. The 'media' option can be used to define the size, type and source. It is important to note here that the 'o' indicator is used before all option definitions. Unlike other commands, options cannot be combined into a single string and may result in an error or fail to work if you try to do so.

Other options that can be used in place of A4 are Letter, Legal, DL, and Transparency. The media source can specify the paper tray to be used — typically Upper, Lower or MultiPurpose. These options can be combined thus:

lpr -o media=Letter,MultiPurpose <filename>

lpr -o media=A4,Upper,Transparency <filename>

The 'landscape' option prints the image horizontally across the page instead of vertically, but you can also use the 'orientation-requested' option thus:

lpr -o orientation-requested=<N> <filename>

Here <N> is a number with the following effect:

N=3 No rotation (portrait)

N=4 90 degrees rotation (landscape)

N=5 270 degree rotation (reverse landscape)

N=6 180 degrees (reverse portrait or up-side down.

The following command would send our Test.txt file to the printer and print it in landscape format:

lpr -o orientation-requested=4 Test.txt

If your printer supports two-sided printing then there are a couple of commands that will be of interest to you:

lpr -o sides=two-sided-long-edge <filename>

Will print in portrait mode on both sides of the paper while:

lpr -o sides=two-sided-short-edge <filename>

Will print two-sided landscape pages. The default is to print singles sided which can be reset with:

lpr -o sides=one-sided <filename>

Normally when you print a file you print all the pages, but in Windows style environments the print options page allows you to specify what pages or what selection of pages to print. You can do this from the command line as well using the page-ranges option. Here are a few examples:

lpr -o page-ranges=4 <filename>

lpr -o page-ranges=1-3,7,8-11 <filename>

Here the page numbers given are the absolute page numbers, that is the page count from the beginning. This may not necessarily line up with the page numbers you have set for your document.

You can also specify to print only odd or even page numbers:

lpr -o page-set=odd <filename>

lpr -o page-set=even <filename>

If you want to draw a border around your page then this option is catered for by the 'page-border' setting, which has double, double-thick, none, single and single-thick as possible attributes:

lpr -o page-border-double-thick <filename>

This one can be a little tricky and you may need to play around with your margin settings (see below) to get it to work correctly.

If you have a list to print then defining the number of columns on a page may save you some paper:

lpr -o columns=2 <filename>

This would divide the page into two columns. The default option here is 1. You can specify other numbers.

Page margins can be set by side, sides or the whole page. The dimensions are specified in 'points' — a point being 1/72nd of an inch or 0.35mm. The following definition would send the Test.txt file to the printer with a one inch margin on all four sides (this is all one single line):

lpr -o page-left=72 -o page-right=72 -o page-top=72 -o page-bottom=72 Test.txt

The examples above are standard options — your printer may have printer specific options and you can find out what these are by using:

lpoptions =p <printer> -l

This will display a list of all the keywords available for use in a similar fashion to that illustrated above., where '<printer>' is the printer name.

Information about using printers with the Raspberry Pi and Raspbian in particular is pretty scarce so be prepared to experiment to find out what your printer can do and how you can make it do it!

CUPS Files

You can find out more about the CUPS software by looking at the data it stores on your Raspberry Pi. If you navigate to '/etc/cups' you will find a variety of files here. The most interesting is in the 'ppd' directory ('ppd' standing for Postscript Printer Description). This will contain a .ppd file bearing the name of your default printer. If you open this in a text editor you will find that it is an English-like description of all the properties of your printer.
16: Camera Happy

If you don't have the Camera Module module for the Raspberry Pi then you are missing out on a lot of fun. But if you have a webcam already then you can still get snap-happy!

The Raspberry Pi Camera Module is a lot of fun and is relatively cheap. There are two types of Camera Module available, one of which is a night-time camera which is sensitive to infrared. The standard Camera Module can take high resolution images that you can edit and manipulate on your Raspberry Pi. This chapter looks at the normal 'day' Camera Module and also shows you how you can use a standard webcam to be picture perfect. The picture above shows how the Camera Module can be mounted on a tripod using a GoPro mount with a SmartiPi case and battery pack. Let's start by having a detailed look at the Camera Module.

Up and Snapping

The first step is to attach the camera to Raspberry Pi board. It is _important_ that you ensure that you remove any static you may have on you by touching a large metal object first. The camera can be damaged or destroyed by static electricity. If you look back at Chapter 5 there is a section about static electricity there and how to ensure you are free of it.

As with installing any new software and especially hardware, I would strongly suggest you check for any software updates and upgrades first:

sudo apt-get upgrade

sudo apt-get update

Inserting the camera ribbon connector into the CSI socket is easy — getting it right first time less so! The thing is that the ribbon connector has to be entered squarely and pushed as far in as possible. The blue edge points away from the HDMI port so that when you hold the cable straight and upright, the camera lens points in the direction of the HDMI port.

_Figure 16a. The Camera Module fitted to the Raspberry Pi._

When you have completed the process, about half of the blue edging will be outside the socket. I am not the brightest with fiddly things so it took me a few attempts to get it right. Every time you look to re-position the ribbon you must turn the Raspberry Pi off first. This is good encouragement to spend some time at the onset satisfying yourself that the ribbon is square and lined-up correctly.

You may also find a small green tab on the lens — this is to enable you to pull what is a small protective film off the lens.

Once you have the camera connected switch back on and open the raspi-config tool from the command line:

sudo raspi-config

Select the Enable Camera option, select 'Enter' and then 'Finish', at which point you'll be prompted to reboot. You can do this with:

sudo reboot

Once the system is back up and running you can use the command line to test things out. As you will probably want to look at the image you are taking it is best to be in the desktop environment and enter commands through a terminal window. Enter:

rapistill -o pic1.jpg

Now you'll either see an image of whatever the lens is pointing at on the screen, or you'll get an error message. The image preview will be shown for about five seconds, at which point the picture will be taken and saved to the Pi directory. This should give you enough time to point the lens where you want it. If you open the Pi directory you should see the file there. Right click on it and select 'Image Viewer' to open the file (we'll look at Image Viewer in detail in Chapter 27).

If you receive an error message in which the last line informs you that the Camera Module couldn't be found then you have probably inserted the ribbon incorrectly. After powering down, put this right and try again.

You might also get a message stating that a firmware update is needed — this is different from the upgrade and update we did at the start. To do this you will need to issue the following command:

sudo rpi-update

This takes several minutes and you will need to reboot (yes, again) after that. This immediately solved the problem for me. It is then just a matter of turning on and trying the above sequence again.

You can also use your camera to take video, this command will take a five second clip:

raspiivid -o vidi1.h264 -t 5000

Here vidi1.h264 is the name and format of the video file and the time is set in milliseconds by the 't' option, for example 5000 ms = 5 seconds. You can play it back with any suitable software. Later in some of the chapters in Section 5 we look at how to play video. For now you can use the command line to call a standard application supplied with the Raspbian called 'omxplayer' (covered in Chapter 24):

omxplayer vivi1.h264

Taking Stills

Figure 16b lists some of the options available for taking images which deal with image size and quality.

_Figure 16b. Size, quality and rotation options available._

By default, the camera captures all still images in the highest resolution — this means that the images are of the best quality but also very large — typically 2.7MB in size. This is because the file measures 2592 by 1944 pixels. Multiply those pixel rows and columns and you have over 5 million pixels (5 megapixels).

You can change the size of the image by using the 'w' and '–h' options to limit the height and width. We can get an image that is about a quarter of the screen size by halving the pixel count:

rapistill -o pic1.jpg -w 1296 -h 972

If you want to create a narrow image set the width parameter only:

rapistill -o pic1.jpg -w 1296

Or compress to create a landscape-style image:

rapistill -o pic1.jpg -h 972

The 'quality' option allows you to restrict the size of the file by specifying the amount of compression to apply to the jpg image you will save. A value of 100 is almost no compression.

You can flip an image along either the horizontal or vertical axis using 'hf' and 'vf'. The on-screen preview reflects this. For example, to create an image that flips through 270 degrees use:

rapistill -rot 270 -o pic1.jpg

Preview Options

The preview you get on the screen for the narrow images where you limit the height or width does not change by default (so in the strictest sense is not a preview!). So you might be taking a letterbox style picture, but still seeing a full-screen preview. However, some options are available to define the type of preview displayed . These are listed in Figure 16c.

_Figure 16c. Preview options available._

Here are a couple of examples:

rapistill -o pic1.jpg -p '100,100,600,200'

This would position a letterbox-style preview screen in the top left hand corner of the screen. However the image taken would not be affected and would still be full size in every aspect. To get a still that mirrors the screen preview you would use the following:

rapistill -o pic1.jpg -p '100,100,600,200' -w 600 -h 200

Image Control

There are numerous options that allow you to make adjustments to specific options of camera operation. Figure 16d lists some of those available. This is not a compressive list, which can be obtained using:

rapistill –help

The image effect options can provide some light entertainment, especially the cartoon effects:

rapistill -o pic1.jpg -ifx cartoon

The exposure mode options will replicate most of the dial functions on a handheld SLR camera.

_Figure 16d. Some of the camera image control options available._

Time Lapse

The Raspberry Pi camera is great for taking time-lapse images. This is a fun activity for the younger members of the family who might, for instance, want to see what happens at home when they are out at school, or may wish to track the weather. Or maybe follow what the family dogs do in the garden!

The command for time-lapse photography looks like this:

rapistill -t 60000 -tl 2000 -o pic%04d.jpg

This would create a series of 30 pictures taken every two seconds over a 60 second period (60000/2000). The time values are specified in milliseconds. The filename would here start with 'pic' and then have a four digit number appended to it reflecting the image in the sequence, 0001, 0002, 003 etc.

The end result could be stitched together in suitable software to create a video file, or alternatively display them in an application like Image Viewer (see Chapter 27) using a short pause delay.

If you intend to create a lot of images as part of your time-lapse sequence, make sure you create and set a new directory as the working directory, otherwise you may find your normal directory swamped in image files. Another point is that it is worth considering a smaller image size when doing time-lapse unless you have plenty of spare memory capacity.

More Functions

There is a lot to explore with the Camera Module. In Section Four we cover programming and in Chapter 18 we'll look at how to create a Bash program that will automatically add a time and date to your pictures.

In Chapter 19, we cover Python programming and look at how we can use some specific camera commands using a specially written extension library supplied.

You may also want to edit images taken with your camera and Chapter 27 has some details on how to do this.

Finally you can find a lot more about the 'PiCamera library' and how to use it at the following web address:

<http://picamera.readthedocs.org/en/latest/index.html>

Using Webcams

You can produce surprisingly good results by hooking up an ordinary webcam to a USB port on your Raspberry Pi. The images will not be of the quality of the Camera Module, but they are good enough to experiment with.

To try this, you need a USB webcam and also you need to install the fswebcam software package using:

sudo apt-get install fswebcam

Then it should be just a matter of pointing the camera and issuing the command to take the picture:

fswebcam image1.jpg

Where 'image1.jpg' is the name of the file and format to be saved. The image will be time and date stamped for you by default. If you are presented with a blank file and an error message along the lines of 'gd-jpeg: JPEG library reports unrecoverable error: Not a JPEG file: starts with 0xff 0x80' then it is likely you will need to do a bit of fiddling with the options available for fswebcam, especially the palette options. Another cause might be that the USB webcam requires a bit more power than the Raspberry Pi can provide, in which case you may need to use a powered USB Hub (see Chapter 13).

The fswebcam software has 'man' pages available so these can be viewed on screen or written to a file for reviewing. Some of the major ones you will want to know for getting up and running are detailed in Figure 16e below.

_Figure 16e. Some of the Options available for use with fswebcam._

The following command solved the black-box image for my Logitec webcam by selecting the correct palette for it to work with. It also created a well-defined image (all one line):

fswebcam -p YUYV -d /dev/video0 -r 640x480 image1.jpg

Note that options are interpreted and actioned in the order that they are placed on the command line, so if you are not getting the result you expect examine your command order. For example (all one line):

fswebcam -r 640x480 full.jpeg --scale 320x240 half.jpeg

will capture a 640x480 resolution image and save it as full.jpg and will then write the same image at 320 x 240 to the file half.jpg.
SECTION FOUR: PROGRAMMING

Learning to program can be a frustrating experience. But, being able to create your own solutions to computing projects is so incredibly rewarding that it is well worth taking the time to master. And with most languages having many common structures, learning the basics in one puts you well on the way to working with many others. It is a skill that you will always cherish.

The _Insider_ skills you'll have at the end of this section will enable you to:

  * understand what a program is and the various structural components that almost every language possesses.
  * write Bash scripts and take control of the way Raspbian operates.
  * create and edit existing Python scripts and use Python libraries.
  * use Scratch to create animations using programming blocks.
  * make your own personal website for use at home or on-line.
  * understand the fundamentals of programming your Raspberry Pi at its microprocessor level.

17: About Programming

Programming is not a mystic art — in fact you already have many of the skills you need and the fundamentals are the same for any of the many programming language options you have with your Raspberry Pi.

Although you may not realise it, you have already been programming a fair bit. Every time you type a command at the Shell you have issued a program command. However, when we talk in general about programming we are normally looking at creating a sequence of commands that when combined together form a program with a defined outcome. Programs are also often called _scripts_. Every time you turn on the Raspberry Pi and it boots into Raspbian, you will notice that the screen is full of text. This is the Raspbian boot (start-up) sequence and it is a script (or program) of instructions that it executes to get the Raspberry Pi ready for you to use. By editing this script you can change the way in which Raspbian starts-up. That really is expert stuff!

Being able to program is a very worthwhile skill. Remember, one of the reasons that the Raspberry Pi was born was to encourage a return to programming. Programmers were becoming scarce and nowadays being able to program is a very marketable professional skill. That aside, as a recreational pastime programming is rewarding and provides an understanding of the way computers work that will stand anyone in good stead, and that skill in a future where the microchip will continue to dominate is no bad thing.

The other big plus about learning a programming language is that once you have learnt one language it becomes much easier to learn a second and a third and so on. Many of the basic fundamentals of programming are readily transferable from one language to another — it is just understanding how they are implemented that you have to master.

As well as new languages being released, existing languages are often being updated to offer more and better features. To keep a track of the progressive improvements,the release of each language is usually allocated a number which is its version number, for example 'PROlanguage V1.2'. A new, minor update to PROlanguage might get a small revision number incremental from 1.2 to 1.25. A more comprehensive revision might see the version number go to 1.3, and a full overhaul might see the latest version become 2.0. Small increments in the version number often just denote some bug fixes and that programming errors were corrected. Bigger increments invariably mean significant new features.

Which Language?

There are literally hundreds of programming languages. In fact if you include all the different versions of any particular language (programming languages have different dialects just like the real talking world) then there are probably thousands, with new languages being added to the list on a daily basis. However, few of these ever become sufficiently popular that they are used by more than a few people, as they are developed for very specific purposes. A professional programmer may use dozens of languages in a career, so where does that leave you?

Among this vast array of programming languages there are a dozen or more languages that could be described as mainstream and that therefore have popular support amongst the general programming community. Several of these are also used to create new languages and write very sophisticated programs and even Operating Systems like Raspbian. This list includes some languages specifically developed with children in mind. These therefore have a strong educational bent.

The Raspbian distro on the Raspberry Pi comes with several languages ready for you to use from the start. There are numerous other languages that you can download and install, and others being developed for the Raspberry Pi with specific applications in mind. Here's a quick overview of some of these popular languages that you can pretty much use right away. We'll look at a few of these in a bit more detail in following chapters.

Bash

We have already examined Bash in quite some detail, so you are already aware of many of the commands it has. However, we have been using these one at a time. By combining them together and adding some additional structural commands we can create programs that can automate tasks.

Python

If there was one 'official' programming language for the Raspberry Pi then this would probably be it. You may recall from the earlier chapters that we tried some Python games such as Four-In-A-Row. According to python.org 'Python is a programming language that lets you work quickly and integrate systems more effectively.' Simplified, that means that it is easy to use and you can create meaningful programs quickly and with a minimum of effort, which is certainly the case. Python is available directly from the desktop environment as well as the command line. You might also be interested to know that Python is named after Monty Python's Flying Circus, the UK TV show that brought you Life of Brian and the Ministry of Funny Walks!

Scratch

Scratch is available directly from the Desktop. With Scratch you can very easily create stories, games, and animations. Because the programming environment you use to do this is very visual, it makes it a great way to introduce children to programming. In a few lines you can make a cartoon character walk around the screen simply by selecting items from a menu. You don't have to worry about getting the text perfect since everything is done by dragging and dropping program blocks to build your script. You don't need to remember any commands.

Scratch was originally created by the Lifelong Kindergarten Group at the MIT Media Lab in Boston, USA, with the object of helping young people to learn mathematical and computational concepts while having fun making things. There is a vast database of existing Scratch programs — according to scratch.mit.edu almost six million Scratch projects have been shared by people!

C

C is one of the most widely used programming languages of all time. Many languages that exist today have their origins in C and many languages have themselves been written in C. Indeed, Raspbian is largely written in C. C++ is a modern version of the original C language and includes many of the bells and whistles required for general purpose programming.

One of the great benefits of C is that most programs written in it can be transferred from one computer to another and will generally work with little modification. C is available from the command line on the Raspberry Pi.

HTML

HTML is language that the Internet uses to display web pages. Every time you go to a new page on the Internet, HTML is being used to display the images, video, text and links. It also does other smart stuff like defining where columns go and how wide margins are. So learning HTML means that you can create your own web pages!

As technology has advanced then new releases of HTML have appeared, for example to allow pages to be displayed on smart phones. The current version at the time of writing is HTML 5.

These four languages can provide you with a real understanding of what programming is all about. They are all available to use on the Raspberry Pi and we'll look at Python, Scratch and HTML in the coming chapters.

As I said earlier, they are only the tip of the iceberg and there are certainly other programming languages you should look at. Towards the end of this book when we delve into the inner workings of the Raspberry Pi we'll look at how to program in machine code — this is the language the ARM microprocessor actually uses to operate! In Chapter 29 we'll look at the RISC OS distro, and another language to consider here is BBC BASIC. Despite being over 30 years old it still offers an effective way to program in a RISC OS environment.

Interpreted and Compiled

Computer programming languages fall into two main types. Interpreted and compiled, and it is important to know the difference between the two. The Raspberry Pi at its most basic level uses a language called machine code. Whenever we run a command or a program on the Raspberry Pi it must be converted into machine code to work. This can be done when you run the program or before you run the program.

If the program language is an interpreted language then the conversion to machine code will be done by the program itself each and every time the program is run. It does this command by command, taking each program line, converting it, running the machine code and then getting the next line.

If the programming language is compiled then you as the programmer have an extra step to do before you can run the program. You must first pass the program or script through a compiler which converts the entire program into a machine code file. You then execute the machine code file to run the program.

The benefit of the compiled language over the interpreted language is that it runs faster and it does not have to be interpreted each time you run it. The advantage of an interpreted language over a compiled one is that you can run it right away (perhaps having just made a small change) without the need to compile it.

Bash, Python, Scratch and HTML are examples of interpreted languages, whilst C is an example of a compiled language.

Structured Programming

The majority of modern day programming languages such as Python and C are said to be structured programming languages. If you Google 'structured programming' you will find a lot of varied descriptions as to what it is. I like to think of it as an organised and modular method of programming that utilises inbuilt structures to minimise the overall size of the program. Here's a very simple example, consider this snippet of 'program code':

starthere

echo "This is a line of text"

wait 1 second

echo "This is a line of text"

wait 1 second

echo "This is a line of text"

wait 1 second

end

So, it should be fairly obvious what this program would do when run. A structure programming way to write this might look like this:

starthere

echo "This is a line of text"

wait 1 second

do three times

end

The second version is only a bit shorter but it is a little more elegant. Imagine that we wanted to do it 1000 times. The first method would be painful to program. Now imagine we wanted to change the wait to two seconds — that would require editing 1000 lines of code. Using the structured method we would only have to change one line of code. The second method uses a structure to control the number of times the program loops through the command. It also makes the program easier to read and quicker to write.

There are a number of control structures and associated programming items that are common to all structured languages. The main difference between languages is that they may use different commands. For example, 'stop', 'halt' or 'end' are all common program commands that do the same thing, although in any given language you must use exactly the right keyword. In the remaining part of this chapter I'll introduce some of these more common control structures so we can then concentrate on the program languages themselves when we come to the appropriate chapter.

Variables

In programming, a variable is a named value that can change, depending on conditions or on information passed to the program. Variables can be numeric or string: numeric variables contain numbers and string variables contain text. The value held in a numeric variable can be manipulated arithmetically, whilst the text in a string can be extended or shortened, or part of it can be extracted or even replaced with another string!

Variables are generally given symbolic names by the programmer to identify what they stand for and string variables normally have a dollar symbol '$' appended to them to indicate that they are strings. It is normal (though not essential) to initialise variables to their starting values at the beginning of a program. For example:

counter = 0

intro$="Hello and welcome"

Here the variable 'counter' holds the value 0. A legitimate operation on this variable would be:

counter = counter + 1

Here the value of 'counter' would be taken (set to zero above), have one added to it and the result placed back into 'counter'. So in the first instance 'counter' would now hold '1'. If we executed it again it would hold '2' and so forth. Consider this:

a = 23

b = 7

result = a + b

The numeric variable 'result' would be set to 30 after the program was executed.

You can perform almost any mathematical operation on a numeric variable, plus numerous logical operations defined by the programming language in question.

With regards to string variables, consider the following:

intro$="Hello and welcome "

intro$=intro$+"friends!"

Now intro$ would hold the text 'Hello and welcome friends!'

Note that with string variables we have put the text to be allocated to the variable in quotes. Some languages do not require the use of quotes. Some languages require you to define or declare each type of variable before you can use it, as well as say what it will hold. This might take a form similar to this:

define counter numeric

define intro$ string

A _constant_ is the name given to a variable whose value cannot be changed. For example:

define pi constant

pi=3.14

Numeric variables play a very important role in structured programming because they provide you with the means to control loop structures, which means controlling the number of times things are repeated. String variables are often used for getting information from the user by reading what is typed at the keyboard, as well as displaying information.

Loops

A loop is a fundamental programming concept that is commonly used in writing programs. It is a sequence of instructions that is repeated a set number of times or until a certain condition is reached. Typically this condition might be a variable reaching a pre-determined value. Consider our structured code snippet from earlier:

starthere

echo "This is a line of text"

wait 1 second

do three times

end

Here we have implemented a loop that re-iterates three times. However, the program fails in reality as it does not have a variable defined to control it thus:

starthere

counter = 0

do loop

counter = counter + 1

echo "This is a line of text"

wait 1 second

until counter = 3

end

In this snippet the loop structure is indented to identify it, and this is common programming practice. It is often done purely to aid readability of the code. Some program like Python require indents otherwise they will not work. Here the loop executes until counter=3.

Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is checked, such as whether a counter has reached a prescribed number. If it hasn't, the next instruction in the sequence is an instruction to return to the first instruction and repeat the sequence. If the condition has been reached, the instruction 'falls through' to the next sequential instruction outside the loop.

Loops are important but they can also be a source of frustration. Consider what happens if the condition to exit the loop is never reached. In this case the loop would become an infinite loop and would never end. This can happen due to a programming error, and if this happens you would have to press the <ESCAPE> or <CTRL>-C key to regain control of the machine, or more seriously you might have to turn the power off and re-boot. This mistake is easy to make. The following snippet would result in an infinite loop. Can you tell why?

starthere

counter = 0

do loop

echo "This is a line of text"

wait 1 second

until counter = 3

end

The loop would continue — 'counter' never equals three as the incrementing line (counter=counter+1) is missing!

Another type of loop structure is the 'for...next' loop. It is essentially the same as 'do loop...until' and takes this form:

starthere

for counter=1 to 10

echo "current value is: " counter

next counter

end

Here you can see that the variable is defined in the 'for...next' loop itself and thus the code is smaller or tighter. However, there is no significant difference in operation although programmers will generally use the 'for...next' loop when they know when they write the program how many times a loop is going to be executed. The for..next loop automatically increments itself, so there is no need to include a line to do this.

A third common structure is the 'while...do while' loop. This tests for a condition before a set of statements are executed. For example:

counter=0

while counter<4

echo "This is a line of text"

counter=counter+1

do while

This loop will execute while 'counter' is less than four. It will terminate as soon as the counter is 4 or above. So if 'counter' was never 4 but was say 6 it would terminate as the condition was met (true).

Decisions

Conditional statements allow you to execute different parts of a program dependent on the result of a test. One of the most common forms of this is the 'if...then...else' structure. This relies on the testing of a variable and would be coded along these lines:

if counter =1 then

echo "counter is set to 1"

else

echo "counter is not 1"

Some languages require you to mark the end of the conditional test sequence by using 'end if' on the final line. Other languages allow you to use an 'elseif' test so that you can test for additional options thus:

if counter =1 then

echo "counter is set to 1"

elseif counter = 2 then

echo "counter is set to 2"

elseif counter = 3 then

echo "counter is set to 3"

endif

In the example above if 'counter' =1 then the text 'counter is set to 1' will be printed to the screen and everything else will be ignored as only one of the conditions in this program can be met.

Although we have only used one line of program code after each test statement there is no limit to the amount of the code you can use.

Nested Loops

A nested loop is a loop within a loop. Look at this example:

for outer=1 to 5

Echo "outer is: " outer

for inner=1 to 2

echo "inner is: " inner

next inner

next outer

The first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.

Languages often have a restriction on the number of loops you can have nested in this way and used correctly that can be a very useful tool, especially when manipulating large amounts of data. However, you must ensure that your loops are nested correctly and that you exit each loop in turn, and in sequence.

You can nest different types of loops inside one another — a nested selection does not have to use the same loop structure.

Functions

Functions are 'self contained' segments of code that accomplish a specific task and may have data passed to them and may also return a result. Functions are normally written to do tasks that you will require over and over again. They are assigned a unique name and can be called from within the program whenever needed. The function's name is used to call it from within a program.

We might create a function called 'FNmultiply' that expects to have two values passed to it. After multiplying them together the function will return the result to the calling program. (This is a trivial example as the code to do this is so small that the overhead of creating a function would not be worthwhile, but it illustrates the point.) The function might be defined thus:

def FNmultiply (a,b)

c=a*b

return c

We could then call it by name:

FNmultiply (4,5)

Here we are passing 4 and 5 to it and we would expect a result returned, in this case, of 20.

Functions encapsulate a task by effectively combining many instructions into a single line of code. Most programming languages provide many built in functions that would otherwise require many steps to accomplish.

Functions have a number of really useful advantages:

  * They allow programs to be written as a bunch of steps which can be called as required.
  * They allow code to be reused by developing a function library.

Functions allow us to keep our variable name space clean as variables used within functions are defined as local and unique to that function.

By developing programs as a set of functions to be called you can test each part of the program as you go. As a means of developing a program in any language, functions (and their variants that are called procedures) are perfectly suited to structured programming.

Debugging

When programs don't work as expected they are said to contain _bugs_. The process of finding these bugs and editing the program to work correctly is called _debugging_. A bug may be immediately apparent because the result is not what was expected or may only raise its head when a certain set of conditions are met. For example, you may want to add two numbers together to get a result, but instead of using the '+' sign you use the '' sign. This is a trivial example but it is still a bug that would need to be located and rectified.

You might have a loop that is due to count from 1 to 50, but at some point in the loop, the loop counter is set back to 0, so that 50 would never be reached. You have an endless loop and another bug.

Experience helps when it comes to debugging, but by using a structured programming technique you can narrow down where the error is, as in the two examples above, by examining the output. Bugs can be frustrating, but resolving and correcting them is also rewarding and part of the learning process.

Learning To Program

The following few chapters show you how to implement these control structures in these languages, in addition to showing you a number of additional interesting aspects of the language. If any particular language takes your fancy then you should definitely buy a book to read more about it. Note that language implementations do vary between Operating Systems and machines so it is best if you can obtain a book specific to the Raspberry Pi implementation.

If you can only purchase a generic book then remember that not everything has been tested and so if a language command doesn't work or creates an error then it may be because it isn't implemented on the Raspberry Pi version (or it may be that you didn't implement it correctly!). If you source information on the Internet then also bear the above in mind and be prepared to search around.

Armed with a suitable reference then you need to do what I call 'try and apply'. Try the examples given and then adapt them for your own need. The other thing to do is to look at what other programmers have done and see how they have implemented a particular structure or problem solution — then apply it to what you want to achieve.

GitHub

As you develop your programming you will find that a lot of programmers — especially Raspberry Pi programmers — seem to live at a place called GitHub! GitHub offers many things, but for the Raspberry Pi orientated it provides programmers with a place to host their on-going projects. Many if not all of these projects are available for you to download and use. They are not necessary bug free but using them provides the programmer with potentially invaluable feedback from end users. So a visit to:

https://github.com/

should be high on the agenda.

You can sign up for an account if you wish, but even without this there's nothing to stop you exploring and downloading either by cloning the application or by downloading a compressed ZIP file. Just head into GitHub and search 'Raspberry Pi' — there's plenty to see!
18: Bash Scripts

You should now be confident enough to use Bash commands. So for our first trip into writing programs let's look at how we can combine some of these commands into a script to do things.

Although we have examined quite a few Bash commands in our run up to this section, we have really only touched the tip of the proverbial iceberg when it comes to the full range of commands available. In this section we'll introduce some more, especially those associated with some of the techniques we examined in the last chapter.

Bash programs are more commonly referred to as scripts and they are best suited for administrative tasks. This includes making changes to your existing setup or altering the configuration of aspects of your system, or maybe just deleting unwanted files. In this respect they can be quite invaluable but you must bear in mind that Bash does not contain the bells and whistles of a programming language such as Python.

One of the most useful reasons to create a script — even if you do not intend to progress with Bash programming — is to create alias definition files. You can create your definition as an executable script and run it each time you start Raspbian so that your definitions are ready to use every time.

Essentials

To write a Bash script you will need to utilise a text editor of your choice. You can create your Bash scripts from the command line or in a Desktop environment. In the case of the latter you will need to have a Terminal window open to test the script.

Let's start by writing a very simple script where we can look at the fundamentals that will be common to all your future scripts. You may want to create a special directory to keep your Bash scripts in. I have a directory called 'Scripts'. Here are three lines of our first script:

#!/bin/bash

# Simple Bash script

echo "Hello Raspberry Pi World!"

Save this file as 'hello.sh'. The .sh is the file extension we will use to denote a shell script. Let's look at the three lines in turn:

#!/bin/bash

This is the location of Bash and by including this line at the very start we are telling the Shell what program to use to execute the file. This is often referred to as a _hashbang_ or _shebang_. The '#!' mark is a special case as it indicates that the rest of the line is an interpreter directive. In this case it identifies this as a Bash script and so will ask Bash to interpret the file and run as appropriate.

# Simple Bash script

'#' on its own followed by a space indicates the rest of the line is a comment and is to be ignored. The space is important as is the lack of one in the shebang above. Ignoring these intricacies can cause problems so it is best to be wise to them!

echo "Hello Raspberry Pi World!"

The 'echo' command is used to print the text that follows to the screen.

We have one more step to do to make the file an executable one (as it stands it will not work as the file is only recognised as a text file despite the use of the '.sh' file type.

Enter the following command at the command line:

sudo chmod 755 hello.sh

As we learnt earlier the 'chmod' command can be used to change the permissions of a file, and in this case we are making the file executable — the '755' does this.

At the command line type the following:

./hello

The './' means execute (run) the named file. You should get the following on the screen:

Hello Raspberry Pi World!

_Figure 18a. You can organise windows simply to make your Bash programming experience easy to manage._

If you define an alias within a script you can then use the alias in the script after the definition has been made.

Bash Variables

To see how variables work in Bash you can experiment at the command line rather than writing individual scripts. At the prompt type:

variable1=123

This defines a variable and sets its value to 123. Type:

echo variable1

The output will not be what you expected — the 'echo' command takes what you have typed literally so it prints:

variable1

To get the value of the variable called 'variable1' we have to signify it as a variable by using the dollar (string) operator thus:

echo $variable1

So 123 is printed. You can assign text strings in a similar fashion:

hello="Hello Raspberry Pi World!"

echo $hello

Unlike many other programming languages, Bash does not segregate its variables by type. Bash variables are always character strings.

You must include the spaces in any text that contains spaces inside the quotes when assigning it to a Bash variable. If you don't then Bash will try and interpret the text after the space as a command.

You can define variables on a single line thus:

var1=1 var2=2 var3=3

Note in all the above definitions that there should be no spaces either side of the '=' sign.

Here's an interesting one:

text= "1 2 3 4 5"

echo $text

Note that the printed output does not contain the additional spaces inserted above between the 4 and 5. The formatting reverts to single spaces between each number so that the output is:

1 2 3 4 5

To print to the screen with the same formatting you need to enclose the variable in double quotes thus:

echo "$text"

If you wanted to literally print $text to the screen and not be interpreted as a variable you would encase it in single quotes:

echo '$text'

You can use the 'let' command to assign a variable with a calculated value thus:

let value1=3*5

This would assign 15 to $value1. You can also assign other variable values to a variable thus:

num1=$value1

Here $num1 would now hold 15.

On your keyboard you should have a single back quote character thus:

`

Note this is not the single quote character ' but the one that normally shares the '~' key. The back quote can be used to make the item being assigned to a variable the output of a Bash command. For example, write the output of the command 'ls –l' to a variable, using back quotes enter:

list=`ls -l`

To see the formatted output of the listing use:

echo "$list"

If you have no back quote key, then another way is to use the $ operator with brackets thus:

list=$(ls -1)

This is probably a clearer method but it is not supported by all versions of Bash, so bear that in mind if you are writing scripts to use on a non-Raspberry Pi system.

Although Bash variables are held as text or character strings, then depending on context, Bash permits arithmetic operations and comparisons on variables. The determining factor is whether the value of a variable contains only digits. Here are some examples:

num1=1234

let "num1 +=1"

echo $num1

This would result in the value 1235 being printed. So 1 has been added to the value placed in the variable 'num1'.

If you try and add a number to a string then the string will be replaced by the number. If you tried a different arithmetic operation such as multiplying by five then the string would be reset to zero.

For Loops

Bash supports 'for' loops and these take the format:

for [argument] in [list]

do

<commands>

done

An example will make this a lot clearer. Create a script called 'loop1.sh' thus:

#!/bin/bash

# loop1.sh

# Simple loop demo

for distro in Raspbian RISCOS ArchLinux Raspbmc

do

echo $distro

done

Note the use of a space to separate each item. Remember to make the file executable using:

sudo chmod 755 loop1.sh

And then execute the script with:

./loop1.sh

The output will be:

Raspbian

RISCOS

ArchLinux

Raspbmc

If you wanted the distros printed all on the same line then enclose them in double quotes thus:

for distro in "Raspbian RISCOS ArchLinux Raspbmc"

In the first instance the loop will have executed four times to read each item in the list. In the second instance it would only be executed once as it is seen as a simple text string.

It is possible to include multiple items in a list by including each separate one in double quotes. For instance, suppose we wanted to include the version number of each distro, one way of doing this would be to change the line as follows (all one line):

for distro in "Raspbian June14" "RISCOS RC12a" "ArchLinux June14" "Raspbmc June14"

Executing with this line in the script would produce:

Raspbian June14

RISCOS RC12a

ArchLinux June14

Raspbmc June14

You can use these types of loops to operate on files. Try this script (loop2.sh):

#!/bin/bash

# loop2.sh

# Simple loop to display files

for file in *

do

ls -l "$file"

done

The asterisk (*) is used as a wildcard to mean any file in the directory, and as no directory is specified then the current working directory is utilised. You can specify a particular directory if you wish by including the path thus:

for file in /bin/*

This would catalogue the files in the bin directory of root.

You can search for specific files, for example ones that begin with 'loop' by using it as part of the wildcard definition, adjusting the line of script as follows:

for file in [loop]*

If you have the files 'loop1.sh' and 'loop2.sh' in the current directory then only these files will be listed.

A more practical use of this sort of script might be to remove certain files from a directory. For example, when developing scripts or programs I often prefix them with 'W' to signify that they are a work in progress. A script to remove all files starting with 'W' would look like this:

#!/bin/bash

# loop3.sh

# Simple loop to remove WIP files

for file in [W]*

do

rm -f "$file"

echo "Removed: \"$file\""

done

Note the use of a back slash character '\' here. The ' \" ' character allows the use of the ' " ' following it to be included in the string and therefore it does not terminate the string itself.

More loops

Condition testing 'while' and 'until' loops is also a feature of Bash. The command structure of a 'while' loop looks like this:

while [test]

do

<commands>

done

The following example (loop4.sh) will execute the loop until a pre-determined value is reached. Be careful to ensure that a space exists after the '[' and before the ' ]':

#!/bin/bash

# loop4.sh

# Simple while loop to count and test

start=0

end=10

while [ "$start" -lt "$end" ]

do

let "start +=1"

echo "Current count is: \"$start\""

done

The while line contains 'lt'. This is a conditional that tests for 'less than'. We'll look at some more of these conditional tests in due course as they are very useful.

An 'until' loop also exists and has a similar structure. The following script (loop5.sh) will wait until the 'x' key is pressed on the keyboard:

#!/bin/bash

# loop5.sh

# until loop which waits for x to be pressed

exit="x"

until [ "$key" = "$exit" ]

do

echo "waiting for x"

read key

done

This loop scans the keyboard using the 'read' command and places the key typed (you must press <ENTER> to complete the command) and it waits until you press 'x' to exit.

The big difference in an 'until' loop is that the condition is tested before the loop is entered. Thus if $key was set to 'x' before the test, the loop itself would never be entered.

Test Conditions

Decision making in Bash scripts is performed using the 'if...then...else' construct. A conditional test in its simplest form can be performed thus:

#!/bin/bash

# test1.sh

# Simple if...then construct test

value=10

if [ "$value" =10 ]

then

echo "Value is 10"

fi

Note that the end of the code is marked by the 'fi' statement, which is 'if' backwards, rather than an 'endif' statement. In the snippet above the 'echo' statement will only be displayed if the value in the variable value is 10. Just a word on the 'if' line. Spaces are important so ensure they are included as follows:

if<SPACE>[<SPACE>"$value"<SPACE>=<SPACE>10<SPACE>]

An 'else' option can be inserted:

#!/bin/bash

# test2.sh

# Using else

value=20

if [ "$value" =10 ]

then

echo "Value is 10"

else

echo "Value is not 10"

fi

Testing multiple conditions can be done by using an additional conditional option that is provided: 'elif...then' as in this example:

#!/bin/bash

# test3.sh

# Using elif..then

value=30

if [ "$value" =10 ]

then

echo "Value is 10"

elif [ "$value" =20 ]

then

echo "Value is 20"

elif [ "$value" =30 ]

then

echo "Value is 30"

else

echo "Value is neither 10, 20 or 30"

fi

If you want to test whether several conditions exist then you can nest 'if...else...fi' constructs providing that you ensure that each 'if' is balanced by a terminating 'fi' before you come out of a nested stage. This makes it possible to test multiple conditions:

#!/bin/bash

# test4.sh

# test multiple conditions

value1=10

value2=20

if [ "$value1" =10 ]

then

if [ "$value2" =20 ]

then

echo "Values are 10 and 20"

else

echo "Failed"

fi

fi

Here the second 'if' condition will only get executed if the first 'if' test is true. So '$value1' must be equal to 10 otherwise the script will progress straight to the 'else' condition.

However, a more elegant method exists of performing several checks. If you want to test that several conditions exist use the '&&' operator. To test that at least one of the listed conditions exist use the '||' operator:

#!/bin/bash

# test5.sh

# Use of && to test multiple conditions

value1=10

value2=20

if [ "$value1" =10 ] && [ "$value2" = 20 ]

then

echo "Values are 10 and 20"

else

echo "Values are not 10 and 20."

fi

Using:

if [ "$value1" =10 ] || [ "$value2" = 20 ]

Only one of the tests in the above line has to be true for the line of code to continue. If '$value' was 30 then the result would still be true as '$value1' would return a positive result.

Figure 18b below defines the various conditional tests you can use when testing numerical values.

_Figure 18b. Numerical conditional test operators._

String Variables

Conditional tests on a string of text are different. Figure 18c plots the various tests with examples.

A few of these need clarification. The '=' operator to compare strings should not be confused with the use of '=' to assign a value to a variable (string or numeric), The '=' can be either an assignment or a test operator, depending on the context.

The '\<' and '\>\>' test to see if one string is greater than or less than the other. This is done at the ASCII level where the internal numeric representation of a string is utilised. For example if '$a' held 'A' and '$b' held 'B' then '$a' would be less than '$b' (A=65 and B=66 in ASCII). If '$a' held 'ABA' and '$b' held 'ABB' then '$a would be less that '$b'. Uppercase capital letters have lower values than their equivalent lower case letters, so 'A' is less than 'a'. You can find out more from the ASCII table in Appendix A.

_Figure 18c. ASCII string conditional test operators._

The null character is an interesting concept in that null is not the same as zero (0). If you examine the ASCII table in Appendix A you will see that 0 has the value 48 while null has the value 0. Null is literally nothing while 0 is a number. This can be tested with the 'z' option.

Bash also provides options for testing the existence or otherwise of files and directories. Figure 18d details some of these.

_Figure 18d. File conditional test operators._

The script below will look to see if a file exists. If no path is given then the current directory is used. If the file exists and is readable by the script it extracts its contents into the variable '$content', which is subsequently echoed to the screen. You should substitute a suitable name for a script you have if you do not have 'loop1.sh'.

#!/bin/bash

# file1.sh

# Read a file's contents

filename=loop1.sh

if [ -r "$filename" ]

then

content=$(cat "$filename")

echo "File exists, contents are:"

echo $content

else

echo "File does not exist."

fi

This example script begins to show what is possible with Bash scripts. The filename might not even be known at the time the script was written and could be extracted by reading the directory information.

Here's a small extension on the above that will cater for an instance where the file might exist but not be readable to the script. It also illustrates further how the 'if...then...else' construct works, as I will explain:

#!/bin/bash

# file2.sh

# Test a file is readable

filename=loop1.sh

if [ -r "$filename" ]

then

content=$(cat "$filename")

echo "File exists, contents are:"

echo $content

elif [ -f "$filename" ]

then

echo "File exists but not readable by script."

else

echo "File does not exist."

fi

As in the previous example, first we check whether the file is readable. If it is, we read it into a variable and display the output. If not, we check whether it actually exists using the 'f' option in the 'elif' statement. If that's true, we report that it exists but isn't readable. If the file doesn't exist, we report that too. The condition at 'elif' is only executed if the condition at 'if' is false. The commands belonging to 'else' are only executed if both conditions are false. It is important get your head around this testing process as if you get it wrong the results will not be as you might expect!

If you have a variable holding a string of information, you can perform operations on the variable to extract or replace specific information. The following script shows how you could make three strings from one by extracting sub-strings from it.

#!/bin/bash

# Extracting strings

# string1.sh

string1="Raspberry Pi Bash"

# 01234567890123456

string2=${string1:0:9}

string3=${string1:10:2}

string4=${string1:13:4}

echo $string2

echo $string3

echo $string4

echo $string1

When run, this program will print:

Raspberry

Pi

Bash

Raspberry Pi Bash

The initial starting string is held in '$string1'. Positions in this string are denoted starting at 0 and incrementing by one each position to the right. Therefore the word 'Raspberry' starts at position 0 and is nine characters long. The word 'Pi' starts at position 10 and is two characters long. Position 9 is a space. Finally the word 'Bash' starts at position 13 and is four characters long. These positions and lengths are reflected in the script above. Thus the line:

string3=${string1:10:2}

is saying: copy the two characters from position 10 into '$string3'. The original string ($string1) is not changed by this operation.

If you want to know the length of a string such as 'string1' above you can use:

length=${#string1}

In the above example this would return 17, remembering that numbering starts at 0.

Bash provides an extensive range of string operators and we'll look at another more practical use of them shortly.

Double Brackets

The use of double square brackets in preference to single square brackets allows for more sophisticated tests to be performed. Examine the following script:

#!/bin/bash

# Use of [[...]]

# string2.sh

string="Hello World"

if [[ $string == *World ]]

then

echo "Yes, it exists"

fi

The double-bracket syntax features something called _shell globbing_. Here, the asterisk, '*' expands to mean anything (you may recall we saw this wildcard usage earlier in this chapter). Therefore if '$string' contains 'World' at the end of it it will return 'true' regardless of what comes before it. Note also the use of '==' in preference to '=' to mean equal.

If you weren't sure if 'World' started with a capital or lower case 'w' you could use the following syntax:

if [[ $string == *[wW]orld ]]

An asterisk can be used on each side of the test as well:

if [[ $string == *[wW]orld* ]]

Here the result is true if either 'World' or 'world' exists anywhere in '$string'.

When using this process with filenames beware, because the double brackets do not expand filenames. So using a line such as:

if [[ -a == loop*.sh ]]

Looking for any script files starting with the word 'loop' will always return 'false' even if a file or files exist. This is because the command is taken literally so it will only return 'true' if the file 'loop*.sh' exists!

Functions

Bash supports functions and the use of local variables within them. Passing parameters into functions is done in the same way that you would pass them into scripts, thereby using the variables '$1', '$2' etc. Declaring a function in Bash is just a matter of writing:

function <name>()

{

# code here

}

After the function 'name' the code you want to use is contained within curly brackets — '{}'.You can then call the function simply by using its name. Functions do not have to be defined in any special order. The following example multiplies two numbers together and displays the result. The example also demonstrates how you can define a local variable to be used within that function alone:

#!/bin/bash

# demonstration of a function

# func1.sh

function multiply() {

local a=$1

local b=$2

return=$(($a * $b))

}

#

multiply 4 5

echo $return

exit

One of the major differences with Bash functions is that you cannot use the function to return a value; you have to use a global variable to return the value as in the example above.

As a more practical example the following function is quite useful and will catalogue the files in a directory with a given extension. This function uses the combination of the 'find' command and 'ls' command to operate and will need a little investigation by you to fully understand how it is working!

#!/bin/bash

# List file specified file extension

# func2.sh

function file-ext()

{

find . -type f -iname '*.'${1}'' -exec ls -l {} \; ;

}

# call function and pass file extension

file-ext sh

exit

When run this will use the function to list all files with the extension 'sh'.

Passing Parameters

Bash maintains its own unique set of variables. These are called Shell variables, which it uses to hold information passed to it. As these Shell variables can be used inside scripts it means you can pass information into your script through them! Figure 18e lists some of the Shell variables and their purpose.

_Figure 18e. Shell variables._

An example will make their use clear. Enter the following script and save it (as 'pass1.sh' for example).

#!/bin/bash

# Passing values

# pass1.sh

if [ "$1" =10 ] && [ "$2" = 20 ]

then

echo "10 an 20 were passed"

echo "The script name is: " $0

else

echo "Values passed not correct"

fi

echo "The number of parameters passed was: " $#

echo "Here are the parameters you passed: " $@

exit

Having saved the script execute it thus:

./pass1 10 20

Here parameters are passed to the command line with the filename execution. Note that there is a single space between each parameter. The script above illustrates how some of the variables can be used. Numbers are passed in the above example, but it could be text or filenames or directory paths. When the filename of the script is printed it will include the './' command to run the file. This could be stripped using the appropriate string operators. This example will do this for any length filename:

#!/bin/bash

# Extract a file name from $0

# pass2.sh

length=${#0}

filename=${0:2:length}

echo $length

echo $filename

Note that this assumes you are running the script and that there is no path involved as part of the filename. If there was, you would need to look at the full filename to see if it contained a path (look for '\' characters for example and then move from the end of the file until you find the ' \' which would mark its start). You can use negative values enclosed in brackets thus:

echo $(filename: (-10)}

This would print the last 10 characters in the filename.

Exiting Scripts

In all the previous examples we have not terminated any of the scripts correctly. Although they work they should all have 'exit' as the last command in the file — I'll show you why below. Just as all files start with the line:

#!/bin/bash

They should end with

exit

Every script returns an exit status (sometimes referred to as a return status or exit code). A successful script returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. This is a number in the range 1-255 which could be used to identify the nature of the error. When an 'exit' command is not included at the end of a script then Bash assumes that the exit status of the script is good and no error occurred. The '$?' operator can be used to print the error code. Try this at the command line prompt:

echo hello

echo $?

A 0 will be printed. Now try this:

test

echo $?

You will get a non-zero value, perhaps a 1 indicating an error.

In a script you can specify the error number after exit. Thus if you were expecting a number instead of a letter to be entered you could abort the program:

exit 85

Here the 85 would have some significance to you or the programmer. You would likely issue an error message from the program regardless but the number could be useful for debugging purposes.

Paths

When you type in the name of a command or a file to execute then Bash will typically look in the current working directory for the name of the command. If it cannot find it there then it will look in something called the 'path'. The path is a list of directories where Bash will look to find the command or file just run. If it doesn't find it there it will generate an error.

You can see the list of directories with the following command:

echo $PATH

This will return a colon separated list of directories that will be searched if a specific path name is not given when a command is attempted.

You can add directories to your path with the following command, where <directory> is the name of the directory you want to add:

PATH=$PATH:<directory>

This will be lost on a reset though, so to make it a permanent inclusion use:

export PATH=$PATH:<directory>

If you were placing your executable scripts in the Script directory you could add it to the PATH thus:

PATH=$PATH:/home/pi/Scripts

Now you could execute any script from anywhere in the directory structure as long as it was placed in the Scripts directory. Note that in this case you can just type the script name, and you do not require the './' at the start, thus:

hello.sh

Most modern Linux distributions encourage a practice in which each user has a specific directory for the programs they use. This directory is called 'bin' and is a subdirectory of your home directory. Create it with:

mkdir bin

And then add it permanently to the PATH:

export PATH=$PATH:/home/pi/bin

Move your executable script into the bin directory and it is available from anywhere within the directory structure.

Camera Auto Number and Date

If you are using the Raspberry Pi Camera Module you can create a Bash script that will make a simple command to take a photo to your requirements and then save the file using the date as part of its filename. This allows you to know exactly when your picture was taken and also the order of the images.

To create the script, open up your text editor of choice and add the following lines:

# Camera snapper with timestamp

#!/bin/bash

DATE=$(date +"%Y-%m-%d_%H%M%S")

raspistill -o /home/pi/Picture/$DATE.jpg

As you can see the script itself only has two lines. The first takes the current date and and time and writes it to a variable called DATE. The lines use the 'date' command and the items within the quotes are the format of the date in years, month, days and then time, all separated by a ''. The capital Y is used to signify a four figure year.

The second lines use the variable as a filename to save a .jpg file. Note that this example uses a pathname that expects to find a directory called 'Pictures' to save the file in.

You can save this file with the name 'snap' and then make it executable. Execute the file with:

./snap

A typical filename will look like this:

2014-12-01_1225.jpg

indicating that the file was saved at 1225 on 1st December 2014.

In this example a default image is taken, but you could create several instances of the file to take different format pictures — eg wide or narrow — with each command containing the desired settings as part of the 'raspistill' command.

Executing at Login

Now you are writing scripts and generally know your way around Bash, you might like to start adding your own functionality to Bash by having your own scripts executed at startup. This might be something as simple as defining your own alias commands, or perhaps much more sophisticated, like configuring your working environment and booting straight to an installed package. The options are endless.

Your Pi directory contains a hidden file called '.bashrc'. This is executed when you logon, so you can add your own files into this. Open and inspect it using a text editor.

It already contains a lot of configuration information and most of this is commented so you can see what is happening. You may like to try editing some of this (in which case exit and create a backup of this file — just in case...). You will see that this file has some of the alias definitions we discussed earlier and some more that are not action as they are behind #'s and therefore treated as comments. You can remove the '#' from the start of the line and re-save the file so that they are also defined at 'login'.

If you have a script to be executed then you can add its name to the base of this file. For example if your file was called 'setup001.sh' then you could add:

./setup001.sh

at the end of the '.bashrc' file and could then save the updated file.

I keep my scripts in the Scripts directory so the actual '.bashrc' entry would be:

./Scripts/setup001.sh

Of course you could add Scripts to PATH as described earlier.

Remember also to make the script file executable with:

sudo chmod 755 /Scripts/setup001.sh

This .bashrc file is always executed when you login and so 'setup001.sh' will be executed each time you login.

There are other options as well; for example you can choose to make a file execute each time you boot up — ie, before you reach the login point and these are all things you can investigate further as you become even more advanced in your understanding of Bash and the startup process for Raspbian on the Raspberry Pi!
19: Python

Python is regarded as the unofficial official programming language of the Raspberry Pi. Getting to grips with it is easy and fun to do and what's more you'll have a rewarding experience right from the off!

There are many elements that need to combine together to create a perfect language and many of these are right there in Python. As a programming language its key attribute is that it is flexible. It is flexible in the manner that you can use it to create desktop applications, games or web related applications. It is also transportable: as Python exists on a variety of computer platforms then you can take programs written elsewhere and run them on your Raspberry Pi (and vice versa).

There is also a very active Python community and at python.org you will find a plethora of resources. And, as we saw early on, there are plenty of example programs already available on your Raspberry Pi. In this chapter we'll look at the essentials that you need to know to get your programming going, and we'll also delve into some of the Python programs that are supplied with Raspbian and see how we can adapt and edit these to achieve a different outcome, so that you become familiar with the Python environment.

At the time of writing there are two major versions of Python available on the Raspberry Pi — version 2.7 and version 3. For the purpose of this book we'll be using version 2.7, simply known as Python 2.7. If you get bitten by Python (!) you can then look at the differences and decide if you want to move to Python 3. As always the choice is yours!

IDLE Person

The 'Programming Menu' contains options for 'Python 2' and 'Python 3' (in pre 24 December 2014 releases of Raspbian these were actaully called 'IDLE' and 'IDLE 3' respectively). Select Python 2 and double-click it. The response should be the Python Shell window opening as illustrated in Figure 19a.

_Figure 19a. The Python Shell window._

You will see that this window contains a number of menus across the top. If you click on each choice you'll get a feel for what they contain. Some items will be very familiar; others less so. You will also see a flashing cursor ('|') after the '>>>' prompt.

IDLE stands for Integrated Development Environment (with the 'L' added on for effect) and signifies that we are in a development environment that can be used to create and edit programs and test them as well. This means that you can work interactively at the prompt and treat it as a command line. Try this:

print "Raspberry Pi"

Notice the use of colour. The command 'print' is in yellow, the text enclosed in quotes is green and the output is in blue. This is very easy on the eye. Also the command is case sensitive — like Bash — so all commands are in lowercase letters. Text to be displayed must always be enclosed in double quotes, and (as in all programming) numbers and calculations must be performed using the values and signs correctly thus:

print 1 + 2

print 5*4

One thing to note when you are doing calculations is that if you want the result to be to the nearest decimal you must use the decimal point in your initial command:

print 10/3.0

Would give 3.3333333.

If you entered:

print 10/3

You would get 3 as the result.

In cases where the decimal component is several places long you can use the 'round' operator to truncate it to the desired length, thus to round to two decimal places you use:

print round (10/2.0,2)

to give:

3.33

When working in _interactive mode_ it is not absolutely necessary to use the 'print' command as Python takes the context of use into account, so typing:

round (10/2.0,2)

works just as well.

One final thing about the Python Shell is that it does not contain a history feature like the Bash Shell. If you have become a regular user of Bash you may find this mildly annoying! That said, if you place the cursor at the end of a command line you want to repeat — press <ENTER> and that line will be copied down to be actual cursor position. You can edit the line , if you wish, or press <ENTER> to execute it again.

Py Scripts

Python programs are called 'scripts' and to create a script we can use IDLE's inbuilt text editor. To create a new script select 'New Window' from the File menu (File>>New Window). At first sight this looks like the Python Shell, but the window is untitled and also does not contain the Python command line prompt. Click inside the window and enter the following two lines:

# Simple Python script

print "Hello Raspberry Pi World"

The '#' is used to enable comments in a script and these are ignored by Python. Go to 'File>>Save' and enter a filename for your script:

hello

Python will automatically add the '.py' extension which is the file type it uses. The file will be saved in the current working directory which is 'Pi' unless you have changed it.

You can run the program simply by pressing the F5 key (or selecting 'Run>>Run Module'). When you do this the focus of Python will return to the Python Shell and you will see the resultant output from the program there.

If you open File Manager and look for the 'hello.py' file you will see that it has the cog icon signifying that it is executable. If you double-click on the file you will see that it doesn't execute and more likely opens in Leafpad. You can run the script from the command line by entering:

python hello.py

at the command line in a Terminal window.

Errors

Errors are displayed a bit differently in Python. When you are developing a script or working in interactive mode they are always displayed in the Python Shell.

When an error occurs, the interpreter prints an error message and a stack trace. A stack trace is a few lines of output that tell you where the error came from, what line it is in and the exact nature of the error. If you have a script open that created the error, the error will also be highlighted in the script window. That identifies exactly where it is and from the message you will usually be able to deduce what is wrong. As we'll see, formatting a Python program correctly is very important and this element is often a common error when you are getting to know the language.

Customising A Game

Back in the Python Shell you can use the File Menu to open some of the supplied Python programs to see what they look like. Select 'File>>Open' and then look for the 'python-games' directory. Double-click on the icon to open this and you will be presented with a list of '.py' files. One of these will be called 'fourinarow.py'. Click on this and then select the 'Open' button. This will open a script window showing the program we looked at in an early chapter. Figure 19b shows the start of the script as it should appear for you. If you scroll through it you will get a sense of its structure.

_Figure 19b. The fourinarow.py listing._

The first thing you may notice is how neat it looks. This is because Python uses indentation to organise its script structure. This is good practice in most languages, because it makes code more readable: in Python it's mandatory. Notice too how the use of colour makes everything easy on the eye and also helps you to pick out individual items in the script. You will almost certainly notice some of the structures that I introduced in the chapter on programming. This script may look long and complex but when you start to break it down into its individual components it becomes quite manageable.

If you go back to the top of the script and look at the first 30 lines or so you will see that a lot of the game parameters are defined here. There is nothing to stop you making changes and customising the game to suit your own needs. For example, by adjusting the 'DIFFICULTY' setting you can change how easy or hard the game is. By default, 'DIFFICULTY' is 2; change this to 1 and you get an easier game. By changing 'BOARDWIDTH' and 'BOARDHEIGHT' you can change the size of the game. You may have already identified these items as variables and there are comments alongside each of these.

If you are changing things to see their effects (and I would encourage you to do so as a way of getting used to using Python) then make sure you do so with a copy of the script and not the original. You can make a copy by using 'File>>Save As', using a new filename. You might want to set the board size to 4x4 to create a smaller game in the first instance. You can run the script by pressing F5.

Raspberry Invaders

Check out the Pi Store for 'Raspberry Invaders'. In fact this is 17 Python tutorials at the end of which you have a space invaders style game.

Variables

Python supports three main types of variables — integer, floating point and string. Examples of each of these respectively are:

value=10

pi = 3.14

name = "Raspberry Pi"

These can be displayed using the print command thus:

print value

print pi

print name

What you will notice here is that no special operators are required. For example, in Bash to print a variable you need to precede the variable name with '$', but this is not a requirement of Python.

You may recall from the 'Four In A Row' listing earlier that variables were all given names using capital letters. This is a useful technique in that it makes variables stand out from the rest of the script code; just remember that the Python program does not discriminate between character case in these instances, so the variable 'pi' and 'PI' are seen as one and the same.

Strings in Python can be defined by enclosing them in single or double quotes, so:

name='Raspberry Pi'

is equally acceptable. That said, I would recommend that you stick with the double quotes; this way you can include apostrophes in your strings.

Python makes it very easy to extract bits of any string by the use of character portions inside square brackets, where the two numeric values separated by a colon mark the start and finish positions in the string for the operation, thus:

print name[0:9]

This prints characters starting from the start (which is 0) to the ninth character, making up the word 'Raspberry'. An individual character can be printed by specifying its position, so:

print name[4]

This would display a 'b'.

You can print a string a number of times thus:

print name * 3

This would print 'Raspberry Pi' three times.

Python has a number of system variables and one of the most useful of these, especially when working in interactive mode is '_'. This is the underscore character. Python assigns the last printed value to this variable. So just typing '_' at the prompt will display the last item that was printed to the screen. This is useful if you are using Python as a desk calculator, for example, type '123' at the prompt and press <ENTER>. Now type: '32 + _' and '155' is printed.

You should always treat this variable as read only and never try to assign your own value to it.

Lists and Dictionaries

A feature of Python is the 'list'. Here you can assign a number of items to a named list and the items can be a mixture of variable types. The list is bound by open and closed square brackets and each list item is separated by a comma. For example enter the following to try examples that follow:

hardware = [ 'USB', 'PSU', 'Printer', 'Memory', 32 ]

Typing:

print hardware[2]

would display, 'Printer'. While,

print hardware [1:3]

would display the second and third elements:

['PSU', 'Printer']

Note here that you actually have to specify one increment higher than required and not the 1:2 you might expect — this is a 'feature' of Python!

Lists make great ways of storing information and extracting their contents to other variables. For example:

item1=hardware[3]

Would assign 'Memory' to the variable 'item1'. Lists can also have their contents updated or changed:

hardware[3]="Stick"

would replace the fourth item in the list with 'Stick' (actually fifth strictly speaking — but we start counting from zero!). Because of this lists are often created in scripts holding dummy information and then not updated with information until the script is in operation.

shortlist=[0,0,0]

shortlist[0]="one"

shortlist[1]="two"

shortlist[2]="three"

If you are not sure how many items are in a list you can use the 'len' operator (len for length) to find out:

strlen=len(shortlist)

This would return '3' in the above example.

You may have noticed that when you print more than one item from a list, Python puts single quotes around it regardless of whether you used double quotes or not.

Another thing you can do with lists is to sort them:

hardware.sort()

This would sort the hardware list alphabetically with any numbers in the list coming first followed by strings. You can do a reverse sort by using this option:

hardware.sort(reverse=True)

You can also use 'append', 'insert' and 'remove' functions to further manipulate lists. Here are a few examples:

hardware.append("Extra")

hardware.insert(4, "Fifth")

hardware.remove("PSU")

In the above examples the 'append' function has been used to add the string 'Extra' onto the end of the list, whilst the second example inserts the string 'Fifth' as the fifth item (remember numbering starts from zero), whilst 'remove' is used to remove the first item in the list that matches the string or value passed to the list.

You can also remove an item from a list by 'popping' it thus:

hardware.pop(1)

This would delete the second item in the list. You can use 'count' to count the number of times an item appears in a list and 'index' will return the offset of the first occurrence of an item into the list:

hardware.count(32)

hardware.index("Memory")

Dictionaries are similar to lists; however you use a key to extract information from them. The key is a unique name that identifies the information that is supplied with it. This way you can search a dictionary for a named item without having to know its position within the dictionary — and that is the fundamental difference between lists and directories. Here's an example:

number={'Alice':123, 'Ollie':987, 'Mel':456}

The dictionary is called 'number' and entries must always be in pairs (called items) of keys and their corresponding values. Here Alice is the key (first and in single quotes) and 123 is the value. Note the whole dictionary definition is enclosed in curly brackets this time. So in this dictionary Alice has the value 123. We can display that with:

print number['Alice']

Note that for print purposes we return to '[ ]' brackets. Again the value could have been assigned to a variable if desired.

A dictionary can be updated very simply. Add a new entry thus:

number=['Sarah']=567

Again note the use of square brackets here. Changing or updating an entry is just as straightforward:

number['Alice']=321

You can delete an entry using the 'del' instruction:

del number['Mel']

would delete the index and value for Mel.

Loops

Python supports not just a basic set of loop structures but also more complex arrangements for working on data structures like directories and lists.

Perhaps the most regularly used loop is the 'for' loop. Open a script window and enter the following:

# Simple for loop use

#loop1.py

for n in range(0,100):

print n

When you type the '(' Python will display a prompt which shows you the format and expected parameters of the command. It will look a bit like this:

range([start,] stop[, step]) ->list of integers]

Items in square brackets are optional and we'll dissect this prompt below.

On the final line ('print n') you must indent the line by pressing the <TAB> key. If you don't, the program will generate an error. Use only one <TAB> — any more are not allowed and will cause an error. Python is very particular about the way it is formatted. Before you run the code you will need to save it, so provide a suitable name ('loop1'). When the code runs it will restart the Python Shell and print the numbers '0' to '99' in the window.

In the 'for' statement the '1' represents the '[start]' value and the '100' represents the 'stop' value. Note also that there was no requirement to include a 'next' command as well because Python understands the context by the formatting.

Edit the 'for' line by adding a '5' thus:

for n in range(0,100,5):

This is now the step value. If you run the program you will see it prints 'n' in steps of 5 (0, 5, 10, 15, 20...). You can make a loop count down by reversing the start and stop values but you must supply a negative step increment:

for n in range(200,100,-1):

In the examples I have used 'n' as a variable to hold the current increment count.

You can use a 'for' loop to print items from a list:

# Print from a list

# loop2.py

distro=[ "Raspbian", "RISC OS", "Arch Linux"]

for n in distro:

print n

An alternative way to code this using the 'range' statement would be:

# Print from a list

# loop3.py

distro=[ "Raspbian", "RISC OS", "Arch Linux"]

for n in range(len(distro)):

print distro[n]

While loop

The 'while' loop works in a similar fashion and will execute while a certain condition remains true:

# Print with a while loop

# loop4.py

distro=[ "Raspbian", "RISC OS", "Arch Linux"]

n=0

while n<len(distro):

print distro(n)

n=n+1

If Tests

The 'if' statement provides us with a conditional test in Python scripts. The syntax of the command is in line with the 'for' command in that the 'then' is implied. The following short script uses the construct to test for a certain value causing the program to exit. This also introduces a couple of new items which we'll discuss after looking at the script in operation:

# Using if and break

# test1.py

values=[1,2,3,4,5,6,7,8,9]

for n in values:

if n == 7:

print "Condition met"

break

else:

print n

When this code is run the values 1-6 are printed. When 7 is reached the 'if' test is met and so the message is printed and everything brought to a halt with the 'break' command. A point to note here as it might not be immediately apparent: The 'else' statement belongs to the 'for' loop and not the 'if' command.

The following script demonstrates the use of nested loops — here is one loop inside another to print out prime numbers between a certain range, which the user specifies at the keyboard via the script itself , which in turn uses the 'input' command to get the values:

# Nested loops

# nest1.py

start=input( "Enter start value: ")

end=input( "Enter end value: ")

for n in range(start,end):

for x in range(start,n):

if n % x == 0:

break

else:

print n, " is a prime number"

Run the script and enter a start and end value (you need to press the <ENTER> key after each number) and see the result. The '%' in the 'if' statement 'test' is the operator representing modulo. It tests to see if there is any remainder of the division — if there is none the condition is met and the end value has been met.

With a little adaptation the prime numbers could be placed in a list.

# Writing to a list

# list1.py

start=input( "Enter start value: ")

end=input( "Enter end value: ")

primes[]

for n in range(start,end):

for x in range(start,n):

if n % x == 0:

break

else:

print n, " is a prime number"

primes.append(n)

print "Number of primes found: ",len(primes)

print primes

Here an empty list called 'primes' is defined and the 'append' function is used to add items to the list. Note that there is a distinct lack of error checking in this program so ensure that your start number is 2 or higher and that the end value is higher than the start value. You may want to have a go at checking for these conditions and adapting the script to cope with them!

Functions

Functions are defined by name using the 'def' command and the name is followed by details of parameters. Here the function 'multiply' has been defined and it expects two arguments to be passed to it. You can return a value or values from the function using the 'return' command. The following script will multiply two values together using a function:

# Simple function call

# func1.py

def multiply (a,b):

c=a*b

return c

result=multiply(5,4)

print result

Functions in Python can be quite sophisticated. In the above example, the function required two items and expected them to be passed in order, although in the multiply case, the result would have been the same had 4,5 been passed. However, imagine that one was a string — order would be all-important. Python supports keyword argument functions which allow keywords to be used, thereby rendering order un-important. Here's an example:

# Simple keyword function call

# func2.py

def details (name,age):

print "Name: ", name

print "Age: ", age

return

#

details(age=35, name= "Fred")

If you write this script and then run it you will see that it works, even though we have passed the parameters to it in the reverse order to the definition in the function, which would have suggested that we have to pass name before age.

Modules

As you start to develop your programs you will want to start writing more and more complex material. One of the fundamentals of structured programming is that you write scripts in such a way that you can reuse them in other programs. In fact, this is what the Python community does and there is an extensive library of these _modules_ for you to take advantage of. We'll look at some shortly. You can create your own modules and you can import them into your own program.

Work through this example. It is relatively trivial but it illustrates the process perfectly. Create a new script, call it 'maths.py' and enter the following functions into it:

# Simple maths module

# maths.py

def multiply (a,b):

c=a*b

return c

def divide (a,b):

c=a/b

return c

def add (a,b):

c=a+b

return c

def sub (a,b):

c=a-b

return c

With the file saved go back to the Python Shell and at the prompt enter:

import maths

This makes the Python Shell aware of the module which you can now use in the following fashion:

maths.multiply(5,8)

Note you must use the module name as part of the call so that Python knows where the 'multiply' function can be found. Alternatively you can provide a local name for the call path and then use it to call the function:

sum=maths.add

sum(4,5)

>>>9

There are plenty of modules that others have created that are available for you to source and use yourself. For example, if games are your thing then you could use either the Pygame or the Pyglet libraries. If science is your thing, there's SciPy. Also, if you go back and look at the script for the Four-In-A-Row game you will see that in the very first few lines of code the script imports the 'pygame' module.

Next we'll look at a Python package that contains modules for use with the Raspberry Pi Camera Module.

PiCamera

Python provides a library you can use to control taking pictures using the Raspberry Pi Camera Module. It is available for use with both Python 2.7 and Python 3.2 or above, although the library to be installed is different in each case so you will need to install a specific one (or both) dependent on your needs.

The 'python-picamera' library (Python 2.7) is available to download and install using:

sudo apt-get update

sudo apt-get install python-picamera

Alternatively, the Python3 package is installed with

sudo apt-get

install python3-picamera

In this chapter we have been using Python 2.7 so you may want to continue on this route for the time being. After you have installed the 'python-picamera' library you must prepare it for use, whether directly from the Python Shell or as one of the first lines in the script you are writing. Working in interactive mode, from the Python Shell prompt type:

import picamera

After the command is executed the prompt will simply reappear without any Fanfare.

We now need to assign a name to the picamera library that will be our unique access to it. For reference this is known as a _class_ , and although we haven't looked at classes in this book, it doesn't preclude you from using them. Think of a class as a blueprint. It isn't something in itself, it simply describes how to make something. You can create lots of objects such as this from that blueprint. These blueprints are known as _instances_. You can choose to name the instance anything you wish, but most examples for the picamera use 'camera', although 'snap' would work just as well:

camera = picamera.PiCamera()

Now to gain access to the Camera Module you use the instance of camera to do so. For example to take a still picture use:

camera.capture('pypic.jpg')

Here a default image will be taken and saved as 'pypic.jpg' in the currently selected folder. Note there is no screen preview and no delays. The snap is snapped immediately!

The use of the dot and command following the name of the instance ('camera' in this example) is the way all commands are issued to picamera — this makes it very easy to construct commands once we know the full library command set.

The following script demonstrates a few of the commands available and how to use them:

import picamera

camera = picamera.PiCamera()

camera.start_preview()

raw_input( "Press Enter")

camera.capture('Pic01.jpg')

raw_input( "Press Enter")

camera.capture('Pic02.jpg')

camera.stop_preview()

The script will start sending camera video output to the screen. When you press <ENTER> on the keyboard it will take a picture. It will wait again for another press of <ENTER> and then take a second picture, at which point the output to the screen will stop. You will not see any messages placed on the screen as the camera feed overrides it.

A word of warning regarding the '.start_preview' command. Make sure your code can execute a 'stop_preview' command as the suggested <CTRL-D> key press to exit doesn't always work.

True and False

There are a number of options that can be used in conjunction with the 'camera' instance. Many of these have a True or False setting and there are some examples below. In these instances the case of the letters is important so it must be 'True' and not 'true'.

_Figure 19c. Picamera properties and default settings._

You can apply a horizontal and vertical flip to your image and this is done by changing the 'hflip' and 'vflip' configuration properties directly:

camera.hflip = True

camera.vflip = True

By default these properties are set to 'False'. Figure 19c lists some examples of properties available and what their default values are. As you will see, some properties take numbers and work in the same fashion as their Bash counterparts.

The following script can be adapted to show the effects of values on the different property configurations.

# Step through property values

import picamera

from time import sleep

camera = picamera.PiCamera()

camera.start_preview()

for value in range (100)

camera.brightness=value

sleep (0.5)

camera.stop_preview()

Here the brightness of the camera is increased in increments of one from 0 to 100 over a period of 50 seconds. You will see the image gradually fade up into view and then clear to white. This command uses the 'sleep' command to pause for half a second each loop, and this command is imported from the time library.

Video recording

You can record a segment of video using 'recording' options. This short segment will take five seconds of video and save it to a file called 'Pyvid.h264'.

# Take a lower res 5 second video

import picamera

camera.resolution=(640,480)

camera.start_recording('pyvid.h264')

camera.wait_recording(5)

camera.stop_recording()

This script sets a lower resolution for the video recording and then opens a file called 'Pyvid.h264' in the current directory to record a five second long clip. Note here that a camera instance method of 'wait' is being used. This also has the advantage of checking for errors during the recording, such as being out of memory for storage.

Shell Python

You can also run Python from the Shell so that you can use it interactively. It is not really suitable for developing scripts. As we'll see in Chapter 34 one good application is to use it to play with devices attached to the GPIO pins. To start the interactive shell type:

sudo python -i

This will present the standard Python prompt. Now you can enter Python commands. To exit back to the command line use:

quit()
20: Scratch

Scratch is an ideal introduction to programming for kids. There is very little typing and you can create graphical adventures just by dragging and dropping action bricks. With a little bit of work you can also include the whole family in the on-screen adventure!

Scratch is a great way to visually demonstrate structured programming. This is because each section of script you create is contained within a 'holding block structure' and you are therefore constrained to its confines. The clever thing is that this is the natural way of doing things in Scratch so for anyone learning, from the onset it becomes the natural thing to do. If you have jumped straight to this section in the book, I would first suggest that you read Chapter 17 — About Programming. If you do that, then there is absolutely nothing that will stop you excelling at Scratch.

Looking at the Raspberry Pi as a teaching tool, Scratch is a big selling point. My three year-old, whilst obviously not understanding structural programming, is certainly becoming comfortable with Scratch the Cat and is starting to take an interest in geometry even though he is only aware of the squares and triangles we get his sprite friends to move in. Familiarisation is all important here.

The Scratch Screen

Scratch is run from the 'Programming Menu&rsquo. The screen is bold, bright and colourful so it captures the attention in that respect and is divided into a number of clear sections. Figure 20a identifies these.

_Figure 20a. The Scratch window displayed on starting up._

There are four main areas. Working from left to right we have:

Block Palette:

This is where you get the building blocks for use in your program. At the top of this area is the grouping area which contains these headings: Motion, Looks, Sound, Pen, Control, Sensing, Operators and Variables. Clicking on any of these buttons will bring up the block palette for the grouping in question. You create a Scratch script by combining code blocks from these groups together.

Script Window:

This is the area where you create your scripts by dragging blocks into it from the Blocks Palette area. The Script Window contains three tabs towards the top: Scripts, Costumes and Sounds.

Sprite Area:

The bottom right hand corner of the screen. A sprite has many definitions but in Scratch terms it is a small graphical image that can be moved around the screen independently of the background. Sprites can be made from any image. Scratch the Cat is a sprite but we could also have other sprites, and these might include pictures of people from your family!

Stage:

This is where you will see the script acted out! In the top right hand corner of the Stage is a green flag and a red circle. You click the green flag to run a script and the red circle to stop the script. Above the Stage on the left and right there are two small sets of icons. The icons on the left allow you to control aspects of the script when it is running, as we'll see in an example shortly, and on the right these icons control how the windows are displayed. The two on the left of the group of three change the respective sizes of the Stage and Spirit Window and the one on the far right, which looks a bit like a TV, makes the Stage open full screen.

A Quick Example

There are four menus at the top of the screen: select 'File>>Open'. An 'Open Project' window will appear. Click on the 'Examples' button on the left. This will present a list in the main area. The last one is entitled 'Stories', double-click on this to reveal another list. In this list is 'BeeStory'. Click once on this and you will be able to see some notes about it in the window to the right, which tells you about this Scratch Script! Once you have read the notes click on the 'OK' button. It will take a few seconds but the BeeStory script will load and the Scratch window will look similar to that illustrated in Figure 20b.

_Figure 20b. The BeeStory script loaded and ready to run._

The Block Palette will not have changed much, if at all, but the BeeStory script will be loaded, sprites will populate the sprite area and the stage will contain the opening screen for the BeeStory which includes a few instructions for starting. Click on the green flag to set BeeStory in motion. You can see the arrow keys to move the bee around the screen. Press the <UP> arrow key and in the Script Window. You will see a block of code highlighted each time you do. This is the code to move the Bee up.

The first blue line in this code says:

Change y by 10

Click in the white box with 10 and edit it to read 50:

Change y by 50

Now press the <UP> arrow key and the movement is much greater.

You can try editing other components in the list in this way to see what happens.

At the top of the Block Palette click on the 'Costumes' and 'Sound' tabs and see what these contain. In the 'Costumes' tab the Bee is being alternated between two costumes as it flies — these relate to what it is doing on the Stage. Move the mouse pointer so it is over the Bee. Hold the left button down and drag the mouse — the Bee flies with you!

The small oblong to the top right of the 'Stage' window contains four icons. If you move the mouse pointer across these you will see their names pop up: Duplicate, Delete, Grow sprite, Shrink sprite. Click on 'Duplicate' and the pointer turns to the stamp shape. Move the stamp over the bee and left-click on the bee — a duplicate is created that you can move by dragging it across the screen. Click on Delete and the pointer turns to scissors. Click these on the icon that was duplicated and it is erased! The 'Grow sprite' and 'Shrink sprite' work in the same way — you can enlarge and shrink the scripts on screen!

If you click on a sprite in the Sprite Window you will see that the script relating to the sprite appears in the Script window. Click on the Rainbow sprite, drag this to the top of the Stage and release. The Rainbow will become part of the script.

There's plenty you can experiment with and there are a lot more examples for you to look at and try from the 'Open' menu. You will be asked If you want to save the current project; I would suggest you respond with the 'No' button while you are still experimenting.

Starting From...

Let's look at a sample that illustrates the fundamentals of Scratch programming.

Select 'File>>New' to create a new project. The screen will be clear of everything although Scratch the Cat will be present on the stage. Drag Scratch the Cat to the top left corner of the Stage.

Click on the 'Costumes' tab and you see there are two costumes, which are effectively Scratch the Cat sprites. Click on the 'Edit' button for costume 2. This will display the Paint Editor with Scratch the Cat in the main window. Across the top are buttons. Find the one labelled 'Flip horizontally' (second from right) and press it to flip the sprite. It should look like Figure 20c. Then click 'OK'.

_Figure 20c. Use the Paint Editor to flip Scratch the Cat._

The Block Palette should be in blue 'Motion' mode. Select the 'move 10 steps' block and drop it into the Script Window and edit the 10 to say 250. Right click on the block and select 'Duplicate' from the pop-up menu. Drop the block under the existing one and edit the value to say -250. Click on 'Looks' button at the top of the Block Palette to select the Looks blocks. The first one should be 'switch to costume 2'. Drag this to the Script window and insert it at the bottom. Duplicate this block and move it to the top, but from the 'blocks' drop-down, select 'costume 1'. Select the Control Palette options and the second one in the yellow list should be 'when Space key pressed'. Drag this to the top of the Script block. Your script should look like the one illustrated in Figure 20d.

Drag the 'Scratch the Cat' sprite in the Stage to the left hand edge. Now press the <SPACE> bar. You probably saw a flicker. It worked but it was too quick. From the Control Palette blocks select the 'wait 1 second;' block and drop it so it fits between the two blue blocks,. Now press <SPACE> and you should see the effect. Scratch the Cat has moved left 250 places, turned around (by swapping his costume) and moved back 250 places. Again all a bit quick. Let's look at a better method that allows us to get Scratch the Cat bouncing off the wall all by himself!

_Figure 20d. Scratch The Cat starting script._

If you make a mistake and need to remove a block you first need to detach the block in question from the rest of the script. To do this, click on the block you want to remove and drag the rest of the block down. Then move to the block below the one you want to remove and repeat the action. Your unwanted block should be on its own and you can left click on it and select 'delete'.

Bouncing Off the Wall

The wall in this case will be the edges of the screen. Scratch will walk from one side of the screen to the other, turn around and come back the other way. Delete the previous script by clicking on it and then holding down the right button and selecting 'Delete'. Enter the script shown in Figure 20e.

The 'repeat until' loop controls the movement here. You get the 'touching edge' segment from the Sensing Palette. Choose 'touching' and drag this onto the hole in the 'repeat until' structure block. From its touch down menu select 'edge'.

_Figure 20e. The new Scratch the Cat script._

Drag Scratch the Cat to the left of the screen and then press <SPACE>. Notice how smoothly Scratch the cat glides to the right of the screen. He then turns around to come back — but doesn't! The second loop never gets to work because he is touching the edge already and so the program just ends. So what we need to do is move him away from the edge. Figure 20f shows the updated listing, to make him come back. See if you can get to go back and fro a few times by adding your own code.

_Figure 20f. Scratch the Cat updated listing to move away from the edge._

The Sound Palette has a good selection of noises you might want to add into your script. The 'play sound' block has a drop-down that has 'cat' as a sound. (Chapter 24 has advice on how to get sound working if you are having problems.)

You might also look to replace the 'when space key pressed' control block for when <green flag> clicked', so that you can start your program by the normal method.

New Sprites

You are not limited to using Scratch the Cat. There are plenty of other sprites you can choose from. The 'Sprite' Window has three icons that allow you to edit or get other sprites. If you press the middle button ('Choose new sprite from file') you will be presented with a window called New Sprite. From here I clicked into the 'Costumes' folder and then scrolled down and clicked the 'football-run' icon. When you select an icon it will load into the Sprite window and will be named as 'SpriteX' where X is a number. Notice though that your script has gone! Double-click on Scratch the Cat. The script reappears!

Scripts are written and applied to individual sprites. Therefore you can have several scripts doing different things at one.

You can apply the same script to the second icon by duplicating it, or by selecting the script and then dragging it onto the icon in question in the Sprite Window. This re-creates the script for the second icon. You will need to change the costume for the sprite, and apply a second one if you flip the second sprite. Now when you select 'green flag' both icons will behave identically, although you could edit the 'move <value> steps' block to make it move at a faster or slower rate.

To add a bit more authenticity, in the Sprite Window click on the 'Stage' sprite and then select the 'Backgrounds' tab in the Stage area. Select 'Import' and from the open window select the 'Sports' folder and then the 'football-field' background. Figure 20g shows the 'Stage' screen now!

Create the same script for the footballer or whatever sprite you chose. But get the new sprite going in the opposite direction. Now when you click the green flag both sprites should move across the screen in opposite directions.

_Figure 20g. The football field sprites race stage!_

The Block Palette

Mastering the Block Palette is the key to being able to create effective Scratch programs. It contains all the tools you need to control your Scratch world. Of course it isn't the only thing, as long as you realise when you might need to create a new sprite, for example, for Scratch the Cat to come back the other way. It would be a good exercise to try and use several items from each of the palettes to understand how they work. Here's a quick look around the eight block palettes so you understand what each contains.

Motion Palette

The Motion Palette provides blocks that control the motion of the sprite they are attached to. They can make the sprite move in any direction; move a set number of points or move to a specific location or point.

The Stage is 480 points wide and 360 points high (a point here being an arbitrary unit of measurement). However, if you move your sprite to the absolute position x=0, y=0 it would be located at the centre of the screen. There is a 'go to x<value>, y<value>' block to do this. Moving to x=20, Y=20 would move diagonally up and right from the centre point. Moving x= –20, y= –20 would move diagonally left and down.

Control Palette

The Control Palette provides the wrappers for the loop and test structures supported by Scratch. These include 'repeat', 'forever', and 'if' as well as the 'start' and 'delay' keys. You can use a pre-determined value to repeat a loop a set number of times and every '...if' structure can have sensing controls attached to them — like a sprite reaching an edge.

The 'Broadcast' block allows messages to be sent throughout the script that can be used to activate other scripts and also allow scripts to talk to one another. In effect they can be used to activate other scripts when a particular action (event) has taken place, like a key press or a mouse movement.

Looks Palette

The Looks Palette allows you to change a sprite's costumes and also create graphics effects. In addition you can use the blocks in this palette to write text onto the screen. Using the 'change color effect by <value>' block allows you to modify a sprite's colour and the drop-down menu that this block supports can be used to distort the sprite. These are all fun things to experiment with.

Sensing Palette

The Sensing Palette provides you with the means to get input from the keyboard, pausing and waiting for a key to be pressed or a question to be answered for example.

Sound Palette

The Sound Palette has a good range of not just sounds but sound types. The values used are Midi numbers and this is explained in more detail in Chapter 25 which looks at Sonic Pi. However, if you enter a note value a keyboard pops-up and you can see what note you are entering as it is displayed graphically and alphabetically on screen. Volume can be set to a value and changed, as can tempo . The 'set instrument' block allows you to select the instrument you would like to use from a long list on a pop-up menu.

Operators Palette

The Operators Palette provides various mathematical and logical operators. You can also pick out letters from within a pre-defined word, which is a useful way of spelling out something on-screen.

Pen Palette

The Pen Palette allows you to select the colour and size of a pen. With this defined using 'pen down' block you can draw lines on the Stage as your sprite moves.

Variables Palette

The Variables Palette allows variables to be named. Click on 'Make a variable' and you'll be asked to give it a name. You can also define whether the variable is sprite-specific or available to all sprites in the program. When you have named the variable you are provided with a set of blocks that can be used to manipulate the variable; this includes setting its start values and adding to or subtracting from its value.

More Scratch

Scratch is addictive and you can import all sorts of things into your menus. The official Scratch website is located at:

<http://scratch.mit.edu>

and this has plenty of help and ideas as well of lots of projects to load and try. Experimentation is the best way to learn so look at the other projects already installed on your Raspberry Pi and see where it takes you.
21: Making a Website

Making a useful website is easy. You can create a website for display on the Internet or just to use locally on your Raspberry Pi as a way to get around your software and documents. The great thing is, you can see the results of your efforts immediately, and you don't need any special software.

If you have spent any time surfing the web you will know that websites come in many flavours. Some are wondrous creations using movies, animated graphics and sound to capture the imagination, whilst others are pages of normal text with basic formatting and plain images. Which is the more effective? To a large extent it depends on the market you are aiming for.

Wikipedia pages for example are relatively straightforward and follow a standard format (template) so that it is easy for the readers to find their way around. The criteria for a Wikipedia page would be to make the information easy to read, easy to access and consistent in presentation. A gaming website or a movie blog may be looking to lure people in with snippets of the latest shoot-em up or blockbuster so the visual presentation of graphics is much more important. In both cases the structure of the website is not drastically dissimilar. At the end of the day a website is a series of pages containing text and images (which may be videos) that link to one another and allow the user to navigate freely around them.

File Structure

When you are creating a website of any sort you can end up with a lot of files. These files may not be very big, but just about every element you see on a website has an associated file. For example, every image is a separate file (and you might have several of the same image at different sizes) and that includes logos and style items such as icons. Every page on a web site is a file, while every item you might want to download from a website is a separate file. For this way it is worth starting as you mean to go on and get your website structure in order from the off. Then you will know where to find things.

I suggest you create a parent directory called 'Website' in your Pi folder. Inside this create the following folders:

  * Images
  * Logos
  * Movies
  * Docs
  * Misc

I have included a Misc folder here. Generally though if there is something that is specific, create a folder for it. Now you know where all your image files belong. And all your document files go in...

The only files we will keep in the parent folder (Website) are the web pages themselves.

A Quick Example

A web page is just a plain text file saved with a specific file extension. To be exact it is a HTML file and this is the file type extension also given to the page. HTML stands for Hyper Text Mark-up Language. HTML is a simple programming language that all web browsers understand. As the programmer you create a text file that contains an HTML script and open it in a web browser. That in a nutshell is essentially what happens.

To create the HTML file you can use any text editor you like, so any of the favourites we have used in the past — Nano or Leafpad would be a couple of examples. As you will want to follow your website development on screen step-by-step I would suggest you start in the Desktop environment and use Leafpad for ease of access.

Open Leafpad and enter these lines of HTML code into it:

<!DOCTYPE html >

<html>

<body>

<h1>Raspberry Pi Resources</h1>

<h2>The Family Guide to the Raspberry Pi</h2>

<p>All about the Raspberry Pi B+</p>

</body>

</html>

Now save the file as:

home.html

Locate the file in the Website directory and right-click on it. From the menu select either Epiphany Web or Netsurf to open the file. The result should look something like that shown in Figure 21a.

_Figure 21a. The start of the website._

Avoid opening in Midori (if an available option) as this is not suitable for our uses at the moment, having no address bar displayed.

By looking at the code and the resultant web page displayed you should have a good idea of what each of the commands do. In fact in HTML we use the term 'tags' and each tag has a start and end component. Look at the heading line 'Raspberry Pi Resources'. This starts with <h1> and ends with </h1>. The h1 stands for heading 1, which is the biggest default heading in HTML. Everything between the two tags will be displayed in heading 1 style. The <h1> starts the heading1 style and the </h1> tag closes the h1 style.

You can see we also use an h2 style <h2></h2> and also a paragraph style <p>. The paragraph style is used for the main body text of the web page. You will note that the html code is enclosed within opening and closing <html></html> tags and that the main body of the html script is also enclosed in <body></body> tags.

Your web document should also contain a title and this title appears at the very top of the browser window. Bear in mind that the title is what search engines like Google consider when ranking your web page. Choose your titles carefully, and keep them brief. At the moment the title is the file location, so we need to change this to define what title we want displayed. Here's the updated HTML:

<!DOCTYPE html >

<html>

<body>

<title>Raspberry Pi Resources</title>

</head>

<body>

<h1>Raspberry Pi Resources</h1>

<h2>The Family Guide to the Raspberry Pi</h2>

<p>New Raspberry Pi B+ now available</p>

</body>

</html>

Here's a trick. Every time you save your page of code you don't actually need to double-click again on the file icon to reload the page, in Web and most browsers you can just press function key F5 to reload the screen (this can also be achieved by 'View>>Reload' from the menus).

Go to 'View>>View Source' and a new window will appear. The contents of this should now look very familiar to you! You are of course looking at the page source, and you can do this for any web page you load. It's a great way to see how things are done by the professionals.

Text Formatting

HTML supports a number of text formatting tags that allow you to create basic effects on the page such as bold, italic and underline:

This is <b>bold</b>

<i>This whole line is in italics</i>

<u>This is underlined</u> and this is not.

You can mix and match these anywhere you display text on the screen.

You will often see instances where the tags <strong></strong> and <em></em> are used for bold and italic. However, there is a difference in the meaning of these tags as <b> and <i> define bold and italic text only. The <strong> or <em> tags mean that you want the text to be rendered in a way that the user understands as 'important'. However, all major browsers render 'strong' as bold and 'em' as italics. But this may not always be the case — HTML features (like all software) are in constant development!

Adding Links and Pages

We'll soon look at how to get some useful effects such as colour and menus on the page. However, before we get into that detail, let's examine how we can add links and pages. A link — which is short for 'hyperlink' in web talk — is what you click on to get you to another place. Links often appear underlined or highlighted on the page. A link can be a single word, group of words, or image that is 'clickable'. When you move the cursor over a link in a Web page, the arrow will turn into a little hand. When you double-click on a link it can transport you to another web page elsewhere on the web or to another page or place in your own website structure. Reword the paragraph tagged text in Leafpad thus:

<p>New Raspberry Pi B+ now available

<a href="http://raspberrypi.org">Click here</a>

</p>

Firstly note how we have moved the close paragraph tag </p> down a couple of lines. Tags are not fussy about what line they are on, just be aware that what is placed between them takes on the characteristic of the particular tag.

The <a></a> tags define a hyperlink or specifically an 'anchor' tag. The 'href' attribute is the hyperlink reference and this, along with the website address becomes part of the tag. Notice how the closing '>' comes after the web address, here it is the address of the Raspberry Pi Foundation website. The address specifies the 'http://' start which we tend to ignore when we enter web addresses. This must be included otherwise it will not work (HTML requires it). The best way to obtain a properly specified web address is to open the website page that you wish to refer to in a browser, copy the URL and then paste it directly into Leafpad.

The text that follows between the attributes is the text you want highlighted, in order to click on. Save the updated code and then look at the result in the browser.

Note how only text between the '>' and '< ,' appears. If you click on the underlined text you will be taken to the web page specified. By default, links will appear underlined in a colour as follows in all browsers:

Blue: An unvisited link

Purple: A visited link

Red: An active link

Add an additional couple of lines after the 'href' line thus:

<p>New Raspberry Pi B+ now available

<a href="http://raspberrypi.org">Click here</a>

To read our review of the Raspberry Pi B+

<a href="page1.html">click here</a>

</p>

Save this and reload it. If you click on the new link you will get an error message saying that the web page was not found. This is because it currently does not exist!

In Leafpad open a new blank file and enter the following text before saving the file as 'page1.html'

<!DOCTYPE html >

<html>

<body>

<title>RPR Reviews</title>

</head>

<body>

<h1>Raspberry Pi B+ Resources</h1>

<h2>Inside the B+</h2>

<p>The Raspberry Pi B+ has many new features.</p>

</body>

</html>

You must save the new page and all subsequent new pages in the 'Websites' directory itself. This is where our link will expect to find it. If you want to store the page in another directory then the reference to 'page1.html' must reflect that with the full address path.

Now reload the home page and then try the link. The link to page 1 should get you to the new page. Now there is no link back to the home page — you might like to try that for yourself.

On the home page when we added the new text and link it was displayed on the same line as the previous link. To force the new text onto the next line you could have created a new

setting, however this inserts additional space on the page that you may not have wanted. So instead you can use the line break tag <br>:

<br>To read our review of the Raspberry Pi B+

The <br> tag is standalone. You do not need to have a close tag for it — it works where you place it.

Images

In HTML, images are defined with the '<img>' tag. This tag is different in that it does not have a corresponding closing tag. You include various attributes within the <> and these define how your images will be displayed.

To display an image on a page, you need to use the 'src' attribute. Src stands for 'source' and will point to the address where your image is stored. Images are not actively stored in the HTML, only their address. When it needs to be displayed, the web browser will locate the image from the address specified. This is why web pages can be slow to load if they contain lots of images.

To see this work you will need an image file and you will need to place it in the 'Websites/Images' directory. Any image will do for now — a photo of your Raspberry Pi for example. I have an image called 'rpi.jpg' and to display this on the webpage I would use the following line of code:

<img src="Images/rpi.jpg" alt="The Raspberry Pi" <

I have included an extra attribute here — 'alt'. This specifies some text that will be displayed if the web browser cannot display the image. It might be missing or you may have specified its filename incorrectly for example.

The browser displays the image where the <img> tag occurs in the document. If you put an image tag between two paragraphs, the browser shows the first paragraph, then the image, and then the second paragraph.

Images can be very large and they may end up being much too big to display sensibly on the web page. You can specify the width and height of an image using attributes. For example (all one line):

<img src="Images/rpi.jpg" alt="The Raspberry Pi" width="540" height="514">

This will limit the size of the picture to 350 by 140 pixels. Be aware that you can seriously distort images if you do not keep the width and height dimensions in proportion. Figure 21b shows the elements of the updated website.

_Figure 21b. Using an image adds impact!_

Like any other script you can comment your html files using the comment tags <! and >:

<! This is a comment in html >

Lists

There are two main types of lists in HTML — unordered lists and ordered lists. They both work the same way, except that the former is used for non-sequential lists with list items usually preceded by bullets and the latter is for sequential lists, which are generally represented by incrementing numbers.

The 'ul' tag is used to define an unordered list and the 'ol' tag is used to define an ordered list. Inside both these lists, the 'li' tag is used to define each list item.

On the page1 we could add a list of items that are new to the Raspberry Pi B+, so that our new 'page1.html' code looks like this:

<!DOCTYPE html>

<! Page1.html>

<html>

<head>

<title>RPR Reviews</title>

</head>

<body>

<h1>Raspberry Pi B+ Resources</h1>

<h2>Inside the B+</h2>

<p>The Raspberry Pi B+ has many new features:</p>

<ul>

<li>Four USB Ports </li>

<li>More GPIO Pins </li>

<li>Micro SD Card </li>

<li>Better Audio and Power consumption </li>

</body>

</html>

Here the list appears in four bullet points. If you changed it to an ordered list it would appear as points 1, 2, 3 and 4.

Colouring By Numbers

Colour in HTML is specified by numbers. HTML colour codes are made up of three colours — red, green and blue values thus:

RRGGBB

For example black would be defined as:

#000000

Which is no red, no green and no blue, whereas white would be:

#FFFFFF

Which is all red, all green and all blue

You may be surprised to see letters and not numbers. These are numbers but expressed in hexadecimal notation. There is no need for you to understand hexadecimal notation, but it is a major issue when you get into the depths of programming, so if you would like to know more please visit my website at www.brucesmith.info and go to the _Insider Guide_ support page. Click the link there for a feature about hexadecimal numbers.

For now though, you can trust your instincts and go with the values we give in Figure 21c for some associated colours. These colour codes can be used to change the colour of the background, text, and tables on a web page.

_Figure 21c. Hexadecimal values for html colours._

The combination of Red, Green and Blue values from 0 to 255 (00 to FF) gives a total of more than 16 million different colours for you to play with (256 x 256 x 256).

Setting text to a particular colour is done with the tags and using the colour attribute. On the home page of your website edit the 'h1' heading line thus (all one line):

<h1><font colour="FF0000">Raspberry Pi Resources</font></h1>

Save and reload and you will see that the heading is indeed in red. Once you define a font colour everything that follows up to the closing font tag will appear in that colour. Some colours have names assigned to them so if you change the FF0000 to blue, the text should appear in blue:

<h1><font colour="blue">Raspberry Pi Resources</font></h1>

Note that the font tag is not supported in the latest versions of HTML (from HTML 5, which is Epiphany Web compatible) and we'll look at another feature called CSS next, for even more control.

CSS

CSS stands for Cascading Style Sheet, and allows web developers to create and easily change how their web pages look and feel. The method we have used up to this point has involved using tags and applying these directly at the points we need them. With CSS you can define how each page looks by defining the elements used generally within a '.css file'. The CSS file can be linked to from multiple pages and if you ever wanted to change the look or feel of all of those pages you would now only need to change one file instead of all files. If you are familiar with styles in word processing software such as Word or LibreOffice Writer, this concept will not be new to you.

To create a CSS open a new file in Leafpad and enter the following:

h1 {color: red;

background-color: yellow; }

Be careful with spelling. I'm a Brit so I always spell color 'colour' and then spend ages trying to work out why the definitions do not work... Here we are defining a colour and background colour for the <h1> tag. Rather we are redefining it as the text colour is black on a white background by default. The curly brackets define the start and end of our definition.

Save this in the Website directory with the following filename: definitions.css

Now go to the page1.html code and add the following line under the line with the <title> tags:

<link rel="stylesheets" href="definitions.css">

Save the 'page1.html' file and then refresh page1. You should see that the 'h1' heading is in red and that it is set against a yellow background.

Now the home page will not be affected by this change as the .css file definitions have only been set on page1. To apply the same styles on the home page you will need to add in the link in the HTML on that page. Note that .css references must always be defined somewhere between the opening <head></head> tags.

In the 'definitions.css' file above we used the colour name but it is also possible to use colour numbers instead. Just remember to include the hash in front of the number:

h1 {color: #FF0000;

background-color: #FFFF00; }

You can also use css files to change the font and size of font you are using:

h1 {color: red;

background-color: yellow;

font-family: "Freeserif", serif; }

This would now change the font used in all 'h1' headings as well as the two colours. If you want to see what fonts are available then in Leafpad go to 'Options>>Font' and you can check them out in the resultant font window.

You can also create your own pseudo tags — case classes — by defining them in the .css file and then calling them in your HTML. By default when you add them, images are placed from the right hand side of the page. However you can change this by defining a class. For example, we can define a class called 'imageright' which will place the associated image so that it is on the right side of the screen.

In the '.css' file add the following after the 'h1' definition.

.imageright { float:right; }

The ',' before the name specifies it as a new definition and the text following the '.' is the name assigned to the definition. You can add this to the image placement line as follows (all one line):

<img src="Images/rpi.jpg " alt="The Raspberry Pi" width="540" height="514" class=imageright>

Now when the page reloads the image will be on the opposite side!

Sometimes you might want to apply a style that is temporary, or maybe just to one line. Rather than defining it in the '.css' file, you can apply it inline with the style attribute. For example:

<p style="color:red">This text is in red.

Here the text colour is set to red up to the end of the paragraph. Any following paragraphs would revert to the default colour — black. The style attribute can contain any CSS property. In the following example we don't use a CSS but define styles at the start of the main code.

Layout

There are plenty of options to choose from when you come to laying out website pages. The best way to find what you might want is to experiment. Because you can see the result of your edits and changes almost instantly it is very easy to do.

The listing below displays a simple web page layout. It is a bit garish at the mo because I have deliberately chosen colours to make the different elements stand out for you. You can change this as you wish, but I suggest you leave them as they are while you settle on the appearance you want. The listing has its lines numbered. You should not enter these numbers — they are simply a guide so that in my text I can refer to a particular line. The numbers should also help you see where each line ends as some carry over onto a new line of the book but do not necessary do so in the script. The listing also contains a lot of new tags that we haven't used before and I'll explain what they do after the listing. Because of the nature of HTML the action of this may seem self-explanatory. Figure 21d shows what you should get when you save and load the code.

1 <!DOCTYPE html>

2 <html>

3 <head>

4 <title>Raspberry Pi Resource</title>

5 </head>

6

7 <body>

8 <div id="container" style="width:800px">

9

10 <div id="header" style="background-color:yellow; color:red;text-align:center;height:50px">

11 <h1 style="margin-bottom:0;">Raspberry Pi Resources</h1>

12 </div>

13

14 <div id="menu" style="background-color:cyan; height:600px; width:150px; float:left;">

15 <b>Menu</b><br>

16 <a href="page1.html">Reviews<a><br>

17 <a href=#>Features<a><br>

18 Links

19 <p>

20 <p style="margin-left:10px; font-size:12px">This is the website of the Smith family.</p>

21 </div>

22

23 <div id="content" style="background-color:silver; height:600px; width:650px; float:left;">

24 <p style=margin-left:10px>Add all your content here!</p>

25 </div>

26

27 <div id="footer" style="background-color:yellow;clear:both;text-align:center;"> The Smith Family RPi Website

28 </div>

29 </div>

30

31 </body>

32 </html>

When you open the HTML file in your browser you should see something similar to that shown in Figure 21d below.

_Figure 21d. The website created by the code above. The colours are there so you can see where the various 'containers' are._ /p>

The <div></div> tags are the key components of this web page. The <div> tag defines a division or a section in an HTML document. Everything within a pair of <div></div> tags is defined as being in the same section. One thing to note is that you can nest <div> tags (in the same way you can with structures loops in other programming languages) so you can create sections within sections. If you look at lines 8 and 29 these are opening and closing <div> tags and contain within them others. You can indent your code if this helps you follow any nesting. In line 8 we start giving the section an id, a name, and it is common to call the section that contains everything the container. The width of this is set to 800px (pixels) and this defines how far we stretch across the screen.

Lines 10 to 12 inclusive define the next section which is called 'header' and is where the 'Raspberry Pi Resources' heading goes. We have defined the height of the header as 50px and centered the text. If we had not defined the height, then the height would have been automatically set to the height of the 'h1' text.

Lines 14 to 21 define the menu section, which is placed at the left of the container by the 'float:left' setting. The width is 150px. Under this we have listed some links, and these can be linked to relevant pages as you wish. Here I have linked line 16 to page1.html and line 17 has an empty link awaiting a page address. Again this assumes that all pages are in the same directory. Below the menu items, line 20, I have added some text. This is in a smaller font, 12px, and the text is also allocated a left margin, 10px, so that it is not butted up against the edge. These are numbers you can play with.

Lines 23 to 25 define the main content area. The height and width of the content area are such that it aligns with the right hand side of the header and within the bounds of the container itself — the container is 80 pixels wide, the menu is 150 pixels wide, so that leaves 650 pixels for the width of the content area! Similar arithmetic gets you the height. Lines 27 to 28 define the header block that spreads across the width of the container, before we exit out of the main container and the code overall.

Try re-adjusting the size of each section and see what effect it has. You might try breaking the contents container into two sections to provide two columns and also look at adding a section down the right of the page. You should be able to do all these things just by re-adjusting and adding to the existing code.

Editors and Web

Although we have written the earlier HTML code in Leafpad there are dedicated HTML editors available to download and use. These can provide you with line numbering by default and also highlight and prompt you for tags and information (in the same way that Python Shell does, as you will have seen if you worked through the chapter on Python). Choice on the Raspberry Pi is limited — not least because editors such as JEdit and Bluefish are large and can be slow to use. The great thing about HTML is that — like Python — it is generally transportable, so you can develop on say a Windows PC and copy the files to the Raspberry Pi, using them with little or no modification.

The files we have created have been for local use, but if you want to publish your own on-line website then you will need a suitable web hosting account (which can be very cheap), a web address and software to upload to the website. Filezilla is software that you might look at to assist in doing this.

Use your browser to find out about websites and suitable software for uploading, and read up about both of them.
22: Assembly Language

Everything that your Raspberry Pi does is executed in machine code. This is the language that the ARM chip understands. You too can program in machine code using assembly language and it is quite a simple process.

Assembly language gives you access to the native language of the Raspberry Pi – machine code. This is the tongue of the ARM chip which is the heart and brain of your Raspberry Pi computer system. Microprocessors such as the ARM control the use and flow of data. The data the central processing unit (CPU) processes are digested as a continuous, almost never ending stream of 1s and 0s. The order of these 1s and 0s has meaning to the ARM, and a particular sequence of them will be translated into a series of actions — just like Morse Code where a series of dots and dashes in the correct order has meaning if you know how each letter is represented.

Numbers With Meaning

A machine code program is a sequence of numbers which are a form of code and represent actions the microprocessor chip must take. In their basic form these numbers are endless strings of 1s and 0s. For example:

11010111011011100101010100001011

01010001011100100110100011111010

01010100011001111111001010010100

10011000011101010100011001010001

These 1s and 0s are represented by electronic pulses applied at the appropriate point. It would be almost impossible — or at the very least extremely time-consuming — to directly interpret what these numbers mean. Assembly language helps to overcome these issues.

Assembly language is a form of shorthand that allows machine code programs to be written using an English style lexicon. An _assembler_ is a program which translates the assembly language program into the machine code, thereby taking away what would otherwise be a laborious process. The assembly language program is often just a text file and this is read by the assembler before being converted into its binary (1s and 0s) equivalent. The assembly language program is called the input or source file, and the machine code program the object file. The assembler translates (or compiles) the source file into an object file.

Assembly language is written using mnemonics. A mnemonic is a device that aids learning or acts as a reminder. This relies upon associations among easy-to-remember letter sequences that can be related back to the information to be remembered. You've probably encountered these at some point as acronyms. For example, to remember the colours of the rainbow you could take the phrase:

'Richard Of York Gave Battle In Vain'

And use the first letter of each word. Or use the fictitious name:

'Roy G. Biv'

A mnemonic language has developed around SMS messages sent on mobile phones. These enable text messages to be shorter and more compact. For example, 'l8r' for later', 'gr8' for Great and '2mrw' for 'tomorrow'.

ARM Instructions

The ARM chip has a specific set of machine code instructions that it understands. These operation codes or 'opcodes' and their use are really what this book is about. The ARM is just one type of microprocessor; there are many different types and each has its own unique set of instructions.

You cannot take a machine code program written for ARM and run it successfully on a different microprocessor. It simply would not work as expected, if at all. That said, the concepts introduced here (rather than the actual code) can be applied with a broad brush to most other microprocessors available and these are pretty consistent in application. If you learn to program in one, you are well on your way to programming others. Essentially you just need to learn a new set of mnemonics, and most likely many will be similar to the ones you are about to learn.

Microprocessors move and manipulate data, so not surprisingly many of the machine code commands deal with this control, and most instruction sets (the collective term for these mnemonics), include commands to add and subtract numbers. The assembly language mnemonics used to represent these tasks are typically in the form:

ADD

SUB

As you can see, these examples are pretty straightforward as are many other ARM mnemonics, However, they can also appear complex when combined in a single line sequence. By breaking them down into their component parts their action can be determined without any real difficulty.

An assembly language mnemonic is normally three characters in length, but there are occasions when it may be longer. Like anything new, this may take a bit of 'getting used to', but if you work through them you should not have too much trouble.

MOV is the mnemonic for the MOVe command. It takes information from one place and moves it to another place. How hard was that?

The Transformation Process

Once you have developed your assembly language program you have to convert it into machine code. This is done using an application called an assembler. For example, when the assembler encounters the MOV mnemonic it will generate the correct number that represents the instruction. It stores the assembled machine code as a sequential file in memory and then allows you to run or execute it. In the process of assembling the program, the assembler also checks its syntax to ensure that it is correct. If it spots an error, it will identify it and allow you to correct it. You can then try and assemble the program again. Note that this syntax check will only ensure that you have used the assembler instructions correctly. It cannot check the 'business' logic (meaning to do what you wanted to do), so if you have written something that has used instructions correctly, but not in the way that achieves what you wanted, it will assemble without error but will produce an unwanted result.

There are various ways to write an assembly language program. The first ARM chips were designed by Acorn and so not surprisingly appeared on a range of Acorn-based computers running RISC OS. This included the Archimedes and RISC PC. These machines ran BBC BASIC, which was innovative in that it allowed you to write assembly language programs as an extension of BBC BASIC. This method is still available to you today should you install RISC OS on your Raspberry Pi — see Chapter 29.

As we have already identified, this book assumes that you are using the Raspbian Operating System and this includes the GNU GCC software which you can use as an assembler. Other assembler software does exist — much of it free — and a quick search on the internet will reveal what the offerings are. A major advantage of GCC is that it can also assemble programs written in the C programming language.

Although this book is not about programming C, there are reasons why some familiarity with the infrastructure it employs is advantageous, and with just a bit of knowledge this can help make programming easier. We'll discuss this with examples later in the book.

The bottom line is that there is nothing to stop you trying any or all of these other assemblers, and certainly what you learn here will be beneficial in that process.

Why Machine Code?

This is an easy question to answer. Essentially everything your Raspberry Pi does is accomplished using machine code. By programming in machine code you are working at the most fundamental level of the Raspberry Pi operation.

If you are using a language such as BBC BASIC or Python then ultimately all its operations have to be converted into machine code on the fly by the computer every time you run the program. This takes a finite amount of time — in human terms lightning fast — but still time. This conversion or interpretation process therefore slows down the operation of the software. In fact, even the most efficient languages can be over 30 times slower than their machine code equivalent!

If you program in machine code, your programs will run much faster as there is no conversion being undertaken. There is a one-off conversion process when you run the assembler, but once you have created the machine code you can execute that directly. You do not have to run the assembler every time. Once you are happy with your program you can save the machine code and use it directly. You can also keep the assembly language source program and perhaps make changes at some later point, in which case you will need to assemble again.

Language Levels

Languages such as Python are called 'high-level' languages. High-level languages are often easier to write as they have a more English-like syntax and also include commands that do a complex sequence of actions using one command that would otherwise take a long list of machine code instructions to perform. Machine code is a 'low-level' language as it is working amongst the 'nuts and bolts' of the computer: it spells out every technical step in detail and as a result is harder to understand.

This is the advantage of a high-level language as opposed to a low-level one. That said, as you become more proficient in assembly language, there is nothing stopping you from building libraries of routines to do a specific task and just adding them to your programs as you write them. As you dig deeper into the world of the ARM, you will find that many such libraries already exist out there in cyberspace.

By writing in assembler you can also transport your assembly language programs onto other computers or systems that use the ARM chip. You simply load the assembly language file into an assembler at the new destination, assemble it and run the machine code program.

The GNU GCC compiler is available for just about all flavours of microprocessor, so being familiar with the use of GCC will allow you to transport your new-found skill onto other systems should you so desire.

Provided you take full advantage of the ARM chip's facilities you can even transfer and run the machine code directly. This has exciting possibilities when you consider that just about every Smart Phone and Tablet device available these days utilises ARM chips!

Creating and Executing

To create a machine code program in Raspbian we need to go through a write-compile-link process before we can end up with a file that can be executed. The first step is to write the assembly language program. Because this is the source from which everything flows, this file is called the source file. It is also signified by having an '.s' appended to its name. For example:

program1.s

The source files can be created in any suitable text editor. Enter the following program as shown:

.global _start

_start:

MOV R0, #65

MOV R7, #1

SWI 0

And save it — I'll use the filename 'prog1.s' here,

The next step is to convert the source file into an executable file of machine code. We do this with two commands entered at the command line. Enter the following two lines, one after the other, at the command line prompt:

as –o prog1.o prog1.s

ld –o prog1 prog1.o

These two lines first assemble and then 'link' the assembly language program. On completion the machine code can be executed. The syntax for this is:

./<filename>

The './' means 'run' and the file to be run is named immediately after the command — no spaces. Thus:

./prog1

When the prompt reappears, the machine code program has completed. Easy as that!

So we have just written, compiled and executed a machine code program — all the basic steps needed were involved in the process above. Of course, as the programs get more complex and we seek to make more use of the tools available in Raspbian then the process will itself become more involved, as we shall see.

Assembler Errors

If at any time during the above process you receive an error message — or any message at all, then look carefully at what you have typed. First look carefully at the assembly language program and then the individual lines of code to assembly, link and finally run the program.

If you get an error message from the assembler (this will be after you have pressed <ENTER> at the end of the first line) it will normally provide you with a line number as a guide. Even if you do not know what the message means note the line number and then reload the source file back into your test editor. For example:

prog3a.s:5: Error bad expression

This would indicate there is an error in line 5 of the source file.

With a small file such as this you can count down the lines and locate the one containing the error.

The Components

Let's now look at the above process and understand a bit more the anatomy of the source file and what we did to make it all come together. Look at 'prog1.s' again. It consists of just five lines.

Each assembler source file must have a starting point, and by default in the GCC assembler this is the label:

_start:

So the first line of this program defines '_start' as a global name and available to the whole program. The second line defines where '_start:' (now with the colon) is in the program. Note the use of the ':' at the end to define it as a label. We've defined _start as global and now marked where _start is.

The next three lines are actually assembly language mnemonics. Two of the lines are similar, and use the MOV instruction. When the hash symbol is used in assembly language it denotes an immediate value. In other words, the value after the hash is the value to be used. In the first case, the value 65 is to be moved into Register 0. Here 'R' stands for register which is a special location in the ARM chip. In the second line, the value 1 is moved into R7 or Register 7.

The final instruction is 'SWI 0'. This is a special instruction that is used to call the Raspbian Operating System itself. In this instance it is being used to exit the machine code program and return control back to the command line prompt (when the program is run of course).

Just a note on the character case used for the assembly language commands in these source files: I am using uppercase letters for mnemonics and registers. I could have just as easily used lower case — inside the source files the character case does not matter, thus:

MOV R0, #65

and:

mov r0, #65

are seen as being one and the same thing. But the practice that I've followed makes the commands easier to identify in the text of the book, and also makes the commands stand out from labels — which I will continue to place in lower case.

If you look at 'prog1.s' again you can see that it consists of two clear sections. At the top (start), are some definitions, and in the lower half, the actual assembly language instructions. Assembly language source files always consist of a sequence of statements, one per line. Each statement has the following format, each part of which is optional:

<label:> <instruction> @ comment

All three of these components can be entered on the same line, or they can be split across lines. It's up to you. However, they must be in the order shown. For example an instruction cannot come before a label.

The 'comment' component is new. When the assembler encounters the '@' it ignores everything after it until the end of the line. This means you can use it to annotate your program.

To convert the source file into an executable file we needed two steps. The first was:

as –o prog1.o prog1.s

The 'as' at the start invokes the assembler program itself which expects several arguments after the command to define the files it will be working with and what it will be doing with them. The first of these is 'o' and this tells the assembler that we want to produce an object file, here called 'prog1.o' from the source file 'prog1.s' You can choose another name if you wish; the body of the name does not have to be the same, although making it the same makes it easier to keep track of your files. Of course, the suffix is not the same as this is a different kind of file!

The second and final step is to 'link' the file object file and convert it into an executable file using the 'ld' command as follows:

ld –o prog1 prog1.o

You can think of linking as the final bit of binding that makes the machine code work. What it produces is an executable file (called an 'elf' file) from the '.o' (object) file created in the assembly process. It is this 'ld' command that uses the '_start:' label to define where the program is to be run from.

Summary

This was a very quick look at how easy it is to create an assembly language program and run it on your Raspberry Pi. Although the commands may look very different from what we have seen when looking at high-level languages such as Python, the concepts behind using them and having a structured approach to programming are still very much the same. As with a high-level language,once you have mastered a machine code language it is reasonably straightforward to learn the fundamentals of others and move from place to place.

If you want to find out more about assembly language then you might want to consider _Raspberry Pi Assembly Language Raspbian Beginners_ by yours truly for a more in depth treatment of the subject. You can find out more by looking at Appendix B or at my website at www.brucesmith.info.
SECTION FIVE: HOME & OFFICE

The Raspberry Pi can be used for home entertainment and business purposes. With so much excellent software available there is almost nothing you can't do on your Raspberry Pi. In this section we'll look at some essential home and business software and how to play video and music around the house.

  * The _Insider_ skills you'll have at the end of this section will enable you to:
  * install and use LibreOffice and its industry standard interface to create sophisticated business solutions.
  * create and read industry standard PDF files.
  * write and play amazing music with Sonic Pi, with incredible outcomes.
  * create a state-of-the-art media centre and access a multitude of new TV channels
  * play high definition videos and create a user-friendly music library.
  * install and play some great retro games, including the incredible Minecraft, plus shoot-em-ups and brain teasers!

23: LibreOffice

LibreOffice provides you with the wherewithal to turn your Raspberry Pi into a fantastic home office centre becoming the hub for whatever you want to do. Whether it's managing the home, the local club or a thriving enterprise, LibreOffice is comprehensive with its word processor, spreadsheet, database and presentation software being just the business. And it's free!

LibreOffice provides a great environment for you to handle all your administrative needs. It has everything you need to conduct your own personal or professional business with an integrated suite of programs that are as versatile as anything you might spend hundreds of dollars on. LibreOffice is also compatible with all other major formats which means you will be able to transfer files from other software, such as Microsoft Office, without too much trouble.

LibreOffice has to be run from the Desktop environment and you can download and install it using the Pi Store. If you prefer you can do it directly from the command line by typing:

sudo apt-get install libreoffice

The process takes around 20-30 minutes depending on your Internet connection. When the download has finished you will see that LibreOffice has been added to the Programs Menu under a new Office heading (althouh LibreOffice Draw is added to a new Graphcs Mneu).

If you select LibreOffice from the menu you load the managing application. Think of this as the control panel from which you can access all the applications available to you. From this 'splash screen' (as it is known) you just select the software you want to run.

_Figure 23a. The LibreOffice splash screen showing the software available to you._

Alternatively you can load the software directly by selecting its actual icon from the Program Menu under the 'Office' tab. Each of the components of LibreOffice listed in the splash screen are summarised below.

Text Document

Writer is a full-featured word processor with file support for Microsoft Word and WordPerfect. You can use Writer to author anything from a simple letter to a full book ready for publishing.

Spreadsheet

Calc is a spreadsheet program similar to Microsoft Excel. You can use Calc to create and monitor all aspects of your financial requirements, from creating budgets and monitoring cash flow, through to creating invoices and keeping track of the bank account.

Presentation

Impress is a presentation program resembling Microsoft PowerPoint. In addition to being able to create slides to give visual impact to talks and discussions, this is also a great way to create graphics for your Writer documents.

Drawing

Draw is a vector graphics editor and diagramming tool similar to Microsoft Visio. Great for creating flowcharts and construction diagrams.

Database

Base is a database management program, similar to Microsoft Access. You can use this to keep any form of records or information. Typical applications include membership lists and stock control to name just two.

Formula

Math is an application designed for creating and editing mathematical formulae. These formulae can be incorporated into other documents in the LibreOffice suite, such as those created by Writer or Calc, by embedding the formulas into the document.

Being from the same stable and part of a combined suite of programs, there is a good deal of similarity across the menus of each of the individual packages, so you should find that as you start using the individual packages you begin to find your way around them relatively easily. Of course, the nature of the software is such that there will be specific menus applicable to the application provided by the software but the continuity is still retained even within these specific options.

Templates and Extensions

Consistency in presentation is something we are all familiar with — it helps in developing a brand and in presenting yourself or organisation in a consistent format. One way to achieve this with LibreOffice is to use templates. You can think of templates as pre-defined documents for each of the programs, that set the style and help to ensure the continuity of what follows. For example, when writing letters you will want to ensure this consistency is applied in terms of text style (the font) and its height and style from one letter to another. You might want to have a logo incorporated and certainly your address and contact details. Rather than creating this every time, you can design a template that contains these elements and save it ready for use each time you want to write a letter.

Templates are especially useful when it comes to presentations, to ensure the look and feel of your displays are consistent, whilst a useful template for Calc might be an invoice template. There is a template icon on the splash screen and this accesses any templates already installed in LibreOffice. On my installation there were only a few presentation templates available. LibreOffice templates can be found at:

<http://templates.libreoffice.org/template-center>

And even if you do not particularly like a given one you can always modify it to your own taste. In addition there are several independent websites that provide both free and paid for templates. Search the Internet for 'LibreOffice templates' to locate these.

Extensions provide the means to add additional functionality to your LibreOffice applications. They are programs that extend the operation of your software. For example, in Writer there is an extension available that will allow you to save a document in several different formats all at once, thus making your work instantly available in several different formats. If you are looking for an Extension for your LibreOffice go to:

<http://extensions.libreoffice.org>

At the bottom of the LibreOffice splash screen there are small icons that provide access to templates and extensions directly.

Writer

LibreOffice Writer is a full featured word processor. It is a _wysiwyg_ (pronounced wizz-e-wig) application which means that what you see on the screen is what you get when printing out. This makes the process of formatting the document useful as you can see the final result before you print it. If you have used any type of word processor before, then you should feel perfectly at ease with Writer.

If you have been through the programming section of this book, one thing I will stress is that you must not use Writer to create program scripts. This is not because it cannot do it, but unless you know how to save the files correctly you will run into problems. This is because the file format that Writer uses is certainly not compatible for use as a script file, even if you use the correct file extension for the programming language in question.

If you want to open an existing file you can go to the 'File>>Open' menu. The default setting for Writer is that all file formats are displayed. However for example you can use the drop-down menu to identify specific formats such as Word or WordPerfect. The File menu also includes an option to open a Template and in addition there is a 'Wizard' option that allows you to select/create a file from scratch. You can save files from the File menu, and you can specify any format you want. There is also an option to save the document as a PDF — discussed towards the end of this chapter.

To make the most of the wysiwyg feature of Writer you should ensure that you make full use of the in-built style feature. This allows you to re-format and change the look and feel of your document with the minimum of fuss. For example, if you have a style called 'Heading1' and apply this to all your headings, just by redefining what font and font style and size is used by 'Heading1' you can instantly change them in your document, without having to go through and do each heading individually. I would urge you to learn how to use the built-in styles of Writer to create flexible documents.

_Figure 23b. Start of the 79,000 words loaded into Writer complete with revision marks._

The 'Format' menu contains all the tools you need to do this. Click 'Format' then 'Styles and Formatting' (or press F11) to gain access to this editing area. The 'Table' menu allows you to add in tables which is suitable for formatting data and information.

The 'Tools' menu contains access to additional productivity items such as a spelling and grammar checker and a word count. It is also the place where you can manage extensions and where you can customise your use of Writer. If you have an extension you wish to use, then install it from here, after you have first downloaded it.

I was keen to test out Writer's compatibility so I loaded an edited copy of one of my manuscripts. This I had last opened in Microsoft Word and it included all my editor's markups, comments, and suggestions. The file contained 79,000 words and took a few seconds to load. On viewing the displayed copy, I found that it contained all the revision marks and scrolled well on the Pi albeit a tad slowly. Figure 23b shows the start of the loaded file.

Calc

LibreOffice Calc is the spreadsheet element of the LibreOffice Suite. It can be used for just about anything from creating simple budgets and keeping track of expenses and invoices, through to manipulating vast amounts of data as well as creating charts and graphical reports. Although LibreOffice includes Base, a database program, Calc can also be used to create and maintain collections of information. Information you create in Calc can be copied into Writer documents to assist in writing reports and presenting information. The same data can also be imported into Impress to provide material for presentations.

_Figure 23c. A budget doesn't have to be complex to be effective in managing money._

Calc is able to open and save most spreadsheets in Microsoft Excel format and can handle documents that contain one million rows! A basic spreadsheet consists of cells that can contain either data or formula. This can be arranged into grids consisting of rows and columns which in turn can be used to display and present information in many different ways.

The simplest spreadsheet would contain a column of numbers that have their contents totalled to give a final sum — the total. The information in the total cell would be a formula that adds up all values entered into the cells above it. Put 12 of these columns side by side and label each by month and you have produced the framework to a sales or expenditure report for the year. Do the same for income and by subtracting the totals in the sales report from the totals in the income sheet you have a very basic profit and loss report.

If anything involves the use of numbers then you can use a spreadsheet to keep a record of it.

Figure 23c illustrates a spreadsheet based created to keep track of household expenditure. It's simple but effective. To create this, open Calc. When it opens you will see that its menus are remarkably similar to that of Writer and their functions are largely the same. The Data menu contains some of the fancy stuff that is particular to the operation of Calc.

The main part of any Calc document is the spreadsheet grid and you will note that columns are labelled by letters and rows by numbers. This means that you can refer to any individual cell by using its grid reference. The very first cell on the grid (top left hand corner) is cell A1 — column A, row 1. A cell does not have a cursor as such, but the active cell (the one you are typing into) is denoted by its bold outline and the fact that its cell reference is in the drop-down box immediately above cell A1.

In cell A1 type:

January

If you press the <ENTER> key the active cell will be the one below A2. Click in A1 again. Note the tiny black square in the bottom right hand corner of the cell highlight? Move the mouse pointer over it and see that the pointer changes to a cross-hair. When it changes to the cross-hair click and hold down the left mouse button. Drag the mouse to the right until you reach cell L1 and then let go. Eureka, the cells are complete with the months of the year! You have probably scrolled the screen so that you cannot see A1— if that's the case use the slider bar at the base of the screen to slide left or simply use the <LEFT> arrow key to get back there.

For the budget we need to place some entries in the column to the right of column A. As such a column doesn't yet exist, we'll need to insert one. Click on the A in the cell above January. The column will be highlighted. Go to 'Insert>>Cells' and all the cells to the right will now be shuffled along to make room for the new column A. January is now in cell B1!

In cells A2 to A5 enter:

Food

Insurances

Phones & Internet

Gas & Electricity

TOTAL

In cells B2 to B4 enter:

300

200

100

200

Now we can sum these values to get the total we require. In cell B6 enter:

=sum(B2:B5)

When you press <ENTER> the formula you have just entered will sum the values of all the cells from B2 to B5 (note that the cells' references are case independent). The '=' sign is used to signify to Calc that a formula is being entered and not text or a number. We can see the results and display dollars by selecting the cells in question and then applying a format to them. To do this click in cell B2 and then, whilst holding the <SHIFT> key down press the down arrow key until you reach cell B6. The cells will be highlighted. Click 'Format>>Cells', in the 'Category' display select 'Currency' and press OK.

To sum the other months you can copy the formula into the cells in exactly the same way as you did for January. Calc will make the adjustments to the cell references automatically for you.

Extending the expenditure sheet simply involves you adding more rows into it using the insert method already described. If you insert in the middle (not before the first or after the last) then the formula will be automatically extended for you by Calc. Using a different set of cells you can create an income sheet and then using a third set of cells produce your profit or loss figures.

Using spreadsheets is straightforward; most errors occur because cell references are not correctly entered or the wrong formula was used. Compatibility-wise I have had no issues with loading even large Excel-created spreadsheets into Calc.

Base

Base is a database program that allows you to collect and sort information quickly and efficiently. The temptation is often to use Calc to do this but spreadsheets can grow very large and ungainly as the information is often repeated many times.

Databases can store very large numbers of records efficiently. For example, using Base properly set up, a car dealership only needs to store the name of a car once and it can be referenced against any other record. A database consists of tables and each table contains records. Each record contains a specific field which holds information. A table might be called 'Cars' and this would have a record for each car model. The record might include fields called 'CarName', 'Model', and 'Year'.

A second table might be called 'Engine' and this would have a record for each engine size. You could then create another table called 'Combined' and this would contain entries that tie in which cars have what size engine. The 'Combined' table takes information that already exists in the database to provide a new _view_.

Consider a database that is for a club membership. A table called 'Member' would have details about each member. This would include 'Name', 'Address', 'Date Joined' and the membership type. The membership type information could be taken from another table called 'MemType', which had those specific details. The 'Member' table would have a field in it that links to the 'Type' table. When you enter information about a new member, you select the type of membership from a drop-down list of entries in the 'Type' table. Therefore we have a relationship between these two tables and, not surprisingly, this type of database is called a _relational database_. If at some stage you add a new membership type, then you just add the new membership type to the 'MemType' table and it is instantly available to you in the 'Member' table.

Extracting information is called _querying_. And you can create and save queries by using a simple form. By querying the membership database you could find out how many members have full memberships, or how many people have been members before a certain date and therefore are due for renewal. You could use this information with the mail-merge feature of Writer to automatically send out reminder letters to people whose memberships are almost due for renewal.

When you want to display your information you can create a _report_. You might have several reports which use different queries to extract different information and present this using a layout you can design yourself using some simple design tools, which include the ability for you to add your own report formatting and text.

When you are creating a new database Base provides a useful wizard that allows you to create tables using some pre-created templates. The templates are categorised under 'Business' or 'Personal' and there is almost certainly one that will assist you in creating a database.

You can also import information from other sources by selecting 'Connect to an existing database' An option exists here to import spreadsheet data and the wizard makes this easy to do. You can also open other database formats.

Impress

You can use Impress to create stand-alone presentations — this might range from a new business strategy for the company to holiday snaps for the relations, and everything in between.

You can create master pages which define the look and feel of your presentation. The master page might include logos or corporate colours and splashes. By using master pages in LibreOffice Impress you can save even more time by downloading templates from the LibreOffice template library. Impress is compatible with Microsoft PowerPoint so you can also search these template libraries and sample presentations. This is a great way to obtain templates that you can customise for yourself.

_Figure 23d. Impress helps you to create consistent presentations._

Impress includes 'Presentation Wizard' from which you can select Presentations and Presentation backgrounds from some pre-defined options. The 'Tasks' pane provides you with access to 'Master Pages' and there are a number of templates you can select from here. In addition the 'Task' pane contains a number of windows through which you can select layouts for your slides. This includes multi-columns and multi-boxes The 'Custom Animation' and 'Slide Transition' panes allow you to animate and to control how you move from one slide to another and even how information is presented on the page — for example you might have a list of bullet points and want them to slide in slowly one-by-one.

When you open a blank file or a template file you will find that the various elements are contained within frames or boxes. These frames can be resized, moved and even added to. You can format text within them using the 'Format' menu in the same way that you would with Writer. To place an image on a slide you select it from the browser when you have chosen 'Insert>>Picture'. Once on the page (or slide) you will note that the image will have a number of drag points which can be used to resize it by using the mouse pointer to drag with.

Once you have created your slides you can preview the presentation by pressing F5, using the left and right arrow keys to move backwards and forwards through the slides.

More Information

LibreOffice is a suite of community-driven and community-developed software. It is free and is a project of The Document Foundation which is a not-for-profit organisation. The software is developed by programmers and people who donate their time to the cause. Anyone can become involved in the LibreOffice project. You don't have to be a programmer — you might be a tester, a designer or a documenter.

To support LibreOffice The Document Foundation has produced some great publications that describe and provide examples of all their products. These can be bought in book form or downloaded as a Writer file or as a pdf. In this chapter I have provided just an overview of what some of the applications can do and I also suggest some ways to use them. To find out more and move from beginner towards expert check out the documents at:

<https://wiki.documentfoundation.org/Documentation>

PDF and Document Viewer

PDF files are perhaps the industry standard way of transmitting documents for people to view. The Portable Document Format was invented by Adobe Systems over 20 year ago and is now an open standard for electronic document exchange maintained by the International Organization for Standardization (ISO).

Provided you have the right software you can convert just about any document into a PDF file, and the resultant document has exactly the same look and feel as if you had printed it to a printer, All the formatting, images and colours are maintained. This means that anyone who has a PDF viewer can read the document as it was intended (provided it hasn't been password protected, which is something you can do to keep important papers away from prying eyes).

When you convert documents, forms, graphics, and web pages to PDF, they look just like they would if printed. But unlike printed documents, PDF files can contain clickable links and buttons, form fields, video and audio.

The MagPi, the free monthly magazine for Raspberry Pi users, can be downloaded as a PDF file. When you share a PDF file, virtually anyone can read it using a PDF Viewer. On the Raspberry Pi such a viewer is Evince — which may already be installed under the 'Accessories Menu' as the PDF Viewer option in the Program Manager menus. Otherwise, you can obtain and install Evince using the following command at the command line:

sudo apt-get install evince

Once installed, Evince can be found in the 'Office' tab of the Program Manager and will be listed as 'Document Viewer', as Evince can also view other document formats including PDF, Postscript and Multi-Page TIFF files.

Figure 23e shows how an issue of The MagPi is displayed on screen using Evince.

_Figure 23e. An edition of The MagPi open for viewing on the Raspberry Pi._

Evince has a number of familiar menus across the top. These allow various operations to be carried out on a loaded document, allow you to move around it quickly and also define how pages are displayed on screen. You can quickly move to a particular page via the Thumbnail window on the left and clicking on it.

You can also use the 'Edit>>Find' option to search through a document for a word or phrase. Enter the term you are looking for in the window that appears at the bottom of the screen and then press <ENTER>. The application will conduct the search, listing the number of occurrences found. You can then use the <LEFT> and <RIGHT> pointer buttons to move through these on each page.

The File menu also provides a 'Print' option if you want to produce a hard copy of your document.

All in all Document Viewer is well worth investigating as you are certain to use it at least once a month to read The MagPi!

Creating PDFs

You can create your own PDF files using any of the LibreOffice programs. All have an 'Export PDF' option that can be found on the File menu. Using this you can create your own secure documents for distribution to people who might have a computer other than the Raspberry Pi!

Most commonly you'll be distributing documents so let's quickly look at the process of creating a PDF from LibreWriter.

First you will need to complete your document — if you create the PDF and then find the need to change the document you will need to then redo the PDF. Once completed go to 'File>>Export As PDF' to display a 'PDF Options' window. The 'General' tab has most of your main settings and the most significant one here is to specify whether there is a range of pages you wish to convert or whether you wish to convert the whole document. For example, if you only wanted the first ten pages in the PDF select the 'Pages' button and enter '1-10' in the window. You can also specify if a watermark appears in the background. Typically this might be used for printing 'DRAFT' lightly down the full length of the document, or perhaps 'TOP SECRET' — who knows!

The other tabs deal a lot with how the file is presented when it is opened by the intended viewers and this can largely be left as is. The final tab is 'Security' and it is here that you can password protect your PDF if you wish. If you click in 'set passwords' then you will be obliged to enter both an 'Open' and a 'Permissions' password. The 'Open' password is used by the reader to read the document, and details in the document can only be changed if the reader has access to the permissions password. In this tab you can also choose whether the user is allowed to print the document.

_Figure 23f. The PDF Options window displayed by LibreOffice applications._

When you have everything as you wish click the 'Export' button at the bottom of the window. At this point you can change the file name if you wish, otherwise it will default to the original document name, but with a '.pdf' file extension.
24: Audio and Video

Watching videos and playing music are two great applications for your Raspberry Pi. But it doesn't stop there. Did you know you can make your Raspberry Pi speak! Let's see — and hear (!) all about it.

In this chapter I'll show you how to make sure that your sound is working and also how to force sound through a particular output on your Raspberry Pi. We'll also look at a great application that you can download and use to make your computer speak and even read text files in different accents to provide you with a bit of attitude. If you like to listen to your music collection then VLC Media Player is a great way to arrange and catalogue your entire digital music library. We'll also look at a ready-to-use installed application to provide fantastic high definition video from the command line.

Getting Sound

You may already know from your use of the Raspberry Pi so far whether your sound is working or not. If it is then you can pretty much skip this section, although the information here is useful to know.

The easiest way to ensure you have sound on your setup is to play some! If you are using the Desktop environment click on the 'Python Games' icon and select a game with sound — 'simulate' or 'gemgem' are good ones. Start playing either one and you should get sound effects to match the screen flashes.

From the command line you can also type:

sudo aplay /usr/share/sounds/alsa/Front_Center.wav

Which should cause the words 'Centre' to be uttered.

If you have no luck and you are sure that all the connections are sound (!) then you may have to tweak your settings. From the Desktop, when you click on 'Python Games' there is a menu option that allows you to choose your audio output. If you are using HDMI then select the 'Force HDMI' button and try one of the games again.

You can change settings using the Raspbian configuration screen. Enter:

sudo raspi-config

at the command line and from the window that appears select 'Advanced Options' (remember you have to use the keys in the configuration screen, as the mouse does not work here). Then select 'Audio', and choose the option that suits before selecting 'OK' and 'Finish'.

Another command line option is to use the following to select HDMI:

sudo amixer cset numid=3 2

Or use the following to route analogue sound through the headphone jack:

sudo amixer cset numid=3 1

If you are using HDMI and can't hear any sound then look to see if the monitor/tv has other HDMI inputs. This is quite common and in this case try plugging your HDMI lead into one of these alternatives. If this still doesn't work then find a pair of headphones (the ones from your smart phone are fine) and see if you can route sound through the headphone jack by resetting accordingly. If you succeed this might indicate that the sound on your HDMI is not working. Likewise if you are using headphones then try another pair or try your existing pair on another device, like a smart phone or tablet device.

Omxplayer

Omxplayer is supplied as part of the Raspbian distro and is an excellent command line operated media file player. It can handle both audio and full high definition video. You need to know where your files are stored and that they are in a supported file format — generally mp3 and mp4 for audio and video respectively. These are the standard formats for such files these days and the most common. If you are not sure if a file is compatible, just try it. At the worst you'll get a shriek through your speakers, which is easily terminated.

To play an audio or video file you just need to enter the filename after the command name thus:

omxplayer video.mp4

omxplayer audio.mp3

where 'video.mp4' and 'audio.mp3' are the filenames with their filetype extensions. This assumes they are in the current working directory, so either set the location to the current working directory or include the path of the directory in the filename.

You can force output to a particular attached device thus:

omxplayer -o hdmi video.mp4

If you get a message saying 'unrecognised command' then ensure you have Omxplayer installed by entering:

sudo apt-get install omxplayer

There's not much more to Omxplayer after that other than being aware of the controls to work with it. They are all keyboard driven and are listed in Figure 24a.

You can use the 'h' option with the command to get further help on file options.

_Figure 24a. Keyboard control for Omxplayer_

VLC Media Player

VLC is one of my personal favourites when it comes to media playing software. It plays everything and is also available on just about every computer platform. It used to be supplied as part of Raspbian early on but was removed in later releases to free up space. It works from the Desktop environment so look in the 'Sound & Video' section of the Program Manager menu. If it is not already there you need to install it by entering the following at the terminal command line:

sudo apt-get install vlc

This only takes a few minutes to install and you should then be able to launch it from the Desktop through the Program Manager.

The controls on VLC are straightforward and arranged across the bottom of the screen, with buttons to play, pause, skip forward and skip backwards amongst others. There is also a triangular volume control that you can click on to adjust the sound levels. All you need to do is to add a file or a directory of files to play. You do this from the 'Media' menu on the top of the VLC window. You can select 'Open File' to play an individual track or file, or you can choose 'Open Directory' if you have a directory containing tracks.

If you are playing an album for example, selecting the directory containing the album files will place them in a Playlist. This should then show the files listed with all their information, and you might also see the album artwork appear in the window in the lower left hand corner.

In the menus down the right hand side of the window there is one called 'Media Library'. This allows you to add directories or individual tracks (files) for future use. To do this click on 'Media Library' and then right click in the window on the right. This will display a small menu from which you can 'Add Directory' or 'Add File'. As you add these items they will appear in the window. If it is a directory you can click on the icon of the directory and this will display the tracks as a Playlist. You can select files or directories in the Media Library and play them using the controls at the bottom of the window.

Sadly, playing video on the Raspberry Pi with VLC is not practical. VLC running in a Desktop environment like X-Windows pushes the Raspberry Pi to its limits and for most video files struggles to work. You can try overclocking (see Chapter 33) and this can improve things, so for the time being enjoy VLC for managing your music and audio files and use Omxplayer for your video needs.

With VLC installed you will find that when you right click on an audio (or a video) file in the menu that pops up you have the option of playing with VLC straight away.

Making Pi Speak

You can make your Raspberry Pi speak! The program you can use to do this is 'eSpeak' and it is free for you to download and use. The application is based on a program originally developed for RISC OS in 1995. It can chat away in over 50 languages, including English, Cantonese, Hindi, French, German and Spanish to name a few.

To install eSpeak access the Shell command line and enter:

sudo apt-get install -y espeak

There are a few ways of using eSpeak. The first two involve using text strings with eSpeak itself and the third uses eSpeak to create a file that can be played by other applications, typically 'aplay' (supplied with Raspbian). I find the latter method produces a better quality playback and also limits text output to the screen. We'll look at each of these in turn.

First to get a sample of eSpeak try this:

espeak -s 200 "This is your Raspberry Pi talking"

You may find that you get a lot of scratching noises in the playback, and probably a lot of error messages to the screen. If you don't hear anything try the command again, or try a longer sentence. You may only hear the latter part of the text as eSpeak takes a bit of time to get going. The 's' option adjusts the speed of playback and I find that 200 works better than the default 175. You may want to experiment a bit as your speakers might require a different value for the best performance.

I was initially playing eSpeak through the speakers in my monitor but found I got better initial results using headphones. If you do this you may need to redirect sound there — see the start of this chapter for details on how to do that.

You can also play back the contents of text in a text file. Open a text editor such as Leafpad, and enter a few lines of text. Save this, typically as: talk.txt. To play the text file use:

espeak -f talk.txt

However, I found the best results were obtained by saving the output to a sound file and then using aplay to re-play the resultant file — you will already have aplay as part of your Raspbian install.

To do this, first create the talk file from the text file thus:

espeak –s 200 –f talk.txt -w talk.wav

Then to hear the recording enter:

aplay talk.wav

This worked really well on my setup and didn't produce any error messages.

Figure 24b below details some of the options that can be used with eSpeak.

_Figure 24b. Some options which can be used with eSpeak. Values are all integer numbers._

Setting a voice is quite simple, although you would need to provide some text in the language to see how accurate it was. Use the 'v' option followed immediately by a two-letter mnemonic for the language in question, such as 'fr' for French, 'de' for German and 'es' for Spanish. Here's an example in French:

espeak -vfr "comment allez vous"

You can also add some flavour to your English text by localising it with a Scottish accent using en-sc:

espeak -ven-sc "Whit's fur ye'll no go past ye."

Taking it to the extreme a little, but try your 'wav' file with the 'en-sc' setting.

You can also choose whether to use a male or female voice by adding a variant. The variants are '+m1', '+m2'...up to '+m7' for male voices and '+f1' to 'f5' for female voices. Also '+croak' or '+whisper' for other effects. For example (all one line):

espeak -ven+f4 "Hello, my name is Doris and I'm your Raspberry Pi"

Pleased to meet you Doris!
25: Sonic Pi

Sonic Pi is not only brilliantly simple to use — it is utterly addictive to play with. Whether just playing simple two-finger piano tunes or converting pop classics from sheet music the sounds are awe-inspiring.

Sonic Pi has been developed for use on the Raspberry Pi computer as part of the KS3 introductory Computer Science classes in Schools. Although it has a very simple interface it can produce some really great output and it provides a perfect introduction to music and synthesised music for children, and indeed beginners of all ages.

Sonic Pi must be run in the Desktop environment and you will find it on the 'Programming Menu'. Version 2 was launched in late in 2014 (it will say what version when you launch the program) so if you have had your Raspberry Pi for a while do an update to ensure you have the latest version of the software:

sudo apt-get update

sudo apt-get install sonic-pi

If you have been using the original version of Sonic Pi then some of the original command names have changed, so any programs you may have might require modification to work.

_Figure 25a. The Sonic Pi Window._

When it opens — and you may find it useful to maximise the window — the Sonic Pi window consists of three main areas; a 'Programming' window (top left), the 'Log' window, which provides program text output (top right) and a 'Help' window (bottom). The 'Help' window includes a number of tabs on the left which provide access to 'Tutorial', 'Examples, 'Synths', 'Fx', 'Samples' and 'Language syntax'. Across the top of the screen are icons which provide direct access to actions you can perform. Most of these are self-explanatory.

In the top left corner are four pink coloured icons that allow you to run and stop your compositions, and also to save and record them. In the middle the yellow coloured icons allow you to change the size of your programming text and on the right the three blue icons give access to information and provide the means to set preferences ('Prefs'). The last one is useful for selecting sound output.

Spread along the bottom of the 'Programming' window screen are a number of tabs providing separate workspace environments — there are eight in all. You can go to any of these by clicking on the required tab. This makes it possible to be working on several compositions at once. It also allows you to try something out before adding it in your main composition.

Getting started is as simple as entering the command 'play' with a note number and then selecting 'Run'.

In the main window type:

play 62

And click the 'Run' button.

Line numbers are added to your programs down the left hand side of the 'Programming' window. As usual, these do not affect the operation of your program but are simply there to make it easier for you to read your program.

Midi Matters

The value after the 'play' command represents a note, 62 being Middle C. This is also known as a midi note number. Midi is the music system used by instruments such as electronic keyboards which are just musical computers at the end of the day. So if each note can be represented by a number (its midi number) it becomes relatively easy to translate sheet music into midi numbers that can in turn be programmed into Sonic Pi to play.Of course you will need to know how to read sheet music.

Like the programming languages we saw in Section 4, Sonic Pi supports variables and loops (see Chapter 19 on programming if you need a refresher on what these are). So we could create a small program that will play some scales. In a new workspace enter the following program you could save as 'Sonic1':

$note=60

while $note < 72

play $note

sleep 0.15

$note=$note +1

end

Now press the 'Align' button at the top of the screen. The program will be indented for you. It is not essential that you indent your program and it will work without any form of indent. Using 'Align' saves you having to sort the indents and you end up with a much more readable program. I'll indent the listings from here on to make them more readable here, but you can get Sonic Pi to do it for you if you want.

Here we have defined '$note' as a variable and assigned the value 62 to it. The '$' is not obligatory, and I could have just used 'note' but I think using the '$' makes it stand out better. We use a 'while...end' loop to enclose the output and the value of '$note' is incremented by one each time through the loop until it gets to 72. The 'sleep' command provides a short pause, here 0.15 seconds. Play the program and see the effect. Now edit 'sleep' to be 0.5 and run it all again. You can hear the difference. You could change the '$note' increment to +2 to see the effect of that.

Midi instruments such as synthesisers use a note range from 0 to 254 which relate to the frequencies (pitch) used. 0 is low pitched and 254 is high pitched. The useful range relates to the Piano keyboard from 21 through to 108. This following program (Sonic2) will loop through this piano range:

$note=21

while $note < 109

play $note

sleep 0.15

$note =$note+1

end

As with other programming languages there are loops and variables available so you can make more complex sequences of notes without having to write out each note.

Figure 25b lists the Midi note values for associated notes. Using these it is fairly easy to convert anything to play through Sonic Pi.

_Figure 25b Midi note values for associated notes._

To make programs easier to read we can assign variables to the values of the notes, for example:

$C=60; $D=62; $E=64; $F=65; $G=67; $A=69; $B-71

The semi-colon is used to separate individual items so that you can enter them on a single line.

However, although this demonstrates the use of variables, you can actually use the note letter (A-G) preceded by a colon with the same result:

play :C

This would play a C and the result is identical to the command:

play 60

You can comment your programs by using the hash character at the start of the line:

# This is a comment

If your program doesn't work then you may have an error. In this case an additional 'Error' window will appear under the 'Programming' window with details of the error. The text will give you some idea as to the nature of the error. If the program started to run but stopped, you can look in the 'Output' window to see where it reached before the error aborted operation — this will help you narrow down the location.

Loops and Tests

Repeating sections of code is a common requirement, especially so in music where introductions and choruses might need to be played several times. Sonic Pi provides a few loop structures, one the 'while...end' structure we have already seen.

If you need to repeat a loop a set number of times then use this loop:

x.times do

end

with 'x' being a number. Try this program (Sonic3):

2.times do

play :C

sleep 0.35

play :D

sleep 0.35

play :E

sleep 0.35

play :C

sleep 0.35

end

You should hear the first part of _Frère Jacques._ The program uses the 'do...end' loop, which is repeated twice as a result of the '2.times' command at the start of the loop. You could repeat the loop four times by changing the 2 to a 4.

If you want to repeat a block of code indefinitely then the:

repeat do...end

loop will achieve it. You would need to press the 'Stop' button to terminate the program.

You can also test for certain conditions by using an 'if...else...end' structure (Sonic4):

$note=21

while $note < 109

if $note <70

play $note

sleep 0.15

$note=$note +1

else

play $note

sleep 0.25

$note=$note +1

end

end

These instructions and how they work were detailed in Chapter 17, so please skip to that chapter if you need to know more about loops and conditional structures.

Pattern Play

Sonic Pi supports a number of more complex commands. A very quick way of playing the start of _Frère Jacques_ could be achieved using the following command:

play_pattern_timed [60,62,64,60],[0.5,0.5,0.5,0.5]

The first set of values between the square brackets are the MIDI note values and the second set of values are the associated sleep times. Thus we are specifying a sleep of half a second between each note. In fact we could have produced the same result with:

play_pattern_timed [60,62,64,60],[0.5]

as the times are re-used in a circular fashion if not enough are specified! Try the following:

play_pattern_timed [60,62,64,60],[0.5], "attack",1

The 'attack' and 'decay' of a sound have a great effect on the sound output. Attack is how hard you hit the note. A fast attack will produce a quick loud note while a slow attack will create a note that slowly increases in volume. Decay is how slowly the note loses its volume after it has been played. You can play staccato for example, by reducing the attack to a number less than the duration of the note itself.

The following is my take (actually my mate Jim's) on the opening bars of a well known tune and shows just what is possible with just a few lines of Sonic Pi code (Sonic5):

2.times do

play_pattern_timed [76],[1.25],"attack",1

play_pattern_timed [78,79],[0.25],"attack",0.25

play_pattern_timed [81,79,78,76],[0.5],"attack",0.5

play_pattern_timed [71],[0.4],"attack",0.5

play_pattern_timed [69],[0.25],"attack",0.25

play_pattern_timed [67],[1.25],"attack",1

play_pattern_timed [69,71,67,71,69,71,67,71,64,71],[0.25],"attack",0.1

end

Incidentally you can also use the 'attack' option with the 'play' command thus:

play 60, "attack", 1

You can also use the 'play_pattern' command to play a list of notes:

play_pattern [69,71,67,71,69,71,67,71,64,71]

The closing square bracket may be followed with '.sort', '.shuffle' or '.reverse' to play the notes in ascending sorted order or a random order selected by Sonic Pi:

play_pattern [69,71,67,71,69,71,67,71,64,71].sort

play_pattern [69,71,67,71,69,71,67,71,64,71].reverse

Active Command Completion

If you are a fast typist then you may have missed that Sonic Pi has an active command completion window. If you have seen this then in a new window type:

wit

and then wait. A pop-up window will appear with all the options available to you. Simply scroll through the list until you find the one you are looking for and double-click on the option to complete the command line entry.

Synths, Tempo, Chords and FX

When you play any script in Sonic Pi you probably will have noticed that the Log window displays information as each note is achieved. If you perform 'play 60', the output window would typically show:

synth :beep, {note: 64}

This indicates that Sonic Pi is playing a note (sound) at Midi value 60. The ':beep' indicates the synth that is being used. Synth is an abbreviation for synthesiser and here means the timbre being used — the synth voice. Sonic Pi supplies a number of synths that you can call by name to change the sound output. You can see a list of the synths by clicking the 'Synths' table in the 'Help' window.

Some of the synths are:

  * Beep
  * Dull Bell
  * Fm
  * Pretty bell
  * Saw

You can change a synth using the 'use_synth' command:

use_synth :fm

Try the following program to see the effect that 'synth' has on the output of playing a D (Sonic6):

use_synth :dull_bell

play :D

sleep 0.5

use_synth :pretty_bell

play :D

sleep 0.5

use_synth :fm

play :D

sleep 0.5

use_synth :beep

play :D

sleep 0.5

use_synth :saw

play :D

You can also use the 'use_synth' command to apply a synth to a section of code (Sonic7):

$note=21

use_synth :beep

while $note < 109

play $note

sleep 0.15

$note=$note +1

end

Change the synth a few times to see the effect it has.

You can change the tempo or speed that your composition is playing at using the 'use_bpm' command. Tempo is measured in beats per minute. To set the tempo at 200 bps use:

use_bpm 200

In music, a chord is any harmonic set of three or more notes that is heard as if sounding simultaneously. You can play a chord of notes using the 'play_chord' command. Try this example:

play_chord [60,62,64]

play_chord [60,62,64], "attack", 1

play_chord [60,62,64]

SonicPi 2 introduced FX (effects) that allow you to control how your tune sounds by applying a form of distortion to it. A list of those available can be found by clicking the 'FX' tab in the 'Help' window. Examples include distortion, echo, and reverb. Try this example (Sonic8):

with_fx :echo do

play 62

end

sleep 3

with_fx :reverb do

play 62

end

Two Tunes

The 'in_thread do...end' command and loop structure allows you to play two tunes at once. You create two complementary tunes — a melody and a backing track for example — in the same window and wrap them in the 'in_thread' structure. Try this example(Sonic9):

in_thread do

use_synth :pretty_bell

2.times do

play 60; sleep 0.35

play 62; sleep 0.35

play 64; sleep 0.35

play 60; sleep 0.35

end

end

in_thread do

use_synth :fm

14.times do

play 70; sleep 0.25

end

end

The trick is to time each track so that they finish together.

Samples

Sonic Pi V2 introduces samples. These are pre-recorded sounds that you can use in your own code. You can record your own using the 'Rec' button (see later) or use one of the many that are pre-supplied. Try this example:

sample :loop_amen_full

And listen to the sound of the drums thumping out! Try this to speed things up:

sample :loop_amen_full, rate: 1.5

Often you will want to use samples as a backing track. You can do this by playing the sample over and over, but you need to know how long it lasts so that it's a seamless process. You can find the length of a sample by using the 'puts sample_duration' command. To find the length of 'loop_amen_full', enter the following in a new Workspace:

puts sample_duration :loop_amen_full

Type Run and the answer will be displayed in the Log window. My code returned: 6.857142857142857. We can shorten this and use it to play a backing track, like this (Sonic10):

3. times do

sample : loop_amen_full

sleep 6.875

end

This will play the drums for around 18 seconds.

Functions

Sonic Pi supports the use of functions and also the ability to pass a parameter to a function. As with other programming languages you can assign the function a name and call the function by name. One of the best reasons for defining sections of code as functions is that it makes it very easy to change the key your music is playing in, by passing the function the 'start key' value and then writing your function code so that it works off a base value using a variable.

In a new Workspace, type the following function which is the structure for 'doe-a-deer' (Sonic11):

def doa (n)

play n

sleep 0.5

play n+2

sleep 0.25

play n+4

sleep 0.5

play n

sleep 0.5

play n+4

sleep 0.25

play n

sleep 0.25

play n+4

end

This is the function definition and here it has been called 'doa'. Below this in the same window insert a blank line and then add:

use_synth :pretty_bell

doa 50

sleep 1

doa 60

sleep 1

doa 80

Press 'Run' and you will hear the tune played in three different keys.

You can pass more than one value into a function, so we could also write the function to receive the sleep intervals as well (Sonic12):

def doa (n,m,p)

play n

sleep m

play n+2

sleep p

play n+4

sleep m

play n

sleep m

play n+4

sleep p

play n

sleep p

play n+4

end

use_synth :pretty_bell

doa 50,0.5,0.25

sleep 1

doa 60,0.5,0.25

sleep 1

doa 80,0.5,0.25

Recording Work

You can use the 'Rec' button at the top of the screen to record your work as a .wav file. Have the file you wish to record open in a Workspace window and click 'Rec'. The button will flash. Then click 'Run'. On completion of the music press the 'Rec' button again. You will then be prompted to save the file and you can enter a name of your choice.

Saving Work

Use the 'Save' button to save your individual workspaces. Click on the workspace you wish to save and then press the 'Save' button. A window will open and you can use this to navigate to the location required. Enter a name for the file and press the 'Save' button in the window.

There is no associated 'load' function for Sonic Pi, but files are saved as '.txt' documents. If you want to reload a tune then open it in Leafpad (or similar), select all the text (Edit>>Select All), then copy it (File>>Copy). Move to Sonic Pi, select the Workspace you want and paste the text in by right clicking in the Workspace window and selecting 'Paste' from the pop-up menu.

Trying It all Out

The 'Lang' tab in the 'Help' window provides a list of all the Sonic Pi commands. You can click on any one of them and get a full description of it with some examples in the 'Help' window. The 'Help' area is packed with great information and plenty of tutorials for you to try and experiment with.
26: Creating A Media Centre

In today's modern home a media centre is an essential if you want access to your favourite videos, music and photos from one or multiple televisions. With the right software the Raspberry Pi and a remote control can be an extremely powerful combination.

When we looked at text editors in Chapter 10 I made the comment that almost everyone has their own personal favourite that they swear by. Well the same can be said for media centre software, albeit the choice is not as extensive, and whichever one you go for someone else will suggest something better. The software we are looking at here is called Raspbmc. This is a Raspberry Pi customised version of XBMC which is available on other computer platforms such as Windows.

It is software that I use in my home every day to watch movies and TV shows simply and easily, and it runs from Raspberry Pi units that have their cases Velcroed to the back of the TV sets themselves. These units in turn are connected via a local network that is run from a central server elsewhere in my house. However, the software and same setup would work just as seamlessly if you were using a USB Stick or hard drive attached directly to the Raspberry Pi. It really does, so you should give it a go.

If you want to create a dedicated media centre then you will need to invest in a few bits and pieces, but in the meantime if you just want to play with the software and experiment locally a spare SD Card is all you need! For a dedicated media centre running from a USB Stick you will need:

  * Raspberry Pi Model B/B+ and Case
  * Power supply
  * SD Card, Type 4, 4GB or 8GB.
  * HDMI Cable
  * USB Stick (4GB or greater)
  * Remote Control and Infrared Receiver

I haven't included a keyboard and mouse here as you can image the SD Card and update it using your existing Raspberry Pi or you can move your keyboard and mouse to the Media Centre setup as required. Once you are up and running you won't really have a need for them. Raspbmc will partition your SD Card when it installs itself, so it will make full use of whatever sized SD Card you opt for.

The remote control unit and infrared receiver you select is up to you. If you have one to hand or have seen another that you like then you can always check its compatibility via the official Raspbmc website FAQ page (www.raspbmc.com) and where you can also purchase an infrared unit if you wish.

Have a think about where you are going to mount your Raspberry Pi as this will dictate the length of HDMI cable you want. Remember, these cables are quite bulky so trying to hide excess cable is not as easy as it might be with a USB lead. So purchase the shortest one you can get away with.

The USB Stick you select can be any size you want — or you may wish to use a bigger USB hard drive. In the case of the latter then you will need to supply power to the drive either via its own power supply or through a powered hub. I would suggest that initially you use any available USB Stick you have while you get up and running, before deciding on what your on going requirements are.

OSMC

Just before we get going, at the time of writing XMBC had announced that it would be changing its name to Kodi. Also Raspbmc have announced that it would undergo a name change in mid-2015 to OSMC and run on multiple platforms (including Android and iOS). This will not affect the functionality of the software and Raspbmc will continue to be supported including updates for the final release of the Raspbmc software. What will change will be the name and also the screen layouts although existing functions and functionality will remain. You can read more about this on the Raspbmc website. An update to this chapter will appear at www.brucesmith.info when relevant.

Note that a fresh install of the new software would be the best option, when it becomes available.

Installing Raspbmc

There are two methods you can use to install Raspbmc. The first is to head off to the 'Downloads' page at:

www.raspberrypi.org/downloads/

where it is available as a distro (this is the same page you downloaded Raspbian and any other OS images from). You install this on your blank SD Card in exactly the same way as before. Alternatively you can download the Raspbmc Installer from the Raspbmc website and then use this to get the very latest version of the software, using Windows, Mac or a Linux PC.

If you have the choice use the latter method as software is often updated overnight and this ensures that you get the very latest version. Only use the distro method if you do not have access to the Internet when you are installing the media centre and therefore need to download it using an alternative source (such as a PC or Mac at work for example).

If you are using the Network Install method then from your PC or Mac go to the 'Download' page at:

www.raspbmc.com/download/

select the installer of your choice, and follow the instructions there, saving the small file to a suitable folder. Navigate to the folder and ensure you can see a file called 'setup.exe'.

Make sure your SD Card is inserted into your computer (again using the same method as when you flashed the Raspbian image to the SD Card) and then double-click on the 'setup.exe' file. You should be presented with a window similar to the one shown below in Figure 26a. You can see that my SD Card is shown on the list. The square box next to this needs to be checked to select it. Note that there are some other options available — these should be ignored apart from the last one where you accept the licence agreement.

Flashing the installer onto the SD Card is a pretty quick process. Once you get the okay transfer the SD Card to the Raspberry Pi, re-connect and apply the power. After a few seconds you will be presented with a multicoloured screen and then the familiar cascade of text before a series of Raspbmc installer screens are displayed informing you of exactly what's happening. The download and install process can take anywhere between 20 and 30 minutes — and as the splash screen suggests, grab a coffee while you are waiting! The Raspberry Pi will probably reboot a few times and you will see screens containing the 'R' illustrated below. On completion, the 'XMBC' screen will appear with a list of languages to select from. Using the mouse or keyboard find the one of your choice.

_Figure 26a. The Raspbmc installer screen._

Local Media

It will take you some time to find your way around Raspbmc and get used to the interface. The best way to do this in the short term is using the mouse (we'll look at adding the remote control in due course). Menus are big and clear and there are prompts as you progress so it is all pretty intuitive. As you navigate through screens you will sometimes see a tab appearing on the left of the screen. If you move to this a side menu will appear and this provides options relating to the media, as well as allowing you to decide how you want your files displayed — whether by name, size and so forth.

If you are connected to the Internet then the current time and date will be displayed in the top right hand corner of the screen. A scrolling band occupies the centre of the screen and in the lower left is an 'off' button. As you move through the screens a back arrow and 'Home' icon will appear; these are quick methods of returning to your starting point. You will always find two dots at the top of any menu — as when working in the Shell, this takes you back to the parent directory to the one you are in, ie up one level. If you have a USB Wi-Fi adaptor then you will need to configure this using the Raspbmc 'Settings' menu.

The menu bar across the screen scrolls left and right as you move across it, and it will display sub-menus as you move the pointer over each particular item. For example, if you hover over 'Video' the options that drop under are 'Files' and 'Add-ons'. Move the move pointer over them and click to make a selection.

You will need some media to navigate to and try out, so put some suitable files on the memory stick — a video file, an audio file and some picture files. These files all come in various file types — some are recognised by Raspbmc and some not, that said the popular formats are. We'll look at this compatibility issue shortly. Plug the USB Stick into a free USB socket and you will get a message displayed on the screen that the drive has been mounted.

Playing Videos

Raspbmc supports the H.264 video file format, This means that it can play any video files that have the file type mp4, m4v, mkv or avi. It can do this to 1080p — which is high definition. Decoding these file formats is handled by a piece of software called a _codec_. If you try and play files that do not adhere to the H.264 format then you will get an error message to that effect. You then have two options: one is to use software to convert the format of the file to H.264 and the other is to install the codec for the file type in question. For a small fee you can purchase a licence for the MPEG2 and VC-1 codecs and download them from the Raspberry Pi website. These would cover you for the most common video files.

_Figure 26b. The Raspbmc navigation screen._

To watch a video you simply navigate to the location of the video file and then double-click on the file name. When you plug in a USB Stick, Raspbmc will recognise it and issue an on-screen message to that effect. To look for a file on the USB Stick click on the 'File' tab below the 'Videos' option. You will see the name of the USB Stick in the menu that appears. Click on the stick name to view any video files on it. As you scroll through the names of any files a thumbnail screen image from the first few frames of each file will be displayed. Note that only compatible video files will be listed in the menu, even though other files may be on the stick. Double-click click on the file name to start it running.

If you move the mouse when a video is running you will bring up a menu across the base of the screen. There is a standard set of video controls that allow you to pause, stop and move through the file. On the right there are other icons which enable you to adjust volume, download and enable subtitles and various other interesting things that you may want to explore through the 'settings' option (the film reel icon). This is somewhat advanced!

Playing Music

There are fewer issues with music file codecs and you should find that they accept most files you give them, including the popular mp3 and FLAC formats. Navigating to audio files on a USB Stick (or hard drive) is done through the 'Files' tab in 'Music'. Once there, select the media and when this opens the files or their holding directories should be available. If you are connected to the Internet, or if the information is already available in the audio file, then you may also see the album artwork.

Once playing, you get a visualisation animation and a similar menu to the one you saw when you played video files. There are a few more options here and plenty to explore at your leisure. It is even possible to download lyrics if you want!

You can continue to browse through your music and other aspects of Raspbmc while tracks are playing. If you leave music playing for a while it slips into full screen mode and acts like a screen saver. Just click on the 'Close' button to return to the interface.

The interface supports a wide range of other queue and play options, favourites and the more common Playlists. The latter can be named and their contents saved and preserved for use after reboots.

Before you can do this you need to scan tracks to the Library and then enable Library Mode. To scan tracks to the Library select them and then right click and choose the 'Scan item to Library' item from the pop-up menu. This doesn't actually scan the music to the Library — it just retrieves information about the file so it can be used by the Library in compiling any list you are looking for.

To enable Library Mode, when at the file browser slip to the right of the screen where a tab will be protruding. Moving over this will show the 'View Options' sidebar. Click on 'Library Mode' to illuminate the button, thus showing it is turned on. Note that you cannot enable 'Library Mode' until you have scanned at least one track to the Library.

Once you have information scanned to the Library then when you select 'Music' from the home page you will find that you have other ways in which to select your music — by artist, by song and album for instance.

Viewing Pictures

Click 'Pictures' on the main screen to display a simple file browser to access any pictures you have stored on the device. After navigating to where they are stored, images are shown in thumbnail view so you can see what picture is which. Double-clicking on the picture will display it in full screen mode.

You can use the 'View Options' menu within the tab to the left of the screen to sort and arrange your pictures. You can also set a slide show from your pictures running from here.

All the popular image file types are supported including JPG, TIFF and PNG.

Network Media

If you have a network at home and the ability to centralise all your media it makes accessing your files easier and avoids the need to make multiple copies for separate sites. With large disk drives available very cheaply it is an exercise worth undertaking.

You only need to navigate once to the network location for each media type — you are then able to give it a name that Raspbmc will remember (even after a reboot) and which you can use as a shortcut.

For example, to add a new source for videos, click on the 'Video' banner and then on the 'Files' sub-menu. Then select 'Add Videos' to bring up an Add Video Source window. Clicking on the 'Browse' button will display a window that lists possible locations for the new source (this new source will be called a share when you have added it). It is now just a matter of locating your network source. The great thing is that if you are not sure you can just look in each option until you locate what you require. You then just need to click down through the hierarchy until you reach the folder containing your files. Click the 'OK' button to add the path to the location of both of them and then edit the name of the older if you are asked to provide a name for the source. The 'Set Content' window that appears allows you to choose additional settings. Click 'OK' to return back to the 'Files' list and the named share will now appear in the 'File' menu.

You can edit a share at any time by right clicking on the source name and selecting from the menu options that are provided.

Add-Ons

Almost all media types have Add-ons associated with them. You may have seen this as the second option presented from the home page. An Add-on is an app that you can download to provide additional functionality and options for the media you are using. To access an Add-on you will need an Internet connection. There is a wide range of Add-ons available and as you examine each one you will find that a full description is provided for it. When you select Add-ons you will be presented with a list of those installed. There will also be an option in the list to 'Get More'; select this to access the current list relevant to the selection from the Internet.

Video: The longest list of add-ons are in this category and include access to free-to-air TV stations such as Al Jazeera, CBS News, ESPN, music videos, movie trailers, YouTube and even NASA. Really something for everyone.

Music: Radio stations and the ability to search for music on the Internet are some of the more popular options that can be installed from this Add-on. There is also access to over 50,000 free Internet radio stations!

Pictures: Add-ons for Pictures can provide you with access to other accounts where you might store photos, including Google, Flickr and Picasa. You can also gain access to the latest Dilbert and Garfield comic strips.

As you scroll down the list of add-ons on the right of the screen a description of each add-on is provided. If you want to see more, double-click on the add-on name in the list and you will be taken to a full-page information sheet. Here you can select the 'Install' option if you decide to go ahead. Most add-ons are not very big and they load quickly. You will have noticed from the menu where you click to install add-ons that options to update, un-install and perhaps even configure exist.

Other add-ons have setting menus where you will need to configure options and perhaps enter account user names and passwords where appropriate.

There is a lot to explore in the add-ons areas and there are some real gems. Many of the streaming media options, like Al Jazeera, not only provide you with a live feed but offer options for viewing previously aired programs and the latest news clips. Remember, it is easy to un-install and add-on, so there is no harm in experimenting and then removing what you don't like or don't use.

Changing Settings

Selecting Programs on the home screen provides two options which are displayed as icons, 'Raspbmc Settings' and 'Raspbmc Browser Launcher'.

The 'Settings' screen allows you to fine tune various aspects of the way Raspbmc interacts with a connected network and also how updates are handled. The 'System Configuration' page is where you would go to enter the licence keys for the MPEG2 and VC-1 Codecs should you purchase them from the Raspberry Pi Foundation. The final screen allows you to adjust settings for an infrared remote where one is needed. For the most part you should really only venture onto these pages if you are quite sure what you are doing.

The Arora Web Browser provides the option of being able to access the Internet from Raspbmc, although it is actually a standalone program. When you launch the browser for the first time it takes a few minutes to initialise and it will be downloaded and then do a quick re-boot. To exit back to Raspbmc select 'Quit' from the 'File' menu.

The Browser is a work in development and at the time of writing had a number of limitations so it would be worth going to the Raspbmc website to see what the latest version can and cannot do.

System Menu

The 'System' option on the home page provides access to four sub menus — 'Settings,' 'File Manager', 'Profiles' and 'System Info'.

The 'Settings' menu provides access to a lot of configuration data for using Raspbmc on your Raspberry Pi. Many of these I'll leave for you to explore — it is worth knowing they are there even if in most instances you will not want to change them. However, there are a couple I will discuss here.

Try clicking on 'Appearance'. Here you can change not just the way Raspbmc looks but also the way it functions and the range of options available on the home menu. A skin is the clothes your program wears — how it looks and appears on screen. The default skin for Raspbmc is called Confluence and it is the bubbly blue background that you see. In fact you will see the name 'Confluence' appear in many of the menus as a sort of logo. You can change this default skin. If you click 'Skin' on the main window area you will see that it is the only one available that is built-in. You can click on the 'Get More' button to download additional skins through the Internet. From the list of these, if you click on each one in turn you will get a preview of it. If one takes your fancy you can download, install and configure, to change the look and operation of your installation. And with that second option there is a word of warning. Your version of Raspbmc will look and feel different — which you would expect, but it will also operate differently, which you might not expect! This is not necessarily a bad thing, but bear in mind that this chapter is based on Confluence and assumes you are using Confluence.

The second item on the 'Appearance' sub menu is 'International' and on this page you can change the region and time zone for Raspbmc — this can be used to adjust your region so that the displayed date and time match your location.

One of the other menu items in 'Settings' is 'Weather'. Some skins provide home page access to Weather and you can display weather in up to three locations. You will need to first set a weather information supplier. Once you have set at least one location then 'Weather' will be an option you can choose from the home screen.

The 'System Info' option provides a lot of useful information about your setup. It is worth looking through these just so you start to get yourself familiar with terminology and settings. Don't expect to know all of it. It is more about getting comfortable looking into these areas and places you might otherwise avoid.

Of the final couple of options, 'File Manager' allows you to look at connected drives and devices and 'Profiles' allows you to construct named setting groups that you can use to configure the way Raspbmc is used.

Raspbian Settings

When you select 'Programs' from the main Raspbmc banner two additional icons are displayed at the bottom of the screen. One is 'Raspbian Settings' and the other is 'Arora' (this is an in-development web browser which can be used but it is slow and takes you out of Raspbmc). Selecting 'Raspbian Settings' brings up access to several screens, each allowing access to a specific area.

Network Configuration:

This allows you to fine tune your network settings. If you are using an Ethernet connection then this will have been detected automatically. If you need to define a USB Wi-Fi adaptor you can do it from this screen. First change the 'Network Node' setting to 'Wireless (Wi-Fi) network'. Then scroll down to find the 'Network Scan' option and locate and select your network. Finally ensure the Wi-Fi Security setting is correct and then enter your password into the 'WI-FI KEY' box. Select 'OK' to save the changes, and you should now be able to access the Internet via your adaptor.

Nightly Build Configuration:

Here you can decide if you want a regular update for Raspbmc — this is useful to ensure you stay up-to-date. Clicking on the 'Install XMBC Nightly build' will display a list of the most recent builds and you can select one to download and install.

System Configuration:

Allows you to define passwords if required, as well as the ability to enable and disable various options.

IR Remote:

Allows you to define and install a remote profile using remote specific information.

Adding A Remote

I have to say I found adding a remote control into the system a piece of cake. I had thought it would be difficult as the HP USB Infrared Reader reader and hand set were fished out of a parts tub from the shed and were probably a few years old. I had no manual — just the two components. I plugged the USB receiver into the Raspberry Pi and rebooted and it worked right away.

You don't really need the remote control for normal operation as you can use the keyboard, but it is a much better alternative when you are sitting in the armchair. Another option is to use the XBMC app on you iPhone or Android phone that accesses the Raspberry Pi over your network, either via a wired connection or by wireless.

If you are opting for a remote you can purchase a compatible one directly from raspbmc.com or access the list of compatible units they have there on line to select one of your choice. Incidentally, my remote was not in that list so if you already have a unit it is worth trying it before purchasing another. As mentioned above the settings for the remote control can be found in the 'System' menu.

OpenElec

In the 'distros download' page of RaspberryPi.org OpenElec is also available as an XBMC Media Centre. The main difference between the OpenElec and Raspbmc is that OpenElec doesn't have a Linux distro (ie Raspbian) underneath it, and the entire installation is about half the size at about 100MB. As a newcomer you would be better to stick with Raspbmc, not least as the software is regularly updated and includes all the hardware and software drivers you are likely to need.

The main benefit of OpenElec is that being smaller it is very fast. The disadvantage are it may not have the specifics you want and requires more customisation. However, as you get more experienced and if media centres take your fancy, then OpenElec may be something you will want to look into.
27: Pictures

With the advent of the digital camera, personal media libraries have swelled with photographic content. Being able to select and edit the images and pictures you want to keep has never been easier.

In previous examples within this book, whenever we have come to saving an image file, for example with the Raspberry Pi Camera Module, we have used the file extension .jpg which is pronounced 'jay-peg'. This file extension signifies a file compression method used to make the file smaller. Generally jpg files compress well without the loss of data, which in image terms means better resolution and sharpness. Other common file formats for images are GIF and PNG. These have very different uses.

A JPEG uses a mathematical algorithm to compress the image and will distort the original slightly. The lower the compression, the larger the file size, but the clearer the image. JPEGs are typically used for images such as photographs.

A GIF (pronounced 'jif') can have no more than 256 colours. The lower the number of colours you have in the image, the lower the file size will be. GIFs also allow any pixel in the image to be transparent, and are typically used for images with solid colours, such as icons or logos.

A PNG (pronounced 'ping') replicates colours, much like a GIF, but allows 16 million colours and as well has the ability to have up to half of its size in transparent form. PNGs are often used for images in complex designs but curiously are not fully supported by some older web browsers.

There are many other file formats, but unless you ever have a particular need or because a situation calls for a certain file type, it is best to stick with the JPG file format. Photographers use the RAW format which preserves all the data.

Image Viewer

Image Viewer can be found under the 'Accessories' Menu of Program Manager. Unless you have installed newer image manipulation software, when you double-click on an image file, like a jpg file it will open automatically in Image Viewer. Alternatively you can right-click on the image file and select 'Image Viewer' from the small menu of options that will present itself.

Image Viewer does basically what it's name suggests and more. You can view images and also change their orientation. This makes it ideal for flipping photos around through 90 degrees if you have taken a picture with the camera on its side, for instance.

_Figure 27a. It's nice having a town named after you! The ribbon along the bottom of the Image Viewer window neatly arranges tools into groups._

Figure 27a shows the Image Viewer interface. The application specific controls are set out along its lower boundary. They are broadly divided into five groups.

Display Control:

The left and right arrow buttons allow you to move one image at a time through any images that exist in the current directory. You can use the <LEFT> and <RIGHT> arrow key on the keyboard to do this as well. Note than if you have made any changes to the image this action will discard the changes unless you have saved them. The third 'Play' button sets a slide show in motion. This will start Image Viewer, automatically displaying any images located in the current directories. It does this one at a time and by default there is a five second delay between images swapping. When it has completed showing all the pictures, it will start again and continue to loop until you stop the slide show, by clicking the same button again (which will have now changed into a 'Stop' button). The five second delay can be changed by editing the Preferences for Image Viewer which we will get to shortly.

Sizing:

The next grouping has five buttons and these are all associated with the size of the image displayed on-screen. When you open an image, Image Viewer will make a decision about the size it will display it. In the name bar across the top of the screen, in addition to the file name you will see its resolution and a percentage value denoting the size it is being displayed at. If it is 50% then it is being displayed half its full size. Using the '+' and '' buttons you can zoom in and zoom out, thereby increasing the image's viewing size or reducing it. The '1' button will set the image to its original size while the buttons either side of it will fit the image to the window size available or reset it to its original displayed size.

Rotating:

The next four buttons rotate the image. The two curved arrows will rotate the image left or right through 90 degrees and the other two will flip the image either on its horizontal or vertical axis.

Disk Access:

The next four icons are all to do with file access. The first allows you to open an image file directly. The two disc icons allow you to save a file with its current name or save a file with a new name (saving will also save any changes you have made to the file). The dustbin allows you to delete the currently displayed image.

Preferential Exit:

The final two icons provide an exit icon for you to close the application. The remaining icon (second in from the right) is where you can make some simple rules for use with Image Viewer, especially in relation to saving and deleting images. It is here you can also set the Slideshow interval timer with one second being the fastest you can step through files. This is a good option to use if you have some time-lapse photographs to show that you may have created with your Camera Module.

GIMP

If you want to make changes to new and existing images and photos then you will need a program especially designed for the purpose. One of the most popular of these in the Linux world is called 'GIMP', and like much of the software we have looked at it is available free under a GNU licence. GIMP has a full graphical user interface which means you will need to run it from the Desktop. First though, you must download and install it via the command line. As always update and upgrade your installation and then issue:

sudo apt-get install gimp

The process takes a few minutes and you will see from the messages echoed to the screen when it is installing that it is heavily based around Python. On completion you will find GNU Image Manipulation Program (ie, GIMP) listed in the 'Graphics' tab of the Program Manager. When you kick GIMP into life you will notice that it goes through a complex loading process in which it looks for extensions and other add-ons for the program. One of the great things about GIMP is that you can add to what it can do by adding on additional software modules. This — and a lot of the functionality of GIMP — is way beyond the scope of this book, but here we will look at just a few useful techniques for editing files, and provide a basis for you to experiment further.

_Figure 27b. When loading, GIMP looks for additional add-on files and extensions._

When GIMP has finished loading it will leave you with three windows. The main window in the centre of the screen is the 'Edit' window. On the right is a 'Layers-Brushes' window and on the left is the 'Toolbox-Options' window. Like any other screen window you can re-size and re-position these to suit you and your monitor. You can also minimise the windows to keep them available but out of sight.

If you move the mouse pointer around over the windows (particularly in the 'Toolbox' window) as you move over an icon, if you pause a second you will get a small box displayed that will tell you what the icon does. Experimentation is a great way to learn so you should get some images (not precious ones — copies only) and be able to play around with them.

Remember you can use the Camera Module, if you have one, to take some quick images so that you can experiment with them.

Resizing An Image

You can open an image in GIMP in a number of ways. One is using 'File>>Open' from the menu and navigating to the file and another is by right clicking on the image and selecting 'GIMP'. When you have loaded the image the menu bar across the top of the window will display information about the file. Across the top of the window, drop-down menus will be listed and these provide access to a lot of the features of GIMP.

_Figure 27c. All in a row. Menus provide easy access to a lot of the facilities in GIMP._

To reset the size of the image go to 'Image>>Scale Image' and the 'Scale Image' window will pop up. This will contain the current width and height as well as the resolution measured in pixels. To the right of this you may see a small china icon. This is indicating that the two measurements are constrained so that when you change one the other will change in proportion to it, which ensures that the image does not get distorted.

_Figure 27d. Images can be reduced in size by using the Scale Image option._

By default, measurements are in pixels (Px) but you can change this to other units of your choice using the small drop-down menu available right there. You can use the control to change the value or you can simply click in one of the small boxes and type a value. When you press <ENTER> the other value will change accordingly to keep the ratio. For example, type 640 in the 'Width' box and press return. For my image the resolution changed to 640 x 418. Click the 'Scale' button to effect the change.

Cropping An Image

Another common task is the need to crop a photo, either to cut unwanted imagery from it, to focus on a particularly nice area or improve the overall composition of the image. Crop just means to cut away unwanted areas. Cropping for this purpose is performed using a straight vertical and horizontal edge, effectively defined by a rectangle you draw to enclose the area you are focused on, thereby excluding anything outside the cropped area.

You should always ensure you have a copy of your original file before you do any work on an image, just in case things go wrong. So making a copy is always the first stage in any edit process! Next load the image you wish to crop into GIMP and then from the 'Toolbox' window locate the 'Crop' tool. This is shaped like a scalpel blade — if you can't see it immediately just work your way through the icons because their function will be displayed as you click each one in turn. It will take a little while to know what each icon represents so now is as good a time as any to find out!

Position your pointer in one corner of the area you want to keep and then , with the left mouse button pressed down, drag out a square — called a _marquee_ — that roughly encloses the area that you wish to keep. If the marquee does not immediately appear give it a few moments — there is a lot of processing going on. Once it does appear the selected area is highlighted and the area that will be removed is darkened as shown in Figure 27e.

_Figure 27e. Although it may take a few seconds to catch up, the selected area to be cropped is soon very obvious._

You will notice that small boxes appear in the four corners of the selected area. If you move the mouse pointer into any of these boxes, you can click down and drag that corner of the box to re-position it. You can do this in any corner. If you want to move the whole box then click in the centre of the main box and hold the left mouse button down as you move the box around. Be careful not to double-click in the centre of the box as this will make the selection and perform the crop itself! If you happen to do this you can press <CTRL>-X to undo the action of select 'Edit>>Undo Crop Image'. All you then need to do is save your work to complete your edit.

Rotating An Image

When we get snap-happy we don't always remember the correct orientation for the photo as we move the camera around to make sure we get the fullest image in the view finder. This means that when we download the pictures a handful or more are often rotated through 90 degrees. This is not a problem and is easily corrected. Simply load the image in question, select 'Image>>Transform' and then slide the pointer to the rotation you required, as shown in Figure 27f.

_Figure 27f. Rotating an image will correct its orientation._

As with resizing an image, don't forget to save your work to reflect your changes.

More GIMP

The previous three operations are probably the most used by anyone who wants to undertake some minor editing on their images. However, it is only just the tip as to what is possible with GIMP. To find out more check out the official GIMP documentation website at: <http://docs.gimp.org/>
28: Games for Fun

Whether it is a Shoot em-up or a taxing puzzle to solve there are some really great games for all ages available to play on the Raspberry Pi. Here's a few to get you started!

In one of the opening chapters we looked at a number of games that were supplied and accessible from the Desktop using the 'python-games' icon. In fact if you look around the Internet you will find a lot of Python games popping up everywhere. Indeed as I mentioned in the Python programming chapter (Chapter 19) there are even tutorials you can download that culminate in really excellent games.

If you are looking for games then there are plenty available at the Raspberry Pi Store. I suggest that you have a look and see what is available both in the paid and free sections. You should also search 'Raspberry Pi Games' with your web browser search engine and see what the links bring. The MagPi website also has a list of games that have been tested with the Raspberry Pi. So there are plenty of sources.

In the following pages I've presented a handful of my favourites for you to look at and try if you are so inclined.

Minecraft Pi

Minecraft has become one of the most popular games of all time (54 million copies have been sold according to some sources). It is available on most computer platforms and with the September 2014 release of Raspbian, Minecraft Pi comes pre-installed and ready to use!

Minecraft is set in a world built from blocks that can be mined for their raw materials and turned into tools, weapons, armour and many other items. Many people just play on worlds randomly generated by the game itself, but others build and share custom-created worlds for adventuring. For example, the UK Ordnance Survey has created an accurate Minecraft map of England and Wales that contains more than 83 billion blocks representing over 220,000 square kilometres of mainland. I have some doubts whether this would load on the Pi Edition, not least because of the large amount of memory required to store the map. I've not tried but feel free to give it a go!

The Pi Edition has been specifically developed for the Raspberry Pi and is based on the 'pocket edition' of the game. It has two major features: the first is that it is free — it must be purchased on other platforms; second, it has an _application programmer's_ _interface_ included. This API allows users to write their own Python programs that link to the game, thereby allowing you to actively adapt their environment. This has made Minecraft Pi a popular teaching and learning tool. Using the API shouldn't present you with any problems at this stage of this _Insider Guide_ and there's an example 'how-to' shortly.

I'm not going to show you how to play Minecraft. There are plenty of books and articles on that subject, but I will provide you with enough information to allow you to have a look around and access the API to develop your own worlds quicker than ever before.

To get started with Minecraft, go to the Desktop and click on the 'Minecraft Pi' icon. If you are using an earlier version of Raspbian then you will need to install Minecraft via the Internet as follows:

Open a web browser and enter the following URL (all one line):

https://s3.amazonaws.com/assets.minecraft.net/pi/minecraft-pi-0.1.1.tar.gz

Click on the 'Download' button. This will create a compressed folder in the home directory ('/home/pi'). From the Desktop you can double-click on this folder and from the window that opens, select 'Action>>Extract' and then double-click on the 'Extract' button. The files in the compressed folder will be extracted into a folder called 'mcpi'. In your home directory, create a new folder called 'mcapi'. Then, in a Terminal window enter the following:

cp -r ~/mcpi/api/python/mcpi ~/mcapi/minecraft

This transfers the Python libraries you will need to a more accessible position. When creating scripts that use the API you will need to place these scripts in this mcapi directory. If you are running scripts from the Terminal then 'mcapi' should be your currently selected directory.

To run a downloaded version of Minecraft , open the 'mcpi' folder and double-click on the executable 'minecraft-pi' icon to run the game.

In all instances, the first time you run the program when you select the 'Play Game' button you will be asked if you want to create a new world. Confirm this and after a few moments you will find that you are within your Minecraft environment. Once here you can use the mouse to move around. If you want to get out of the Minecraft window and back to the surrounding Desktop at any time, press the <TAB> key.

Apart from the block scenery that surrounds you, you will also see a bar of nine boxes across the base of the screen. This is called the 'hot bar' and contains blocks and tools for you to use in the game.

Getting Around

If If you haven't played Minecraft before then one of the first things you will want to do is learn the keys and mouse buttons that will allow you to move around your world. Figure 28a below lists the more important of these. There's plenty of fun to be had just trekking about.

_Figure 28a. A selection of commands to use in Minecraft Pi._

When you press <ESC> it brings up a menu. Click on the 'Block Person' button to change whether you are viewing as the player or seeing the player. <ESC> to toggle back to the game.

If you repeatedly press one of the movement keys (W,S,A,D) then you will start to run. <SPACE> will make you jump. If you repeatedly press this key you can go into fly mode and holding the key down will keep you there. Pressing any of the movement keys (W,S,A,D) will allow you to control your direction of flight. Touching the ground or water will turn fly mode off. Double press the <SPACE> bar to descend to the ground. pressing <SHIFT> will make you descend if flying. In addition:

Left Mouse button: Clicking will swing whatever you're holding in your hand. This is used to attack other players and monsters. Click and hold it to break blocks, with your hands or specific tools.

Right Mouse button: Aim and then click the button to place a block anywhere around you. Click and hold the button to keep placing blocks if there is space available.

Scroll button: Scroll through the hot bar and click the scroll button to select the item.

Access the API

With Minecraft running, open a Terminal window. Next, open a new file in Leafpad. Give it a suitable name to try some examples:

api.py

will work.

If you are using the pre-installed Minecraft, enter the following script into the file:

import mcpi.minecraft as minecraft

mc=minecraft.Minecraft.create()

mc.postToChat ("Get ready to play!")

If you are using a version of Minecraft you have installed (using the process outlined earlier) then your import commands must always substitute 'mcpi' with 'minecraft' in all future scripts listed, thus:

import minecraft.minecraft as minecraft

Remember also that these scripts should be stored in your 'mcapi' folder.

These three lines are enough to allow you to interact with Minecraft Pi. The first line imports the API and creates a connection to the game itself and the second creates an object that allows you to use the postToChat() function to display a message on screen.

With the game open and running, go to the Terminal window and ensure that the directory containing the Python script is the currently selected directory. At the command line enter:

sudo python api.py

The message will appear on the screen for a few seconds. You can define the length of time it is displayed by importing the time library and using time.sleep() to set a limit, say 10 seconds. The script for this would become:

import mcpi.minecraft as minecraft

import time

mc=minecraft.Minecraft.create()

mc.postToChat ("Get ready to play!")

time.sleep(10)

Again, remember to substitute 'minecraft' for 'mcpi' if you have installed Minecraft yourself.

Location, Location, Location

There are four really useful features the API provides and you can:

  * find out where someone is.
  * change a player's position.
  * find out what material a block is.
  * change the block type.

The following script will get your current position and drop gold blocks on the ground as you walk around. Save this script as 'gold.py':

import mcpi.minecraft as minecraft

# or import minecraft.minecraft as minecraft

import time

mc=minecraft.Minecraft.create()

while True:

pos=mc.player.getPos()

x=pos.x

y=pos.y

z=pos.z

block=41

mc.setBlock(x,y,z,block)

time.sleep(0.3)

This script also shows that you can use loops and variables in the same way that you can in any normal Python script. The first line of the loop reads your position in the game in three dimensions and then copies these co-ordinates into x, y and z. The value of gold is 41 and this is assigned to 'block'. The 'setBlock' class is then used to drop the block at your current position.

To break out of the loop press <CTRL>-C in the Terminal window.

By creating your own scripts to engineer situations in Minecraft, you can go a lot further in the game a lot quicker. For example, you could create a command to erect a building either beside you or at co-ordinates you supply. By repeating the command you would instantly have two buildings. Imagine how quickly you could create a city in this way!

To see a full list of commands and details about classes available proceed as follows:

Open an interactive Python window:

sudo python -i

import the module:

import mcpi.minecraft as minecraft

and access its help:

help(minecraft)

Minecraft has proven its worth as a game and with the API in place it is sure to encourage games players to want to program and show their ingenuity.

Space Invaders

A space invaders shoot-em-up that works very well on the Raspberry Pi is XInvaders 3D. It's a wire frame game that runs in a Desktop window and is very reminiscent of the old arcade games of that style.

_Figure 28b. Keyboard control for XInvaders 3D._

It's quick and easy to install from the command line using:

sudo apt-get install xinv3d

You will then find that XInvaders 3D has been added to the 'Other' tab of Program Menu. The aim of the game is to clear all the alien's fighters in each level. If you hit a UFO you rack up bonus points of 500. The first row of aliens are worth 10 points each, the second row are worth 50 points each and each subsequent row a further 50 points on the previous row. Importantly you secure a new life for every 7500 points accumulated.

The game is over when the player has lost all their lives or if the alien formation reaches the player position.

The action keys and their function are listed in Figure 28b.

Penguins Puzzle

Penguins Puzzle is a solution-based game in which you use keyboard controls to move a penguin around on a sheet of ice and to the exit. The problem is that parts of the ice are very slippery and you can go sliding off the edge if you are not careful. The great thing is that the puzzle runs from the command line, fills the entire screen and is very colourful.

Penguins Puzzle is part of the Raspbian install so you can go to the command line and just enter the command to run it by typing the following at the prompt:

penguinspuzzle

If you get an error message when you enter this command then you can install the program using:

sudo apt-get install penguinspuzzle

Note that 'penguins' is in the plural and not singular. That confused me for a while!

_Figure 28c. It's very easy to end up in the drink!_

When the game starts you will see ice blocks and an exit sign. You have to guide the penguin to the ice block marked 'exit' and make your get away to the next level. Use the arrow keys to move around and when you get to the exit press the <SPACE> bar to move to the next level — there are 50 in all!

Figure 28d details the keys for use in the game.

_Figure 28d. Keys to control Penguins Puzzle._

Shoot-Em-Up

Geki2 and Geki3 are addictive 2D scrolling shoot-em-up games. I probably prefer the latter of the two as the images are bigger and easier to work with. The graphics are also nicer although the end result is essentially the same.

In both cases you can manoeuvre your space fighter around the screen as a stream of aliens head for you. Take them out before they take you out. The controls are the same for both games and are listed below. The commands to install the games are:

sudo apt-get install geki2

sudo apt-get install geki3

Figure 28e details the main keys for playing the game.

_Figure 28e. Keys to control Geki._

Figure 28f. Geki3 is a simple buy fun shot-em-up game.

Su-Do-Ku

Su-Do-Ku is a simple grid based game that works in the Shell or in an LX Terminal window. It is a version of the Sudoku game where you have to fill in the blanks with numbers, the one rule being that each row, column and 3 by 3 box contains the numbers 1 to 9.

To install the game use:

sudo apt-get install sudoku

And then type 'sodoku' at the command line to play the game. It is best to play using a terminal window so that your whole screen is not tied up. The instructions and key uses are displayed on the screen with the grid you are completing. The game level is random but if the level of difficulty of the game is indicated so if your game is too easy or difficult choose a new board and seek a harder or easier level.
SECTION SIX: OPERATING SYSTEMS

The Downloads page at the Raspberry Pi Foundation website lists just a few of the increasing number of Operating Systems being developed or ported for use on the Raspberry Pi. Experimenting with a new OS is an important stage in learning the different philosophies around programming and interfacing with users.

The _Insider_ skills you'll have at the end of this section will enable you to:

  * understand the unique way that RISC OS organises its files for use.
  * be able to use the Command Line Interface to access RISC OS system calls and fire up BBC BASIC.
  * install and configure Pidora.
  * use Arch Linux as a base to create your own customised distro.
  * add a Desktop to Arch Linux.

29: RISC OS

The Raspberry Pi world is not limited just to Raspbian, and I strongly urge you to look into and experiment with other Operating Systems that have Raspberry Pi specific distros readily available. If you want to broaden your horizons even further there is no better place to start than with RISC OS.

Despite being over 30 years old RISC OS is far from showing its age. In fact the arrival of the Raspberry Pi has given this great OS a chance to bloom and prosper. Although there have been a number of releases of RISC OS down the years the basic principles haven't changed that much, and the arrival of the Raspberry Pi has actually expanded its development to provide even greater opportunities for the would-be programmer. The software is still in active development and you can read about this from the official website which also hosts an active forum which is one of many. What's more within the UK, there are still annual RISC OS Shows both nationally and locally.

RISC OS runs using a window style Desktop which is light on memory and quick on speed. RISC OS looks and feels very different to Raspbian. If you have read the book through to this point, then much of what you have learned will still be pertinent. Whilst the specific software we have discussed so far may change, the fundamentals of operation remain the same.

RISC OS also comes with in excess of 4,000 pages of documentation and this provides access to the really strong feature of RISC OS which is the programmability of the Operating System. Although RISC OS supports many of the mainstream programming languages, there is limited support at present for the likes of Python, for example, after version 2.7. However, RISC OS provides access to innovative new boutique type languages such as RiscLua and Charm, and another long term favourite (certainly of mine) BBC BASIC.

As new hardware comes along for the Raspberry Pi, the RISC OS community always responds with suitable software to fully enable its operation on a number of levels. I mentioned the programmability of its Operating System — this is enhanced by the ability of RISC OS to be expanded with the addition of _modules_. These are specifically written blocks of software which slot into the Operating System seamlessly to provide additional functionality.

RISC OS does do things a little differently. In this chapter we'll have a look around RISC OS and I'll try to guide you through its eccentricities and make the process a little easier for you.

The process for downloading the RISC OS distro and installing on your SD Card is no different to that for Raspbian or Raspxmc. However, before you go forward and run RISC OS you will need to make sure you have a three-button mouse! In actual fact a two button mouse with a scroll-wheel in the middle is a three-button mouse so any normal PC-style mouse should do.

The purpose of each 'button' is a little different from other distros and is detailed in Figure 29a.

_Figure 29a. RISC OS three-button mouse, key actions._

Up and Running

The first thing you will notice is just how quickly RISC OS boots. In just a matter of seconds you should find yourself at the RISC OS Desktop screen. RISC OS does not require you to go through a configuration screen before you start. However, there are some housekeeping tasks related to your location and setting up Internet access that you will want to sort out, and we'll look at that shortly.

The main RISC OS screen is called the Desktop. As Figure 29b shows it is colourful and easy to navigate. You will immediately notice some icons running down the left hand side of the screen, and also the 'icon bar' across the full width of the base of the screen. In the icon bar you will see there are icons on the left and right hand side. As a general rule of thumb, file systems (called the 'Filer') and related items are located on the left and applications are on the right. Again the icons reflect this as well. Finally in the centre of the screen will be a browser window with some welcome text inside it and a few links that jump to text within the document being displayed.

_Figure 29b. The RISC OS Desktop is bright and colourful._

One big change from other Operating Systems you may have used is that there is no 'Start' or 'Finder'. Generally the things you want are accessed from the icon bar. For example, applications are found in 'Apps' (an icon on the left of the icon bar). Click this to open a window and you can see various applications that can be run. Double-left-click on the '!Alarm' icon and notice that a clock appears on the right side of the icon bar. Generally, when you open an application, you might have expected a window to open on the Desktop instead. If you left-click on the Clock then a window will open and in here you can set an alarm and provide a message by editing the boxes in the window. Click 'Cancel' to exit the window. With the mouse pointer still over the clock, click your middle button (this might be the wheel) and you should see a pop-up menu. This action is called a 'menu click' for obvious reason. You can check out the various options here or select 'Quit' to exit the '!Alarm' application.

Remembering that context-sensitive menus are via the middle button and that launching an application invariably (though not always) places it on the icon bar, are a couple of the things that often make RISC OS seem alien to other users. But once you get the hang of it, it is very simple. Figure 29a outlined the function of the three mouse keys under RISC OS. In summary:

Left (Select) clicking is just like any other system. You perform actions by clicking, double-clicking and dragging with the left button.

Right (Adjust) clicking usually performs some variation of the left click action. For example, left clicking on a menu item will select that item and close the menu, while right clicking will select the item and keep the menu open.

Middle (Menu) clicking opens a 'context sensitive' menu of things you can do. Typically, this menu is related to whatever was under the mouse pointer at the time you opened it.

RISC OS Desktop windows are generally utilised in the same fashion as other desktop systems, although the close 'X' is located on the top left rather than the top right.

Configuring

You can use the '!Configure' window to set up your RISC OS-driven Raspberry Pi. This should be an icon to the upper left hand side on your Desktop so just double-click on it to open the window.

Click on the following icons in the 'Configuration' window and edit each one accordingly. There are only three you need to change initially, but if you look at the other options available you will get an understanding of how configurable RISC OS is.

Keyboard:

This is set to 'UK' by default. Click on the small button to the left of the window saying 'UK (Default)' and you will get a long list of country options to choose from. Scroll to the one of your choice and select it. There are other options you can change if you wish. Click the 'Set' button to confirm and exit.

Mouse:

Not essential to change anything here but you might want to adjust your mouse speed.

Network:

If you have Ethernet cable access to the Internet you can configure options here. Click here, select the 'Internet' option and then ensure the 'Enable TCP/IP Protocol Suite' is checked. When you close and save these options you will be invited to reboot RISC OS to implement them.

Unfortunately there is no USB Wi-Fi dongle support for RISC OS, so unless you have access to a Wi-Fi Ethernet bridge, this option is not currently available.

Time and Date:

It is straightforward enough here to select your settings and also to set your locality from the long list that pops up.

The Filer

The Filer is the name given to the filing system manager in RISC OS. On the left hand side of the icon bar you will see an icon of an SD Card with a ':0' below it, similar to that shown in Figure 29c.

_Figure 29c. The left hand side of the icon bar contains icons to access discs and disc drives in RISC OS._

Left click the 'SD Card' icon and a window opens revealing a number of folders. These folders are directories on the SD Card and you can open and interrogate each of them as you wish. The '!Boot' window is a different colour because it contains more applications — in fact it contains the '!Configuration settings.

Figure 29d lists each of these folders and gives you an indication of what is inside. We'll go through each of these in more detail later in this chapter. The one to note at the moment is 'Public' as this is empty and is a place where you can create your own folders and files.

_Figure 29d. Folder contents of the SD Card._

As you will have already gathered, RISC OS supports the same hierarchical filing system as Raspbian — and all other Operating Systems for that matter. You can move down the structure by clicking on nested folders. For example click on 'Documents', then 'Books', then 'First Steps Programming' and you will have three windows open on top of one another. RISC OS opens each folder in a new window. If you don't want to open three windows but want to replace the old window with the new one, then rather than left-double-click, do right-double-click. Here's the good thing — if you want to go back to the previous window, you don't have to close and start again. You can move back up through the folders using right-close-window. That is click the 'X' in the window with the 'adjust' button. You can also move up a window by middle-clicking in the window and then selecting Open Parent from the ensuing menu.

Although you can find all the normal buttons on a window — to minimise, to maximise and close — there is a fourth one (far top left-hand side) that when clicked will move the window to the back of any already open windows, that is to the bottom of the pile.

The Filing System

In our discussion of Raspbian we learnt about the filing system and how to use it in a variety of ways including issuing commands from the Shell to create directories and list files. RISC OS has its own equivalent of the Shell and we'll be dealing with that in the next Chapter.

However, there are many types of filing systems and different systems use different formats. The way each Operating System stores data on the disk (or the USB Stick) is very different. However, because of the popularity of these filing systems most are capable of being read by one another. RISC OS can certainly read disks or sticks formatted for a Raspbian filing system such as FAT32.

The display of files and directories (folders) on the Desktop, and also the functionality to interact with them is provided by the Filer. The filing systems which are most intensively used on RISC OS Pi are the SD Filing System (SDFS) and the Fat32 Filing System (Fat32FS). These two filing systems deal with the SD Card and with any flash drives or external drives that you might plug into the Raspberry Pi USB ports. If you take a USB Stick that you have used with Raspbian and insert it into your Raspberry Pi, you will see the icon for a USB drive appear to the right of the icon bar.

The naming of files must obey certain rules in order to allow filing systems to operate in a consistent way. The Filer makes no distinction between upper and lower case filenames, so a file named 'Letter' is the same as 'letter' or 'LETTER'. You cannot use punctuation characters as part of a filename as these have special meanings. if you use them by mistake you can expect error messages to result. In RISC OS the root directory is denoted by the dollar symbol '$'. Each disc device, whether it is floppy or hard, has a root whose real directory name is the name of the disc. It is important to note here that the root directory of RISC OS, whilst being positioned at the same point in the file structure, does not carry with it the super-user privileges as in Raspbian. As such in RISC OS the super-user user does not exist.

Thus the disc name (preceded by a colon) can usually be used interchangeably with the dollar symbol to refer to the root directory.

_Figure 29e. Punctuation reserved for use in pathnames, and its meaning._

The Currently Selected Directory (CSD) is represented by the '@' symbol.

Files within the CSD may be referred to by their name alone; files in other directories must be referred to by a name sequence which uniquely identifies them. This is known as their _pathname_.

The pathname is formed by stringing together the appropriate sequence of directory names connected by full stops. Thus, a file called 'Prog10' in directory 'Programs', which is itself located in the directory called 'Book' which is in turn a sub-directory of the root has the full pathname:

$.Book.Programs.Prog10

The more dots in a filename, the deeper in the directory structure you are going. The rightmost item in the list is always the filename.

If you open the SD Disc window by double-clicking on the icon, and then in turn open 'Documents and PRMs', you will see in the yellow title bar across the top of the window this address:

SDFS::RISCOSpi.$.Documents.Books.PRMs

Note the two colons.

The address starts with the filing system and then is followed by the OS specification and then the actual address in the root directory.

The other reserved punctuation symbols noted earlier have special meanings when used in pathnames. These are listed in Figure 29e.

You refer to files on other filing systems in exactly the same way, after first defining the file system:

FAT32FS::USB1.Book.Programs.Prog07

This refers to the file 'Prog07' which is in the sub-directory 'Book.Programs' on the disc entitled 'USB1' which is mounted on the FAT32 Filing System. Note that here two colons are required, one to follow the filing system name and the other to precede the disc name.

Folders and Files

Creating folders is simple. Open the SD Card and then locate the 'Public' folder and open this. The 'Public' folder is where you should save all your work to. This isn't a hard and fast rule, but it makes sense to stick to it rather than having them stored all over the place.

_Figure 29f. Creating and naming a new folder._

Place the mouse inside the folder and press the menu (middle) button. This provides you with a selection of tasks that you can perform here, for example 'New Directory' creates a new folder. As you move over this it becomes highlighted and you will notice a small arrow — move off to the side and you have a naming box where you can use the keyboard to name your new file. Type the name you require and press <ENTER> or click on the 'OK' button. You can move folders around simply by dragging them as you would using the Raspbian Desktop.

To perform operations on a folder, click the menu button on the mouse to bring up a list of options. The first of these will be 'Display'. Slide off the side of this option (in the direction of the arrow) and you can change how the directory and file information is displayed. Select 'Full Info' for a listed display. The option below this provides functions that act on the directory and this includes the ability to delete it, rename it, or set read/write access options. With your knowledge from using Raspbian you should have no problems understanding these and should feel confident experimenting with them.

The 'Set type' option allows you to set the file type of files and we'll discuss this in the next chapter. The 'Set directory' option forces the chosen directory to become the current working directory.

If you drag a folder (or file for that matter) onto the desktop it will stay on the Desktop. Clicking over it then has the same effect as if clicking over it in the directory window. A double-click on a file (or dragging it onto an empty part of the icon bar) causes it to be run and its file type will determine the application that is used for this. There is no 'Load' option available in applications — another unique feature of RISC OS.

Here is one point to bear in mind with regards to programs or scripts you may come to write in due course. Double-clicking on the script or program file will cause it to be executed, or run. If you want to actually load the file into an associated editor you must <SHIFT>-double-click it, in other words hold down the <SHIFT> key when you double-click it.

!Applications

You may have noticed that all the items in the Apps window begin with an exclamation mark — which is called a _pling_. Open the Apps folder and locate the '!Alarm' icon which we encountered earlier. You know that double-clicking on this icon will place a clock on the icon bar. If you try and click it again you will get a message say it is already running. This is not always the case as you can have several instances of the same program running side-by-side, which is called _multitasking_.

Now move the pointer over the '!Alarm' icon, hold the <SHIFT> key down and double-click. A window opens. Inside the window are three icons, '!Help', '!Run' and '!Boot'.

An icon that starts with a pling ('!') is an executable directory! Double-click on '!Help'. This will launch a window which contains information about the application. Look at the '!Boot' and '!Run' icons and the image has 'Obey' in it. These are Obey files which are RISC OSs versions of executable scripts. <SHIFT>-double-click on either one of these files and you will find the script opens in a window for you to inspect. Obey files contain commands that the OS will act on. You might want to spend some time in other directories examining the '!..' directories to see what other applications may contain. For example, try '!PDF' in the 'Utilities' directory.

So, generally speaking, in RISC OS an application contains all of the files it requires. '!Alarm' has three files; others may have more or less. In Raspbian, files may be located in many different folders and may require special sudo-style privileges for you to access them.

As you get more experienced, it becomes easy to create and write your own applications using this arrangement.

The Big Raspberry

You may be itching to know what the Raspberry icon on the right of the icon bar is for. It's called the 'Switcher'. If you double-click on it, you will get a 'Tasks' window displayed. This is a graphical representation of all the things that RISC OS is doing at that moment — its tasks. It shows how much memory is being used by each of them.

If you menu-click the Switcher then you will get a list of items, the first showing details about the version of RISC OS you have, while another takes you to the 'Configuration' screen. A third provides you with access to the 'Task Manager' (coming up in the next chapter) and the final option provides you with the safe way to log-out of RISC OS and shut down.

Bundled Software

RISC OS comes with plenty of pre-installed software and many of these applications have been around for some time so they are very familiar in the RISC OS world. They are also very sophisticated which is sometimes overlooked because of the clutter-free nature of their interface. Here's a quick look at some of the things what you can find in the Apps directory, but don't take it as a complete guide. Remember that when you launch an application it opens on the icon bar rather than in a window on the Desktop.

Paint can be used for editing bitmap images. Paint is more than capable of cropping and tidying images such as photos. This includes rotating and scaling the images.

Draw is a vector-based graphics application which you can use to create fully scalable images for use on their own or in other applications. It provides a set of tools for calculating, transforming and rendering lines, polygons, bezier curves, sprites and text.

There are some files in the '$.Documents.Images.Backdrops' folder which you can load as backgrounds to play with in both Paint and Draw.

For converting between image formats and for re-sizing images, the '$.Utlities' directory contains a program called 'ChangeFSI'. This can read a wide range of file types, and is able to save as a JPEG. The RISC OS file format 'sprite' is the RISC OS equivalent of the Windows BMP format.

Maestro is a simple, easy to use music application based around writing a traditional score. The '$.Documents.Music.Maestro' folder contains scores that are ready to use. Once you select the 'Play' option from the menu, it takes a few seconds to start-up.

_Figure 29g. The StrongHlp manual for OS SWIs_

PipeDream is a fully functional spreadsheet that comes with a whole host of tutorials and examples in the '$.Documents.PipeDream' folder. Edit is a simple text editor program that can be use to create files in a variety of file formats. You select the file format when you create a new document or script. StrongED is a programmer's text editor and comes with a rich set of features which we'll look at a bit more in the next chapter.

The 'Diversions' folder contains what essentially amounts to games. Douku is a good version of Sudoku and allows you to set the difficulty level when you start a new game. Patience is the popular card game of the same name, and Blocks is effectively Tetris. If you want a bit more action then try Meteors, the asteroids look-alike of the popular arcade game.

The 'Utility' folder contains useful applications such as PDF which will open and display PDF files and PrivateEye is an image viewer and ChangeFSI I have mentioned.

In addition to the 'Documents' folder which contains pdf files there are also programming references via the !StrongHlp applications. Open the Apps folder and launch '!StrongHlp'. Double-click the icon to reveal a directory of files. Clicking on one of these will open a window containing hyperlinks to the text inside. StrongHlp is also a simple hypertext authoring program which you can use to create your own documentation..

That's really a quick look around and I would encourage you to take some time and check out the folders one-by-one and see what you can find. There is plenty of documentation supplied with RISC OS, so let's look at just that.

Other Software

There are a couple of ways in which you can access a vast library of software — a lot of it free. The gateway to this is through the '!PackMan' and '!Store' icons on the Desktop.

PackMan is a simple, clever and easy way to add software to your setup and ensure that you have the latest releases and updates. It does this by maintaining lists of software, and you should ensure that these lists are up-to-date by selecting the 'Update Lists' option from its icon bar menu. Once PackMan has checked their status you can choose to 'Update all' if you wish and Packman will take care of the process for you. By using Packman you should never have to download and install software by hand.

By scrolling through the alphabetical software list in Packman you can get descriptions of the programs and can see if updates are available. There are whole libraries of programming languages you can download, along with a variety of software.

'!Store' allows you to search other third party software, both free and paid for. You can search this by catalogue or simply by looking at the list in the store window. You can choose to create an account (needed if the software is not free and must be for purchased) or simply to download the application by clicking on the name.

Documentation

I would estimate that there are well in excess of 5,000 pages of professional documentation supplied with RISC OS. (My editor calculates this would be over a million words!) This documentation can be found in the 'Books' folder on the SD Card, at '$.Documents.Books'. Inside here you can find _First Steps in Programming RISC OS Computers_ , which is a guide to using BBC BASIC. This was originally written for pre-Raspberry Pi implementations of BBC BASIC so it is not entirely compatible with this device, especially when it comes to using the graphics elements of BBC BASIC, due to the way that the video display is handled. There are ways of getting around this and you will need to go searching for them via the forums and blogs.

_Beginners Guide to Wimp Programming on RISC OS Computers_ is a great text for learning about the Wimp. The Wimp is the Desktop element of RISC OS — containing Windows, Icon, Mouse, Pointer. It is quite advanced, but something to look at as it might stimulate your interests in this area. It comes with the same proviso as the previous book in regards to graphics.

The _Programmers Reference Manuals_ or PRMs contain absolutely everything you could want to know about programming RISC OS and how RISC OS works behind the scenes. These really are the ultimate reference books but take some getting around. I wrote _Raspberry Pi RISC OS System Programming_ to provide an introduction to programming RISC OS and also as a more gentler introduction to the PRMs. See Appendix B for more details.

The '$.Documents.Others' directory provides documentation for some of the utilities supplied including 'PrivateEye'. Again lots of useful reading matter here. In addition, many of the other folders contain manuals and documents relating to applications. I mentioned 'PipeDream' as one before.

Also don't forget the '!StrongHlp' manuals. When you download new utilities you will probably find associated '!StrongHlp' files with them.

Desktop to CLI

This chapter has been a quick introduction to the RISC OS Desktop, and there is plenty more for you to explore. Next up it's time to look at how RISC OS can be used from the command line — using the Command Line Interpreter or CLI.
30: RISC OS from the CLI

As a programmer's model RISC OS is the perfect example of the way things should be done. Written as a series of modules, every facet and feature of the Operating System is available to the user, making programming at every level easy and consistent.

In amongst the PRM manuals you will find a PDF file called 'Style'. This defines all aspects of how a RISC OS application should look and feel. It provides a template for developers and ensures that programs are written 'legally', meaning that they don't break fundamental rules and also to ensure they all operate in the same way. This is also how RISC OS itself works in that you can access any part of it, and if you pass it information in a particular way, it will return results to you accordingly. This is at a much deeper level that I intend to go in this chapter, but it is an important philosophy to bear in mind should you wish to delve even deeper into RISC OS.

However, if you intend to program using a language such as BBC BASIC or C in RISC OS, it means that you can access all the features of the Operating System from these programs. This accessibility is fundamental to RISC OS and all the languages it supports and that you use on it. The top level of these commands is '*' (pronounced 'star') commands.

Task Window

The Command Line Interpreter (CLI) provides direct access to '*' commands from the Desktop. The CLI is the RISC OS version of the Shell. To access the CLI open the 'Switcher' menu (the Raspberry Pi icon on the icon bar) and select 'Task Window'. This will display a task window which in turn will display a '*' as a prompt indicating that you are in '*' command mode.

To enter a '*' command at this point, simply type the command. There is no need to include the '*' for a second time — this is taken as implicit as you are in the RISC OS environment. For example, typing:

COUNTRY

will return a message displaying the country setup in use. You can also pass a parameter with this command to change or set the country preference thus:

COUNTRY USA

This will set RISC OS operation to USA preferences (keyboard, dollar signs, date format etc).

Note that '*' commands are keyboard case independent and thus:

*COUNTRY

and:

*country

are treated as identical, so either is acceptable. If you enter them, leading spaces are ignored. However, within a command ading additional spaces can create an error in its execution.

Essential '*' Commands

RISC OS provides '*' commands to allow access to files and directories, and these utilise the same hierarchical structure that we looked at in the previous Chapter. Here's a look around some of the more essential of these commands. They operate very much like their counterparts in Bash, so the action should be familiar to you. In these cases you are interested in learning the syntax differences.

To catalogue the current directory type:

*CAT

The first four lines provide information about current settings and then show the contents of the directory. The directories here are signified by the 'D' in the listing. You can catalogue a particular directory using the path name:

*CAT $.!Boot

This will list the contents of the '!Boot' directory. Here the files are listed with their read/write status signified, eg:

!help WR/

which shows that the file '!Help' is both readable and writable.

If you want to change directories then you use the '*DIR' command followed by the file path of the directory you want to be the currently selected directory:

*DIR $.Public

This would set 'Public' as the CSD. If you now enter '*CAT' notice how the first two lines of directory information have changed to reflect where you are.

To create a new directory use '*CDIR', as in:

*CDIR Work

Where 'Work' is the name of the directory to be created. You can use the file path to create directories lower in the hierarchy:

*CDIR Work.Docs

This would create a directory called 'Docs' in the 'Work' directory.

The '*DELETE' command will remove the named directory or file. In the case of a directory, the command will not work unless the directory is empty.

*DELETE Work.Docs

This removes the 'Docs' directory.

Many '*' commands can accept multiple parameters as well as options to specify how you want a command to work. The '*COPY' command is a perfect example of this. The syntax for the command is:

*COPY <source> <destination> {<options>}

This is a general-purpose file duplication command. It requires at least two parameters: a source specification and a destination specification (both of which may contain wildcards) and it then copies all the specified objects from the source to the destination. For example:

*COPY $.Documents.* $.Backup.Documents.*

Here all the files in '$.Documents' in the current filing system are copied into '$.Backup.Documents', preserving the names of the files as the process takes place. Here the asterisk is used as a wildcard meaning 'all'. This example assumes all the directories exist.

A range of options may be appended to the '*COPY' command:

*COPY Here There ~RV

Specifying an option prefixed by '~' causes the option to be de-selected and the corresponding action is not taken. In the above example, we specify that a recursive copy (R) is not to take place but that we want to force verbose mode (V) to be selected. The other options revert to their default settings.

To find out what options are available for a command you can look in the PRMs or use the comprehensive '*HELP' command thus:

*HELP COPY

which would list information about usage and options for the '*COPY' command. The '*HELP' command displays help text on topics whose keywords are provided. You will find this a quick and easy way to get initial and syntax information on any aspect of the '*' commands.

The '*EVAL' command evaluates the expression supplied and displays the result on screen. For example:

*EVAL 255+1024

The result is an integer, value: 1279

Logical operators may also be used by using the shift operators. Thus:

*EVAL 2 << 3

This would shift 2 left by three places to give the response:

Result is an integer, value : 16

Operators may be mixed within commands to provide more complex operations:

*EVAL 12+4*5-4

This would result in 28. Note that this arithmetical operation has the multiplication evaluated first. Brackets can be used to force the order of solution:

*EVAL (12+4)*(5-4)

Here the result is 16.

RISC OS supports the action of 16 function keys. Each function key can be assigned a command line string, so that when a function key is pressed the string assigned to it is executed.

For example:

*KEY 1 *CAT|M

This sets up function key F1 to issue '*CAT' when pressed. The ' |M' (note the bar) is interpreted by RISC OS as the <ENTER> key. Function keys are good for saving long but frequently used key sequences — changing directories is one useful application of them. A hard reset (cycling the power) will reset all '*KEY' definitions, but they should survive a soft-reset (rebooting from the task menu).

Aliases

The 'ALIAS' operator can be used to create a new command or re-adjust how a particular command is used for your own needs. One simple need might be to correct an error you always make when typing. If you always type:

*CAY

instead of:

*CAT

(an easy mistake because the 'Y' is next to the 'T' on the keyboard), you can create an alias so that when you type:

*CAY

then:

*CAT

is executed automatically for you. To create a pseudo-command called 'CAY' that executes 'CAT', you use the '*SET' command thus:

*SET alias$CAY CAT

This alias method makes it possible to define command names that you personally prefer to use as alternatives for the built-in names. Note in the alias definition the star is not required and is implicit in the operation.

The syntax used to define an alias is therefore:

alias$name

In the above line 'name' is the name of the alias you wish to add which can be made up from any of the alphanumeric characters as well as these others:

! ' ( ) + – . ; = ? @ [ ] _ ' { } ~

The alias may also be followed by up to ten parameters which can be used to act as placeholders for information that may not be known at the time of defining the alias. These pseudo-variables are labelled '%0' through to '%9' and are used as placeholders within the alias definition. When the alias is then called a value can be specified after it on the command line and this is substituted into the pseudo-variable:

*SET ALIAS$ASCII ECHO |<%0>

This would print the character represented by the number stated after the alias command. So

*ASCII 65

would print an 'A' on the screen.

You can remove an alias definition at any time using the '*' command UNALIAS. For example:

*UNALIAS ASCII

BBC BASIC

BBC BASIC has a lot to answer for. Thirty years ago when the BBC Micro was launched it was your go-to place from which you could enter programs or type '*' commands. It might surprise you to know that parts of RISC OS are written in BBC BASIC, and there are numerous extensions to it that can make programming it a fun process. It is not Python, so it is probably not politically correct, but it is forgiving and, I think, a good learning tool.

It's easy to start BASIC. In the Task Window just type:

*BASIC

You will get feedback that you are up and running and the '>_' is the prompt.

Because you are now in BASIC if you want to type a '*' command you must include the '*' otherwise you will get 'Mistake' fed back to you in return. BBC BASIC is quite blunt with its error messages!

Try this:

PRINT "Hello World"

Your typing must be accurate and the 'PRINT' command must be all upper case. Press <ENTER> and the result is there to see.

If you want to have a play with BBC BASIC then perhaps try working through some of the opening chapters of _First Steps in Programming RISC OS Computers_ which are located at '$.Documents.Books'. The opening chapters of this should be very straightforward for you if you have worked through the Programming section of this book.

Alternatively you might wish to look at or maybe modify existing programs. For example, go to '$Pprogramming.BASIC.Routine' and double-click on the file 'FontTest'. This will run and will display some of the fonts available on RISC OS. You can open this file in 'StrongEd' by <SHIFT>-double-clicking it. Again, if you worked through the Programming section of this book you should feel quite comfortable about trying to modify the program to see the effects.

'StrongEd' is a full-feature programmer's text editor that is surprisingly easy to use. It can be used to edit just about anything and can do this in the context of the filetype being edited. This means that you can create a BASIC file and 'StrongEd' will treat it like a BASIC program, saving it in the correct format. In this way you can also run the program from within the Editor so that you don't have to go to a BASIC task window, load and run it, before retreating back to make any corrections.

Modules

In the early days of home computers memory was at a premium and expensive and so system software was burned permanently into Read Only Memory. ROM chips were fitted making the OS available immediately on start-up. As modern manufacturing techniques have dramatically reduced the cost (and size) of volatile memory (RAM), the use of burned-in memory has become almost redundant. Operating Systems can be loaded into RAM in a matter of seconds.

RISC OS Pi is a memory-based Operating System. On start-up the RISC OS ROM image stored on the Raspberry Pi SD card is loaded into the memory on your Raspberry Pi. This provides the basic Operating System and to a large extent has remained unchanged down the years, at least from a user's point of view.

However, RISC OS has been enhanced and extended, no more so than with the release of RISC OS Pi. The additional functionality has been provided by supplying extra system code in the form of Relocatable Modules.

Modules allow RISC OS to be extended and enhanced. Modules can add applications, services or functionality to RISC OS and the Raspberry Pi in general in a well-defined and structured way. These additions can be in the form of new command sets, languages or software to control hardware connected to the Raspberry Pi. Something like the GPIO Module is a good example of this. It can be downloaded and installed using PackMan and allows easy access to the GPIO — the General-Purpose Input/Output interface on the Raspberry Pi to which you can connect and control external devices (discussed in Chapter 34).

One of the most important things about modules is that they do not need to be physically installed in the computer; they are supplied as software and RISC OS maintains an area of memory exclusively for them — the Relocatable Module Area. Modules can be added as required and also removed when not required. If you want to see a list of all the modules installed use:

*MODULES

Your list may be different or it may be identical. Either way do not worry as installed modules come and go depending on the software and hardware that you are using. If you examine the list you will see a lot of names that are probably familiar to you. Applications such as '!Paint' and '!Draw' are implemented as modules. You can use the '*HELP' command to find out more about each module.

FileTypes

RISC OS uses a file's file type to decide what action to take when it accesses a file. You can use '*SHOW' to display the current settings for file types. Figure 30a below shows the original range of file type allocation sets denoted by Acorn who was the originator of RISC OS.

_Figure 30a. File Type allocation ranges._

Note that the '&' signify's a hex number under RISC OS. The minimum requirement for a valid allocation is that double-clicking the file loads an application specified by the assigned RunType and does something meaningful with it. The '!Typeinfo' website keeps an unofficial database of file types and it is worth having a look at it to see what is available. You may be surprised!

Where Next?

If you want to find out more about RISC OS then I would suggest you make regular visits to the ROOL website at www.riscosopen.org. ROOL manages the source code to RISC OS and is an organisation run on an (almost) voluntary basis. By exploring the pages here you will find out what new things are planned for RISC OS and you can even have a say in them yourselves. The forum pages are active and a hive of information. The website also has a growing reference section and is a great place to get questions answered.

There are a number of active user groups, especially in the UK, and these organise shows at least once and often a couple of times a year. Search the Internet for these and also check out: <http://www.acornarcade.com>
31: Pidora

Pidora is an Operating System based on Fedora which is itself a derivative of Linux and illustrates how one set of developers has taken that original kernel and moved with it. Like Raspbian it supports both a command line and a Desktop environment.

Pidora is free and community-supported, and the Fedora Project on which it is based has gained a reputation for focusing on innovation. However, as with Raspbian, the Pidora Desktop (called 'XFCE') and which looks very different to its Raspbian counterpart is pushing the Raspberry Pi to its limits.

The first time you run the software you will need to go through the configuration process. Using the 'Forward' and 'Back' buttons on the screen you can set up your keyboard, time zone and date simply enough. Pidora lets you define your own user name and password and you are given the options of making the user part of the Administrators group. You also set the root password separately. It's up to you what you use here, The common approach might be to use your name (one word) as your user name. You could of course go with 'pi' and 'raspberry' as per Raspbian if you want to keep consistent across your OSs.

The 'System Settings' screen lets you select what environment to switch into — either a graphical GUI or a command line. If you go with the latter then you can switch to the Desktop display by typing 'startxfce4'. To my mind the GUI for Pidora is less brash than the Raspbian version but certainly a little slower. Finally you can select the HDMI output you require. I have passed over a few other options which are more advanced and which you can come back to at a later stage from the 'Settings' menu available from the Desktop.

XFCE

The Desktop itself is called 'XFCE' and is a collection of programs that together provide the Desktop environment. This includes 'Window Manager', 'Panel', 'Desktop Manager', 'File Manager', 'Session Manager', 'Settings Systems' and 'Applications Finder'.

The bar across the top of the screen is called the 'Panel' and this contains a number of drop-down menus and buttons to access the components of Pidora. Top left is the 'Applications Menu', which you can relate to Raspbian's 'Program' menu. You will find some familiar programs from your time in Raspbian.

One of the items accessed from the Application Menu is the Settings menu and you can further fine tune your configuration. The 'Application Menu also provides the 'Log Out' option to finish your session.

The File Manager is shown in Figure 31a and this shows what should be a familiar structure in root. The pane at the side also shows that I have set the system up with my names as my user name. The 'Home' folder is set up already with a number of directories in place such as 'Documents', 'Misc', 'Pictures' and 'Video'.

_Figure 31a. The File Manager window open at root._

The top right of the screen provides access to three other Desktops as well as a dedicated shut-down menu. The bottom panel is configurable and is where you will find 'Terminal' amongst other things, which includes the 'spy glass' icon. Click this to open up the Application Finder from which you can locate programs by names and grouping. This is quite a good tool to play with as you find out what Pidora offers.

Software updates and removal can be performed from the Desktop via the 'Administration>Software Update' and 'Administration>Add Software' and '...Remove...' options.

Pidora Command Line

Although the Pidora command line operates in a very similar fashion to the Raspbian one, there are subtle differences that you will need to familiarise yourself with.The 'h' options for commands can assist in this as well as the Fedora related websites.

For example, package management is similar but utilises the 'yum' interface. The 'Yellowdog Updater Modified' uses repositories and caches information like 'apt-get' from a user's point of view. The the most common yum commands and their action is listed in Figure 31b:

_Figure 31b. A selection of yum commands for use on the command line._

You can get information regarding yum using:

yum —help

To install this software you need to be root. If you try any of the above it will give you an error message to that effect. To switch user to root use:

su root

You will then be prompted for your root user password.

Pidora also contains extensive command line help in the form of manual pages and you can install these using:

yum install man -y
32: Arch Linux

Arch Linux is a minimal Linux system for the Raspberry Pi and contains only the bare essentials. It is an ideal starting point if you want to develop your own distro to meet your personal requirements. As a project it is an educating way to understand Linux in greater depth.

Arch Linux does not have any software installed that is not required. For example, you will not find a Desktop environment available to you (although you could install one) but you will find the text editor Nano.

You would use Arch Linux for a number of reasons: Firstly, with a specific application in mind — one that you want to build and create for yourself. Secondly, to create a distribution that is specific to your needs, and may in reality end up being a minimal version of Raspbian. And thirdly, to readily learn about using the command line. The second and third items sit nicely together and allow you to build something from the ground up. You would learn a lot by developing your own environment, assembled by installing only what is required or desired for your unique purpose.

Arch Linux boots very quickly. In a few seconds you are at the login prompt. The user name and password at this stage are both 'root'. The prompt 'alarmpi' — is not a warning but broken down is 'al arm pi', meaning Arch Linux ARM Pi.

If you type 'ls' t the prompt you will not get any files or directories listed. Type:

ls /

And you will see the root directories listed.

Connecting to Wi-Fi

If you have an Ethernet cable attached you should have immediate access. However, that is not the case if you are using a Wi-Fi USB dongle. Use the command:

wifi-menu

This gets you going, but does not survive a hard boot.

From the command line enter:

netctl list

The 'netctl' command invokes the Network Profile Manager. This will provide a list of current networks in range. The one that you selected above should be listed with an asterisk next to it. Note this name. On my system it is '3Net', and use it in the command line thus:

netctl start 3Net

This will load a window that will display any networks local to you. Select the network you want and then click <OK>. You will then be requested to enter a name or the new profile you have created — you can keep the default one or enter your own. Then you will be requested for any security key, so enter your network password here. Setup will take several seconds (so be patient) after which your prompt will return.

You can locate your settings for your network connection in the:

/etc/netctl/

directory. The filename will be that of your profile ('3Net' in my case).

This will contain not just your network name but also your network password in a plain text format — so anyone with access to your root directory can find out what your password is — a reason to protect yourself as a root user.

If you want to access an alternative network then you can do so by defining the new profile and then copying the information from this file and editing the network name and password settings directly as required.

Setting Zone and Time

Once you are connected to the Internet you should update your location and time before looking to upgrade or add more software. This is to ensure that you get the correct files and upgrades. You will need first to define your zone and city. You can use the 'timedatect1' command to do this. Type:

timedatect1 status

This will give you a display of current settings, which are probably all zeroes.

To set your current date and time enter the information in the following format:

timedatectl set-time "yyyy-MM-dd hh:mm:ss"

Thus:

timedatectl set-time "2014-12-01 08:08:00"

which would set the date to 1st December 2014 and the time to 8.08am.

To set the time zone you need to enter the region and city. Enter this command:

ls /usr/share/zoneinfo

This will provide a list of time zones — locate the one applicable to you. For me it is Australia. Then add your choice onto the end of the command thus:

ls /usr/share/zoneinfo/Australia

You will now get a list of cities in your zone. Select the one nearest to you. For me that is Sydney. So my timezone is Australia/Sydney and the command:

timedatectl set-timezone "Australia/Sydney"

would set this. Typing:

timedatect1 status

should show all the updates in place. It will also provide information relating to any daylight saving changes that have taken or are taking place.

The command:

timedatect1 list-timezones

will also output all options possible.

Package Manager

The Package Manager is 'pacman'. If you get a 'command not recognised' error when you use this check the spelling. It is worth creating an alias so that 'packman' also works! One of the first things you might like to do is to investigate what packages you have installed. It is worth writing this out to a file and using 'nano' to read it. The following command would send the list to a file called 'packages.txt'

pacman -Q > packages.txt

Armed with your list you can find out more about each of the commands at your disposal by examining their manual pages using the 'man' command. For example:

man zlib

Not all have manual pages, so you may also have to surf the Net to find out. This investigation is important if you plan to actually do something with Arch Linux.

The packages of Arch Linux are constantly upgraded and it is not uncommon for there to be a new upgrade of Arch Linus most nights. There is no grand fanfare about this and it is commonly known as a rolling archive. That means that you can update Arch Linux as regularly as you want. You can check arclinux.org for details as you wish, to see if there are any significant upgrades that might concern you. This also means that the packages in archive repositories are constantly upgraded.

Like 'apt-get' in Raspbian pacman saves to disk a list of packages available in a repository. This list is not automatically updated (refreshed) and is called a repository database. You can update the list (cache) with:

pacman -Sy

Pacman gives you a nice character-orientated graphical progress display of where it is in the update process. You can use:

pacman -Syu

which will also offer you the opportunity to upgrade superseded packages. It is good to do this after an initial install as the original distro will likely be out-of-date.

Pacman operates at a lower level when compared to 'apt' on Raspbian and 'yum' on Pidora and so requires you to pay a bit more attention when going through installations and upgrades. As such 'pacman' always lists packages to be installed or removed and asks for permission before it takes action.

You can install a specific package using:

pacman -S <packagename>

which installs the package called packagename and all its dependencies.

pacman -R <packagenem>

removes packagename. If other packages depend on packagename, then it fails with a message. To remove them too use:

pacman -Rc mypackage

Bits and Bobs

If you want to see what your Raspberry Pi is up to with Arch Linux then use this command:

top

which will give you a comprehensive list of what memory is being used, and by what applications.

To exit, type:

halt

Remember, as you are logged in as root user you do not use the 'sudo' command.

The file '/boot/config.txt' contains some settings you can edit that will probably correct issues you may be having with your HDMI output and audio output. You can also configure overclocking here amongst other things. Edit the file using a text editor such as 'nano':

nano /boot/config.txt

Although you may want to make a backup copy of the file first.

You may want to change the root password by running the 'passwd' command:

passwd

You will then be prompted to 'Enter new UNIX password'.

To exit type:

halt

Tasks such as mounting USB sticks and other devices are essentially the same and I would refer you back to the earlier chapters on Bash to remind yourself how these are done. If commands do not work then just look up the 'man' pages for the command in question to understand what the differences are, if any.

Desktop Arch

If you want to add a Desktop for Arch Linux then there are several you can use. First though you need to add X-Server and associated libraries to provide the base infrastructure. To do this use:

pacman -S xorg-xinit xorg-server xorg-server-utils

This downloads and extracts to about 55Mb of SD Card space.

If you want to add XFCE as your Desktop (the same as used by Pidora) execute:

pacman -S xfce4

You will be presented with a selection of items you can download and install. Press <ENTER> to select them all. The complete selection expands to about 320MB, so the total new install will be around 375MB. You may not need all these items and as you become more familiar with the software you may wish to do a lighter installation to minimise your memory usage. Extracting and installing XFCE does take a little while.

You should then update your video drivers:

pacman -S mesa xf86-video-fbdev xf86-video-vesa

Once completed reboot and log back in. You can start XFCE with:

startxfce4

You may find that you get a few errors in the start-up process but XFCE should boot and provide you with some options to configure the panel. A lot of what you get here from your Desktop you can find out about by checking back to Chapter 31 and the discussion of Pidora XFCE.

This is a quite minimal system so you may wish to install a web browser for example. Refer back to Chapter 10 for some options we looked at in relation to LXDE. Again, bear in mind size as the whole purpose of Arch Linux is to be minimal with functionality a prime concern.

If you are looking for other relatively lightweight applications to install on XFCE then this link contains some suggestions: http://wiki.xfce.org.recommendedapps
SECTION SEVEN: PHYSICAL PI

This final section concentrates on the Raspberry Pi hardware — what it is and what you can do with it. It includes a guide to hooking up some simple electronics projects — ideal for the beginner — as well as programming third party add-on boards.

The _Insider_ skills you'll have at the end of this section will enable you to:

  * understand what the main chip components on the Raspberry Pi do.
  * make your Raspberry Pi go faster by _overclocking_.
  * understand the pins and configuration of the GPIO and be able to download software to access them.
  * connect a small light and pushbutton to the GPIO and use them in tandem.
  * select an add-on board and work out how to program it when no instructions are given.

33: Pi Inside and Out

We've been learning all about the software, but what is actually happening in those hardware components and what makes your Raspberry Pi so special? Here are some of the answers as we also look at how to connect it to the outside world!

The square chip in the centre of the Raspberry Pi board has been pretty much where everything we have been doing to this point has been happening. Amazing! Figure 33a shows it in all its glory. In fact this bit of silicon is much more than _just_ an ARM chip. It is actually a System On Chip device.

Broadly speaking, a SoC is a microchip that contains all the components required to drive a computer. In the case of the Raspberry Pi, the Broadcom BCM2835 chip contains a 700MHz ARM processor and a Videocore 4 Graphics Processing Unit (GPU).

_Figure 33a. The Raspberry Pi with the SoC at its heart._

This technology is increasingly popular, and the packaging of numerous components onto a single integrated circuit (IC) means that the devices that they are embedded into become ever smaller. If you have a close look at the Raspberry Pi board then you will see that much of the space is actually taken up by components that allow us to connect to it. The actual computer part probably occupies less than 10% of the printed circuit board!

Make no mistake, the SoC technology used on the Raspberry Pi is cutting edge, and you can expect to see it become prevalent in major advances in technology as the physical size of the SoC device continues to implode. Because of its great digital capabilities you might expect to see similar silicon devices restoring sight to the blind and providing sound for the deaf in the near future.

Another major advantage of the SoC design is the fact that it doesn't require a lot of power and it becomes very efficient because of the small distances that signals have to travel. Remember how much heat standard PCs throw out and where much of the space is given over to cooling?

There is a downside to SoC technology from the home hobbyist point of view — their lack of ability to be upgraded. Essentially everything is metaphorically glued into one place, so you can't readily add new memory or upgrade the core processor. When you are finished with the device, you effectively throw it away. So your Raspberry Pi will no doubt become out-dated but then you would have to simply replace it with the newer model. I am not sure if that makes the Raspberry Pi a disposable computer?

No Risc at all

At the heart of the SoC on the Raspberry Pi is the ARM1176JZF-S core. This can be referred to as the central processing unit — cpu, the micro-processor, or simply 'the chip'. It is a very significant chip. The R in ARM stands for RISC. This is an acronym for Reduced Instruction Set Computing and one of the big leaps that the ARM chip introduced when it was first released some 30 years ago was to allow things to work faster by using a reduced set of commands (or instructions)! Having a reduced set of instructions might make you think that you would not be able to do as much, but the clever bit was that you were able to do more with the reduced set that was designed as each command had a greater range of operations that it could undertake. Really clever stuff.

The ARM chip's speed of operation is also increased because it is working on up to eight, yes eight!, commands at any one time. In this way it never has to wait for something to happen — there is always a conveyor belt of things for it to do. (By the way ARM stands for Acorn RISC Machine).

You will find ARM chips at the centre of almost everything today. Just about every smart phone and tablet device utilises one as of course does your Raspberry Pi!

Just to underline the power of the ARM chip and indeed smart phones in general, a whole new generation of satellites called CubeSats are being placed into orbit around the Earth. They are small (about 10cms square) and have very specific tasks. The Surrey Space Centre in the south of England has designed several CubeSats that are powered by Android phones. At around $100,000 each, these satellites are a fraction of the cost of previous machines. At the same time, the computing power of a single smart phone is perhaps tens of thousands of times more than could be found in the computers on all the Apollo moon missions put together! This power is at your disposal on your Raspberry Pi.

SoCs are not limited to ARM chips but these chips are the processor of choice due to the use of RISC, which offers power saving advantages.

Foundations

The Graphics Processing Unit is the other major component of the SoC configuration. It is a Broadcom VideoCore IV unit that provides 1080 high resolution graphics using a combination of Open software and hardware accelerated computing.

Depending on what model Raspberry Pi you have, it will come with a certain amount of memory. This memory is part of the SoC and it sits on top of the ARM chip in an arrangement called 'package on package'.

The ARM also has an area of very fast memory called a cache that it can use for its own purposes. Caches are for instruction and data storage and are respectively known as Icache and Dcache. They are both 16k in size and are collectively known as the L1 cache.

The ARM design allows for additional processing hardware to be connected to it. Interestingly, this was a unique design structure introduced by Acorn as early as 1983 with the launch of its Second Processor Tube interface. This allowed additional CPUS to be literally bolted onto the side of the BBC Micro, and which would allow other processor dependent Operating Systems such as CP/M to be run. An ARM Second Processor unit was one of the last released for the BBC Micro!

As these are designed to support the ARM they are called co-processors. Up to 16 can be connected and are numbered from 0-15. The ARM in the Raspberry Pi has a 'Vector Floating Point' co-processor attached and uses this to do all real or floating point mathematics.

Overclocking

One of the determining factors on how fast your Raspberry Pi runs or operates at is the speed of the microprocessor. By default, the processor in the Raspberry Pi runs at 700MHz. MHz standing for MegaHertz. One MHz represents one million cycles per second. So the Raspberry Pi operates by default at 700 million cycles per second. This is also known as its clock speed, and if you try and make it go faster than its default _clock speed_ then the process is known as _overclocking_.

In (very) broad terms you can think of each instruction that the Raspberry Pi executes as requiring a fixed number of cycles, so the clock speed determines how many instructions per second the microprocessor can execute. If you can speed up this process then you can make the Raspberry Pi go faster, and this can be a great way of making applications like games run faster. In fact there is a whole world out there where people make it even tougher than usual to play games by running them on overclocked machines.

Normally, overclocking is something frowned on by computer manufacturers and they will state that it will void your warranty if you overclock a computer. This is because overclocking puts more stress on the microprocessor and causes it to run hotter than normal, which does have a detrimental effect on the stability of the chip. You will often see overclocked computers with heat-sinks or cooling devices attached to them to dissipate the heat generated by the chip as quickly as possible.

During 2012, the Raspberry Pi Foundation announced that overclocking was now officially supported without affecting your warranty. The Foundation is spending time to understand the effects that overclocking have on the lifetime of the ARM chip.

The 'raspi-config' tool can be used to set the level of overclocking. Start the tool using:

sudo raspi-config

Select 'Overclock' and press <ENTER>. Press <ENTER> again to confirm that you understand the possible problems with overclocking. Raspi-config offers five clock frequency presets:

_Figure 33b. Overclocking settings available on the Raspberry Pi._

Use the <UP> and <DOWN> arrow keys to select the desired frequency and press <ENTER>. Press <ENTER> again when the confirmation dialog appears and then exit raspi-config. You will then need to reboot your system.

The highest frequency allowed via raspi-config is 1GHz — this is also called Turbo mode as it is the fastest setting you can achieve via the menu.

The actual stability of your overclocked Raspberry Pi depends on your specific Pi and on the quality of your power supply. So it makes sense to ensure you have the best quality power supply available if you want to play with overclocking. Generally this is best achieved by purchasing a power supply from a reputable manufacturer, and look for reviews of it before you buy. Avoid going for the cheap option, which may be substandard.

If you want to disable the overclocking then hold the <SHIFT> key down during a reboot until the 'log-in' prompt appears. This will set the chip speed back to 700MHz until you next reboot without holding down <SHIFT>.

Try experimenting with the different clock levels. You don't need to be over-cautious as you can always select a lower clock speed if you feel your device has become unstable. However you should always back up any important data before experimenting.
34: GPIO

Connecting your Raspberry Pi to the outside world is simple and easy using the General Purpose Input/Output (GPIO) connector. You can just plug in third party boards or get a bit more adventurous using component kits and program them in your favourite language. But first you need to know which pins are which, and then which software to download that will allow you to program them.

The General Purpose Input/Output (GPIO) pins provide the main thoroughfare through which you can connect your Raspberry Pi to the outside world. The pins occupy the large black connector down one side of the board. On the Model B+ there are 40 pins and on the Model B there are 26 pins. This means that there is a difference in the connector size itself and this can create issues in terms of compatibility with older third party add-on boards. This is not insurmountable as long as you know how to connect them — more on that shortly. Most suppliers offer a B+ and B version of their hardware, so just make sure you get the correct one for your flavour of Raspberry Pi, and if you are not sure then ask before you part with your money.

If you are feeling slightly more adventurous then you can build your own projects from scratch or by using simple kits such as the CamJam EduKit where individual items are supplied and you can connect them together. This is a great way to get to know and understand the basics of electronics, and we'll look at a couple of simple projects shortly.

You can also expand your GPIO capability by adding expander boards such as _TriBorg_.

One further thing to say at this point, which I have neglected until now, is that there are actually two revisions of the original Model B Raspberry Pi. Up until now it has not been an issue as there are no differences operationally in terms of using the software, but you should be aware that there is a Model B Revision 1 and a Model B Revision 2. Revision 2 boards were released around September 2012. It is important to know what revision you have as some changes have been made including a few to the GPIO pin numbering. There are a number of ways you can test to see what revision you have but the sure fire way is to enter the following at this Shell in Raspbian:

cat /proc/cpuinfo

Now look up the appropriate hardware revision code in the Figure 34a.

_Figure 34a. Raspberry Pi Hardware revision codes_

Another way to determine which model you have is to check if the board has two mounting holes, as these were introduced with Revision 2. All Model A Raspberry Pi are Revision 2 boards.

From the point of using the GPIO, the main differences affect a couple of pins and these are illustrated in the figures that follow.

Pins Explained

Each pin on the GPIO can be referred to by two different numbers, Figures 34b and 34c, illustrate these numbers for the Model B+ (and A+) and Model B (and A). These numbers are identical for all boards, however for Model A+ and B+ there are physically more pins.

The first way to determine this is to note the physical or board number and this really refers to the geographical location of the pin. So looking down on top of the board the two pins at the edge of the circuit board are numbered 1 and 2, with number 1 being the one closest to the SD Card (top left). Below these come pin numbers 3 and 4 and so forth. On a B+ there are two rows of 20 pins making 40 pins in all. On a Model B there are two rows of 13 pins making 26 pins in total.

The second way of referring to the pins is using their BCM number which is the way the Raspberry Pi sees them — their Broadcom SOC channel number. You may also see these referred to as BCM GPIO numbers as well. So, for example, Physical or Board pin 3 is BCM 2 and Physical pin 11 is BCM 17.

_Figure 34b. The Raspberry Pi B+ GPIO Pin designations._

If you look at and compare the Model B revisions you can see the real difference is that the BCM numbers attached to physical pins 3 and 5 have changed. You will also notice that there are some pins with the designation 'dnc' (Do Not Connect) now have a voltage setting applied to them (0v or 3.3v) in Revision 2.

_Figure 34c. The Raspberry Pi B Revision 1 and Revision 2 GPIO Pin designations._

The first 26 pins on the B+ GPIO are identical to those of the Model B revision 2 board. This means it should be possible to use any third party add-on boards developed for the Model B on the B+ provided the board is inserted at the top of the connector to utilise the same 'early' pins (ensuring that it is orientated the right way around). Caution though: First verify that the board is compatible by checking with the manufacturer and secondly make sure that you inserted it at the top of the connector. If you use the wrong pins then you may damage the third party board and maybe your B+ as well.

To help you program the GPIO pins you can access various program libraries which will provide you with commands to control the GPIO pins individually. It is worth getting these installed and working before we connect things up.

WiringPi

WiringPi is an application that is written specifically to allow control of the GPIO pins in the form of simple, easy-to-use commands, which you can enter from the Raspbian Shell command line. In its pure form 'WiringPi' allows you to write directly to the pins but there are additional modules available that allow you to talk to specific third party boards such as the 'GertBoard'. The website at: http://wiringpi.com

will continue to provide information and feedback for users, so if you go this route ensure you check it out.

There are a couple of ways you can download and install WiringPi and I'll outline one here. If they fail then do check the website in case things have changed, or to try the alternative way to install. From the command line enter:

sudo apt-get install git-core

You may get an error saying this is already installed, which can be ignored, otherwise wait for the software to download and install. Next enter:

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

This will download the code which you now have to build.

cd wiringPi

./build

You will get feedback dialogue on the screen. If you want to see the build script you can load it into 'nano' to examine. (Note use of lowercase 'w' above.)

You can check the version number with:

gpio -v

And you can get help in the normal fashion:

gipo -h

Typing:

gpio readall

will provide you with an on-screen map of all the current pins and their settings. Figure 34d shows how this looked on my B+ (with nothing connected). Note how the printout displays the Physical and BCM pin numbers for you. There is also an additional set of WiringPi numbers as well. However you can designate what pin numbering system you want to use.

The 'WiringPi' utility includes its own manual pages, so you can get a full breakdown of the commands and options with:

man gpio

_Figure 34d. The 'readall' option provides an update on the status of your GPIO pins._

Python

At the time of writing the latest release of Raspbian contains the 'RPi.GPIO' library for Python. You can ensure you have the latest version of the library by typing

sudo apt-get update && sudo apt-get upgrade

This will get you up-to-date on all the software fronts. In Python you will first need to import the library using:

import RPi.GPIO as GPIO

Note the character case here, the 'i' in RPi is lower case. Now test which version you have:

GPIO.VERSION

At the time of writing this reported '0.5.5'

If you get an error message or want to ensure that you have the latest version for both releases of Python use:

sudo apt-get install python-rpi.gpio python3-rpi.gpio
35: Simple Projects

For just a few dollars you can purchase the components you need to connect your Raspberry Pi to the outside world. Or simply buy a kit to get you started. It's as easy as... er... Pi!

In this chapter we'll look at two very simple interfacing projects. You do not need to understand electronics to be able to create these projects as you can simply follow the instructions and then see the results!

In the first project we'll connect a small light to the Raspberry Pi and see how to turn it on and off using Bash and Python. In the second we will add a small push switch to the project and make the light flash when we push the switch. To do this you will need some very basic components that you will be able to get from a hobby electronic shop or on-line, or you could order the CamJam EduKit which has everything you need neatly packaged in a smart tin. Your component shopping list then is given in Figure 35a.

_Figure 35a. Requirements for two simple projects._

Most of these components are sold in small packs so you will probably end up with more than you need (at first!). Let's look at each item in the shopping list.

Breadboard

The breadboard is the construction platform for these projects and the many others that you might like to try. They contain a maze of holes into which you can plug components to build your circuit. The key thing here is knowing how the holes are connected. Figure 35b shows this diagrammatically.

_Figure 35b. Breadboard connections._

The top and bottom of the Breadboard contains two rows of holes that are connected together. On this particular design of breadboard the top one is the positive (+) rail and the bottom one is the negative (–) rail. These will often have a red and blue line respectively along their edge. Think of these as being the rails that bring the power to your project, like the positive and negative pins on a battery.

Within these there are two sets of rows connected in columns, again illustrated in Figure 35b. Down the side of the Breadboard you might find letters that number each of these rows in the columns. In these central columns we will place the components for the project.

LEDS

Light Emitting Diodes, or LEDs, glow when they have electricity passed through them. Even though you may not know what they are they are used in a lot of household appliances. They come in many different colours. The colour does not affect their functionality so you can choose what colours suit you best. The thing to note with LEDs is that they have two legs which plug into the Breadboard. However, they must be plugged in the right way around to work (you won't damage them plugging them in the wrong way around — they just won't work!). To assist in orientation one of the legs is longer than the other one and this is the positive side (also called the anode). The shorter leg is the negative side (or cathode).

Resistors

These devices provide resistance and limit the amount of electricity that is passing or flowing through the circuit. You can connect them any way round. Different resistors provide different amounts of resistance and this is measured in Ohms. A colour coding system is used on the body of the resistor to show what the resistance is, It is important therefore not to get the resistors mixed up. Components like LEDs will try and draw as much electricity as possible, so to avoid them burning out, resistors are placed in the circuit to limit the current.

Jumper Wires

These allow you to connect the GPIO pins to the Breadboard. One end will have a female connection (to go on a pin) and the other will have a male connection (to plug into a hole in the Breadboard). You can also have jumper leads with two male end connections and others with two female end connections.

LED Circuit

Building the LED circuit is not difficult, but it can be a bit fiddly if you haven't done it before. Let's take it step-by-step. Refer to Figure 35c below to ensure everything is connected correctly.

_Figure 35c. Building the Breadboard Circuit._

For the purposes of description the column rows are labelled (from the bottom) A, B, C, D, E, F . And the holes are numbered from the left starting at 1.

Take a 330Ohm resistor and carefully bend the legs over so that you can plug one leg into a '' (negative) rail running across the Breadboard and the other into one of the column sockets in the centre of the board. You should be able to fit the second leg of the resistor into the second (B4) or third (C4) pin in the column.

Take the LED and plug the short leg into the column which contains the resistor (E4). The long leg should plug into the column directly next to it (E5).

Take a jumper wire and plug the male end into a hole in the same column of holes as the long leg of the LED (A5).

Take a second jumper wire and plug the male end into a hole on the negative rail, ie, one that is in the same lines as the negative end of the resistor.

The power for the LED will be provided by the Raspberry Pi, from GPIO pin 18, which can offer up 3.3 volts when it is set high and 0v when it is set low. To complete the circuit we need a ground or 0v which supplies the negative rail on the Breadboard. Physically this is pin number 6.

Until you are familiar and comfortable with using and attaching the GPIO pins you should turn your Raspberry Pi off before attaching your project to it. Now take the female end of the A5 jumper (the one from the LED end) and attach that to physical pin number 12 (BCM18) on the Pi, and then take the jumper that's connected to the negative rail of the breadboard and attach the female end to the Pi physical pin 6 or the GND/0 pin. Figure 35d illustrates how the connections should all look — the diagram shows a Model B board, it is the same for a B+ as the pins are the same. This worksheet can use a Raspberry Pi Model A, B or B+. The first 26 pins on the B+ (when looking at the B+ with the pins in the top left) are exactly the same.

_Figure 35d. The final circuit connected to a Model B._

If you are happy you're good to go. Power back on and we'll write some code to flash the LED on and off.

Making it Work!

We can use Bash or Python to flash the LED on and off. If you haven't already installed the Wiring Pi Library and ensured that you have the Python GPIO library installed, flick back a few pages and do so now.

WiringPi

Bash commands provided by WiringPi are all prefixed with 'gpio' and the following three lines typed in at the command line would turn the LED on and then off:

gpio -g mode 18 out

gpio -g write 18 1

gpio -g write 18 0

The 'g' option selects the pin numbering system that you wish to use. Here 'g' chooses BCM. We are then setting the mode of BCM 18 to output. The next two lines write a '1' and then a '0' to BCM 18. A '1' being a high (turns it on) and a '0' being low (turns it off). You do need to specify the 'g' option each time you refer to a pin.

You could instead refer to the physical pin numbers by using the '' option, therefore our three lines of code would become:

gpio -1 mode 12 out

gpio -1 write 12 1

gpio -1 write 12 0

Python

Although you can control the GPIO from the command line, it is probably easier to put your commands into a script to do so, but you need a few more lines of code. Create a new script file and save it as 'leds1.py':

#LED flasher — leds1.py

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)

GPIO.setup(18,GPIO.OUT)

GPIO.output(18,GPIO.HIGH)

time.sleep(2)

GPIO.setup(18,GPIO.OUT)

GPIO.output(18,GPIO.LOW)

GPIO.cleanup()

This script starts by importing the 'RPi.GPIO' library and also the time library as we'll introduce a short delay between switching the LED on and then off. Looking at the main points of the code:

GPIO.setmode(GPIO.BCM)

determines that we'll use the BCM numbering system

GPIO.setwarnings(False)

ensures that no warning messages are printed to the screen (not that there should be any).

GPIO.setup(18,GPIO.OUT)

set pin BCM18 to an output.

GPIO.output(18,GPIO.HIGH)

set pin BCM18 to high — turn it on.

GPIO.output(18,GPIO.LOW)

set pin BCM18 to low — turn it off.

GPIO.cleanup()

resets the status of the pins that were used back to their starting condition.

Now you will not be able to run this script from Python itself as it requires super-user privileges. So, with the script saved, use:

sudo python leds1.py

When you execute the script, remember that you will need to make your current selected directory the same as where the script is saved.

The next script is a variation on the above which loops 20 times and simply turns the LED on and off repeatedly:

#LED looping flasher — leds2.py

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)

for n in range (1,20):

GPIO.setup(18,GPIO.OUT)

GPIO.output(18,GPIO.HIGH)

time.sleep(0.5)

GPIO.setup(18,GPIO.OUT)

GPIO.output(18,GPIO.LOW)

time.sleep(0.5)

GPIO.cleanup()

Save and then run this from the command line with:

sudo python leds2.py

Using A Switch

The LED project teaches the fundamental of how to program a pin so that it can be used to output a signal and turn on a small light. Another fundamental is learning how to look for and read an input, interpret it and then act on it. In this section we'll do just that by adding a switch to the Breadboard and use the switch to turn the LED on and off.

To start you'll need the LED circuit exactly as used; don't change anything. You'll also need:

  * Pushbutton switch
  * 4.7kOhm resistor
  * 2 x Male-Female jumper lead
  * 1 x Male-Male jumper lead

Here are the five things you need to do after you have turned your Raspberry Pi off:

Insert the pushbutton onto the Breadboard. Note that the pins straddle the middle of the board with two sitting on the far side. The pushbutton will only go in one way around (because of the hole pitch and the fact that the button is rectangular in shape) so you should not be able to get it wrong. Choose a column of pins a bit further down the breadboard away from the LED. Take note where the pins sit on the LED side of the board as we will be using both these columns to connect the GPIO to the button. The columns nearest the LED we'll call 'nearside' and the other 'farside'.

Take the 4.7kOhm resistor and insert one leg into the power switch nearside column and the other should go into the + (positive) horizontal power rail.

Connect the female end of a jumper lead to physical pin 22 of the GPIO — this is the BCM25 pin — and then insert the male end of the jumper into a spare hole in the nearside column that contains the leg of both the 4.7kOhm resistor and the pushbutton.

Connect the female end of a jumper lead to physical pin 1 of the GPIO — this is the 3.3volt pin — and then insert the male end of the jumper into the nearest available hole on the + (positive) horizontal rail.

Use a male-male jumper lead and connect one end onto a hole in the far side column of holes where the second pushbutton switch sits and then plug the other male end onto the - (negative) horizontal rail.

Figure 35e shows the completed breadboard with the push switch in place. Carefully ensure that your circuit looks the same.

_Figure 35e. The pushbutton circuit in place with the LED circuit._

Reading an Input

The push switch has been connected to BCM pin 25, so we need to be able to read that pin to see if the button has been pressed. Therefore we have to initially set the pin as an input and then read when the line goes low (0) to indicate that the button has been pressed. The Bash script below (switch1.sh) can be entered using your text editor of choice and then must be made executable. Where it is shown (on the 'if' line) be careful to use the character that looks like a single quote backwards '`'(on most keyboards this is the same key that is shifted to produce the tilde '~'). This will ensure that the 'if' line is interpreted as a command by Bash. The program assumes the WiringPi library is installed.

# WiringPi to read switch & turn LED on when pressed

# switch1.sh

gpio -g mode 18 out

gpio -g mode 25 in

while true

do

if [ `gpio -g read 25` = 0 ]

then

gpio -g write 18 1

else

gpio -g write 18 0

fi

done

The script creates a continuous look, scanning pin 25. When the pushbutton is held down then BCM 25 will go low (=0) and the 'if' condition will be met and a 1 is written to pin 18, where the LED is connected to turn it on. When the button is released, and not held down, pin 25 will be high (=1) and the 'else' condition of the text is met and therefore a 0 is written to pin 18 and the LED turned off. Spacing is critical in the 'if' line, so check there is one space between each item except the inside of the back apostrophe '`'.

To exit from this continuous loop press <CTRL>-C.

In Python it is easy to adapt the 'leds2.py' script to test for the pushbutton and create the 'leds3.py' script below:

#Using a Switch — leds3.py

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)

GPIO.setup(25,GPIO.IN)

while True:

if GPIO.input(25) == False:

GPIO.setup(18,GPIO.OUT)

GPIO.output(18,GPIO.HIGH)

time.sleep(0.5)

GPIO.setup(18,GPIO.OUT)

GPIO.output(18,GPIO.LOW)

time.sleep(0.5)

GPIO.cleanup()

You can execute this with:

sudo python leds3.py

The operation is identical to the Bash script except here when you hold down the button the LED flashes on and off. To exit from this continuous loop press <CTRL>-C.

Interpretive — Not Direct

The switch example above is indicative of an interpretive circuit. The push switch is not actually in the LED circuit directly. If you think of a light switch at home then the switch itself physically sits in the line of power, so when you turn the switch on power flows through the switch and to the light bulb itself. Turn the switch off and the power is disconnected by the interruption of a physical gap in the conducting path.

In this circuit the LED and push switch are not directly connected. When the switch is not being pressed, a current flows between the 3.3v (physical pin 1) pin of the GPIO, to the positive rail of the breadboard, into the 4.7kOhm resistor, and then back through the jumper lead to BCM 25. When the switch is pressed the current can also flow through the switch and back to the negative rail of the breadboard. Now current is flowing through two separate paths. The effect of this is to lower the overall voltage on pin BCM 25 and the 3.3v is split. The drop in voltage sends BCM 25 low (low voltage) indicating the change in situation. The program reacts by sensing this and then turning the LED on.

Using this technique you can design and connect lots of smaller circuits to combine to perform bigger tasks and you can program them to interpret and action. This is relatively straightforward as I hope these two examples have shown.
36: Add On Boards

If electronic components are not for you, the abundance of third party add-on boards means you can experiment with the GPIO pins using a plug-and-play approach.

The ability to extend and add onto the Raspberry Pi is one of the key factors in its success. What the home hobbyist computer market had lacked for a long time was an inexpensive – cheap – system that tinkerers and would-be tinkerers could hook up to. One of the features that have made the Raspberry Pi so popular is it's 'connectability'. It is pretty easy to connect or interface devices to it as we have already seen. The proliferation of third party add-on boards and the increasing number of projects being developed seems only limited by people's ingenuity. The first of these add-on boards was probably the Gertboard, shown in Figure 36a, which provided easy access to the GPIO pins and the supplied software and project examples for you to develop. Libraries such as 'WiringPi' even supply Gertboard commands to allow easy interaction from its popular Bash interface.

_Figure 36a. The Gertboard was one of the first add-on boards for the Raspberry Pi._

The Gertboard offers possibly the most comprehensive of interfaces for the Raspberry Pi but may not be the ideal first add-on board to experiment with. Something less cluttered and more accessible such as the Pibrella might be worth considering. This device contains several LEDs, a pushbutton and a buzzer. Additional input and output connections make it readily accessible.

As mentioned in the previous chapter, but worth reiterating here, on the Module B+ there are 40 pins and on the Model B there are 26 pins. This means that there is a difference in the connector size itself and this can create issues in terms of compatibility with older third party add-on boards. Most boards will work provided there are no physical obstacles to them on the B+. This is the case on the Gertboard however, as it will not physically fit to the Pi unless it is spaced upwards by means of a header extension. The Pibrella will work comfortably and just needs you to ensure that it is plugged into the first 26 pins at the very top of the GPIO connector.

You should check with the board manufacturer or distributor to ensure it will work with your flavour of Raspberry.

Pibrella

The Pibrella board will work with all versions of the Raspberry Pi. However, be careful to insert it at the top end of the GPIO connector on the B+, so that it occupies the first 26 pins (13 rows) on the board (Figure 36c).

The Pibrella comes with very few instructions but you can use both Python and WiringPi to program the Pibrella board. Pibrella provides its own Python command library and you can install this using:

sudo apt-get install python-pip

sudo pip install pibrella

This provides very specific commands to program the various components. On the Wiring Pi website you can also download an additional library for it.

However, as the Pibrella board connects to the GPIO it is just a matter of knowing what is connected to what to be able to utilise the regular libraries, and Figure 36b lists these.

_Figure 36b. The BCM pins used on the GPIO by Pibrella._

The following Bash script (pibrella.sh) starts with the red LED on and will wait for the Pibrella button to be held down before turning the red LED off and switching the Yellow and Green LEDs on. When the button is released the LEDs are reversed again. The script uses variables that are initialised to the BCM pin numbers and also demonstrates the use of functions to read the button state.

_Figure 36c. Add-on boards such as Pibrella must be plugged into the top 26-pins on the Model B+._

# Using WiringPi to play Pibrella

# pibrella.sh

red=27

yellow=17

green=4

button=11

gpio -g mode $red out

gpio -g mode $yellow out

gpio -g mode $green out

gpio -g mode $button in

# wait for button to be pressed

# will go low when pressed

waitButtonPress ()

{

while [ `gpio -g read $button` = 0 ]; do

sleep 0.1

done

}

waitButtonReleased ()

{

while [ `gpio -g read $button` = 1 ]; do

sleep 0.1

done

}

gpio -g write $red 1

gpio -g write $yellow 0

gpio -g write $green 0

while true ; do

waitButtonPress

gpio -g write $red 0

gpio -g write $yellow 1

gpio -g write $green 1

waitButtonReleased

gpio -g write $red 1

gpio -g write $yellow 0

gpio -g write $green 0

done

The following script (squawk.py) is in Python and demonstrates reading the button for an input and then making a short click sound on the squawk buzzer. The buzzer is a small piezo device and sound quality isn't great.

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

GPIO.setwarnings(False)

squawk=18

button=11

red=27

GPIO.setup(button,GPIO.IN)

GPIO.setup(squark,GPIO.OUT,initial=0)

GPIO.setup(red,GPIO.OUT)

while True:

if GPIO.input(button) == True:

GPIO.output(squawk,GPIO.HIGH)

GPIO.output(red,GPIO.HIGH)

time.sleep(0.5)

GPIO.output(squawk,GPIO.LOW)

GPIO.output(red,GPIO.LOW)

time.sleep(0.5)

GPIO.cleanup()

The eagle-eyed amongst you might have noticed that the push switch on the Pibrella board is a reversal of the way that the push script on the Breadboard projects earlier was coded.

Hats

The issue of add-on board compatibility, certainly in relation to the Raspberry Pi B+, should be alleviated somewhat by going forward with the introduction by the Raspberry Pi Foundation of the 'HAT' (Hardware Attached on Top) standard. This specification requires that an add-on board for the B+ conforms to a specific set of rules. By following these rules the B+ will be able to identify that it is connected to a HAT board and will automatically configure the GPIOs and drivers for that board. This ensures that all HAT compliant software and hardware will work and work in a pre-defined way. Most new B+ specific add-on boards appearing are HAT compliant.

A HAT board has four mounting holes that align with the mounting holes on the B+, and connects via GPIO header and supports the special auto-configuration system. The automatic configuration is achieved using two dedicated pins (ID_SD and ID_SC) on the GPIO header that are reserved for an I2C EEPROM. This small memory chip holds the board manufacturer information, GPIO setup and a description of the attached hardware that allows Linux to automatically load the required drivers.

_Dear Expert..._

_So what else do you need to know? Well there's a whole world out there and it all depends on the direction you wish to go. This book has been predominantly about the software of the Raspberry Pi. I have really only given you a taster of the interfacing project side of what is possible and you may wish to look further into this._

_By now you probably also have a favourite programming language and want to take your knowledge of it further, or perhaps investigate the specifics of the Python games library or experiment with a new language like Ruby or maybe dabble with machine code._

_Whatever avenue you do wish to pursue you should feel confident that you have the essential skills you need to take it head on and work towards — at the very least — a thorough understanding of the topic._

_Whatever the route, make yourself active in the environment and check out those local Jams. I'm sure you'll find them to your taste!_

_Bruce, November 2014._
A: ASCII Character Set

Binary Dec Hex ASC

010 0000 32 20 ?

010 0001 33 21 !

010 0010 34 22 "

010 0011 35 23 #

010 0100 36 24 $

010 0101 37 25 %

010 0110 38 26 &

010 0111 39 27 '

010 1000 40 28 (

010 1001 41 29 )

010 1010 42 2A *

010 1011 43 2B +

010 1100 44 2C ,

010 1101 45 2D -

010 1110 46 2E .

010 1111 47 2F /

011 0000 48 30 0

011 0001 49 31 1

011 0010 50 32 2

011 0011 51 33 3

011 0100 52 34 4

011 0101 53 35 5

011 0110 54 36 6

011 0111 55 37 7

011 1000 56 38 8

011 1001 57 39 9

011 1010 58 3A :

011 1011 59 3B ;

011 1100 60 3C <

011 1101 61 3D =

011 1110 62 3E >

011 1111 63 3F ?

100 0000 64 40 @

100 0001 65 41 A

100 0010 66 42 B

100 0011 67 43 C

100 0100 68 44 D

100 0101 69 45 E

100 0110 70 46 F

100 0111 71 47 G

100 1000 72 48 H

100 1001 73 49 I

100 1010 74 4A J

100 1011 75 4B K

100 1100 76 4C L

100 1101 77 4D M

100 1110 78 4E N

100 1111 79 4F O

101 0000 80 50 P

101 0001 81 51 Q

101 0010 82 52 R

101 0011 83 53 S

101 0100 84 54 T

101 0101 85 55 U

101 0110 86 56 V

101 0111 87 57 W

101 1000 88 58 X

101 1001 89 59 Y

101 1010 90 5A Z

101 1011 91 5B [

101 1100 92 5C \

101 1101 93 5D ]

101 1110 94 5E ^

101 1111 95 5F _

110 0000 96 60 `

110 0001 97 61 a

110 0010 98 62 b

110 0011 99 63 c

110 0100 100 64 d

110 0101 101 65 e

110 0110 102 66 f

110 0111 103 67 g

110 1000 104 68 h

110 1001 105 69 i

110 1010 106 6A j

110 1011 107 6B k

110 1100 108 6C l

110 1101 109 6D m

110 1110 110 6E n

110 1111 111 6F o

111 0000 112 70 p

111 0001 113 71 q

111 0010 114 72 r

111 0011 115 73 s

111 0100 116 74 t

111 0101 117 75 u

111 0110 118 76 v

111 0111 119 77 w

111 1000 120 78 x

111 1001 121 79 y

111 1010 122 7A z

111 1011 123 7B {

111 1100 124 7C |

111 1101 125 7D }

111 1110 126 7E ~
B: Hands On Guides

Hands On Guides

Current titles from BSB. Visit www.brucesmith.info for additional details and information about all Bruce Smith Books. You can see full detailed contents list on the website. Information is subject to change.

Raspberry Pi Assembly Language RASPBIAN Beginners

Available in Print and eBook editions.

"This is a great book. Bruce Smith writes great books."

_Raspberry Pi Assembly Language RASPBIAN Beginners_ is your hands-on guide to learning to program ARM machine code on your Raspberry Pi. With nothing other than the Raspbian Operating System installed on your Raspberry Pi, this book shows you how to access all the tools that you'll need to create your own machine code programs using assembly language.

Examples are provided that are written using the GCC Compiler running under the Raspbian Operating System on the Raspberry Pi, all of which can be downloaded from the book support website at www.brucesmith.info.

Ideal for the novice, this book starts from first principles and leads you comfortably on your way to become an accomplished programmer. Providing lucid descriptions, award winning author Bruce Smith keeps things simple and includes plenty of program examples you can try for yourself. Ideas and concepts are introduced in the order required so you should never be left wondering. Just some of the many features include:

  * 260 pages
  * Practical approach with example programs
  * GCC assembler and linker
  * ARM registers and arrangements
  * Addressing modes
  * Use of Operating System Syscalls
  * Debugging with GDB
  * Using libc function calls
  * Programming the GPIO
  * Purchase Print edition and get eBook edition for just 99c/p

Note: book contents may change without warning. Please check out www.brucesmith.info for full details.

REVIEWS for _Raspberry Pi Assembly Language RASPBIAN Beginners_

_This book gives a great introduction to assembler programming. I followed the instructions and had my first few programs compiled, linked, running and working. Don't know what those terms mean? Buy this book. I'ts a great introduction on the process of creating an assembler program and how to get it running. I have had previous experience with x86 assembler programming and a little Linux assembler programming. This is a great book. Bruce Smith writes great books._

_It is easy to find good books about C# and Java. However, for many more specialized development tools it is hard to find a book that provides what a beginner needs. In many cases, a book thoroughly covers the language commands, but leaves the reader staring a a blank command line wondering "What, exactly, do I need to type to compile and run my program?" Bruce Smith's books do not fall into this trap. Smith provides not only the necessary coaching and instruction in assembly language for the Raspberry Pi's ARM processor, but also gives clear practical instructions for getting everything to work... Whether you are looking just to have some fun learning assembly language with your Raspberry Pi or whether you view the PI as a stepping-stone to greater things ARM, Bruce Smith's book definitely belongs on your shelf._

_This was just the book I was looking for. Not only does it teach you how about programming the ARM chip it also delves into some of the specifics of the Raspberry Pi itself, and those topics you find unanswered in the forums. This book is worth it for that fact alone providing chapters on things like Thumb Code, Floating Point and programming the GPIO. In summary this is an excellent book which is a must-buy for anyone who wants to learn how to program their Raspberry Pi at the most fundamental level. Well priced and well written, and the print version I have is well-laid out and easy to follow._

_Excellent little book. Uses the linux gcc toolchain rather than the riscos basic assembler, so its easy to try the examples directly under Raspbian. I did a lot of X86 assembler coding at one time ( ugh! ) and had forgotten just how brilliant the ARM instruction set is. Very easy to memorise and get coding. Shows how to interface assembler to C as well. Would thoroughly recommend this to anyone looking to learn ARM assembly language_

_This is a great book for budding programmers who want to dig deeper into the Raspberry PI to really understand how the computer works. Great step by step examples and code to learn from and enjoy._

_I'm totally new to Raspberry Pi, Linux, and to Arm processors. This book is clearly written with easy to follow examples. I'm up to chapter 12 so far. I bought the kindle edition and am reading it on my IPad. The formatting, pictures, and text flow are all superb._

Raspberry Pi Assembly Language RISC OS Beginners

Available in Print and eBook editions

If you want to learn machine code using the RISC OS distro then this is the book to choose!

Ideal for the novice, this volume starts from first principles and leads you comfortably through to become an accomplished ARM programmer.

It adopts a modular approach with simple examples to get you started. Foundation building early chapters lead you gently into the subject without sacrificing the subtle nuances that make Raspberry Pi Assembly Language special. The tools to do this you may already have, or you can simply download them for free in just seconds. We show you how, quickly and simply. Just some of the many features include:

  * Example programs and segments
  * Use of the BBC BASIC Assembler
  * ARM registers and arrangements
  * Data processing
  * Branches, shifts and rotates
  * Conditional execution
  * Addressing modes
  * Use of Operating System SWI calls
  * Macros and look-up tables
  * Debugging
  * Programming the GPIO
  * Floating Point Co-processor programming
  * Context Switching
  * Using GCC & C
  * System on Chip
  * Plus more .... see website

Note: book contents may change without warning. Please check out www.brucesmith.info for full details of final contents.

REVIEWS for _Raspberry Pi Assembly Language RISC OS Beginners_

_Another great Bruce Smith book. This time, it's Assembly Language on the RISC OS. I purchased this book and the Raspbian Assembly book. They have similar content but this one is focused on assembler on RISC OS. It's great to have another perspective on programming Assembler for different OS's on the same hardware platform._

_What you'll see is that while the tools and OS calls differ, in the end, assembler offers the same instructions on the SoC (system on a chip) computer. Understanding assembler is key to understanding how computers work. Buying this book and installing RISC OS is a great way to learn assembler in a not-so-familiar (to me) environment._

_Good book, good tricks_

_This book is an excellent introduction to coding in ARM assembler on the Raspberry Pi._

Raspberry Pi RISC OS System Programming Revealed

Available in Print and eBook editions

Learn how to get the most from RISC OS on the Raspberry Pi. This book takes the lid off the RISC OS Operating System and reveals how to really use it.

Aimed at those wishing to learn how to program RISC OS directly but are struggling with the Programmers Reference Manuals (PRMs) or simply don't know where to start – this book will teach you everything you need to know to get the most from RISC OS and your Raspberry Pi.

Providing lucid descriptions, award winning author Bruce Smith keeps things simple and includes plenty of examples you can try for yourself. Ideas and concepts are introduced in the order required so you should never be left wondering. Just some of the many features include:

  * Filing systems including SDFS and FAT32F2
  * FileCore and FileSwitch Operation
  * The CLI, *Commands and the SWI interface
  * Communicating with RISC OS
  * Writing and using Modules
  * Vectors, Interrupts and Events
  * The Window Manager (Desktop) and WIMP Utilities
  * The Font Manager
  * The Sound System
  * SoundDMA and SoundControl
  * Floating Point Model
  * Programming the GPIO
  * Book support pages on authors website.
  * 320 pages

Note that the GPIO chapter and some of the information provided in the sections covering VFP and processor modes are duplicates of the information provided in this book.. More information on the website.

Also available as a two-part eBook.

Book Folio Information

Raspberry Pi Insider Guide

© Bruce Smith

ISBN-13: 978-0-9922316-8-3

Second Edition: January 2015 [002] Smashwords

Editor: Alan Ford Edits

Cover: Brad Covey (www.bradcovey.com)

Typeset in 11 on l2pt Garamond by BSB

All Trademarks and Registered Trademarks are hereby acknowledged.

Within this _Hands On Guide_ the term BBC refers to the British Broadcasting Corporation. Raspberry Pi and the Raspberry Pi logos are registered trademarks of the Raspberry Pi Foundation.

_Raspberry Pi Insider Guide_ is not endorsed by the Raspberry Pi Foundation.

All rights reserved. No part of this book (except brief passages quoted for critical purposes) or any of the computer programs to which it relates may be reproduced or translated in any form, by any means mechanical electronic or otherwise without the prior written consent of the copyright holder.

Disclaimer: Whilst every effort has been made to ensure that the information in this publication (and any programs and software) is correct and accurate, the author and publisher can accept no liability for any consequential loss or damage, however caused, arising as a result of the information printed in this book and on any associated websites. Because neither BSB nor the author have any control over the way in which the contents of this book is used, no warranty is given or should be implied as to the suitability of the advice or programs for any given application. No liability can be accepted for any consequential loss or damage, however caused, arising as a result of using the programs or advice printed in this book.

Published by BSB – www.brucesmith.info.
