附录1:C8051F340单片机控制系统
附录2:程序源代码
#include
sbit buffer = P1^7; //蜂鸣器 sbit k1 = P2^3; //按键 sbit k2 = P2^2; sbit d1 = P2^7; //LED sbit d2 = P2^6; sbit d3 = P2^5; sbit d4 = P2^4;
//value-保存AD转换数据,dc1-第一路PWM占空比,dc2-第二路PWM占空比, adc1电压采样值
//adc2、adc3-两路电流采样值
long int value1 = 0,value2 = 0,value3 = 0, dc1 = 4030,dc2 = 4030,adc1 = 0,adc2 = 0,adc3 = 0;
unsigned char cs = 1,t1 = 0,t2 = 0,t3 = 0,s = 0; float k = 1.0; //电流分配比例 bit I_flag = 0; void Port_Init() {
PCA0MD &= ~0X40; //关闭看门狗 OSCICN |= 0X03; //内部12M晶振 P0MDOUT |= 0X03; //PWM推挽输出 P0MDIN &= ~0X18; //ADC输入 P0SKIP = 0X18; P1MDIN &= ~0X02; P1SKIP = 0X02; XBR1 = 0X42; //端口使能,CEX0、CEX1连接到端口 }
//显示部分
void Led_Delay() //延时 {
int i,j;
for(i = 1;i > 0;i--) for(j = 100;j > 0;j--);
}
void Led(unsigned int kk) //数码管显示电流分配比例 {
unsigned char table[4] = {0xef,0xf7}; //选通对应数码管 unsigned char dat[4] = {0,0}; //保存结果各位的数值 unsigned char i; dat[0] = kk % 10; dat[1] = kk / 10;
for(i = 0;i < 2;i++) //循环显示 { P4 = 0xff; P3 = table[i]; P4 = dat[i]; Led_Delay(); } }
//AD采集 void Adc_Init() {
AMX0P = 0X11; //正输入P0.3 AMX0N = 0X1F; //负输入地 ADC0CF = 3 << 3;//转换时钟3M ADC0CN = 0X81;
REF0CN = 0X08; //VDD作为电压基准 EIE1 |= 0X08; //转换结束中断允许 }
void Ad1() //第1路 {
AMX0P = 0X11; //正输入P0.3 cs = 1; }
void Ad2() //第2路 {
AMX0P = 0X12; //正输入P0.4 cs = 2; }
void Ad3() //第3路 {
AMX0P = 0X13; //正输入P1.1 cs = 3;
}
//定时器0,溢出进行AD采集 void Timer0_Init() //0.5ms采集一次 {
TMOD = 0X01;
TH0 = (65536 - 500) >> 8; TL0 = (65536 - 500) & 0XFF; ET0 = 1; EA = 1; TR0 = 1; }
//两路十六位PWM输出 void Pca_Init() {
PCA0MD = 0X08; PCA0CPM0 = 0XCB; PCA0CPM1 = 0XCB;
PCA0CPL0 = (65536 - (int)((dc1/10000.0)*65536)) & 0XFF; PCA0CPH0 = (65536 - (int)((dc1/10000.0)*65536)) >> 8; PCA0CPL1 = (65536 - (int)((dc2/10000.0)*65536)) & 0XFF; PCA0CPH1 = (65536 - (int)((dc2/10000.0)*65536)) >> 8; CR = 1;
EIE1 |= 0X10; EA = 1; }
//按键部分
void Key_Delay() {
unsigned int i,j; for(i = 250;i > 0;i--) for(j = 50;j > 0;j--); }
bit Key1() {
bit i = 0; if(k1 == 0) { Key_Delay(); if(k1 == 0) {
i = 1;d3 = ~d3; while(!k1);d3 = ~d3; } }
return i; }
bit Key2() {
bit i = 0; if(k2 == 0) { Key_Delay(); if(k2 == 0) { i = 1;d4 = ~d4; while(!k2);d4 = ~d4; } }
return i; }
void K_test() {
if(Key1()) { if(k < 2.0) { k += 0.1; } if(k == 2.0) { d1 = 0; d2 = 1; } }
if(Key2()) { if(k > 0.5) { k -= 0.1; } if(k == 0.5) { d1 = 1;