Jetson Nano利用普通引脚进行PWM波输出

这篇博客我就简单介绍一下好了,不深入讲了

需要注意的是,我这里用到了ROS,所以运行之前需要安装ROS

初始化中有一个12和50,分别代表频率,完之后他就会让pin12自动输出50hz的50%空占比的PWM波。
如果你想改这个配置的话,需要用ROS话题发布/pwm这个话题来控制他
话题格式没用自定义的,而是使用Point这个数据格式
其中

  • x:代表是否继续输出,0就是停止
  • y: 代表的是频率
  • z: 代表的是空占比,如0.5就是50%

需要注意的是,利用普通引脚进行输出的PWM会不稳定

#!/usr/bin/env python
# coding:utf-8
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()

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值