pengfei wu
/
ESP8266Program
For test
Diff: ArduinoSerial.cpp
- Revision:
- 10:9d4ec0359a5c
- Child:
- 11:7bd1b2a67b1a
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ArduinoSerial.cpp Mon Feb 02 09:46:16 2015 +0000 @@ -0,0 +1,103 @@ +#include "ArduinoSerial.h" + +unsigned int ArduinoSerial::instance_counter = 0; +ArduinoSerial* ArduinoSerial::instance_reference[ARDUINOSERIAL_INSTANCE_MAX] = {0}; + +void ArduinoSerial::uart_irq_callback(void) { + unsigned int index; + for (index = 0; index < instance_counter; index++) { + if (instance_reference[index] != NULL) { + while(instance_reference[index]->readable()) { + instance_reference[index]->write_char(instance_reference[index]->getc()); + } + } + } +} + +ArduinoSerial::ArduinoSerial(PinName tx, PinName rx):Serial(tx, rx) { + if (instance_counter < ARDUINOSERIAL_INSTANCE_MAX) { + instance_reference[instance_counter++] = this; + if (1 == instance_counter) { + attach(&uart_irq_callback); + } + } else { + printf("Create instance 0x%u failed: more instances created!\r\n"); + } +} + +ArduinoSerial::~ArduinoSerial(void) { + instance_counter--; + if (0 == instance_counter) { + attach(NULL); + } +} + +void ArduinoSerial::begin(int baud_rate) { + baud(baud_rate); + flush(); +} + +int ArduinoSerial::available(void) { + return (unsigned int)(ARDUINOSERIAL_BUFFER_SIZE + rx_buffer.head - rx_buffer.tail) % ARDUINOSERIAL_BUFFER_SIZE; +} + +/* 清空接收缓冲区的数据 */ +void ArduinoSerial::flush(void) +{ + memset(&rx_buffer, 0, sizeof(rx_buffer)); +} + +char ArduinoSerial::read_char(void) { + // if the head isn't ahead of the tail, we don't have any characters + if (rx_buffer.head == rx_buffer.tail) { + return (char)-1; + } else { + unsigned char c = rx_buffer.buffer[rx_buffer.tail]; + rx_buffer.tail = (unsigned int)(rx_buffer.tail + 1) % ARDUINOSERIAL_BUFFER_SIZE; + return c; + } +} + +void ArduinoSerial::setTimeout(unsigned long millisecond) { + find_timeout = millisecond; +} + +/* 在超时之前, 如果在串口接收数据缓冲区中找到了定长字符串 str 就返回 true, 如果超时, 返回 false */ +bool ArduinoSerial::find(const char *str) { + bool ret = false; + String data; + char c; + unsigned long i; + + for (i = 0; i < find_timeout; i++) { + while(available() > 0) { + c = read_char(); + data += c; + } + if (data.indexOf(String(str)) != -1) { + ret = true; + break; + } + delay(1); + } + + return ret; +} + +size_t ArduinoSerial::write(uint8_t data) { + putc(data); + return 1; +} + +void ArduinoSerial::write_char(unsigned char c) { + int i = (unsigned int)(rx_buffer.head + 1) % ARDUINOSERIAL_BUFFER_SIZE; + + // if we should be storing the received character into the location + // just before the tail (meaning that the head would advance to the + // current location of the tail), we're about to overflow the buffer + // and so we don't write the character or advance the head. + if (i != rx_buffer.tail) { + rx_buffer.buffer[rx_buffer.head] = c; + rx_buffer.head = i; + } +}