Stimulation of target neuronal populations using optogenetic techniques during specific sleep stages has begun to elucidate the mechanisms and effects of sleep. To conduct closed-loop optogenetic sleep studies in untethered animals, we designed a fully integrated, low-power system-on-chip (SoC) for real-time sleep stage classification and stage-specific optical stimulation. The SoC consists of a 4-channel analog front-end for recording polysomnography signals, a mixed-signal machine-learning (ML) core, and a 16-channel optical stimulation back-end. A novel ML algorithm and innovative circuit design techniques improved the online classification performance while minimizing power consumption. The SoC was designed and simulated in 180 nm CMOS technology. In an evaluation using an expert labeled sleep database with 20 subjects, the SoC achieves a high sensitivity of 0.806 and a specificity of 0.947 in discriminating 5 sleep stages. Overall power consumption in continuous operation is 97 uW.