D40 should have a 'B' or BULB setting where you can leave it on as long as you like... or as long as the battery lasts. Be careful though, I don't think it's great for the sensor.
Put the camera in manual, dial the wheel left until you get it into BULB mode. You'll need to either hold in the shutter button or use a remote to open and close the shutter.
The D40 has a maximum allowed exposure time of 30 minutes.