M♪o 之學習筆記本《巳》文章︰【䷊】包荒馮河

派生碼訊

巳 蛇

來氏《 易 》易註︰

九二,包荒,用馮河,不遐遺,朋亡,得尚于中行。

包荒者,包乎初也。初為草茅,荒穢之象也 。因本卦小往大來,陽來乎下,故包初。馮河者,二變則中爻成坎水矣,河之象也。河水在前,乾健利涉大川,馮之象也。用馮河者,用馮河之勇往也。二居柔位,故教之以勇。二變與五隔河,若馮河而往,則能就乎五矣。二與初為邇,隔三四,與五為遐。不遐遺者,不遺乎五也。朋者初也,三同陽體 ,牽連而進,二居其中,朋之象也,故咸卦中爻成乾,四居乾之中,亦曰朋從。朋亡者 ,亡乎初而事五也。尚者,尚往而事五也。中行,指六五,六五小《象》曰中以行願是也。卦以上下交為泰,故以尚中行為辭。曰得尚者,慶幸之辭也。若惟知包乎荒,則必不能馮河而就五矣,必遐遺乎五矣,必不能亡朋矣。用馮河以下,聖人教占者之辭。陽來居內,不向乎外,有惟知包乎內卦之初,遐遺乎外卦君上之象,故聖人于初教之以征 ,于二教之以尚。舊註不識象,所以失此爻之旨。

當泰之時,陽來于下,不知有上,故九二有包初之象,然二五君臣同德,天下太平,賢人君子,正當觀國用賓之時,故聖人教占者用馮河之勇,以奮其必為之志,不可因邇而忘遠。若能忘其所邇之朋,得尚往于中行之君,以共濟其泰,則上下交而其志同,可以收光大之事業,而泰道成矣。故其象占如此 。

《象》曰:包荒,得尚于中行,以光大也。

曰包荒兼下三句而言也。孔子小象多是如此 ,捨相比溺愛之朋,而尚往以事中德之君 ,豈不光明正大。乾陽大之象也,變離光之象也。

︰地氣居上而性趨下;天氣處下而情往上 。天地氤氳,萬物化醇。不泰又待何時?

今兒學堂氣氛有些低迷,同學們意興闌珊,有點悶悶不樂。想來是因為昨天有些議題,不能定奪結論,某些改寫嘗試,失敗告終。這因『辨』而『辯』與由『辯』能『辨』,應該如何決定分際?

《 文 》文說︰

辨,判也。从刀辡聲。

辯,治也。从言在辡之閒。

,彷彿說了似沒說!

沒多時學長來了。

 

派︰同學們,大家好。昨兒因故請假,晚上讀了 M♪o 的課堂摘記,看到大家合力完成的 TuxIOme 程式深感驚豔。別說當年我們學習時沒有這樣的創舉,就算當初在小學堂課綱之訂定時,也未曾設想過,真可以小學堂裡講程式文法的哩!所以今兒自備禮物 ── 環境溫度感測器 ──,給你們嘉獎,替同學們加油。同時特傳能看影音的 Kodi 安裝 秘 技 秘技,為大家助興。【熱烈鼓掌】

雖然說『包荒馮河』在於『勇』,更在『朋不遐遺』。 議 論 議論之旨,重在得 理 理。同或不同,以 辨辯 ,貴能 和 同異,方謂得 宜 宜。

程式語言的文法,道理博大精深,大家既已敲門叩關,更應當細思幕後法則,往往牽一髮而動全身。於此略對入出針文法,作個 平 平說︰

【函元之不妥】

通常研習程式文法實務,精通了算術表達式,大概思過半矣。這事早由 λ 運算所揭示,所以知道『函式求值』與『變元代換』的概念看來似乎簡單,其中的精巧細密,除非深入探究,並不容易掌握。如果考察派生語法,它並沒有『抽象函數』運算︰

(f + g) (x) = f (x) + g (x)

(f - g) (x) = f (x) - g (x)

(f * g) (x) = f (x) * g (x)

(f / g) (x) = f (x) / g (x)

(f \circ g) (x) = f (g (x) )

,這是因為首先『 def 』關鍵字所定義的『函式』,可以不是數學上講的『函數』,而是執行某種『功能』 function 。 再者從語用上說,針對特定領域應用,設計特殊語法,並不是普通程式語言應該專注的目標,多半經由『程式庫』來作擴充。比方講 NumPy 方便了科學運算, SymPy 開啟符號代數系統。它們並不直接擴張 Python 的基本語法。因此對於入出針文法,也需要思考它的『目的性』。由於 TPG 只是普通派生定義的『 class 』類,所謂文法的『內』與『外』就有很多彈性,可以在應用上作適度規劃。由此觀之,函元 ,或該叫做函式,之擴張並非『必要的』,因此認為不妥。

 

【文法之整合】

假使將 TuxIOme 的系統溫度文法,如此修改

# 原先
            |   "系統溫度"                        e = 讀取系統溫度()         ; # 改作             |   "系統溫度" self["CPU溫度"] = e = 讀取系統溫度()
        ;

,原先的用法依舊,『變元』裡將增加一項『 CPU溫度』,於是就可以用『顯示』文法,將系統溫度顯示在數碼管上。現今又多了『環境溫度』的感測器,可以思考如何『相容』『整合』的作文法擴充 。

 

【功能之衡量】

現在已經有了 IRTX 和 IRRX 的『功能』。如果我們將 紅 外 線紅外線發射碼中的 KEY_0、KEY_1 … KEY_9 看成『數字碼』,用來傳遞『四位數字訊息』,舉例︰

1314 ──→ 一生一世

5200 ──→ 我愛人人

等等,可以用『明文』,也可以用『亂數加密』成『密訊』。如此除了將需要『明文』或『密訊』的『發文』與『收文』之文法外,還需要『亂數』產生器,下面程式片段定義了一種『基本』 Atom 原子資料,稱為『Random』,是『四位亂數』的製造者,

        Atom/a ->
                real/a
            |   integer/a
            |   Function/a
            |   Var/a
            |   '' Expr/a ''
            |   Random/a
        ;

        Function/y ->
                函數一/f '' Expr/x ''               y = f(x)             |   函數二/f '<img src="https://www.freesandal.org/wp-content/ql-cache/quicklatex.com-5618a7a7b23dfd84e41ef622fed8142e_l3.png" class="ql-img-inline-formula quicklatex-auto-format" alt="' Expr/x1 ',' Expr/x2 '" title="Rendered by QuickLaTeX.com" height="19" width="165" style="vertical-align: -5px;"/>' y = f(x1,x2)
        ;

        Random/x -> "四位亂數"                          x = random.randint(0, 9999)         ;</pre> ,把它當成起始點,試以『應用』為中心,探索『亂數』的用途。     <a href="http://www.freesandal.org/wp-content/uploads/%E7%94%9F.png"><img class="alignnone size-full wp-image-32797" src="http://www.freesandal.org/wp-content/uploads/%E7%94%9F.png" alt="生" width="48" height="48" /></a> <span style="color: #ff0000;"><strong>生</strong></span>︰由於 Linux 核心的向前發展,直接支援了某些遙控器。欲了解這個改變,就先從閱讀這篇《 <a href="http://www.freesandal.org/wp-content/uploads/網.gif"><img class="alignnone size-full wp-image-33767" src="http://www.freesandal.org/wp-content/uploads/網.gif" alt="網" width="22" height="44" /></a> 》網文開始︰ <h1 align="CENTER"><a href="http://www.lirc.org/html/configuration-guide.html#key-symbols-using-linux-input-layer">Configuration guide</a></h1>  <hr width="70%" />  <h2 align="center">About this guide</h2> This guide tries to describe the basic configuration steps for commonly used hardware. It's focused on the basic usage scenario to get the remote up and running, the more advanced features are not covered. This includes irexec, lircmd, ir blasting and the TCP/IP-based remote features.  <hr />  <h2 align="center">Why should I use LIRC?</h2> Recent Linux kernels have built-in support for IR remotes. Using that, pressing an up-arrow on the remote works the same way as pressing the up-arrow on a keyboard. This is a modern "just works" solution. On the other hand, LIRC is an old style linux application which can be tweaked to do almost anything, but is tricky to setup. So, why would you use LIRC? <ul> 	<li>You might have a remote which is supported by LIRC but not the kernel.</li> 	<li>If you have a remote which isn't supported at all, LIRC is probably your best bet to get it running.</li> 	<li>You might be on a non-Linux platform supporting lirc e. g., MacOS.</li> 	<li>You might have an application which is more or less designed to use LIRC.</li> 	<li>You might need LIRC's capabilities e. g., modes where a single remote button can be teached to deliver different keys to the application.</li> 	<li>You might want to send IR signals to other devices (IR blasting).</li> 	<li>Handling several applications with one remote is easier with LIRC. E. g., you can use irexec(1) to run arbitrary commands in parallel with an application such as mythtv or xbmc.</li> </ul> So, while the kernel built-in handling works out of the box in many cases, there are still scenarios when LIRC is the right tool.  <hr />  <h2 align="center">Overall Configuration Decisions.</h2> <pre>       ----------         ---------------------               ----------        |        |         |                   |               |        |        |        |----→----| Linux input layer |-------→-------| Appli- |        |        |         |                   |  /dev/input   | cation |        |        |         ---------------------               |        | ---→---| kernel |                |        |                   ---------- remote |        |       devinput v        |        |        |                |        ^ uinput        |        |                |        |                   ----------        |        |         ---------------------               | Appli- |        |        |----→----|      lirc         |-------→-------| cation |--        |        |         |                   | /var/run/lirc |        | |        ----------         ---------------------               ---------- |--                                                                 |        | |                                                                 ---------- |                                                                   |        |                                                                   ---------- </pre> LIRC can be run together with the kernel in different ways. You need to decide on a general approach first.  Depending on whether lirc is used or not application will get data either from the input layer (/dev/input) or from LIRC (/var/run/lirc). Using the LIRC data requires application support. Support for LIRC is common in typical linux htpc applications like mythtv, xbmc and vlc.  The /var/run/lirc interfaces allows several applications to receive input events. On the other hand, the /dev/input interfaces only allows one application to receive the events. <ul> 	<li>A common scenario is to not involve lirc at all, the upmost path in the picture (kernel -> Linux input layer -> application). Unless there is reason to use lirc <a href="http://www.lirc.org/html/configuration-guide.html#why-use-lirc">(above)</a>) this is probably the way to go.</li> </ul> If you need to use lirc, there is two cases depending on if your remote is supported by the kernel or not. <ul> 	<li>If it's supported, you should probably at least first try using the linux input layer decoding and use that as input to lirc. This is the devinput data path in picture (kernel -> Linux input layer -> lirc -> app).</li> 	<li>If the kernel built-in decoding can't be used you need to use a lirc driver instead. This is the bottom data path (kernel ->lirc -> app).</li> </ul> Last option is to connect the LIRC driver to the linux input layer using LIRC's --uinput option. This means that application sees the input as coming from the kernel, and LIRC's other capabilities are not available. This is not described here.  ……  △ 現在系統上所用的『lircd.conf』檔案,遙控器的『名稱』叫做  name /home/pi/lircd.conf  ,如今也許應該重新命名為『tuxiome』︰ <pre class="lang:sh decode:true">pi@raspberrypi ~ more /etc/lirc/lircd.conf 
