Inserting hex value and sending it at serial port.

I am trying to convert decimal value 1 to 32 to hex value and insert it at 4th pos of char array and send it as hex value at the serial port .

My issue is it is converting to decimal to hex value but when it sends, it treat the converted hex value as char and sends it equivalent hex value.

For example

if decimal =1 then its hex = 1.
so , writebuffer[3] =1
but when we send whole writebuffer through send function, it treat this 1 as char and sends its hex value as 31. how to send its hex value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

unsigned int i=0;
char hex[3];
unsigned char hexunsigned[3];
unsigned int dec;

do
{
unsigned char writebuffer[8] ={0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

// to place the hex value of each point on writeBuffer[3]
dec=i+1;
decimal_hex(dec,hex); //convert dec to hex value
memcpy(writebuffer+3, hex, sizeof(writebuffer+3));

unsigned short int crc = CRC16(writebuffer, 6); 
writebuffer[6] = ((unsigned char*) &crc)[1];
writebuffer[7] = ((unsigned char*) &crc)[0];

serialObj.send(writebuffer, 8);

//send another packet only after getting the response
DWORD nBytesRead = serialObj.Read(inBuffer, sizeof(inBuffer));
i++;
}while(nBytesRead!=0 && i<32);



The send function is

1
2
3
4
5
void serial::send(unsigned char data[], DWORD noOfByte)
{
	DWORD dwBytesWrite;
	WriteFile(serialHandle, data, noOfByte, &dwBytesWrite, NULL);
}


Last edited on
I guess that line 9 gives you the wrong idea (0x.. is just a notation). You don't need to convert dec to hex:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
unsigned int char i=0; // Note
char hex[3];
unsigned char hexunsigned[3];
unsigned int dec;

do
{
unsigned char writebuffer[8] ={0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

// to place the hex value of each point on writeBuffer[3]
dec=i+1;
decimal_hex(dec,hex); //convert dec to hex value
memcpy(writebuffer+3, hex, sizeof(writebuffer+3));
writebuffer[3] = i+1;

unsigned short int crc = CRC16(writebuffer, 6); 
writebuffer[6] = ((unsigned char*) &crc)[1];
writebuffer[7] = ((unsigned char*) &crc)[0];

serialObj.send(writebuffer, 8);

//send another packet only after getting the response
DWORD nBytesRead = serialObj.Read(inBuffer, sizeof(inBuffer));
i++;
}while(nBytesRead!=0 && i<32);

thank you
Topic archived. No new replies allowed.