summaryrefslogtreecommitdiff
path: root/examples/sinewave/sinewave_example.cpp
blob: 8b50804d930eec2c5174db343d684f238f9164e6 (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
#include <signal.h>
#include <unistd.h>

#include <chrono>
#include <functional>
#include <iostream>
#include <stdexcept>
#include <string>
#include <thread>

#include <hwd.h>

volatile sig_atomic_t keep_running{ 1 };

void termination_handler(int signum){
	keep_running = false;
}

using seconds = std::chrono::duration<double>;
using Clock = std::chrono::high_resolution_clock;

int main(int argc, char* argv[]) {

	struct sigaction int_action;

	int_action.sa_handler = termination_handler;
	sigemptyset(&int_action.sa_mask);
	int_action.sa_flags = 0;
	sigaction(SIGINT, &int_action, NULL);


	seconds interval{ 0.01 };
	int i = 0;
	int samples = 0;
	int	opt = 0;

	try {
		while ((opt = getopt(argc, argv, "n:i:")) != -1) {
			switch (opt) {
			case 'i':
				interval = seconds{ std::stod(optarg) };
				break;
			case 'n':
				samples = std::stoi(optarg);
				break;
			default:
				std::cerr << "Usage: " << argv[0] << " [-i interval][-n samples]" << std::endl;
				return 1;
			}
		}
	}
	catch (const std::invalid_argument& ia) {
		std::cerr << "Invalid argument: " << ia.what() << std::endl;

		return 1;
	}


	while (keep_running) {
		if (i >= samples) break;
		i++;

		const auto endTime = Clock::now() + interval;

		std::cout << hwd::sinewave::get_point() << std::endl;
	
		std::this_thread::sleep_until(endTime);
	}

	return 0;
}