title

Raspberry PI 3

前へ


2018-11-14  「PyQt5 はじめ, INTERNET RADIO」
[pyqt5-mywindow.png]
①インストール
 sudo apt install python3-pyqt5 qtcreator qt5-qmake qt5-default
 (ui-python.py変換する場合は、pyqt5-dev-tools もインストール)

②プログラム作成
 qtcreator 起動 => プロジェクト新規作成 アプリケーション・Qtウィジェットアプリケーション で 「選択」クリック。
 プロジェクト名・パス 入力 「次へ」 クリック。
 フォーム生成チェック 次へ クリック 「完了」 クリック。
 フォームとプログラムが生成される。
 プロジェクト・プログラム新規作成 ファイルとクラス でPython、Pythonソース 「選択」クリック。
 Pythonソースファイル名 入力 「次へ」 クリック。
 「次へ」 クリック。
 「完了」 クリック。
 Pyhonプログラムとフォームをqtcreatorで作成。
 qtcreatorウィンドウの左側のプロジェクト編集ウィンドウの「開いているドキュメント」内のPythonソース名を
 マウス右クリックしてメニュー「ここでターミナルを開く」を選んで、端末ターミナル内で
 ”python3 作ったプログラムソース名”のコマンドでPythonプログラムを実行する。

qtcreatorの設定でのGCCは/usr/bin/gccでよい。c,c++を使う場合はドキュメントまたは、WEB検索で調べたものを設定すること。 
以下はプログラム一式。

---- mainwindow.ui -------
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>285</width>
    <height>206</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <widget class="QSlider" name="horizontalSlider">
    <property name="geometry">
     <rect>
      <x>60</x>
      <y>100</y>
      <width>160</width>
      <height>26</height>
     </rect>
    </property>
    <property name="orientation">
     <enum>Qt::Horizontal</enum>
    </property>
   </widget>
   <widget class="QLCDNumber" name="lcdNumber">
    <property name="geometry">
     <rect>
      <x>90</x>
      <y>10</y>
      <width>91</width>
      <height>81</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <pointsize>25</pointsize>
     </font>
    </property>
    <property name="layoutDirection">
     <enum>Qt::LeftToRight</enum>
    </property>
    <property name="autoFillBackground">
     <bool>false</bool>
    </property>
    <property name="styleSheet">
     <string notr="true">color: red;</string>
    </property>
    <property name="smallDecimalPoint">
     <bool>false</bool>
    </property>
    <property name="digitCount">
     <number>2</number>
    </property>
    <property name="value" stdset="0">
     <double>0.000000000000000</double>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>285</width>
     <height>31</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>
------------------------
mainwindow.uiファイルはpythonプログラムと同じディレクトリへ入れる。

---- test01.py----------
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QIcon

class MyWindow(QMainWindow):
    """ My window Class """
    def __init__(self):
        super().__init__()

        self.window = uic.loadUi('mainwindow.ui')
        self.window.horizontalSlider.valueChanged.connect(self.sel)
        self.window.setWindowIcon(QIcon('num.png'))
        # アイコンは適当なものを同じディレクトリに入れておく。要らなければコメントにする。        
        self.window.setWindowTitle("私の窓")
        self.window.show()

    def sel(self,val):
        self.window.lcdNumber.display(val)

def main():
    """ Main """
    app = QApplication(sys.argv)
    exe = MyWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
-----------
実行
python3 test01.py

「INTERNET RADIO インストール」
参照:http://skalldan.wordpress.com/2013/02/20/raspberry-pi-%E3%81%A7%E9%81%8A%E3%81%B6-3-radiko-%E3%81%AE%E9%8C%B2%E9%9F%B3%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC/
参照:http://zinziroge.hatenablog.com/entry/20121224/1356346975

(1)sudo apt-get install mplayer2
(2)sudo apt-get install streamripper
(3)sudo apt-get install rtmpdump swftools libxml2-utils libav-tools libao-dev libasound2-dev libmp3lame0 libmp3lame-dev
(4)pip3 install pyalsaaudio

radiko インストール
参照:http://kyoshiaki.hatenablog.com/entry/2014/05/04/184748
   (http://kyoshiaki.sakura.ne.jp/osx/Sample/rec_radiko2_2.zip)
からShellScriptもらいました。

修正内容 rec_radiko2.sh

   rec_radiko2.sh
    MP3変換に時間がかかるのでrtmdump の--flv の出力先を/tmpから${outdir}にしてそのまま格納
    聞くときはmplayer。
    聞くだけの時は出力をSTDOUTにし、mplayerに渡せばよい
    play_radiko.shに名前変更。
   ●mp3変換(libav-tools)
    avconv -y -i "入力ファイル名" -acodec libmp3lame -ar 44100 ¥
     -metadata album="名称" -metadata artist="名前" ¥
     "出力ファイル名.mp3" )
   ●VOLUME
     amixer -c card-no set PCM n%

   ●mplayer URL (line out)
    mplayer --audio-device alsa/hw:1  URL (USB speaker)

以下の添付ファイルを解凍して同じディレクトリに置いて
station.txtは作成する
---------station.txtフォーマット------------
rdid,ラジコ登録メールアドレス
rdpass,ラジコ登録パスワード
ラジオ局名タイトル,mplayerに渡すURL
ワシントンWTOPFM,http://playersexxxxxxxxld.com/api/livxxxxxxxxx/WTOPFM.mp3
ラジコのラジオ局名タイトル,jpn ラジコ局ID
ニッポン放送,jpn LFR
---------
mplayer URLはVtunerのリストから選んでくる
http://vtuner.com/setupapp/guide/asp/BrowseStations/startpage.asp
radikoのタイトルの後のカンマ、英字小文字jpn空白1は決まりごと、その後に局idを記述
rdid, rdpass,も決まりごと

(5)python3 radio-1.py
実行する。

プログラムダウンロード pyradiko.tgz

[pyradio-window.png]

2018-07-30  「Raspberry pi 3B+」
[RasPI3BPlus.jpg]
(1)箱を開けたら、裸で基板が入っていた。
 なんと大胆なことで。普通は静電気防止の袋に入ってるのに。
 特に壊れてはいなかったが、大丈夫なの?

osは2018−06−27イメージ使用。

(2) USB Boot 確認
 
  vcgencmd otp_dump

  17:3020000a
  を確認。
  確かにusbブートした。何もしなくてもよい。

(3)ロケールを日本にしても、負荷メータの文字化けはまだ治らない。

(4) Wifi 5Ghz はIDリストに赤い字で5G表示になる。

2018-07-25  「emacs, slime, SBCL Lispのインストール」
LISPをSLIMEでやる。

(1)sudo apt update
(2)sudo apt install -y emacs slime sbcl
(3)nano .emacs
---
(cd ".")               ;start on current directory
(setq frame-title-format "%b") ;タイトルに表示

(setq make-backup-files t)
(setq auto-save-default nil)
(setq make-backup-files nil)

(setq column-number-mode t)

(setq tab-width 4)
(setq default-tab-width 4)
(setq auto-save-default nil)
(setq make-backup-files nil)

(setq column-number-mode t)

