Abstract. We consider the Selective Harmonic Modulation (SHM) problem, consisting in the design of a staircase control signal with some prescribed frequency components. In this work, we propose a novel methodology to address SHM as an optimal control problem in which the admissible controls are piecewise constant functions, taking values only in a given finite set. In order to fulfill this constraint, we introduce a cost functional with piecewise affine penalization for the control, which, by means of Pontryagin’s maximum principle, makes the optimal control have the desired staircase form. Moreover, the addition of the penalization term for the control provides uniqueness and continuity of the solution with respect to the target frequencies. Another advantage of our approach is that the number of switching angles and the waveform need not be determined a priori. Indeed, the solution to the optimal control problem is the entire control signal, and therefore, it determines the waveform and the location of the switches. We also provide several numerical examples in which the SHM problem is solved by means of our approach.