基于tlc2543连接51单片机实现光伏MPPT的C语言代码
时间: 2023-10-25 08:06:57 浏览: 49
下面是基于TLC2543连接51单片机实现光伏MPPT的C语言代码:
```c
#include <reg51.h>
#include <intrins.h>
#define FOSC 22118400L //系统时钟频率
sbit DCLK = P2^0; //定义时钟信号端口
sbit DIN = P2^1; //定义数据输入端口
sbit CS = P2^2; //定义片选信号端口
sbit M1 = P1^0; //定义步进电机控制信号端口1
sbit M2 = P1^1; //定义步进电机控制信号端口2
unsigned char AD_Result_H, AD_Result_L, AD_Value_H, AD_Value_L;
unsigned int AD_Value;
void Delay_us(unsigned int n) //微秒级延时函数
{
while(n--)
{
_nop_();
}
}
void Delay_ms(unsigned int n) //毫秒级延时函数
{
unsigned char i, j;
while(n--)
{
i = 22;
j = 128;
do
{
while (--j);
} while (--i);
}
}
void InitADC() //初始化ADC
{
CS = 1; //片选信号置高
DCLK = 1; //时钟信号置高
DIN = 1; //数据输入信号置高
}
unsigned int ReadADC(unsigned char Channel) //读取ADC
{
unsigned char i;
unsigned int AD_Value = 0;
unsigned long AD_Result;
CS = 0; //片选信号置低
DCLK = 0; //时钟信号置低
DIN = 1; //数据输入信号置高
DCLK = 1; //时钟信号置高
DCLK = 0; //时钟信号置低
DIN = 1; //数据输入信号置高
DCLK = 1; //时钟信号置高
DCLK = 0; //时钟信号置低
DIN = (0x08 | Channel) << 4; //发送通道号
for(i = 0; i < 12; i++)
{
DCLK = 1; //时钟信号置高
AD_Result <<= 1;
if(DIN & 0x80) AD_Result++;
DCLK = 0; //时钟信号置低
}
for(i = 0; i < 4; i++)
{
DCLK = 1; //时钟信号置高
AD_Result <<= 1;
if(DIN & 0x80) AD_Result++;
DCLK = 0; //时钟信号置低
}
CS = 1; //片选信号置高
AD_Value = (unsigned int)(AD_Result >> 3);
AD_Value_H = (unsigned char)(AD_Value >> 8);
AD_Value_L = (unsigned char)(AD_Value & 0x00ff);
return AD_Value;
}
void main()
{
unsigned int i, j, k;
unsigned int AD_Value1, AD_Value2;
unsigned int Max_Power, Max_Power_Last;
unsigned char Direction;
InitADC(); //初始化ADC
while(1)
{
Max_Power = 0;
Direction = 0;
for(i = 0; i < 100; i++) //扫描电压范围
{
M1 = 1;
M2 = 0;
Delay_us(500);
AD_Value1 = ReadADC(0); //读取电压值
Delay_us(500);
AD_Value2 = ReadADC(1); //读取电流值
k = AD_Value1 * AD_Value2;
if(k > Max_Power) //寻找最大功率点
{
Max_Power = k;
Direction = 0;
}
M1 = 0;
M2 = 1;
Delay_us(500);
AD_Value1 = ReadADC(0); //读取电压值
Delay_us(500);
AD_Value2 = ReadADC(1); //读取电流值
k = AD_Value1 * AD_Value2;
if(k > Max_Power) //寻找最大功率点
{
Max_Power = k;
Direction = 1;
}
}
if(Max_Power > Max_Power_Last) //判断是否需要调整步进电机
{
Max_Power_Last = Max_Power;
if(Direction == 0) //调整步进电机
{
for(j = 0; j < 20; j++)
{
M1 = 1;
M2 = 0;
Delay_ms(5);
M1 = 0;
M2 = 0;
Delay_ms(5);
}
}
else
{
for(j = 0; j < 20; j++)
{
M1 = 0;
M2 = 1;
Delay_ms(5);
M1 = 0;
M2 = 0;
Delay_ms(5);
}
}
}
else
{
break;
}
}
}
```
这段代码实现了基于TLC2543连接51单片机的光伏MPPT,具体实现过程为:扫描电压范围,寻找最大功率点,并根据最大功率点的变化调整步进电机的位置,一直循环执行,直到找到最佳的最大功率点。