# Please make this file available to others
# by sending it to <lirc@bartelmus.de>
#
# this config file was automatically generated
# using lirc-0.9.0-pre1(default) on Tue Oct  8 07:05:38 2013
#
# contributed by
#
# brand:                       /home/pi/lircd.conf
# model no. of remote control:
# devices being controlled by this remote:
#
 
begin remote
 
  name  tuxiome
  bits           16
  flags SPACE_ENC|CONST_LENGTH
  eps            30
  aeps          100
 
  header       9006  4447
  one           594  1648
  zero          594   526
  ptrail        587
  repeat       9006  2210
  pre_data_bits   16
  pre_data       0xFD
  gap          107633
  toggle_bit_mask 0x0

,當然『TuxIOme』程式中的

def 紅外線輸出(字碼):
    global 重複次數
    subprocess.call(['irsend', 'SEND_ONCE', 'tuxiome', 字碼,"--count=" +str(重複次數) ])
    return "已送出"

也當對應修改。

其實所用遙控器的『lircd.conf』是由 LIRC 之『irrecord』程式產生的︰

IRRECORD

NAME

irrecord – application for recording IR-codes for usage with LIRC

SYNOPSIS

irrecord [-f] [-n] [-H driver] [-d device] [file]
irrecord -a <file>
irrecord -l
irrecord –help | –version

DESCRIPTION

This program will record the signals from your remote control and create a config file for lircd. A proper config file for lircd is maybe the most vital part of this package, so you should invest some time to create a working config file. Although I put a good deal of effort in this program it is often not possible to automatically recognize all features of a remote control.

If the program fails to recognize the protocol of the remote control you should use the –force option to at least create a config file in raw mode.

If file is not specified it defaults to “irrecord.conf”

If file already exists and contains a valid config irrecord will use the protocol description found there and will only try to record the buttons. This is very useful if you want to learn a remote where config files of the same brand are already available. Of course this will only work if the remotes use the same protocol but it’s worth a try. You will find template files for the most common protocols in the remotes/generic/ directory of this package. The name of the new file is created by appending .conf to the given filename in this case.

OPTIONS

-h –help
display this message
-v –version
display version
-a –analyse
Analyse a raw_codes config file, trying to convert it to a regular configuration.
-f –force
Force raw mode. Use this if recording fails otherwise. This creates a raw codes configuration file which can be used as-is or converted using the -a option.
-n –disable-namespace
disables namespace checks
-l –list-namespace
list valid button names
-H –driver=driver
Use given driver. -H help lists available drivers.
-d –device=device
read from given device
-D –loglevel=level
Determine the amount of logging information. [level] can be a symbolic syslog level: ‘error’,’warning, ‘info’, ‘notice’ or ‘debug’. lircd also defines three additional levels ‘trace’, ‘trace1’ and ‘trace2’ which gives even more messages (‘trace2’ bringing the most). However, in the log these messages are marked as ‘debug’. The level can also be an integer in the range 3 (almost no messages) to 10.

……

如果能深入了解它的用法與限制,你將可以『拷貝』 Copy 或應講『備份』 Backup 一般的家用遙控器,這也就是『學習型』遙控器的基本原理。

 

△ 如何安裝 kodi 『家庭劇院』 Home Theatre︰

sudo nano /etc/apt/sources.list.d/mene.list

# 輸入內容
deb http://archive.mene.za.net/raspbian wheezy contrib

# 安裝
sudo apt-get update
sudo apt-get install kodi

 

首次用『選單』執行 Kodi Media Center 媒體中心,系統將會產生『~/.kodi/』的目錄,請建立如下的遙控器設定參考檔案︰

pi@raspberrypi ~ more ~/.kodi/userdata/Lircmap.xml  <lircmap>   <remote device="tuxiome">     <select>KEY_ENTER</select>     <back>KEY_BACK</back>     <stop>KEY_STOP</stop>     <playpause>KEY_PLAYPAUSE</playpause>     <volumeup>KEY_VOLUMEUP</volumeup>     <volumedown>KEY_VOLUMEDOWN</volumedown>   </remote> </lircmap> pi@raspberrypi ~ 

以及

pi@raspberrypi ~ more ~/.kodi/userdata/keymaps/remote.xml  <keymap>   <global>     <remote>       <select>Select</select>       <back>PreviousMenu</back>       <stop>Stop</stop>       <playpause>PlayPause</playpause>       <volumeup>VolumeUp</volumeup>       <volumedown>VolumeDown</volumedown>     </remote>   </global> </keymap> pi@raspberrypi ~ 

,研究

一、為何沒有 KEY_LEFT、KEY_RIGHT、KEY_UP、KEY_DOWN 卻還能左右上下的呢?

二、遙控器難以操控的原因?

三、可以用 irsend 來控制嗎?

 

碼 ︰會 習 。學長講習後時間已經很晚,同學們興高采烈正忙著安裝與驗證諸諸種種軟體。何不……

長 長︰同學們請安靜。今天的會習,改為自由習作與自由討論 ……【鼓掌通過】

 

訊 ︰☿ 今日方真知︰循循善誘,誠非易事。

 

 

 

 

 

 

M♪o 之學習筆記本《巳》文章︰【䷒】知臨之宜

派生碼訊

巳 蛇

來氏《 易 》易註︰

六五,知臨,大君之宜,吉。

變坎,坎為通,智之象也。知臨者,明四目 ,達四聰,不自用而任人也。應乾陽,故曰大君。知臨之知,原生于九二,故即曰大君 。知者覺也,智即知也。六五非九二不能至此宜者,得人君之統體也。

六五柔中居尊,下任九二剛中之賢,兼眾智以臨天下,蓋得大君之宜者也,吉可知矣。占者有是德,亦如是占也。

︰甘澤 ☱ 連沃土 ☷ ,內兌悅外坤順,又有乾陽來相應,吉兆也。故曰︰知臨之宜。

今兒學堂的氣氛頗不尋常,不見往日課前之嘻笑打鬧,正三五成群的討論紅外線控制種種以及入出針文法擴張等等的哩!

學長來了,看了看沒進教室,卻招手將我喚到室外,說道︰

同學們能主動學習很好,今天就不上課了。妳帶著大家研習,要是真的碰到了疑難,那時我再來。如果同學問起,就說我有事請假,晚點才能到校,請大家先行自習。

 

派︰☿ 長 長︰同學們請安靜。學長告知︰上午有事請假,請大家先行自習。既然昨日的討論,意猶未盡,何不今早大家就

輪番上陣講習,彼此觀摩,溝通想法。為著下午的 會習 習,也來個 會 外 會 會外會的耶!……【鼓掌通過】

於此特寫一致同意的若干事項︰

【小學堂 旗 旗號】

正式將入出針程式命名為『TuxIOme』── Tux  [GP]IO m[achin]e ──,啟始時數碼管顯示『 -| |- -| |- 』,意味井井相通,友情長存 。

 

【量系統溫度】

入出針文法增加系統溫度讀取,語法

系統溫度

,使用『 vcgencmd measure_temp 』傳回攝氏溫度浮點 數值。

建置範例︰

>>> import subprocess
>>> import shlex
>>> command_line = "vcgencmd measure_temp"
>>> shlex.split(command_line)
['vcgencmd', 'measure_temp']
 
>>> t = subprocess.call(['vcgencmd', 'measure_temp'])
temp=53.5'C
>>> t
0
>>> t = subprocess.check_output(['vcgencmd', 'measure_temp'])
>>> t
b"temp=54.1'C\n"
>>>
>>> T = t.decode('utf-8')
>>> T
"temp=54.1'C\n"
>>> 
>>> T.find('=')
4
>>> T.find("'")
9
>>> T[4-9]
'.'
>>> T[4]
'='
>>> T[9]
"'"

 >>> T[5:9]
'54.1'
>>>
 >>> TT = float(T[5:9])
>>> TT
54.1
>>>

 

參考《 網 》網文︰

17.5. subprocess — Subprocess management

 

【亂數隨選芻議】

random.choice(seq)

Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

規劃增添一個亂數產生的語法。使之可用於入出針隨選,或是其它用途。

 

【執行緒結束法確證】

實務確證了將『 daemon 』設定為 True ,執行緒隨程式正常結束。

……

 

生 ︰列舉今天的參考資料如下︰

△ LIRC 紅外線發射︰

IRSEND

NAME

irsend – basic LIRC program to send infra-red commands

SYNOPSIS

irsend [options] DIRECTIVE REMOTE CODE [CODE…]

DESCRIPTION

Asks the lircd daemon to send one or more CIR (Consumer Infra-Red) commands. This is intended for remote control of electronic devices such as TV boxes, HiFi sets, etc.

DIRECTIVE can be:

SEND_ONCE – send CODE [CODE …] once SEND_START – start repeating CODE SEND_STOP – stop repeating CODE LIST – list configured remote items SET_TRANSMITTERS – set transmitters NUM [NUM …] SIMULATE – simulate IR event

