Unexpected current reading when powering LED from ATmega328p IO pin
The pin on your MCU won't sustain a nominal voltage of 3.3 volts except under very light loading conditions. What I think is happening is that as you draw 17 mA, the pin voltage is drooping down to something smaller than 3.3 volts. You can check this with a multimeter of course.


  I would like my LED to run at 40mA


Trying to take 40 mA from your MCU pin is ill-advised - you should consider using a buffer transistor. Read this answer for clarification and note you should never design something that is close to abusing the absolute maximum ratings of a part.

If you look at the ATmega328p data sheet this table is in section 32.2. (Common DC Characteristics): -



With Vcc at 3 volts the output voltage is only guaranteed to be 2.3 volts at an ambient of 85 degC with 10 mA load. This is an effective output series resistance of 70 ohms. At 105 degC the output resistance is 90 ohms and, if you did a rough extrapolation to a lower temperature like 25 degC it might be 30 ohms or so. 

With a 40 mA demand placed on the pin this means the output voltage will drop from 3.3 volts to about 2.1 volts and this is less than the LED forward voltage. Sure you can try this and get something like 40 mA but there are no guarantees this will always happen. That is what the data sheets are for - to guide you in making some common-sense judgements.