Course resource
Syllabus

Course Number3111400300

CourseComprehensive Experiments for Communications

Credit(s)Two credits,36 hours

Course Description:The module of comprehensive experiments for communications includes two parts: Simulation of communication systems ……
Your location now is: Home > Course resource > Exam&answers
Exam & Answer

Question1Please write a code (in C or Python) to program Raspberry Pi to make an LEDblink

 

Answer:

Step 0: Build the circuit

https://www.sunfounder.com/media/wysiwyg/swatches/Super_kit_v2_for_raspberrypi/1_Blinking_LED/2.png

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");

delay(500);

}

 

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

time.sleep(0.5)

 

def destroy():

GPIO.output(LedPin, GPIO.HIGH) # led off

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 2: Changedirectory to your code location

 

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.

 

Answer:

Step 0: Build the circuit

For C language:

Step2: Writing acode

#include <wiringPi.h>

#include <stdio.h>

 

#define LedPin 0

#define ButtonPin 1

 

int main(void)

{

if(wiringPiSetup() == -1){ //wheninitialize wiring failed,print messageto screen

printf("setup wiringPi failed!");

return 1;

}

 

pinMode(LedPin, OUTPUT);

pinMode(ButtonPin, INPUT);

 

pullUpDnControl(ButtonPin, PUD_UP); //pull upto 3.3V,make GPIO1 a stable level

while(1){

digitalWrite(LedPin, HIGH);

if(digitalRead(ButtonPin) == 0){//indicate that button has pressed down

digitalWrite(LedPin, LOW); //led on

}

}

 

return 0;

}

Step 2: Changedirectory to your code location

 

Step 3: Compile

gcc BtnAndLed.c –o BtnAndLed –lwiringPi

 

Step 4: Run

      sudo./BtnAndLed  

 

For Python users:

Step 1: Writing a code

#!/usr/bin/env python
import RPi.GPIO as GPIO

LedPin = 11 # pin11 --- led
BtnPin = 12 # pin12 --- button

Led_status = 1

def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output
GPIO.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_status
Led_status = not Led_status
GPIO.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 falling
while True:
pass # Don't do anything

def destroy():
GPIO.output(LedPin, GPIO.HIGH) # led off
GPIO.cleanup() # Release resource

if __name__ == '__main__': # Program startfrom here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child programdestroy() will be executed.
destroy()

Step 2: Changedirectory to your code location

 

Step 3: Run

        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

 

Answer:

Step 0: Build the circuit

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 screen
printf("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;
}

Step 2: Changedirectory to your code location

 

Step 3: Compile

        gcc PwmLed.c –o PwmLed -lwiringPi  

 

Step 4: Run

      sudo./PwmLed  

 

For Python users:

Step 1: Writing acode

#!/usr/bin/env python

import RPi.GPIO as GPIO

import time

 

LedPin = 12

 

def setup():

global p

GPIO.setmode(GPIO.BOARD) # Numbers GPIOsby physical location

GPIO.setup(LedPin, GPIO.OUT) # SetLedPin's mode is output

GPIO.output(LedPin, GPIO.LOW) # SetLedPin to low(0V)

 

p = GPIO.PWM(LedPin, 1000) # set Frequece to1KHz

p.start(0) # Duty Cycle = 0

 

def loop():

while True:

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)

time.sleep(0.05)

time.sleep(1)

 

def destroy():

p.stop()

GPIO.output(LedPin, GPIO.HIGH) # turnoff all leds

GPIO.cleanup()

 

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 2: Changedirectory to your code location

 

Step 3: Run

      sudopython 04_pwmLed.py  


 

Question 4: Using Raspberry Pi to control aRGB LED

 

Answer:

Step 0: Build the circuit

 

For C language users:

Step 1: Writing acode

#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);
}

int main(void)
{
int i;

if(wiringPiSetup() == -1){ //wheninitialize wiring failed,print messageto screen
printf("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); //green
delay(500);
ledColorSet(0x00,0x00,0xff); //blue
delay(500);

ledColorSet(0xff,0xff,0x00); //yellow
delay(500);
ledColorSet(0xff,0x00,0xff); //pick
delay(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);

}

return 0;
}

Step 2: Changedirectory to your code location

 

Step 3: Compile

      gccrgb.c -o rgb –lwiringPi -lpthread  

 

Step 4: Run

      sudo./rgb  

 

For Python users:

Step 1: Writing acode

import RPi.GPIO as GPIO
import 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 location
for i in pins:
GPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is output
GPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off led

p_R = GPIO.PWM(pins['pin_R'], 2000) # setFrequece to 2KHz
p_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 =0x112233
R_val = (col & 0x110000) >> 16
G_val = (col & 0x001100) >> 8
B_val = (col & 0x000011) >> 0

R_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 cycle
p_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 leds
GPIO.cleanup()

Step 2: Changedirectory to your code location

 

Step 3: Run

        sudo python 05_rgb.py  


 

Question 5: Using Raspberry Pi to controlLCD1602 to display character strings

 

Answer:

Step 0: Build the circuit

For C language users:

Step 1: Writing acode

#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.h
printf("%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);
}
}

