Raspberry PI上操作GPIO(GPIO编程)

一 Raspberry PI的GPIO

1. 什么是GPIO

2. Raspberry上的GPIO介绍

 

二Raspberry PI上编程操作GPIO

1. Python操作

(1) 安装环境

     a.下载控制GPIO的python库:http://pypi.python.org/pypi/RPi.GPIO/0.3.1a#downloads

     b. 在Pi上安装python-dev: sudo apt-get install python-dev

     c. 解压并安装python库

          tar xvzf RPi.GPIO-0.x.xx.tar.gz

          cd RPi.GPIO-0.x.xx

          sudo python setup.py install

 (2)测试程序

    说明:led灯闪烁(分别接pi-01 和pi-11,11作为输出)

import RPi.GPIO as GPIO
import time

def blink(times, delay):
	GPIO.setmode(GPIO.BOARD)
	GPIO.setup(11, GPIO.OUT)

	while times>0:
		if 0==times%2:
			GPIO.output(11, GPIO.HIGH) #or output(11, GPIO.True)
		else:
			GPIO.output(11, GPIO.LOW)
		time.sleep(delay)
		times-=1
	return


if __name__ == '__main__':
	blink(20, 1)

  (3)测试程序2——远程点亮/关闭相应的led灯

  说明:和上个例子不同的就是a)用到了远程控制,即socket通信;b)操作多个led;

  究其本质是一样。当然本人之所以要远程控制,只不过是为了以后远程管理更多的外设做个铺垫。

  文件1:remoIO.py

import socket
import time
g_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def init(ip, port):
    g_sock.connect((ip, port))
    time.sleep(2)
    return

def send(data):
    g_sock.send(data)
    return

def read():
    data = g_sock.recv(1024)
    return data

def end():
    g_sock.close()
    return

def _test(ip, port):
    sock = init(ip, port)
    send("I am Raspberry Pi\r\n!");
    print read(1024);
    sock.close()
    return

if __name__=='__main__':
    #_test('192.168.2.1', 9999)
    import sys
    if len(sys.argv) == 3:
        _test(sys.argv[1], int(sys.argv[2]))
    else:
        print 'usage:'+sys.argv[0]+' ip  port\r\n'
    

  文件2:blink.py

  

import RPi.GPIO as GPIO
import time
import remoIO


ip = '192.168.2.12'
port = 8888
def blink(times, delay):

	R=11
	Y=12
	W=15
	GPIO.setmode(GPIO.BOARD)
	GPIO.setup(R, GPIO.OUT)
	GPIO.setup(Y, GPIO.OUT)
	GPIO.setup(W, GPIO.OUT)

	remoIO.init(ip, port)
	remoIO.send('Now, you can input 1,2 or 3 to turnon  the right led:')
	#in order to initial a communication protocol, add code here
	#....
	command = ''
	while 1:
		command = remoIO.read()
		if command=='1\n':
			GPIO.output(R, GPIO.LOW)
			time.sleep(2)
			GPIO.output(R, GPIO.HIGH)
			remoIO.send('ok for 1\t')
		elif command=='2\n':
			GPIO.output(Y, GPIO.LOW)
			time.sleep(2)
			GPIO.output(Y, GPIO.HIGH)
			remoIO.send('ok for 2\t')
		elif command=='3\n':
			GPIO.output(W, GPIO.LOW)
			time.sleep(2)
			GPIO.output(W, GPIO.HIGH)
			remoIO.send('ok or 3\t')
		elif command=='quit\n':
			remoIO.send('end remote control!\r\n')
			remoIO.end()
			break
		else:
			remoIO.send('eroor input!\r\n')

	while times>0:
		if 0==times%2:
			GPIO.output(R, GPIO.HIGH) #or output(R, GPIO.True)
		else:
			GPIO.output(R, GPIO.LOW)
		time.sleep(delay)
		times-=1
	return


if __name__ == '__main__':
	blink(10, 0.5)

 

 

 

    

posted on 2012-09-22 01:44  rainduck  阅读(18210)  评论(0编辑  收藏  举报

导航