YOGYUI

Adafruit TCS34725 RGB Color Sensor with IR Filter & LED 본문

Hardware/Sensor

Adafruit TCS34725 RGB Color Sensor with IR Filter & LED

요겨 2021. 2. 14. 17:23
반응형

Adafruit TCS34725 RGB Sensor 모듈

1. Hardware

TAOS(Texas Advanced Optoelectronic Solutions)사에서 만든 TCS34725 RGB Sensor와 함께 조명을 위한 white LED 및 적외선(IR) 필터가 함께 장착된 breakout 보드

(TAOS사는 2011년에 ams AG사에 인수되어 지금은 AMS-TAOS USA Inc.로 검색할 수 있다)

Adafruit 공식 소개 페이지: RGB Color Sensor with IR filter and White LED - TCS34725

TCS34725 IC의 통신방식은 I2C이며, LED는 MCU의 GPIO로 제어하거나 인터럽트로 On/Off 제어가 되도록 설계되었다

 

센서모듈 근방에 접근한 물체의 색을 읽어 내장된 4종의 Photo-Diode (Red, Green, Blue, Clear Light = RGBC) 각각에 조사된 빛의 세기를 ADC를 거쳐 디지털 값으로 출력한다

모든 PD는 IR 필터가 장착되어 있어 사람의 눈에 감지되지 않는 적외선은 걸러주기 때문에 더 정확한 색상값을 출력할 수 있다고 하며 Red, Green, Blue PD는 각각 빛의 3원색인 빨간색, 초록색, 파란색 빛만 통과시켜 각각의 세기를 출력할 수 있도록 하며, Clear Light는 어떠한 색상 필터도 거치지 않은 원색의 세기를 읽을 수 있다

(각 PD별 ADC는 16-bit resolution)

자세한 내용은 데이터시트를 참고하도록 하자

TCS34725 Features, 출처: 데이터시트
IC Diagram, 출처: 데이터시트

활용가능한 분야는 조명 동기화, 색상에 따른 물품 분류, 색온도 측정, 디스플레이 모듈 백라이트 제어 등이 있는데, 개인적으로는 어떻게 써야될지는 잘 모르겠다...

웨어러블 방식으로 구현한 예제는 링크를 참고

(2012년쯤에 호기심에 사고 한두번 다룬 뒤로는 창고에 박아뒀다...)

2. Prototyping

Adafruit은 Evaluation용 breakout 하드웨어와 함께 아두이노 라이브러리를 제공하는 아주 고마운 기업이다

(라즈베리파이를 위한 파이썬 라이브러리도 대부분 제공한다)

Adafruit TCS34725 Arduino Library

라이브러리 소스코드 링크: Adafruit TCS34725

 

Adruino Micro를 활용해서 프로토타이핑을 해보자

TCS34725 Module Arduino Micro
VIN +5V
GND GND
3V3 +3.3V
SCL GPIO3
SDA GPIO2
INT  
LED GPIO4

배선 Schmatic

인터럽트(INT)는 조명 원색(Clear Light)의 세기가 일정 범위 안에 들어오면 (Threshold 설정 가능) 신호 레벨이 LOW로 떨어지는 Active Low Signal Line이며, 주변 환경의 광량에 따라 측정 여부를 결정하고자 할 경우 사용하면 된다 (MCU의 인터럽트 기능을 활용하면 된다, 본 포스팅에서는 시연 제외, polling 방식으로만 센서 측정)

 

참고로 LED는 전원만 연결하였을 경우 default로 ON된다 (끄고자 할경우 GND에 핀을 연결하거나, GPIO로 끄거나 인터럽트 제어를 해야한다) LED 밝기가 꽤 쎄니 눈조심!

전원 연결시 LED가 자동으로 켜진다...눈뽕!

제대로 센서를 구동하기 위해 신경써야 할 두 가지 파라미터가 있다

  • Integration Time

  • Analog Gain

파라미터가 무엇을 뜻하는지 알려면 센서의 동작 과정을 알아야 한다

RGBC 동작 설명, 출처: 데이터시트
System Timing Diagram, 출처: 데이터시트

