1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RPi > GPIO+UDP(v0.4..v0.6) > フットキー入力を認識しつつUDPコマンド応答する実装

Last updated at Posted at 2016-04-23

関連 http://qiita.com/7of9/items/c5e39a8c08ca7a6e5af6
関連 http://qiita.com/7of9/items/3491b41f3b18a393e2cf

v0.4

GPIO入力値をUDP通信で返すようにした。

v0.4 @ github

footInputl.py
#!/usr/bin/env python

'''
v0.4 2016 Apr 24
  - add UDP_procCommand()
v0.3 2016 Apr 23
  - add UDP_recvData()
  - add UDP_setup()
  - add GPIO_setup()
v0.2 2016 Apr 23
  - define main()
  - change interval to 10 msec base for UDP comm
v0.1 2016 Apr 23
  - can check 5 GPIO input
'''

import RPi.GPIO as GPIO
import socket
import time
import os

ins = [40, 38, 36, 32, 26]
vals = range(5)

def GPIO_setup():
    GPIO.setmode(GPIO.BOARD)
    for idx in range(5):
        GPIO.setup(ins[idx], GPIO.IN, pull_up_down=GPIO.PUD_UP)

def UDP_setup():
    # incoming data string port
    datip="" # INADDR_ANY
    datport = 7002
    datsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    datsock.bind((datip, datport))
    datsock.setblocking(0)
    return datsock

def UDP_recvData(datsock, rcvdat):
    address = ""
    try:
	data,address = datsock.recvfrom(100)
    except socket.error:
	pass
    else:
	rcvdat = rcvdat + data
	return rcvdat, True, address
    return rcvdat, False, address

def UDP_procCommand(rcvdat, datsock, rcvadr):
    if "foot" not in rcvdat:
        return
    
    ret = "foot"
    for idx in range(5):
        if vals[idx]==GPIO.HIGH:
            ret = ret + ",1"
        else:
            ret = ret + ",0"
    ret = ret + "\n"            
    datsock.sendto(ret, rcvadr)
    

def main():
    GPIO_setup()
    datsock = UDP_setup()
    
    cnt=0
    rcvdat = ""

    while True:
        cnt=cnt+1
        rcvdat,rcvd,rcvadr = UDP_recvData(datsock, rcvdat)
        time.sleep(0.01)

        if rcvd == True and "\n" in rcvdat:
            UDP_procCommand(rcvdat, datsock, rcvadr)
            rcvdat = ""

        if cnt < 30: # 300msec
            continue
        cnt=0

        for idx in range(5):
            vals[idx]=GPIO.input(ins[idx])
            print vals[idx],
        print

if __name__ == '__main__':
    main()

通信プロトコル

UDP通信は以下とした

  • ポート: 7002
送信者
foot<LF>
RPi
foot,1,0,0,1,1<LF>

実行例

RPi側で以下としておく

RPi
$ sudo python footInput.py

例としてMac OS X からのコマンド送信

$ echo "foot" | nc -u 192.168.10.6 7002
foot,1,0,0,1,1

code v0.6

足で踏んでからの応答性を改良するためIO取り込みのタイミングを300msecから100msecに速めた。

v0.6 @ github

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?