Sending an integer to Arduino

I need to send an integer, say between 0-10000, to Arduino using serial communication. What is the best way to do this?

I can think of breaking the number into an array of characters (for example: 500 as "5", "0", "0") and send them as a stream of bytes (yes, this is ugly). Then rebuild on the other end. (anything is sent in serial as a stream of bytes, right?)

Isn't there a better way? One way or another, it should be able to assign a value to a variable of type int .

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

+4
source share
5 answers

If you are looking for speed, then instead of sending an ASCII encoded int, you can divide the number into two bytes, here is 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); 
+6
source

You do not specify the environment, so I assume that your problems are related to reading serial data on Arduino?

In any case, as can be seen from the Arduino Serial reference , you can read an integer by calling the Serial.parseInt() method. You can read lines, for example. Serial.readBytes(buffer, length) , but your real problem is to know when to expect a string and when to expect an integer (and what to do if something else happens, such as noise or so ...)

+3
source

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).

+1
source

Another way:

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

I like this way.

+1
source

I'm not from background coding, today I try to do the same and got it working. I just send the number of bytes with the start and end bytes added ('a' and 'b'). hope this 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); 
-1
source

All Articles