I wrote this code for a project -

int sensorpin = A5;           
int val = 0;
double avgval = 0;
int E1 = 11;
int brake = 12;
char data = ' ';

void setup()
  pinMode(E1, OUTPUT);   
  pinMode(brake, OUTPUT);
  pinMode(sensorpin, INPUT);

void loop()

  if (Serial.available()>0){
      data = Serial.read();

  val = analogRead(sensorpin);   
  avgval = average(val);
  double volt = (avgval*5)/1023;
  Serial.println (avgval);

  if (data == 'G'){
    analogWrite(E1, 255);
    digitalWrite(brake, LOW);

  if( volt > 1.5 && volt < 1.75 ){
    digitalWrite(brake, HIGH);

double average(double adc){
  int n = 1;
  double avg = 0.00, sum = 0.00;
    sum = sum + adc;
    avg = sum/25;
  return avg;

The code works fine, except for the fact that the Sharp IR sensor (GP2Y0A710K0F) outputs values which are wrong (by a HUGE distance), ONLY if in the void setup() function, the commands -

pinMode(E1, OUTPUT);  
pinMode(brake, OUTPUT);

are left uncommented. If I comment the above two statements, the sketch works fine.

What on earth is wrong here? I can't make out anything.


Not sure why commenting out those two lines makes a difference. I think we need to see a schematic to resolve this.


You do not use "pinMode" to setup an analog input!

Look at the examples on the "analogRead" page. Notice there is no setup needed for the analog pin. Just call "analogRead" like you are doing and everything should be fine.

  • 1
    And that was it! Removing the line pinMode(sensorpin, A5) and uncommenting the two lines solved my problem. Getting the expected readings now. Thanks very much! That was something I should have noticed long ago.
    – YaddyVirus
    Jul 4 '16 at 23:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.