Monday, August 24, 2020

Wio Terminal: Read Light Sensor and display on LCD graphically


The light sensor on Wio Terminal uses Analog interface and you can simply read the surrounding Light sensor values via reading its pin.

This exercise run on Wio Terminal (using Arduino framework) to read the built-in light sensor in 10ms interval, and display on the LCD screen graphically.

Also, the time to perform the job is displayed as info for reference.

Wio_LightSensor.ino

#include <SPI.h>
#include <TFT_eSPI.h>

TFT_eSPI tft = TFT_eSPI();

#define FrameOx 5
#define FrameOy 5
#define FrameWidth  300
#define FrameHeight 200

#define Title   "Wio Terminal Light Sensor"
#define TitleX  FrameOx
#define TitleY  210
#define InfoX   FrameOx
#define InfoY   230

#define BUFFER_SIZE 300
#define MAX_VAL 200
int BufferSensorVal[BUFFER_SIZE];

int sampling;

// interval at which to sample light sensor (milliseconds)
const long interval = 10;
unsigned long previousMillis = 0;

void drawFrame(){
  tft.fillRect(FrameOx, FrameOy, FrameWidth, FrameHeight, TFT_DARKGREY);
  tft.drawRect(FrameOx-1, FrameOy-1, FrameWidth+2, FrameHeight+2, TFT_LIGHTGREY);
}

void setup() {
  pinMode(WIO_LIGHT, INPUT);
  
  tft.init();
  tft.setRotation(3);
  tft.fillScreen(TFT_BLACK);

  tft.drawString(Title,TitleX,TitleY);

  for(int i=0; i<BUFFER_SIZE;i++)
  {
    int v = map(i, 0, BUFFER_SIZE, 0, MAX_VAL);
    BufferSensorVal[i] = 0;
  }

  sampling = 0;

}

void loop() {
  unsigned long currentMillis = millis();
  unsigned long startMicros = micros();

  if (currentMillis - previousMillis >= interval) {

    if(sampling == 0){
      drawFrame();
    }
    
    previousMillis = currentMillis;

    //Read Light Sensor and map to value suitable for display
    int light = analogRead(WIO_LIGHT);
    int lightVal = map(light, 0, 1024, 0, MAX_VAL);
    BufferSensorVal[sampling] = lightVal;

    tft.drawLine(sampling+FrameOx, FrameOy+MAX_VAL, 
          sampling+FrameOx,FrameOy+MAX_VAL-lightVal, TFT_WHITE);
    
    sampling++;
    if(sampling == BUFFER_SIZE){
      sampling = 0;
    }

    //How long to perform the drawing, 
    //for information only,in microsecond
    String strInfo = String(micros()-startMicros);
    tft.drawString("     ", InfoX, InfoY);
    tft.drawString(strInfo, InfoX, InfoY);

  }
}



No comments: