Adding a filament sensor
With marlin firmware:

source here: filiament sensor config

//#define FILAMENT_RUNOUT_SENSOR
#if ENABLED(FILAMENT_RUNOUT_SENSOR)
  #define FIL_RUNOUT_INVERTING false // set to true to invert the logic of the sensor.
  #define ENDSTOPPULLUP_FIL_RUNOUT // Uncomment to use internal pullup for filament runout pins if the sensor is defined.
  #define FILAMENT_RUNOUT_SCRIPT "M600"
#endif



  With this feature, a mechanical or opto endstop switch is used to
  check for the presence of filament in the feeder (usually the switch
  is closed when filament is present). If the filament runs out, Marlin
  will run the specified GCode script (by default “M600”). RAMPS-based
  boards use SERVO3_PIN. For other boards you may need to define
  FIL_RUNOUT_PIN.


and this is a nice piece of hardware: run out sensor