关于 Arduino Serial Print 和 Write 的一点认识

https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.h

class HardwareSerial : public Stream
{
private:
ring_buffer *_rx_buffer;
ring_buffer *_tx_buffer;
volatile uint8_t *_ubrrh;
volatile uint8_t *_ubrrl;
volatile uint8_t *_ucsra;
volatile uint8_t *_ucsrb;
volatile uint8_t *_ucsrc;
volatile uint8_t *_udr;
uint8_t _rxen;
uint8_t _txen;
uint8_t _rxcie;
uint8_t _udrie;
uint8_t _u2x;
bool transmitting;
public:
HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer,
volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
volatile uint8_t *ucsrc, volatile uint8_t *udr,
uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x);
void begin(unsigned long);
void begin(unsigned long, uint8_t);
void end();
virtual int available(void);
virtual int peek(void);
virtual int read(void);
virtual void flush(void);
virtual size_t write(uint8_t);
inline size_t write(unsigned long n) { return write((uint8_t)n); }
inline size_t write(long n) { return write((uint8_t)n); }
inline size_t write(unsigned int n) { return write((uint8_t)n); }
inline size_t write(int n) { return write((uint8_t)n); }
using Print::write; // pull in write(str) and write(buf, size) from Print
operator bool();
};

https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp

size_t HardwareSerial::write(uint8_t c)
{
int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE;

// If the output buffer is full, there’s nothing for it other than to
// wait for the interrupt handler to empty it a bit
// ???: return 0 here instead?
while (i == _tx_buffer->tail)
;

_tx_buffer->buffer[_tx_buffer->head] = c;
_tx_buffer->head = i;

sbi(*_ucsrb, _udrie);
// clear the TXC bit — “can be cleared by writing a one to its bit location”
transmitting = true;
sbi(*_ucsra, TXC0);

return 1;
}

从上面可以看出来 Serial.Write 是直接把要发的东西送出去,Serial.Print 就复杂多了,会占用大量的内存。因此,如果有可能尽量用 Serial.Write。 如果你的程序用的大量的 Serial.Print,并且出现奇怪的问题,很可能产生的原因是内存不足,不妨删除几个 Print试试。

发表评论

电子邮件地址不会被公开。 必填项已用*标注