So I'm new to coding and I'm trying to incorporate a function that will read a sensor five times with analogRead() and calculate the average of five readings. It then should scale the data to 8 bits (0-255), and inverts it, returning the inverted result.
I roughly know the code I need to add is:
int ReadSens_and_Condition(){
int i;
int sval = 0;
for (i = 0; i < 5; i++){
sval = sval + analogRead(0); // sensor on analog pin 0
}
sval = sval / 5; // average
sval = sval / 4; // scale to 8 bits (0 - 255)
sval = 255 - sval; // invert output
return sval;
}
But I am unsure where to add this into my code here:
/*
The following code is to test your LCD with the I2C connector. Make sure to connect the 5V, GND, SCL, and SDA pins. Also, make sure to install the LiquidCrystal library.
*/
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27 // <<----- Add your address here. Find it from I2C Scanner
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
int a = 1;
LiquidCrystal_I2C lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);
void setup()
{
lcd.begin (16, 2); // <<----- My LCD was 16x2
// Switch on the backlight
lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
lcd.setBacklight(HIGH);
lcd.home (); // go home
lcd.print("Yeah! It prints");
lcd.setCursor (0, 1); // go to start of 2nd line
lcd.print(a);
delay(2000);
lcd.clear();
}
void loop()
{
int QRE_value=analogRead(0); // note that this should be connected to the analog pin # in parantheses
// The following lines have the LCD update every 150 ms the value of QRE
static uint8_t lastDisplayTime;
if ((uint8_t)(millis() - lastDisplayTime) >= 100)
{
lastDisplayTime = millis();
// Update the LCD with new value of QRE
lcd.clear();
lcd.print("QRE Value");
lcd.setCursor(0, 1);
lcd.print(QRE_value);
}
}
Any pointers and help are appreciated, thank you. I also apologize if the formatting of my question turns out questionable. This is my first time posting.