REMOTE is the name of a remote, as described in the lircd configuration file.

CODE is the name of a remote control key of REMOTE, as it appears in the lircd configuration file.

NUM is the transmitter number of the hardware device.

For the LIST DIRECTIVE, REMOTE and/or CODE can be empty:

LIST “” “” – list all configured remote names LIST REMOTE “” – list all codes of REMOTE LIST REMOTE CODE – list only CODE of REMOTE

The SIMULATE command only works if it has been explicitly enabled in lircd.

OPTIONS

-h –help
display usage summary
-v –version
display version
-d –device
use given lircd socket [/var/run/lirc/lircd]
-a –address=host[:port]
connect to lircd at this address
-# –count=n
send command n times

ENVIRONMENT

LIRC_SOCKET_PATH
The lircd socket to connect to, defaults to a hardcoded default value usually /var/run/lirc/lircd

FILES

/etc/lirc/lircd.conf
Default lircd configuration file. It should contain all the remotes, their infra-red codes and the corresponding timing and waveform details.

DIAGNOSTICS

If lircd is not running (or /var/run/lirc/lircd lacks write permissions) irsend aborts with the following diagnostics:

"irsend: could not connect to socket"
"irsend: Connection refused" (or "Permission denied").

EXAMPLES

irsend LIST DenonTuner “”
irsend SEND_ONCE DenonTuner PROG-SCAN
irsend SEND_ONCE OnkyoAmpli VOL-UP VOL-UP VOL-UP VOL-UP
irsend SEND_START OnkyoAmpli VOL-DOWN ; sleep 3 irsend SEND_STOP OnkyoAmpli VOL-DOWN
irsend SET_TRANSMITTERS 1
irsend SET_TRANSMITTERS 1 3 4
irsend SIMULATE “0000000000000476 00 OK TECHNISAT_ST3004S”

DRIVER LOADING

Drivers are loaded dynamically. The directory used for this is determined by (falling priority):

– The ‘plugindir’ entry in the [lircd] section of the lirc_options.conf file.
– The environment variable LIRC_PLUGINDIR.
– A hardcoded default (usually /usr/lib[64]/lirc/plugins).

△ 派生之 LIRC 程式庫︰

python-lirc 1.2.1

Python bindings for LIRC.

python-lirc
===========

LIRC extension written in Cython for Python 3 (and 2). I’m trying to get this into
[Debian]http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=Bug%23718980

[PyPI]https://pypi.python.org/pypi/python-lirc/

Install
=======
`python-lirc` is in the main repositories for Raspbian. If you’re on a
RaspberryPi you can just run:

sudo apt-get install python-lirc  Otherwise, download the latest relase from [here]https://github.com/tompreston/python-lirc/releases and install with: sudo dpkg -i python3-lirc_1.2.1-1_all.deb

Configure
=========

You need a valid [lircrc configuration file]http://www.lirc.org/html/configure.html#lircrc_format) For example:

cat ~/.lircrc begin button = 1 # what button is pressed on the remote prog = myprogram # program to handle this command config = one, horse # configs are given to program as list end  begin button = 2 prog = myprogram config = two end  Use === python3
>>> import lirc
>>> sockid = lirc.init(“myprogram”)
>>> lirc.nextcode() # press 1 on remote after this
[‘one’, ‘horse’]
>>> lirc.deinit()

Load custom configurations with:

>>> sockid = lirc.init(“myprogram”, “mylircrc”)
>>> lirc.load_config_file(“another-config-file”) # subsequent configs

Set whether `nextcode` blocks or not with:

>>> sockid = lirc.init(“myprogram”, blocking=False)
>>> lirc.set_blocking(True, sockid) # or this

……

△ 依據決議新增的 lircrc 檔案︰

pi@raspberrypi ~ more /etc/lirc/lircrc begin   prog = TuxIOme   button = KEY_1   config = 1 end  begin   prog = TuxIOme   button = KEY_2   config = 2 end  begin   prog = TuxIOme   button = KEY_3   config = 3 end  begin   prog = TuxIOme   button = KEY_4   config = 4   end  begin   prog = TuxIOme   button = KEY_5   config = 5   end  begin   prog = TuxIOme   button = KEY_6   config = 6     end  begin   prog = TuxIOme   button = KEY_7   config = 7   end  begin   prog = TuxIOme   button = KEY_8   config = 8   end  begin   prog = TuxIOme   button = KEY_9   config = 9     end  begin   prog = TuxIOme   button = KEY_0   config = 0 end  begin   prog = TuxIOme   button = KEY_DOWN   config = DOWN end  begin   prog = TuxIOme   button = KEY_LEFT   config = LEFT end  begin   prog = TuxIOme   button = KEY_UP   config = UP end  begin   prog = TuxIOme   button = KEY_RIGHT   config = RIGHT end  begin   prog = TuxIOme   button = KEY_BACK   config = BACK end  begin   prog = TuxIOme   button = KEY_ENTER   config = ENTER end  begin   prog = TuxIOme   button = KEY_SETUP   config = SETUP end  begin   prog = TuxIOme   button = KEY_PLAYPAUSE   config = PLAYPAUSE end  begin   prog = TuxIOme   button = KEY_STOP   config = STOP end  begin   prog = TuxIOme   button = KEY_VOLUMEUP   config = VOLUMEUP end  begin   prog = TuxIOme   button = KEY_VOLUMEDOWN   config = VOLUMEDOWN end  </pre>    △ 按造結論新改之 TuxIOme 初始版程式︰ <pre class="lang:python decode:true ">#!/usr/bin/python3 # -*- coding: utf-8 -*-  import math import operator import string import threading import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False)  開 = 亮 = 低 = 0 關 = 滅 = 高 = 1  from time import sleep  import tpg   if tpg.__python__ == 3:     operator.div = operator.truediv     raw_input = input   def make_op(op):     return {         '加'   : operator.add,         '減'   : operator.sub,         '乘'   : operator.mul,         '除'   : operator.div,         '剩'   : operator.mod,         '^'   : lambda x,y:x**y,         '**'  : lambda x,y:x**y,         '餘弦' : math.cos,         '正弦' : math.sin,         '切弦' : math.tan,         'acos': math.acos,         'asin': math.asin,         'atan': math.atan,         '平方' : lambda x:x*x,         '根號': math.sqrt,         '正值' : abs,         'norm': lambda x,y:math.sqrt(x*x+y*y),     }[op]  數碼賦值 = [(滅, 亮, 亮, 滅, 滅, 滅, 亮, 滅), (滅, 滅, 滅, 滅, 亮, 亮, 亮, 滅), (滅, 亮, 亮, 滅, 滅, 滅, 亮, 滅),   (滅, 滅,
]

遲延 = 0.012

# 數碼管

四位數碼管位選一 = 17
四位數碼管位選二 = 27
四位數碼管位選三 = 22
四位數碼管位選四 = 10

LEDA = 21
LEDB = 16
LEDC = 19
LEDD = 6
LEDE = 5
LEDF = 20
LEDG = 26
LEDH = 13

# 初始態

GPIO.setup(四位數碼管位選一, GPIO.OUT, initial=關)
GPIO.setup(四位數碼管位選二, GPIO.OUT, initial=關)
GPIO.setup(四位數碼管位選三, GPIO.OUT, initial=關)
GPIO.setup(四位數碼管位選四, GPIO.OUT, initial=關)

GPIO.setup(LEDA, GPIO.OUT, initial=滅)
GPIO.setup(LEDB, GPIO.OUT, initial=滅)
GPIO.setup(LEDC, GPIO.OUT, initial=滅)
GPIO.setup(LEDD, GPIO.OUT, initial=滅)
GPIO.setup(LEDE, GPIO.OUT, initial=滅)
GPIO.setup(LEDF, GPIO.OUT, initial=滅)
GPIO.setup(LEDG, GPIO.OUT, initial=滅)
GPIO.setup(LEDH, GPIO.OUT, initial=滅)



def 數碼管執行緒():
    global 數碼賦值
    global 遲延

    數碼管 = [LEDA, LEDB, LEDC, LEDD, LEDE, LEDF, LEDG, LEDH]

    while True :

        for 單元 in range(0,4):
            if 單元 == 0 :
                GPIO.output(四位數碼管位選一, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選一, 關)

            if 單元 == 1 :
                GPIO.output(四位數碼管位選二, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選二, 關)

            if 單元 == 2 :
                GPIO.output(四位數碼管位選三, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選一, 關)

            if 單元 == 1 :
                GPIO.output(四位數碼管位選二, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選二, 關)

            if 單元 == 2 :
                GPIO.output(四位數碼管位選三, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選三, 關)

            if 單元 == 3 :
                GPIO.output(四位數碼管位選四, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選四, 關)

        sleep(遲延)

數碼緒 = threading.Thread(name="數碼", target=數碼管執行緒)
數碼緒.daemon = True
數碼緒.start()

數碼管輸出字典 = { "0" : (亮, 亮, 亮, 亮, 亮, 亮, 滅, 滅) ,
                   "1" : (滅, 亮, 亮, 滅, 滅, 滅, 滅, 滅) ,
                   "2" : (亮, 亮, 滅, 亮, 亮, 滅, 亮, 滅) ,
                   "3" : (亮, 亮, 亮, 亮, 滅, 滅, 亮, 滅) ,
                   "4" : (滅, 亮, 亮, 滅, 滅, 亮, 亮, 滅) ,
                   "5" : (亮, 滅, 亮, 亮, 滅, 亮, 亮, 滅) ,
                   "6" : (亮, 滅, 亮, 亮, 亮, 亮, 亮, 滅) ,
                   "7" : (亮, 亮, 亮, 滅, 滅, 滅, 滅, 滅) ,
                   "8" : (亮, 亮, 亮, 亮, 亮, 亮, 亮, 滅) ,
                   "9" : (亮, 亮, 亮, 亮, 滅, 亮, 亮, 滅) ,
                 }


