title: Oscillating signal on a digital output of AVR ATmega32U4
body: <p>I set up my Atmel ATMega32U4 with a relay (using an NPN transistor to control the 5V supply to the relay, not driving it directly with the microcontroller). I want to use PD4 as a digital output to control the relay's state. As I'll be using USB communication later, I've got an external crystal oscillator attached, so I set the appropriate fuse and left the others at their default.</p>
  
  <p>When I run a very simple program like the one below, which should just switch the relay on once, instead I hear the relay switching on and off rapidly at about 10 Hz.</p>
  
  <pre><code>#include &lt;avr/io.h&gt;
  
  int main(void)
  {
      // toggle PD4 as an output
      DDRD |= _BV(4);
  
      // set output high
      PORTD |= _BV(4);
  }
  </code></pre>
  
  <p>I noticed that commenting out the <code>PORTD |= _BV(4);</code> line stops the oscillation, but of course that doesn't solve my problem. It seems to be that line that's creating the problem, anyway.</p>
  
  <p>I'm using Atmel Studio 6.2, programming with JTAG via an Atmel-ICE programmer.</p>
  
  <p>Taking a wild stab in the dark, I guess it might have something to do with PD4's alternative function as <code>ICP1/ADC8</code> as shown in the <a href="http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf" rel="nofollow noreferrer">datasheet</a> (section 10.3.3, p78), but I don't know how to disable this functionality.</p>
  
  <p>Does anyone have any ideas where I'm going wrong?</p>