센서 Reading을 계속 활성화시켜둔 상태라면 (약자들은 각각 PON=Power On, WEN=Wait Enable, AEN=RGBC Enable을 가리키며, I2C 레지스터로 접근 및 제어 가능) RGBC 값 읽기 시퀀스 시 초기화는 2.4msec가 소요되며 이 후 총 256단계로 나누어진 Acquisition Time (범위=2.4msec ~ 614msec) 동안 ADC가 4종류 PD의 값으로 들어오는 빛의 세기를 읽어들인다(Integration Time동안 들어온 빛의 세기를 누적 합산) 즉, 카메라의 노출과 유사한 개념이라고 보면 될 것 같다

- 광량이 적은 환경에서 센서의 감도를 높이고자 할 경우 노출시간을 길게 설정하면 된다

 

Analog Gain은 카메라의 감도와 유사한 개념으로, PD로 읽은 빛의 세기를 ADC를 통해 디지털값으로 변환한 뒤 얼마나 '뻥튀기'해줄 것인가를 결정하며, 총 4단계 (x1, x4, x16, x60)로 설정할 수 있다

 

두 파라미터 모두 I2C로 레지스터에 값을 직접 쓰기하여 제어해야 하며, 아두이노 라이브러리에서는 다음과 같이 메서드로 정의해두었다 (두 입력변수 모두 열거형으로 사전정의해두었다)

typedef enum {
  TCS34725_INTEGRATIONTIME_2_4MS =
      0xFF, /**<  2.4ms - 1 cycle    - Max Count: 1024  */
  TCS34725_INTEGRATIONTIME_24MS =
      0xF6, /**<  24ms  - 10 cycles  - Max Count: 10240 */
  TCS34725_INTEGRATIONTIME_50MS =
      0xEB, /**<  50ms  - 20 cycles  - Max Count: 20480 */
  TCS34725_INTEGRATIONTIME_101MS =
      0xD5, /**<  101ms - 42 cycles  - Max Count: 43008 */
  TCS34725_INTEGRATIONTIME_154MS =
      0xC0, /**<  154ms - 64 cycles  - Max Count: 65535 */
  TCS34725_INTEGRATIONTIME_700MS =
      0x00 /**<  700ms - 256 cycles - Max Count: 65535 */
} tcs34725IntegrationTime_t;

typedef enum {
  TCS34725_GAIN_1X = 0x00,  /**<  No gain  */
  TCS34725_GAIN_4X = 0x01,  /**<  4x gain  */
  TCS34725_GAIN_16X = 0x02, /**<  16x gain */
  TCS34725_GAIN_60X = 0x03  /**<  60x gain */
} tcs34725Gain_t;

void Adafruit_TCS34725::setIntegrationTime(tcs34725IntegrationTime_t it) {
  if (!_tcs34725Initialised)
    begin();

  /* Update the timing register */
  write8(TCS34725_ATIME, it);

  /* Update value placeholders */
  _tcs34725IntegrationTime = it;
}

void Adafruit_TCS34725::setGain(tcs34725Gain_t gain) {
  if (!_tcs34725Initialised)
    begin();

  /* Update the timing register */
  write8(TCS34725_CONTROL, gain);

  /* Update value placeholders */
  _tcs34725Gain = gain;
}

클래스 초기화 시 integraion time과 gain을 설정할 수 있으며 default값은 각각 2.4ms, x1이다

class Adafruit_TCS34725 {
public:
  Adafruit_TCS34725(tcs34725IntegrationTime_t = TCS34725_INTEGRATIONTIME_2_4MS,
                    tcs34725Gain_t = TCS34725_GAIN_1X);
}

환경에 따라 적절하게 변경할 수 있도록 코드를 구성하면 된다 (본 포스팅에서 따로 시연하지는 않음)

 

다음과 같이 시리얼 통신으로 LED 켜고 끄기, Gain 조정, Integration Time 조정할 수 있는 기능을 구현해보았다

#include "Adafruit_TCS34725.h"

Adafruit_TCS34725 tcs = Adafruit_TCS34725();
bool bInit = false;
int LED_PIN = 4;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
  digitalWrite(LED_PIN, LOW);
}

bool checkSensor() {
  if (!bInit){
    if (tcs.begin()) {
      Serial.println("TCS34725 Initialized");
      bInit = true;
    } else {
      Serial.println("Failed to initialize TCS34725");
      delay(1000);
      bInit = false;
    }
  }
  
  return bInit;
}

