TinyRobotics
Loading...
Searching...
No Matches
Arduino.h
1#pragma once
2#ifdef USE_TR_ARDUINO_EMULATION
3#include <algorithm>
4#include <chrono>
5#include <cmath>
6#include <cstdint>
7#include <iostream>
8#include "TinyRobotics/utils/Config.h"
9#include "Stream.h"
10#include "TinyRobotics/utils/LoggerClass.h"
11#include <thread>
12
13namespace tinyrobotics_arduino {
14enum PinMode { INPUT = 0, OUTPUT = 1 };
15enum DigitalValue { LOW = 0, HIGH = 1 };
16
17// Timing
18#if USE_MILLIS_CHRONO
19inline unsigned long millis() {
20 static auto start = std::chrono::steady_clock::now();
21 auto now = std::chrono::steady_clock::now();
22 return std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
23 .count();
24}
25inline void delay(unsigned long ms) {
26 std::this_thread::sleep_for(std::chrono::milliseconds(ms));
27}
28#else
29unsigned long millis();
30delay(unsigned long ms);
31#endif
32
33// Pin functions (no-op for native)
34#if USE_DUMMY_PIN_FUNCTIONS
35inline void pinMode(int pin, int mode) {
36 tinyrobotics::TRLogger.debug("Emulator: pinMode(%d,%d)", pin, mode);
37}
38inline void digitalWrite(int pin, int value) {
39 tinyrobotics::TRLogger.debug("Emulator: digitalWrite(%d,%d)", pin, value);
40}
41inline void analogWrite(int pin, int value) {
42 tinyrobotics::TRLogger.debug("Emulator: analogWrite(%d,%d)", pin, value);
43}
44#else
45void pinMode(int, int);
46void digitalWrite(int, int);
47void analogWrite(int, int);
48#endif
49
50// Math helper: constrains a value between a minimum and maximum
51#ifndef constrain
52template <typename T, typename L, typename H>
53constexpr T constrain(T amt, L low, H high) {
54 return std::min(std::max(amt, static_cast<T>(low)), static_cast<T>(high));
55}
56#endif
57
58// Math helper: maps a value from one range to another
59#ifndef map
60template <typename T, typename U>
61constexpr auto map(T x, U in_min, U in_max, U out_min, U out_max) {
62 return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
63}
64#endif
65
66
67#if USE_PRINT_CHAR
68bool print_char(uint8_t ch) {
69 std::cout << static_cast<char>(ch);
70 return true;
71}
72#else
73bool print_char(uint8_t);
74#endif
75
76
77/// Serial stub class
78struct HardwareSerial1 : public Stream {
79 void begin(unsigned long) {}
80 int read() override { return -1; }
81 int peek() override { return -1; }
82 int available() override { return 0; }
83 size_t write(uint8_t ch) override {
84 return print_char(ch) ? 1 : 0;
85 }
86};
87
88static HardwareSerial1 Serial;
89
90} // namespace tinyrobotics_arduino
91
92void setup();
93void loop();
94
95int main() {
96 setup();
97 while (true) {
98 loop();
99 }
100}
101
102#endif