通过 begin() 函数设定串口通信参数。
port.begin(baud)
port.begin(sets)
"(baudrate)[parity[data bit[stop bit[flow control]]]]"
※ (): 必选, []: 可选
参数 | 设定范围 | 说明 | 基本参数 |
---|---|---|---|
baudrate | 1200 ~ 115200 | baudrate(bps) | 115200 |
parity | N, E, O, M or S | parity bit (N:None, E:Even, O:Odd, M:Mark, S:Space) |
N |
data bit | 8 or 7 | data bit | 8 |
stop bit | 1 or 2 | stop bit | 1 |
flow control | N, H or S | flow control (N: None, H: RTS/CTS, S: Xon/Xoff) |
N |
#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();
// sets the parameters for serial data communication
port.begin("115200N81N");
}
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);
}