def 輸出數碼管(數據) :
    global 數碼賦值
    global 數碼管輸出字典

    if 數據 > 999.9 :
        return "數值超過 999.9"
    else:

        字符串 = "%05.1f" %數據

        for 單元 in range(0,5):
            if 單元 == 0 :
                數碼賦值[單元] = 數碼管輸出字典[字符串[單元]]
            elif 單元 == 1 :
                數碼賦值[單元] = 數碼管輸出字典[字符串[單元]]
            elif 單元 == 2 :
                暫列 = list(數碼管輸出字典[字符串[單元]])
                暫列[7] = 亮
                數碼賦值[單元] = tuple(暫列)
            elif 單元 == 3 :
                continue
            else:
                數碼賦值[單元 - 1] = 數碼管輸出字典[字符串[單元]]

    return "完成"


GPIO.setup(11, GPIO.OUT, initial=GPIO.HIGH)
小哨子 = GPIO.PWM(11, 130.8)

def 啟動蜂鳴器():
        小哨子.start(100)
        return "蜂鳴器已啟動"

def 響聲控制(頻率):
        小哨子.ChangeFrequency(頻率)
        小哨子.start(50)
        return 頻率

def 噤聲控制(頻率):
        小哨子.ChangeFrequency(頻率)
        小哨子.start(100)
        return "噤聲"

def 控制蜂鳴器(op):
    return {
        '響聲'   : 響聲控制,
        '禁音'   : 噤聲控制,
   }[op]

def 輸入符碼(針碼):
        return GPIO.input(針碼)


def 輸出符碼(針碼, 賦值):
        GPIO.output(針碼, 賦值)
        return "輸出" + str(賦值)

def 出入定義(針碼, 入出):
        if 入出 == "出" :
            GPIO.setup(針碼, GPIO.OUT, initial = GPIO.HIGH)
        else:
            GPIO.setup(針碼, GPIO.IN, pull_up_down = GPIO.PUD_UP)
        return "定義完成"

def 出針定義(針碼):
    GPIO.setup(針碼, GPIO.OUT, initial = GPIO.HIGH)
    return "定義輸出完成"

def 入針定義(針碼):
    GPIO.setup(針碼, GPIO.IN, pull_up_down = GPIO.PUD_UP)
    return "定義輸入完成"


def 入出針定義(op):
    return {
        '入針'   : 入針定義,
        '出針'   : 出針定義,
   }[op]

import subprocess

重複次數 = 1

def 紅外線輸出(字碼):
    global 重複次數
    subprocess.call(['irsend', 'SEND_ONCE', '/home/pi/lircd.conf', 字碼,"--count=" +str(重複次數) ])
    return "已送出"

import lirc
sockid = lirc.init("TuxIOme", blocking=False)

def 紅外線輸入():

    return lirc.nextcode()

def 讀取系統溫度():
    t = subprocess.check_output(['vcgencmd', 'measure_temp'])
    T = t.decode('utf-8')
    Tb = T.find('=')
    Te = T.find("'")
    return float(T[Tb + 1 : Te])

class 實習機板(tpg.Parser, dict):
    r"""
    此為實習基板入出針語言 TuxIOme 初始版,自 Calc.py 擴充而來。由於使用中文之故,
    不能使用預設的 NamedGroupLexer 。
    文法定義如下 ::

        set lexer = CacheLexer

        separator space '\s+' ;

        token 指數運算    '\^|\*\*'                                               make_op         token 入出設定    '(入針|出針)\b' 入出針定義
        token 聲音控制    '(響聲|禁音)\b'                                                   控制蜂鳴器         token 加減運算    '[加|減]' make_op
        token 乘除運算    '[乘|除|剩]'                                                 make_op         token 函數一    '(餘弦|正弦|切弦|acos|asin|atan|平方|根號|正值)\b' make_op
        token 函數二    '(norm)\b'                                              make_op         token real      '(\d+\.\d*|\d*\.\d+)([eE][-+]?\d+)?|\d+[eE][-+]?\d+' float
        token integer   '\d+'                                                   int         token VarId     '\w*'                                                    ;          START/e ->                 '變元' e=self.記憶()
            |   VarId/v '=' Expr/e      self[v]=e             |   Expr/e #            |   '定義' Expr/p '出' e=出入定義(p, '出')
#            |   '定義' Expr/p '入'             e=出入定義(p, '入')             |   '入出針'  Expr/p 入出設定/op e=op(p)
            |   '讀入' Expr/p                  e=輸入符碼(p)             |   '寫出' Expr/p '開' e=輸出符碼(p, 0)
            |   '寫出' Expr/p '關'                 e=輸出符碼(p, 1)             |   "打開蜂鳴器" e=啟動蜂鳴器()
            |   "蜂鳴器" 聲音控制/op Expr/p       e = op(p)             |   "顯示" Expr/p e = 輸出數碼管(p)
            |   "IRTX" VarId/s                    e = 紅外線輸出(s)             |   "IRRX" e = 紅外線輸入()
            |   "系統溫度"                        e = 讀取系統溫度()         ;          Var/self.get(v,0)-> VarId/v ;          Expr/e -> Term/e ( 加減運算/op Term/t e=op(e,t)
                         )*
        ;

        Term/t -> Fact/t ( 乘除運算/op Fact/f     t=op(t,f)                          )*         ;           Fact/f ->                 加減運算/op Fact/f f=op(0,f)
            |   Pow/f
        ;

        Pow/f -> Atom/f ( 指數運算/op Fact/e      f=op(f,e)                         )?         ;          Atom/a ->                 real/a             |   integer/a             |   Function/a             |   Var/a             |   '<img src="https://www.freesandal.org/wp-content/ql-cache/quicklatex.com-47b60ee797a9328acb352e3ae7895aa5_l3.png" class="ql-img-inline-formula quicklatex-auto-format" alt="' Expr/a '" title="Rendered by QuickLaTeX.com" height="19" width="68" style="vertical-align: -5px;"/>'         ;          Function/y ->                 函數一/f '<img src="https://www.freesandal.org/wp-content/ql-cache/quicklatex.com-22e0e32183ddc257d3b853d237d23b4a_l3.png" class="ql-img-inline-formula quicklatex-auto-format" alt="' Expr/x '" title="Rendered by QuickLaTeX.com" height="19" width="69" style="vertical-align: -5px;"/>' y = f(x)
            |   函數二/f '' Expr/x1 ',' Expr/x2 ''  $ y = f(x1,x2)
        ;
 
    """

    def __init__(self):
        super().__init__()
        self.名稱 = "實習機板"
        self["一藍"] = 5
        self["二藍"] = 6
        self["三藍"] = 13
        self["四藍"] = 19
        self["五綠"] = 0
        self["六綠"] = 1
        self["七黃"] = 7
        self["八紅"] = 8
        self["按鍵一"] = 23
        self["按鍵二"] = 18
        self["撥碼一"] = 24
        self["撥碼二"] = 25



    def 記憶(self):
        vars = sorted(self.items())
        memory = [ "%s = %s"%(var, val) for (var, val) in vars ]
        return "\n\t" + "\n\t".join(memory)



print("Calc (TPG example)")
實習機 = 實習機板()
while 1:
    try:
       l = raw_input("\n:")
    except UnicodeDecodeError:
       continue

    if l:
        try:
            print(實習機(l))
        except Exception:
            print(tpg.exc())
    else:
        break


# 數碼緒._stop()

GPIO.cleanup()


 

碼 ︰會 習 。☿ 長 長︰同學們請安靜。今天這第一次 會 外 會 會外會可是破天荒的熱烈,現在早過了响午,就算大家還不覺得 餓 餓,也該中場休息一會兒吧!雖說還有一些分歧的意見,並不急的今天論定。稍晚飯後,就讓我們開始研讀資料、驗證 TuxIO me 程式 碼碼、測試 IRTX 與 IRRX ,隨性三三兩兩的分組討論,這樣好不好呢?……【鼓掌通過】

 

訊 ︰☿ 果其然《 易 》易曰︰咸臨貞吉,志行正也。

 

 

 

 

 

 

M♪o 之學習筆記本《巳》文章︰【䷗】中行獨復

派生碼訊

巳 蛇

來氏《 易 》易註︰

六四,中行獨復。

中行者,在中行也。五陰而四居其中,中之象也。凡卦三四皆可言中,益卦三四,皆言中行是也。此爻變震,應爻亦震,震為足,行之象也。獨復者,不從其類而從陽也,故孔子以從道象之。

六四柔而得正,在群陰之中,而獨能下應于陽剛,故有中行獨復之象。曰獨復,則與休者等矣,蓋二比而四應也。

︰雷動在初,居九地之下。雷出地奮,能得其中行。故曰︰中行獨復。

連假剛結束,今天學堂上哄哄隆隆,大家談著廟會、祭典、出遊的點點滴滴,好不熱鬧。就連學長來了,都還不知道,繼續機哩括啦的說 。

 

派︰同學們,大家好。【漸漸靜了下來】

這學期的實習課已經結束,接下來的 專題 題,可以自由報名參加。首先安排的是 視 視而不 見 見的 紅 外 線 紅外線串講 。大家都知道實習 機 機板上有一個 IR TX 發射器,假使沒有 IR RX 接收器,也是枉然。為了鼓勵同學們的踴躍參與,除了發給接收器之外,還附贈紅外線遙控器一只,希望大家一起玩的個盡興。不過報名者得寫心得報告 文章 章,將擇其優者參加明年之生生祭大賽,盼為小學堂增光。現在請大家到班長 M♪o 處登記,隨後正式開講。

☿☺ 竟然全班加入,看來這下學長可是虧大了耶!

 

生 ︰同學們不要被紅外線嚇到,雖說眼睛看不見,比方講,

NoIR

,它 Pi-Noir 可是抓的住它。如從驅動原理上說,和發光二極體 LED 差異不大︰

IR-TX

藍光LED

因為一般家用遙控器所用的訊號『規範』 Protocol ,需要作高速的資料處理,所以通常不用『派生』 Python 直接操作。更由於應用與系統整合的考慮,因此早年就有了 Linux LIRC ── Linux Infrared Remote Control ── 專案,提供了方便的程式界面以及使用架構。現在就讓我們展開紅外線之旅的吧。

 

Linux LIRC Driver Model


 

Driver Model

 


  |  +---------------------------------------------------------------+
