简体   繁体   中英

How to send a integer value to arduino from visual studio C#

I study a project about controlling a robot with visual studio C#. I wanna control a stepper motor connected arduino with Track position. But i don't send track values as integer to arduino by serial port. I can send characters or string values. I wanna send each track values to arduino for controling stepper motor.

On the C# side, you can use something like this:

Byte[] bytes = BitConverter.GetBytes(1234); //1234-sample  32 bit int

Watch out for endianness, in this example in bytes[0] will be least least significant byte, so it's better to send this array starting from end.

On the Arduino side, you can get this array byte to byte, and assemble it back to int, by left shifting, for example:

tmp_long|=getbyte(); //got first byte of int
tmp_long<<=8;
tmp_long|=getbyte(); //got second byte of int
tmp_long<<=8;
tmp_long|=getbyte(); //
tmp_long<<=8;
tmp_long|=getbyte(); //

//Remember, int is 32 bit in C# and 16 bit on Arduino Uno, so you need long type here.

Or you could typedef union, and fill it byte by byte, like this:

typedef union _WORD_VAL
{
    unsigned long Val;
    unsigned char v[4];
} WORD_VAL;

WORD_VAL myData;

myData.v[0]=getbyte(); //got first byte of int
myData.v[1]=getbyte();
myData.v[2]=getbyte(); 
myData.v[3]=getbyte();

unsigned long data=myData.Val; //got assembled in back

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM