python - 在 python 和 arduino 之间共享枚举

标签 python enums arduino share

我用 python 创建了一个 GUI,允许 arduino 控制的麦克纳姆轮车四处移动。

小车有 8 种不同的移动方向,并且可以左右旋转。命令通过笔记本电脑(w10、python)和arduino之间的串行连接发送。

我在 python 中有一个 Enum 类,代表不同的移动方向。

我在 arduino 中有一个相应的枚举来解释来自 python 任务的命令。

为两个编码环境共享单个通用枚举定义的简单方法是什么?

最佳答案

没有。 C/C++ 中的枚举和 python 中的 enum.Enum 是两个截然不同的东西。然而,有一个强大的解决方案。我建议从Python代码中编写C/C++/Arduino头文件。借助 python 强大的内省(introspection)功能,可以轻松使用 __dict__ 扫描 python 枚举/类,并编写 Arduino 代码可以使用的 .h 文件。这就是我生成与相关 python 项目中的枚举和常量相匹配的 Verilog 和 SystemVerilog header 的方法。运行 python 应用程序会生成一个始终同步的新头文件。

编辑:一个更明确的示例

我已经为基于 FPGA 的微处理器构建了一个汇编器。汇编器是用Python编写的,而处理器是用Verilog编写的。所以我创建了一个像这样的 Verilog 头文件:

# Compute the 'after' content.
content = '// opcodes.vh\n'
content += '`ifndef _opcodes_vh\n'
content += '`define _opcodes_vh\n'
content += '// DO NOT EDIT -- FILE GENERATED BY ASSEMBLER\n'
content += '// ------------------------------------\n'
content += '// OPCODES\n'
content += '// ------------------------------------\n'
A = Arch
for i in A.__dict__:
    if i.startswith('OPC_'):
        o = i.replace('OPC_', 'OPCODE_')
        s = '`define ' + o
        while len(s) < 40:
            s = s + ' '
        hexval = str(hex(A.__dict__[i])).replace('0x', '')
        decval = str(A.__dict__[i])
        s = s + "7'h" + hexval + '\t\t// ' + str(decval) + '\n'
        content += s
content += '// END OF GENERATED FILE.\n'
content += '`endif'

# Write to very specific location for Vivado to see it.
file = open(self.opcodes_filename, 'w', encoding='utf-8')
file.write(content)
file.close()

最终输出如下所示:

// opcodes.vh
`ifndef _opcodes_vh
`define _opcodes_vh
// DO NOT EDIT -- FILE GENERATED BY ASSEMBLER
// ------------------------------------
// OPCODES
// ------------------------------------
`define OPCODE_LD_GPR_EXPR              7'h0        // 0
`define OPCODE_LD_GPR_GPTR              7'h1        // 1
`define OPCODE_SV_EXPR_GPR              7'h2        // 2
...
`define OPCODE_IO_T                     7'h4a       // 74
`define OPCODE_TX_T                     7'h4b       // 75
// END OF GENERATED FILE.
`endif

关于python - 在 python 和 arduino 之间共享枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65048495/

相关文章:

java - 是否可以在 JSF 中创建静态枚举对象?

c++ - 用 int + char 组合 uint8_t

Python:从开发服务器迁移到生产服务器

.net - wcf - 更改整数值时枚举是否向后兼容?

c# - 将枚举转换为另一种类型的枚举

java - Arduino Ping))) 传感器在显示一些结果后突然停止

c - C 在没有操作系统的微 Controller 上的限制是什么?

python - 如何从 setup.py 添加 cron 作业

python - 在字符串中的字符之间添加空格的有效方法

python - 通过用户定义的索引用 np.nan 替换 np.array 值的最干净的方法