-
Notifications
You must be signed in to change notification settings - Fork 0
/
scom.h
70 lines (60 loc) · 1.66 KB
/
scom.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#define SCOM_TIMEOUT 5000
#define SCOM_BAUD_RATE 9600
#define SCOM_DEV Serial
void scom_init()
{
SCOM_DEV.begin(SCOM_BAUD_RATE);
SCOM_DEV.setTimeout(SCOM_TIMEOUT);
}
bool scom_available()
{
return SCOM_DEV.available()>0;
}
void scom_write_bytes(byte *mem, long nbytes, const char *errmsg = NULL) {
long bytesWritten = (long)SCOM_DEV.write(mem,nbytes);
if(bytesWritten != nbytes) {
if(errmsg) {
BAIL(errmsg);
}
else {
char buf[80];
sprintf(buf,"Failed writing correct number of bytes, expected %ld, wrote %ld",nbytes,bytesWritten);
BAIL(buf);
}
}
}
void scom_read_bytes(byte *mem, long nbytes, const char *errmsg = NULL) {
long bytesRead = (long)SCOM_DEV.readBytes((char*)mem,nbytes);
if(bytesRead != nbytes) {
if(errmsg) {
BAIL(errmsg);
}
else {
char buf[80];
sprintf(buf,"Failed reading correct number of bytes, expected %ld, got %ld",nbytes,bytesRead);
BAIL(buf);
}
}
}
uint16_t scom_read_u16()
{
uint8_t bts[2];
scom_read_bytes(bts,2,"Failed reading u16.");
return ((uint16_t)bts[0]) | (((uint16_t)bts[1])<<8);
}
void scom_write_u16(uint16_t v)
{
uint8_t bts[2] = { (uint8_t)(v & 0xff), (uint8_t)((v>>8) & 0xff)};
scom_write_bytes(bts,2,"Failed writing u16");
}
uint32_t scom_read_u32()
{
uint8_t bts[4];
scom_read_bytes(bts,4,"Failed reading u32.");
return ((uint32_t)bts[0]) | (((uint32_t)bts[1])<<8) | (((uint32_t)bts[2])<<16) | (((uint32_t)bts[3])<<24);
}
void scom_write_u32(uint32_t v)
{
uint8_t bts[4] = {(uint8_t) (v & 0xff), (uint8_t) ((v >> 8) & 0xff), (uint8_t) ((v >> 16) & 0xff), (uint8_t) ((v >> 24) & 0xff)};
scom_write_bytes(bts,4,"Failed writing u32");
}