tcs3200颜色识别51代码,并用串口发送颜色
时间: 2023-11-15 15:05:45 浏览: 144
tx.zip_51串口发送
以下是使用TCS3200模块实现颜色识别的51单片机代码,并通过串口发送颜色信息:
```c
#include <reg52.h>
#include <stdio.h>
#define uchar unsigned char
#define uint unsigned int
#define S2 P3_4
#define S3 P3_5
#define OUT P2_7
sbit LED1 = P1^0;
sbit LED2 = P1^1;
sbit LED3 = P1^2;
uchar code color[6][10] = {"Red", "Green", "Blue", "Yellow", "Purple", "White"};
void init();
uint get_color();
void send_data(uchar dat);
void main()
{
init();
while(1)
{
uint color = get_color();
printf("Color: %s\n", color[color]);
send_data(color);
}
}
void init()
{
TMOD = 0x20;
TH1 = 0xfd;
TL1 = 0xfd;
TR1 = 1;
SCON = 0x50;
EA = 1;
ES = 1;
}
uint get_color()
{
uint red, green, blue;
S2 = 0;
S3 = 0;
OUT = 1;
delay(50);
red = TH0 * 256 + TL0;
TH0 = 0;
TL0 = 0;
OUT = 0;
S3 = 1;
delay(50);
green = TH0 * 256 + TL0;
TH0 = 0;
TL0 = 0;
S2 = 1;
delay(50);
blue = TH0 * 256 + TL0;
TH0 = 0;
TL0 = 0;
if(red > 500 && green < 400 && blue < 400)
{
LED1 = 1;
LED2 = 0;
LED3 = 0;
return 0;
}
else if(red < 400 && green > 500 && blue < 400)
{
LED1 = 0;
LED2 = 1;
LED3 = 0;
return 1;
}
else if(red < 400 && green < 400 && blue > 500)
{
LED1 = 0;
LED2 = 0;
LED3 = 1;
return 2;
}
else if(red > 500 && green > 500 && blue < 400)
{
LED1 = 1;
LED2 = 1;
LED3 = 0;
return 3;
}
else if(red > 500 && green < 400 && blue > 500)
{
LED1 = 1;
LED2 = 0;
LED3 = 1;
return 4;
}
else
{
LED1 = 1;
LED2 = 1;
LED3 = 1;
return 5;
}
}
void send_data(uchar dat)
{
SBUF = dat;
while(TI == 0);
TI = 0;
}
void delay(uint i)
{
uint j, k;
for(j = i; j > 0; j--)
{
for(k = 110; k > 0; k--);
}
}
void UART() interrupt 4
{
uchar receive_data;
if(RI == 1)
{
receive_data = SBUF;
RI = 0;
}
}
```
其中,使用了TCS3200模块进行颜色检测,并根据颜色的RGB值进行判断。在get_color()函数中,通过设置S2、S3引脚的高低电平状态,以及OUT引脚的电平状态,分别读取红、绿、蓝三个颜色通道的值。然后根据这三个值的大小关系进行颜色判断,并点亮相应的LED灯。最后通过串口将颜色信息发送出去,可以通过串口调试助手查看。
阅读全文