analogRead loop panic

Any idea why this would just lock up right away on me? I had a timer in there to slow it down, but started striping things out to troubleshoot.
Trying to A. get an idea of how fast this will sample, and B. Try to output values that are slightly slower then 60hz to see if graphing the wave will match oscilloscope output.

#include "application.h""
unsigned int nextTime =     0; 

void setup() {
 pinMode(A1, INPUT);
 Serial.begin(9600);
 while(!Serial.available()) Spark.process();  //Press any button to continue
}

void loop() {
    int volt = analogRead(1);
    Serial.println(volt+":"+millis());
}

HI @officeboy

I don't think the above line does what you wanted it to do. Since volt is an int type, adding it is doing arithmetic not string concatenation.

Try this instead:

Serial.print(volt);
Serial.print(":");
Serial.println(millis());

[EDIT] By the way, the 9600 baud character output will slow this down quite a bit but not to 60Hz.

Thanks,I knew serial output would slow me, that is why I was trying to lump them into one output. I suppose that int is also why I was unable to make the output into a string.

This gets it done too. But not really any faster. Fastest it will run is 6 milliseconds.

#include "application.h""
unsigned int nextTime =     0; 
String csv,volt;

void setup() {
 pinMode(A0, INPUT);
 Serial.begin(57600);
 while(!Serial.available()) Spark.process();  //Press any button to continue
}

void loop() {
    if (nextTime > millis()) {
    return;
    }
    
    csv = ";";
    volt = csv + millis();
    volt = volt + csv + analogRead(A0);
    //Serial.print(millis());
    //Serial.print(";");
    Serial.println(volt);
    
    nextTime = millis() + 10;
}

As far as I’m aware the baud rate setting does not make any difference when using the USB Serial. It’ll always be USB speed more like 115200.
And since the actual transfer doesn’t happen in Serial.println() but interrupt driven there shouldn’t be a direct correlation either.
But some speed gain might be in the use of write() instead of print().

Next, for max execution speed of loop() you might try out SYSTEM_MODE(MANUAL) - just add some means to reactivate OTA flashing otherwise you have to flash via USB.

Additionally there would be some ways to speed up your loop() but the accuracy of analogRead() will suffer if you get too quick.

@officeboy, just a few pointers. First, when using analogRead() there is no need to set the pinMode(). The analogRead() call does that implicitly. While connected to the Cloud, the loop() function gets delayed at regular intervals while servicing that connection. @ScruffR is correct about using MANUAL mode for fastest loop() time.

If you want a more deterministic sampling approach, you may want to use SparkIntervalTimer and read/queue the analog via a timer interrupt. I believe if you search the Community you will find a topic on this, if I recall. :smile:

3 Likes