Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdint.h>
- #include <string.h>
- #define STRBUF_SIZE 100
- static char strbuf[STRBUF_SIZE];
- static uint8_t strbuf_i = 0;
- static uint8_t handshake_retry = 0;
- #define HANDSHAKE_MAX_RETRY 5
- #define HANDSHAKE_FAILED 0
- #define HANDSHAKE_OK 1
- #define HANDSHAKE_LED 13
- #define VERSION "INOST_IOT_V1"
- void setup(void) {
- pinMode(HANDSHAKE_LED, OUTPUT);
- Serial.begin(9600);
- if (!three_way_handshake()) {
- reset_board();
- }
- snprintf(strbuf, STRBUF_SIZE, "HELLO %s", VERSION);
- uart_write_string(strbuf);
- }
- void loop() {
- char *buf = uart_read_string();
- if (buf != NULL && strncmp(buf, "GET ", 4) == 0) {
- int port = -1; /* Will use standard int here, because of atoi */
- buf += 4; /* Skip "GET " */
- port = atoi(buf);
- if (port == -1 || port > 5) {
- uart_write_string("NACK");
- return;
- }
- dtostrf(get_sensor_read(port),5, 2, strbuf);
- uart_write_string(strbuf);
- } else if (buf != NULL && strcmp(buf, "VER") == 0) {
- uart_write_string(VERSION);
- } else if (buf != NULL && strcmp(buf, "RESET") == 0) {
- reset_board();
- } else {
- uart_write_string("NACK");
- }
- }
- float get_sensor_read(int pinNumber) {
- pinMode(A0 + pinNumber, INPUT);
- return analogRead(A0 + pinNumber);
- }
- uint8_t three_way_handshake() {
- handshake_retry++;
- if (handshake_retry > HANDSHAKE_MAX_RETRY) {
- reset_board();
- }
- char *buf;
- buf = uart_read_string();
- if (buf == NULL || strcmp("SYN", buf) != 0) {
- uart_write_string("NACK");
- return three_way_handshake();
- }
- uart_write_string("ACK");
- uart_write_string("SYN");
- buf = uart_read_string();
- if (buf == NULL || strcmp("ACK", buf) != 0) {
- uart_write_string("NACK");
- return three_way_handshake(); // recursive call, try again
- }
- digitalWrite(HANDSHAKE_LED, HIGH);
- return HANDSHAKE_OK;
- }
- char *uart_read_string() {
- strbuf_i = 0;
- int8_t temp;
- while (true) {
- while (Serial.available() > 0) {
- temp = Serial.read();
- if (temp == ';') {
- strbuf[strbuf_i] = 0;
- return strbuf;
- }
- strbuf[strbuf_i] = temp;
- strbuf_i++;
- if (strbuf_i > STRBUF_SIZE) {
- return NULL;
- }
- }
- }
- return NULL;
- }
- void uart_write_string(const char *data) {
- for (int i = 0; i < strlen(data); i++) {
- Serial.write(data[i]);
- }
- Serial.write(';');
- }
- void reset_board() {
- digitalWrite(HANDSHAKE_LED, LOW);
- uart_write_string("GOODBYE");
- asm volatile("jmp 0");
- }
Advertisement
Add Comment
Please, Sign In to add comment