return 0;
}

Step 2: Changedirectory

 

Step 3: Compile

      gcclcd1602_2.c –o lcd1602_2 –lwiringPiDev –lwiringPi

 

Step 4: Run

      sudo./lcd0602_2  

 

For Python users

Step 1: Writing acode

#!/usr/bin/env python

#
# 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:

# commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80

# flags for display entry mode
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00

# flags for display on/off control
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00

# flags for display/cursor shift
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00

# flags for display/cursor shift
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
LCD_MOVERIGHT = 0x04
LCD_MOVELEFT = 0x00

# flags for function set
LCD_8BITMODE = 0x10
LCD_4BITMODE = 0x00
LCD_2LINE = 0x08
LCD_1LINE = 0x00
LCD_5x10DOTS = 0x04
LCD_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 use
if not GPIO:
import RPi.GPIO as GPIO
self.GPIO = GPIO
self.pin_rs = pin_rs
self.pin_e = pin_e
self.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) # initialization
self.write4bits(0x32) # initialization
self.write4bits(0x28) # 2 line 5x7 matrix
self.write4bits(0x0C) # turn cursor off 0x0E to enable cursor
self.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_5x8DOTS
self.displayfunction |= self.LCD_2LINE

""" Initialize to defaulttext direction (for romance languages) """
self.displaymode = self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENT
self.write4bits(self.LCD_ENTRYMODESET | self.displaymode) # set the entry mode

self.clear()


def begin(self, cols, lines):

if (lines > 1):
self.numlines = lines
self.displayfunction |= self.LCD_2LINE
self.currline = 0


def home(self):

self.write4bits(self.LCD_RETURNHOME) # setcursor position to zero
self.delayMicroseconds(3000) # this command takes a long time!

def clear(self):

self.write4bits(self.LCD_CLEARDISPLAY) #command to clear display
self.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_DISPLAYON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)


def display(self):
""" Turn the display on (quickly) """

self.displaycontrol |= self.LCD_DISPLAYON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)


def noCursor(self):
""" Turns the underline cursor on/off """

self.displaycontrol &= ~self.LCD_CURSORON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)


def cursor(self):
""" Cursor On """

self.displaycontrol |= self.LCD_CURSORON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)


def noBlink(self):
""" Turn on and off the blinking cursor """

self.displaycontrol &=~self.LCD_BLINKON
self.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)


def noBlink(self):
""" Turn on and off the blinking cursor """

self.displaycontrol &=~self.LCD_BLINKON
self.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_ENTRYLEFT
self.write4bits(self.LCD_ENTRYMODESET | self.displaymode);


def rightToLeft(self):
""" This is for text that flows Right to Left """
self.displaymode &= ~self.LCD_ENTRYLEFT
self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)


def autoscroll(self):
""" This will 'right justify' text from the cursor"""

self.displaymode |=self.LCD_ENTRYSHIFTINCREMENT
self.write4bits(self.LCD_ENTRYMODESET | self.displaymode)


def noAutoscroll(self):
""" This will 'left justify' text from the cursor"""

self.displaymode &= ~self.LCD_ENTRYSHIFTINCREMENT
self.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 pin in self.pins_db:
self.GPIO.output(pin, False)

for i in range(4,8):
if bits[i] == "1":
self.GPIO.output(self.pins_db[::-1][i-4], True)

self.pulseEnable()


def delayMicroseconds(self, microseconds):
seconds = microseconds / float(1000000) # divide microseconds by 1 million forseconds
sleep(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 line
else:
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()

Step 2: Changedirectory

cd /home/pi/Sunfounder_SuperKit_ Python_code_for_RaspberryPi/

 

Step 3: Run

     sudo python 13_lcd1602.py

 



Address: No 10, Xitucheng Road, Haidian District, Beijing, PRC, 100876
E-mail:   slsun@bupt.edu.cn         Phone: +86-10 62283295

Copyright © Beijing University of Posts and Telecommunications