中微CMS8S5880 PWM输出 占空比可调

废话不多直接上代码

main.c

#include "uart.h"
#include "pwm.h"
#include "led.h"
#include "stdio.h"
#include "sys_time.h"
#include "timer.h"
#include "my_iic.h"



void main()
{
	UART0_INIT();								//initinal UART
	PWM_init();
	LED_INIT();
	Timer2Init();
	set_pwm5_Duty_cycle(30);
	IIC_GPIO_Init();
	printf("code start\r\n");
	EA = 1;//使能总中断
	calc_value_pressure();
	LED4_ON;
	LED5_ON;
	while(1)
	{
		if(get_sys_time_ms() % 100 == 0)
		{
			Put_press_and_temp_value();
			printf("Pressure %f\r\n",pressure);
			printf("TEMP %f\r\n",temp); 
		}
		clrwdt();	
	}

}

lib.h

#ifndef __LIB_H__
#define __LIB_H__

#define BIT0 0x01
#define BIT1 0x02
#define BIT2 0x04
#define BIT3 0x08
#define BIT4 0x10
#define BIT5 0x20
#define BIT6 0x40
#define BIT7 0x80



#endif

PWM.C

#include "pwm.h"
#include "lib.h"

void PWM_init(void)
{
    P36CFG = 0x06;    
    P3TRIS |= BIT6;//输出
    P3OD   |= BIT6;//推挽输出 
    PWMCON = 0x00;//独立模式、边沿对齐
    PWMPINV = 0x00;//输出不反向
    PWMCNTM |= 0x3F; //自动加载模式,即PWM一直输出
    
    /*PWM4、PWM5时钟来源*/
    PWM45PSC = 5; 
    PWM5DIV = 0x05;//PWM5时钟来源=SysClk。本例SysClk=24MHz,所以PWM5时钟来源=24MHz

     /*对边沿对齐,频率=PWMn时钟来源/({PWMPnH,PWMPnL}+1)*/
    #define PWMP5H_PWMP5L 799
    PWMP5H = (PWMP5H_PWMP5L >> 8) & 0x00FF;;//本例PWM5频率=24MHz/800=30KHz
    PWMP5L = PWMP5H_PWMP5L & 0x00FF;
    
    /*对边沿对齐,当{PWMDnH,PWMDnL}=0时,占空比=0%;其他情况时,占空比=({PWMDnH,PWMDnL}+1)/({PWMPnH,PWMPnL}+1)*/
    #define PWMD5H_PWMD5L 399
    PWMD5H = (PWMD5H_PWMD5L >> 8) & 0x00FF;//本例PWM5占空比=400/800=50%
    PWMD5L = PWMD5H_PWMD5L & 0x00FF;
     
    PWMLOADEN |= 0x30;//使能PWM加载周期、占空比数据
    PWMOE |= 0x30; //使能PWM的输出
    PWMCNTE |= 0x30; //启动PWM计数器
}

void set_pwm5_Duty_cycle(uint32_t val)
{ 
    if(val > 100)
    {
        val = 100; 
    }
    val = val * 800 / 100;
    PWMCNTE &= ~0x30; //关闭PWM计数器
    PWMD5H = (val >> 8) & 0x00FF;
    PWMD5L = val & 0x00FF;
    PWMCNTE |= 0x30; //启动PWM计数器
}

PWM.H

#ifndef __PWM_H__
#define __PWM_H__
#include 

void PWM_init();
void set_pwm5_Duty_cycle(uint32_t val);


#endif

 

 

你可能感兴趣的:(中微单片机开发,c语言,嵌入式,芯片)