(setq default-file-name-coding-system 'utf-8-unix)

(require 'tramp)
;;  ------ Shell Mode でShift-Jisコードを扱いファイル書き込ではUTF-8 ---
;;  ------ (o) 文字化けがないのであると便利で (o)
(add-hook
 'shell-mode-hook
 '(lambda()
 (set-buffer-process-coding-system 'sjis 'sjis)
 (set-buffer-file-coding-system 'utf-8-dos)))

;; ---------SLIME----------------------
(setq inferior-lisp-program "/usr/bin/sbcl")

(require 'slime)
(add-hook 'lisp-mode-hook (lambda ()
               (slime-mode t)
               (show-paren-mode)))
(slime-setup '(slime-fancy))

(global-set-key "\C-cs" 'slime-selector)
(slime)
---
(4)メインメニュー プログラミング Emacs GUI

emacs, slime インストールで sbcl LISPが入る。
普段はLISP使いのEmacsではなくShift-jisコードを扱いたいとき使っています。
Wikipediaには載っていたので忘れてそのままではなっているわけではなさそう。
実はasahi-netのパソコン通信の入り口から入って、ブログの一括ダウンロードができるので使っています。
ブログが全部できるかどうかはわかりません。昔のままのメニューに出ているのはいいようです。
動態保存の博物館ようでそれなりの意味があるかも。
2018-07-08  「AQM1248A SPI接続」
いろいろなものがインストールされているので、今まで説明されていたインストールモジュールとなっていたのがいらなくなるかを見た。

LCDの接続

LCD       Raspberry pi 3B
1 VDD -- 3.3V
2 CS  --- GPIO25
3 RST -- GPIO25
4 RS  -- GPIO24
5 SCLK -- GPIO11/SPCLK
6 SDI -- GPIO10/MOSI
7 GND -- GND 

AQM1248Aライブラリ
https://github.com/kujirahand/Raspi-AQM1248A
より
AQM1248.py をもらう。

$ nano t1248.py
---
# -*- coding: utf-8 -*-
import AQM1248A
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

disp = AQM1248A.LCD(rs_port=24, cs_port=7, reset_port=25)
image = Image.open('test.jpg')
disp.show(image)
disp.close()
--- 作成
AQM1248A.LCD(rs_port=24, cs_port=7, reset_port=25)のピン番号はrs_port=24, cs_port=8, reset_port=23がデフォルト
その時はAQM1248A.LCD()でよい。
AQM1248.py も同じディレクトリに入れる。

ビットマップ作成ツールインストール
$ sudo apt install imagemagick

$ convert -background white -fill black -font /usr/share/fonts/truetype/takao-gothic/TakaoGothic.ttf  -size "128x48"  label:"SPI AQM1248A\ngit-kujirahand\n/Raspi-AQM1248A" test.jpg
 label: 表示する内容
 font: フォントのパスを指定
 イメージビューアでtest.jpgが確認できる

$ python3 t1248.py
[aqm1248a-spi.jpg]

$ nano t-mozi.py
---
# -*- coding: utf-8 -*-
import AQM1248A
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

# font drawing
path = '/usr/share/fonts/truetype/takao-gothic/TakaoGothic.ttf'
# text
disp = AQM1248A.LCD(rs_port=24, cs_port=7, reset_port=25)
image = Image.new('1', (disp.WIDTH, disp.HEIGHT), 0)
draw = ImageDraw.Draw(image)
draw.rectangle((0,0,disp.WIDTH, disp.HEIGHT), outline=1, fill=1)
f = ImageFont.truetype(path, 11, encoding='unic')
draw.text((0,  0), "【参考】 日経LINUX", font=f, fill=0)
draw.text((0, 12), "2016.10月号 特集3", font=f, fill=0)
draw.text((0, 24), " Raspberry piを小さな", font=f, fill=0)
draw.text((0, 36), " ガジェットにしよう", font=f, fill=0)
disp.show(image)
disp.close()
ーー作成

$ python3 t-mozi.py
2018-06-18  「Wordpress 投稿メールを取りにいく」
WORDPRESSプラグインpostieは時間指定してもメールを取りに行かないのでcrontabで取るようにする。
wp_cli コマンドをインストールすること。

www/www/wp-config.php
--- 追加
define('DISABLE_WP_CRON',true);
ーーwordpress cron を止める

crontab で10分ごとにメールを見るようにする。

*/10 * * * * cd /wordpressディレクトリ; /usr/local/WP_CLIインストールディレクトリ/wp cron event run check_postie_hook  > /dev/null 2>&1

(check_postie_hookはwp  cron event listで表示されるhook名称,または--due-now)
2018-06-11  「Pythonフローチャート」
pythonでTABと空白がよく見えないので、よく見えるようにした。
インデントがプログラムの意味をもつのでこれを表現したら、ドキュメントになるかなと思って。

行先頭のTAB,空白だけ見ている。
インデントは',' 、空白は'_"を表す。漢字空白は空白のまま。
ーーーflow.pyーーー
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Kiyoshi Shimomura
# This software is released under the MIT License.

import re
import sys

while True:
	head = ""
	bdy = sys.stdin.readline()
	if not bdy: break
	bdy = bdy.rstrip('\r\n')
	match = re.search(r'^([\t]+)(.*)$',bdy)
	if not match is None:
		n1 = 4 - (len(head) % 4)
		n2 = len(match.groups()[0]) - 1
		head += "," * (n2 * 4 + n1)
		bdy = match.groups()[1]

	match = re.search(r'^([ ]+)(.*)$',bdy)
	while not match is None:
		head += "_" * len(match.groups()[0])
		bdy = match.groups()[1]
		match = re.search(r'^([\t]+)(.*)$',bdy)
		if not match is None:
			n1 = 4 - (len(head) % 4)
			n2 = len(match.groups()[0]) - 1
			head += "," * (n2 * 4 + n1)
			bdy = match.groups()[1]
			match = re.search(r'^([ ]+)(.*)$',bdy)
	print(head + bdy)
ーーーー終ーーーー
■使い方
$ ./flow.py < flow.py
 ;;
 ;;
while True:
,,,,head = ""
,,,,bdy = sys.stdin.readline()
,,,,if not bdy: break
,,,,bdy = bdy.rstrip('\r\n')
,,,,match = re.search(r'^([\t]+)(.*)$',bdy)
,,,,if not match is None:
,,,,,,,,n1 = 4 - (len(head) % 4)
,,,,,,,,n2 = len(match.groups()[0]) - 1
,,,,,,,,head += "," * (n2 * 4 + n1)
,,,,,,,,bdy = match.groups()[1]
2018-05-10  「CQ トラ技2018 - 3月号 有機EL 128x68 追加,ドップラーセンサ追加」
秋月電子通商 0.96インチ 128×64ドット有機ELディスプレイ(OLED) (P-12031) i2cインターフェースと 
秋月電子で売っているドップラーレーダーセンサをATtiny85経由i2c接続して使うもの。
CQ トラ技2018年3月号の今はオプション基板取り付け部分に取り付ける。配線は3.3V、GND、SCL,SDA結線。
ATiny85関係のプログラム、作成手順はAIY VoiceKitと同じ。
[el096-dopplersenser.jpeg]
[el-senser.png]
Google AIY Projectのサンプルソースassistant_library_with_button_demo.pyに、SW入力部分を別Classにして修正して使う。
手のひらをセンサにかざしてバスケットボールのドリブルをするように手首を中心にして前後に4回ほど振ります。それでSWが押されたことにする。
自分の喋った英語が認識されるかをみるためのツール。

http://ytkyk.info/blog/2016/06/19/raspberry-pi%E3%81%A7128x64%E3%81%AEoled%E3%81%AB%E6%97%A5%E6%9C%AC%E8%AA%9E%E3%82%92%E8%A1%A8%E7%A4%BA%E7%BE%8E%E5%92%B2%E3%83%95%E3%82%A9%E3%83%B3%E3%83%88/
Raspberry PiでI2C接続の128×64 OLEDに日本語を表示(美咲フォント)
より

  cd ~
  python3でインストールすること。
  git clone https://github.com/adafruit/Adafruit_Python_SSD1306.git
  cd Adafruit_Python_SSD1306
  sudo python3 setup.py install
  cd ~
  mkdir font
  mkdir font/misakifont
  cd font/misakifont
  wget http://www.geocities.jp/littlimi/arc/misaki/misaki_ttf_2015-04-10.zip
  unzip misaki_ttf_2015-04-10.zip
  cd ~

  参照サイト"Raspberry PiでI2C接続の128×64 OLEDに日本語を表示"よりソースをもらって、修正する。

  sudo nano ssd1306_japanese_font.py
  ---
#!/usr/bin/env python3    <==追加

ソースのはじめのところを以下のようpython3用に修正。

# import Adafruit_GPIO.SPI as SPI <=コメント
import Adafruit_SSD1306
 
from PIL import Image, ImageDraw, ImageFont
import sys
import unicodedata

# 表示可能行幅切り出し
def splitline(str, siz):
	i = 0
	mstr = []
	while i < len(str):
		n = 0
		c = 0
		for j in str[i:]:
			w = unicodedata.east_asian_width(j)
			if w  == "Na" or w == "H":
				n += 1
			else:
				n += 2
			if n == siz:
				c += 1
				break
			if n > siz:
				break
			c += 1
		mstr.append(str[i:i+c])
		i = i + c
	return mstr

# コマンドライン引数
if len(sys.argv) == 1:
	argv = ""
else:
	argv=sys.argv[1]
argv = argv.replace("¥n","\n")
argv = argv.replace("\\n","\n")
mlst = argv.split('\n')
msgv = []
for strg in mlst:
	str = strg.encode('UTF-8')
	str = str.decode('UTF-8')
	abc = splitline(str, 30)
	msgv += abc

# Raspberry Pi pin configuration
RST = 24
# RST 未使用
# EL i2cアドレス 0x3C (i2cdetect -y 1 で確認)
disp = Adafruit_SSD1306.SSD1306_128_64(rst=None)

# Initialize library.
disp.begin()
 ;;
 ;;

# Write two lines of text.
x=0
y=0
for str in msgv:
	draw.text((x,y), str, font=font, fill=255)
	y+=8
	if y >= 64:
		break

disp.image(image)
disp.display()
 ---
  chmod +x ssd1306_japanese_font.py

 使い方
  ./ssd1306_japanese_font.py "表示文字列 改行は\nを入れる"
 これを ~/sbin ディレクトリに入れる。

 nano ~/AIY-projects-python/src/examples/voice/assistant_library_with_button_demo.py
 ---
import logging
import platform
import sys
import threading
import os                                            <<<
from MyButton import MyButton  <<<

import aiy.assistant.auth_helpers
from aiy.assistant.library import Assistant
import aiy.voicehat
from google.assistant.library.event import EventType

;;

    def __init__(self):
        self._task = threading.Thread(target=self._run_task)
        self._can_start_conversation = False
        self._assistant = None
        self._dev_mybutton = MyButton(self._on_button_pressed)                 <<<
        self._my_done = False                                                                        <<<

    def lcd_dsp(self, str):                                                                                  <<<
        os.system("/home/pi/sbin/ssd1306_japanese_font.py \"" + str + "\" &")  <<<
;;

    def _process_event(self, event):
        status_ui = aiy.voicehat.get_status_ui()
        if event.type == EventType.ON_START_FINISHED:
            status_ui.status('ready')
            self._can_start_conversation = True
            # Start the voicehat button trigger.
            # aiy.voicehat.get_button().on_press(self._on_button_pressed)          <<<
            self.lcd_dsp('Say "OK, Google" or press the button, then speak. \n\nPress Ctrl+C to quit...')   <<
            self._dev_mybutton.start()                                                           <<
            #if sys.stdout.isatty():                                                                  <<
            #   print('Say "OK, Google" or press the button, then speak. '       <<
            #        'Press Ctrl+C to quit...')                                                     <<
;;
        elif event.type == EventType.ON_ASSISTANT_ERROR and event.args and event.args['is_fatal']:
            sys.exit(1)

        if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED and event.args:   <<<
            self.lcd_dsp('You said:' + event.args['text'])                                                             <<<

;;
def main():
    if platform.machine() == 'armv6l':
        print('Cannot run hotword demo on Pi Zero!')
        exit(-1)
    MyAssistant().lcd_dsp("Start with SW...")     <<<
    try:                                                             <<<
        MyAssistant().start()
    except  KeyboardInterrupt:                         <<<
      MyAssistant()._dev_mybutton.ctrl_exit()    <<<
;;
 ----以上のように修正して、~/AIY-projects-python/src/main.py という名前で書き込む。

  chmod +x ~/AIY-projects-python/src/main.py 

 nano systemd/voice-recognizer.service
 ----
[Service]
Environment=PYTHONPATH=/home/pi/AIY-projects-python/src   <<<
Environment=PATH=/home/pi/AIY-projects-python/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ExecStart=/home/pi/AIY-projects-python/src/main.py                   <<<
WorkingDirectory=/home/pi/AIY-projects-python
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi
  ----修正する

  sudo systemctl restart voice-recognizer
  で自動で起動するようになる。AIY SDKインストールした時サービスをインストール(sudo scripts/install-services.sh)していればですが。

 "OK google" の後英語で発音したものが帰るのでテキストを有機ELに表示します。
 ただ自分の発音が意図したセンテンスで認識されたかどうかの確認のためだけのものです。
2018-05-09  「CQ トラ技2018 - 3月号 2018-04-18 raspbian stretch imageにダンボール箱AIYに入ってるサンプルプログラムインストール」
ダンボール箱AIYスピーカに入ってるサンプルプログラムを 2018-04-18-raspbian-stretch.img にインストール

ハードの動作テストはあらかじめする。
[cq-trg-201803]
OSフル(raspbian liteはないのがあると面倒なので)をSDカードに書き込む。
piパスワード変更、ホスト名設定、TZ JST,キーボード設定、ロケールja_JP.UTF-8設定、Wifi-JP設定をする。

sudo apt update;sudo apt-get install 日本語フォント; sudo rpi-update;sudo reboot をし、リーブート。
フォントはインストールしなくてもいいがCPU負荷の%表示が化ける。

sudo nano /boot/config.txt
---
dtparam=i2c_arm=on
dtparam=i2s=on
---#を取る
sudo nano /etc/modules
---
snd-bcm2835
---追加
sudo reboot
lsmod| grep snd
  snd_soc_bcm2835_i2s, snd_bcm2835 があること。

speaker-test -t wav
 analoggに切り替えてスピーカから音がでること。

sudo apt install bc libncurses5-dev
sudo wget https://raw.githubusercontent.com/notro/rpi-source/master/rpi-source -O /usr/bin/rpi-source
sudo chmod +x /usr/bin/rpi-source
/usr/bin/rpi-source -q --tag-update
rpi-source --skip-gcc
sudo mount -t debugfs debugs /sys/kernel/debug
  エラーが出るが無視。

sudo cat /sys/kernel/debug/asoc/platforms
 3f203000.i2s
 snd-soc-dummy 確認。

git clone https://github.com/PaulCreaser/rpi-i2s-audio
cd rpi-i2s-audio
make -C /lib/modules/$(uname -r)/build M=$(pwd) modules
sudo insmod my_loader.ko
lsmod | grep my_loader
 my_loader がロードされていること。

dmesg |tail
 3f203000.i2s mapping ok 確認。

sudo cp my_loader.ko /lib/modules/$(uname -r)

sudo nano /etc/modules
---
snd-bcm2835
my_loader
---my_loader追加

sudo depmod -a
sudo modprobe my_loader
sudo reboot

cd 〜
nano .asoundrc
---
pcm.softvol {
        type softvol
        slave.pcm "hw:1,0"
        control {
                name "Boost Capture Volume"
                card sndrpisimplecar
        }
        min_dB -3.0
        max_dB 30.0
}
pcm.!default {
        type asym
        capture.pcm "plug:softvol"
        playback.pcm "hw:0,0"
}
---

arecord --format=S16_LE --duration=5 --rate=16000 --file-type=raw out.raw
aplay --format=S16_LE --duration=5 --rate=16000 --file-type=raw out.raw
 録音されるか確認する。音は小さい。
 上の作業をしないとamixerに接続されない。
sudo reboot

cd ~
 .asoundrc が上で設定したままの内容のこと。

alsamixer
PF6 -> mic device選択 -> Volume 大きくする -> esc key
 録音ミキサーが"snd_rpi_simple_card"表示されること。

git clone https://github.com/google/aiyprojects-raspbian.git AIY-projects-python
cd AIY-projects-python
  soundに関しては設定したのでしない。
 systemdに関しては好みでよい。

nano ~/.bashrc
---
export PYTHONPATH="/home/pi/AIY-projects-python/src:$PYTHONPATH" 
---最後に追加

pip3 install RPi.GPIO
pip3 install numpy
python3 -m pip install --upgrade pip setuptools wheel
sudo apt install portaudio19-dev libffi-dev libssl-dev
sudo python3 -m pip install --upgrade google-assistant-library
sudo python3 -m pip install --upgrade google-assistant-sdk[samples]
sudo python3 -m pip install --upgrade google-auth-oauthlib[tool]
sudo reboot

python3 -m pip list| grep google-assistant
  google-assistant-sdk     0.4.4 となっていた。      

cd ~
 console cloud googleで登録した時ダウンロードした、 client_secret_xx...xxx.apps.googleusercontent.com.jsonを
  ホームディレクトリにコピーする。
   または、

 https://developers.google.com/assistant/sdk/guides/library/python/embed/register-device
     の手順でデバイスモデルを登録する

  ログインしてダッシュボードからスタートガイドのAPIをクリックする。左側のメニュー認証情報をクリックする。
 「OAuth 2.0 クライアント ID」 のデバイス登録されたIDをダウンロードする。

google-oauthlib-tool --scope https://www.googleapis.com/auth/assistant-sdk-prototype --save --headless --client-secrets /home/pi/client_secret_xxxxx....xxxx.apps.googleusercontent.com.json
WEB URLコピーしてログイン、許可。文字列コピーペースト。

credentials saved: /home/pi/.config/google-oauthlib-tool/credentials.json
が表示される。

client_secret_xxxxx....xxxx.apps.googleusercontent.com.jsonを/home/pi/assistant.jsonとしておピー。

src/examples/voice/assistant_library_demo.py
  最初はWEBで確認する。”Ok Google"でLED7が点灯する。それまではボヤ〜ボヤ〜と点滅。元気、天気、とかを質問。
  これを実行前までに環境変数PYTHONPATHを有効にしておくこと。

sudo apt install libttspico-utils
  assistant_library_with_local_commands_demo.pyの実行でTTS発声がありました。それのために追加インストール。

注)google-oauthlib-tool 認証してから固定IPアドレスにするとサンプルが実行できなくなるようです。
 そうなったら、もう一度google-oauthlib-tool 認証をし直せば良い。
2018-05-09  「AVR V-USB キーボード」
AVR V-USBのHID キーボードを試してみた。

●V-USB Reference Projects
https://www.obdev.at/products/vusb/prjobdev.html

の中にある、HIDKeys - a USB Keyboardのサンプル

●HIDKeys - An Example USB HID
https://www.obdev.at/products/vusb/hidkeys.html
の"HIDKeys.2012-12-08.zip"をもとに作成。

書き込み配線、ソフトツールはCQトラ技2018-3月号のAIY工作と同じものを使う。
[key.jpg]
オリジナルはATMEGA8ですが、ATMEGA88PA-DIPにしました。ハードウェアキーボードマトリクスは大昔のNewtonKeyboardというやつです。
キートップの印刷がUSなのでUS仕様に定義。回路はオリジナルとほぼ同じ。
動作はキー入力部分を修正してコンパイルして確認するとキー入力はできるようになります。

でも、raspi-configでKeyboard map変更でキーボード種類の一覧表が出てきません。これはHID定義にキー定義されていないため。

ディスクトップ以外の時キーマップは/etc/default/keyboardの内容に従います。
ディスクトップを使うと日本語入力fcitx-mozc等を使うのでタスクバーキーアイコンを右クリックして、「入力メソッドの設定」でUSキーマップを追加してください。

修正するところは以下。
ーーー
--- HIDKeys.2012-12-08/Makefile	2013-01-16 22:58:30.000000000 +0900
+++ New-vusb/Makefile	2018-04-10 13:53:29.000000000 +0900
@@ -7,13 +7,13 @@
 # License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt)
 # This Revision: $Id$
 
-SERIAL = `echo /dev/tty.KeySerial*`
-UISP = uisp -dprog=avr910 -dserial=$(SERIAL) -dpart=auto
+#SERIAL = `echo /dev/tty.KeySerial*`
+#UISP = uisp -dprog=avr910 -dserial=$(SERIAL) -dpart=auto
 # The two lines above are for "uisp" and the AVR910 serial programmer connected
 # to a Keyspan USB to serial converter to a Mac running Mac OS X.
 # Choose your favorite programmer and interface.
 
-COMPILE = avr-gcc -Wall -Os -Iusbdrv -I. -mmcu=atmega8 -DF_CPU=12000000L #-DDEBUG_LEVEL=1
+COMPILE = avr-gcc -Wall -Os -Iusbdrv -I. -mmcu=atmega88pa -DF_CPU=12000000L #-DDEBUG_LEVEL=1
 
 OBJECTS = usbdrv/usbdrv.o usbdrv/usbdrvasm.o usbdrv/oddebug.o main.o
 
@@ -35,7 +35,8 @@
 	$(COMPILE) -S $< -o $@
 
 flash:	all
-	$(UISP) --erase --upload if=main.hex
+	sudo avrdude -p m88p -P linuxgpio -c linuxgpio -v -U flash:w:main.hex
+#	$(UISP) --erase --upload if=main.hex
 #	$(UISP) --erase --upload --verify if=main.hex
 
 # Fuse high byte:
@@ -55,7 +56,8 @@
 #        | +------------------ BODEN (BrownOut Detector enabled)
 #        +-------------------- BODLEVEL (2.7V)
 fuse:
-	$(UISP) --wr_fuse_h=0xc9 --wr_fuse_l=0x9f
+	sudo avrdude  -p m88p -c linuxgpio -P linuxgpio -v -U lfuse:w:0xDF:m -U hfuse:w:0xDD:m -U efuse:w:0xF9:m
+#	$(UISP) --wr_fuse_h=0xc9 --wr_fuse_l=0x9f
 
 clean:
 	rm -f main.hex main.lst main.obj main.cof main.list main.map main.eep.hex main.bin *.o usbdrv/*.o main.s usbdrv/oddebug.s usbdrv/usbdrv.s
ーーー

ーーー
--- HIDKeys.2012-12-08/main.c	2013-01-16 22:58:30.000000000 +0900
+++ New-vusb/main.c	2018-05-06 13:18:26.251529511 +0900
@@ -12,6 +12,7 @@
 #include <avr/interrupt.h>
 #include <avr/pgmspace.h>
 #include <avr/wdt.h>
+#include <avr/cpufunc.h>
 
 #include "usbdrv.h"
 #include "oddebug.h"
@@ -19,83 +20,204 @@
 /* ----------------------- hardware I/O abstraction ------------------------ */
 
 /* pin assignments:
-PB0	Key 1
-PB1	Key 2
-PB2	Key 3
-PB3	Key 4
-PB4	Key 5
-PB5 Key 6
-
-PC0	Key 7
-PC1	Key 8
-PC2	Key 9
-PC3	Key 10
-PC4	Key 11
-PC5	Key 12
-
-PD0	USB-
-PD1	debug tx
-PD2	USB+ (int0)
-PD3	Key 13
-PD4	Key 14
-PD5	Key 15
-PD6	Key 16
-PD7	Key 17
+PB0	 Key Y3
+PB1	 Key Y5
+PB2	 Key Y14
+PB3	 Key Y15
+PB4	 Key Y16
+PB5 Key Y17
+
+PC0	 Key X2,4
+PC1	 Key X6
+PC2	 Key X7
+PC3	 Key X8
+PC4	 Key X0
+PC5	 Key X10
+
+PD0	 USB-
+PD1	 Key X11
+PD2	 USB+ (int0)
+PD3	 Key X12
+PD4 Key X13
+PD5	 Key X19,20
+PD6	 Key Y18
+PD7	 Key Y21
 */
 
+#define NUM_KEYS    9
+
+static const PROGMEM uchar Normkey[NUM_KEYS][8] = {
+  //Out-0   F6    F5    F4     xx    F3   F2    F1    xx     
+          {0x3F, 0x3E, 0x3D, 0x00, 0x3C, 0x3B, 0x3A, 0x00},
+  //Out-1    8     I     K      <    7     U     J     M     
+          {0x25, 0x0C, 0x0E, 0x36, 0x24, 0x18, 0x0D, 0x10},
+  //Out-2    9     O_    L      >    6     Y     H     N     
+          {0x26, 0x12, 0x0F, 0x37, 0x23, 0x1C, 0x0B, 0x11},
+  //Out-3    0|    P     ;      ?    5     T     G     B     
+          {0x27, 0x13, 0x33, 0x38, 0x22, 0x17, 0x0A, 0x05},
+  //Out-4    -     [     "  R-SHIFT  4     R     F     V    
+          {0x2D, 0x2F, 0x34, 0x52, 0x21, 0x15, 0x09, 0x19},
+  //Out-5   +=     ]   Retn  Ctrl    3     E     D     C     
+          {0x2E, 0x30, 0x28, 0xE0, 0x20, 0x08, 0x07, 0x06},
+  //Out-6   BS     \    Fn     ↓    2     W     S     X     
+          {0x2A, 0x31, 0x00, 0x4F, 0x1F, 0x1A, 0x16, 0x1B},
+  //Out-7   ALT Option   →          ↑           1     Q     A     Z     
+          {0xE2, 0x00, 0x51, 0xE5, 0x1E, 0x14, 0x04, 0x1D},
+  //Out-8 Space   ←     xx    xx    ~    TAB CAPS_LOCK L_SHIFT     
+          {0x2C, 0x50, 0x00, 0x00, 0x35, 0x2B, 0x39, 0xE1}
+};
+static const PROGMEM uchar Fnkey[NUM_KEYS][8] = {
+  //Out-0   F12   F11   F10   xx    F9    F8    F7    xx     
+          {0x45, 0x44, 0x43, 0x00, 0x42, 0x41, 0x40, 0x00},
+  //Out-1    8     I     K      <    7     U     J     M     
+          {0x25, 0x0C, 0x0E, 0x36, 0x24, 0x18, 0x0D, 0x10},
+  //Out-2    9     O_    L      >    6     Y     H     N     
+          {0x26, 0x12, 0x0F, 0x37, 0x23, 0x1C, 0x0B, 0x11},
+  //Out-3    0| PRT-SCRN ;      ?    5     T     G     B     
+          {0x27, 0x46, 0x33, 0x38, 0x22, 0x17, 0x0A, 0x05},
+  //Out-4    -     [     "  R-SHIFT  4     R     F     V    
+          {0x2D, 0x2F, 0x34, 0x4B, 0x21, 0x15, 0x09, 0x19},
+  //Out-5   +=     ]   Retn  Ctrl    3     E     D     C     
+          {0x2E, 0x30, 0x28, 0xE0, 0x20, 0x08, 0x07, 0x06},
+  //Out-6   DEL    \    Fn  PG-DOWN  2     W     S     X     
+          {0x4C, 0x31, 0x00, 0x4D, 0x1F, 0x1A, 0x16, 0x1B},
+  //Out-7   ALT Option  END  PG-UP   1     Q     A     Z     
+          {0xE2, 0x00, 0x4E, 0xE5, 0x1E, 0x14, 0x04, 0x1D},
+  //Out-8 Space  HOME   xx    xx    ESC  TAB CAPS_LOCK L_SHIFT     
+          {0x2C, 0x4A, 0x00, 0x00, 0x29, 0x2B, 0x39, 0xE1}
+};
+static const PROGMEM uchar Optnkey[NUM_KEYS][8] = {
+  //Out-0   F23   F22   F21     xx  F20    F2    F1   xx     
+          {0x72, 0x71, 0x70, 0x00, 0x6F, 0x3B, 0x3A, 0x00},
+  //Out-1    8     I     K      <    7     U     J     M     
+          {0x25, 0x0C, 0x0E, 0x36, 0x24, 0x18, 0x0D, 0x10},
+  //Out-2    9     O_    L      >    6     Y     H     N     
+          {0x26, 0x12, 0x0F, 0x37, 0x23, 0x1C, 0x0B, 0x11},
+  //Out-3    0|    P  ;    ?    5     T     G     B     
+          {0x27, 0x13, 0x33, 0x38, 0x22, 0x17, 0x0A, 0x05},
+  //Out-4    -     [     "  R-SHIFT  4     R     F     V    
+          {0x2D, 0x2F, 0x34, 0x52, 0x21, 0x15, 0x09, 0x19},
+  //Out-5   +=     ]   Retn  Ctrl    3     E     D     C     
+          {0x2E, 0x30, 0x28, 0xE0, 0x20, 0x08, 0x07, 0x06},
+  //Out-6   BS     \    Fn     ↓    2     W     S     X     
+          {0x2A, 0x31, 0x00, 0x4F, 0x1F, 0x1A, 0x16, 0x1B},
+  //Out-7   ALT Option   →          ↑           1     Q     A     Z     
+          {0xE2, 0x00, 0x51, 0xE5, 0x1E, 0x14, 0x04, 0x1D},
+  //Out-8 Space   ←          xx    xx     ~    TAB CAPS_LOCK L_SHIFT     
+          {0x2C, 0x50, 0x00, 0x00, 0x35, 0x2B, 0x39, 0xE1}
+};
+/* Keyboard usage values, see usb.org's HID-usage-tables document, chapter
+ * 10 Keyboard/Keypad Page for more codes.
+ */
+#define MOD_CONTROL_LEFT    (1<<0)
+#define MOD_SHIFT_LEFT      (1<<1)
+#define MOD_ALT_LEFT        (1<<2)
+#define MOD_GUI_LEFT        (1<<3)
+#define MOD_CONTROL_RIGHT   (1<<4)
+#define MOD_SHIFT_RIGHT     (1<<5)
+#define MOD_ALT_RIGHT       (1<<6)
+#define MOD_GUI_RIGHT       (1<<7)
+
+static uchar	Swb[16][3];		/* sw buffer */
+
+void sw_ini( void )
+{
+	int i, j;
+	for(i = 0; i < 16; i++ ) {
+		for( j = 0; j < 3; j++ )	Swb[i][j] = 0;
+	}
+}
+void chatta( uchar x, int ix )
+{
+	uchar y,d;
+
+	y = Swb[ix][0];
+	d = x ^ y;
+	Swb[ix][0] = x;
+	d = (y ^ Swb[ix][1]) | d;
+	Swb[ix][1] = y;
+	Swb[ix][2] = y & (d ^ 0xFF);
+}
+
+unsigned int sw( void )
+{
+	int i, j;
+	unsigned char a, b, c, f, Opt;
+	unsigned int sca;
+	uchar	sfl, sfr, ctl, alt;
+
+	PORTC = 0x3F;
+	PORTD = 0xF8;
+	for( i = 0; i < 9; i++) {
+		if( i < 6 ) {
+			PORTC = 0x3F ^ (1<<i);
+			PORTD = 0xF8;
+		} else {
+			PORTC = 0x3F;
+			PORTD = 0xF8 ^ (1<<(i-3));
+		}
+		_NOP();
+		_NOP();
+		a = PINB & 0x3F;
+		b = PIND & 0xC0;
+
+		c = a | b;
+		PORTC = 0x3F;
+		PORTD = 0xF8;
+		c ^= 0xFF;
+		chatta(c, i);
+	}
+	f = Swb[6][2] & 0x04 ;	// [fn] Key
+	Swb[6][2] ^= f;
+	Opt = Swb[7][2] & 0x02; // [Option] Key
+	Swb[7][2] ^= Opt;
+	sfr = Swb[7][2] & 0x08;
+	Swb[7][2] ^= sfr;
+	sfl = Swb[8][2] & 0x80;
+	Swb[8][2] ^= sfl;
+	ctl = Swb[5][2] & 0x08;
+	Swb[5][2] ^= ctl;
+	alt = Swb[7][2] & 0x01;
+	Swb[7][2] ^= alt;
+	
+	sca = ctl ? MOD_CONTROL_LEFT: 0;
+	sca |= sfr ? MOD_SHIFT_RIGHT: 0;
+	sca |= sfl ? MOD_SHIFT_LEFT: 0;
+	sca |= alt ? MOD_ALT_LEFT: 0;
+	for( i = 0; i < 9; i++ ) {
+		for( j = 0; j < 8; j++ ) {
+		    if( Swb[i][2] & (1<<j) )	{
+			if( f ) {
+				return (sca<<8)|pgm_read_byte(Fnkey[i]+j);
+			} else if( Opt ) {
+				return (sca<<8)|pgm_read_byte(Optnkey[i]+j);
+			} else {
+				return (sca<<8)|pgm_read_byte(Normkey[i]+j);
+			}
+		    }
+		}
+	}
+
+	return (sca<<8);
+}
 static void hardwareInit(void)
 {
 uchar	i, j;
 
-    PORTB = 0xff;   /* activate all pull-ups */
+    PORTB = 0x3F;   /* activate all no pull-ups */
     DDRB = 0;       /* all pins input */
-    PORTC = 0xff;   /* activate all pull-ups */
-    DDRC = 0;       /* all pins input */
-    PORTD = 0xfa;   /* 1111 1010 bin: activate pull-ups except on USB lines */
-    DDRD = 0x07;    /* 0000 0111 bin: all pins input except USB (-> USB reset) */
+    PORTC = 0x3F;
+    DDRC = 0x3F;    /* all pins OUTUT */
+    PORTD = 0xFA;   /* 1111 1010 bin: activate pull-ups except on USB lines */
+    DDRD = 0x3F;    /* 0000 0111 bin: all pins input except USB (-> USB reset) */
 	j = 0;
 	while(--j){     /* USB Reset by device only required on Watchdog Reset */
 		i = 0;
 		while(--i); /* delay >10ms for USB reset */
 	}
-    DDRD = 0x02;    /* 0000 0010 bin: remove USB reset condition */
+    DDRD = 0x3A;    /* 0000 0010 bin: remove USB reset condition */
     /* configure timer 0 for a rate of 12M/(1024 * 256) = 45.78 Hz (~22ms) */
-    TCCR0 = 5;      /* timer 0 prescaler: 1024 */
-}
-
-/* ------------------------------------------------------------------------- */
-
-#define NUM_KEYS    17
-
-/* The following function returns an index for the first key pressed. It
- * returns 0 if no key is pressed.
- */
-static uchar    keyPressed(void)
-{
-uchar   i, mask, x;
-
-    x = PINB;
-    mask = 1;
-    for(i=0;i<6;i++){
-        if((x & mask) == 0)
-            return i + 1;
-        mask <<= 1;
-    }
-    x = PINC;
-    mask = 1;
-    for(i=0;i<6;i++){
-        if((x & mask) == 0)
-            return i + 7;
-        mask <<= 1;
-    }
-    x = PIND;
-    mask = 1 << 3;
-    for(i=0;i<5;i++){
-        if((x & mask) == 0)
-            return i + 13;
-        mask <<= 1;
-    }
-    return 0;
+    TCCR0B = 5;      /* timer 0 prescaler: 1024 */
 }
 
 /* ------------------------------------------------------------------------- */
@@ -105,7 +227,7 @@
 static uchar    reportBuffer[2];    /* buffer for HID reports */
 static uchar    idleRate;           /* in 4 ms units */
 
-const PROGMEM char usbHidReportDescriptor[35] = {   /* USB report descriptor */
+const PROGMEM char usbHidReportDescriptor[USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH] = {   /* USB report descriptor */
     0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
     0x09, 0x06,                    // USAGE (Keyboard)
     0xa1, 0x01,                    // COLLECTION (Application)
@@ -119,9 +241,11 @@
     0x81, 0x02,                    //   INPUT (Data,Var,Abs)
     0x95, 0x01,                    //   REPORT_COUNT (1)
     0x75, 0x08,                    //   REPORT_SIZE (8)
-    0x25, 0x65,                    //   LOGICAL_MAXIMUM (101)
+    0x15, 0x00,			   //   LOGICAL_MIN (0)
+    0x05, 0x07,			   //   Keyboard
+    0x25, 0xFF,                    //   LOGICAL_MAXIMUM (101)
     0x19, 0x00,                    //   USAGE_MINIMUM (Reserved (no event indicated))
-    0x29, 0x65,                    //   USAGE_MAXIMUM (Keyboard Application)
+    0x29, 0xFF,                    //   USAGE_MAXIMUM (Keyboard Application)
     0x81, 0x00,                    //   INPUT (Data,Ary,Abs)
     0xc0                           // END_COLLECTION
 };
@@ -135,93 +259,10 @@
  * for the second INPUT item.
  */
 
-/* Keyboard usage values, see usb.org's HID-usage-tables document, chapter
- * 10 Keyboard/Keypad Page for more codes.
- */
-#define MOD_CONTROL_LEFT    (1<<0)
-#define MOD_SHIFT_LEFT      (1<<1)
-#define MOD_ALT_LEFT        (1<<2)
-#define MOD_GUI_LEFT        (1<<3)
-#define MOD_CONTROL_RIGHT   (1<<4)
-#define MOD_SHIFT_RIGHT     (1<<5)
-#define MOD_ALT_RIGHT       (1<<6)
-#define MOD_GUI_RIGHT       (1<<7)
-
-#define KEY_A       4
-#define KEY_B       5
-#define KEY_C       6
-#define KEY_D       7
-#define KEY_E       8
-#define KEY_F       9
-#define KEY_G       10
-#define KEY_H       11
-#define KEY_I       12
-#define KEY_J       13
-#define KEY_K       14
-#define KEY_L       15
-#define KEY_M       16
-#define KEY_N       17
-#define KEY_O       18
-#define KEY_P       19
-#define KEY_Q       20
-#define KEY_R       21
-#define KEY_S       22
-#define KEY_T       23
-#define KEY_U       24
-#define KEY_V       25
-#define KEY_W       26
-#define KEY_X       27
-#define KEY_Y       28
-#define KEY_Z       29
-#define KEY_1       30
-#define KEY_2       31
-#define KEY_3       32
-#define KEY_4       33
-#define KEY_5       34
-#define KEY_6       35
-#define KEY_7       36
-#define KEY_8       37
-#define KEY_9       38
-#define KEY_0       39
-
-#define KEY_F1      58
-#define KEY_F2      59
-#define KEY_F3      60
-#define KEY_F4      61
-#define KEY_F5      62
-#define KEY_F6      63
-#define KEY_F7      64
-#define KEY_F8      65
-#define KEY_F9      66
-#define KEY_F10     67
-#define KEY_F11     68
-#define KEY_F12     69
-
-static const uchar  keyReport[NUM_KEYS + 1][2] PROGMEM = {
-/* none */  {0, 0},                     /* no key pressed */
-/*  1 */    {MOD_SHIFT_LEFT, KEY_A},
-/*  2 */    {MOD_SHIFT_LEFT, KEY_B},
-/*  3 */    {MOD_SHIFT_LEFT, KEY_C},
-/*  4 */    {MOD_SHIFT_LEFT, KEY_D},
-/*  5 */    {MOD_SHIFT_LEFT, KEY_E},
-/*  6 */    {MOD_SHIFT_LEFT, KEY_F},
-/*  7 */    {MOD_SHIFT_LEFT, KEY_G},
-/*  8 */    {MOD_SHIFT_LEFT, KEY_H},
-/*  9 */    {MOD_SHIFT_LEFT, KEY_I},
-/* 10 */    {MOD_SHIFT_LEFT, KEY_J},
-/* 11 */    {MOD_SHIFT_LEFT, KEY_K},
-/* 12 */    {MOD_SHIFT_LEFT, KEY_L},
-/* 13 */    {MOD_SHIFT_LEFT, KEY_M},
-/* 14 */    {MOD_SHIFT_LEFT, KEY_N},
-/* 15 */    {MOD_SHIFT_LEFT, KEY_O},
-/* 16 */    {MOD_SHIFT_LEFT, KEY_P},
-/* 17 */    {MOD_SHIFT_LEFT, KEY_Q},
-};
-
-static void buildReport(uchar key)
+static void buildReport(unsigned int key)
 {
-/* This (not so elegant) cast saves us 10 bytes of program memory */
-    *(int *)reportBuffer = pgm_read_word(keyReport[key]);
+	reportBuffer[0] = (key>>8) & 0xFF;
+	reportBuffer[1] = key & 0xFF;
 }
 
 uchar	usbFunctionSetup(uchar data[8])
@@ -232,7 +273,7 @@
     if((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS){    /* class request type */
         if(rq->bRequest == USBRQ_HID_GET_REPORT){  /* wValue: ReportType (highbyte), ReportID (lowbyte) */
             /* we only have one report type, so don't look at wValue */
-            buildReport(keyPressed());
+            buildReport(sw());
             return sizeof(reportBuffer);
         }else if(rq->bRequest == USBRQ_HID_GET_IDLE){
             usbMsgPtr = &idleRate;
@@ -250,25 +291,27 @@
 
 int	main(void)
 {
-uchar   key, lastKey = 0, keyDidChange = 0;
+unsigned int key, lastKey = 0;
+uchar   keyDidChange = 0;
 uchar   idleCounter = 0;
 
 	wdt_enable(WDTO_2S);
-    hardwareInit();
-	odDebugInit();
+	sw_ini();
+        hardwareInit();
+	//odDebugInit();
 	usbInit();
 	sei();
-    DBG1(0x00, 0, 0);
+        //DBG1(0x00, 0, 0);
 	for(;;){	/* main event loop */
-		wdt_reset();
-		usbPoll();
-        key = keyPressed();
-        if(lastKey != key){
+	  wdt_reset();
+	  usbPoll();
+          key = sw();
+          if(lastKey != key ){
             lastKey = key;
             keyDidChange = 1;
-        }
-        if(TIFR & (1<<TOV0)){   /* 22 ms timer */
-            TIFR = 1<<TOV0;
+          }
+          if(TIFR0 & (1<<TOV0)){   /* 22 ms timer */
+            TIFR0 = 1<<TOV0;
             if(idleRate != 0){
                 if(idleCounter > 4){
                     idleCounter -= 5;   /* 22 ms in units of 4 ms */
ーーー

ーーー
--- HIDKeys.2012-12-08/usbconfig.h	2013-01-16 22:58:30.000000000 +0900
+++ New-vusb/usbconfig.h	2018-05-06 13:31:10.544386859 +0900
@@ -130,7 +130,7 @@
 #define USB_CFG_DEVICE_VERSION  0x00, 0x01
 /* Version number of the device: Minor number first, then major number.
  */
-#define USB_CFG_VENDOR_NAME     'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
+#define USB_CFG_VENDOR_NAME     's', 'a', 'k', 'u', 'r', 'a', '5', '1'
 #define USB_CFG_VENDOR_NAME_LEN 8
 /* These two values define the vendor name returned by the USB device. The name
  * must be given as a list of characters under single quotes. The characters
@@ -140,13 +140,13 @@
  * obdev's free shared VID/PID pair. See the file USBID-License.txt for
  * details. 
  */
-#define USB_CFG_DEVICE_NAME     'H', 'I', 'D', 'K', 'e', 'y', 's'
-#define USB_CFG_DEVICE_NAME_LEN 7
+#define USB_CFG_DEVICE_NAME     'p', 'c', '1', '0', '1'
+#define USB_CFG_DEVICE_NAME_LEN 5
 /* Same as above for the device name. If you don't want a device name, undefine
  * the macros. See the file USBID-License.txt before you assign a name.
  */
-/*#define USB_CFG_SERIAL_NUMBER   'N', 'o', 'n', 'e' */
-/*#define USB_CFG_SERIAL_NUMBER_LEN   0 */
+#define USB_CFG_SERIAL_NUMBER   'N', 'o', '0', '1'
+#define USB_CFG_SERIAL_NUMBER_LEN   4
 /* Same as above for the serial number. If you don't want a serial number,
  * undefine the macros.
  * It may be useful to provide the serial number through other means than at
@@ -159,12 +159,12 @@
 /* See USB specification if you want to conform to an existing device class.
  */
 #define USB_CFG_INTERFACE_CLASS     0x03    /* HID class */
-#define USB_CFG_INTERFACE_SUBCLASS  0       /* no boot interface */
-#define USB_CFG_INTERFACE_PROTOCOL  0       /* no protocol */
+#define USB_CFG_INTERFACE_SUBCLASS  1       /* boot interface */
+#define USB_CFG_INTERFACE_PROTOCOL  1       /* Keyboard protocol */
 /* See USB specification if you want to conform to an existing device class or
  * protocol.
  */
-#define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH    35  /* total length of report descriptor */
+#define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH    39  /* total length of report descriptor */
 /* Define this to the length of the HID report descriptor, if you implement
  * an HID device. Otherwise don't define it or define it to 0.
  */
ーーー
2018-05-02  「2018-04-18-raspbian-stretchインストール/AIY Voice Kit」
日本語ja_JP.UTF-8にするとゴミ箱はいいけど、タスクバー右の負荷メータの文字が化けるので日本語フォントをインストールすること。

●AIY Voice Kitインストール (ダンボール箱キット基板SP-MICを使う)
新しいGoogleAsisstantインストール
2018-04-18-raspbian-stretch.img にインストール

(1)git clone https://github.com/google/aiyprojects-raspbian.git AIY-projects-python

(2)https://github.com/google/aiyprojects-raspbian/blob/voicekit/HACKING.md
  HACKING.mdの説明により,AIY-voice-hatのドライバインストールの概要使う。

(3)cd AIY-projects-python
(4)sudo nano /boot/config.txt
--
#dtparam=i2s=on

#dtparam=audio=on
dtoverlay=googlevoicehat-soundcard
---1コメント、1行追加

(5)nano ~/.bashrc
---
export PYTHONPATH="/home/pi/AIY-projects-python/src:$PYTHONPATH" 
---最後に追加

(6)pip3 install RPi.GPIO
(7)pip3 install numpy
(8)sudo scripts/install-alsa-config.sh
(9)sudo reboot
(10)cd ~/AIY-projects-python
(11)python3 checkpoints/check_audio.py
    音が大きいがそのままで、実行。すぐにリブートする。
(12)sudo reboot
(13)alsamixer
     でsnd_rpi_googlevoicehat_soundcardになっていることを確認する

https://developers.google.com/assistant/sdk/guides/library/python/embed/install-sample
から
(14)python3 -m pip install --upgrade pip setuptools wheel
(15)sudo apt install portaudio19-dev libffi-dev libssl-dev
(16)sudo python3 -m pip install --upgrade google-assistant-library
(17)sudo python3 -m pip install --upgrade google-assistant-sdk[samples]
(18)sudo python3 -m pip install --upgrade google-auth-oauthlib[tool]

(19) console cloud googleで登録した時ダウンロードした、 client_secret_xx...xxx.apps.googleusercontent.com.jsonを
  ホームディレクトリにコピーする。
   または、

(20)https://developers.google.com/assistant/sdk/guides/library/python/embed/register-device
     の手順でデバイスモデルを登録する

(21) ログインしてダッシュボードからスタートガイドのAPIをクリックする。左側のメニュー認証情報をクリックする。
 「OAuth 2.0 クライアント ID」 のデバイス登録されたIDをダウンロードする。

(22)google-oauthlib-tool --scope https://www.googleapis.com/auth/assistant-sdk-prototype --save --headless --client-secrets /home/pi/client_secret_xxxxx....xxxx.apps.googleusercontent.com.json
WEB URLコピーしてログイン、許可。文字列コピーペースト。

credentials saved: /home/pi/.config/google-oauthlib-tool/credentials.json
が表示される。
(23)client_secret_xxxxx....xxxx.apps.googleusercontent.com.jsonを/home/pi/assistant.jsonとしておピー。

(22)src/examples/voice/assistant_library_demo.py
  最初はWEBで確認する。”Ok Google", "Wether in newyork"とか言ってみる。

src/examples/voice/assistant_library_with_button_demo.pyのSW入力をATTiny85でI2C接続してドップラーレーダーセンサをつけ、
SWの代わりにする。回路はCQ トラ技2018−3月号の回路につけるものと同じもの。
VoiceHAT基盤のI2C端子からの接続。

ATTiny85は別RaspberryPIで書き込み。
まずは配線。
GPIO接続

ピン17,1:3.3V ーー> ATTINY85 pin8(VDD)
ピン19:MOSI(GPO10) ーー> ATTINY85 pin5(MOSI)
ピン21:MISO(GPIO9) ーー> ATTINY85 pin6(MISO)
ピン23:CLK(GPIO11) ーー> ATTINY85 pin7(CLK)
ATTINY85 pin8(VDD) --[10 kΩ]-- ATTINY85 pin1(RESET) pull up
ピン37:GPIO26 ーー> ATTINY85 pin1(RESET)
ピン6,39:GND ーー> ATTINY85 pin4(GND)

ヒューズビットが外付けXtal,セラミック発振子の場合はつけること。

インストール
sudo apt-get install gcc-avr avr-libc binutils-avr avrdude

sudo nano /etc/avrdude.conf
----修正-----
programmer
  id    = "linuxgpio";
  desc  = "Use the Linux sysfs interface to bitbang GPIO lines";
  type  = "linuxgpio";
  reset = 26;
  sck   = 11;
  mosi  = 10;
  miso  = 9;
;

https://yetanotherhackersblog.wordpress.com/2011/04/12/interfacing-the-beagleboard-with-an-attiny85-microcontroller-over-i2c/
Yet Another Hacker's Blog - Interfacing the BeagleBoard with an ATtiny85 Microcontroller over I2C
にあったリンクのソース ↓
https://storage.googleapis.com/google-code-archive-source/v2/code.google.com/usi-i2c-slave/source-archive.zip
をもらってきて、修正。
-----i2ctest.c -------
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay_basic.h>
#include "usiTwiSlave.h"
#include <avr/cpufunc.h>

#define I2C_SLAVE_ADDR  0x26
#define PIEZO PB1
#define IN_NEAR PB3
#define IN_FAR PB4


// Somewhere to store the values the master writes to i2c register.
static volatile uint8_t i2cReg = 0;
static volatile uint8_t sns_near = 0;
static volatile uint8_t sns_far = 0;
static volatile uint8_t sns_on = 0;
static volatile uint8_t pinb = 0;
static volatile uint8_t sec_tm = 0;
static volatile uint8_t sns_tm = 0;

void set_freq(uint8_t f)
{
	TCCR0A &= 0xEF;		// Stop OC0B
	if (f < 3 ) {
		OCR0A = 2;
		OCR0B = 1;
	} else {
		OCR0A = f - 1;
		OCR0B = f - 2;
	}
	TCCR0A |= 0x10;		// out OC0B
}
// A callback triggered when the i2c master attempts to write to a register.
void i2cWriteToRegister(uint8_t value)
{
unsigned long n;

	if( value < 1 ) value = 1;
	if( value > 50 ) value = 50;
	n = 2000000;
	n = n / (value * 100) / 128;
	i2cReg = value;
	set_freq((unsigned char)n);
	sec_tm = 2;
}

ISR(PCINT0_vect)
{
	uint8_t r, ii;

	if( sns_tm == 0 ) {
		sns_near = 0;
		sns_far = 0;
	}
	r = PINB;
	r &= ( (1 << IN_NEAR)|(1 << IN_FAR) );

	ii = r ^ pinb;
	pinb = r;
	if( ii & (1<<IN_NEAR) ) {
		if ( r & (1<<IN_NEAR) ) {
			if ( sns_near < 8 ) {
				sns_near++;
				//i2cWriteToRegister(8);
			}
		}
	}

	if( ii & (1<<IN_FAR) ) {
		if ( r & (1<<IN_FAR) ) {
			if ( sns_far < 8 ) {
				sns_far++;
				//i2cWriteToRegister(15);
			}
		}
	}
	if (sns_near > sns_far) {
		r = sns_near - sns_far;
	} else {
		r = sns_far - sns_near;
	}
	if ( r > 1 )	{
		sns_near = sns_far = 0;
		//i2cWriteToRegister(3);
	}
	if ( sns_near > 3 && sns_far > 3 ) {
		if ( sns_on == 0 ) {
			sns_on = 1;
			set_freq(12);
			sec_tm = 3;
		}
		sns_near = sns_far = 0;
	}
	sns_tm = 6;
}
ISR(TIM1_OVF_vect)
{
	if( sec_tm > 0 ) {
		sec_tm--;	
		if( sec_tm == 0 ) {
			TCCR0A &= 0xEF;
			PORTB &= ~(1 << PIEZO);
		}
	}
	if( sns_tm > 0 ) {
		sns_tm--;
	}
}
// A callback triggered when the i2c master attempts to read from a register.
uint8_t i2cReadFromRegister(void)
{
	uint8_t r;
	r = pinb;
	if(sns_on != 0 ) {
		r |= 0x80;
		set_freq(19);
		sec_tm = 3;
		sns_on = 0;
	}
	return r;
}

void init_int(void)
{
	PCMSK = 0x18;  // PINB3,PINB4 interrupt
	GIMSK |= 0x20; 	// Accept PINB interrupt

	// Timer0
	TCCR0A = 0x00;
	TCCR0A = 0x02;	// OC0B out OCR0A CTC
	TCCR0B = 0x00;    
	TCCR0B = 0x03;  // 2 Mhz / (64 [TCCR0B.CS0] * n[OCR0A] ) = 7812-61Hz
	OCR0A = 250;

	// Timer1
	TCCR1 = 0xcc;	// CK / 2048  -- OCR1C on zero cntr
	OCR1C = 100;	// 2Mhz / 2048 / 100 = 100ms 
	TIMSK |= 0x04;
	
	pinb = PINB & ( (1 << IN_NEAR)|(1 << IN_FAR) );
}
int main()
{
	CLKPR = 0x80;
	CLKPR = 0x02;  // 8Mhz/4 =2000000hz

	// Set the LED pin as output.
	DDRB |= (1 << PIEZO);
	PORTB = (1 << PIEZO) ^ 0x3F; // in pull up
	init_int();
	usiTwiSlaveInit(I2C_SLAVE_ADDR, i2cReadFromRegister, i2cWriteToRegister);
	sei();

	while (1)
	{
		_NOP();
	}
}
----

変更部分

$ diff usiTwiSlave.c ../OLD/usiTwiSlave.c
253,254c253,254
< static uint8_t	(*_onI2CReadFromRegister)(void);
< static void    	(*_onI2CWriteToRegister)(uint8_t value);
---
> static uint8_t	(*_onI2CReadFromRegister)(uint8_t reg);
> static void    	(*_onI2CWriteToRegister)(uint8_t reg, uint8_t value);
258c258
< //static volatile uint8_t 		currentRegister = NO_CURRENT_REGISTER_SET;
---
> static volatile uint8_t 		currentRegister = NO_CURRENT_REGISTER_SET;
273,274c273,274
<   	uint8_t	(*onI2CReadFromRegister)(void),
< 	void (*onI2CWriteToRegister)(uint8_t value)
---
>   	uint8_t	(*onI2CReadFromRegister)(uint8_t reg),
> 	void (*onI2CWriteToRegister)(uint8_t reg, uint8_t value)
365c365
<     //currentRegister = NO_CURRENT_REGISTER_SET;
---
>     currentRegister = NO_CURRENT_REGISTER_SET;
449,450c449,450
< 	  USIDR = _onI2CReadFromRegister();
<       //currentRegister = NO_CURRENT_REGISTER_SET;
---
> 	  USIDR = _onI2CReadFromRegister(currentRegister);
>       currentRegister = NO_CURRENT_REGISTER_SET;
475,481c475,481
< 	  //if (currentRegister == NO_CURRENT_REGISTER_SET)
< 	  //{
< 	  //	// Store the value as the current register.
< 	  //	currentRegister = USIDR;
< 	  //}
< 	  //e/lse
< 	  //{
---
> 	  if (currentRegister == NO_CURRENT_REGISTER_SET)
> 	  {
> 	  	// Store the value as the current register.
> 	  	currentRegister = USIDR;
> 	  }
> 	  else
> 	  {
483c483
< 	  	_onI2CWriteToRegister(USIDR);
---
> 	  	_onI2CWriteToRegister(currentRegister, USIDR);
487,488c487,488
< 		//currentRegister = NO_CURRENT_REGISTER_SET;
< 	  //}
---
> 		currentRegister = NO_CURRENT_REGISTER_SET;
> 	  }
----

$ diff usiTwiSlave.h ../OLD/usiTwiSlave.h
46,47c46,47
< 	uint8_t	(*onI2CReadFromRegister)(void),
< 	void (*onI2CWriteToRegister)(uint8_t value)
---
> 	uint8_t	(*onI2CReadFromRegister)(uint8_t reg),
> 	void (*onI2CWriteToRegister)(uint8_t reg, uint8_t value)
-----
コンパイル
avr-gcc i2ctest.c usiTwiSlave.c -o hand -Wall -Os -std=gnu99 -mmcu=attiny85 -I.
avr-objcopy -O ihex hand hand.hex
プログラム書き込み
sudo avrdude -p t85 -P linuxgpio -c linuxgpio -v -U flash:w:hand.hex
ヒューズビット書き込み
sudo avrdude  -p t85 -c linuxgpio -P linuxgpio -v -U lfuse:w:0x72:m -U hfuse:w:0xDF:m -U efuse:w:0xFF:m
ATTiny85を試す。
i2cdetect -y 1
0x26 があること

i2cget -y 1 0x26
0x18 となっていること。
i2cset -y 1 0x26 8
おおよそ800Hzの音がピエゾから出る。
i2cset -y 1 0x26 1〜50  # 100Hz〜5000Hz


AIYの光るボタンの代わりに手のひらをパタパタ4回でSWを押したことにするクラスライブラリ。importして使う。

----- src/examples/voice/MyButton.py--------
# -*- coding: utf-8 -*-

from threading import Thread
import time
import smbus

_I2C_DEVICE_ID = 0x26

class MyButton(Thread):
	"""
	Using:
		from MyButton import MyButton

		th1 = MyButton(callback)
		try:
		    	th1.start()
		    	th1.join()
		except   KeyboardInterrupt:
		    	th1.ctrl_exit()
	"""
	def __init__(self, callback):
		''' Constructor. '''
		Thread.__init__(self)
		self.id = _I2C_DEVICE_ID
		self.callback = callback
		try:
			self.bus = smbus.SMBus(1)
			self.alivef = True
		except:
			self.bus = None
			self.alivef = False


	def __del__(self):	pass

	def request_reading(self):
		try:
			reading = int(self.bus.read_byte(self.id))
			if (reading & 0x42) == 0 and reading & 0x80:
				return 1
			else:
				return 0
		except:
			return 0

	def run(self):
		s = self.request_reading() # reset On
		while self.alivef:
			s = self.request_reading()
			if s == 1 and self.callback:
				self.callback()
			time.sleep(0.25)

	def buzzer(self, n):
		self.bus.write_byte(self.id, n)

	def ctrl_exit(self):
		self.alivef = False
		self.callback = None
------

デモプログラムassistant_library_with_button_demo.pyを以下のように修正する。

--- diff src/examples/voice/assistant_library_with_button_demo.py -- start ------------------------------------------
--- src/examples/voice/assistant_library_with_button_demo.py	2018-04-30 14:52:33.078016768 +0900
+++ src/examples/voice/assistant_library_with_button_demo-new.py	2018-05-02 01:19:09.190669262 +0900
@@ -30,6 +30,7 @@
 from aiy.assistant.library import Assistant
 import aiy.voicehat
 from google.assistant.library.event import EventType
+from MyButton import MyButton
 
 logging.basicConfig(
     level=logging.INFO,
@@ -50,6 +51,7 @@
         self._task = threading.Thread(target=self._run_task)
         self._can_start_conversation = False
         self._assistant = None
+        self._dev_mybutton = MyButton(self._on_button_pressed)
 
     def start(self):
         """Starts the assistant.
@@ -71,12 +73,14 @@
             status_ui.status('ready')
             self._can_start_conversation = True
             # Start the voicehat button trigger.
-            aiy.voicehat.get_button().on_press(self._on_button_pressed)
+            # aiy.voicehat.get_button().on_press(self._on_button_pressed)
+            self._dev_mybutton.start()
             if sys.stdout.isatty():
                 print('Say "OK, Google" or press the button, then speak. '
                       'Press Ctrl+C to quit...')
 
         elif event.type == EventType.ON_CONVERSATION_TURN_STARTED:
+            self._dev_mybutton.buzzer(14)
             self._can_start_conversation = False
             status_ui.status('listening')
 
@@ -102,11 +106,17 @@
 
 
 def main():
+    import RPi.GPIO as GPIO
+
     if platform.machine() == 'armv6l':
         print('Cannot run hotword demo on Pi Zero!')
         exit(-1)
-    MyAssistant().start()
-
+    try:
+        MyAssistant().start()
+    except  KeyboardInterrupt:
+      MyAssistant()._dev_mybutton.ctrl_exit()
+      GPIO.cleanup()
+      sys.exit(1)
 
 if __name__ == '__main__':
     main()
-------- diff end -----------------
・・・

HDDでブートは
$ sudo nano /boot/config.txt
---
program_usb_boot_mode=1
---追加
$ sudo reboot

$ vcgencmd otp_dumpで"17:3020000a"確認をする。
でできるようになる。
2018-04-01  「音声認識 python3 Speechrecognition Module/AIY Project」
参照:
https://github.com/Uberi/speech_recognition/blob/master/reference/library-reference.rst
マニュアル
https://github.com/Uberi/speech_recognition
説明

sudo apt-get install libportaudio-dev
sudo apt-get install libportaudiocpp0 portaudio19-dev libjack-jackd2-dev
sudo apt-get install python-pyaudio python3-pyaudio
sudo apt-get install flac
sudo pip3 install SpeechRecognition

認識プログラムを起動するとbluealsaのエラーが出るので、
sudo apt-get remove bluealsa
サウンドカードのエラーもたくさん出るので以下の行をコメントにする。
sudo nano /usr/share/alsa/alsa.conf
---
#pcm.front cards.pcm.front
#pcm.rear cards.pcm.rear
#pcm.center_lfe cards.pcm.center_lfe
#pcm.side cards.pcm.side
#pcm.surround21 cards.pcm.surround21
#pcm.surround40 cards.pcm.surround40
#pcm.surround41 cards.pcm.surround41
#pcm.surround50 cards.pcm.surround50
--上記をコメントにする

jack server connectエラーが出るので、認識前に以下のコマンド実行
jack_control start
このエラーがあっても認識結果は表示される。

python3 speech.py

---speech.py-------
#!/usr/bin/env python3
# Requires PyAudio and PySpeech.
 
import speech_recognition as sr
 
# Record Audio
r = sr.Recognizer()
with sr.Microphone(device_index = 2,sample_rate = 48000) as source:
	    print("Say something!")
	    audio = r.listen(source,timeout=1,phrase_time_limit=4)
 
# Speech recognition using Google Speech Recognition
try:
    # for testing purposes, we're just using the default API key
    # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
    # instead of `r.recognize_google(audio)`
    print("You said: " + r.recognize_google(audio))
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))
------- end ----

MIcrophone(device_index = 2,sample_rate = 48000)
device_index, sample_rateがあるとちょっと認識がよくなるような気がする。
 r.listen(source,timeout=1,phrase_time_limit=4)
USB micの感度、ノイズ等により、終わりがないとかのとき入れてみるとよい。

"light"と"right"は難しい!

=======================================
AIY-kit (aiyprojects-2017-09-11.img)
ハードウェアはAIY ダンボール箱キット
[AIY]
使っていたUSBマイクがノイズが多いので認識が良くなかった。
AIY ダンボール箱キットのマイクはノイズが少ないのでやってみた。
参考URLにあるように添付MagPiどおりにやるとユーザ登録でお金がかかる。
assistant SDKだけだと音声認識と回答の声が使える。
GPIOを制御するにはユーザ登録でお金かかる場合があるので面倒。
認識としゃべるのは音声合成ソフトにすればよい。
GPIOの制御は通常のPythonプログラムでいい。

参考:
https://kureuetan.com/category/web/iot/
モノのインターネット ブログ

$ sudo apt-get install libportaudio-dev
$ sudo apt-get install libportaudiocpp0 portaudio19-dev libjack-jackd2-dev
$ sudo apt-get install python-pyaudio python3-pyaudio
$ sudo apt-get install flac
$ sudo pip3 install SpeechRecognition

Pyaudioのバージョンが古いので
$ git clone http://people.csail.mit.edu/hubert/git/pyaudio.git
$ cd pyaudio
$ sudo python3 setup.py install

$ sudo apt-get install jackd2
$ jack_control start
$ nano speech.py
--- speech.py ---
#!/usr/bin/env python3
# Requires PyAudio and PySpeech.
 
import speech_recognition as sr
 
# Record Audio
r = sr.Recognizer()
with sr.Microphone() as source:
	    print("Say something!")
	    audio = r.listen(source)
 
# Speech recognition using Google Speech Recognition
try:
    # for testing purposes, we're just using the default API key
    # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
    # instead of `r.recognize_google(audio)`
    print("You said: " + r.recognize_google(audio))
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))
---
$ python3 speech.py

 soundドライバーのエラーがいっぱい出るがそのまま話す。

注)~/assistant.json, ... *.jsonファイルは取っておくこと。インストールし直したあとでコピーして使えるから。
   ファイル名はそのままで取っておくこと。
=======================================
ハードウェアはAIY Project段ボール箱キットを使い、通常の2018-01-13(stretch)版イメージにAiy project音声認識プログラム動作環境をインストール
AIY HAT, AIY Microphone, Raspberry pi 3B

rasbianは前もって
piパスワード設定、ロケール、タイムゾーン、Wifi国別、キーボードマップ、ホスト名、SSHサーバ有効 設定すること。
Wifi接続であれば設定する。

参照:https://github.com/google/aiyprojects-raspbian
google assistant SDK バージョンアップの説明URL
参照:http://itpro.nikkeibp.co.jp/atcl/mag/14/236760/122200040/
参照:https://developers.google.com/assistant/sdk/guides/library/python/embed/setup
....
$ cd ~
$ git clone https://github.com/google/aiyprojects-raspbian.git AIY-projects-python

https://github.com/google/aiyprojects-raspbian/blob/voicekit/HACKING.md
HACKING.mdの説明によりインストール

$ cd AIY-projects-python
$ sudo scripts/install-deps.sh
$ sudo scripts/install-services.sh
$ sudo scripts/configure-driver.sh

~/.asoudrcがないことを確認。

$ sudo reboot
$ cd AIY-projects-python
$ sudo scripts/install-alsa-config.sh
$ python3 checkpoints/check_audio.py

XXXX SundVoiceHATが上記の手順で接続できない