ASI 1, TI-Nspire(Student Software)と Arduino とを接続してみる

バージョン 4.2(API 2.7)で Asynchronous Serial Interface が正式サポートされた。

Student Software と Arduino Duemilanove 328 とを接続してみる。コードは http://www.ticalc.org/archives/files/fileinfo/466/46657.html から持ってきた。理窟はわからない。


-- http://www.ticalc.org/archives/files/fileinfo/466/46657.html からダウンロードしたコードそのままである

require "asi"

local size = nil

local msgBuffer = {}
local max_buffer = 999
function LOG(msg)
    if(#msgBuffer>=max_buffer) then
        for i=0,max_buffer-1 do
            msgBuffer[i]=msgBuffer[i+1]
        end 
        msgBuffer[max_buffer] = tostring(msg)
    else
        msgBuffer[#msgBuffer+1] = tostring(msg)
    end
end

local asiStateCallback = function(state)
    print("asiStateCallback:")
    print("state = ", state)
    if state == asi.ON then
        startScanning()
    end
end

local asiAddStateListenerErr = asi.addStateListener(asiStateCallback)
if (asiAddStateListenerErr) then
    print("Error in asiAddStateListenerErr: ", asiAddStateListenerErr)
end


local portConnectionCallback = function(port, event)
    LOG("portConnectionCallback:")
    local portName, portID, portState = port:getName(), port:getIdentifier(), port:getState()
    local str=""
    if portName then
        str=str.."Name="..portName
    end
    if portID then
        str=str.." ; ID="..portID
    end
    if portState then
        str=str.." ; State="..portState
    end
    if event then
        str=str.." ; event="..event
    end
    LOG(str)
    platform.window:invalidate()
end

local portFoundCallback = function(port)
    LOG("portFoundCallback:")
    local portName, portID, portState = port:getName(), port:getIdentifier(), port:getState()
    local str=""
    if portName then
        str=str.."Name="..portName
    end
    if portID then
        str=str.." ; ID="..portID
    end
    if portState then
        str=str.." ; State="..portState
    end
    LOG(str)
    if portState == asi.DISCONNECTED then
        local portConnectError = port:connect(portConnectionCallback)
        if (portConnectError) then
            LOG("Error in portConnectError: ", portConnectError)
        end
    end
    platform.window:invalidate()
end

function startScanning()
    LOG("Starting scan")
    local asiStartScanningErr = asi.startScanning(portFoundCallback)
    if (asiStartScanningErr) then
        LOG("Error in asiStartScanningErr: ", asiStartScanningErr)
    end
    platform.window:invalidate()
end

function on.paint(gc, x, y, w, h)
    local i=0
    gc:setFont("serif","r",6)
    if(not size) then
        size=gc:getStringHeight("W")
        max_buffer = math.floor(platform.window:height()/size)
    end
    for _,str in pairs(msgBuffer) do
        gc:drawString(str, 5, i*size, "top")
        i=i+1
    end
end