Python Community (www.freelycode.com) organized the translation, reproduction is prohibited
Introduction
This article is intended to help beginners set up a development environment for Raspberry Pi and program in Python and C on the Raspberry Pi.
Main content is as follows, mainly about Raspberry Pi, Python, and C.
Raspberry Pi Programming
File Manager
Web Browser
Text Editor
Shell
Command Line
Tips and Tricks
Files and File Systems
Raspberry Pi and Python
Python Version of Hello World
Method 1
Method 2
More on Python
Python Functions
Keywords
Keywords related to conditional statements
Keywords related to loop statements
Keywords related to built-in functions
Keywords related to classes and modules
Keywords related to error handling
Setting up Raspberry Pi programming environment
Installing VIM
Installing Python
Installing RPi.GPIO
Debugging Tips
Programming in C
Installing BCM2835-C
Installing WiringPi
C Language Light Sensor Program
Background
If you are using Raspberry Pi for the first time, please refer to the sister article — Introduction to Raspberry Pi with Raspbian version for setting up the Raspberry Pi, link below:
Introduction to Raspberry Pi with Raspbian (http://www.codeproject.com/Articles/839230/Introduction-to-Raspberry-Pi-with-Raspbian-OS)
Raspberry Pi Programming
Please refer to the article mentioned above to set up and boot into the Raspberry Pi system for the first time.
Once Raspberry Pi is set up and you enter the LXDE desktop environment (the lightweight graphical interface for Raspbian), let’s quickly browse through some important content that will be used in programming.
File Manager
You can find it in the “Start Menu” and treat it just like the Windows File Explorer, which means you can use the mouse to move files without relying on the command line. With the file manager, you can browse the file system using icons and folders just like other graphical operating systems.
Web Browser
The default web browser is Midori, a lightweight browser designed for low-performance processors. Common browsers like Chrome, IE, and Safari run many tasks in the background and consume a lot of resources, making it a bit challenging for Raspberry Pi to run these programs. However, the lightweight Midori does not implement all the functionalities of the aforementioned “heavyweight” browsers.
For example:
Midori cannot run Flash
Midori cannot run Java plugins
Midori does not support all HTML5 tags, such as Video
The Raspbian system also comes with another browser, Netsurf.
Text Editor
Leafpad is the default browser on the Raspbian system. Traditional editors like VIM and emacs are not pre-installed, but you can install them manually.
Shell
Most tasks we perform on Raspberry Pi are command-line programs, which can be run through LXTerminal (a virtual terminal). LXTerminal is used to access the shell (also known as the command line). The default shell on Raspbian is BASH.
Command Line
Tips and Tricks
Programming on Raspberry Pi will frequently use the command line. You can access the command line via LXTerminal by default. Here are two important tips to help us use the command line more easily:
Auto-completion: Many times, we can just type a few characters of a command or file name and hit the tab key, and the shell will automatically complete the rest. The shell tries to auto-complete based on the current environment, such as the folder you are in, or commonly used folders like /bin and /usr/bin where programs are located.
Command History: This trick allows us to use previously run commands again. You can browse previous commands using the up arrow key, with the most recently used appearing first. When there is a small error in a long command that needs to be corrected, you don’t have to re-enter the entire command.
Files and File Systems
The table below lists some commonly used folders, most of which conform to the Linux directory structure, but some are unique to Raspberry Pi. The /sys folder contains all hardware devices on Raspberry Pi, and you can use this folder to access them.
/boot Contains Linux kernel and other packages used to boot Raspberry Pi
/bin Contains binary executable files related to Raspbian (including those needed to run the graphical interface)
/dev This is one of the virtual folders used to access all connected devices, including storage cards
/etc System management and configuration files
/home My Documents on Linux, contains a folder named after the username
/lib Code libraries required by various applications
/lost+found Generally empty, this is where files are stored after an improper shutdown
/media Contains removable storage drives, such as USB and CD
/mnt Used to manually mount external hardware drives or storage devices
/opt Optional software folder, non-system software will be placed here
/proc Another virtual folder that contains information about running processes (or programs)
/selinux Security tool developed by the NSA to enhance Linux security
/sbin Contains system management commands for superusers
/sys Contains operating system files
/tmp Contains temporary files
/usr Contains programs for user use
/var Virtual files for programs to save data
The prompt will show the current path. In Linux, ~ represents the home directory. When we first open the command line, the displayed content is:
pi@raspberrypi ~ $
The meaning of each part of the line of text is:
pi Current username, followed by the @ character
raspberrypi Device or computer name. Default is Raspberry Pi
~ Current working directory of the shell, default working directory is the home folder
$ Shell prompt, followed by the command. Enter the command and press Enter to execute it
Next, let’s learn how to program Raspberry Pi using Python and C.
Raspberry Pi and Python
Python is simple and straightforward, and it has a large community where you can seek help, which makes Python one of the best programming languages for beginners.
Python is an interpreted language, which means that code does not need to be compiled before running, i.e., the program executes directly without being compiled into machine language. This type of language makes programming more convenient. Interpreted languages also have some hidden advantages, such as not needing to declare variable types. We do not need to explicitly declare whether a variable is a string, number, or list; the interpreter determines this when executing the code.
There are two ways to start the Python interpreter:
1. Run it as an interactive shell, executing commands one by one
2. Run it as a command-line program, executing standalone scripts written in Python
The integrated development environment (IDE) for Python on the Raspbian system is IDLE. The following image shows how to find this program.
Python Version of Hello World
As mentioned earlier, Python programs can be run/executed in two different ways. Next, let’s say “Hello World” using both methods.
Method 1:
1. Open IDLE3 from the desktop icon or Start Menu
2. Loading the IDE may take a little time
3. Once the IDE is loaded, a Python shell window will appear
4. Type the following command in the Python shell window
print(“Hello World”)
5. Press Enter and you will see the output below saying Hello World
Method 2:
1. Open IDLE3 from the desktop icon or Start Menu
2. Loading the IDE may take a little time
3. Once the IDE is loaded, a Python shell window will appear
4. In the Python shell window, click on the menu item “File” and select “New Window” from the dropdown menu
5. In the new window that appears in step 4, enter the following code
print(“Hello World”)
6. Save the file and name it HelloWorld.py
7. Open LXTerminal and enter the following command to execute the program in the file
python HelloWorld.py
More on Python
Some of us come from the Arduino world, accustomed to writing setup and loop, and calling them sketches.
In Python, sketches are called scripts, and here is an example of a Python version of setup and loop:
#setup part
initNum = 0
#repeating loop
While True:
initNum = initNum + 1
if((initNum%2)==0):
print(initNum)
The above program will print all even numbers. Running this script from IDLE, you can run the module in the menu and save the file, as shown in the image below.
You can press Ctrl+C to stop the execution of the program in the shell
In the above program, we did not use parentheses but used whitespace to separate code blocks. Whitespace is 4 spaces, and pressing the TAB key in IDLE will input 4 spaces.
Python Functions
Python is a highly structured language, where whitespace is used to determine the indentation level of logical lines, thereby determining the grouping of statements. Statements at the same level must have the same indentation, and each group of such statements becomes a block, separated from the main program as a function, which can be called from anywhere in the program.
Here is an example of using a function:
# global declaration
i=0
# define setup function
def setup():
global i
i=100
# define the loop function
def loop():
global i
i=i+1
if((i%2)==0):
print(i)
# main program
setup()
while True:
loop()
It can be noted that this program is somewhat different from the previous one:
-
1. Declare the global variable i before defining the function
-
2. Define the setup function but do not execute it
-
3. Define the loop function but do not execute it
-
4. In both functions, access the global variable using the global keyword with the variable name, which avoids creating a local variable with the same name as the global variable (scope is limited to within the function)
-
5. The main part of the program calls the setup function once and calls the loop() function in an infinite while loop
Keywords
Conditional Keywords
The table below lists keywords related to conditional statements and their brief descriptions:
if Used to determine which statement to execute
else Optional, executes the statement after the else keyword when the condition is false
elif Represents else if. If the previous test result is false, this statement is executed
not Logical NOT operator
or Logical OR operator
and Logical AND operator
is Tests object identity
TRUE Boolean value true
FALSE Boolean value false
Loop Keywords
The table below lists keywords related to loop statements and their brief descriptions:
for Iterates through all elements in the collection in order
while Controls the flow of the program
break Ends the loop and exits the loop body
as Used to give a module an alias
continue Ends the current loop, starts the next loop
Built-in Function Keywords
The table below lists keywords related to built-in functions and their brief descriptions:
print Outputs to the console
pass Does nothing
del Deletes an object
Class and Module Related Keywords
The table below lists keywords related to classes and modules and their descriptions:
class Used to create user-defined objects
def Used to create user-defined functions
global Accesses global variables defined outside the function
lambda Creates an anonymous function
exec Dynamically executes Python code
yield Used in constructors
import Imports other modules into Python scripts
return Exits the function and returns a value
from Imports specified variables, classes, or functions from a module
Error Handling Keywords
The table below lists keywords related to error handling and their brief descriptions:
try Specifies an exception handler
except Catches exceptions and executes corresponding code
finally Always executed at the end, used to clean up resources
raise Creates user-defined exceptions
assert Assertion
Setting Up the Programming Environment
Installing VIM
Many people are familiar with the Vi editor. The VIM editor is an upgraded version of Vi, which not only includes all the features of Vi but also adds some functionalities and improves Vi.
Below is the command to install vim:
sudo apt-get install vim
Use the following command to edit text with vim:
vim mynewProgram.py
Vim has a graphical version that can be installed separately. This version opens a new window that supports mouse operations.
sudo apt-get install vim-gnome
Installing Python
Generally, the latest version of Python is already installed on Raspberry Pi. If not, you can install or update Python using the command below:
sudo apt-get install python-dev
Installing RPi.GPIO
After installing Python, you can install the RPi.GPIO module, which is used to control the input and output interfaces of Raspberry Pi.
Below is the command to install or upgrade the module:
sudo apt-get install python-rpi.gpio
Python Debugging:
When writing code, you will often encounter errors and need to debug to find the cause of the problem.
The interactive mode of IDLE is the best tool for debugging Python. The debugging menu has some tools for analyzing code/programs, and you can also observe the changes of each variable by executing the code line by line, just like other high-level languages and their integrated development environments.
Syntax Error The most common error, easy to correct. Usually a typo or misuse of keywords
Semantic Error Logical error, i.e., the program syntax is correct but the result is incorrect. Usually difficult to locate the error, IDLE can help us find the cause by executing the code line by line
Just like having excellent programming skills, having excellent debugging skills is also very important and requires years of practice and experience. Below are some debugging exercises to help us debug Python programs on Raspberry Pi.
Debugging Tips
1. Use the print() function to output the execution status at specified locations in the code
2. Use print() to output the value of variables
3. Check if spaces are correct
4. The beginning of a line may show syntax errors detected by the interpreter; at this time, we need to go back and check for syntax errors
5. Pay attention to the use of global and local variables
6. Parentheses should match
7. Use parentheses to ensure execution order when unsure about operator precedence
1. For example: 5+8*3 and (5+8)*3 are not the same
C Programming
Installing BCM2835-C
The C library for Raspberry Pi can be downloaded from the link below:
http://www.airspayce.com/mikem/bcm2835
The following is a quote from airspyace regarding this library:
“This is a C library for Raspberry Pi. It is used to control the general input and output interfaces and other input and output functions on the Broadcom BCM2835 chip, allowing you to control and access various external devices through the 26 pins on the RPi board.
Functions are provided for SPI and I2C data access, as well as controlling system timers. It supports polling pin event detection (interrupts are not supported).
Compatible with C++, it can be installed as a header file and non-shared library on any Linux distribution (but will not work on development boards other than Raspberry Pi or other BCM 2835 boards).”
Below are the installation steps. Execute the commands in order:
Download the tar file from the website:
wget http://www.airspayce.com/mikem/bcm2835/bcm2835-1.35.tar.gz
Extract the library:
tar -xvzf bcm2835-1.35.tar.gz
Enter the extracted folder:
cd bcm2835-1.35
Run the configuration command:
./configure
Compile the library:
make
Check the compilation:
sudo make check
Install the library:
sudo make install
Test the installation with the following program, which sets the LED on Raspberry Pi to blink every 500 milliseconds:
#include <bcm2835.h>
#define MY_PIN RPI_GPIO_P1_11
BOOLEAN main(int argc, char **argv)
{
if (!bcm2835_init())
return FALSE;
bcm2835_gpio_fsel(MY_PIN, BCM2835_GPIO_FSEL_OUTP);
while (1=1)
{
bcm2835_gpio_write(MY_PIN, HIGH);
bcm2835_delay(700);
bcm2835_gpio_write(MY_PIN, LOW);
bcm2835_delay(700);
}
bcm2835_close();
return TRUE;
}
Then compile the code:
gcc -o blink blink.c -lbcm2835
Run the program with administrator privileges:
sudo ./blink
Installing WiringPi
Below is the link to the open-source project WiringPi and a quote from the project description:
WiringPi is a C library for controlling the BCM2835 GPIO on Raspberry Pi. Released under the GNULGPLv3 license, it can be used with C and C++ as well as many other languages (with appropriate wrappers), and is similar to Arduino’s “wiring system”.
Here are the steps to install WiringPi:
sudo apt-get update
sudo apt-get upgrade
apt-get install git-core
git clone git://git.drogon.net/wiringPi
cd wiringPi
git pull origin
cd wiringPi
./build
Check if WiringPi is installed successfully:
gpio -v
gpio readall
Programming a Light Sensor in C
The following program reads the light intensity and outputs it:
#include <wiringPi.h>
#include <stdio.h>
#define G_1 0
#define G_2 1
#define G_3 2
typedef unsigned char gchar;
gchar get_Result(void)
{
gchar i;
gchar dat1=0, dat2=0;
digitalWrite(G_1, 0);
digitalWrite(G_2,0);
digitalWrite(G_3,1);
delayMicroseconds(2);
digitalWrite(G_2,1);
delayMicroseconds(2);
digitalWrite(G_2,0);
digitalWrite(G_3,1);
delayMicroseconds(2);
digitalWrite(G_2,1);
delayMicroseconds(2);
digitalWrite(G_2,0);
digitalWrite(G_3,0);
delayMicroseconds(2);
digitalWrite(G_2,1);
digitalWrite(G_3,1);
delayMicroseconds(2);
digitalWrite(G_2,0);
digitalWrite(G_3,1);
delayMicroseconds(2);
for(i=0;i<8;i++)
{
digitalWrite(G_2,1);
delayMicroseconds(2);
digitalWrite(G_2,0);
delayMicroseconds(2);
pinMode(G_3, INPUT);
dat1=dat1<<1 | digitalRead(G_3);
}
for(i=0;i<8;i++)
{
dat2 = dat2 | ((gchar)(digitalRead(G_3))<<i);
digitalWrite(G_2,1);
delayMicroseconds(2);
digitalWrite(G_2,0);
delayMicroseconds(2);
}
digitalWrite(G_1,1);
if(dat1==dat2)
{
return dat1 ;
}
else
return 0;
}
int main(void)
{
gchar rawValue;
gchar calculate_Value;
if(wiringPiSetup() == -1){
printf(“Failure with calling a wiringPi method!”);
return 1;
}
pinMode(G_1, OUTPUT);
pinMode(G_2, OUTPUT);
while(1){
pinMode(G_3, OUTPUT);
rawValue = get_Result();
calculate_Value = 210 – rawValue;
printf(“Current calculate_Value: %d\n”, calculate_Value);
delay(500);
}
return 0;
}
Below is the breadboard connection:
Now we know how to program Raspberry Pi using Python and C, let me know in the comments which language you prefer and why.
Original English text: http://www.codeproject.com/Articles/850842/Setting-up-and-Programming-Raspberry-Pi-in-Python
Translator: cmsl
Leave a Comment
Your email address will not be published. Required fields are marked *