summaryrefslogtreecommitdiff
path: root/electic_streaming328p/main.cpp
blob: 71c276ebdd5e8d45f26d8edfc6e479e04ee36a92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
extern "C" void __cxa_pure_virtual(void); //for C++ defines

/*
Electric data access template

TJR 191011

Uses Arduino c++ libraries in vanilla AVR environment

Explanation
http://www.johnhenryshammer.com/WOW2/pagesHowTo/atmelPage.php#index

*/
#define SAMPLES 512 //size of ram buffer
#define PACKETSIZE 320 //size of output packet

#include <WProgram.h> //import main Arduino header file


byte dd[SAMPLES];  // ram buffer
int loopCount=0;
int sample=0;

void fill_sinewave(){
    /*
    sample data to stream
    the vital thing is that its possible to distinguish the end of a packet

    here the data is in the range 1-255 and a 0 denotes the end of the packet
    */
  float pi = 3.141592;
  float fcnt=0;
  float fd;
  float dx=2 * pi / SAMPLES;                    // fill the 512 byte bufferarry
  int bb;
    for (int i = 0; i <SAMPLES ; i++){      // with  50 periods sinewawe
    fd= 127*sin(fcnt);                // fundamental tone
    fcnt=fcnt+dx;                     // in the range of 0 to 2xpi  and 1/512 increments
    bb=128+fd;                        // add dc offset to sinewawe
    dd[i]=bb;                        // write value into array
  }
}

int main(){

    //init(); -- init Arduino library - delay, PWM setup messes with timers, millis(), micros() etc don't work without it
    fill_sinewave();
    Serial.begin(115200);

    DDRB |= (1 << 5); // port B bit 6 = arduino pin 13
    PORTB = (1 << 5); //turn on to start
    TCCR1B |= (1 << WGM12); // Configure timer 1 for CTC mode
    TIMSK1 |= (1 << OCIE1A); // Enable CTC interrupt
    OCR1A   = 390; // Set CTC compare value: final speed = CPU clocks / prescaler / CTC 15625=1Hz
    sei(); //  Enable global interrupts

     while(1) {
        if (Serial.available() > 0) {
        PORTB ^= (1 << 5);
        byte in=Serial.read();
        if (in=='a') {
            Serial.println("Welcome to electic");
            TCCR1B |= ((1<<CS10)|(1 << CS12)); // Set up timer at Fcpu/1024
        }
      }
     }
}

ISR(TIMER1_COMPA_vect)
{
    //if (enabled)
    PORTB ^= (1 << 5);
    for (int i=0;i<PACKETSIZE;i++) {
        Serial.write(dd[sample]);
        sample=(sample+1)%SAMPLES;
    }
    Serial.write((byte)0);
}