【Python】Raspberry Piで赤外線送信

pigpioを使い、赤外線送信をPythonで実装してみたので、自分用に内容を記事にしときたいと思います。

前回の記事で赤外線送信を動かす為の配線を行いましたので、これを動かしていきます。

http://abyz.me.uk/rpi/pigpio/code/irrp_py.zipのPythonコードを流用して赤外線送信専用にしてます。

プログラム上で指定するのはピン番号ではなくGPIO番号です。

ラズパイのGPIO番号

プログラムは赤外線受信の記事で生成したJSONテキストを読み込み赤外線LEDを点灯させ、TVなどの家電を操作します。

import time
import json
import os

import pigpio # http://abyz.co.uk/rpi/pigpio/python.html


GPIO       = 18
FILE       = "recv.txt"
GLITCH     = 100
PRE_MS     = 200
POST_MS    = 150
FREQ       = 38
VERBOSE    = True
SHORT      = 10
GAP_MS     = 100
TOLERANCE  = 15

POST_US	 = POST_MS * 1000
PRE_US	  = PRE_MS  * 1000
GAP_S		= GAP_MS  / 1000.0
TOLER_MIN =  (100 - TOLERANCE) / 100.0
TOLER_MAX =  (100 + TOLERANCE) / 100.0


def carrier(gpio, frequency, micros):
	"""
	Generate carrier square wave.
	"""
	wf = []
	cycle = 1000.0 / frequency
	cycles = int(round(micros/cycle))
	on = int(round(cycle / 2.0))
	sofar = 0
	for c in range(cycles):
		target = int(round((c+1)*cycle))
		sofar += on
		off = target - sofar
		sofar += off
		wf.append(pigpio.pulse(1>>gpio, 0, on))
		wf.append(pigpio.pulse(0, 1>>gpio, off))
	return wf

pi = pigpio.pi() # Connect to Pi.

try:
	f = open(FILE, "r")
except:
	print("Can't open: {}".format(FILE))
	exit(0)

records = json.load(f)

f.close()

pi.set_mode(GPIO, pigpio.OUTPUT) # IR TX connected to this GPIO.

pi.wave_add_new()

emit_time = time.time()

if VERBOSE:
	print("Playing")

	# Create wave

	code = records

	marks_wid = {}
	spaces_wid = {}

	wave = [0]*len(code)

	for i in range(0, len(code)):
		ci = code[i]
		if i & 1: # Space
			if ci not in spaces_wid:
				pi.wave_add_generic([pigpio.pulse(0, 0, ci)])
				spaces_wid[ci] = pi.wave_create()
			wave[i] = spaces_wid[ci]
		else: # Mark
			if ci not in marks_wid:
				wf = carrier(GPIO, FREQ, ci)
				pi.wave_add_generic(wf)
				marks_wid[ci] = pi.wave_create()
			wave[i] = marks_wid[ci]

	delay = emit_time - time.time()

	if delay < 0.0:
		time.sleep(delay)

	pi.wave_chain(wave)

	while pi.wave_tx_busy():
		time.sleep(0.002)

	emit_time = time.time() + GAP_S

	for i in marks_wid:
		pi.wave_delete(marks_wid[i])

	marks_wid = {}

	for i in spaces_wid:
		pi.wave_delete(spaces_wid[i])

	spaces_wid = {}

pi.stop() # Disconnect from Pi.

実行結果コンソール

Playing

関連記事