AsciiMassage
AsciiMassage V1.7
AsciiMassage允許發送和接收訊息。更準確地說,它是一個微控制器訊息打包器和解析器,適用於任何類型的流(串行、UDP 等)的 ASCII 格式。訊息訊息始終以位址字串開頭,後面跟著使用者定義數量的元素(位元組、整數、長整數、浮點數或字串)。地址字串用於路由訊息。
這是 Massage API 的 ASCII 實作。
https://github.com/SofaPirate/AsciiMassage
完整的類別文件可以在“docs”資料夾中或在此處線上找到。
將庫加入程式碼頂部並實例化一個名為“inbound”的 AsciiMassageParser:
# include < AsciiMassageParser.h >
AsciiMassageParser inbound;
在loop()內部使用parse()解析串列流。如果 parse() 傳回 true,則按摩已完成並準備就緒。
if ( inbound.parseStream( &Serial ) ) {
// parse completed massage elements here.
}
此範例解析以位址「value」開頭且包含一個 long 後面接著一個 int 的訊息的元素:
// Does the massage's address match "value"?
if ( inbound.fullMatch ( " value " ) ) {
// Get the first long.
long ms = inbound. nextLong ();
// Get the next int.
int an0 = inbound. nextInt ();
}
完整的程式碼區塊如下:
# include < AsciiMassageParser.h >
AsciiMassageParser inbound;
// [...]
void loop () {
if ( inbound. parseStream ( &Serial ) ) {
// parse completed massage elements here.
// Does the massage's address match "value"?
if ( inbound. fullMatch ( " value " ) ) {
// Get the first long.
long ms = inbound. nextLong ();
// Get the next int.
int an0 = inbound. nextInt ();
}
}
// [...]
}
將庫加入程式碼頂部並實例化一個名為“inbound”的 AsciiMassageParser:
# include < AsciiMassageParser.h >
AsciiMassageParser inbound;
在loop()之前加入一個函數,當收到訊息時將呼叫該函數
void readMessage () {
// parse completed massage elements here.
}
在loop()內部使用parse()解析串列流,並在收到訊息時執行“readMessage”
inbound.parseStream( &Serial , readMessage );
完整的程式碼區塊如下:
# include < AsciiMassageParser.h >
AsciiMassageParser inbound;
// [...]
void readMessage () {
// parse completed massage elements here.
// Does the massage's address match "value"?
if ( inbound. fullMatch ( " value " ) ) {
// Get the first long.
long ms = inbound. nextLong ();
// Get the next int.
int an0 = inbound. nextInt ();
}
}
void loop () {
inbound. parseStream ( &Serial , readMessage );
// [...]
}
將庫加入程式碼頂部並實例化一個名為「outbound」的 AsciiMassagePacker:
# include < AsciiMassagePacker.h >
AsciiMassagePacker outbound;
打包一個按摩,然後透過串口蒸煮:
outbound.beginPacket( " value " ); // Start a packet with the address called "value".
outbound.addLong( millis() ); // Add the milliseconds.
outbound.addInt( analogRead( 0 ) ); // Add a reading of analog 0.
outbound.streamPacket(&Serial); // End the packet and stream it.