S |  | 'gpm -t msc -m /var/run/lirc/lircm' or a well configured X    |
O |  | (see section 'Configuring lircmd') for details                |
F |  +--------------+------------------------------------------------+
T |                 |
W |   /var/run/lirc/lircm (named pipe (FIFO) ==> one connection)
A |                 |
R |     +-----------+-----------+   +----------------------------------+
E |     | mouse daemon (lircmd) |   | tools (irexec, irxevent, ...)    |
  |     | configured with       |   | configured with ~/.config/lircrc |
  |     | lircmd.conf           |   |                                  |
  |     +-----------+-----------+   +-----------+----------------------+
  |                 |                           |
  |                 +-------------+-------------+
  |                               |
  |              /var/run/lirc/lircd (socket → multiple connections)
  |                               |
S |              +----------------+--------------------------+
O |              | decoder daemon (lircd), irrecord or mode2 |    TCP/IP
F |              | lircd is configured through lircd.conf    +---  port
T | User space   |                                           |     8765
W |              +------------------+------------------------+
A |                                 |            |
R |                                 |            |
E |                                 |            |
  |                                 |   /dev/uinput (Linux input layer)
  |                                 |
  |                                 |
  +---------------------------------+----------------------------------
  | Kernel space                    |              (character device
  |                                 |                  driver →
  |                    +------------+----------+    one connection)
  |                    |                       |
  |                /dev/lirc               /dev/ttySx
  |                    |                       |
  |       +------------+-------------+   +-----+---------------+
  |       |  LIRC device driver      |   | Linux serial driver |
  |       | (with ioctl-interface)   |   |                     |
  |       +------------+-------------+   +----------+----------+
  |                    |                            |
--+--------------------+----------------------------+------------------
  |                    |                            |
  |         +----------+------------+               |
  |         |                       |               |
  | +-------+----------------+ +----+-----+ +-------+-----------------+
H | | serial / parallel port | | TV cards | | Irman/RemoteMaster/etc. |
W | +------------------------+ +----------+ +-------------------------+
  |


Formats


  • /dev/lirc:
    highly depends on the mode selected with ioctls:

    LIRC_MODE_MODE2
    outputs packets containing an int value describing a IR signal

    • bits 0-23 contain the length of the pulse/space in microseconds
    • bits 31-24 can be:
      • 0: space
      • 1: pulse
      • 2: timeout (has to be enabled using LIRC_SET_REC_TIMEOUT ioctl and is not supported by all receivers)
    • all other values are reserved

    Lengths greater than or equal to 16 seconds are clamped to 0xffffff.

    References:

    • drivers/lirc_serial/lirc_serial.c
    • drivers/lirc_parallel/lirc_parallel.c
    • tools/mode2.c (dumps the output from the driver to stdout)
    LIRC_MODE_LIRCCODE
    outputs codes of configurable length in big endian byte order
  • /var/run/lirc/lircd:
    outputs strings containing all information about the remote and the pressed button.References:

    • daemons/lircd.c
    • tools/irw.c
  • /var/run/lirc/lircm:
    • MouseSystems
      5 byte packets:

      • byte 1: button information
      • byte 2: change on X axis
      • byte 3: change on Y axis
      • byte 4,5: 0
    • IMPS/2
      4 byte packets: check the source code for details
    • IntelliMouse
      4 byte packets: check the source code for details

    References:

    • daemons/lircmd.c

 

IR protocol analyzer

IR protocol analyzer is a universal application for automatic decoding several types of infrared remote control protocol packets. The application uses microphone input of a soundcard to capture infrared signal from a remote control. As a consequence, the hardware receiver is minimalistic and easy to build; just plug a phototransistor to input of your soundcard, that’s all hardware you need.

Application processes IR signal from a remote control and compares it with its own database of known protocols. When a match is found, packet is decoded and its characteristic is displayed to user (including protocol name, description, decoded data and graph with timing).

Protocol definitions are stored in separate XML file. This XML file can be easily modified and new protocol definitions can be added by user. When an unknown packet is captured, user may still display its graph with timing details. Then, on the basis of the graph and timing, he may create new protocol description.

IR protocol analyzer screenshot IR protocol analyzer – screenshot

Documentation

Download

Licence

You can use this program for free. If you find the program useful, please consider making a donation via PayPal.

Theory

The ProtocolAnalyzer constantly samples the analog input signal, trying to recreate any digital pulses found in the signal. The so called flank detector uses a quite simple algorithm to find the flanks of the pulses:

Find sequences where the sampled value changed significanlty (Flank Swing) over a short period of time (Flank Length)

To avoid the same flank being counted twice if it is large, we wait a while (Flank Holdoff) after finding a flank until we accept a new flank. This picture shows the meaning of the settings on a real sampled signal. The red line is the analog value (where the sample points are marked with black dots). The blue line is the flank detectors interpretation of the signal:

In the example Flank Swing was set at 50 and Flank Length set to 3, so when the signal changed more than 50 over 3 samples, the flank was detected (see the blue line). Note that the signal changed more than 50 in the following samples as well, but since this was within Flank Holdoff, this was not counted.

……

 

△ 軟體安裝以及設定

【安裝】

sudo apt-get install lirc liblircclient-dev
sudo apt-get install python-lirc python3-lirc

在 /boot/config.txt 的檔案底增加一行︰

dtoverlay=lirc-rpi,gpio_in_pin=9,gpio_out_pin=12

在 //etc/modules 的檔案底增加兩行︰

lirc_dev
lirc_rpi gpio_in_pin=9 gpio_out_pin=12

 

【設定】

將 /etc/lirc/hardware.conf 修改成︰

pi@raspberrypi ~ more /etc/lirc/hardware.conf  # /etc/lirc/hardware.conf # # Arguments which will be used when launching lircd LIRCD_ARGS="--uinput"  #Don't start lircmd even if there seems to be a good config file #START_LIRCMD=false  #Don't start irexec, even if a good config file seems to exist. #START_IREXEC=false  #Try to load appropriate kernel modules LOAD_MODULES=true  # Run "lircd --driver=help" for a list of supported drivers. DRIVER="default" # usually /dev/lirc0 is the correct setting for systems using udev  DEVICE="/dev/lirc0" MODULES="lirc_rpi"  # Default configuration files for your hardware if any LIRCD_CONF="" LIRCMD_CONF="" pi@raspberrypi ~ 

 

給定遙控器之 /etc/lirc/lircd.conf 檔案內容︰

pi@raspberrypi ~ more /etc/lirc/lircd.conf  # Please make this file available to others # by sending it to <lirc@bartelmus.de> # # this config file was automatically generated # using lirc-0.9.0-pre1(default) on Tue Oct  8 07:05:38 2013 # # contributed by # # brand:                       /home/pi/lircd.conf # model no. of remote control: # devices being controlled by this remote: #   begin remote     name  /home/pi/lircd.conf   bits           16   flags SPACE_ENC|CONST_LENGTH   eps            30   aeps          100     header       9006  4447   one           594  1648   zero          594   526   ptrail        587   repeat       9006  2210   pre_data_bits   16   pre_data       0xFD   gap          107633   toggle_bit_mask 0x0         begin codes           KEY_1                    0x08F7           KEY_2                    0x8877           KEY_3                    0x48B7           KEY_4                    0x28D7           KEY_5                    0xA857           KEY_6                    0x6897           KEY_7                    0x18E7           KEY_8                    0x9867           KEY_9                    0x58A7           KEY_0                    0x30CF           KEY_DOWN                 0xB04F           KEY_LEFT                 0x10EF           KEY_UP                   0xA05F           KEY_RIGHT                0x50AF           KEY_BACK                 0x708F           KEY_ENTER                0x906F           KEY_SETUP                0x20DF           KEY_PLAYPAUSE            0x807F           KEY_STOP                 0x609F           KEY_VOLUMEUP             0x40BF           KEY_VOLUMEDOWN           0x00FF       end codes   end remote pi@raspberrypi ~ 

 

【測試】

安裝好 IR 接收器,執 行 irw ,

IRW(1) User Commands IRW(1)

NAME
irw – sends data from Unix domain socket to stdout

SYNOPSIS
irw [socket]

DESCRIPTION
irw will connect to any Unix domain socket and will print the data that it receives to stdout. If you don’t give it a socket name argument it will watch
/var/run/lirc/lircd. Useful for debugging.

-h –help
display usage summary

-v –version
display version

SEE ALSO
The documentation for lirc is maintained as html pages. They are located under html/ in the documentation directory.

irw 0.9.0-pre1 October 2010

,對準 IR 接收器操作遙控器,結果類似如下︰

pi@raspberrypi ~ $  irw
0000000000fd08f7 00 KEY_1 /home/pi/lircd.conf
0000000000fda05f 00 KEY_UP /home/pi/lircd.conf
0000000000fd00ff 00 KEY_VOLUMEDOWN /home/pi/lircd.conf
0000000000fd00ff 01 KEY_VOLUMEDOWN /home/pi/lircd.conf
0000000000fd00ff 02 KEY_VOLUMEDOWN /home/pi/lircd.conf
0000000000fd40bf 00 KEY_VOLUMEUP /home/pi/lircd.conf
0000000000fd40bf 01 KEY_VOLUMEUP /home/pi/lircd.conf
0000000000fdb04f 00 KEY_DOWN /home/pi/lircd.conf
0000000000fdb04f 01 KEY_DOWN /home/pi/lircd.conf

 

碼 ︰會 習 。☿ 長 長︰同學們請安靜。也許有人還忙著安裝以及驗證紅外線的軟體程式。先發下今天的講義︰

‧ 數碼管討論摘要。

‧入出針文法大綱。

‧試作程式。

請大家回顧瞻前,稍候開始會習。

誰知同學們對那個『入出針語言』興奮莫名,討論的意外熱烈,直到時間已近傍晚,還興致高昂。縱使深感大家的熱情,實在難以記其要,勉強摘記︰

‧一開始顯示 1234 ,沒有什麼意思!該將實習 機 機板命名,用個代表大家的符號,彰顯小學堂彼此間的友情。

‧派生停止執行緒的辦法,聽說可以將之設定為 daemon 。

