Files
ElecScalesMeasur/export_pin.py

88 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
# @Time : 2025/2/18 17:49
# @Author : hjw
# @File : export_pin.py
'''
import os
import time
class GPIOChipController:
def __init__(self, chip_path="/sys/class/gpio/gpiochip0"): # 注意引脚分组
# 读取GPIO控制器信息
self.base = int(self._read_file(os.path.join(chip_path, "base")))
self.ngpio = int(self._read_file(os.path.join(chip_path, "ngpio")))
self.label = self._read_file(os.path.join(chip_path, "label"))
print(f"GPIO控制器信息: {self.label} (base={self.base}, ngpio={self.ngpio})")
def _read_file(self, path):
with open(path, 'r') as f:
return f.read().strip()
def _write_file(self, path, value):
with open(path, 'w') as f:
f.write(str(value))
def export_gpio(self, offset):
"""导出指定控制器的GPIO引脚"""
if offset < 0 or offset >= self.ngpio:
raise ValueError(f"偏移量必须在0-{self.ngpio - 1}范围内")
gpio_number = self.base + offset
export_path = "/sys/class/gpio/export"
if not os.path.exists(f"/sys/class/gpio/gpio{gpio_number}"):
try:
self._write_file(export_path, gpio_number)
time.sleep(0.1) # 等待系统创建目录
except IOError as e:
if "Device or resource busy" in str(e):
print(f"GPIO{gpio_number} 已经导出")
else:
raise
return gpio_number
def setup_gpio(self, gpio_number, direction='out'):
"""配置GPIO方向"""
direction_path = f"/sys/class/gpio/gpio{gpio_number}/direction"
self._write_file(direction_path, direction)
def set_gpio(self, gpio_number, value):
"""设置GPIO电平"""
value_path = f"/sys/class/gpio/gpio{gpio_number}/value"
self._write_file(value_path, 1 if value else 0)
def read_gpio(self, gpio_number):
"""读取GPIO电平"""
value_path = f"/sys/class/gpio/gpio{gpio_number}/value"
return int(self._read_file(value_path))
if __name__ == "__main__":
"""
rk3506导出引脚
该脚本导出扩展口引脚 SAI1_SDO017 对应 GPIO0_B4_d 8 + 4 = 12
"""
try:
# 初始化GPIO控制器
ctrl = GPIOChipController()
# 导出并配置GPIO (假设控制器的base=0偏移量B4即12)
gpio_num = ctrl.export_gpio(12)
ctrl.setup_gpio(gpio_num, 'out')
# 引脚高低电平测试
for _ in range(10):
ctrl.set_gpio(gpio_num, 1)
print(f"GPIO{gpio_num} 置高")
time.sleep(10)
ctrl.set_gpio(gpio_num, 0)
print(f"GPIO{gpio_num} 置低")
time.sleep(1)
except PermissionError:
print("需要root权限请使用sudo运行")
except Exception as e:
print(f"发生错误: {str(e)}")