The cardiac pacemaker controls the rhythmicity of heart contractions and can be substituted by a battery-operated device as a last resort. We created a genetically encoded, optically controlled pacemaker by expressing halorhodopsin and channelrhodopsin in zebrafish cardiomyocytes. Using patterned illumination in a selective plane illumination microscope, we located the pacemaker and simulated tachycardia, bradycardia, atrioventricular blocks, and cardiac arrest. The pacemaker converges to the sinoatrial region during development and comprises fewer than a dozen cells by the time the heart loops. Perturbation of the activity of these cells was entirely reversible, demonstrating the resilience of the endogenous pacemaker. Our studies combine optogenetics and light-sheet microscopy to reveal the emergence of organ function during development.