Arduino cheat sheet: Difference between revisions

From misc notes
Jump to navigation Jump to search
(ページの作成:「*without Arduino IDE [https://github.com/scottdarch/Arturo Arturo] /etc/ano.ini or ~/.anorc <pre> [build] board-model = uno arduino-dist = /cygdrive/C/Program Files (x8...」)
 
 
(279 intermediate revisions by the same user not shown)
Line 1: Line 1:
*without Arduino IDE
=Arduino + cygwin + ino (ano) ハマりどころメモ=
==Without Arduino IDE==
:arduino sketch を cygwin 環境内で build, upload したい。
 
===arduino.cc の情報===
[http://playground.arduino.cc/Learning/CommandLine Arduino from the Command Line]
:によると
  [https://github.com/scottdarch/Arturo Arturo]
  [https://github.com/scottdarch/Arturo Arturo]
:Arturo (a.k.a ano) というのがある。(ググったら ino というのがみつかるが、これがメンテされてないので ino のメンテナンス引き継ぎ版が ano のようだ)
:しかし cygwin で Windows 版 Arduino IDE (指定の 1.6.1)のコンパイラーや avrdude を起動したばあい、(cygwin からは正しく見えるのに)パスの問題があるようだ。さっくり cygwin 環境で AVR toolchain を作ることにする。
:VirtualBox いれて Linux 動かすという手もあるが、それをいっちゃぁ cygwin がかわいそう ;)


/etc/ano.ini or ~/.anorc
*ano build のエラー
<pre>
<pre>
fatal error: Arduino.h: No such file or directory
#include <Arduino.h>
</pre>
*ano upload のエラー
<pre>
avrdude: can't open config file "/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf": No such file or directory
avrdude: error reading system wide configuration file "/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf"
</pre>
==cygwin 環境で AVR toolchain をビルド==
===cygwin 準備===
[https://cygwin.com/install.html Installing and Updating Cygwin for 32-bit versions of Windows]
:32bit バージョンをインストールする。(64bit バージョンは AVR toolchain のコンパイルに不具合あり)
:cygwin のパッケージは以下のものを入れる。
<pre>
git
wget
unzip
zip
gperf
bison
flex
make
patch
autoconf
gcc-g++
libncurses-devel
python-setuptools
pkg-config
libtool
</pre>
===libusb問題===
:cygwin のパッケージで libusb をインストールしている場合は avrdude の build で不具合があるので、あれば削除しておく。(もし必要なら avrdude の build で static link をやめる逃げ道はある)
===FTDI USB serial driver (メモ書き)===
:arduino のパッケージには FTDI 社のドライバが梱包されてる
[http://www.ftdichip.com/Drivers/VCP.htm http://www.ftdichip.com/Drivers/VCP.htm]
:Arduino Unoは Microsoft 純正のドライバで認識する。(Windows 10)
===arduino IDE 配置===
:先ほど arduino.cc の記述によると ano は arduino IDE versions 1.6.1 は動くとのこと。
[https://www.arduino.cc/en/Main/OldSoftwareReleases#previous Arduino 1.6.x, 1.5.x BETA]
[http://arduino.cc/download.php?f=/arduino-1.6.1-windows.exe arduino-1.6.1-windows.exe]
:をとってきてインストールする。
:Windows 版の IDE は最新をつかいたいので、version 1.6.1 は /Program Files/Arduino を /cygwin/usr/share 配下にコピーする。
:名前は Arduino から arduino に変える。(たんなる趣味)
:Windows の権限管理の問題があるので arduino フォルダーのプロパティを開き、セキュリティ タブで *適切な設定* にしておく。
:Windows 版 IDE を最新したいなら、1.6.1 を uninstall して、再度最新版をインストールする。
===AVR toolchain 配置===
[https://github.com/arduino/toolchain-avr  The AVR toolchain used by the Arduino IDE]
:arduino IDE 1.6.1 の場合は AVR toolchain release 3.4.5 である。tag を指定して git clone する。
<syntaxhighlight lang="bash">
git clone --depth=1 --branch 3.4.5 --single-branch https://github.com/arduino/toolchain-avr.git
</syntaxhighlight>
:Readme.md にあるように texinfo の指定バージョン 4.13 は cygwin にないので、自分でコンパイルして配置する。
:ついでに automake-1.11.1 も cygwin のパッケージつかわないで自分でコンパイルして配置する。
[http://ftp.gnu.org/gnu/texinfo/texinfo-4.13.tar.gz texinfo-4.13.tar.gz]
[http://ftp.gnu.org/gnu/automake/automake-1.11.1.tar.bz2 automake-1.11.1.tar.bz2]
:arch.win32.build.bash はつかわない。なので MinGW 環境は不要。
:sourceforge の ごたごたで URL がかわってしまってソースが取れない。 build がコケるので事前にとって配置しておく。
<syntaxhighlight lang="bash">
wget http://distribute.atmel.no/tools/opensource/Atmel-AVR-GNU-Toolchain/3.4.5/avr8-headers-6.2.0.469.zip
wget http://download.savannah.gnu.org/releases/avr-libc/avr-libc-1.8.0.tar.bz2
wget http://download.savannah.gnu.org/releases/avrdude/avrdude-6.0.1.tar.gz
wget http://mirror.switch.ch/ftp/mirror/gnu/autoconf/autoconf-2.64.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/automake/automake-1.11.1.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/binutils/binutils-2.24.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/gcc/gcc-4.8.1/gcc-4.8.1.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/gdb/gdb-7.8.tar.xz
wget http://mirror.switch.ch/ftp/mirror/gnu/gmp/gmp-5.0.2.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/mpfr/mpfr-3.0.0.tar.bz2
wget http://download.sourceforge.net/project/libusb-win32/libusb-win32-releases/1.2.6.0/libusb-win32-bin-1.2.6.0.zip
wget http://download.sourceforge.net/project/libusb/libusb-1.0/libusb-1.0.18/libusb-1.0.18.tar.bz2
wget http://download.sourceforge.net/project/libusb/libusb-compat-0.1/libusb-compat-0.1.5/libusb-compat-0.1.5.tar.bz2
wget http://www.multiprecision.org/mpc/download/mpc-0.9.tar.gz
</syntaxhighlight>
<syntaxhighlight lang="bash">
bash build.all.bash
</syntaxhighlight>
:数時間コンパイルにかかる。
===なぞなエラー ===
build.all.bash でなぜか以下のエラー。
<syntaxhighlight lang="text" enclose="div">
/bin/sh ../avrdude-6.0.1/ylwrap ../avrdude-6.0.1/lexer.l lex.yy.c lexer.c -- flex
      2 [main] bison 6908 fhandler_disk_file::fixup_mmap_after_fork: requested 0xFFEA0000 != 0x0 mem alloc base 0xFFEA0000, state 0x1000, size 20480, Win32 error 487
  18406 [main] bison 6908 C:\cygwin\bin\bison.exe: *** fatal error in forked process - recreate_mmaps_after_fork_failed
  19179 [main] bison 6908 cygwin_exception::open_stackdumpfile: Dumping stack trace to bison.exe.stackdump
      1 [main] bison 960 fork: child -1 - forked process 6908 died unexpectedly, retry 0, exit code 0x100, errno 11
bison: m4 サブプロセスが失敗しました: Resource temporarily unavailable
Makefile:1263: ターゲット 'config_gram.c' のレシピで失敗しました
make: *** [config_gram.c] エラー 1
</syntaxhighlight>
:ビルドのどこかでコケる。avr-gcc や avr libc 系は完了してる。avrdude か gdb かで。
:avrdude.build.bash とか単体でビルドなら出ない
:どうも cygwin 固有の問題らしい。locale が問題とのこと。
:.bashrc に
<syntaxhighlight lang="bash">
export LANG=ja_JP.SJIS
export LC_ALL=C
</syntaxhighlight>
:で解決。
:ちなみに cygwin terminal の locale ももちろん ja_JP.SJIS にしておく。
===配置===
:objdir を /usr/share/arduino/hardware/tools/ 配下にコピーし、tools ディレクトリの avr ディレクトリを avr.org にリネームして、objdir を avr にリネームする。
===avrdude.exe===
:avrdude の serial port の指定は(もし Windows で認識しているポートが 'COM5' なら) /dev/ttyS4 が動かず '\\.\com5' で動く。
:COM ポートを指定したい場合は、Windows で
デバイスマネージャ -> ポート (COM と LPT) -> Arduino Uno (COM?) -> プロパティ -> ポートの設定 -> 詳細設定 -> COM ポート番号
:で変える。
===giveio services===
:これが起動しない。32bit only とのこと。あと giveio はいろいろ評判わるそう。
:パラレルポートの場合に必要とのこと。なので今回は無視。
===libusb-win32 問題===
:cygwin でコンパイルした avrdude.exe がいろいろ win32 系の dll を見るのでうざい
===arduino usb serial の windows OS での初期化===
:arduino の usb を刺しただけでは cygwin から serial device (COM5) としてみえてなので、windows OS で認識させる。
[http://www.ueda.info.waseda.ac.jp/~yajima/eyebot/serial.html シリアルポートの使い方@windows]
<syntaxhighlight lang="bash">
#!/bin/sh
mode.com $1: BAUD=115200 PARITY=N DATA=8 STOP=1 to=off xon=off odsr=off octs=on dtr=off rts=on idsr=off
</syntaxhighlight>
:このスクリプト動かす。
===avrdude build メモメモ===
:もし、libusb-win32 をつかわないで build する場合は libusb-1.0.18 にパッチを当てる。
<syntaxhighlight lang="diff">
diff -urN libusb-1.0.18.orig/libusb/os/windows_usb.h libusb-1.0.18/libusb/os/windows_usb.h
--- libusb-1.0.18.orig/libusb/os/windows_usb.h  2014-01-09 08:55:51.000000000 +0900
+++ libusb-1.0.18/libusb/os/windows_usb.h      2015-08-27 12:55:34.000000000 +0900
@@ -46,7 +46,7 @@
#endif
#if defined(__CYGWIN__ )
-#define _stricmp stricmp
+#define _stricmp strcasecmp
// cygwin produces a warning unless these prototypes are defined
extern int _snprintf(char *buffer, size_t count, const char *format, ...);
extern char *_strdup(const char *strSource);
</syntaxhighlight>
:ややこしいので AVR toolchain を fork してパッチあてたので、これ使ってください
[https://github.com/nxhack/toolchain-avr/tree/cygwin_only avr toolchain cygwin only]
[https://github.com/arduino/toolchain-avr/compare/master...nxhack:cygwin_only masterとの差分]
<syntaxhighlight lang="bash">
git clone -b cygwin_only https://github.com/nxhack/toolchain-avr.git
cd toolchain-avr
./arch.cygwin.build.bash
</syntaxhighlight>
:(メモ) 要確認
[https://savannah.nongnu.org/bugs/index.php?40831 bug #40831: LUFA AVRISP-MKII fails with avrdude 6.0.1]
==Arturo (ano)==
===ano===
[https://github.com/scottdarch/Arturo Arturo]
===stty 周りのパッチをあてる。(かなり強引に)===
:fork してパッチあてたもの
[https://github.com/nxhack/Arturo/tree/cygwin_only fork scottdarch/Arturo (for cygwin only)]
[https://github.com/scottdarch/Arturo/compare/master...nxhack:cygwin_only masterとの差分]
<syntaxhighlight lang="bash">
git clone -b cygwin_only https://github.com/nxhack/Arturo.git
cd Arturo
make install
</syntaxhighlight>
===picocom===
[https://github.com/npat-efault/picocom picocom]
:picocom をインストール
===ano の環境===
:/etc/ano.ini or ~/.anorc
:'com-port' に Windows の COM ポートを指定する。
:ちなにみ cygwin の ttyS? は Windows の COM ポート番号からマイナス 1 の数字になる
<syntaxhighlight lang="ini">
[build]
[build]
board-model = uno
board-model = uno
arduino-dist = /cygdrive/C/Program Files (x86)/arduino-1.6.5-r3/
arduino-dist = /usr/share/arduino


[upload]
[upload]
board-model = uno
board-model = uno
arduino-dist = /cygdrive/C/Program Files (x86)/arduino-1.6.5-r3/
arduino-dist = /usr/share/arduino
serial-port = /dev/ttyS3
serial-port = /dev/ttyS4
com-port = '\\.\com5'


[serial]
[serial]
serial-port = /dev/ttyS3
serial-port = /dev/ttyS4
</pre>
</syntaxhighlight>
 
===ano の使い方===
:ino と同じなので、arduino ino build とかでググってください
 
==cygwin メモ==
===cygwin terminalのロケール===
:ja_JP.SJIS がよさげ。
:かつ .bashrc に
<syntaxhighlight lang="bash">
export LANG=ja_JP.SJIS
export LC_ALL=C
</syntaxhighlight>
:MS-DOS 的な SJIS の世界と Windows+cygwin の世界の落としどころかも。
:Windows システム自体は(NT Kernel内は) Unicode なので、整合性がおかしい場合があって、いろいろ文字化けはあるかも。(グループ名とか日本語になってるとイタイ)
 
<syntaxhighlight lang="bash">
alias ls='ls -hFG --color=tty'
alias ll='ls -alG'
</syntaxhighlight>
:group を非表示にする。
 
:(メモ) chcp.com
<syntaxhighlight lang="bash">
chcp.com 65001
chcp.com 932
</syntaxhighlight>
 
===cygwin terminalのショートカット===
Mouse -> (ON) Clicks place command line cursor
Mouse -> Right click action -> Paste
 
===apt-cyg===
[https://raw.githubusercontent.com/transcode-open/apt-cyg/master/apt-cyg apt-cyg]
 
===emacs===
:.emacs
 
<syntaxhighlight lang="lisp">
; Emacs 2x
(cond ((> emacs-major-version 19)
      (progn
        (set-language-environment "Japanese")
        (setq default-enable-multibyte-characters t)
        (setq auto-coding-functions nil)
        (set-default-coding-systems 'sjis )
        (set-buffer-file-coding-system 'sjis )
        (set-terminal-coding-system 'sjis )
        (setq default-buffer-file-coding-system 'sjis )
        (setq default-terminal-coding-system 'sjis )
        (set-keyboard-coding-system 'sjis)
        (set-clipboard-coding-system 'sjis)
        (setq inhibit-startup-message t)
        (setq initial-scratch-message nil)
        ;;(global-font-lock-mode nil)
        (require 'jka-compr)
        (auto-compression-mode 1)
)))
 
(setq dired-listing-switches "-alG")
 
;;
;; whitespace
;;
(require 'whitespace)
(setq whitespace-style '(face
                        trailing
                        tabs
                        empty
                        space-mark
                        tab-mark
                        ))
 
(setq whitespace-display-mappings
      '((tab-mark ?\t [?> ?\t] [?\\ ?\t])))
 
(global-whitespace-mode 1)
(set-face-foreground 'whitespace-tab "brown")
;(set-face-background 'whitespace-tab "DimGray")
 
;
(setq-default scroll-step 1)
(line-number-mode t)
(column-number-mode t)
(setq visible-bell t)
(setq-default truncate-lines nil)
(setq next-line-add-newlines nil)
(setq minibuffer-max-depth nil)
(setq initial-scratch-message nil)
(setq inhibit-startup-message t)
 
(setq-default c-basic-offset 2
              tab-width 4
              indent-tabs-mode nil)
 
;
(require 'cl)
(add-to-list 'load-path "~/.emacs.d/vendor/arduino-mode")
(setq auto-mode-alist (cons '("\\.\\(pde\\|ino\\)$" . arduino-mode) auto-mode-alist))
(autoload 'arduino-mode "arduino-mode" "Arduino editing mode." t)
</syntaxhighlight>
 
[https://github.com/bookest/arduino-mode Emacs major mode for editing Arduino sketches.]
 
= cygwin + Arduino-mk =
[https://github.com/sudar/Arduino-Makefile Arduino-Makefile]
上記の cygwin で作りなおした AVR toolchain であれば若干の修正で動く。
 
/usr/local/share/arduino/Common.mk:
<syntaxhighlight lang="diff" enclose="div">
83,87c83,87
< ifeq ($(CURRENT_OS),WINDOWS)
<    ifneq ($(shell echo $(ARDUINO_DIR) | egrep '^(/|[a-zA-Z]:\\)'),)
<        echo $(error On Windows, ARDUINO_DIR must be a relative path)
<    endif
< endif
---
> #ifeq ($(CURRENT_OS),WINDOWS)
> #    ifneq ($(shell echo $(ARDUINO_DIR) | egrep '^(/|[a-zA-Z]:\\)'),)
> #        echo $(error On Windows, ARDUINO_DIR must be a relative path)
> #    endif
> #endif
</syntaxhighlight>
:UNIX 流の path でOK
 
Makefile:
<syntaxhighlight lang="make" enclose="div">
ARDUINO_DIR = /usr/share/arduino
ARDMK_DIR = /usr/local/share/arduino
 
BOARD_TAG    = uno
 
MONITOR_PORT  = com1
MONITOR_CMD  = picocom
FORCE_MONITOR_PORT = /dev/ttyS0
 
include ${ARDMK_DIR}/Arduino.mk
</syntaxhighlight>
 
ano (ino) ではなく、こちらのほうが使い勝手が良いかも。
 
Arduino IDE 由来の AVR toolchain ではなく、本家 [http://distribute.atmel.no/tools/opensource/Atmel-AVR-GNU-Toolchain/3.5.0/ Atmel AVR 8-bit GNU Toolchain] を cygwin で build しても動くかもとおもったが、Arduino IDE に絡んでいることが発覚。Arduino.cc の AVR toolchain の 3.5.0 版でチャレンジ。
 
:Arduino.cc 版 AVR toolchain 3.5.0 ポーティング自体が、はまだ作業途中なので、動く状態だけど、様子見
[https://github.com/nxhack/toolchain-avr/tree/cygwin_only-3.5.0 avr toolchain 3.5.0 cygwin only]
[https://github.com/arduino/toolchain-avr/compare/trecinquezero...nxhack:cygwin_only-3.5.0 本家との差分]
 
<syntaxhighlight lang="bash">
git clone -b cygwin_only-3.5.0 https://github.com/nxhack/toolchain-avr.git
cd toolchain-avr
./arch.cygwin.build.bash
</syntaxhighlight>
 
= Develop =
(レガシープログラマーのリハビリ大作戦)
== Arduino 系の雑多なメモ ==
=== Library 作成 ===
[https://www.arduino.cc/en/Hacking/LibraryTutorial Writing a Library for Arduino]
[http://playground.arduino.cc/Code/Library How to write libraries for the Arduino?]
 
== AVR atmega328p 系の雑多なメモ ==
 
=== objdump ===
<syntaxhighlight lang="bash">
avr-objdump -S hoge.elf
</syntaxhighlight>
 
=== nm ===
<syntaxhighlight lang="bash">
avr-nm --size-sort -C hoge.elf
</syntaxhighlight>
 
=== HALT ===
AVR のニーモニックで HALT (Z80 や x86 でおなじみ) がみつからない。SLEEP てーのがそれかな?
[http://playground.arduino.cc/Learning/ArduinoSleepCode How to let your Arduino go to sleep and wake up on an external event.]
 
<syntaxhighlight lang="text" enclose="div">
SLEEP_MODE_IDLE
SLEEP_MODE_ADC
SLEEP_MODE_PWR_SAVE
SLEEP_MODE_EXT_STANDBY
SLEEP_MODE_STANDBY
SLEEP_MODE_PWR_DOWN
</syntaxhighlight>
 
==== sleep_mode() ====
[http://flogics.com/wp/diy/zigbee-temp/arduino-%E3%81%AE%E3%82%B9%E3%83%AA%E3%83%BC%E3%83%97%E3%81%A8%E3%80%81pin-change-%E5%89%B2%E8%BE%BC/ これ]によると、sleep_mode() は、
<syntaxhighlight lang="c" enclose="div">
sleep_enable();
sleep_cpu();
sleep_disable();
</syntaxhighlight>
を実行するらしい。(実際にアセンブリコードをみたらそのとおりだった)
 
==== avr/power.h ====
avr/power.h に 個別のマクロがある。([http://firewheel.m40.coreserver.jp/blog/archives/123 参照])
 
<syntaxhighlight lang="text" enclose="div">
power_adc_enable() (ADコンバータ使用時)
power_spi_enable()(SPI使用時)
power_usart0_enable() (シリアルコンソール使用時)
power_timer0_enable() (タイマー0使用時、delay()やmillis()も)
power_timer1_enable()(タイマー1使用時)
power_timer2_enable()(タイマー2使用時、tone()も)
power_twi_enable()(I2C使用時)
</syntaxhighlight>
もちろん、power_*_disable() もある。いったん power_all_disable() してから個別に設定も可。
 
==== Power Save いろいろ ====
これから試してみる...
<syntaxhighlight lang="c" enclose="div">
  set_sleep_mode (SLEEP_MODE_PWR_DOWN); 
 
  byte old_ADCSRA = ADCSRA;
  ADCSRA = 0; 
  sleep_mode();
  ADCSRA = old_ADCSRA;
</syntaxhighlight>
 
<syntaxhighlight lang="c" enclose="div">
  noInterrupts();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_bod_disable();
  interrupts();
  sleep_cpu();
  sleep_disable();
</syntaxhighlight>
 
avr/sleep.h のコメント読む...
<syntaxhighlight lang="c" enclose="div">
    #include <avr/sleep.h>
 
    ...
      set_sleep_mode(<mode>);
      sleep_mode();
</syntaxhighlight>
<syntaxhighlight lang="c" enclose="div">
    #include <avr/interrupt.h>
    #include <avr/sleep.h>
 
    ...
      set_sleep_mode(<mode>);
      cli();
      if (some_condition)
      {
        sleep_enable();
        sei();
        sleep_cpu();
        sleep_disable();
      }
      sei();
</syntaxhighlight>
<syntaxhighlight lang="c" enclose="div">
    #include <avr/interrupt.h>
    #include <avr/sleep.h>
 
    ...
      set_sleep_mode(<mode>);
      cli();
      if (some_condition)
      {
        sleep_enable();
        sleep_bod_disable();
        sei();
        sleep_cpu();
        sleep_disable();
      }
      sei();
</syntaxhighlight>
 
実測の結果:
<syntaxhighlight lang="c" enclose="div">
#include <avr/sleep.h>
#include <avr/power.h>
 
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
 
...
 
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  cbi(ADCSRA, ADEN);
  power_all_disable();
  //noInterrupts();
  sleep_enable();
  sleep_bod_disable();
  //interrupts();
  sleep_cpu();
  sleep_disable();
  power_all_enable();
  sbi(ADCSRA, ADEN);
</syntaxhighlight>
 
==== disable BOD ====
ブラウンアウト機能 要調査
uno.bootloader.extended_fuses=0x07
 
[http://jasper.sikken.nl/arduinobootloader/index.html Arduino Uno brown-out detection]
 
=== float の printf ===
Arduino UNO (atmega328p) は float と double の差はない。[https://www.arduino.cc/en/Reference/Double Double]
 
printf 系は float は使えない。'?' に変換される。(小一時間ハマった)
:avr-ld のオプションに -lprintf_flt -lm を追加したら動く。コードが大きくなるので、標準ではミニマム機能のみにしている。
avr libs の (stdlib.h) で代用できる。[http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga6c140bdd3b9bd740a1490137317caa44 dtostre, dtostrf]
 
:そもそも FPU の無いマイコンで浮動小数使うのはダメね。無理やり整数か、美しくするなら固定小数点で書き換える。
 
[https://ucexperiment.wordpress.com/2015/03/31/avr-gcc-fixed-point-vs-floating-point-comparison/ AVR GCC Fixed-Point vs. Floating Point Comparison | µC eXperiment]
[https://gcc.gnu.org/wiki/avr-gcc#Fixed-Point_Support avr-gcc - GCC Wiki]
[https://gcc.gnu.org/onlinedocs/gcc/Fixed-Point.html Fixed-Point - Using the GNU Compiler Collection (GCC)]
[http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1169.pdf ISO/IEC TR 18037:2006(E)]
:固定小数点 fixed point の情報すくないね。もともと FPU の無い マイコン系の拡張なのでネットでも情報出て無い。
:gcc の拡張は動くけど、g++ は未対応なので、arduino の場合は pure C では使えるが、いろいろ大変そう。
 
=== Tips ===
[http://embeddedgurus.com/stack-overflow/category/efficient-cc/ Efficient C/C++ « Stack Overflow]
:(富豪的プログラミングになれてしまてっていたので)マイコンのプログラムテクニックは新鮮。
:除算は工夫して少なく。できたら浮動小数は使わない。
:むかしむかし、HP-PA のコンパイラの出すコードに関心したように、RISC の場合は、あるていどコンパイラー任せにできるような(わかりやすい)コードを心がけるのも忘れないように。(むかしついでに... HP-PA の 浮動小数点プロセッサーが Intel 系のそれと精度がちがっていて数日ハマってたな)
 
==== 除算 ====
[http://embeddedgurus.com/stack-overflow/2009/06/division-of-integers-by-constants/ Division of integers by constants « Stack Overflow]
 
:Using the values generated by Jones, together with some of the values I have computed, here’s a summary of some common divisors for unsigned 16 bit integers.
<syntaxhighlight lang="c" enclose="div">
Divide by 3: (((uint32_t)A * (uint32_t)0xAAAB) >> 16) >> 1
Divide by 5: (((uint32_t)A * (uint32_t)0xCCCD) >> 16) >> 2
Divide by 6: (((uint32_t)A * (uint32_t)0xAAAB) >> 16) >> 2
Divide by 7: ((((uint32_t)A * (uint32_t)0x2493) >> 16) + A) >> 1) >> 2
Divide by 9: (((uint32_t)A * (uint32_t)0xE38F) >> 16) >> 3
Divide by 10: (((uint32_t)A * (uint32_t)0xCCCD) >> 16) >> 3
Divide by 11: (((uint32_t)A * (uint32_t)0xBA2F) >> 16) >> 3
Divide by 12: (((uint32_t)A * (uint32_t)0xAAAB) >> 16) >> 3
Divide by 13: (((uint32_t)A * (uint32_t)0x9D8A) >> 16) >> 3
Divide by 14: ((((uint32_t)A * (uint32_t)0x2493) >> 16) + A) >> 1) >> 3
Divide by 15: (((uint32_t)A * (uint32_t)0x8889) >> 16) >> 3
Divide by 30: (((uint32_t)A * (uint32_t)0x8889) >> 16) >> 4
Divide by 60: (((uint32_t)A * (uint32_t)0x8889) >> 16) >> 5
Divide by 100: (((((uint32_t)A * (uint32_t)0x47AF) >> 16U) + A) >> 1) >> 6
Divide by PI: ((((uint32_t)A * (uint32_t)0x45F3) >> 16) + A) >> 1) >> 1
Divide by √2: (((uint32_t)A * (uint32_t)0xB505) >> 16) >> 0
</syntaxhighlight>
 
==== modulus (%) ====
[http://embeddedgurus.com/stack-overflow/2011/02/efficient-c-tip-13-use-the-modulus-operator-with-caution/ Efficient C Tip #13 – use the modulus (%) operator with caution « Stack Overflow]
 
<syntaxhighlight lang="c" enclose="div">
void display_value(uint16_t value)
{
uint8_t    msd, nsd, lsd;
 
if (value > 999)
{
value = 999;
}
 
lsd = value % 10;
value /= 10;
nsd = value % 10;
value /= 10;
msd = value;
 
/* Now display the digits */
}
</syntaxhighlight>
 
<syntaxhighlight lang="c" enclose="div">
void display_value(uint16_t value)
{
uint8_t    msd, nsd, lsd;
 
if (value > 999U)
{
  value = 999U;
}
 
msd = value / 100U;
value -= msd * 100U;
 
nsd = value / 10U;
value -= nsd * 10U;
 
lsd = value;
 
/* Now display the digits */
}
</syntaxhighlight>
 
==== Fast loops ====
[http://embeddedgurus.com/stack-overflow/2009/03/efficient-c-tips-7-fast-loops/ Efficient C Tips #7 – Fast loops « Stack Overflow]
 
<syntaxhighlight lang="text" enclose="div">
So how does this efficiency arise? Well in the count up case, the assembly language generated by the compiler typically looks something like this:
 
INC lpc      ; Increment loop counter
SUB lpc, #10 ; Compare loop counter to 10
BNZ loop    ; Branch if loop counter not equal to 10
 
By contrast, in the count down case the assembly language looks something like this
 
DEC lpc  ; Decrement loop counter
BNZ loop  ; Branch if non zero
 
Evidently, because of the ‘specialness’ of zero, more efficient code can be generated.
</syntaxhighlight>
 
=== メモメモ===
[http://www.gammon.com.au/power Gammon Forum : Electronics : Microprocessors : Power saving techniques for microprocessors]
:sleep 系はここがまとまってる
 
[http://programresource.net/2015/04/23/2547.html ArduinoでDS3231 RTCモジュールを使った定期処理 | Program Resource]
:RTC の SQW 割り込みでうんぬん。これ系ですね。
 
= もろもろメモ =
 
== あとにつながるメモ ==
[https://xively.com/  xively (ザイブリー)]
[https://evrythng.com/ EVRYTHNG]
[https://thethings.io/ thethings.iO]
[https://m2x.att.com/ AT&T M2X]
[https://soracom.jp/ SORACOM ソラコム]
 
[https://influxdb.com/blog/2015/09/29/how_to_send_sensor_data_to_influxdb_from_an_arduino_uno.html How to send sensor data to InfluxDB from an Arduino Uno]
:Time series database にブチ込む
 
[https://www.pagerduty.com/blog/diy-arduino-integration-pagerduty-alerts/ DIY Arduino YUN Integration for PagerDuty Alerts]
:PagerDuty の Alert で動く
 
[https://www.twilio.com/blog/2012/08/diy-home-automation-using-twilio-powerswitch-arduino-and-pusher.html DIY Home Automation Using Twilio, PowerSwitch, Arduino, and Pusher]
:Twilio blog arduino ネタ多し
 
[http://www.seeedstudio.com/depot/s/grovefamily.html Find grovefamily - Buy grovefamily from Best grovefamily Distributors | Seeedstudio]
[http://www.seeedstudio.com/wiki/Grove_System Grove System - Wiki]
[https://github.com/Seeed-Studio/Suli Suli]
:Grove 自作とくれべたらちょっと高いけど、お気楽に遊べるな。なかなか良い感じ。
:Suli の考え方も興味深い。(ここはいろいろアプローチあるだろうなぁ)
 
[http://www.mikroe.com/flip-n-click/ MikroElektronika - Flip-n-click]
:これも似たようなコンセプトか。ソフトはどうだろう...
 
[http://meshprj.com/jp/ SH:遊び心を形にできる、アプリとつなげるブロック形状の電子タグ|ソニー]
:あぁ こういったアプローチもあるな。(でも hack する楽しさはあるのかぁ...)
 
=== RTOS ===
[http://www.freertos.org/ FreeRTOS]
 
=== 入門 ===
ここがいちばんいい感じ。昔を思い出しつつ...
[http://garretlab.web.fc2.com/index.html garretlab]
 
基本の7セグ
[http://www.thecoderscorner.com/electronics/microcontrollers/driving-displays/45-arduino-example-for-driving-7-segment-led-s Arduino 7 segment LED display tutorial]
:[http://garretlab.web.fc2.com/arduino_reference/language/structure/bitwise_operators/port_manipulation.html ポート・レジスタ]使わない形の一番シンプルなもの
 
=== AVR libc ===
[http://cega.jp/avr-libc-jp/ AVR Libc 日本語]
 
[http://www.akamoz.jp/you/junkbox/avr/avr-libc.htm AVR libcを使ってみる you/junkbox]
 
=== IoT するなら ===
いろいろ検討したが (様々なシールドやPC系GW) 、これでいいやん、そこそこ安いし、arduino 的手軽さもあるし... [https://www.arduino.cc/en/Main/ArduinoBoardYun Arduino Yún]
[http://mag.switch-science.com/2015/10/13/aws-iot-yun-detail/ AWS IoTをArduino Yúnで使う(少し詳しく書いてみた) | スイッチサイエンス マガジン]
[http://fight-tsk.blogspot.jp/2015/05/arduino-yunibm-iot-foundation-quickstart.html 腹腹開発: Arduino YUN上の温湿度センサデータをIBM IoT Foundation QuickStartへ送信する]
[http://recruit.gmo.jp/engineer/jisedai/blog/%E3%80%90%E9%9B%BB%E5%AD%90%E5%B7%A5%E4%BD%9C%E3%80%91arduino-yun%E3%82%92google-docs%E3%82%84twitter%E3%81%A8%E9%80%A3%E6%90%BA%E3%81%97%E3%81%A6%E3%81%BF%E3%81%9F/ 【電子工作】Arduino YúnをGoogle DocsやTwitterと連携してみた | GMOインターネット 次世代システム研究室]
[http://blog.parse.com/learn/using-parse-for-iot-to-create-an-order-button/ Using Parse for IoT to Create an Order Button]
[http://qiita.com/ToshiakiEnami/items/7b4b3090f3687979d21a awsIoT - 太陽光パネルの発電量をAWS IoTとAmazon Elasticsearch Serviceを使って可視化してみる]
 
[https://github.com/aws/aws-iot-device-sdk-arduino-yun/ SDK for connecting to AWS IoT from an Arduino Yún]
 
[https://openwrt.org/ OpenWrt]
 
[https://github.com/GeertJohan/openwrt-go  Fork of the openwrt project to add gccgo and libgo]
 
[http://data.andyburgin.co.uk/post/65526969877/experiment-2-how-to-secure-beaver Burgin's Data Thing | Experiment 2 - How to secure Beaver]
 
[http://ser2net.sourceforge.net/ Serial to Network Proxy (ser2net)]
 
[http://qiita.com/syoyo/items/d31e9db6851dfee3ef82 tunneling - Reverse ssh tunnel を安定運用する]
[http://mm011106.github.io/blog/2015/02/23/init-dot-d-script/ init.dスクリプトを書いてみる - MQTT and …]
 
== Arduino の歴史 ==
[http://arduinohistory.github.io/ja.html  Arduinoの語られざる歴史]
:こえーーー
 
[http://wiring.org.co/ Wiring]

Latest revision as of 15:09, 26 December 2018

Arduino + cygwin + ino (ano) ハマりどころメモ

Without Arduino IDE

arduino sketch を cygwin 環境内で build, upload したい。

arduino.cc の情報

Arduino from the Command Line
によると
Arturo
Arturo (a.k.a ano) というのがある。(ググったら ino というのがみつかるが、これがメンテされてないので ino のメンテナンス引き継ぎ版が ano のようだ)
しかし cygwin で Windows 版 Arduino IDE (指定の 1.6.1)のコンパイラーや avrdude を起動したばあい、(cygwin からは正しく見えるのに)パスの問題があるようだ。さっくり cygwin 環境で AVR toolchain を作ることにする。
VirtualBox いれて Linux 動かすという手もあるが、それをいっちゃぁ cygwin がかわいそう ;)
  • ano build のエラー
fatal error: Arduino.h: No such file or directory
 #include <Arduino.h>
  • ano upload のエラー
avrdude: can't open config file "/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf": No such file or directory
avrdude: error reading system wide configuration file "/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf"

cygwin 環境で AVR toolchain をビルド

cygwin 準備

Installing and Updating Cygwin for 32-bit versions of Windows
32bit バージョンをインストールする。(64bit バージョンは AVR toolchain のコンパイルに不具合あり)
cygwin のパッケージは以下のものを入れる。
git
wget
unzip
zip
gperf
bison
flex
make
patch
autoconf
gcc-g++
libncurses-devel
python-setuptools
pkg-config
libtool

libusb問題

cygwin のパッケージで libusb をインストールしている場合は avrdude の build で不具合があるので、あれば削除しておく。(もし必要なら avrdude の build で static link をやめる逃げ道はある)

FTDI USB serial driver (メモ書き)

arduino のパッケージには FTDI 社のドライバが梱包されてる
http://www.ftdichip.com/Drivers/VCP.htm
Arduino Unoは Microsoft 純正のドライバで認識する。(Windows 10)

arduino IDE 配置

先ほど arduino.cc の記述によると ano は arduino IDE versions 1.6.1 は動くとのこと。
Arduino 1.6.x, 1.5.x BETA
arduino-1.6.1-windows.exe
をとってきてインストールする。
Windows 版の IDE は最新をつかいたいので、version 1.6.1 は /Program Files/Arduino を /cygwin/usr/share 配下にコピーする。
名前は Arduino から arduino に変える。(たんなる趣味)
Windows の権限管理の問題があるので arduino フォルダーのプロパティを開き、セキュリティ タブで *適切な設定* にしておく。
Windows 版 IDE を最新したいなら、1.6.1 を uninstall して、再度最新版をインストールする。

AVR toolchain 配置

The AVR toolchain used by the Arduino IDE
arduino IDE 1.6.1 の場合は AVR toolchain release 3.4.5 である。tag を指定して git clone する。
git clone --depth=1 --branch 3.4.5 --single-branch https://github.com/arduino/toolchain-avr.git
Readme.md にあるように texinfo の指定バージョン 4.13 は cygwin にないので、自分でコンパイルして配置する。
ついでに automake-1.11.1 も cygwin のパッケージつかわないで自分でコンパイルして配置する。
texinfo-4.13.tar.gz
automake-1.11.1.tar.bz2
arch.win32.build.bash はつかわない。なので MinGW 環境は不要。
sourceforge の ごたごたで URL がかわってしまってソースが取れない。 build がコケるので事前にとって配置しておく。
wget http://distribute.atmel.no/tools/opensource/Atmel-AVR-GNU-Toolchain/3.4.5/avr8-headers-6.2.0.469.zip
wget http://download.savannah.gnu.org/releases/avr-libc/avr-libc-1.8.0.tar.bz2
wget http://download.savannah.gnu.org/releases/avrdude/avrdude-6.0.1.tar.gz
wget http://mirror.switch.ch/ftp/mirror/gnu/autoconf/autoconf-2.64.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/automake/automake-1.11.1.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/binutils/binutils-2.24.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/gcc/gcc-4.8.1/gcc-4.8.1.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/gdb/gdb-7.8.tar.xz
wget http://mirror.switch.ch/ftp/mirror/gnu/gmp/gmp-5.0.2.tar.bz2
wget http://mirror.switch.ch/ftp/mirror/gnu/mpfr/mpfr-3.0.0.tar.bz2
wget http://download.sourceforge.net/project/libusb-win32/libusb-win32-releases/1.2.6.0/libusb-win32-bin-1.2.6.0.zip
wget http://download.sourceforge.net/project/libusb/libusb-1.0/libusb-1.0.18/libusb-1.0.18.tar.bz2
wget http://download.sourceforge.net/project/libusb/libusb-compat-0.1/libusb-compat-0.1.5/libusb-compat-0.1.5.tar.bz2
wget http://www.multiprecision.org/mpc/download/mpc-0.9.tar.gz
bash build.all.bash
数時間コンパイルにかかる。

なぞなエラー

build.all.bash でなぜか以下のエラー。

/bin/sh ../avrdude-6.0.1/ylwrap ../avrdude-6.0.1/lexer.l lex.yy.c lexer.c -- flex
      2 [main] bison 6908 fhandler_disk_file::fixup_mmap_after_fork: requested 0xFFEA0000 != 0x0 mem alloc base 0xFFEA0000, state 0x1000, size 20480, Win32 error 487
  18406 [main] bison 6908 C:\cygwin\bin\bison.exe: *** fatal error in forked process - recreate_mmaps_after_fork_failed
  19179 [main] bison 6908 cygwin_exception::open_stackdumpfile: Dumping stack trace to bison.exe.stackdump
      1 [main] bison 960 fork: child -1 - forked process 6908 died unexpectedly, retry 0, exit code 0x100, errno 11
bison: m4 サブプロセスが失敗しました: Resource temporarily unavailable
Makefile:1263: ターゲット 'config_gram.c' のレシピで失敗しました
make: *** [config_gram.c] エラー 1
ビルドのどこかでコケる。avr-gcc や avr libc 系は完了してる。avrdude か gdb かで。
avrdude.build.bash とか単体でビルドなら出ない
どうも cygwin 固有の問題らしい。locale が問題とのこと。
.bashrc に
export LANG=ja_JP.SJIS
export LC_ALL=C
で解決。
ちなみに cygwin terminal の locale ももちろん ja_JP.SJIS にしておく。

配置

objdir を /usr/share/arduino/hardware/tools/ 配下にコピーし、tools ディレクトリの avr ディレクトリを avr.org にリネームして、objdir を avr にリネームする。

avrdude.exe

avrdude の serial port の指定は(もし Windows で認識しているポートが 'COM5' なら) /dev/ttyS4 が動かず '\\.\com5' で動く。
COM ポートを指定したい場合は、Windows で
デバイスマネージャ -> ポート (COM と LPT) -> Arduino Uno (COM?) -> プロパティ -> ポートの設定 -> 詳細設定 -> COM ポート番号
で変える。

giveio services

これが起動しない。32bit only とのこと。あと giveio はいろいろ評判わるそう。
パラレルポートの場合に必要とのこと。なので今回は無視。

libusb-win32 問題

cygwin でコンパイルした avrdude.exe がいろいろ win32 系の dll を見るのでうざい

arduino usb serial の windows OS での初期化

arduino の usb を刺しただけでは cygwin から serial device (COM5) としてみえてなので、windows OS で認識させる。
シリアルポートの使い方@windows
#!/bin/sh
mode.com $1: BAUD=115200 PARITY=N DATA=8 STOP=1 to=off xon=off odsr=off octs=on dtr=off rts=on idsr=off
このスクリプト動かす。

avrdude build メモメモ

もし、libusb-win32 をつかわないで build する場合は libusb-1.0.18 にパッチを当てる。
diff -urN libusb-1.0.18.orig/libusb/os/windows_usb.h libusb-1.0.18/libusb/os/windows_usb.h
--- libusb-1.0.18.orig/libusb/os/windows_usb.h  2014-01-09 08:55:51.000000000 +0900
+++ libusb-1.0.18/libusb/os/windows_usb.h       2015-08-27 12:55:34.000000000 +0900
@@ -46,7 +46,7 @@
 #endif
 
 #if defined(__CYGWIN__ )
-#define _stricmp stricmp
+#define _stricmp strcasecmp
 // cygwin produces a warning unless these prototypes are defined
 extern int _snprintf(char *buffer, size_t count, const char *format, ...);
 extern char *_strdup(const char *strSource);
ややこしいので AVR toolchain を fork してパッチあてたので、これ使ってください
avr toolchain cygwin only
masterとの差分
git clone -b cygwin_only https://github.com/nxhack/toolchain-avr.git
cd toolchain-avr
./arch.cygwin.build.bash
(メモ) 要確認
bug #40831: LUFA AVRISP-MKII fails with avrdude 6.0.1

Arturo (ano)

ano

Arturo

stty 周りのパッチをあてる。(かなり強引に)

fork してパッチあてたもの
fork scottdarch/Arturo (for cygwin only)
masterとの差分
git clone -b cygwin_only https://github.com/nxhack/Arturo.git
cd Arturo
make install

picocom

picocom
picocom をインストール

ano の環境

/etc/ano.ini or ~/.anorc
'com-port' に Windows の COM ポートを指定する。
ちなにみ cygwin の ttyS? は Windows の COM ポート番号からマイナス 1 の数字になる
[build]
board-model = uno
arduino-dist = /usr/share/arduino

[upload]
board-model = uno
arduino-dist = /usr/share/arduino
serial-port = /dev/ttyS4
com-port = '\\.\com5'

[serial]
serial-port = /dev/ttyS4

ano の使い方

ino と同じなので、arduino ino build とかでググってください

cygwin メモ

cygwin terminalのロケール

ja_JP.SJIS がよさげ。
かつ .bashrc に
export LANG=ja_JP.SJIS
export LC_ALL=C
MS-DOS 的な SJIS の世界と Windows+cygwin の世界の落としどころかも。
Windows システム自体は(NT Kernel内は) Unicode なので、整合性がおかしい場合があって、いろいろ文字化けはあるかも。(グループ名とか日本語になってるとイタイ)
alias ls='ls -hFG --color=tty'
alias ll='ls -alG'
group を非表示にする。
(メモ) chcp.com
chcp.com 65001
chcp.com 932

cygwin terminalのショートカット

Mouse -> (ON) Clicks place command line cursor
Mouse -> Right click action -> Paste

apt-cyg

apt-cyg

emacs

.emacs
; Emacs 2x
(cond ((> emacs-major-version 19)
       (progn
         (set-language-environment "Japanese")
         (setq default-enable-multibyte-characters t)
         (setq auto-coding-functions nil)
         (set-default-coding-systems 'sjis )
         (set-buffer-file-coding-system 'sjis )
         (set-terminal-coding-system 'sjis )
         (setq default-buffer-file-coding-system 'sjis )
         (setq default-terminal-coding-system 'sjis )
         (set-keyboard-coding-system 'sjis)
         (set-clipboard-coding-system 'sjis)
         (setq inhibit-startup-message t)
         (setq initial-scratch-message nil)
         ;;(global-font-lock-mode nil)
         (require 'jka-compr)
         (auto-compression-mode 1)
)))

(setq dired-listing-switches "-alG")

;;
;; whitespace
;;
(require 'whitespace)
(setq whitespace-style '(face
                         trailing
                         tabs
                         empty
                         space-mark
                         tab-mark
                         ))

(setq whitespace-display-mappings
      '((tab-mark ?\t [?> ?\t] [?\\ ?\t])))

(global-whitespace-mode 1)
(set-face-foreground 'whitespace-tab "brown")
;(set-face-background 'whitespace-tab "DimGray")

;
(setq-default scroll-step 1)
(line-number-mode t)
(column-number-mode t)
(setq visible-bell t)
(setq-default truncate-lines nil)
(setq next-line-add-newlines nil)
(setq minibuffer-max-depth nil)
(setq initial-scratch-message nil)
(setq inhibit-startup-message t)

(setq-default c-basic-offset 2
              tab-width 4
              indent-tabs-mode nil)

;
(require 'cl)
(add-to-list 'load-path "~/.emacs.d/vendor/arduino-mode")
(setq auto-mode-alist (cons '("\\.\\(pde\\|ino\\)$" . arduino-mode) auto-mode-alist))
(autoload 'arduino-mode "arduino-mode" "Arduino editing mode." t)
Emacs major mode for editing Arduino sketches.

cygwin + Arduino-mk

Arduino-Makefile

上記の cygwin で作りなおした AVR toolchain であれば若干の修正で動く。

/usr/local/share/arduino/Common.mk:

83,87c83,87
< ifeq ($(CURRENT_OS),WINDOWS)
<     ifneq ($(shell echo $(ARDUINO_DIR) | egrep '^(/|[a-zA-Z]:\\)'),)
<         echo $(error On Windows, ARDUINO_DIR must be a relative path)
<     endif
< endif
---
> #ifeq ($(CURRENT_OS),WINDOWS)
> #    ifneq ($(shell echo $(ARDUINO_DIR) | egrep '^(/|[a-zA-Z]:\\)'),)
> #        echo $(error On Windows, ARDUINO_DIR must be a relative path)
> #    endif
> #endif
UNIX 流の path でOK

Makefile:

ARDUINO_DIR = /usr/share/arduino
ARDMK_DIR = /usr/local/share/arduino

BOARD_TAG    = uno

MONITOR_PORT  = com1
MONITOR_CMD   = picocom
FORCE_MONITOR_PORT = /dev/ttyS0

include ${ARDMK_DIR}/Arduino.mk

ano (ino) ではなく、こちらのほうが使い勝手が良いかも。

Arduino IDE 由来の AVR toolchain ではなく、本家 Atmel AVR 8-bit GNU Toolchain を cygwin で build しても動くかもとおもったが、Arduino IDE に絡んでいることが発覚。Arduino.cc の AVR toolchain の 3.5.0 版でチャレンジ。

Arduino.cc 版 AVR toolchain 3.5.0 ポーティング自体が、はまだ作業途中なので、動く状態だけど、様子見
avr toolchain 3.5.0 cygwin only
本家との差分
git clone -b cygwin_only-3.5.0 https://github.com/nxhack/toolchain-avr.git
cd toolchain-avr
./arch.cygwin.build.bash

Develop

(レガシープログラマーのリハビリ大作戦)

Arduino 系の雑多なメモ

Library 作成

Writing a Library for Arduino
How to write libraries for the Arduino?

AVR atmega328p 系の雑多なメモ

objdump

avr-objdump -S hoge.elf

nm

avr-nm --size-sort -C hoge.elf

HALT

AVR のニーモニックで HALT (Z80 や x86 でおなじみ) がみつからない。SLEEP てーのがそれかな?

How to let your Arduino go to sleep and wake up on an external event.
SLEEP_MODE_IDLE
SLEEP_MODE_ADC
SLEEP_MODE_PWR_SAVE
SLEEP_MODE_EXT_STANDBY
SLEEP_MODE_STANDBY
SLEEP_MODE_PWR_DOWN

sleep_mode()

これによると、sleep_mode() は、

sleep_enable();
sleep_cpu();
sleep_disable();

を実行するらしい。(実際にアセンブリコードをみたらそのとおりだった)

avr/power.h

avr/power.h に 個別のマクロがある。(参照)

power_adc_enable() (ADコンバータ使用時)
power_spi_enable()(SPI使用時)
power_usart0_enable() (シリアルコンソール使用時)
power_timer0_enable() (タイマー0使用時、delay()やmillis()も)
power_timer1_enable()(タイマー1使用時)
power_timer2_enable()(タイマー2使用時、tone()も)
power_twi_enable()(I2C使用時)

もちろん、power_*_disable() もある。いったん power_all_disable() してから個別に設定も可。

Power Save いろいろ

これから試してみる...

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);  

  byte old_ADCSRA = ADCSRA;
  ADCSRA = 0;  
  sleep_mode();
  ADCSRA = old_ADCSRA;
  noInterrupts();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_bod_disable();
  interrupts();
  sleep_cpu();
  sleep_disable();

avr/sleep.h のコメント読む...

    #include <avr/sleep.h>

    ...
      set_sleep_mode(<mode>);
      sleep_mode();
    #include <avr/interrupt.h>
    #include <avr/sleep.h>

    ...
      set_sleep_mode(<mode>);
      cli();
      if (some_condition)
      {
        sleep_enable();
        sei();
        sleep_cpu();
        sleep_disable();
      }
      sei();
    #include <avr/interrupt.h>
    #include <avr/sleep.h>

    ...
      set_sleep_mode(<mode>);
      cli();
      if (some_condition)
      {
        sleep_enable();
        sleep_bod_disable();
        sei();
        sleep_cpu();
        sleep_disable();
      }
      sei();

実測の結果:

#include <avr/sleep.h>
#include <avr/power.h>

#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

 ...

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  cbi(ADCSRA, ADEN);
  power_all_disable();
  //noInterrupts(); 
  sleep_enable();
  sleep_bod_disable();
  //interrupts();
  sleep_cpu();
  sleep_disable();
  power_all_enable();
  sbi(ADCSRA, ADEN);

disable BOD

ブラウンアウト機能 要調査

uno.bootloader.extended_fuses=0x07
Arduino Uno brown-out detection

float の printf

Arduino UNO (atmega328p) は float と double の差はない。Double

printf 系は float は使えない。'?' に変換される。(小一時間ハマった)

avr-ld のオプションに -lprintf_flt -lm を追加したら動く。コードが大きくなるので、標準ではミニマム機能のみにしている。

avr libs の (stdlib.h) で代用できる。dtostre, dtostrf

そもそも FPU の無いマイコンで浮動小数使うのはダメね。無理やり整数か、美しくするなら固定小数点で書き換える。
AVR GCC Fixed-Point vs. Floating Point Comparison | µC eXperiment
avr-gcc - GCC Wiki
Fixed-Point - Using the GNU Compiler Collection (GCC)
ISO/IEC TR 18037:2006(E)
固定小数点 fixed point の情報すくないね。もともと FPU の無い マイコン系の拡張なのでネットでも情報出て無い。
gcc の拡張は動くけど、g++ は未対応なので、arduino の場合は pure C では使えるが、いろいろ大変そう。

Tips

Efficient C/C++ « Stack Overflow
(富豪的プログラミングになれてしまてっていたので)マイコンのプログラムテクニックは新鮮。
除算は工夫して少なく。できたら浮動小数は使わない。
むかしむかし、HP-PA のコンパイラの出すコードに関心したように、RISC の場合は、あるていどコンパイラー任せにできるような(わかりやすい)コードを心がけるのも忘れないように。(むかしついでに... HP-PA の 浮動小数点プロセッサーが Intel 系のそれと精度がちがっていて数日ハマってたな)

除算

Division of integers by constants « Stack Overflow
Using the values generated by Jones, together with some of the values I have computed, here’s a summary of some common divisors for unsigned 16 bit integers.
Divide by 3: (((uint32_t)A * (uint32_t)0xAAAB) >> 16) >> 1
Divide by 5: (((uint32_t)A * (uint32_t)0xCCCD) >> 16) >> 2
Divide by 6: (((uint32_t)A * (uint32_t)0xAAAB) >> 16) >> 2
Divide by 7: ((((uint32_t)A * (uint32_t)0x2493) >> 16) + A) >> 1) >> 2
Divide by 9: (((uint32_t)A * (uint32_t)0xE38F) >> 16) >> 3
Divide by 10: (((uint32_t)A * (uint32_t)0xCCCD) >> 16) >> 3
Divide by 11: (((uint32_t)A * (uint32_t)0xBA2F) >> 16) >> 3
Divide by 12: (((uint32_t)A * (uint32_t)0xAAAB) >> 16) >> 3
Divide by 13: (((uint32_t)A * (uint32_t)0x9D8A) >> 16) >> 3
Divide by 14: ((((uint32_t)A * (uint32_t)0x2493) >> 16) + A) >> 1) >> 3
Divide by 15: (((uint32_t)A * (uint32_t)0x8889) >> 16) >> 3
Divide by 30: (((uint32_t)A * (uint32_t)0x8889) >> 16) >> 4
Divide by 60: (((uint32_t)A * (uint32_t)0x8889) >> 16) >> 5
Divide by 100: (((((uint32_t)A * (uint32_t)0x47AF) >> 16U) + A) >> 1) >> 6
Divide by PI: ((((uint32_t)A * (uint32_t)0x45F3) >> 16) + A) >> 1) >> 1
Divide by 2: (((uint32_t)A * (uint32_t)0xB505) >> 16) >> 0

modulus (%)

Efficient C Tip #13 – use the modulus (%) operator with caution « Stack Overflow
void display_value(uint16_t value)
{
 uint8_t    msd, nsd, lsd;

 if (value > 999)
 {
 value = 999;
 }

 lsd = value % 10;
 value /= 10;
 nsd = value % 10;
 value /= 10;
 msd = value;

 /* Now display the digits */
}
void display_value(uint16_t value)
{
 uint8_t    msd, nsd, lsd;

 if (value > 999U)
 {
  value = 999U;
 }

 msd = value / 100U;
 value -= msd * 100U;

 nsd = value / 10U;
 value -= nsd * 10U;

 lsd = value;

 /* Now display the digits */
}

Fast loops

Efficient C Tips #7 – Fast loops « Stack Overflow
So how does this efficiency arise? Well in the count up case, the assembly language generated by the compiler typically looks something like this:

INC lpc      ; Increment loop counter
SUB lpc, #10 ; Compare loop counter to 10
BNZ loop     ; Branch if loop counter not equal to 10

By contrast, in the count down case the assembly language looks something like this

DEC lpc   ; Decrement loop counter
BNZ loop  ; Branch if non zero

Evidently, because of the ‘specialness’ of zero, more efficient code can be generated.

メモメモ

Gammon Forum : Electronics : Microprocessors : Power saving techniques for microprocessors
sleep 系はここがまとまってる
ArduinoでDS3231 RTCモジュールを使った定期処理 | Program Resource
RTC の SQW 割り込みでうんぬん。これ系ですね。

もろもろメモ

あとにつながるメモ

xively (ザイブリー)
EVRYTHNG
thethings.iO
AT&T M2X
SORACOM ソラコム
How to send sensor data to InfluxDB from an Arduino Uno
Time series database にブチ込む
DIY Arduino YUN Integration for PagerDuty Alerts
PagerDuty の Alert で動く
DIY Home Automation Using Twilio, PowerSwitch, Arduino, and Pusher
Twilio blog arduino ネタ多し
Find grovefamily - Buy grovefamily from Best grovefamily Distributors | Seeedstudio
Grove System - Wiki
Suli
Grove 自作とくれべたらちょっと高いけど、お気楽に遊べるな。なかなか良い感じ。
Suli の考え方も興味深い。(ここはいろいろアプローチあるだろうなぁ)
MikroElektronika - Flip-n-click
これも似たようなコンセプトか。ソフトはどうだろう...
SH:遊び心を形にできる、アプリとつなげるブロック形状の電子タグ|ソニー
あぁ こういったアプローチもあるな。(でも hack する楽しさはあるのかぁ...)

RTOS

FreeRTOS

入門

ここがいちばんいい感じ。昔を思い出しつつ...

garretlab

基本の7セグ

Arduino 7 segment LED display tutorial
ポート・レジスタ使わない形の一番シンプルなもの

AVR libc

AVR Libc 日本語
AVR libcを使ってみる you/junkbox

IoT するなら

いろいろ検討したが (様々なシールドやPC系GW) 、これでいいやん、そこそこ安いし、arduino 的手軽さもあるし... Arduino Yún

AWS IoTをArduino Yúnで使う(少し詳しく書いてみた) | スイッチサイエンス マガジン
腹腹開発: Arduino YUN上の温湿度センサデータをIBM IoT Foundation QuickStartへ送信する
【電子工作】Arduino YúnをGoogle DocsやTwitterと連携してみた | GMOインターネット 次世代システム研究室
Using Parse for IoT to Create an Order Button
awsIoT - 太陽光パネルの発電量をAWS IoTとAmazon Elasticsearch Serviceを使って可視化してみる
SDK for connecting to AWS IoT from an Arduino Yún
OpenWrt
Fork of the openwrt project to add gccgo and libgo
Burgin's Data Thing | Experiment 2 - How to secure Beaver
Serial to Network Proxy (ser2net)
tunneling - Reverse ssh tunnel を安定運用する
init.dスクリプトを書いてみる - MQTT and …

Arduino の歴史

Arduinoの語られざる歴史
こえーーー
Wiring