Square wave not really square with direct port manipulation.

Hello everybody,

This is my first post in this great forum and I really hope to find an answer to my question here.
Couple of days ago a friend of mine gave me an Arduino Nano and I'm playing with it, but I'm facing a strange problem. The pulses generated by me are not really square as they should be. I'm trying to generate two pulses on two different digital pins. The problem exist on most digital pins, but not on all of them. For instance pins d13 and d8 work pretty well, but others not. You can see the scope images.

Here is the code:

void setup() {
  DDRB = DDRB | (1 < 5);
  DDRB = DDRB | 1;
}

void loop() {
  //Generate pulse with 70uS width on pin D13
  PORTB = PORTB | 1 << 5;
  delayMicroseconds(70);
  PORTB = PORTB & (~(1 << 5));

  //Wait for 20uS
  delayMicroseconds(20);

  //Generate pulse with 40uS width on pin D8
  PORTB = PORTB | 1;
  delayMicroseconds(40);
  PORTB = PORTB & (~1);

  //Wait for 1.6mS
  delayMicroseconds(1600);
}

Please, if you don't understand my English, just ask me and I will try to explain with different words.

Try doing the same thing with digitalWrite(). To me that looks like the Output impedance is really high, so some parasitic capacitance is smoothing out the waveform.
Just a guess.

Also, you posted the code that drives the pins that work. We need the non-working code to tell you what's wrong with it :slight_smile:

lg, couka

Hi couka,
I tried with digitalWrite() and it works perfect on all digital pins. Unfortunately digitalWrite() delays for approximately 5uS which is not fast enough to my project.

Please post the code that doesn't work.

In your picture, you added a label "You can see the problem". Well, no I can't. I can't see what, besides the sillyscope is connected to the pin that is causing the distortion. All the other wave forms look perfectly good, so it is NOT a code problem.

If it is not a programming problem why does it work perfectly with digitalWrite() on all pins? Why does the wave is perfectly square on pin D8, with the same setup and same oscilloscope? I did this experiment more than 10 times in the last day and the result is the same.

Here is the non working code:

void setup() {
  DDRB = DDRB | (1 << 5);
  DDRD = DDRD | (1 << 3);
}

void loop() {
  //Generate pulse with 70uS width on pin D13
  PORTB = PORTB | 1 << 5;
  delayMicroseconds(70);
  PORTB = PORTB & (~(1 << 5));

  //Wait for 20uS
  delayMicroseconds(20);

  //Generate pulse with 40uS width on pin D3
  PORTD = PORTD | (1 << 3);
  delayMicroseconds(40);
  PORTD = PORTD & (~1 << 3);

  //Wait for 1.6mS
  delayMicroseconds(1600);
}

  PORTD = PORTD & (~1 << 3);didn't you mean:
  PORTD = PORTD & ~(1 << 3);?

aarg, you just save me :slight_smile: I can't believe I did not spot this mistake whole day. Now it works. Thank you, man! Thank to all who replied to my post.