質問

I need to send an integer, say between 0-10000, to Arduino using serial communication. What's the best way of doing that?

I can think of breaking the number into an character array (eg: 500 as '5','0','0') and sending them as a byte stream (yeah, that's ugly). Then reconstruct at the other end. (anything is sent serially as a byte stream, right?)

Isn't there a better way? Somehow, it should be able to assign the value into an int type variable.

(really need to know the same thing about strings too, if possible)

役に立ちましたか?

解決

If what you're looking for is speed, then instead of sending an ASCII encoded int, you can divide your number into two bytes, here's an example:

uint16_t number = 5703;               // 0001 0110 0100 0111
uint16_t mask   = B11111111;          // 0000 0000 1111 1111
uint8_t first_half   = number >> 8;   // >>>> >>>> 0001 0110
uint8_t sencond_half = number & mask; // ____ ____ 0100 0111
    
Serial.write(first_half);
Serial.write(sencond_half);

他のヒント

You don't specify the from environment, so I assume your troubles is with reading serial data on an Arduino?

Anyways, as can be seen in the Arduino Serial reference, you can read an integer using the Serial.parseInt() method call. You can read strings with eg. Serial.readBytes(buffer, length) but your real issue is to know when to expect a string and when to expect an integer (and what to do if something else comes along, eg. noise or so...)

Another way:

unsigned int number = 0x4142; //ASCII characters 'AB';
char *p;
    
p = (char*) &number;
    
Serial.write(p,2);

will return 'BA' on the console (LSB first).

Other way:

char p[2];
*p = 0x4142; //ASCII characters 'AB'
Serial.write(p,2);

I like this way.

I am not from coding background, today i was trying the same and got it working.. I am just sending the number byte wise with start and end bytes added ('a' and 'b'). hope it helps..enter code here

//sending end
unsigned char a,n[4],b;
int mynum=1023;// the integer i am sending
for(i=0;i<4;i++)
{
    n[i]='0'+mynum%10; // extract digit and store it as char
    mynum=mynum/10;
}

SendByteSerially(a);
_delay_ms(5);
SendByteSerially(n[3]);
_delay_ms(5);
SendByteSerially(n[2]);
_delay_ms(5);
SendByteSerially(n[1]);
_delay_ms(5);
SendByteSerially(n[0]);
_delay_ms(5);
SendByteSerially(b);
_delay_ms(100);


//at receiving end. 
while(portOne.available() > 0) 
{
    char inByte = portOne.read();
    if(inByte!='a' && inByte !='b')
    {
    Serial.print(inByte);
    }
    else if(inByte ='a')
        Serial.println();
    else if(inByte ='b')
        Serial.flush();
    }
delay(100);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top