嵌入式开发之lua串口通信 嵌入式串口实验代码
liuian 2024-12-25 13:59 28 浏览
一 背景
串口是我接触到最多的一种通信方式,在自动化测试领域发挥了很大的作用,通过串口与上位机交互完成自动测试、自动控制、自动监控等功能,常用的波特率有9600bps、38400bps、115200bps,我们可以把串口相关的API加进去满足这些有通信需求的应用场景。
二 实现串口相关API
2.1 C底层串口的实现
暂时没有开发板,先在codeblocks上模拟一个串口功能
HANDLE hCom;
uint32_t wCount;//读取的字节数
uint8_t bReadStat;
COMMTIMEOUTS TimeOuts;
#define DEVICE_UART_BUF_SIZE 32768
void __SendByte(int8_t ucData)
{
int8_t tempbuf[2]={0};
uint32_t write_len = 0;
tempbuf[0] = ucData;
WriteFile(hCom,tempbuf,1,&write_len,NULL);
}
void __SendString(int8_t *str)
{
while(*str != '\0')
{
__SendByte(*str);
str++;
}
}
2.2 uart库
static const luaL_Reg uartlib[] =
{
{"open", uart_open},
{"UART_PORT_1", NULL},
{"UART_PORT_2", NULL},
{"UART_PORT_3", NULL},
{NULL, NULL}
};
int luaopen_uart (lua_State *L)
{
luaL_newlib(L, uartlib);
lua_pushnumber(L, UART_PORT_1);
lua_setfield(L, -2, "UART_PORT_1");
lua_pushnumber(L, UART_PORT_2);
lua_setfield(L, -2, "UART_PORT_2");
lua_pushnumber(L, UART_PORT_3);
lua_setfield(L, -2, "UART_PORT_3");
return 1;
}
static int uart_open (lua_State *L){
lua_lock(L);
csp_uart_t *p_uart = (csp_uart_t *)lua_newuserdata(L, sizeof(csp_uart_t));
if (!p_uart)
{
goto err;
}
lua_getfield(L,1,"port");//第一个是port类型是int
uint32_t get_port = lua_tointeger(L, -1);
lua_pop(L, 1);
if (get_port>=UART_PORT_MAX)
{
goto err;
}
lua_getfield(L,1,"baudrate");//第二是baudrate类型是int
uint32_t get_baudrate= lua_tointeger(L, -1);
lua_pop(L, 1);
if ((get_baudrate>115200) || (get_baudrate<9600))
{
goto err;
}
p_uart->port = get_port;
p_uart->baudrate = get_baudrate;
p_uart->p_read_callback = uart_irq_handler;
char set_port[10];
sprintf(set_port,"COM%d",p_uart->port);
hCom=CreateFile(TEXT(set_port),GENERIC_READ|GENERIC_WRITE, 0, NULL,OPEN_EXISTING,0, NULL);
SetupComm(hCom,DEVICE_UART_BUF_SIZE,DEVICE_UART_BUF_SIZE);
luaL_newmetatable(L, TNAMESTR_UART);
luaL_newlib(L, uart_userdata);
lua_setfield(L, -2, "__index");
lua_setmetatable(L, -2);
lua_unlock(L);
return 1;
err:
lua_pushnil(L);
lua_unlock(L);
return 1;
}
2.2.1 uart userdata
typedef enum
{
UART_PORT_1 = 1,
UART_PORT_2,
UART_PORT_3,
UART_PORT_MAX
} Uart_Comport;
typedef enum
{
UART_BAUDRATE_9600 = 9600,
UART_BAUDRATE_19200 = 19200,
UART_BAUDRATE_38400 = 38400,
UART_BAUDRATE_57600 = 57600,
UART_BAUDRATE_115200 = 115200,
UART_BAUDRATE_MAX
} Uart_Baudrate;
typedef enum
{
UART_DATABITS_5 = 5,
UART_DATABITS_6,
UART_DATABITS_7,
UART_DATABITS_8,
UART_DATABITS_MAX
} Uart_Databits;
typedef void(*uart_receive_callback_t)(uint8_t _data);
typedef struct
{
uint8_t port;//uart0,uart1,uart2...
volatile uint32_t baudrate;
volatile uint8_t databits; //**Default:** `8`.
uart_receive_callback_t p_read_callback;
} csp_uart_t;
#define TNAMESTR_UART "g_utype_uart"
const luaL_Reg uart_userdata[] ={
{"put_char",uart_putchar},
{"put_str",uart_str},
{NULL,NULL}
};
static int uart_putchar (lua_State *L){
csp_uart_t *p_uart = (csp_gpio_t *)luaL_checkudata(L, 1,TNAMESTR_UART);
if (p_uart)
{
BOOLEAN get_ch = luaL_checkinteger(L, 2);
printf("getch=[%02x]\n",get_ch);
__SendByte(get_ch);
}
return 0;
}
static int uart_str (lua_State *L)
{
csp_uart_t *p_uart = (csp_gpio_t *)luaL_checkudata(L, 1,TNAMESTR_UART);
if (p_uart)
{
char *get_str = luaL_checkstring(L, 2);
printf("get_str=[%s]\n",get_str);
__SendString(get_str);
}
return 0;
}
2.2.2 定义uart回调函数
int uart1_callback_index;
lua_State *g_uart1_l;
int uart1_callback(lua_State *L)
{
int res = 0;
uint8_t ch;
{
int n = lua_gettop(L);
if(n<1)
{
lua_pushinteger(L, 0);
return 1;
}
ch = lua_tointeger(L,1);
lua_rawgeti(L, LUA_REGISTRYINDEX, uart1_callback_index);
lua_pushinteger(L, ch);
lua_pcall(L, 1, 1, 0);
}
return 1;
}
void uart_irq_handler(uint8_t rx_data)
{
//其它操作
if (g_uart1_l)
{
int top = lua_gettop(g_uart1_l);
lua_pushcfunction(g_uart1_l, &uart1_callback);
lua_pushinteger(g_uart1_l, rx_data);
lua_pcall(g_uart1_l, 1, 1, 0);
int res = lua_tointeger(g_uart1_l, -1);
lua_pop(g_uart1_l, 1);
lua_settop(g_uart1_l, top);
}
}
2.2.3 注册uart回调函数
if(LUA_TFUNCTION==lua_getglobal(g_l, "uart1_callback"))
{
uart1_callback_index = luaL_ref(g_l, LUA_REGISTRYINDEX);
g_uart1_l = lua_newthread(g_l);
}
三 工具
3.1 虚拟串口
3.2 串口助手
配置为每隔1秒自动发送数字1到数字10
四 测试程序
4.1 lua应用
print("hello lua")
--新建一个gpio设备,引脚编号为10,模式为推挽输出
pin_config = {pin=10,mode=gpio.MODE_OUT_PUSHPULL}
local led = gpio.open(pin_config)
led:write(gpio.HIGH_LEVEL)--输出高电平
led:read()--读取电平
led:write(gpio.LOW_LEVEL)--输出低电平
led:read()--读取电平
timer_config = {id=1,ivt_ms=1000}
local time1 = timer.open(timer_config)
time1:start()
function timer1_callback(id)
print("timerout with id:",id)
end
uart_config = {port=1,baudrate=115200}
local uart1 = uart.open(uart_config)
uart1:put_char(0x55)
uart1:put_str("hello uart")
function uart1_callback(rx_data)
print("rx_data:",rx_data)
end
4.2 c底层应用代码
uint32_t readCount=0,send_count=0;
BOOL bRet;
uint8_t send_char=0;
uint32_t receive_length=0;
COMSTAT ComStat;
uint32_t dwErrorFlags=0;
uint32_t dwCommModemStatus;
OVERLAPPED os;
lua_State *g_l= luaL_newstate();
if (g_l)
{
luaL_openlibs(g_l);
}
luaL_dofile(g_l, "G:\\temp.lua");
if(LUA_TFUNCTION==lua_getglobal(g_l, "timer1_callback"))
{
timer1_callback_index = luaL_ref(g_l, LUA_REGISTRYINDEX);
g_timer1_l = lua_newthread(g_l);
}
if(LUA_TFUNCTION==lua_getglobal(g_l, "uart1_callback"))
{
uart1_callback_index = luaL_ref(g_l, LUA_REGISTRYINDEX);
g_uart1_l = lua_newthread(g_l);
}
while(1)
{
bRet=ClearCommError(hCom,&dwErrorFlags,&ComStat);
receive_length = ComStat.cbInQue;
if(receive_length>0)
{
ReadFile(hCom,str,receive_length,&readCount,NULL);
if(readCount>0)
{
for(send_count=0;send_count<readCount;send_count++)
{
send_char = str[send_count];
//printf("%02x ",send_char);
uart_irq_handler(send_char);
}
}
}
Sleep(5);
}
4.3 输出结果
五 总结
这里只是实现了基本的发送字节、发送字符串,接收单个字节的功能,后续还可以加入环形队列,在主循环读取每一个字节,这样就不会丢包,可保证数据的可靠性。
在自动化领域中,串口通信只是其中的一种,还有更多的更可靠的通信方式同样可以使用lua来实现。
相关推荐
- 10种常见的MySQL错误,你可中招?
-
【51CTO.com快译】如果未能对MySQL8进行恰当的配置,您非但可能遇到无法顺利访问、或调用MySQL的窘境,而且还可能给真实的应用生产环境带来巨大的影响。本文列举了十种MySQL...
- MySQL主从如何保证数据一致性
-
MySQL主从(主备)搭建请点击基于Spring的数据库读写分离。MySQL主备基本原理假设主备切换前,我们的主库是节点A,节点B是节点A的备库,客户端的读写都是直接访问节点A,节点B只是将A的更新同...
- MySQL低版本升级操作流程
-
(关注“数据库架构师”公众号,提升数据库技能,助力职业发展)0-升级背景MySQL5.5发布于2010年,至今已有十年历史,官方已经停止更新。2008年发布的MySQL5.1版本,在2018年...
- MySQL数据库知识
-
MySQL是一种关系型数据库管理系统;那废话不多说,直接上自己以前学习整理文档:查看数据库命令:(1).查看存储过程状态:showprocedurestatus;(2).显示系统变量:show...
- Mysql 8.4数据库安装、新建用户和数据库、表单
-
1、下载MySQL数据库yuminstall-ywgetperlnet-toolslibtirpc#安装wget和perl、net-tools、libtirpcwgethtt...
- mysql8.0新功能介绍
-
MySQL8.0新特性集锦一、默认字符集由latin1变为utf8mb4在8.0版本之前,默认字符集为latin1,utf8指向的是utf8mb3,8.0版本默认字符集为utf8mb4,utf8默...
- 全网最详细解决Windows下Mysql数据库安装后忘记初始root 密码方法
-
一、准备重置root的初始化密码Win+R键启动命令输入窗口;输入cmd打开命令执行窗口;##界面如下##输入命令:netstopmysqld#此操作会停止当前运行的...
- 互联网大厂面试:MySQL使用grant授权后必须flush privilege吗
-
从我上大学时,数据库概论老师就告诉我,MySQL使用grant对用户授权之后,一定记得要用flushprivilege命令刷新缓存,这样才能使赋权命令生效。毕业工作以后,在很多的技术文档上,仍然可以...
- # mysql 8.0 版本无法使用 sqlyog 等图形界面 登录 的解决方法
-
30万以下的理想L6来了##mysql8.0版本无法使用sqlyog等图形界面登录的解决方法当我们在cmd下登录mysql时正常时,用sqlyog等图形界面连接数据库时却...
- MySQL触发器介绍
-
前言:在学习MySQL的过程中,可能你了解过触发器的概念,不清楚各位是否有详细的去学习过触发器,最近看了几篇关于触发器的文档,分享下MySQL触发器相关知识。1.触发器简介触发器即trigg...
- 管理员常用的MySQL命令汇总(一)
-
以下是管理员常用的MySQL命令:以管理员身份连接到MySQL:mysql-uroot-p创建新的MySQL用户:CREATEUSER'username'@'...
- Linux(CentOS) 在线安装MySQL8.0和其他版本,修改root密码
-
一:安装MySQL数据库1),下载并安装MySQL官方的YumRepositorymysql官方仓库地址:https://dev.mysql.com/downloads/repo/yum/选择自...
- 解决 MySQL 8.0 一直拒绝 root 登录问题
-
Accessdeniedforuser'root'@'localhost'(usingpassword:YES)这个错误在网上搜一下,能看到非常多的此类...
- 大模型MCP之MYSQL安装
-
前言学习大模型的时候需要一个mysql,原因还是在公司使用电脑的时候不允许按照Docker-Desktop,我的宿主机其实是MAC,我习惯上还是在centsos上面安装,就发现这件过去很简单的事情居然...
- MySQL ERROR 1396
-
ERROR1396(HY000):OperationCREATEUSERfailedfor'usera'@'%'问题描述mysql>create...
- 一周热门
-
-
Python实现人事自动打卡,再也不会被批评
-
【验证码逆向专栏】vaptcha 手势验证码逆向分析
-
Psutil + Flask + Pyecharts + Bootstrap 开发动态可视化系统监控
-
一个解决支持HTML/CSS/JS网页转PDF(高质量)的终极解决方案
-
再见Swagger UI 国人开源了一款超好用的 API 文档生成框架,真香
-
网页转成pdf文件的经验分享 网页转成pdf文件的经验分享怎么弄
-
C++ std::vector 简介
-
系统C盘清理:微信PC端文件清理,扩大C盘可用空间步骤
-
飞牛OS入门安装遇到问题,如何解决?
-
10款高性能NAS丨双十一必看,轻松搞定虚拟机、Docker、软路由
-
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)