这篇博客我就简单介绍一下好了,不深入讲了
需要注意的是,我这里用到了ROS,所以运行之前需要安装ROS
初始化中有一个12和50,分别代表频率,完之后他就会让pin12自动输出50hz的50%空占比的PWM波。
如果你想改这个配置的话,需要用ROS话题发布/pwm这个话题来控制他
话题格式没用自定义的,而是使用Point这个数据格式
其中
- x:代表是否继续输出,0就是停止
- y: 代表的是频率
- z: 代表的是空占比,如0.5就是50%
需要注意的是,利用普通引脚进行输出的PWM会不稳定
import Jetson.GPIO as GPIO
import time
import rospy
from multiprocessing import Process, Queue
from geometry_msgs.msg import Point,Twist
class PWM():
def __init__(self, channel, frequency, level=1):
self.channel = channel
self.frequency = frequency
if level == 1:
self.HIGH = GPIO.HIGH
self.LOW = GPIO.LOW
elif level == 0:
self.HIGH = GPIO.LOW
self.LOW = GPIO.HIGH
else:
raise ValueError("ERROR: level's err")
GPIO.setmode(GPIO.BOARD)
GPIO.setup(self.channel, GPIO.OUT, initial=self.LOW)
self.if_pwm = True
self.if_change = False
def ros_pwm(self):
rospy.init_node("pwm")
a = rospy.Subscriber("/pwm",Point,self.Change)
f = 50.0
c = 0.1
t = 1/f
t_h = t*c
t_l = t*(1-c)
print(t, t_h, t_l)
while True:
if self.if_change:
f = self.frequency
c = self.cycle
t = 1/f
t_h = t*c
t_l = t*(1-c)
if self.if_pwm:
GPIO.output(self.channel, self.HIGH)
time.sleep(t_h)
GPIO.output(self.channel, self.LOW)
time.sleep(t_l)
print('f and c: ', f, ' ',c)
if rospy.is_shutdown():
exit()
rospy.spin()
def Change(self, data):
if int(data.x) == 0:
self.if_pwm = False
else:
self.if_pwm = True
print("Change\n", data)
self.frequency = data.y
self.cycle = data.z
self.if_change = True
if __name__=="__main__":
a = PWM(12, 50)
a.ros_pwm()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)