Course Number:3111400300
Course:Comprehensive Experiments for Communications
Credit(s):Two credits,36 hours
Question1:Please write a code (in C or Python) to program Raspberry Pi to make an LEDblink
Answer:
Step 0: Build the circuit
For C language:
Step 1: Writingthe code
#include <wiringPi.h>
#include <stdio.h>
#define LedPin 0
int main(void)
{
if(wiringPiSetup() == -1){ //wheninitialize wiring failed,print messageto screen
printf("setup wiringPi failed!");
return 1;
}
printf("linker LedPin : GPIO%d(wiringPi pin)\n",LedPin); //when initialize wiring successfully,printmessage to screen
pinMode(LedPin, OUTPUT);
while(1){
digitalWrite(LedPin, LOW); //led on
printf("led on...\n");
delay(500);
digitalWrite(LedPin, HIGH); //led off
printf("...led off\n");
return 0;
Step 2: Changedirectory to your code location
Step 3: Compile
gccled.c –o led –lwiringPi
Step 4: Run
sudo./led
For Python language:
Step 1: Writing the code
import RPi.GPIO as GPIO
import time
LedPin = 11 # pin11
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOsby physical location
GPIO.setup(LedPin, GPIO.OUT) # SetLedPin's mode is output
GPIO.output(LedPin, GPIO.HIGH) # SetLedPin high(+3.3V) to off led
def loop():
while True:
print '...led on'
GPIO.output(LedPin, GPIO.LOW) # led on
time.sleep(0.5)
print 'led off...'
GPIO.output(LedPin, GPIO.HIGH) # led off
def destroy():
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program startfrom here
setup()
try:
loop()
except KeyboardInterrupt: # When'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
Step 3: Run
sudo python 01_led.py
Now, you should see the LED blinking
Question 2: Please write a code (in C orPython) to turn an LED on or off by a button.
Step2: Writing acode
#define ButtonPin 1
pinMode(ButtonPin, INPUT);
pullUpDnControl(ButtonPin, PUD_UP); //pull upto 3.3V,make GPIO1 a stable level
digitalWrite(LedPin, HIGH);
if(digitalRead(ButtonPin) == 0){//indicate that button has pressed down
gcc BtnAndLed.c –o BtnAndLed –lwiringPi
sudo./BtnAndLed
For Python users:
Step 1: Writing a code
#!/usr/bin/env pythonimport RPi.GPIO as GPIO
LedPin = 11 # pin11 --- ledBtnPin = 12 # pin12 --- button
Led_status = 1
def setup():GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical locationGPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is outputGPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode isinput, and pull up to high level(3.3V)GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led
def swLed(ev=None):global Led_statusLed_status = not Led_statusGPIO.output(LedPin, Led_status) # switch led status(on-->off; off-->on)if Led_status == 1:print 'led off...'else:print '...led on'
def loop():GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLed) # wait for fallingwhile True:pass # Don't do anything
def destroy():GPIO.output(LedPin, GPIO.HIGH) # led offGPIO.cleanup() # Release resource
if __name__ == '__main__': # Program startfrom heresetup()try:loop()except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child programdestroy() will be executed.destroy()
sudo python 02_btnAndLed.py
Through this experiment, you have learnt howto control the GPIOs of the Raspberry Pi by programming.
Question 3: Writing a code to make abreathing LED by Raspberry Pi
For C language users:
Step 1: Writing acode
#include <wiringPi.h>#include <stdio.h>
#define LedPin 1
int main(void){int i;
if(wiringPiSetup() == -1){ //wheninitialize wiring failed,print messageto screenprintf("setup wiringPi failed !");return 1; }pinMode(LedPin, PWM_OUTPUT);//pwm output mode
while(1){for(i=0;i<1024;i++){pwmWrite(LedPin, i);delay(2);}delay(1000);for(i=1023;i>=0;i--){pwmWrite(LedPin, i);delay(2);}}
return 0;}
gcc PwmLed.c –o PwmLed -lwiringPi
sudo./PwmLed
#!/usr/bin/env python
LedPin = 12
global p
GPIO.output(LedPin, GPIO.LOW) # SetLedPin to low(0V)
p = GPIO.PWM(LedPin, 1000) # set Frequece to1KHz
p.start(0) # Duty Cycle = 0
for dc in range(0, 101, 4): # Increaseduty cycle: 0~100
p.ChangeDutyCycle(dc) # Change dutycycle
time.sleep(0.05)
time.sleep(1)
for dc in range(100, -1, -4): # Decreaseduty cycle: 100~0
p.ChangeDutyCycle(dc)
p.stop()
GPIO.output(LedPin, GPIO.HIGH) # turnoff all leds
GPIO.cleanup()
sudopython 04_pwmLed.py
Question 4: Using Raspberry Pi to control aRGB LED
#include <wiringPi.h>#include <softPwm.h>#include <stdio.h>
#define uchar unsigned char
#define LedPinRed 0#define LedPinGreen 1#define LedPinBlue 2
void ledInit(void){softPwmCreate(LedPinRed, 0, 100);softPwmCreate(LedPinGreen,0, 100);softPwmCreate(LedPinBlue, 0, 100);}
void ledColorSet(uchar r_val, uchar g_val,uchar b_val){softPwmWrite(LedPinRed, r_val);softPwmWrite(LedPinGreen, g_val);softPwmWrite(LedPinBlue, b_val);}
if(wiringPiSetup() == -1){ //wheninitialize wiring failed,print messageto screenprintf("setup wiringPi failed !");return 1; }//printf("linker LedPin : GPIO %d(wiringPi pin)\n",LedPin); //wheninitialize wiring successfully,print message to screen
ledInit();
while(1){ledColorSet(0xff,0x00,0x00); //red delay(500);ledColorSet(0x00,0xff,0x00); //greendelay(500);ledColorSet(0x00,0x00,0xff); //bluedelay(500);
ledColorSet(0xff,0xff,0x00); //yellowdelay(500);ledColorSet(0xff,0x00,0xff); //pickdelay(500);ledColorSet(0xc0,0xff,0x3e);delay(500);
ledColorSet(0x94,0x00,0xd3);delay(500);ledColorSet(0x76,0xee,0x00);delay(500);ledColorSet(0x00,0xc5,0xcd); delay(500);
gccrgb.c -o rgb –lwiringPi -lpthread
sudo./rgb
import RPi.GPIO as GPIOimport time
colors = [0xFF0000, 0x00FF00, 0x0000FF,0xFFFF00, 0xFF00FF, 0x00FFFF]pins = {'pin_R':11, 'pin_G':12, 'pin_B':13} # pins is a dict
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs byphysical locationfor i in pins:GPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is outputGPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off led
p_R = GPIO.PWM(pins['pin_R'], 2000) # setFrequece to 2KHzp_G = GPIO.PWM(pins['pin_G'], 2000)p_B = GPIO.PWM(pins['pin_B'], 5000)
p_R.start(0) # Initial duty Cycle = 0(ledsoff)p_G.start(0)p_B.start(0)
def map(x, in_min, in_max, out_min,out_max):return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def setColor(col): # For example : col =0x112233R_val = (col & 0x110000) >> 16G_val = (col & 0x001100) >> 8B_val = (col & 0x000011) >> 0R_val = map(R_val, 0, 255, 0, 100)G_val = map(G_val, 0, 255, 0, 100)B_val = map(B_val, 0, 255, 0, 100)p_R.ChangeDutyCycle(R_val) # Change duty cyclep_G.ChangeDutyCycle(G_val)p_B.ChangeDutyCycle(B_val)
try:while True:for col in colors:setColor(col)time.sleep(0.5)except KeyboardInterrupt:p_R.stop()p_G.stop()p_B.stop()for i in pins:GPIO.output(pins[i], GPIO.HIGH) # Turn off all ledsGPIO.cleanup()
sudo python 05_rgb.py
Question 5: Using Raspberry Pi to controlLCD1602 to display character strings
#include <stdio.h>#include <stdlib.h>#include <wiringPi.h>#include <lcd.h>
const unsigned char Buf[] ="---SUNFOUNDER---";const unsigned char myBuf[] = " sunfounder.com";
int main(void){int fd;int i;if (wiringPiSetup() == -1){exit(1);}
fd = lcdInit(2,16,4, 2,3, 6,5,4,1,0,0,0,0);//see /usr/local/include/lcd.hprintf("%d", fd);if (fd == -1){printf("lcdInit 1 failed\n") ;return 1;}sleep(1);
lcdClear(fd);lcdPosition(fd, 0, 0); lcdPuts(fd, "Welcom To--->");
lcdPosition(fd, 0, 1); lcdPuts(fd, " sunfounder.com");
sleep(1);lcdClear(fd);
while(1){for(i=0;i<sizeof(Buf)-1;i++){lcdPosition(fd, i, 1);lcdPutchar(fd, *(Buf+i));delay(200);}lcdPosition(fd, 0, 1); lcdClear(fd);sleep(0.5);for(i=0; i<16; i++){lcdPosition(fd, i, 0);lcdPutchar(fd, *(myBuf+i));delay(100);}}
Step 2: Changedirectory
gcclcd1602_2.c –o lcd1602_2 –lwiringPiDev –lwiringPi
sudo./lcd0602_2
For Python users
## based on code from lrvick and LiquidCrystal# lrvic - https://github.com/lrvick/raspi-hd44780/blob/master/hd44780.py# LiquidCrystal -https://github.com/arduino/Arduino/blob/master/libraries/LiquidCrystal/LiquidCrystal.cpp#
from time import sleep
class Adafruit_CharLCD:
# commandsLCD_CLEARDISPLAY = 0x01LCD_RETURNHOME = 0x02LCD_ENTRYMODESET = 0x04LCD_DISPLAYCONTROL = 0x08LCD_CURSORSHIFT = 0x10LCD_FUNCTIONSET = 0x20LCD_SETCGRAMADDR = 0x40LCD_SETDDRAMADDR = 0x80
# flags for display entry modeLCD_ENTRYRIGHT = 0x00LCD_ENTRYLEFT = 0x02LCD_ENTRYSHIFTINCREMENT = 0x01LCD_ENTRYSHIFTDECREMENT = 0x00
# flags for display on/off controlLCD_DISPLAYON = 0x04LCD_DISPLAYOFF = 0x00LCD_CURSORON = 0x02LCD_CURSOROFF = 0x00LCD_BLINKON = 0x01LCD_BLINKOFF = 0x00
# flags for display/cursor shiftLCD_DISPLAYMOVE = 0x08LCD_CURSORMOVE = 0x00
# flags for display/cursor shiftLCD_DISPLAYMOVE = 0x08LCD_CURSORMOVE = 0x00LCD_MOVERIGHT = 0x04LCD_MOVELEFT = 0x00
# flags for function setLCD_8BITMODE = 0x10LCD_4BITMODE = 0x00LCD_2LINE = 0x08LCD_1LINE = 0x00LCD_5x10DOTS = 0x04LCD_5x8DOTS = 0x00
def __init__(self, pin_rs=27, pin_e=22,pins_db=[25, 24, 23, 18], GPIO = None):# Emulate the old behavior of using RPi.GPIO if we haven't been given# an explicit GPIO interface to useif not GPIO:import RPi.GPIO as GPIOself.GPIO = GPIOself.pin_rs = pin_rsself.pin_e = pin_eself.pins_db = pins_db
self.GPIO.setmode(GPIO.BCM)self.GPIO.setup(self.pin_e, GPIO.OUT)self.GPIO.setup(self.pin_rs, GPIO.OUT)
for pin in self.pins_db:self.GPIO.setup(pin, GPIO.OUT)
self.write4bits(0x33) # initializationself.write4bits(0x32) # initializationself.write4bits(0x28) # 2 line 5x7 matrixself.write4bits(0x0C) # turn cursor off 0x0E to enable cursorself.write4bits(0x06) # shift cursor right
self.displaycontrol = self.LCD_DISPLAYON |self.LCD_CURSOROFF | self.LCD_BLINKOFF
self.displayfunction = self.LCD_4BITMODE |self.LCD_1LINE | self.LCD_5x8DOTSself.displayfunction |= self.LCD_2LINE
""" Initialize to defaulttext direction (for romance languages) """self.displaymode = self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode) # set the entry mode
self.clear()
def begin(self, cols, lines):
if (lines > 1):self.numlines = linesself.displayfunction |= self.LCD_2LINEself.currline = 0
def home(self):
self.write4bits(self.LCD_RETURNHOME) # setcursor position to zeroself.delayMicroseconds(3000) # this command takes a long time!
def clear(self):
self.write4bits(self.LCD_CLEARDISPLAY) #command to clear displayself.delayMicroseconds(3000) # 3000 microsecond sleep, clearing the displaytakes a long time
def setCursor(self, col, row):
self.row_offsets = [ 0x00, 0x40, 0x14, 0x54]
if ( row > self.numlines ): row = self.numlines - 1 # we count rows starting w/0
self.write4bits(self.LCD_SETDDRAMADDR |(col + self.row_offsets[row]))
def noDisplay(self): """ Turn the display off (quickly) """
self.displaycontrol &=~self.LCD_DISPLAYONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def display(self):""" Turn the display on (quickly) """
self.displaycontrol |= self.LCD_DISPLAYONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def noCursor(self):""" Turns the underline cursor on/off """
self.displaycontrol &= ~self.LCD_CURSORONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def cursor(self):""" Cursor On """
self.displaycontrol |= self.LCD_CURSORONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def noBlink(self):""" Turn on and off the blinking cursor """
self.displaycontrol &=~self.LCD_BLINKONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)
def DisplayLeft(self):""" These commands scroll the display without changing the RAM"""
self.write4bits(self.LCD_CURSORSHIFT |self.LCD_DISPLAYMOVE | self.LCD_MOVELEFT)
def scrollDisplayRight(self):""" These commands scroll the display without changing the RAM"""
self.write4bits(self.LCD_CURSORSHIFT |self.LCD_DISPLAYMOVE | self.LCD_MOVERIGHT);
def leftToRight(self):""" This is for text that flows Left to Right """
self.displaymode |= self.LCD_ENTRYLEFTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode);
def rightToLeft(self):""" This is for text that flows Right to Left """self.displaymode &= ~self.LCD_ENTRYLEFTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode)
def autoscroll(self):""" This will 'right justify' text from the cursor"""
self.displaymode |=self.LCD_ENTRYSHIFTINCREMENTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode)
def noAutoscroll(self): """ This will 'left justify' text from the cursor"""
self.displaymode &= ~self.LCD_ENTRYSHIFTINCREMENTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode)
def write4bits(self, bits, char_mode=False):""" Send command to LCD """
self.delayMicroseconds(1000) # 1000microsecond sleep
bits=bin(bits)[2:].zfill(8)
self.GPIO.output(self.pin_rs, char_mode)
for pin in self.pins_db:self.GPIO.output(pin, False)
for i in range(4):if bits[i] == "1":self.GPIO.output(self.pins_db[::-1][i], True)
self.pulseEnable()
for i in range(4,8):if bits[i] == "1":self.GPIO.output(self.pins_db[::-1][i-4], True)
def delayMicroseconds(self, microseconds):seconds = microseconds / float(1000000) # divide microseconds by 1 million forsecondssleep(seconds)
def pulseEnable(self):self.GPIO.output(self.pin_e, False)self.delayMicroseconds(1) # 1 microsecond pause - enable pulse must be >450ns self.GPIO.output(self.pin_e, True)self.delayMicroseconds(1) # 1 microsecond pause - enable pulse must be >450ns self.GPIO.output(self.pin_e, False)self.delayMicroseconds(1) # commands need > 37us to settle
def message(self, text):""" Send string to LCD. Newline wraps to secondline"""
for char in text:if char == '\n':self.write4bits(0xC0) # next lineelse:self.write4bits(ord(char),True)
def loop():lcd = Adafruit_CharLCD()while True:lcd.clear()lcd.message(" LCD 1602 Test \n123456789ABCDEF")sleep(2)lcd.clear()lcd.message(" SUNFOUNDER \nHello World ! :)")sleep(2)lcd.clear()lcd.message("Welcom to --->\n sunfounder.com")sleep(2)
if __name__ == '__main__':loop()
cd /home/pi/Sunfounder_SuperKit_ Python_code_for_RaspberryPi/
sudo python 13_lcd1602.py
Copyright © Beijing University of Posts and Telecommunications