Mozzi  alpha 0.01.1t
sound synthesis library for Arduino
 All Classes Functions Typedefs
Phasor.h
00001 /*
00002  * Phasor.h
00003  *
00004  * Copyright 2012 Tim Barrass.
00005  *
00006  * This file is part of Mozzi.
00007  *
00008  * Mozzi is free software: you can redistribute it and/or modify
00009  * it under the terms of the GNU General Public License as published by
00010  * the Free Software Foundation, either version 3 of the License, or
00011  * (at your option) any later version.
00012  *
00013  * Mozzi is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016  * GNU General Public License for more details.
00017  *
00018  * You should have received a copy of the GNU General Public License
00019  * along with Mozzi.  If not, see <http://www.gnu.org/licenses/>.
00020  *
00021  */
00022 
00023 #ifndef PHASOR_H_
00024 #define PHASOR_H_
00025 
00026 #include "Arduino.h"
00027 #include "fixedMath.h"
00028 #include <util/atomic.h>
00029 
00030 #define PHASOR_MAX_VALUE_UL 4294967295UL
00031 
00039 template <unsigned int UPDATE_RATE>
00040 class Phasor
00041 {
00042 private:
00043                 unsigned long current_value;
00044                 volatile unsigned long step_size;
00045 
00046 public:
00050                 Phasor (){
00051                                 ;
00052                 }
00053 
00057                 inline
00058                 unsigned long next()
00059                 {
00060                                 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
00061                                 {
00062                                                 current_value += step_size; // will wrap
00063                                 }
00064                                 return current_value;
00065                 }
00066 
00070                 inline
00071                 void set(unsigned long value)
00072                 {
00073                                 current_value=value;
00074                 }
00075 
00076 
00081                 inline
00082                 void setFreq(unsigned int frequency)
00083                 {
00084                                 step_size = ((((unsigned long)((PHASOR_MAX_VALUE_UL>>8)+1))/(UPDATE_RATE))*frequency)<<8;
00085                 }
00086 
00087 
00092                 inline
00093                 void setFreq(float frequency)
00094                 { // 1 us - using float doesn't seem to incur measurable overhead with the oscilloscope
00095                                 //ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
00096                                 //{
00097                                 step_size = ((unsigned long)((((unsigned long)((PHASOR_MAX_VALUE_UL>>8)+1))/(UPDATE_RATE))*frequency))<<8;
00098 
00099                                 //}
00100                 }
00101 };
00102 
00103 #endif /* PHASOR_H_ */