1

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.