summaryrefslogtreecommitdiffstats
path: root/src/main.cpp
blob: 8c6772924f0e37a7a6e91cc507235d4fa956fb0b (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <Arduino.h>
#include <LiquidCrystal.h>
#include "Bounce.h"

void setup();
void loop();

// buffer size must be > LCD_CHARS
#define BUFFER_SIZE 80
char display_data[BUFFER_SIZE];
char buf[BUFFER_SIZE];
int buffered = 0;

#define LCD_ROWS 2
#define LCD_COLS 16
#define LCD_CHARS (LCD_COLS * LCD_ROWS)
#if LCD_CHARS > BUFFER_SIZE
#error "BUFFER too small"
#endif

// initialize the library with the numbers of the interface pins
#ifdef ENERGIA
LiquidCrystal lcd(13, 12, 10, 9, 8, 7);
#else
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
#endif

// indices: 0 = prev; 1 = pause; 2 = next
#ifdef ENERGIA
byte buttons[] = {15, 6, 5};
#else
byte buttons[] = {A0, A1, A2};
#endif

#define NUMBUTTONS sizeof(buttons)
#define DEBOUNCE 10
Bounce bounce_buttons[NUMBUTTONS];

void setup() {
	byte i;
	lcd.begin(LCD_COLS, LCD_ROWS);

// The usb chip hangs if it tries to send data and no-one listens
// so we give the client time to start up first
#ifdef ENERGIA
	lcd.print("Waiting ...");
	for (int i = 0; i < 20; i++) {
		lcd.setCursor(0, 1);
		lcd.print("Serial: ");
		lcd.print(i);
		lcd.print("/20");
		delay(1000);
	}
	lcd.setCursor(0,0);
	lcd.clear();
#endif

	Serial.begin(9600);
	Serial.setTimeout(5000);

	for (i = 0; i < NUMBUTTONS; i++) {
		pinMode(buttons[i], INPUT_PULLUP);
		bounce_buttons[i] = Bounce(buttons[i], DEBOUNCE);
	}

	Serial.println("ready");
	memset(display_data, ' ', BUFFER_SIZE);
	strcpy(display_data, "Waiting for data");
}

bool button_just_pressed(int i) {
	bounce_buttons[i].update();
	return bounce_buttons[i].fallingEdge();
}

void loop() {
	if (button_just_pressed(0)) {
		Serial.println("previous");
	}

	if (button_just_pressed(1)) {
		Serial.println("pause");
	}

	if (button_just_pressed(2)) {
		Serial.println("next");
	}

	// buffer serial input ourselves
	if (Serial.available() >= 1) {
		buffered += Serial.readBytes(buf + buffered, LCD_CHARS - buffered);
	}

	if (buffered >= LCD_CHARS) {
		strcpy(display_data, buf);
		buffered = 0;
	}

	// update display
	lcd.setCursor(0, 0);
	int line = -1;
	for (int i = 0; i < LCD_CHARS; i++) {
		if (display_data[i] == '\0') {
			break;
		}
		if (i % LCD_COLS == 0) {
			line++;
			lcd.setCursor(0, line);
		}
		lcd.write(display_data[i]);
	}
}