Adafruit_VCNL4000.cpp
1 // SPDX-FileCopyrightText: 2019 Anne Barela for Adafruit Industries 2 // 3 // SPDX-License-Identifier: MIT 4 5 #include "Arduino.h" 6 #include "Wire.h" 7 8 #include "Adafruit_VCNL4000.h" 9 10 11 bool Adafruit_VCNL4000::begin() { 12 Wire.begin(); 13 14 // Check VCNL4000 product ID and fail if not expected value. 15 uint8_t rev = read8(VCNL4000_PRODUCTID); 16 if ((rev & 0xF0) != 0x10) { 17 return false; 18 } 19 20 // Set IR LED current to 200mA. 21 write8(VCNL4000_IRLED, 20); // set to 20 * 10mA = 200mA 22 23 // Set proximity adjustment value. 24 write8(VCNL4000_PROXINITYADJUST, 0x81); 25 26 return true; 27 } 28 29 uint16_t Adafruit_VCNL4000::readProximity() { 30 write8(VCNL4000_COMMAND, VCNL4000_MEASUREPROXIMITY); 31 while (1) { 32 uint8_t result = read8(VCNL4000_COMMAND); 33 //Serial.print("Ready = 0x"); Serial.println(result, HEX); 34 if (result & VCNL4000_PROXIMITYREADY) { 35 return read16(VCNL4000_PROXIMITYDATA); 36 } 37 delay(1); 38 } 39 } 40 41 // Read 1 byte from the VCNL4000 at 'address' 42 uint8_t Adafruit_VCNL4000::read8(uint8_t address) 43 { 44 uint8_t data; 45 46 Wire.beginTransmission(VCNL4000_ADDRESS); 47 #if ARDUINO >= 100 48 Wire.write(address); 49 #else 50 Wire.send(address); 51 #endif 52 Wire.endTransmission(); 53 54 delayMicroseconds(170); // delay required 55 56 Wire.requestFrom(VCNL4000_ADDRESS, 1); 57 while(!Wire.available()); 58 59 #if ARDUINO >= 100 60 return Wire.read(); 61 #else 62 return Wire.receive(); 63 #endif 64 } 65 66 67 // Read 2 byte from the VCNL4000 at 'address' 68 uint16_t Adafruit_VCNL4000::read16(uint8_t address) 69 { 70 uint16_t data; 71 72 Wire.beginTransmission(VCNL4000_ADDRESS); 73 #if ARDUINO >= 100 74 Wire.write(address); 75 #else 76 Wire.send(address); 77 #endif 78 Wire.endTransmission(); 79 80 Wire.requestFrom(VCNL4000_ADDRESS, 2); 81 while(!Wire.available()); 82 #if ARDUINO >= 100 83 data = Wire.read(); 84 data <<= 8; 85 while(!Wire.available()); 86 data |= Wire.read(); 87 #else 88 data = Wire.receive(); 89 data <<= 8; 90 while(!Wire.available()); 91 data |= Wire.receive(); 92 #endif 93 94 return data; 95 } 96 97 // write 1 byte 98 void Adafruit_VCNL4000::write8(uint8_t address, uint8_t data) 99 { 100 Wire.beginTransmission(VCNL4000_ADDRESS); 101 #if ARDUINO >= 100 102 Wire.write(address); 103 Wire.write(data); 104 #else 105 Wire.send(address); 106 Wire.send(data); 107 #endif 108 Wire.endTransmission(); 109 }