Pelles C forum
C language => Beginner questions => Topic started by: 0gmios on April 29, 2008, 04:03:39 PM
-
Hi People,
I am working on a serial port interface, see http://forum.pellesc.de/index.php?topic=2461.0 (http://forum.pellesc.de/index.php?topic=2461.0), which is now fully functional.
When I get information back from the interface it is a string, in the form of "ADC <channel> <value>" So if 5 volts is applied to channel one, the returned string would be "ADC 1 255".
I want to extract the 255.
I have written the following code, but can anyone suggest something smaller?
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char Stuff[] = "ADC 1 255";
char * pStuff;
long int Notneeded, ADCchannel, ADCvalue;
Notneeded = strtol (Stuff,&pStuff,32);
ADCchannel = strtol (pStuff,&pStuff,0);
ADCvalue = strtol (pStuff,NULL,0);
printf ("The ADC value at channel %ld is %ld.\n", ADCchannel, ADCvalue);
return 0;
}
Regards,
-
For example:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char Stuff[] = "ADC 1 255";
char * pStuff;
long int /* Notneeded, */ ADCchannel, ADCvalue;
//Notneeded = strtol (Stuff,&pStuff,32);
ADCchannel = strtol (&Stuff[4], &pStuff, 0);
ADCvalue = strtol (pStuff, NULL, 0);
printf ("The ADC value at channel %ld is %ld.\n", ADCchannel, ADCvalue);
return 0;
}
or maybe this works if channel is 0 - 99
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char Stuff[] = "ADC 1 255";
long int ADCchannel, ADCvalue;
ADCchannel = strtol (&Stuff[4], NULL, 0);
ADCvalue = strtol (&Stuff[6], NULL, 0);
printf ("The ADC value at channel %ld is %ld.\n", ADCchannel, ADCvalue);
return 0;
}
-
Like this?
int main(int argc, char *argv[])
{
char Stuff[] = "ADC 1 255", *pValue, *pChannel;
pValue = Stuff;
for(pValue += strlen(Stuff)-1;*pValue != ' ';pValue--);
pChannel = pValue++;
for(*pChannel = '\0';*pChannel != ' ';pChannel--);
printf ("The ADC value at channel %s is %s.\n", pChannel, pValue);
return 0;
}
-
Gentlemen,
Thank you for your suggestions. Since there are only 16 pins, 8 of which can be ADCs, telling the strtol to start at element 6 is what I will go with. Hence it is one line to extract the 255. The channel should already be known, since you have to tell the interface that you what the value of that channel. But extracting that information will also be helpful if an error check is required to ensure the interface returned the correct channel.
DMac, I like the code since it is extracting elements and then equating them to another string (which I thought we weren't allowed to do in C BTW), but I would then need to use strtol to convert to an integer that can be manipulated to give an analogue voltage. For example I will actually want to...
printf ("The voltage at channel %ld is %f.\n", ADCchannel, (float) ADCvalue/51);
Hence it needs to be a integer.
Regards,