Firmata 函式库

Firmate 是一个规范微处理器如何与主机端互相传递资料的协定。Firmata 详细的协定内容可以看 wiki page 或是 Firmate 官网

Firmata 函式库实作了 Firmata 协定,让使用者可以製作自己的韧体而不需要另外建立微处理器与主机端之间的沟通方式。

我们拍了一个使用 86Duino 与电脑透过 Firmata 函式库传递资料的范例影片,也许你会有兴趣。

方法

begin()
启动 Firmata 函式库

begin(long)
启动 Firmata 函式库并同时设定与主机端传输资料时的鲍率(baud rate)

printVersion()
传送使用的 Firmata 版本到主机端

blinkVersion()
使用 pin 13 连接的 LED 标示目前 Firmate 使用的版本

printFirmwareVersion()
传送韧体名称和版本到主机端

setFirmwareVersion(byte major, byte minor)
设定韧体名称和版本,使用草稿码(sketch)的档案名称(不包含副档名, 如:.ino, .pde)

传送讯息:

sendAnalog(byte pin, int value)
传送类比讯息到主机端

sendDigitalPorts(byte pin, byte firstPort, byte secondPort)
传送数位讯息到主机端,一次传送一整个埠(port)的数位值

sendSysex(byte command, byte bytec, byte* bytev)
传送讯息型态和阵列中的资料到主机端

sendString(const char* string)
传送字串到主机端

sendString(byte command, const char* string)
传送讯息型态和字串到主机端

接收讯息:

available()
检查是否有接收到讯息

processInput()
解析接收到的讯息并且依收到的讯息内容呼叫对应的回呼函数

attach(byte command, callbackFunction myFunction)
设定讯息型态所对应的回呼函式

detach(byte command)
移除讯息型态所对应的回呼函式

回呼函式(Callback Functions)

Firmata 函式库使用 attach() 设定讯息型态所对应的回呼函式,而这些被讯息型态对应的回呼函式有固定的格式,格式一共有四种,请参考下列:

generic
void callbackFunction(byte pin, int value);

system_reset
void systemResetCallbackFunction(void);

string
void stringCallbackFunction(char *myString);

sysex
void sysexCallbackFunction(byte pin, byte byteCount, byte *arrayPointer);

讯息型态:

以下列出所有的讯息型态,这些讯息型态可以个别设定对应的回呼函式:

ANALOG_MESSAGE
单一脚位的类比值,使用 callbackFunction 作为其对应的回呼函式格式

DIGITAL_MESSAGE
一个埠的数位值(一共有八个脚位),使用 callbackFunction 作为骑对应的回呼函式格式

REPORT_ANALOG
主机端要求回传指定脚位的类比值请求,使用 callbackFunction 作为其对应的回呼函式格式

REPORT_DIGITAL
主机端要求回传指定埠的数位值请求,使用 callbackFunction 作为其对应的回呼函式格式

SET_PIN_MODE
改变脚位状态为 INPUTOUTPUTPWM,使用 callbackFunction 作为其对应的回呼函式格式

FIRMATA_STRING
字串讯息,C 风格字串(C-style string),使用 stringCallbackFunction 作为其对应的回呼函式格式

SYSEX_START
字串讯息,支援任意长度的字串(透过 MIDI SysEx 协定),使用 sysexCallbackFunction 作为其对应的回呼函式格式

SYSTEM_RESET
主机端要求微处理器重新启动的的讯息型态,使用 systemResetCallbackFunction 作为其对应的回呼函式格式

范例

这个范例示范如何使用 Firmata 函式库收发类比讯息。

#include <Firmata.h>

byte analogPin;

void analogWriteCallback(byte pin, int value)
{
    pinMode(pin,OUTPUT);
    analogWrite(pin, value);
}

void setup()
{
    Firmata.setFirmwareVersion(0, 1);
    Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
    Firmata.begin();
}

void loop()
{
    while(Firmata.available()) {
        Firmata.processInput();
    }
    for(analogPin = 0; analogPin < TOTAL_ANALOG_PINS; analogPin++) {
        Firmata.sendAnalog(analogPin, analogRead(analogPin)); 
    }
}

范例影片


函式库参考主页面

The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.