Tired of Repeated Recurring Arduino Serial Monitor Values? Try this-

The Serial monitor in the Arduino IDE is essential for simulating outputs and diagnosing problems in the circuit. However, depending on what your project does, the Serial monitor, not only helps you, but can also potentially drive you crazy with constant bombardment of serial values like this-

This makes it hard for you to extract the relevant values you're looking for.
Luckily, there's a simple solution to the problem. A minor change in code can get it to work perfectly. 
NOW, if you simple want to just slow down the fast updating Serial Monitor, you can simply add a small delay after each print.


Definitely, that's not the way to go about important values that you are dealing with.
So here's how you transform your code, to a serial friendly code.

Let's say you're reading values from an LDR using an analog pin as an INPUT pin and simultaneous printing them on the Serial monitor using a code like this-
void loop() {
// Variable declaration etc etc.....
// The remaining stuff..
Now if you wish to see the serial values only if there is a change observed in the consecutive value, You'll have to write something like this-
int lastValue,newValue;
int threshold=200; // The minimum change you're looking for, 

void loop() {
// Variable declarations, etc etc
if (newValue-lastValue > threshold) {
    Serial.print("Value increased to ");
if (lastValue-newValue < threshold) {
    Serial.print("Value decreased to ");
// remaining code...
Note that in the above code any consecutive values that differ by less than 200 won't be printed! This value can be adjusted by changing  threshold to the required value.
The basic idea of the code snippet is that we are using two variables, one that stores the present value of the pin and the other, that stores the previous/last value of the pin.by measuring the difference between the two, you can understand whether the pin has undergone any significant change of value.
This is just perfect if you're using an LDR, to detect the lighting conditions of the room. Also notice that after each iteration, we update lastValue to newValue making the code reusable again for the next loop iteration!


Post a Comment

Popular Posts