isan98
Posts: 19
Joined: Sun May 14, 2017 6:36 am

get first number that read from serialGetchar()

Sun Jul 29, 2018 4:51 pm

Code: Select all

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <wiringSerial.h>

int main ()
{
  int fd,value ;

  if ((fd = serialOpen ("/dev/ttyACM0", 115200)) < 0)
  {
    fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
    return 1 ;
  }

// Loop, getting and printing characters

  for (;;)
  {
    value=serialGetchar (fd) ;
    fflush (stdout) ;
  }
  serialClose(fd);
}

I get the serialGetchar as int
for example the data that recieve is:
81,2018/07/29,18:21:34
34,2018/07/29,18:21:34
102,2018/07/29,18:21:35
...
....
....
how can I cast only the first number (81,34,102,.....,not date and time) in the other int?
int first;
first <----81
first<-----34
first<----102

danjperron
Posts: 3076
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: get first number that read from serialGetchar()

Sun Jul 29, 2018 5:49 pm

First create a function to capture on line to a char * array. Check for new line to end.

Then use Maybe sscanf(buffer,"%d,",&intvalue)

Or replace the comma character to NULL and use atoi.

isan98
Posts: 19
Joined: Sun May 14, 2017 6:36 am

Re: get first number that read from serialGetchar()

Fri Aug 03, 2018 10:12 am

danjperron wrote:
Sun Jul 29, 2018 5:49 pm
First create a function to capture on line to a char * array. Check for new line to end.

Then use Maybe sscanf(buffer,"%d,",&intvalue)

Or replace the comma character to NULL and use atoi.
can you show me the code?or example

jahboater
Posts: 3050
Joined: Wed Feb 04, 2015 6:38 pm

Re: get first number that read from serialGetchar()

Fri Aug 03, 2018 11:32 am

isan98 wrote:
Fri Aug 03, 2018 10:12 am
danjperron wrote:
Sun Jul 29, 2018 5:49 pm
Or replace the comma character to NULL and use atoi.
can you show me the code?or example
I think the ASCII character NUL ('\0') was meant, not the pointer.
Avoids a nasty warning from the compiler ...

Atoi() will stop when it finds a comma by the way, no need to end the string.

see "man atoi" and "man scanf" for the details.

Return to “C/C++”