单片机实验(定时器产生方波)

2019-04-15 19:28发布

普通IO口输出方波/* * Copyrite (c) 2018, 单片机与嵌入式系统工作室 * All Rights Reserved * * File Name :main.cpp * File Description :T2定时器 实现普通IO口输出方波 * P3.6 200Hz * P3.7 100Hz 晶振频率12MHz * * Current Version: 1.0 * Author : 徐子航 * Finish Time : 2018.04.24 * * Earlier Version : * Author : * Finish Time */ #include #define uchar unsigned char #define uint unsigned int sbit PWM_200 = P3^6; sbit PWM_100 = P3^7; uint TIME_Flag = 0; void TIME_Configuration() { TMOD =0x02; TL0 = 6; TH0 = 6; ET0 = 1; EA = 1 ; TR0 = 1; } void TIME_Handler() interrupt 1 { TIME_Flag++; if(TIME_Flag % 10 == 0) { PWM_200= ~PWM_200; } if(TIME_Flag == 20) { PWM_100 = ~PWM_100; TIME_Flag = 0; } } int main() { TIME_Configuration(); while(1) { } }

按键控制产生不同的频率
button.h#ifndef BUTTON_H #define BUTTON_H #define uchar unsigned char #define uint unsigned int sbit KEY_05_hz = P1^0; sbit KEY_1_hz = P1^1; sbit KEY_2_hz = P1^2; sbit KEY_4_hz = P1^3; extern uint PWM_Flag; void KeyScan(); void Delay_Ms(uint n); #endifbutton.c#include "reg52.h" #include "button.h" void KeyScan() { if(KEY_05_hz == 0) { Delay_Ms(10); if(KEY_05_hz == 0) { PWM_Flag = 8; } while(!KEY_05_hz); } if(KEY_1_hz == 0) { Delay_Ms(10); if(KEY_1_hz == 0) { PWM_Flag = 4; } while(!KEY_1_hz); } if(KEY_2_hz == 0) { Delay_Ms(10); if(KEY_2_hz == 0) { PWM_Flag = 2; } while(!KEY_2_hz); } if(KEY_4_hz == 0) { Delay_Ms(10); if(KEY_4_hz == 0) { PWM_Flag = 1; } while(!KEY_4_hz); } }main.c/* * Copyrite (c) 2018, 单片机与嵌入式系统工作室 * All Rights Reserved * * File Name :main.cpp * File Description :T2定时器产生方波 按键控制产生不同的频率 * P1.0 0.5kHz P1.1 1kHz * P1.2 2K P1.3 4kHz * * Current Version: 1.1 * Author : 徐子航 * Finish Time : 2018.04.24 * * Earlier Version : * Author : * Finish Time */ #include #include "button.h" #define uchar unsigned char #define uint unsigned int sbit PWM = P1^7; uint PWM_Flag = 8; //默认输出0.5khz方波 uint TIME_Flag = 0; void Delay_Ms(uint n) { int i = 0; for(;n>0;n--) { for(i = 110; i > 0; i++) {} } } void TIME_Configuration() { TMOD =0x02; TL0 = 131; //125us TH0 = 131; ET0 = 1; EA = 1 ; TR0 = 1; } void TIME_Handler() interrupt 1 { TIME_Flag++; if(TIME_Flag == PWM_Flag) { PWM= ~PWM; TIME_Flag = 0; } } int main() { TIME_Configuration(); while(1) { KeyScan(); } }