ios - Sending int data to BLE device -
i have 4 distinct int values need send ble device (connection established ok).
i'll call int values a,b,c,d clarity. , b range between 0-100, c has range of 0-2000 , d has range of 0-10000. values determined user input.
i need send these 4 values ble device in quick succession, , package each of them differently: , b (8 bits), c (16 bits) , d (32 bits). i'm unsure how package values correctly.
below 3 methods i've tried varying degrees of success.
convert int data , send, e.g. (8 bit) int:
const unsigned char chr = (float)a; float size = sizeof(chr); nsdata * adata = [nsdata datawithbytes:&chr length:size]; [p writevalue:adata forcharacteristic:achar type:cbcharacteristicwritewithresponse];
convert string first, e.g. (16 bit) c:
nsstring * cstring = [nsstring stringwithformat:@"%i",c]; nsdata * cdata = [cstring datausingencoding:nsutf16stringencoding]; [p writevalue:cdata forcharacteristic:cchar type:cbcharacteristicwritewithresponse];
use uint, e.g. (32 bit) d int:
uint32_t val = d; float size = sizeof(val); nsdata * ddata = [nsdata datawithbytes:(void*)&val length:size]; [p writevalue:valdata forcharacteristic:dchar type:cbcharacteristicwritewithresponse];
what doing wrong in above, , how best convert , send int value device, allowing 3 formats required?
you need know little more information format device expects:
- are values signed or unsigned
- is system little-endian or big-endian
assuming want use little-endian format ios uses, can use datawithbytes
-
unsigned char = 100 nsdata *adata = [nsdata datawithbytes:&a length:sizeof(i)]; uint16 c = 1000 nsdata *cdata = [nsdata datawithbytes:&c length:sizeof(c)]; unit32 d = 10000 nsdata *ddata = [nsdata datawithbytes:&d length:sizeof(d)];
and write nsdata using writevalue:forcharacteristic:type:
if device wants big-endian data need manipulate bytes proper order. reason easier send numeric values ascii strings , convert them numeric values on receiving end, depend on whether have control on format device expecting.
Comments
Post a Comment