Chronic pain is characterized by discrete pain episodes of unpredictable frequency and duration. This hinders the study of pain mechanisms and contributes to the use of pharmacological treatments associated with side effects, addiction and drug tolerance. Here, we show that a closed-loop brain-machine interface (BMI) can modulate sensory-affective experiences in real time in freely behaving rats by coupling neural codes for nociception directly with therapeutic cortical stimulation. The BMI decodes the onset of nociception via a state-space model on the basis of the analysis of online-sorted spikes recorded from the anterior cingulate cortex (which is critical for pain processing) and couples real-time pain detection with optogenetic activation of the prelimbic prefrontal cortex (which exerts top-down nociceptive regulation). In rats, the BMI effectively inhibited sensory and affective behaviours caused by acute mechanical or thermal pain, and by chronic inflammatory or neuropathic pain. The approach provides a blueprint for demand-based neuromodulation to treat sensory-affective disorders, and could be further leveraged for nociceptive control and to study pain mechanisms.