This article focuses on developing an energy management system (EMS) for a microgrid on a university campus. The microgrid comprises photovoltaic (PV) systems, Battery Energy Storage Systems (BESS), backup generators, and local loads. The proposed EMS seeks to optimize the power flow, enabling the bidirectional power flow between the microgrid and the utility grid, through a mathematical model and algorithm that establishes BESS charging and discharging patterns, also considering battery degradation via the rainflow algorithm, to minimize energy cost. The EMS is modeled through a Mixed-Integer Conic Programming (MICP) optimization problem aiming at minimizing the operational cost of the university campus. The results obtained showed that the EMS developed reached the proposed objective, minimizing the energy costs of the microgrid when choosing the appropriate device to meet the loads. In addition, potential improvements were identified for the analyzed microgrid, such as expanding the photovoltaic generation system and improving system management strategies and the use of the storage system.