陈拓 2021/01/04-2021/01/09
1. 概述
在《Win10启用Linux子系统安装Ubuntu》
https://zhuanlan.zhihu.com/p/341394468
https://blog.csdn.net/chentuo2000/article/details/112131624
一文中我们已经在Win10上安装了Ubuntu,本文中我们要在Ubuntu中使用串口。
Windows的Linux子系统Windows Subsystem for Linux 简称WSL。
Win10的串口,可以直在WSL中接使用。从windows COM端口到Linux tty接口之间有一个简单的映射,即COMx映射到ttySx,例如COM3对应WSL中的设备名称/dev/ttyS3。
在WSL2版本中,硬件访问支持将受到限制,例如:您将无法访问GPU、串行或USB设备。所以要使用串行或USB设备要用WSL。
查看当前wsl版本:
Win+R > cmd
输入wsl -l -v
![0ce6263433b636e98cfe4ac2e59407ac.png](https://img-blog.csdnimg.cn/img_convert/0ce6263433b636e98cfe4ac2e59407ac.png)
2. 连接USB-Serial串口设备
- 硬件连接
笔记本上没有串口,我们用CH340G USB-Serial转接板。为进行串口回环测试,用跳线帽短接TXD和RXD。
![7d1527531b4f134c37c377e85221d832.png](https://img-blog.csdnimg.cn/img_convert/7d1527531b4f134c37c377e85221d832.png)
Win10可以自动识别CH340,在我的电脑上识别为COM3。
![c342e3b7f57e573150eb09bf12da6b7a.png](https://img-blog.csdnimg.cn/img_convert/c342e3b7f57e573150eb09bf12da6b7a.png)
3. Win10使用CH340 USB-SERIAL串口
见《Win10使用CH340USB-SERIAL串口》
https://zhuanlan.zhihu.com/p/342339132
4. WSL Ubuntu使用程序访问USB-SERIAL串口
参考文档《WSL: Working with COM ports on Windows/Linux》
https://icircuit.net/wsl-working-with-com-ports-on-windows-linux/2866
4.1 从Python访问COM端口
通过WSL,我们可以从Linux程序访问windows COM端口。下面我们将从Python和NodeJS程序访问COM端口。
ls /dev | grep ttyS3
![cb6e0a14081c136e15495f0d61a6d151.png](https://img-blog.csdnimg.cn/img_convert/cb6e0a14081c136e15495f0d61a6d151.png)
- 创建一个目录wsl-python-sp
mkdir wsl-python-sp
cd wsl-python-sp
- 安装python串口模块
pip install pyserial
![38cf722ce8acbff6bdc8e433f46f4107.png](https://img-blog.csdnimg.cn/img_convert/38cf722ce8acbff6bdc8e433f46f4107.png)
需要先安装Python2包管理工具pip。
参考《Win10的Linux子系统Ubuntu安装pip》https://zhuanlan.zhihu.com/p/342750610
重新启动Ubuntu再安装:
![97459fec6d832cb146c43ee85246a565.png](https://img-blog.csdnimg.cn/img_convert/97459fec6d832cb146c43ee85246a565.png)
- 复制下面的代码到hello.py