TP-Link TL-WR703n路由USB口用途1——串口

理论上wr703n的USB口跟普通电脑上的USB口没有任何区别,wr703n就是一台mini pc,在普通PC上能干的事,在wr703n上都能干,只要你拥有对它的完全控制。刷了OpenWrt固件,我们就有了这样的控制。

下面介绍将wr703n USB口当做串口用。

将arduino板连接至wr703n的USB口,安装驱动。
我自己用的是OCRobot mangoII,USB转ttl用的是FT232RL芯片,

opkg intall kmod-usb-serial-ftdi

如果是arduino uno r3,USB转换芯片用的是ATmega16U2

opkg install kmod-usb-acm

其他USB转ttl芯片如PL2303

opkg install kmod-usb-serial-pl2303

CP201x系列:

opkg install kmod-usb-serial-cp210x

安装完驱动wr703n就可以识别arduino开发板了,可以看到在/dev/目录下多了一个ttyUSB0

下面的任务就是在wr703n上显示串口数据了,可以使用在嵌入式开发中经常被用到的minicom
不过我们不打算用minicom在wr703n终端显示串口数据

既然是无线路由,当然要好好利用它的无线功能,ser2net可以将串口数据转换为一个TCP服务,通过无线连接到wr703n就可以查看到串口数据了

opkg install ser2net

修改ser2net的配置文件/etc/ser2net.conf,在文件末尾添加一行:

1234:raw:0:/dev/ttyUSB0:115200

运行ser2net命令将开启一个TCP 1234端口,以115200波特率读取/dev/ttyUSB0串口
波特率根据自己的arduino代码进行设置,这里我设的是115200

下面是在arduino上运行的代码,每秒钟打印一次接在pin 2上的pushbutton的状态:

/*
DigitalReadSerial
Reads a digital input on pin 2, prints the result to the serial monitor

This example code is in the public domain.
*/

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;

// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(115200);
// make the pushbutton’s pin an input:
pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.print(millis());
Serial.print(“ms: “);
Serial.println(buttonState);
delay(1000); // delay in between reads for stability
}
在笔记本上需要一个工具连接到TCP 1234端口,推荐使用Hercules,Hercules还可以连串口、UDP,功能齐全
下载:http://pan.baidu.com/share/link?shareid=543374251&uk=1560615390

Hercules切换到TCP,填好wr703n的IP地址和端口号,连接就可以看到arduino程序的串口输出了

这里有篇文章Control Arduino with TP-Link TL-WR1043ND Router提到socat,说是功能比ser2net更强大,有空可以试试

另外,不只是读串口数据,我们还可以向串口发送数据,在arduino代码中实现好解析协议,实现对IO端口进行控制

 


2013-09-08更新:

ser2net使用非常不稳定,连接10多秒就自动断开连接了,改用socat后很稳定,可保持长时间连接不掉线

配置如下,在/etc/rc.local文件中添加两行(注:命令末尾要加上’&’放到后台运行,如果不加重启路由后LED会闪烁不止,因为脚本在这一行挂起了,后续脚本无法执行):

#open a tcp 9600 port & set to baud rate 9600. The usb serial port is /dev/ttyUSB0
socat tcp-listen:9600,reuseaddr,fork file:/dev/ttyUSB0,nonblock,raw,echo=0,waitlock=/var/run/tty1,b9600 &

#open a tcp 115200 port & set to baud rate 115200. The usb serial port is /dev/ttyUSB0
socat tcp-listen:115200,reuseaddr,fork file:/dev/ttyUSB0,nonblock,raw,echo=0,waitlock=/var/run/tty2,b115200 &
每次通过TCP连接时都会重置一下(打开/dev/ttyUSB0设备时重置),为避免 重置,可以在rc.local开头处加上:

cat /dev/ttyUSB0

查看更多socat用法