main.c
#include “../inc/drivers.h”
#include “../inc/lib.h”
#include <string.h>
#include <stdio.h>
#include “inc/lcd320.h”
#include “inc/macro.h”
#include “inc/reg2410.h”
#pragma import(__use_no_semihosting_swi) // ensure no functions that use semihosting
void ARMTargetInit(void);
extern U32 LCDBufferII2[480][640];
// AD转换寄存器定义
#define rADCCON (*(volatile unsigned *)0x58000000)
#define rADCTSC (*(volatile unsigned *)0x58000004)
#define rADCDLY (*(volatile unsigned *)0x58000008)
#define rADCDAT0 (*(volatile unsigned *)0x5800000C)
#define rADCDAT1 (*(volatile unsigned *)0x58000010)
// AD转换控制位定义
#define ADCCON_FLAG (0x1 << 15) // 转换结束标志
#define ADCCON_ENABLE_START_BYREAD (0x1 << 1) // 通过读操作启动转换
#define PRSCVL (49 << 6) // 预分频值
#define ADCCON_ENABLE_START (0x1) // 启动转换
#define STDBM (0x0 << 2) // 正常模式
#define PRSCEN (0x1 << 14) // 预分频使能
// LCD缓冲区指针
extern U16 *pLCDBuffer16I1;
// 初始化AD转换器
void init_ADdevice()
{
rADCCON = (PRSCVL | ADCCON_ENABLE_START | STDBM | PRSCEN);
}
// 获取指定通道的AD转换结果
int GetADresult(int channel)
{
int result;
int i;
// 每个通道采样两次,第二次才是有效值(参考原始代码做法)
for (i = 0; i <= 1; i++)
{
// 设置通道并启动转换
rADCCON = ADCCON_ENABLE_START_BYREAD | (channel << 3) | PRSCEN | PRSCVL;
hudelay(10); // 等待转换开始
while (!(rADCCON & ADCCON_FLAG))
; // 等待转换结束
result = (0x3ff & rADCDAT0); // 读取10位采样值(0-1023)
}
hudelay(50); // 增加通道切换延时,防止通道干扰
return result;
}
// 将AD值(0-1023)转换为0-255范围
unsigned char AD_to_255(int ad_value)
{
return (unsigned char)((ad_value * 255) / 1023);
}
// 将RGB888(0-255)转换为RGB565格式
unsigned short RGB888_to_RGB565(unsigned char r, unsigned char g, unsigned char b)
{
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}
// 用指定颜色填充全屏
void LCD_FillScreen(unsigned short color)
{
int i;
for (i = 0; i < LCDWIDTH * LCDHEIGHT; i++)
{
*(pLCDBuffer16I1 + i) = color;
}
}
int main(void)
{
int ad_value[3]; // 存储三个通道的AD值
unsigned char r, g, b; // RGB值(0-255)
unsigned short color; // RGB565格式的颜色值
ARMTargetInit(); // 系统初始化
LCD_Init(); // LCD初始化
init_ADdevice(); // AD转换器初始化
Uart_Printf(0, “\nAD转换控制LCD颜色显示程序\n”);
Uart_Printf(0, “调整电位器可改变屏幕颜色\n\n”);
while (1)
{
// 读取三个通道的AD值
ad_value[0] = GetADresult(0); // 通道0 – 红色(R)
ad_value[1] = GetADresult(1); // 通道1 – 绿色(G)
ad_value[2] = GetADresult(2); // 通道2 – 蓝色(B)
// 将AD值(0-1023)转换为0-255范围
r = AD_to_255(ad_value[0]);
g = AD_to_255(ad_value[1]);
b = AD_to_255(ad_value[2]);
// 将RGB888转换为RGB565格式
color = RGB888_to_RGB565(r, g, b);
// 用指定颜色填充全屏
LCD_FillScreen(color);
// 打印当前AD值和RGB值
Uart_Printf(0, “\rAD: [%4d, %4d, %4d] RGB: [%3d, %3d, %3d] “,
ad_value[0], ad_value[1], ad_value[2], r, g, b);
hudelay(100); // 延时,避免刷新过快
}
return 0;
}