First thing I fought of was an optoisolator to keep the voltages safe + sperate. Code seems pretty simple.