在python和arduino之间共享枚举

2024-10-04 01:33:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用python创建了一个gui,允许arduino控制的mecanum轮车四处移动

手推车允许8个不同的移动方向,并可左右旋转。命令通过笔记本电脑(w10,python)和arduino之间的串行连接发送

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

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

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


Tags: 方法命令编码定义环境guienum方向
2条回答

不,C/C++中的enum和python中的enum.enum是两个完全不同的东西。然而,有一个强大的解决方案。我建议从python代码中编写C/C++/Arduino头。借助python强大的内省功能,可以轻松地使用__dict__扫描python枚举/类,并编写Arduino代码可以使用的.h文件。这就是我如何生成与相关python项目中的枚举和常量匹配的Verilog和SystemVerilog头的方法。运行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

正如@TomServo所说,让Python代码编写Arduino头。下面是一个使用aenum 3.01或Python 3.102的示例:

from aenum import Enum   # or "from enum import Enum"

class CHeader(Enum):
    def __init_subclass__(cls, **kwds):
        # write Enums to C header file
        cls_name = cls.__name__
        header_path = getattr(cls, '_%s__header' % cls_name)
        with open(header_path, 'w') as fh:
            fh.write('initial header stuff here\n')
            for enum in cls:
                fh.write('#define %s %r\n' % (enum.name, enum.value))

class Arduino(CHeader):
    #
    _order_ = 'ONE TWO'  # only if using Python 2
    #
    __header = './arduino.h'
    #
    ONE = 1
    TWO = 2

这将导致:

initial header stuff here
#define ONE 1
#define TWO 2

1披露:我是Python stdlib ^{}^{} backportAdvanced Enumeration (^{})图书馆的作者

aenum 3.0和Python 3.10中的2将在将枚举成员添加到enum类后调用(在早期版本中,在添加成员之前调用

相关问题 更多 >