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

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

#include <hwd.h>


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


volatile sig_atomic_t keep_running {true};


void termination_handler(int)
{
	keep_running = false;
}


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, nullptr);
	seconds interval {0.01};
	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;
	}
	int i = 1;
	while (keep_running) {
		if (samples != 0 && i++ > samples)
			break;
		const auto end_time = std::chrono::high_resolution_clock::now() + interval;
		std::cout << hwd::sinewave::get_point() << std::endl;
		std::this_thread::sleep_until(end_time);
	}
	return 0;
}