Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
11 years ago.
int to hex and hex toi int
Hi i'm trying to use a max5312 With my mbed. I use spi at 16 bits and 10 mhz like on the documentation. To modify the out of the dac, i need to write 0x04XXX on the spi (XXX is hexa number that can take 000 to FFF value). It's works. But now i'm trying to use a potentiometer to modify the out of dac. For this i use analogIn and read_u16(). After that i divide this number by 16 to convert this in 12 bits number. After that i need to convert this number to hexa (for max53212) and after to int (to write it on spi). See under my code :
max5312
Terminal term(USBTX, USBRX); // tx, rx SPI spi1(p5,p6,p7); //mosi,miso, sclk DigitalOut cs(p10),clr(p15),ldac(p16); AnalogIn potar1(p17); PwmOut led1(p21); int main() { term.printf("test laison spi max 5312 \r\n"); //reset du max clr=0; ldac=0; //init du max cs = 1; wait_us(1); //delay for max5312 (see doc) clr=1; ldac=1; spi1.format(16); //trame on 16 bits spi1.frequency(10000000); //freq max5312 10Mhz int reponse(0); unsigned short valeurPotar(0); short valeurPotar12Bits(0); unsigned int testHex(0); while(1) { valeurPotar=potar1.read_u16(); valeurPotar12Bits = valeurPotar/16; //convert value on 12 bits char* hex ; int size; size = sprintf(hex,"0x04%X",valeurPotar12Bits);//convert value in hex /*if(size<7) { for(;size<7;size++) hex[size]=0; }*/ testHex = strtoul(hex, NULL, 16);//pconvert in int led1.write(valeurPotar); term.cls(); term.locate(0,0); term.printf("valeur potentiometre 12 bits : %d \r\nValeur potentiometre hex : %x \r\nTest conversion hexa %s\r\nTest sur spi %d / %X \r\ntaille %d\r\n",valeurPotar12Bits,valeurPotar12Bits,hex,testHex,testHex,size); // on active la transmission en mettant cs à zero cs = 0; reponse=spi1.write(testHex); //sortie à zero en unipolaire term.printf("resultat min : %X \r\n",reponse); // on coupe la transmission cs = 1; } }
I find that my code is not good, how i can optimize it ?
1 Answer
11 years ago.
Hex and decimal are just ways to write the number, but in this case it is sent as binary, just like how your AnalogIn is read. Only when you write something as string (for example via serial) do you need to worry about that. In this case what should work is simply:
spi.write(0x4000 + your_12_bit_value);