# Distance sensor

The distance sensor extension board is based on the **VCNL4040** by Vishay Semiconductors. The sensor uses I2C to communicate with the Picoclick (SDA = GPIO2, SCL = GPIO8). It has an ultra low power voltage regulator on board and can be used to activate the Picoclick by firing an interrupt. The interrupt can be configured via software.

## Hardware

### Overview

### Technical drawing

<figure><img src="https://3814073947-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F8e8Y0oYz6ujS2c1GD1Qy%2Fuploads%2FaktpKlHeFZtRcMNFvzz7%2Fpc3_ext_vcnl4040_techdraw.png?alt=media&#x26;token=45551a7c-4351-47f7-9217-795d608e3978" alt=""><figcaption></figcaption></figure>

* PCB: 18mm x 10mm
* Thickness: 1mm
* Mounting holes: 3.2mm
* Corner radius: 2mm

### Schematics

<figure><img src="https://3814073947-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F8e8Y0oYz6ujS2c1GD1Qy%2Fuploads%2Fd7xLlKxK9NG0Hpzy4Frm%2Fpc3_ext_vcnl4040_schematics.png?alt=media&#x26;token=614522f6-e483-4932-90e3-ee87dda7c421" alt=""><figcaption></figcaption></figure>

## Software

Hardwaretest can be found on [GitHub](https://github.com/makermoekoe/Picoclick-C3/tree/main/code/Picoclick_C3/PC3_Hardwaretest_Motion).

```
#include <Arduino.h>
#include <FastLED.h>
#include <Wire.h>
#include "SparkFun_VCNL4040_Arduino_Library.h"
#include "config.h"

VCNL4040 vcnl;

void setup(){
  pinMode(BUTTON_PIN, INPUT);
  pinMode(ADC_ENABLE_PIN, OUTPUT);
  pinMode(ADC_PIN, INPUT);
  analogReadResolution(12);
  digitalWrite(ADC_ENABLE_PIN, HIGH);

  WiFi.mode(WIFI_OFF);

  FastLED.addLeds<APA102, APA102_SDI_PIN, APA102_CLK_PIN, BGR>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
  delay(50);

  set_fastled(CRGB::Blue);
  
  Wire.begin(SDA_PIN, SCL_PIN);

  if(vcnl.begin() == false){
    printf("Device not found. Please check wiring.\r\n");
    set_fastled(CRGB::Red);
    while(1); //Freeze!
  }
}

unsigned long led_timer = millis();
int hue1 = 0, hue2 = 0;
int brightness = 255;
unsigned long t_sensor = 500;

void loop() {
  if(digitalRead(BUTTON_PIN) == 1){
    set_fastled(CRGB::Red);
    delay(1000);
    esp_deep_sleep_start();
  }

  if(millis() >= t_sensor + 100){
    t_sensor = millis();
    unsigned int proxValue = vcnl.getProximity();
    printf("Proximity: %i\r\n", proxValue);
  }

  if(millis() >= led_timer + 15){
    led_timer = millis();
    set_fastled(CHSV(hue1, 255, brightness), CHSV(hue2, 255, brightness));
    hue1 = (hue1 + 1)%255;
    hue2 = (hue1 + 127)%255;
  }
}
```
