include <Wire.h> // TCS34725 I2C address #define TCS34725ADDR 0x29 #define CMDBIT 0x80…
- User
include <Wire.h>
// TCS34725 I2C address #define TCS34725_ADDR 0x29 #define CMD_BIT 0x80
// Register addresses #define REG_ENABLE 0x00 #define REG_ATIME 0x01 #define REG_CONTROL 0x0F #define REG_AILTL 0x04 #define REG_AILTH 0x05 #define REG_AIHTL 0x06 #define REG_AIHTH 0x07
// ENABLE register bits #define ENABLE_PON 0x01 // Power ON #define ENABLE_AEN 0x02 // ADC Enable #define ENABLE_AIEN 0x10 // ALS Interrupt Enable
const int interruptPin = 2; // Digital pin connected to INT volatile bool interruptFlag = false; // Interrupt flag volatile uint16_t clearValue = 0; // Last clear value that triggered the interrupt
void handleInterruptISR() { interruptFlag = true; // Set the interrupt flag }
// Function to write an 8-bit value to a register void writeRegister(uint8_t reg, uint8_t value) { Wire.beginTransmission(TCS34725_ADDR); Wire.write(CMD_BIT | reg); // Command bit Wire.write(value); Wire.endTransmission(); }
// Function to write a 16-bit value to a register (little endian) void writeRegister16(uint8_t reg, uint16_t value) { Wire.beginTransmission(TCS34725_ADDR); Wire.write(CMD_BIT | reg); Wire.write((uint8_t)(value & 0xFF)); // Low byte Wire.write((uint8_t)((value >> 8) & 0xFF)); // High byte Wire.endTransmission(); }
// Function to read a 16-bit value from a register (little endian) uint16_t readRegister16(uint8_t reg) { Wire.beginTransmission(TCS34725_ADDR); Wire.write(CMD_BIT | reg); Wire.endTransmission(false); // Send restart Wire.requestFrom(TCS34725_ADDR, (uint8_t)2); if (Wire.available() >= 2) { uint16_t value = Wire.read(); value |= (Wire.read() << 8); return value; } return 0xFFFF; // Return invalid value if not available }
// Function to read an 8-bit value from a register uint8_t readRegister(uint8_t reg) { Wire.beginTransmission(TCS34725_ADDR); Wire.write(CMD_BIT | reg); // Command bit combined with register address Wire.endTransmission(false); // Send repeated start Wire.requestFrom(TCS34725_ADDR, (uint8_t)1); // Request 1 byte from the sensor if (Wire.available()) { return Wire.read(); // Read and return the byte } return 0xFF; // Return an invalid value if not available }
void setup() { Serial.begin(9600); Wire.begin();
pinMode(interruptPin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterruptISR, FALLING);
// Power on the sensor writeRegister(REG_ENABLE, ENABLE_PON); delay(3); // Wait for oscillator to stabilize
// Enable ADC writeRegister(REG_ENABLE, ENABLE_PON | ENABLE_AEN);
// Set integration time to 50 ms writeRegister(REG_ATIME, 0xEB); // 0xEB for 50 ms integration time writeRegister(REG_CONTROL, 0x00); // 1x gain
// Set the interrupt thresholds uint16_t clearThresholdLow = 1000; uint16_t clearThresholdHigh = 0xFFFF;
writeRegister16(REG_AILTL, clearThresholdLow); writeRegister16(REG_AIHTL, clearThresholdHigh);
- Assistant