PulseIn() function on the arduino UNO

Hello

I ran into a weird problem yesterday while testing the functionality of the pulseIn() command. For this, I tried inputting a square wave with an offset(bias) so it varied between 0and 5V which is ideal for Arduino UNO. I've initialized analog pin 0 and fed this modified square wave to the same. Additionally I used the code available on the arduino website which goes like this :

int analogPin = 0;
unsigned long duration;

void setup()
{
Serial.begin(9600);
pinMode(analogPin, INPUT);
}

void loop()
{
duration = pulseIn(analogPin, HIGH);
Serial.write(duration);
}

Oddly enough, as soon as I ran the program, a string of "hhhh..." started coming in. To make things worse, too much bad data in the form of special characters such as a # or a % etc, started arriving at the serial monitor on the second attempt. These results are driving me crazy. Please suggest a way forward.

PS. The frequency of the square wave used is 100Hz.

Thanks in advance
Teja

That compiled? It is missing a ; after Serial.begin(9600)

When you define it like that, you end up treating pin 0 as a digital input.
Try using 14 and make sure you are connecting to A0 and not 0.
Altho I don't see any Serial.print(), so no idea why anything was being sent out.

Under File:Preferences, check the verbose output boxes, see if any errors are occurring.

  Serial.write(duration);

That function prints an ASCII character defined by the given parameter (0-255). I don't think you want to do that. I think you want to use Serial.println(duration) which prints a human readable representation of its parameter.

Thanks for the reply,
I've corrected the line and used Serial.println instead. However, the readings on the serial monitor are not at all what's expected. The results are atrocious and this is a serious setback to a newbie like me :confused:
Do you think the baud rate I used is wrong? Will it impact when I use a square wave whose frequency is 100Hz on the analogPin 0 on the arduino UNO? Please enlighten me.
Thank you

The results are atrocious

Well, give them a serious "improve your grades or you're out" talking to.

Do you think the baud rate I used is wrong?

How can we tell? We can't see your results.

const byte timingPin = 2;
const byte PWMpin = 3;

void setup()
{
  Serial.begin(115200);
  pinMode(timingPin, INPUT);
  analogWrite (PWMpin, 64);  // 25% duty cycle or roughly
  // pin 2 jumpered to pin 3
}

void loop() 
{
  Serial.println (pulseIn (timingPin, HIGH));
}

produces results in the expected ~500us range

Altho I don't see any Serial.print(), so no idea why anything was being sent out.

Whoa, talk about being spaced out - totally overlooked this when I read the post: Serial.write(duration);

Whoa, talk about being spaced out

No, you were quite right - the "write" was edited-in after you posted.

Redemption! Thanks Awol.