Instructables

Step 2: Basic Example for Arduino

Here's an example to graph an analog sensor, such as a potentiometer. The analog pin is A0 for these examples.

void setup() {
  Serial.begin(9600);
}

void loop() {
  // Analog Sensor Connected to analog pin 0
  int SensorVal = analogRead(A0);

  for(int i = 0; i < SensorVal; i++) {
    Serial.print("l");
  }
  Serial.println();
  delay(50);
}



Try it, you know you want to!

 When you do try it, you'll notice that the graph is sideways, and the bottom of the Serial Monitor shows the most recent reading of the Sensor.

You'll also notice that the graph can get quite long, and may be wrapped around to the next line if the windows isn't wide enough. To fix this we can use a function called map();

this will take in a minimum and maximum value for your sensor, and then scale it to a desirable output.

Here's how the code would look like for this example. Note, 1023 is the maximum output value for the analogRead() function. also note, we are scaling the analog read function to a value from 0 to 100. You will need to place this line of code before the for loop in the earlier example.

SensorVal = map(SensorVal, 0, 1023, 0, 100);

Here is the complete code for a scaled graph of an Analog sensor on analog pin 0.

void setup() {
  Serial.begin(9600);
}

void loop() {
  // Analog Sensor Connected to analog pin 0
  int SensorVal = analogRead(A0);

  SensorVal = map(SensorVal, 0, 1023, 0, 100);

  for(int i = 0; i < SensorVal; i++) {
    Serial.print("l");
  }
  Serial.println();
  delay(50);
}


 
Remove these adsRemove these ads by Signing Up