发送数据


确认发送缓冲区的空间

通过 availableForWrite() 函数可确认发送缓冲区的业余空间。

port.availableForWrite()

此函数将发送缓冲的字节返还为整数形态。

等待完成数据传输

通过 flush() 函数可等待发送缓冲的数据全部传输完毕(发送缓冲为空为止)。

port.flush()

发送数据

You can send data by using write() function.

port.write(byte)
port.write(wbuf, wlen)

示例

#include <PhpocExpansion.h>
#include <Phpoc.h>
#define BUFFER_SIZE 100  // read and write buffer size, reduce it if memory of Arduino is not enough

byte spcId = 1;

ExpansionSerial port(spcId);

byte rwbuf[BUFFER_SIZE];  // read and write buffer

void setup() {
    Serial.begin(9600);
    while(!Serial)
        ;

    Phpoc.begin(PF_LOG_SPI | PF_LOG_NET);
    Expansion.begin();
    port.begin("115200N81T");
}

void loop() {

    int txfree = port.availableForWrite();
    int rxlen = port.available(); 

    if(rxlen > 0) {
        if(rxlen <= txfree) {
            int rwlen; // read and write length

            if(rxlen <= BUFFER_SIZE) 
                rwlen = rxlen;
            else
                rwlen = BUFFER_SIZE;

            // receive data
            rwlen = port.readBytes(rwbuf, rwlen);

            // send data
            port.write(rwbuf, rwlen);

            // print data to serial monitor of Arduino IDE
            Serial.write(rwbuf, rwlen);
        }
    }

    delay(1);
}