TA的每日心情 | 开心 2024-5-26 11:02 |
---|
签到天数: 791 天 连续签到: 1 天 [LV.10]以坛为家III
|
本帖最后由 leo121_3006061 于 2018-1-17 00:15 编辑
正好前几天收到了stm32F091 nucleo开发板,试试这款Dfrobot的颜色传感器。
1. 硬件准备
开发板
tcs34725 color sensor
导线 4根
2连接方式(兼容ardunio的pin)
传感器===》Nucleo
SDA==>SDA/D14
SCL==》SCL/D15
注意不是A4,A5
2. 软件开发环境 mbed 在线编译
修改一下频率为(100000)原来是200000会报错
附上代码,非常简单- // Example program connecting to the TCS34725 Color Sensor to the K64F using I2C
- #include "mbed.h"
- I2C i2c(I2C_SDA, I2C_SCL); //pins for I2C communication (SDA, SCL)
- Serial pc(USBTX, USBRX);
- int sensor_addr = 41 << 1;
- DigitalOut green(LED1);
- int main() {
- pc.baud(9600);
- green = 1; // off
-
- // Connect to the Color sensor and verify whether we connected to the correct sensor.
-
- i2c.frequency(100000);//修改为100000,否则报错
-
- char id_regval[1] = {146};
- char data[1] = {0};
- i2c.write(sensor_addr,id_regval,1, true);
- i2c.read(sensor_addr,data,1,false);
-
- if (data[0]==68) {
- green = 0;
- wait (2);
- green = 1;
- } else {
- green = 1;
- }
-
- // Initialize color sensor
-
- char timing_register[2] = {129,0};
- i2c.write(sensor_addr,timing_register,2,false);
-
- char control_register[2] = {143,0};
- i2c.write(sensor_addr,control_register,2,false);
-
- char enable_register[2] = {128,3};
- i2c.write(sensor_addr,enable_register,2,false);
-
- // Read data from color sensor (Clear/Red/Green/Blue)
-
- while (true) {
- char clear_reg[1] = {148};
- char clear_data[2] = {0,0};
- i2c.write(sensor_addr,clear_reg,1, true);
- i2c.read(sensor_addr,clear_data,2, false);
-
- int clear_value = ((int)clear_data[1] << 8) | clear_data[0];
-
- char red_reg[1] = {150};
- char red_data[2] = {0,0};
- i2c.write(sensor_addr,red_reg,1, true);
- i2c.read(sensor_addr,red_data,2, false);
-
- int red_value = ((int)red_data[1] << 8) | red_data[0];
-
- char green_reg[1] = {152};
- char green_data[2] = {0,0};
- i2c.write(sensor_addr,green_reg,1, true);
- i2c.read(sensor_addr,green_data,2, false);
-
- int green_value = ((int)green_data[1] << 8) | green_data[0];
-
- char blue_reg[1] = {154};
- char blue_data[2] = {0,0};
- i2c.write(sensor_addr,blue_reg,1, true);
- i2c.read(sensor_addr,blue_data,2, false);
-
- int blue_value = ((int)blue_data[1] << 8) | blue_data[0];
-
- // print sensor readings
-
- pc.printf("Clear (%d), Red (%d), Green (%d), Blue (%d)\r\n", clear_value, red_value, green_value, blue_value);
- wait(0.5);
- }
-
- }
复制代码 下载编译结果,打开串口助手之类的,使用三种颜色来实验,结果如下(传感器不能离的太近,否则数值飙升)
使用红色的时候,红色值偏大,使用蓝色,蓝色值偏大,另外两个值基本固定在100多不到200.
最后来张合影
|
|