TI-Nspire & Arduino、サーボを使う 4 of 4、Keyboard ライブラリーを使って TI-Nspire で角度をモニタリングする(続き)

Leonardo will use the Keyboard.h library to transmit data to TI-Nspire. TI-Nspire can receive the data from him by using the on.charIn() function without opening a serial port.
 
f:id:ti-nspire:20160817103532p:plain:h315

.ino

#include <Servo.h>
#include <Keyboard.h>
#define sigPin 9
#define swPin 12

Servo myservo;
int pos = 0;

void setup() {
  pinMode(swPin, INPUT_PULLUP);
  myservo.attach(sigPin);
  Keyboard.begin();
}

void loop() {
  while (digitalRead(swPin) == LOW) {
    for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      Keyboard.print(pos);
      Keyboard.print(";"); //A semicolon indicates end-of-data.
      delay(25);
    }
    for (pos = 180; pos >= 0; pos -= 1) {
      myservo.write(pos);
      Keyboard.print(pos);
      Keyboard.print(";");
      delay(25);
    }
  }
}


.lua

require "color"
platform.window:setBackgroundColor(color.dodgerblue)

function on.resize() 
   W, H = platform.window:width(), platform.window:height()
   X0, Y0 = W/2, H * 0.9
   UNIT = W/10
   fontSize = W/13.25
end
function polar2screen(r, deg, x0, y0, unit)
   local rad = math.rad(deg)
   local x, y = r * math.cos(rad), r * math.sin(rad)
   return x0 + x * unit, y0 - y * unit
end

rxString = ""
DATA = 0

function on.charIn(char)
   if char ~= ";" then 
      rxString = rxString..char
   elseif char == ";" then
      DATA = rxString
      rxString = ""
   end
   platform.window:invalidate()
end

-------------------------------------------------------------------------------
function on.paint(gc)
   gc:setFont("sansserif", "r", fontSize)
   gc:setColorRGB(color.white)
   gc:drawString("  "..DATA.."°", 0, 0)
   gc:setPen("thick")
   gc:drawLine(X0, Y0, polar2screen(4, DATA, X0, Y0, UNIT))
end