Motoron Motor Controller library for Arduino
Loading...
Searching...
No Matches
SerialWithDE.h
1#pragma once
2
3#include <Arduino.h>
4
5// This class wraps HardwareSerial object and drives one or two configurable
6// pins high whenever the serial object is transmitting. These pins
7// essentially output the same signal, and you can connect that signal to the
8// the DE (Driver Enable) and RE (Receiver Enable) pins on an RS-485
9// transceiver chip.
10//
11// This object switchs to transmit mode when you call txMode() or write()
12// (note that write() is called by every function that writes or prints any
13// data to the serial port.)
14//
15// Unforunately, it does not switch to receive mode automatically when the
16// transmission is done. You must call rxMode() or flush() to do that.
17// This class works well with classes like the MotoronSerial which
18// calls flush() before reading any responses.
19//
20// A future, smarter version of this class might keep track of whether it is
21// in TX mode or RX mode. Then in the available(), read(), and peek()
22// functions, it should call flush() *if* it is currently in TX mode.
23// However, this implementation is good enough for MotoronSerial, which always
24// calls flush().
25class SerialWithDE : public Stream
26{
27public:
28 SerialWithDE(Stream * port, uint8_t de_pin = 0xFF, uint8_t re_pin = 0xFF)
29 : port(port), de_pin(de_pin), re_pin(re_pin)
30 {
31 }
32
33 void begin()
34 {
35 if (de_pin != 0xFF)
36 {
37 pinMode(de_pin, OUTPUT);
38 digitalWrite(de_pin, LOW);
39 }
40 if (re_pin != 0xFF)
41 {
42 pinMode(re_pin, OUTPUT);
43 digitalWrite(re_pin, LOW);
44 }
45 }
46
47 void txMode()
48 {
49 if (de_pin != 0xFF) { digitalWrite(de_pin, HIGH); }
50 if (re_pin != 0xFF) { digitalWrite(re_pin, HIGH); }
51 }
52
53 void rxMode()
54 {
55 if (de_pin != 0xFF) { digitalWrite(de_pin, LOW); }
56 if (re_pin != 0xFF) { digitalWrite(re_pin, LOW); }
57 }
58
59 int available() override
60 {
61 return port->available();
62 }
63
64#if defined(ARDUINO_ARCH_SAM) || defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_ARCH_ARC32)
65 // availableForWrite is not available in the Stream or Print class in these cores.
66#else
67 // availableForWrite is needed in ArduinoCore-avr and probably other platforms as well.
68 int availableForWrite() override
69 {
70 return port->availableForWrite();
71 }
72#endif
73
74 int peek() override
75 {
76 return port->peek();
77 }
78
79 int read() override
80 {
81 return port->read();
82 }
83
84 void flush() override
85 {
86 port->flush();
87 rxMode();
88 }
89
90 size_t write(uint8_t b) override
91 {
92 txMode();
93 return port->write(b);
94 }
95
96 Stream * port;
97 uint8_t de_pin, re_pin;
98};