Neocortical activity can evoke sensory percepts, but the cellular mechanisms remain poorly understood. We trained mice to detect single brief whisker stimuli and report perceived stimuli by licking to obtain a reward. Pharmacological inactivation and optogenetic stimulation demonstrated a causal role for the primary somatosensory barrel cortex. Whole-cell recordings from barrel cortex neurons revealed membrane potential correlates of sensory perception. Sensory responses depended strongly on prestimulus cortical state, but both slow-wave and desynchronized cortical states were compatible with task performance. Whisker deflection evoked an early (<50 ms) reliable sensory response that was encoded through cell-specific reversal potentials. A secondary late (50-400 ms) depolarization was enhanced on hit trials compared to misses. Optogenetic inactivation revealed a causal role for late excitation. Our data reveal dynamic processing in the sensory cortex during task performance, with an early sensory response reliably encoding the stimulus and later secondary activity contributing to driving the subjective percept.