This paper presents a framework to minimize energy consumption in the medium access control (MAC) layer for wireless sensor networks. While satisfying a range of quality of service (QoS) requirements, such as the packet transmission success rate and maximum delay constraint, we optimally choose the lengths of periods in which sensors are active and inactive, such that the energy consumption per unit time in the entire network is minimized. We first use our framework to optimize the values of the MAC attributes macBeaconOrder and macSuperframeOrder in an IEEE 802.15.4 beacon-enabled star network. Then we consider a much simpler protocol, which we call "select-and-transmit" (S&T), and the same framework is applied to find the optimal lengths of the active and inactive portions. Finally, we compare the minimal energy consumption of the IEEE 802.15.4 MAC and S&T under the same QoS requirements and show that the IEEE 802.15.4 MAC outperforms S&T in most cases. However, the S&T MAC performs better than the standard under our framework in certain scenarios, e.g., event-driven sensor networks where the packet transmission success rate is usually low.