gpt4 book ai didi

python - 如何使用 Python 写入硬件寄存器?

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:07 25 4
gpt4 key购买 nike

我有一个 C 函数,它可以通过打开设备描述符 (nf10) 完美地读取/写入硬件寄存器。我正在尝试使用 Python 做同样的事情。我能够读取寄存器,但无法写入寄存器。为什么我不会写?有没有更好的方法来对硬件中的寄存器进行读/写?

相关Python代码:

#! /usr/bin/env python
import os
from fcntl import *
from struct import *

SIOCDEVPRIVATE = 35312
NF10_IOCTL_CMD_READ_STAT = SIOCDEVPRIVATE + 0
NF10_IOCTL_CMD_WRITE_REG = SIOCDEVPRIVATE + 1
NF10_IOCTL_CMD_READ_REG = SIOCDEVPRIVATE + 2

def rdaxi(addr):

f = open("/dev/nf10", "r+")
arg = pack("q", int(addr, 16))
value = ioctl(f, NF10_IOCTL_CMD_READ_REG, arg)
value = unpack("q", value)
value = value[0]
value = hex(value & int("0xffffffff", 16))
f.close()
return value

def wraxi(addr, value):

f = open("/dev/nf10", "r+")
arg = (int(addr, 16) << 32) + int(value, 16)
arg = pack("q", arg)
ioctl(f, NF10_IOCTL_CMD_WRITE_REG, arg)
f.close()

相关C代码

#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#define NF10_IOCTL_CMD_READ_STAT (SIOCDEVPRIVATE+0)
#define NF10_IOCTL_CMD_WRITE_REG (SIOCDEVPRIVATE+1)
#define NF10_IOCTL_CMD_READ_REG (SIOCDEVPRIVATE+2)

int main(int argc, char* argv[]){
int f;
uint64_t v;
uint64_t addr;
uint64_t val;

if(argc < 3){
printf("usage: rdaxi reg_addr(in hex) reg_val(in_hex)\n\n");
return 0;
}
else{
sscanf(argv[1], "%llx", &addr);
sscanf(argv[2], "%llx", &val);
}

//----------------------------------------------------
//-- open nf10 file descriptor for all the fun stuff
//----------------------------------------------------
f = open("/dev/nf10", O_RDWR);
if(f < 0){
perror("/dev/nf10");
return 0;
}

printf("\n");

// High 32 bits are the AXI address,
// low 32 bits are the value written to that address
v = (addr << 32) + val;
if(ioctl(f, NF10_IOCTL_CMD_WRITE_REG, v) < 0){
perror("nf10 ioctl failed");
return 0;
}
printf("\n");

close(f);

return 0;

最佳答案

我觉得最好用C实现对寄存器的底层操作,然后把C编译成.so。然后在 python 中加载 .so。

关于python - 如何使用 Python 写入硬件寄存器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17426932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com