We present an optogenetic illumination system capable of real-time light delivery with high spatial resolution to specified targets in freely moving Caenorhabditis elegans. A tracking microscope records the motion of an unrestrained worm expressing channelrhodopsin-2 or halorhodopsin in specific cell types. Image processing software analyzes the worm's position in each video frame, rapidly estimates the locations of targeted cells and instructs a digital micromirror device to illuminate targeted cells with laser light of the appropriate wavelengths to stimulate or inhibit activity. Because each cell in an unrestrained worm is a rapidly moving target, our system operates at high speed (∼50 frames per second) to provide high spatial resolution (∼30 μm). To test the accuracy, flexibility and utility of our system, we performed optogenetic analyses of the worm motor circuit, egg-laying circuit and mechanosensory circuits that have not been possible with previous methods.