I’m a bit new to hardware and am having a a few issues reading some analog inputs.
Ideally, I’d like to be able to swap out inputs at anytime and have them report back to a web application. The code below loops over all pins, checks for update, and publishes a change if needed.
The digital portion works great, but only if I comment out the analog part. The analog never works What’s wrong with the below code? Am I overwhelming the stream? Is there some kind of interference that continually gets published? If I change the loop interval from 100 to 1000 milliseconds I start to see analog reporting, but I’m not manipulating anything ? Any ideas as to what might be wrong here?
Thanks,
Joe
int analogPins[] = {A0, A1, A2, A3, A4, A5, A6, A7};
int digitalPins[] = {D0, D1, D2, D3, D4, D5, D6, D7};
int digitalStates[] = {0, 0, 0, 0, 0, 0, 0};
int analogStates[] = {0, 0, 0, 0, 0, 0, 0};
int analogChangeThreshold = 5;
unsigned long lastTime = 0UL;
void loop()
{
unsigned long now = millis();
if(now-lastTime>100UL){
lastTime = now;
// Loop over the analog inputs and publish the read
// states if they've changed "enough" since the
// previous event loop
for(int a=0; a<8; a++){
int currentState = analogRead(analogPins[a]);
if(abs(analogStates[a] - currentState) > analogChangeThreshold){
analogStates[a] = currentState;
char publishString[64];
sprintf(publishString, "{ \"pinId\": \"A%u\", \"state\": %u }", a, currentState);
Spark.publish("input-update", publishString);
}
}
// Loop over the digital inputs and publish the read
// states if they've changed since the previous
// event loop
for(int d=0; d<8; d++){
int currentState = digitalRead(digitalPins[d]);
if(currentState != digitalStates[d]){
digitalStates[d] = currentState;
char publishString[64];
sprintf(publishString, "{ \"pinId\": \"D%u\", \"state\": %u }", d, currentState);
Spark.publish("input-update", publishString);
}
}
}
}```