TI-Nspire & Arduino、キーボードから任意の文字列を Arduino へ送る
TI-Nspire will send a string to a Leo. Then the Leo will send the received string back to TI-Nspire.
(You should use a TI Launchpad instead of a Leonardo.)
.ino
String inString = ""; void setup() { Serial.begin(115200); } void loop() { while(Serial.available()) { char c = Serial.read(); if(c != '\n') { inString += c; // 各文字をつなぎ合わせる。 } if(c == '\n') { // 改行記号が入ってきたら、 Serial.print(inString); // 今までつなぎ合わせた文字列を返して、 inString = ""; // その文字列をクリアする。 } } }
.lua
require "asi" require "color" platform.window:setBackgroundColor(color.dodgerblue) function on.resize() W, H = platform.window:width(), platform.window:height() fontSize = W/13.25 leftMargin = fontSize / 5 lineSpace = fontSize * 1.5 end function reset() txString, rxString = "", "" platform.window:invalidate() end local PORT -------------------------------------------------------------------------------- -- ASI ステートリスナーを定義する(ASI の準備が整ったらポートスキャンを開始する) -------------------------------------------------------------------------------- function stateListener(state) if state == asi.ON then asi.startScanning(portScanner) end end ---------------------------------------------------------------- -- ポートスキャナーを定義する(見つかったポートに接続要求を出す) ---------------------------------------------------------------- function portScanner(port) PORT = port port:connect(portConnector) end ----------------------------- -- ポートコネクターを定義する ----------------------------- function portConnector(port, event) if event == asi.CONNECTED then asi.stopScanning() port:setReadListener(readListener) end end ----------------------------- -- 読み取りリスナーを定義する ----------------------------- function readListener(port) rxString = port:getValue() platform.window:invalidate() end --------------------------------- -- ASI ステートリスナーを登録する --------------------------------- function on.construction() reset() asi.addStateListener(stateListener) end ------------------------------------------------------------------------------- function on.charIn(char) txString = txString..char platform.window:invalidate() end function on.backspaceKey() txString = string.usub(txString, 1, -2) platform.window:invalidate() end function on.enterKey() PORT:write(txString.."\n") PORT:read() txString = "" platform.window:invalidate() end function on.escapeKey() reset() end function on.paint(gc) gc:setFont("sansserif", "r", fontSize) gc:setColorRGB(color.white) gc:drawString(txString or "", leftMargin, 0) gc:drawString(rxString or "", leftMargin, lineSpace) end