A coffee machine comprising a machine body, an electronic controller, a water feed pump, a boiler for producing steam from said water, a steam dispenser provided with a shut-off solenoid valve, a dispensing device dispensing milk emulsified and/or heated with said steam, said device having a jug containing the milk and a lid closing the jug having a Venturi effect chamber connected to said steam dispenser and to said jug drawing the milk present in said jug, an optical sensor being further provided to detect the level of milk present in said jug comprising at least a first operative infrared optical sensor (12a, 12b) to acquire a signal at least around a first level (L1) of milk in said jug, wherein said controller is configured to:
- store a nominal value of a transition time of said signal from a first threshold to a second threshold (S1, S2) preset around said first level (L1), and a nominal value of a first delay between an instant of deactivation of said boiler and an instant of detection of said first level of milk (L1);
- during the execution of a current milk dispensing cycle, acquire a current value (Δtx) of said transition time of said signal from said first preset threshold to said second preset threshold (S1, S2);
- execute said current milk dispensing cycle with a current value (dt1a) of said first delay that is modified with respect to said nominal value of said first delay if said current transition time (Δtx) differs from said nominal transition time.