Just as an info - using D4 (GPIO2) as input is likely not a good idea.
I had very unstable boot-up of my setup and looking into the D1-mini documentation the D4-pin (GPIO2) is "high-at-boot" and more importantly the boot fails, if pulled low during boot. And that can obviously happen quite randomly, if the NPN-phototransistor gets a signal in that moment.
Will change now to another pin and check, if it is stable afterwards.
EDIT: now everything works as expected. Maybe add D4 as not usable to the documentation?