Skip to content

Example Arduino Serial Reader

markrileybot edited this page Sep 22, 2014 · 2 revisions
#include <Arduino.h>
#include <thrift/thrift_nano.h>
#include <test/example_gen.h>

struct tn_transport_serial_t
{
	tn_transport_t parent;
};

static bool
tn_transport_serial_is_open(tn_transport_t *self)
{
    return true;
}
static size_t
tn_transport_serial_read(tn_transport_t *self, void *buf, size_t len, tn_error_t *error)
{
	size_t l = Serial.readBytes((char*)buf, len);
    if( l != len ) *error = T_ERR_BUFFER_UNDERFLOW;
    return l;
}
static size_t
tn_transport_serial_write(tn_transport_t *self, void *buf, size_t len, tn_error_t *error)
{
	size_t l = Serial.write((char*)buf, len);
    if( l != len ) *error = T_ERR_BUFFER_OVERFLOW;
    return l;
}
static void
tn_transport_serial_reset(tn_transport_t *self)
{
}

tn_transport_t *
tn_transport_serial_init(struct tn_transport_serial_t *s, tn_error_t *error)
{
	tn_transport_t *self = (tn_transport_t*) s;
	self->tn_is_open = &tn_transport_serial_is_open;
	self->tn_read = &tn_transport_serial_read;
	self->tn_write = &tn_transport_serial_write;
    self->tn_reset = &tn_transport_serial_reset;
	return self;
}


struct tn_transport_serial_t serial_transport;
tn_transport_t *transport;
tn_protocol_t *protocol;
tn_package_name_structa_t* message;

void setup()
{
	tn_error_t error;
	transport = tn_transport_serial_init(&serial_transport, &error);
	protocol = (tn_protocol_t*)tn_protocol_compact_create(&error);
	message = tn_package_name_structa_create(&error);	
	Serial.begin(115200);
}

int loopCounter;
void loop() // run over and over
{
	tn_error_t error;
	if( Serial.available() )
	{
		size_t l = tn_read_struct(message, protocol, transport, &error);
		Serial.print("Read ");
		Serial.print(l);
		Serial.println(" bytes");
		Serial.write((char *)message->strprop->buf, message->strprop->pos);
	}
	else
	{
		if( loopCounter % 1000000 == 0 )
		{
			Serial.write("Waiting for a message\n");
			loopCounter = 0;
		}
	}
	loopCounter++;
}
Clone this wiki locally