‧要是加入 IRTX 與 IRRX 就更好玩了。

‧變元只能記數值,不知道可不可以擴增函元 Functional 的呢?

‧蜂鳴器的禁音文法不好用。

‧……

,以結束今日之 習 習,明兒再 會 會。

 

訊 ︰☿ 此刻或許真的能體會,俗話所說︰吃虧就是佔便宜。

 

 

 

 

 

 

M♪o 之學習筆記本《巳》文章︰【䷁】黃裳元吉

派生碼訊

巳 蛇

漫天一白漢江秋,
憔悴黃花總帶愁;
吉曜半升箕斗隱,

金烏起滅海山頭。

巳蛇︰《 文 》文說︰ 巳 巳,巳也。四月 ,陽气巳出,陰气巳藏,萬物見,成文章,故巳為蛇,象形。凡巳之屬皆从巳。

《淮南子‧天文》講︰巳則生已定也。或存巳之古意,新生兒。

蛇 蛇,它或从虫。

若講形質已具,氣息已出,因此萬物見,成文章,自然有理。但說『故 巳 巳為 蛇 蛇』從何得出?據聞蛇的古字是 它 它,當真是以『象形』形像為故,實在有點牽強。如今夏日正炎炎,何不就尋棵湯谷扶桑 ,

大樹底下好乘涼

,作此《大哉問》??

Albrecht_Dürer_-_Adam_and_Eve_(Prado)_2
夏娃的蘋果

Golden_Apple_of_Discord_by_Jacob_Jordaens
金蘋果事件

640px-Newton's_tree,_Botanic_Gardens,_Cambridge
牛頓的蘋果

青蘋果
圖靈的蘋果

根據《聖經‧創世記》記載︰

亞當和夏娃二人住在伊甸園中,後來夏娃受『』的哄誘,偷食了『知善惡樹』所結的『禁果』,也讓亞當食用,二人遂被上帝逐出伊甸園。

□︰禁果是蘋果嗎?
○︰莫宰羊!
□︰那蘋果是禁果嗎?
○︰煩惱即菩提!!

也許希臘神話中關鍵之因緣生法的一顆『金蘋果』── 獻給最美女神 ──,引發 → 帕里斯的評判,導致 → 特洛伊戰爭。明示了『蘋果』與『誘惑』的關係,至於說怎麼聯繫上了『知識』,那只能問『牛頓』的了?

雖說『牛頓』並沒有創造『機械的宇宙』,如果仔細考察『運動定律』,假使再加上『物質組構』的『構造方程式』與『初始條件』── 位置和動量 ──,那麼該物之『運動軌跡』就被『確定』了。這演示了一種『軟體設計』之方法學,它以『資料驅動』為中心。或許艾倫‧圖靈非常了解那個『抽象機械』,所以創想發明了『萬有圖靈機』。只不過人類的知識還很難駕馭那樣的『仙女計算機』,然而隨著一九六零年代以來『硬體描述語言』 HDL hardware description language 的發展,也許我們終將受邀進入『計算機械的世界 』,一探『軟硬體的真諦』!『圖靈的蘋果』正述說著『尊重』與『寬容』,如今想來他早已『知道』這些『演算法』了的吧!!

 

派︰連假。無課。今日已夏至,窗明時尚早,天光逐日短,讀書趁年少。心懸 廟 會 廟會去是不去?但思學期雖已近尾聲,即將臨 專題 題,講義還欠 文章 章。就吟首

 

和夢得夏至憶蘇州呈盧賓客‧白居易

憶在蘇州日,常諳夏至筵。

粽香筒竹嫩,炙脆子鵝鮮。

水國多台榭,無風尚管弦。

每家皆有酒,無處不過船。

交印君相次,寒帷我在前。

此鄉俱老矣,東望共依然。

洛下麥秋月,江南梅雨天。

齊雲樓上事,已上十三年。

,權當已經如理而去,夢中也能行禮如儀。

 

生 ︰實習 機 機板,紅外線發射與接收原理《 圖 》︰

紅外線發射

IR-TX

紅外線接收

IR-RX

△ 《 網 》 網文參考如下︰

 


What is LIRC ?


 

LIRC is a package that allows you to decode and send infra-red signals of many (but not all) commonly used remote controls.

Recent linux kernels make it possible to use some IR remote controls as regular input devices. In some cases this makes LIRC redundant. However, LIRC offers more flexibility and functionality and is still the right tool in a lot of scenarios.

Former versions focussed on home-brew hardware connected to the serial or parallel port. Descriptions how to build this hardware can be found here. Current versions of LIRC also support a variety of other hardware. An up-to-date list of all supported devices and the status of the according drivers is available on the left.

The most important part of LIRC is the lircd daemon that will decode IR signals received by the device drivers and provide the information on a socket. It will also accept commands for IR signals to be sent if the hardware supports this. The second daemon program called lircmd will connect to lircd and translate the decoded IR signals to mouse movements. You can e.g. configure X to use your remote control as an input device.

The user space applications will allow you to control your computer with your remote control. You can send X events to applications, start programs and much more on just one button press. The possible applications are obvious: Infra-red mouse, remote control for your TV tuner card or CD-ROM, shutdown by remote, program your VCR and/or satellite tuner with your computer, etc. I’ve heard that using lirc on Raspberry Pie is quite popular these days.


Supported remote controls


There are some config files for remote controls at the remotes database. This is about 2000 devices and counting. These devices should work with the general drivers or (if it lacks timing info) the driver used to create them.

If you can’t find your remote control here it does not mean that your remote control is not supported. It’s just that there is no config file for it yet. All remote controls that are supported by learning remote controls, i.e. almost any, should also work with LIRC.


Supported capture devices

Besides a remote control you also need a capture device to read the data from the remote. LIRC supports a broad range of input devices. As a starter, you can use the kernel built-in support for many USB dongles and similar. Besides this LIRC supports basically any conceivable way to capture your data including serial devices, parallel ports, sound input etc. You can see the complete list in the left pane.

……

 

 

Overview

Author Gravatar Image SIMON MONK

In this tutorial, you will learn how to use an Infrared remote with a Raspberry Pi configured as a media center.

 

The IR receiver is attached to the GPIO connector on the Raspberry Pi.

 

Before tackling this project, you need to follow this tutorial to set up your Raspberry Pi as a media center.

……

 

碼 ︰無 習 。無課。

 

行 習 行習︰茲將實習 機 機板『入出針文法』初步整理如下

,待會習時再討論改善以及擴張︰

‧ 入出針   BCM制針碼表達式  [入針 | 出針]
‧讀入   BCM制針碼表達式
‧寫出   BCM制針碼表達式   [開 | 關]
‧打開蜂鳴器
‧蜂鳴器   [響聲 | 禁音]   頻率表達式Hz
‧顯示   表達式

△ 算術運算︰加、減、乘、除、剩【※餘數】、『^』與『**』指數運算。

△ 一元函數︰餘弦、正弦、切弦、acos 、asin 、atan 、平方、根號 、正值。

△ 二元函數︰ norm 。

△ 變元記憶。

 

訊 ︰☿ 《風俗通》裡記載:杜宣夏至日赴飲,見酒杯中似有蛇,然不敢不飲。酒後胸腹痛切,多方醫治不愈。後得知壁上赤弩照于杯中,影如蛇,病即愈。

, 未雨先綢繆!又豈是杯弓蛇影胡疑猜?寧夜靜思,

夏至日作》權德輿

睿樞無停運,
四序相錯行。
寄言赫曦景,
今日一陰生。

忽兒,一日又將盡!!

 

 

 

 

 

 

 

M♪o 之學習筆記本《辰》組元︰【䷝】重明麗正

派生碼訊

辰 龍

離:利貞,亨。 畜牝牛,吉。

彖曰:離,麗也﹔日月麗乎天,百谷草木麗乎土,重明以麗乎正,乃化成天下。 柔麗乎中正,故亨﹔是以畜牝牛吉也。

象曰:明兩作離,大人以繼明照于四方。

︰例假日。

 

派《 文 》文說︰ 離 離,黃倉庚也。鳴則蠶生。从隹离聲。據聞古意是︰鳥兒被網罩住。

昨兒個 廟會 會跳的 朱 雀 舞 朱雀舞,總不覺舞於庭,倒真像被網罩住似的!不過在這個《 阡 陌 網 》阡陌網時代 ,又有幾人不被 網 網罩住了呢?恐怕孔子想的相反了,現今也許 薦 荐儀還有人看,那個 盥 盥禮大概能省就省了吧!!果真早就『天 象 象遠』?『人 事 事近』了的耶??

試想城居幾時能見

220px-Black-naped_Oriole 黃鶯出谷

,哪有緣得識黃倉庚。又怎曉《 詩 》詩言

七月流火,九月授衣。春日載陽,有鳴倉庚。

說何 事 事︰

詩經‧國風‧豳風‧七月

七月流火,九月授衣。一之日觱發,二之日栗烈。無衣無褐,何以卒歲!三之日於耜,四之日擧趾。同我婦子,饁彼南畝。田畯至喜 。

七月流火,九月授衣。春日載陽,有鳴倉庚。女執懿筐,遵彼微行 ,爰求柔桑。春日遲遲,采蘩祁祁。女心傷悲,殆及公子同歸。

七月流火,八月萑葦。蠶月條桑,取彼斧斨。以伐遠颺,猗彼女桑 。七月鳴鵙,八月載績。載玄載黄,我朱孔陽,爲公子裳。

四月秀葽,五月鳴蜩。八月其穫,十月隕萚.一之日於貉,取彼狐狸 ,爲公子裘。二之日其同,載纘武功。言私其豵,獻豜於公。

五月斯螽動股,六月莎雞振羽。七月在野,八月在宇,九月在戶,十月蟋蟀入我床下。穹窒熏鼠,塞向墐戶。嗟我婦子,曰爲改歲,入此室處。

六月食鬱及薁,七月亨葵及菽。八月剝棗,十月穫稻。爲此春酒,以介眉壽。七月食瓜,八月斷壺,九月叔苴,采荼薪樗。食我農夫 。

