Method and apparatus for controlling a motor