Node.js 调用 C++ 原生模块实现串口通信 (Arduino / UART)
最近使用 Node.js 的串口库发现速度很慢,于是自己用 C++ 编写了一个原生模块(通过 node-gyp 编译),让 Node.js 直接调用,测试通过,速度提升明显。以下是最初版本的记录。
项目结构
包含以下文件:
- test.cc:C++ 原生插件代码,通过 UART 与 Arduino 通信
- binding.gyp:node-gyp 编译配置文件
- test.js:Node.js 调用示例
编译后的模块下载(可能已失效):百度网盘
test.js(调用示例)
var test = require('./build/Release/test');
test.ArduinoDevice('test', function(data) {
console.log(data);
});
binding.gyp(编译配置)
{
"targets": [
{
"target_name": "test",
"sources": [ "test.cc" ]
}
]
}
test.cc(C++ 原生模块)
该模块通过 Linux UART 设备(/dev/ttyAMA0)与 Arduino 串口通信,数据通过回调函数传回 Node.js 层:
#include <node.h>
#include <v8.h>
#include <stdio.h>
#include <unistd.h> //Used for UART
#include <fcntl.h> //Used for UART
#include <termios.h> //Used for UART
#include <string.h>
using namespace v8;
// 传入两个参数:args[0] 字符串,args[1] 回调函数
void hello(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
int uart0 = -1;
printf("----------starting-------------------\n");
uart0 = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
if (uart0 == -1) {
printf("Error opening UART\n");
return;
}
// 配置串口参数
struct termios options;
tcgetattr(uart0, &options);
options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uart0, TCIFLUSH);
tcsetattr(uart0, TCSANOW, &options);
// 读取数据并返回
unsigned char rx_buffer[256];
int rx_length = read(uart0, (void*)rx_buffer, 255);
if (rx_length > 0) {
rx_buffer[rx_length] = '\0';
printf("Received: %s\n", rx_buffer);
// 通过回调返回给 Node.js
}
close(uart0);
}
以雷霆击碎黑暗

浙公网安备 33010602011771号