Use diag_pin to detect obstacle on bed and set offset in IDEX printer

You can try to adopt this working solution based on optical switches and macros.