九月築場圃,十月納禾稼。黍稷重穋,禾麻菽麥。嗟我農夫!我稼既同,上入執宮功。晝爾於茅,宵爾索綯,亟其乘屋,其始播百穀 。

二之日鑿冰沖沖,三之日納於凌陰。四之日其蚤,獻羔祭韭。九月肅霜,十月滌場。朋酒斯饗,曰殺羔羊。躋彼公堂,稱彼兕觥,“萬壽無疆”!

今年 飛 龍 祭 飛龍祭緊接夏至,雖尚講『長陽』之祀,恐怕 星回 回,早已名存實亡。事實上『火把』習俗,也恐怕忘名凋喪 。《火把節》又稱『星回節』,節期一般是在農曆的六月二十五日。這個盛夏『大暑節氣之時,是彝族上半年的『過年日』,更不要說這背後淒美的故事

南詔野史》:

南詔首領皮羅閣圖并吞五詔,將五詔於松明樓焚殺鄧賧妻慈善諫夫勿往夫不從而被殺慈善閉城死滇人以是日燃炬吊之

這位鄧賧詔詔主的妻子慈善夫人,是開元間人,又名『白潔夫人』,真不知其夫皮邏登為何執意不聽,一定要去那個『鴻門宴』,以致不但自己身亡,其妻只能據其夫所帶之『鐵鐲』來為他收屍守喪,並為免於皮邏閣之玷污,百日之後投洱海自盡。十九世紀英國有一位卡萊爾寫了《英雄與英雄崇拜》一書洋洋灑灑的談著『煮酒論英雄』之『英雄觀』,作者心想以那『白潔夫人』之『』與『』的情意來說,也許根本不想『死後立廟』,寧願『生前相守』的吧!!

釋迦牟尼佛在一部了一個『將來』佛的『』事,這就是『光明』燈的由來︰

佛說阿闍世王受決經
西晉三藏沙門釋法炬譯

聞如是。一時佛在羅閱祇國耆闍崛山中。時阿闍世王請佛。飯食已訖佛還祇洹。王與祇婆議曰。今日請佛。佛飯已竟更復所宜。祇婆言。唯多然燈也。於是王乃具百斛麻油膏。從宮門至祇洹精舍。

時有貧窮老母。常有至心欲供養佛而無資財。見王作此功德乃更感激。行乞得兩錢。以至 麻油家買膏。膏主曰。母人大貧窮。乞得兩錢何不買食。以自連繼用此膏為。 母曰。我聞佛生難值百劫一遇。我幸逢佛世而無供養。今日見王作功德。巍巍無量激起我意。雖實貧窮故欲然一燈為後世根本者也。於是膏主嘉其至意。與兩錢膏應 得二合。特益三合凡得五合。母則往當佛前然之。心計此膏不足半夕。乃自誓言。若我後世得道如佛。膏當通夕光明不消。作禮而去 。王所然燈或滅或盡。雖有人侍 恒不周。老母所然一燈光明特朗 。殊勝諸燈通夕不滅。膏又不盡至明朝旦。母復來前頭面作禮叉手却住。

佛告目連。天今已曉可滅諸燈。目連承教以次滅諸燈。燈皆已滅。唯此母一燈三滅不滅。 便舉袈裟以扇之燈光益明。乃以威神引隨藍風以次吹燈。老母燈更盛猛。乃上照梵天。傍照三千世界悉見其光 。佛告目連。止止。此當來佛之光明功德。非汝威神所毀滅。此母宿命供養百八十億佛已。從前佛受決。務以經法教授開化人民。未暇修檀。故今貧窮無有財寶。却後三十劫。功德成滿當得作佛。號曰須彌燈光如來至真。世界無有日月。人民身中皆有大光。宮室眾寶光明相照如忉利天上。老母聞決歡喜。即時輕舉身昇虚空。去地百八十丈。來下頭面作禮而去。

過去作者曾聽過一個『問題』和一個『回答

問題如何『照亮』世界

回答點燃自己心中的『光明』,照亮自己『身旁』的人;另一人因著光照明亮或因偶然燃起他心中的『光明』,如此如是持久長遠,終將『照亮』世界

,今日想來這個『點燈理論』也許出自『佛說』。

 

生 ︰何能繼明照于四方?唯願效法而已矣!續繼昨日之軌跡 ,釐清若干疑義。

Unicode HOWTO

This HOWTO discusses Python support for Unicode, and explains various problems that people commonly encounter when trying to work with Unicode.

Introduction to Unicode

History of Character Codes

In 1968, the American Standard Code for Information Interchange, better known by its acronym ASCII, was standardized. ASCII defined numeric codes for various characters, with the numeric values running from 0 to 127. For example, the lowercase letter ‘a’ is assigned 97 as its code value.

ASCII was an American-developed standard, so it only defined unaccented characters. There was an ‘e’, but no ‘é’ or ‘Í’. This meant that languages which required accented characters couldn’t be faithfully represented in ASCII. (Actually the missing accents matter for English, too, which contains words such as ‘naïve’ and ‘café’, and some publications have house styles which require spellings such as ‘coöperate’.)

For a while people just wrote programs that didn’t display accents. In the mid-1980s an Apple II BASIC program written by a French speaker might have lines like these:

PRINT "MISE A JOUR TERMINEE"
PRINT "PARAMETRES ENREGISTRES"

Those messages should contain accents (terminée, paramètre, enregistrés) and they just look wrong to someone who can read French.

In the 1980s, almost all personal computers were 8-bit, meaning that bytes could hold values ranging from 0 to 255. ASCII codes only went up to 127, so some machines assigned values between 128 and 255 to accented characters. Different machines had different codes, however, which led to problems exchanging files. Eventually various commonly used sets of values for the 128–255 range emerged. Some were true standards, defined by the International Standards Organization, and some were de facto conventions that were invented by one company or another and managed to catch on.

255 characters aren’t very many. For example, you can’t fit both the accented characters used in Western Europe and the Cyrillic alphabet used for Russian into the 128–255 range because there are more than 128 such characters.

You could write files using different codes (all your Russian files in a coding system called KOI8, all your French files in a different coding system called Latin1), but what if you wanted to write a French document that quotes some Russian text? In the 1980s people began to want to solve this problem, and the Unicode standardization effort began.

Unicode started out using 16-bit characters instead of 8-bit characters. 16 bits means you have 2^16 = 65,536 distinct values available, making it possible to represent many different characters from many different alphabets; an initial goal was to have Unicode contain the alphabets for every single human language. It turns out that even 16 bits isn’t enough to meet that goal, and the modern Unicode specification uses a wider range of codes, 0 through 1,114,111 ( 0x10FFFF in base 16).

There’s a related ISO standard, ISO 10646. Unicode and ISO 10646 were originally separate efforts, but the specifications were merged with the 1.1 revision of Unicode.

(This discussion of Unicode’s history is highly simplified. The precise historical details aren’t necessary for understanding how to use Unicode effectively, but if you’re curious, consult the Unicode consortium site listed in the References or the Wikipedia entry for Unicode for more information.)

……

PEP 3111 — Simple input built-in in Python 3000

Abstract

Input and output are core features of computer programs. Currently, Python provides a simple means of output through the print keyword and two simple means of interactive input through the input() and raw_input() built-in functions.

Python 3.0 will introduce various incompatible changes with previous Python versions [1] . Among the proposed changes, print will become a built-in function, print(), while input() and raw_input() would be removed completely from the built-in namespace, requiring importing some module to provide even the most basic input capability.

This PEP proposes that Python 3.0 retains some simple interactive user input capability, equivalent to raw_input(), within the built-in namespace.

It was accepted by the BDFL in December 2006 [5] .

Motivation

With its easy readability and its support for many programming styles (e.g. procedural, object-oriented, etc.) among others, Python is perhaps the best computer language to use in introductory programming classes. Simple programs often need to provide information to the user (output) and to obtain information from the user (interactive input). Any computer language intended to be used in an educational setting should provide straightforward methods for both output and interactive input.

The current proposals for Python 3.0 [1] include a simple output pathway via a built-in function named print(), but a more complicated method for input [e.g. via sys.stdin.readline()], one that requires importing an external module. Current versions of Python (pre-3.0) include raw_input() as a built-in function. With the availability of such a function, programs that require simple input/output can be written from day one, without requiring discussions of importing modules, streams, etc.

……

 

碼 ︰無 習 。無課。

 

行 習 行習︰雖然過程跌跌撞撞,終於得此『入出針語言』之第一嚐︰

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import math
import operator
import string
import threading
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

開 = 亮 = 低 = 0
關 = 滅 = 高 = 1

from time import sleep

import tpg

if tpg.__python__ == 3:
    operator.div = operator.truediv
    raw_input = input

def make_op(op):
    return {
        '加'   : operator.add,
        '減'   : operator.sub,
        '乘'   : operator.mul,
        '除'   : operator.div,
        '剩'   : operator.mod,
        '^'   : lambda x,y:x**y,
        '**'  : lambda x,y:x**y,
        '餘弦' : math.cos,
        '正弦' : math.sin,
        '切弦' : math.tan,
        'acos': math.acos,
        'asin': math.asin,
        'atan': math.atan,
        '平方' : lambda x:x*x,
        '根號': math.sqrt,
        '正值' : abs,
        'norm': lambda x,y:math.sqrt(x*x+y*y),
    }[op]

數碼賦值 = [(滅, 亮, 亮, 滅, 滅, 滅, 滅, 滅), (亮, 亮, 滅, 亮, 亮, 滅, 亮, 滅), (亮, 亮, 亮, 亮, 滅, 滅, 亮, 滅),  (滅, 亮, 亮, 滅, 滅, 亮, 亮, 滅)
]

遲延 = 0.012

# 數碼管

四位數碼管位選一 = 17
四位數碼管位選二 = 27
四位數碼管位選三 = 22
四位數碼管位選四 = 10

LEDA = 21
LEDB = 16
LEDC = 19
LEDD = 6
LEDE = 5
LEDF = 20
LEDG = 26
LEDH = 13

# 初始態

