Effective treatments for chronic pain remain limited. Conceptually, a closed-loop neural interface combining sensory signal detection with therapeutic delivery could produce timely and effective pain relief. Such systems are challenging to develop because of difficulties in accurate pain detection and ultrafast analgesic delivery. Pain has sensory and affective components, encoded in large part by neural activities in the primary somatosensory cortex (S1) and anterior cingulate cortex (ACC), respectively. Meanwhile, studies show that stimulation of the prefrontal cortex (PFC) produces descending pain control. Here, we designed and tested a brain-machine interface (BMI) combining an automated pain detection arm, based on simultaneously recorded local field potential (LFP) signals from the S1 and ACC, with a treatment arm, based on optogenetic activation or electrical deep brain stimulation (DBS) of the PFC in freely behaving rats. Our multiregion neural interface accurately detected and treated acute evoked pain and chronic pain. This neural interface is activated rapidly, and its efficacy remained stable over time. Given the clinical feasibility of LFP recordings and DBS, our findings suggest that BMI is a promising approach for pain treatment.