Инструменты пользователя

Инструменты сайта


works:programmer:arduino:serial-read

Чтение Серийного порта в Arduino

SerialReader.ino
void popSerialData(); // read serial data
uint32_t atou(char* chars, uint32_t defvalue); // ansi to unsigned
 
void setup() {
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
}
 
void loop() {
  popSerialData();
}
 
void onCommand(char* cmd) {
  if (strcmp(cmd, "on") == 0) {
    digitalWrite(LED_BUILTIN, 1);
  }
  else if (strcmp(cmd, "off") == 0) {
    digitalWrite(LED_BUILTIN, 0);
  } else {
    Serial.println(atou(cmd, 4294967295), 16);
  }
}
 
//------------ ANSI TO UNSIGNED INT ------------
 
uint32_t atou(char* chars, uint32_t onfail) {
  uint32_t result = 0;
  for (uint8_t i=0; chars[i] != 0; i++) {
    if (chars[i] - '0' < 10) {
      result = result * 10 + (chars[i] - '0');
    } else {
      return onfail;
    }
  }
  return result;
}
 
//------------ SERIAL DATA READER ---------------
 
static uint32_t bx = 0;
const uint32_t bm = 30;
static char buff[bm] = {0};
 
void popSerialData() {
  while ( Serial.available()) {
    char c = Serial.read();
    if (c == 13) continue;
    else if (c == 10) {
      buff[bx] = 0;
      onCommand(buff);
      bx = 0;
    }
    else {
      buff[bx] = c;
      bx += 1;
      if (bx >= bm) {
        bx = 0;
      }
    }
  }
}
works/programmer/arduino/serial-read.txt · Последнее изменение: 2019/12/03 12:40 — 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki