P0340 usually means the timing is off I'm sorry to say, not the sensor itself. The noise and rough idle are quite good clues.
Looks like the cambelt is timed correctly....no wait.....that's my engine
That part arrowed cannot make a rattle noise as it's just the end of the camshaft shrouded with a cover. There are no interference parts in that area.
I'm not trying to poo-poo your mechanic, but I'll put money on the noise travelling down the cam shaft. Believe me, I spent 2 years misdiagnosing a rattle because engines are echo chambers. My rattle turned out to be a broken VVT oil control ring in the chain cover. That's how I know sound from that end can resonate down the camshaft
The reason the noise goes off idle is because either you also have a broken oil ring (easily done when refitting the chain cover after chain replacement - don't ask how I know) and an increase in oil pressure silences it, or the base timing is off, causing a VVT rattle.
My advice - check the base timing. Get the engine on TDC cylinder one and make sure the arrows line up as per the picture. If that end is good, check the timing on the chain end. A *lot* of people get that end a tooth off. It's not a criticism, it's just an easy mistake to make because there's a lot of slop in the cams when timing it up, in spite of using the proper cam locking tool.
Is the rattle worse when the engine is up to temperature?