I am sending a sequence of numbers by serial from the my computer.
I need to then store the sequence as a long integer.
So if I send 54321 which begin their life as a sequence ascii characters. How do I put them together in the arduino so i end up with a long int = 54321 ?
Would a kind soul be able to help me out here.
Embarrisingly frustrated with the hours I've been playing around trying to solve this seeming simple task.
You'll have to make at least one change (i = 0 should be i = 0L) to support long ints, but this is a function I wrote. It echoes and checks for validity. Looking at the code at this late date, I'm not sure why I made c and i static...
int read_int()
{
static byte c;
static int i;
i = 0;
while (1)
{
while (!Serial.available())
{;}
c = Serial.read();
Serial.print(c, BYTE);
if (c == '\r')
{
Serial.print(crlf);
return i;
}
if (isdigit(c))
{
i = i * 10 + c - '0';
}
else
{
Serial.print("\r\nERROR: \"");
Serial.print(c, BYTE);
Serial.print("\" is not a digit\r\n");
return -1;
}
}
}
You'll have to make at least one change (i = 0 should be i = 0L) to support long ints, but this is a function I wrote. It echoes and checks for validity. Looking at the code at this late date, I'm not sure why I made c and i static...
int read_int()
{
static byte c;
static int i;
i = 0;
while (1)
{
while (!Serial.available())
{;}
c = Serial.read();
Serial.print(c, BYTE);
if (c == '\r')
{
Serial.print(crlf);
return i;
}
if (isdigit(c))
{
i = i * 10 + c - '0';
}
else
{
Serial.print("\r\nERROR: "");
Serial.print(c, BYTE);
Serial.print("" is not a digit\r\n");
return -1;
}
}
}
-j
I'm trying to reuse some of this logic, but it looks like there's a static variable "crlf" that's undefined, and a function "isdigit" that's not defined. Any clues?
Don't know if this will help or if you already figured it out - but I recently spent a unexpected long, painful day at this (if I had known it was going to be hard I would have braced myself...)
Probably better ways to do it but this worked for me:
int getInput(){
int total = 0;
int byteCount = 1;
int val;
while(1){
while (Serial.available() > 0) {
val = Serial.read();
if (val == '*'){
return total;
}
else {
switch(byteCount){
case 1:
total = total + (val * 16777216);
byteCount++;
break;
case 2:
total = total + (val * 65536);
byteCount++;
break;
case 3:
total = total + (val * 256);
byteCount++;
break;
case 4:
total = total + val;
break;
}
}
}
}
}
A more intuitive approach might be to use bitshifting, so it's clear what's going on:
byte4 = num & 0xFF; // least significant byte of the long "num"
byte3 = (num >> 8) & 0xFF;
byte2 = (num >> 16) & 0xFF;
byte1 = num >> 24; // most significant byte of the long "num"
You could even pretty easily embed it in a for loop if so desired.