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

标签 python c hardware cpu-registers

我有一个 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/

相关文章:

python - 在 numpy/pandas 中生成相关数

python - Python 中的自适应描述符

c - 使用输入字符串并逐字符打印出来

hardware - AVR 和 Arduino 之间有什么区别/关系?

python - Django AUTHENTICATION_BACKENDS 导入错误

python - Python 3 可以对我的 Mac 上打开的文件使用react吗?

在没有 Root 访问的情况下,Linux 在 CPL3(用户模式)下会崩溃或挂起吗?

c - 指向全局数组中元素位置的全局变量(在 C 中)

android - 如何开始Android/iOS配件开发?

performance - Lucene (Solr/Zoie/Elasticsearch) 设置的硬件要求