目前我們還不知如何控制 / 使用 firmata ,但沒關係。今天我們直接打開 examples > frimata > SimpleDigitalFirmata ,從這段 code 來推測他究竟在晶片裡做了哪些事情...
/*
* Firmata is a generic protocol for communicating with microcontrollers
* from software on a host computer. It is intended to work with
* any host computer software package.
*
* To download a host software package, please clink on the following link
* to open the download page in your default browser.
*
* http://firmata.org/wiki/Download
*/
/* Supports as many digital inputs and outputs as possible.
*
* This example code is in the public domain.
*/
#include <Firmata.h> //引用 Firmata.h 標頭檔
byte previousPIN[TOTAL_PORTS];
byte previousPORT[TOTAL_PORTS];
void outputPort(byte portNumber, byte portValue)
{
// only send the data when it changes, otherwise you get too many messages!
if (previousPIN[portNumber] != portValue) {
Firmata.sendDigitalPort(portNumber, portValue);
previousPIN[portNumber] = portValue;
}
}
void setPinModeCallback(byte pin, int mode) {
if (IS_PIN_DIGITAL(pin)) {
pinMode(PIN_TO_DIGITAL(pin), mode);
}
}
void digitalWriteCallback(byte port, int value)
{
byte i;
byte currentPinValue, previousPinValue;
if (port < TOTAL_PORTS && value != previousPORT[port]) {
for(i=0; i<8; i++) {
currentPinValue = (byte) value & (1 << i);
previousPinValue = previousPORT[port] & (1 << i);
if(currentPinValue != previousPinValue) {
digitalWrite(i + (port*8), currentPinValue);
}
}
previousPORT[port] = value;
}
}
void setup()
{
//告訴 host computer 我的 firmata 版本,僅供辨識用
Firmata.setFirmwareVersion(0, 1);
// attach(byte command, callbackFunction myFunction)
// 註冊各種不同指令,對應會執行的 function
// 當收到帶有DIGITAL_MESSAGE 控制指令時,要執行 digitalWriteCallback 這個 function
Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
// 註冊 SET_PIN_MODE 指令對應 setPinModeCallback
Firmata.attach(SET_PIN_MODE, setPinModeCallback);
// 設定跟 host 溝通的 baud rate , 並開始監聽/等待傳送
Firmata.begin(57600);
}
void loop()
{
byte i;
for (i=0; i<TOTAL_PORTS; i++) {
outputPort(i, readPort(i, 0xff));
}
// 如果 incoming msg buffer 滿了,就執行 processInput , 觸發上面 reset() 中由attach 註冊的指令動作
while(Firmata.available()) {
Firmata.processInput();
}
}
看完 loop() , reset() 後,剩下 setPinModeCallback 跟 setPinModeCallback 這兩個 function 不知道是做什麼的。firmata protocol 是定義自 MIDI protocol ,但不使用 MIDI protocol 的所有的控制指令。 所以長成這樣 : <command><DATA>...
我們明天見