Does it just set a 'soft' code? (not go into closed loop?).
It could be as simple as corroded battery terminals, but more than likely it's a bad or corroded pin/connector/ground, ..rodent-chewed wire, etc. If you live in an area where things rust or corrode from road or moisture elements, that...