Hi there!
Let's start off by saying I'm an ultra beginner in programming. I am at the point of copying code and smashing two things together, adding the super basic stuff. The code I am trying to write has to get ESP8266 (D1 mini clone) talking, one taking as much analog reads as possible and spitting out the highest value within a period of time over I2C to the second. I was trying to see how many times the code runs between Wire.writes, and with a request every approximate 10ms the void loop runs about 1500 times, but when I paste in my analogRead code in the loop keeping track of time and the highest value taken it's all over the place. It seems to slow the code down a LOT but also miss a heck of a lot of request events. It now runs between 92 and 1182 from what I've seen in the serial monitor.
What am I doing wrong here?
#include <Wire.h>
int timePassed = 0;
int val;
int highVal;
int mills;
int millsLast;
int highResetInterval = 20;
enum REQUEST_TYPE {
NONE = -1,
GET_NAME = 0,
GET_VAL
};
void requestEvent();
void receiveEvent(int numBytes);
REQUEST_TYPE request = NONE;
void setup() {
Wire.begin(0x12);
Serial.begin(115200);
while (!Serial){}
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
void loop() {
mills = millis();
val = analogRead(A0);
if(mills - millsLast >= highResetInterval){
highVal = val;
millsLast = mills;
}
if(val>highVal){
highVal = val;
}
timePassed++;
}
void requestEvent() {
switch (request) {
case GET_VAL:
Wire.write((byte)highVal);
Serial.println(timePassed);
timePassed = 0;
request = NONE;
break;
default:
break;
}
}
void receiveEvent(int numBytes) {
if (numBytes==1){
int requestVal = Wire.read();
request = static_cast<REQUEST_TYPE>(requestVal);
}else{
}
}