void loop() {
  while (Serial.available() > 0) {
    int command = Serial.parseInt();
    if (command >= 10 && command < 20) {
      // start with '1' = LED Control
      if (command - 10 > 0){
        Serial.println("Command: LED ON");
        digitalWrite(LED_PIN, HIGH);
      } else {
        Serial.println("Command: LED OFF");
        digitalWrite(LED_PIN, LOW);
      }
    } else if (command >= 20 && command < 30) {
      // start with '2' = Gain Control
      int temp = command - 20;
      switch(temp){
        case 0:
          Serial.println("Command: Set Gain 1X");
          tcs.setGain(TCS34725_GAIN_1X);
          break;
        case 1:
          Serial.println("Command: Set Gain 4X");
          tcs.setGain(TCS34725_GAIN_4X);
          break;
        case 2:
          Serial.println("Command: Set Gain 16X");
          tcs.setGain(TCS34725_GAIN_16X);
          break;
        case 3:
          Serial.println("Command: Set Gain 60X");
          tcs.setGain(TCS34725_GAIN_60X);
          break;
        default:
          break;
      }
    } else if (command >= 30 && command < 40) {
      // start with '3' = Integration Time Control
      int temp = command - 30;
      switch (temp){
        case 0:
          Serial.println("Command: Set Integration Time 2.4ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_2_4MS);
          break;
        case 1:
          Serial.println("Command: Set Integration Time 24ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_24MS);
          break;
        case 2:
          Serial.println("Command: Set Integration Time 50ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_50MS);
          break;
        case 3:
          Serial.println("Command: Set Integration Time 101ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_101MS);
          break;
        case 4:
          Serial.println("Command: Set Integration Time 154ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_154MS);
          break;
        case 5:
          Serial.println("Command: Set Integration Time 700ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_700MS);
          break;
        default:
          break;
      }
    }
  }
  
  if (checkSensor()) {
    uint16_t r, g, b, c;

    tcs.getRawData(&r, &g, &b, &c);
    // colorTemp = tcs.calculateColorTemperature(r, g, b);
    uint16_t colorTemp = tcs.calculateColorTemperature_dn40(r, g, b, c);
    uint16_t lux = tcs.calculateLux(r, g, b);
  
    Serial.print("Color Temp: "); Serial.print(colorTemp, DEC); Serial.print(" K - ");
    Serial.print("Lux: "); Serial.print(lux, DEC); Serial.print(" - ");
    Serial.print("R: "); Serial.print(r, DEC); Serial.print(" ");
    Serial.print("G: "); Serial.print(g, DEC); Serial.print(" ");
    Serial.print("B: "); Serial.print(b, DEC); Serial.print(" ");
    Serial.print("C: "); Serial.print(c, DEC); Serial.print(" ");
    Serial.println(" ");
  }
  delay(100);
}

시리얼 출력 예시

Command: Set Integration Time 154ms
Command: LED ON
Color Temp: 3020 K - Lux: 70 - R: 159 G: 109 B: 68 C: 340  
Color Temp: 3011 K - Lux: 232 - R: 555 G: 371 B: 236 C: 1193  
Color Temp: 2999 K - Lux: 1060 - R: 1971 G: 1463 B: 832 C: 4405  
Color Temp: 2419 K - Lux: 539 - R: 1876 G: 964 B: 510 C: 3340  
Color Temp: 2345 K - Lux: 500 - R: 1961 G: 952 B: 499 C: 3391  
Color Temp: 2338 K - Lux: 506 - R: 2019 G: 972 B: 508 C: 3482  
Color Temp: 3062 K - Lux: 481 - R: 1085 G: 749 B: 476 C: 2383

센서에 물체를 근접시키면 RGB값이 변화되는 것을 볼 수 있다

적당히 밝은 환경에서는 LED를 켜고 Integration Time을 50ms나 101ms 수준으로 설정하면 색이 서로 다른 물체들에 대해 RGB가 명확히 다른 값이 측정되는 것을 볼 수 있다

 

라이브러리는 색온도(Color Temperature)를 계산하는 두 종류의 알고리즘을 제공한다

calculateColorTemperature_dn40 메서드는 AMS사의 Application Note DN40: Lux and CCT Calculations using ams Color Sensors에 나와있는 공식을 수식으로 구현해둔 것이며 관련 수식은 링크에서 참고하면 된다

주석처리되어있는 calculateColorTemperature은 MaCamy's approximation을 구현한 코드이다

(색온도라는 개념 자체가 사진이나 영상처리를 전문적으로 하거나 혹은 디스플레이 업계에 종사하지 않는 일반인에게는 생소한 개념일 수 있다...본인도 TV나 모니터에 색온도 조절 기능이 있다는 정도만 알았지, 이정도로 심오한 개념일줄은 몰랐다, 위키피디아에 자세하게 설명되어 있으니 참고)

3. Advanced

RGB값을 텍스트로만 뿌리면 별로 재미가 없다

ESP8266 모듈을 통해 웹서버로 RGB값을 전송한 뒤, 웹서버는 웹페이지의 배경색을 측정된 RGB값으로 변경하는 Tiny Project를 진행해보았다 (측정 데이터 전송 및 센서 제어는 MQTT 프로토콜 활용)

 

[아두이노(ESP8266) 소스코드]

- JSON 해석을 위해 ArduinoJson 라이브러리 사용

- MQTT Publish/Subscribe 위해 PubSubClient 라이브러리 사용

#include "Adafruit_TCS34725.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

Adafruit_TCS34725 tcs = Adafruit_TCS34725();
bool sensor_init = false;
int LED_PIN = 16;

char publish_msg[256];
StaticJsonDocument<256> json_doc;
long last_acq_time = 0;

const char* WIFI_SSID = "당신의 WiFi SSID";
const char* WIFI_PW = "당신의 WiFi Password";
const char* MQTT_BROKER_ADDR = "당신의 MQTT Broker 주소";
const int   MQTT_BROKER_PORT = 1883;
const char* MQTT_ID = "당신의 MQTT Broker ID"; // optional
const char* MQTT_PW = "당신의 MQTT Broker Password";  // optional

WiFiClient wifi_client;
PubSubClient mqtt_client(wifi_client);

void mqtt_callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  if (!strcmp(topic, "esp8266_test/rgbsensor/control")) {
    DynamicJsonDocument doc_temp(256);
    deserializeJson(doc_temp, payload);
    JsonVariant led = doc_temp["led"];
    JsonVariant gain = doc_temp["gain"];
    JsonVariant it_time = doc_temp["it"];

    if (!led.isNull()) {
      if (led.as<int>()) {
        Serial.println("Command: LED ON");
        digitalWrite(LED_PIN, HIGH);
      } else {
        Serial.println("Command: LED OFF");
        digitalWrite(LED_PIN, LOW);
      }
    }
    if (!gain.isNull()) {
      switch(gain.as<int>()) {
        case 0:
          Serial.println("Command: Set Gain 1X");
          tcs.setGain(TCS34725_GAIN_1X);
          break;
        case 1:
          Serial.println("Command: Set Gain 4X");
          tcs.setGain(TCS34725_GAIN_4X);
          break;
        case 2:
          Serial.println("Command: Set Gain 16X");
          tcs.setGain(TCS34725_GAIN_16X);
          break;
        case 3:
          Serial.println("Command: Set Gain 60X");
          tcs.setGain(TCS34725_GAIN_60X);
          break;
        default:
          break;
      }
    }
    if (!it_time.isNull()) {
      switch (it_time.as<int>()) {
        case 0:
          Serial.println("Command: Set Integration Time 2.4ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_2_4MS);
          break;
        case 1:
          Serial.println("Command: Set Integration Time 24ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_24MS);
          break;
        case 2:
          Serial.println("Command: Set Integration Time 50ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_50MS);
          break;
        case 3:
          Serial.println("Command: Set Integration Time 101ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_101MS);
          break;
        case 4:
          Serial.println("Command: Set Integration Time 154ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_154MS);
          break;
        case 5:
          Serial.println("Command: Set Integration Time 700ms");
          tcs.setIntegrationTime(TCS34725_INTEGRATIONTIME_700MS);
          break;
        default:
          break;
      }
    }
  }
}

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);
  Serial.begin(115200);

  WiFi.begin(WIFI_SSID, WIFI_PW);
  Serial.print("WiFi Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  Serial.printf("MAC address = %s\n", WiFi.softAPmacAddress().c_str());

  // setup MQTT Client
  mqtt_client.setServer(MQTT_BROKER_ADDR, MQTT_BROKER_PORT);
  mqtt_client.setCallback(mqtt_callback);
}

void establish_mqtt_connection() {
  if (mqtt_client.connected())
    return;
  while (!mqtt_client.connected()) {
    Serial.println("Try to connect MQTT Broker");
    if (mqtt_client.connect("ESP8266_Client", MQTT_ID, MQTT_PW)) {
      Serial.println("Connected");
      mqtt_client.subscribe("esp8266_test/rgbsensor/control");
    } else {
      Serial.print("failed, rc=");
      Serial.print(mqtt_client.state());
      delay(2000);
    }
  }
}

bool checkSensor() {
  if (!sensor_init) {
    if (tcs.begin()) {
      Serial.println("TCS34725 Initialized");
      sensor_init = true;
    } else {
      Serial.println("Failed to initialize TCS34725");
      delay(1000);
      sensor_init = false;
    }
  }
  
  return sensor_init;
}

void loop() {
  establish_mqtt_connection();
  mqtt_client.loop();

  if (checkSensor()) {
    uint16_t r, g, b, c;
    tcs.getRawData(&r, &g, &b, &c);
    uint16_t colorTemp = tcs.calculateColorTemperature_dn40(r, g, b, c);
    uint16_t lux = tcs.calculateLux(r, g, b);

    long current = millis();
    if (current - last_acq_time > 2000) {
      last_acq_time = current;
      json_doc["red"] = r;
      json_doc["green"] = g;
      json_doc["blue"] = b;
      json_doc["clear"] = c;
      json_doc["temp"] = colorTemp;
      json_doc["lux"] = lux;
      size_t n = serializeJson(json_doc, publish_msg);
      mqtt_client.publish("esp8266_test/rgbsensor/data", publish_msg, n);
      Serial.print("Published (esp8266_test/rgbsensor/data): ");
      Serial.println(publish_msg);
    }
  }
}

[웹서버 코드 (Python, Flask)]

import json
import paho.mqtt.client as mqtt
from flask import Flask, render_template, jsonify, request, redirect, url_for

class SensorData:
    red: int = 0
    green: int = 0
    blue: int = 0
    clear: int = 0
    temp: int = 0
    lux: int = 0

def set_led(onoff: int):
    obj = {'led': onoff}
    mqtt_client.publish("esp8266_test/rgbsensor/control", json.dumps(obj), 1)

def set_gain(gain: int):
    obj = {'gain': gain}
    mqtt_client.publish("esp8266_test/rgbsensor/control", json.dumps(obj), 1)

def set_integrate_time(it: int):
    obj = {'it': it}
    mqtt_client.publish("esp8266_test/rgbsensor/control", json.dumps(obj), 1)

data = SensorData()
app = Flask(__name__)
mqtt_client = mqtt.Client()
mqtt_client.username_pw_set(
    username="MQTT Broker ID", 
    password="MQTT Broker Password"
)

@app.route('/')
def index():
    return render_template('index.html', sensor_data=data)

@app.route('/update', methods=['POST'])
def update():
    return jsonify({
        'red': data.red,
        'green': data.green,
        'blue': data.blue,
        'clear': data.clear,
        'temp': data.temp,
        'lux': data.lux
    })

@app.route('/control', methods=['POST'])
def control():
    if request.method == 'POST':
        if request.form.get('led_on'):
            set_led(1)
        elif request.form.get('led_off'):
            set_led(0)

        if request.form.get('gain_x1'):
            set_gain(0)
        elif request.form.get('gain_x4'):
            set_gain(1)
        elif request.form.get('gain_x16'):
            set_gain(2)
        elif request.form.get('gain_x60'):
            set_gain(3)

        if request.form.get('it_2_4'):
            set_integrate_time(0)
        elif request.form.get('it_24'):
            set_integrate_time(1)
        elif request.form.get('it_50'):
            set_integrate_time(2)
        elif request.form.get('it_101'):
            set_integrate_time(3)
        elif request.form.get('it_154'):
            set_integrate_time(4)
        elif request.form.get('it_700'):
            set_integrate_time(5)
    return redirect(url_for('index'))

def on_mqtt_connect(client, userdata, flags, rc):
    mqtt_client.subscribe('esp8266_test/rgbsensor/data')

def on_mqtt_message(client, userdata, message):
    print(f'Message: {message.topic}, {message.payload}')
    if message.topic == 'esp8266_test/rgbsensor/data':
        msg_dict = json.loads(message.payload.decode("utf-8"))
        data.red = msg_dict['red']
        data.green = msg_dict['green']
        data.blue = msg_dict['blue']
        data.clear = msg_dict['clear']
        data.temp = msg_dict['temp']
        data.lux = msg_dict['lux']

def on_mqtt_publish(client, userdata, mid):
    print(f'Publish: {userdata}')

mqtt_client.on_message = on_mqtt_message
mqtt_client.on_publish = on_mqtt_publish
mqtt_client.on_connect = on_mqtt_connect

if __name__ == '__main__':
    mqtt_client.connect('MQTT Broker 주소', 1883)
    mqtt_client.loop_start()
    app.run(host='127.0.0.1', port=9999, debug=True)
    mqtt_client.loop_stop()
    mqtt_client.disconnect()

[템플릿 HTML]

<!-- index.html -->
<!DOCTYPE html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <a>RED</a>
    <h2 id="red">
        {% if sensor_data %}
            {{ sensor_data["red"] }}
        {% endif %}
    </h2>
    <a>GREEN</a>
    <h2 id="green">
        {% if sensor_data %}
            {{ sensor_data["green"] }}
        {% endif %}
    </h2>
    <a>BLUE</a>
    <h2 id="blue">
        {% if sensor_data %}
            {{ sensor_data["blue"] }}
        {% endif %}
    </h2>
    <a>CLEAR</a>
    <h2 id="clear">
        {% if sensor_data %}
            {{ sensor_data["clear"] }}
        {% endif %}
    </h2>
    <a>COLOR TEMPERAURE</a>
    <h2 id="temp">
        {% if sensor_data %}
            {{ sensor_data["temp"] }}
        {% endif %}
    </h2>
    <a>LUX</a>
    <h2 id="lux">
        {% if sensor_data %}
            {{ sensor_data["lux"] }}
        {% endif %}
    </h2>

    <form method="post" action="control">
        <input type="submit" value="LED ON" name="led_on"/>
        <input type="submit" value="LED OFF" name="led_off"/>
    </form>
    <form method="post" action="control">
        <input type="submit" value="GAIN x1" name="gain_x1"/>
        <input type="submit" value="GAIN x4" name="gain_x4"/>
        <input type="submit" value="GAIN x16" name="gain_x16"/>
        <input type="submit" value="GAIN x60" name="gain_x60"/>
    </form>
    <form method="post" action="control">
        <input type="submit" value="IT 2.4ms" name="it_2_4"/>
        <input type="submit" value="IT 24ms" name="it_24"/>
        <input type="submit" value="IT 50ms" name="it_50"/>
        <input type="submit" value="IT 101ms" name="it_101"/>
        <input type="submit" value="IT 154ms" name="it_154"/>
        <input type="submit" value="IT 700ms" name="it_700"/>
    </form>

    <script> setInterval(function(){$.ajax({
        url: '/update',
        type: 'POST',
        success: function(response) {
            console.log(response);
            $("#red").html(response["red"]);
            $("#green").html(response["green"]);
            $("#blue").html(response["blue"]);
            $("#clear").html(response["clear"]);
            $("#temp").html(response["temp"]);
            $("#lux").html(response["lux"]);

            var rval = parseInt(response["red"] / 65536 * 255);
            var gval = parseInt(response["green"] / 65536 * 255);
            var bval = parseInt(response["blue"] / 65536 * 255);
            var clr = "#" + rval.toString(16) + gval.toString(16) + bval.toString(16);
            document.body.style.background = clr;
        },
        error: function(error) {
            console.log(error);
        }
    })}, 2000);
    </script>
</body>

[DEMO]

테스트에 사용할 적당한 시료가 없어서 책상에 있던 포스트잇으로 해봤는데, LED 빛이 반사되면서 읽는 값은 실제 눈으로 보는 값과는 다소 차이가 있는 것으로 보인다

2초에 한번씩 값을 업데이트하도록 해서 반응속도가 많이 느린 감이 있다

끝~!

반응형
Comments