GPIO.setup(四位數碼管位選一, GPIO.OUT, initial=關)
GPIO.setup(四位數碼管位選二, GPIO.OUT, initial=關)
GPIO.setup(四位數碼管位選三, GPIO.OUT, initial=關)
GPIO.setup(四位數碼管位選四, GPIO.OUT, initial=關)

GPIO.setup(LEDA, GPIO.OUT, initial=滅)
GPIO.setup(LEDB, GPIO.OUT, initial=滅)
GPIO.setup(LEDC, GPIO.OUT, initial=滅)
GPIO.setup(LEDD, GPIO.OUT, initial=滅)
GPIO.setup(LEDE, GPIO.OUT, initial=滅)
GPIO.setup(LEDF, GPIO.OUT, initial=滅)
GPIO.setup(LEDG, GPIO.OUT, initial=滅)
GPIO.setup(LEDH, GPIO.OUT, initial=滅)



def 數碼管執行緒():
    global 數碼賦值
    global 遲延

    數碼管 = [LEDA, LEDB, LEDC, LEDD, LEDE, LEDF, LEDG, LEDH]

    while True :

        for 單元 in range(0,4):
            if 單元 == 0 :
                GPIO.output(四位數碼管位選一, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選一, 關)

            if 單元 == 1 :
                GPIO.output(四位數碼管位選二, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選二, 關)

            if 單元 == 2 :
                GPIO.output(四位數碼管位選三, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選三, 關)

            if 單元 == 3 :
                GPIO.output(四位數碼管位選四, 開)
                GPIO.output(數碼管, 數碼賦值[單元])
                sleep(0.002)
                GPIO.output(四位數碼管位選四, 關)

        sleep(遲延)

數碼緒 = threading.Thread(name="數碼", target=數碼管執行緒)

數碼緒.start()

數碼管輸出字典 = { "0" : (亮, 亮, 亮, 亮, 亮, 亮, 滅, 滅) ,
                   "1" : (滅, 亮, 亮, 滅, 滅, 滅, 滅, 滅) ,
                   "2" : (亮, 亮, 滅, 亮, 亮, 滅, 亮, 滅) ,
                   "3" : (亮, 亮, 亮, 亮, 滅, 滅, 亮, 滅) ,
                   "4" : (滅, 亮, 亮, 滅, 滅, 亮, 亮, 滅) ,
                   "5" : (亮, 滅, 亮, 亮, 滅, 亮, 亮, 滅) ,
                   "6" : (亮, 滅, 亮, 亮, 亮, 亮, 亮, 滅) ,
                   "7" : (亮, 亮, 亮, 滅, 滅, 滅, 滅, 滅) ,
                   "8" : (亮, 亮, 亮, 亮, 亮, 亮, 亮, 滅) ,
                   "9" : (亮, 亮, 亮, 亮, 滅, 亮, 亮, 滅) ,
                 }


def 輸出數碼管(數據) :
    global 數碼賦值
    global 數碼管輸出字典

    if 數據 > 999.9 :
        return "數值超過 999.9"
    else:

        字符串 = "%05.1f" %數據

        for 單元 in range(0,5):
            if 單元 == 0 :
                數碼賦值[單元] = 數碼管輸出字典[字符串[單元]]
            elif 單元 == 1 :
                數碼賦值[單元] = 數碼管輸出字典[字符串[單元]]
            elif 單元 == 2 :
                暫列 = list(數碼管輸出字典[字符串[單元]])
                暫列[7] = 亮
                數碼賦值[單元] = tuple(暫列)
            elif 單元 == 3 :
                continue
            else:
                數碼賦值[單元 - 1] = 數碼管輸出字典[字符串[單元]]

    return "完成"



GPIO.setup(11, GPIO.OUT, initial=GPIO.HIGH)
小哨子 = GPIO.PWM(11, 130.8)

def 啟動蜂鳴器():
        小哨子.start(100)
        return "蜂鳴器已啟動"

def 響聲控制(頻率):
        小哨子.ChangeFrequency(頻率)
        小哨子.start(50)
        return 頻率

def 噤聲控制(頻率):
        小哨子.ChangeFrequency(頻率)
        小哨子.start(100)
        return "噤聲"

def 控制蜂鳴器(op):
    return {
        '響聲'   : 響聲控制,
        '禁音'   : 噤聲控制,
   }[op]

def 輸入符碼(針碼):
        return GPIO.input(針碼)


def 輸出符碼(針碼, 賦值):
        GPIO.output(針碼, 賦值)
        return "輸出" + str(賦值)

def 出入定義(針碼, 入出):
        if 入出 == "出" :
            GPIO.setup(針碼, GPIO.OUT, initial = GPIO.HIGH)
        else:
            GPIO.setup(針碼, GPIO.IN, pull_up_down = GPIO.PUD_UP)
        return "定義完成"

def 出針定義(針碼):
    GPIO.setup(針碼, GPIO.OUT, initial = GPIO.HIGH)
    return "定義輸出完成"

def 入針定義(針碼):
    GPIO.setup(針碼, GPIO.IN, pull_up_down = GPIO.PUD_UP)
    return "定義輸入完成"


def 入出針定義(op):
    return {
        '入針'   : 入針定義,
        '出針'   : 出針定義,
   }[op]


class 實習機板(tpg.Parser, dict):
    r"""
    此實習基板入出針語言嘗試,自 Calc.py 擴充而來。由於使用中文之故,
    不能使用預設的 NamedGroupLexer 。
    文法定義如下 ::

        set lexer = CacheLexer

        separator space '\s+' ;

        token 指數運算    '\^|\*\*'                                               make_op         token 入出設定    '(入針|出針)\b' 入出針定義
        token 聲音控制    '(響聲|禁音)\b'                                                   控制蜂鳴器         token 加減運算    '[加|減]' make_op
        token 乘除運算    '[乘|除|剩]'                                                 make_op         token 函數一    '(餘弦|正弦|切弦|acos|asin|atan|平方|根號|正值)\b' make_op
        token 函數二    '(norm)\b'                                              make_op         token real      '(\d+\.\d*|\d*\.\d+)([eE][-+]?\d+)?|\d+[eE][-+]?\d+' float
        token integer   '\d+'                                                   int         token VarId     '\w*'                                                    ;          START/e ->                 '變元' e=self.記憶()
            |   VarId/v '=' Expr/e      self[v]=e             |   Expr/e #            |   '定義' Expr/p '出' e=出入定義(p, '出')
#            |   '定義' Expr/p '入'             e=出入定義(p, '入')             |   '入出針'  Expr/p 入出設定/op e=op(p)
            |   '讀入' Expr/p                  e=輸入符碼(p)             |   '寫出' Expr/p '開' e=輸出符碼(p, 0)
            |   '寫出' Expr/p '關'                 e=輸出符碼(p, 1)             |   "打開蜂鳴器" e=啟動蜂鳴器()
            |   "蜂鳴器" 聲音控制/op Expr/p       e = op(p)             |   "顯示" Expr/p e = 輸出數碼管(p)
        ;

        Var/self.get(v,0) -> VarId/v ;

        Expr/e -> Term/e ( 加減運算/op Term/t     e=op(e,t)                          )*         ;         Term/t -> Fact/t ( 乘除運算/op Fact/f t=op(t,f)
                         )*
        ;

        Fact/f ->
                加減運算/op Fact/f                f=op(0,f)             |   Pow/f         ;          Pow/f -> Atom/f ( 指數運算/op Fact/e f=op(f,e)
                        )?
        ;

        Atom/a ->
                real/a
            |   integer/a
            |   Function/a
            |   Var/a
            |   '' Expr/a ''
        ;
        
        Function/y ->
                函數一/f '' Expr/x ''              y = f(x)               | 函數二/f '<img src="https://www.freesandal.org/wp-content/ql-cache/quicklatex.com-5618a7a7b23dfd84e41ef622fed8142e_l3.png" class="ql-img-inline-formula quicklatex-auto-format" alt="' Expr/x1 ',' Expr/x2 '" title="Rendered by QuickLaTeX.com" height="19" width="165" style="vertical-align: -5px;"/>' y = f(x1,x2)
        ;

    """

    def __init__(self):
        super().__init__()
        self.名稱 = "實習機板"
        self["一藍"] = 5
        self["二藍"] = 6
        self["三藍"] = 13
        self["四藍"] = 19
        self["五綠"] = 0
        self["六綠"] = 1
        self["七黃"] = 7
        self["八紅"] = 8
        self["按鍵一"] = 23
        self["按鍵二"] = 18
        self["撥碼一"] = 24
        self["撥碼二"] = 25



    def 記憶(self):
        vars = sorted(self.items())
        memory = [ "%s = %s"%(var, val) for (var, val) in vars ]
        return "\n\t" + "\n\t".join(memory)



print("Calc (TPG example)")
實習機 = 實習機板()
while 1:
    try:
       l = raw_input("\n:")
    except UnicodeDecodeError:
       continue

    if l:
        try:
            print(實習機(l))
        except Exception:
            print(tpg.exc())
    else:
        break


數碼緒._stop()

GPIO.cleanup()


 

,還得加緊的試,趕在那開課之先︰

IMG_0660s

 

pi@raspberrypi ~ $ sudo python3 Miomachine.py 
Calc (TPG example)

:顯示 3
完成

:顯示 正弦( 3.14 除 6)
完成

:打開蜂鳴器
蜂鳴器已啟動

:蜂鳴器 響聲 2
2

:蜂鳴器 禁音 10
噤聲

:入出針 七黃 出針
定義輸出完成

:寫出 七黃 開
輸出0

:顯示 1000 除 365.25
完成

:顯示 根號(179)
完成

:變元

	一藍 = 5
	七黃 = 7
	三藍 = 13
	二藍 = 6
	五綠 = 0
	八紅 = 8
	六綠 = 1
	四藍 = 19
	按鍵一 = 23
	按鍵二 = 18
	撥碼一 = 24
	撥碼二 = 25

:入出針 撥碼一 入針
定義輸入完成

:讀入 撥碼一
1

:讀入 撥碼一
0

:

 

訊 如今或將曉 禮記‧中庸》:

或生而知之,或學而知之,或困而知之,及其知之一也。或安而行之,或利而行之,或勉強而行之,及其成功一也。

,所謂之困知勉行何謂也?