These lecture notes provide an overview of recent research on the modeling and control of smart grids using distributed algorithms. In particular, energy-based modeling of general AC power networks using the framework of port-Hamiltonian systems theory is presented, and the relevance of such a formulation for stability analysis and control design is discussed. Low-level control design aspects (at a physical layer) for DC microgrids are also considered, achieving objectives such as fair load sharing among distributed generation units and (average) voltage regulation using limited data and measurements from the system. Finally, general frameworks for the optimal control of smart grids are introduced to consider both physical and economic cons...