Bela
Real-time, ultra-low-latency audio and sensor processing system for BeagleBone Black
 All Classes Files Functions Variables Typedefs Macros Groups
Oscillator.h
1 /***** Oscillator.h *****/
2 #pragma once
3 #include <cmath>
4 class Oscillator {
5  public:
6  Oscillator(){};
7  Oscillator(float frequency, float fs, unsigned int type = sine, float initialPhase = 0)
8  {
9  setup(frequency, fs, type, initialPhase);
10  }
11  ~Oscillator(){};
12 
13  void setup(float frequency, float fs, unsigned int type = sine, float initialPhase = 0)
14  {
15  fs_ = fs;
16  invSampleRate_ = 1.0 / fs_;
17  setFrequency(frequency);
18  setType(type);
19  phase_ = (-M_PI < initialPhase < M_PI) ? initialPhase : 0;
20  }
21 
22  float process()
23  {
24  float out;
25  switch(type_) {
26  default:
27  // SINEWAVE
28  case sine:
29  out = sinf(phase_);
30  break;
31  // TRIANGLE WAVE
32  case triangle:
33  if (phase_ > 0) {
34  out = -1 + (2 * phase_ / (float)M_PI);
35  } else {
36  out = -1 - (2 * phase_/ (float)M_PI);
37  }
38  break;
39  // SQUARE WAVE
40  case square:
41  if (phase_ > 0) {
42  out = 1;
43  } else {
44  out = -1;
45  }
46  break;
47  // SAWTOOTH
48  case sawtooth:
49  out = 1 - (1 / (float)M_PI * phase_);
50  break;
51  }
52  computePhase();
53  return out;
54  }
55 
56  unsigned int setType(unsigned int type) {
57  type_ = (type < numOscTypes) ? type : sawtooth;
58  return type_;
59  }
60  void setFrequency(float frequency) {
61  frequency_ = (frequency < 0.5*fs_) ? frequency : 0.5*fs_;
62  }
63 
64  float getPhase() { return phase_; }
65  float getFrequency() { return frequency_; }
66  int getType() { return type_; }
67 
68  enum osc_type
69  {
70  sine, // 0
71  triangle, // 1
72  square, // 2
73  sawtooth, // 3
74  numOscTypes
75  };
76 
77  private:
78  float phase_ = 0;
79  float frequency_;
80  float fs_;
81  float invSampleRate_;
82  unsigned int type_ = sine;
83 
84  void computePhase() {
85  // Compute phase
86  phase_ += 2.0f * (float)M_PI * frequency_ * invSampleRate_;
87  if(phase_ > M_PI)
88  phase_ -= 2.0f * (float)M_PI;
89  }
90 };
Definition: Oscillator.h:4