IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

 C Discussion :

Communication sur port série (linux)


Sujet :

C

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    18
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2006
    Messages : 18
    Points : 11
    Points
    11
    Par défaut Communication sur port série (linux)
    Bonjour à tous,

    à nouveau je requiert votre aide pour mon programme.

    Que dois-je faire?

    Communiquer avec un périphérique depuis le port série.
    Je dois envoyer une série de byte (5 byte = une commande) et je dois récupérer la réponse (de 0 à 300 bytes)

    Mon problème ?
    Je ne parviens pas à configurer, dans mon programme, le port série comme il faudrait.
    Il doit avoir la configuration suivante

    300 baud ; Parité even ; 8 bit ; 1 bit stop ; pas de controle de flux

    Dans mon code j'utilise la structure termios (d'après ce que j'ai trouvé sur le net c'est comme cela qu'il faut faire). Mais lorsque je tente une commande du type stty -F /dev/ttyUSB1 -a après avoir lancé mon code, rien n'y fait, je suis toujours en 9600 bauds (pour le reste de la configuration je ne pense pas non plus que cela change...)

    Mon code actuellement ?
    Voici ce que j'ai pour l'instant. Qu'est-ce qui est faux?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
     
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <termios.h>
    #include <string.h>
    #include <sys/ioctl.h>
    #include <errno.h>
    #include "serial.h"
    int fd = 2;
     
     
     
    int OpenSerialPort()
    {
     
       //ouverture port serie en mode non-bloquant (read fait un return imédiat)
          fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY );
          if (fd < 0)
          {
             perror(DEVICE);
             exit(-1);
          }
        int rate;
        rate= B300;
     
        tcgetattr(fd,&oldtio); // sauvegarde de la configuration courante
     
        bzero(&newtio, sizeof(newtio));
     
        newtio.c_cflag = rate; //| CS8 | ~CSTOPB | PARENB | ~PARODD | CLOCAL | CREAD;
        //newtio.c_iflag = IGNPAR;
        newtio.c_oflag = 0;
        newtio.c_lflag = 0;       //ICANON;
        //newtio.c_cc[VMIN]=1;
        //newtio.c_cc[VTIME]=0;
     
        // à présent, on vide la ligne du port, et on active la configuration
        tcflush(fd, TCIFLUSH);
        tcsetattr(fd,TCSANOW,&newtio);
        fcntl(fd, F_SETFL, getpid());
        return fd; //renvoit résultat tentative ouverture
     
     
     
     
    }
     
    int ResetSerialPort()
    {
        //restaure l'ancienne configuration du port série
        tcsetattr(fd,TCSANOW,&oldtio);
        return 0;
    }
     
    int WriteSerialPort(char* SerialPOut)
    {
        int iOut;
        if (fd < 1)
        {
            printf(" Port série non ouvert   %d\n", fd);
            return -1;
        } // end if
        iOut = write(fd, SerialPOut, strlen(SerialPOut));
        if (iOut < 0)
        {
            printf("Erreur écriture %d %s\n", errno, strerror(errno));
        }
        else
        {
        	printf("%d caractères ont été écrit: %s\n", iOut, SerialPOut);
        }
        return iOut; //renvoit le résultat de l'écriture
    }
     
     
    int ReadSerialPort(char* SerialPReponse, int Chmax)
    {
        int iIn,dawf;
     
        //printf("in ReadAdrPort Chmax=%d\n", Chmax);
        if (fd < 1)
        {
            printf(" Port série non ouvert\n");
            return -1;
        } // end if
        strncpy (SerialPReponse, "N/A", Chmax<4?Chmax:4); //si Chmax est < 4, alors on prend Chmax, sinon 4
        iIn = read(fd, SerialPReponse, Chmax-1);
        if (iIn < 0)
        {
        	if (errno == EAGAIN)
        	{
                return 0; // assume that command generated no response
            }
            else
            {
                printf("Erreur de lecture %d %s\n", errno, strerror(errno));
            }
        }
        else
        {
        	SerialPReponse[iIn<Chmax?iIn:Chmax] = '\0';
    	    printf("%d carcatères ont été lu: %s\n", iIn, SerialPReponse);
    	    dawf=strlen(SerialPReponse);
    	    printf ("longueur %d \n",dawf);
     
        }
        return iIn;
    }
     
    int SerialPort_sendByte(int caract){
     
        unsigned char c = (unsigned char)caract;
     
        if ( caract >= 0 && caract < 256 )
        {
            write(fd, &c, 1);
            //printf("Sending: %02X\n",c);
            //usleep(20000);
            return 0;
        }else return 1;
     
    }
     
     
    int main ()
    {
        char sCmd[255];
    	char sResult[255];
    	int i;
     
    	//strcpy(sCmd,"105B086316");
     
        if (OpenSerialPort < 0) return 0;
     
        printf("tagada");
        //if (WriteSerialPort(sCmd) < 0) return 0;
    		//sleep(1); // temps d'attente pour une réponse
    		/*
    SerialPort_sendByte(0x10);
    SerialPort_sendByte(0x5B);
    SerialPort_sendByte(0x08);
    SerialPort_sendByte(0x63);
    SerialPort_sendByte(0x16);
    usleep(1000);
     
        if (ReadSerialPort(sResult,255) > 0)
    	{
    			printf("La reponse fut: %s\n", sResult);
    			fflush (stdout);
    	}
    */
        //ResetSerialPort();
    //sleep(5);
        return 1;
    }
    Merci pour votre aide

  2. #2
    Modérateur
    Avatar de Obsidian
    Homme Profil pro
    Développeur en systèmes embarqués
    Inscrit en
    Septembre 2007
    Messages
    7 388
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : France, Essonne (Île de France)

    Informations professionnelles :
    Activité : Développeur en systèmes embarqués
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2007
    Messages : 7 388
    Points : 23 707
    Points
    23 707
    Par défaut
    As-tu regardé du côté de cfsetispeed() et cfsetospeed() ?

  3. #3
    Membre à l'essai
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    18
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2006
    Messages : 18
    Points : 11
    Points
    11
    Par défaut
    Non, mais entre temps j'ai trouvé des erreurs et j'ai bidouillé qq trucs ci et là

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
     
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <termios.h>
    #include <string.h>
    #include <sys/ioctl.h>
    #include <errno.h>
    #include "serial.h"
    int fd = 2;
     
     
     
    int OpenSerialPort()
    {
        int dawf;
     
       //ouverture port serie en mode non-bloquant (read fait un return imédiat)
          fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY ); //O_RDWR | O_NOCTTY | O_NONBLOCK);
     
          if (fd < 0)
          {
             perror(DEVICE);
             exit(-1);
          }
        int rate;
        rate= B300;
     
        tcgetattr(fd,&oldtio); // sauvegarde de la configuration courante
     
     
         /*printf("old cflag=%08x\n", oldtio.c_cflag);
            printf("old oflag=%08x\n", oldtio.c_oflag);
            printf("old iflag=%08x\n", oldtio.c_iflag);
            printf("old lflag=%08x\n", oldtio.c_lflag);
            printf("old line=%02x\n", oldtio.c_line);
     
            fflush(stdout);*/
     
        bzero(&newtio, sizeof(newtio));
     
        /*newtio.c_cflag = rate| CS8 | ~CSTOPB | PARENB | ~PARODD | CLOCAL | CREAD;
        //newtio.c_iflag = IGNPAR;
        newtio.c_oflag = 0;
        newtio.c_lflag = 0;       //ICANON;
        //newtio.c_cc[VMIN]=1;
        //newtio.c_cc[VTIME]=0;*/
     
       settings.c_line = 0;
     
       settings.c_lflag &= ~(ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOKE|ECHOCTL|IEXTEN);
     
       settings.c_iflag &= ~(INLCR|IGNCR|ICRNL|IUCLC|IXON|IXOFF|IMAXBEL|PARMRK);
       settings.c_iflag |= IGNBRK;
       settings.c_iflag |= IGNPAR;
     
       settings.c_oflag &= ~(OLCUC|ONLCR|OCRNL|ONLRET|OFILL|OFDEL|OPOST);
     
       settings.c_cflag &= (CSTOPB|PARODD|HUPCL|CRTSCTS|ISIG|ICANON|ECHO);
       settings.c_cflag |= CREAD;
       settings.c_cflag |= CLOCAL;
       settings.c_cflag |= CS8;
       settings.c_cflag |= PARENB;
       settings.c_cflag |= B300;
     
        settings.c_cc[VMIN] = 0;
        settings.c_cc[VTIME] = 0;
     
     
     
     
        // à présent, on vide la ligne du port, et on active la configuration
        tcflush(fd, TCIFLUSH);
        if ((dawf=tcsetattr(fd,TCSANOW,&settings))<0){
            printf("erreur applicatin nouveau config");
            fflush(stdout);
            return -1;
        }
     
        //printf ("applique ? %d \n",dawf);
        fcntl(fd, F_SETFL, getpid());
        return fd; //renvoit résultat tentative ouverture
     
     
     
     
     
    }
     
    int ResetSerialPort()
    {
        //restaure l'ancienne configuration du port série
        tcsetattr(fd,TCSANOW,&oldtio);
        return 0;
    }
     
    int WriteSerialPort(char* SerialPOut)
    {
        int iOut;
        if (fd < 1)
        {
            printf(" Port série non ouvert   %d\n", fd);
            return -1;
        } // end if
        iOut = write(fd, SerialPOut, strlen(SerialPOut));
        if (iOut < 0)
        {
            printf("Erreur écriture %d %s\n", errno, strerror(errno));
        }
        else
        {
        	printf("%d caractères ont été écrit: %s\n", iOut, SerialPOut);
        }
        return iOut; //renvoit le résultat de l'écriture
    }
     
     
    int ReadSerialPort(unsigned char SerialPReponse, int Chmax)
    {
        int iIn;
     
        //printf("in ReadAdrPort Chmax=%d\n", Chmax);
        if (fd < 1)
        {
            printf(" Port série non ouvert\n");
            return -1;
        } // end if
        //strncpy (SerialPReponse, "N/A", Chmax<4?Chmax:4); //si Chmax est < 4, alors on prend Chmax, sinon 4
        iIn = read(fd, &SerialPReponse, Chmax-1);
        if (iIn < 0)
        {
        	if (errno == EAGAIN)
        	{
                return 0; // assume that command generated no response
            }
            else
            {
                printf("Erreur de lecture %d %s\n", errno, strerror(errno));
            }
        }
        else
        {
        	//SerialPReponse[iIn<Chmax?iIn:Chmax] = '\0';
    	    /*printf("%d carcatères ont été lu: %s\n", iIn, SerialPReponse);
    	    dawf=strlen(SerialPReponse);
    	    printf ("longueur %d \n",dawf);*/
     
        }
        return iIn;
    }
     
    int SerialPort_readByte(){
         char buffer;
         read(fd, &buffer, 1);
         //SerialPort.lastbyteread = (int)buffer;
         //return SerialPort.lastbyteread;
         printf("Received: %02X\n",buffer);
         return 0;
    }
     
    int SerialPort_sendByte(int caract){
     
        unsigned char c = (unsigned char)caract;
     
        if ( caract >= 0 && caract < 256 )
        {
            write(fd, &c, 1);
            //printf("Sending: %02X\n",c);
            //usleep(20000);
            return 0;
        }else return 1;
     
    }
     
     
    int main ()
    {
        //char sCmd[255];
    	unsigned char sResult;
    	//int i;
     
    	//strcpy(sCmd,"105B086316");
     
        if (OpenSerialPort() < 0){ printf ("merdouille");}
        //OpenSerialPort();
     
        /*while (1){
        printf("tagada d");
        fflush (stdout);
        sleep (2);}*/
     
        /*if (WriteSerialPort(sCmd) < 0) return 0;
    		sleep(1); // temps d'attente pour une réponse
    		*/
     
    SerialPort_sendByte(0x10);
    SerialPort_sendByte(0x5B);
    SerialPort_sendByte(0x08);
    SerialPort_sendByte(0x63);
    SerialPort_sendByte(0x16);
    //sleep(1);
     
    /*while (1){
        SerialPort_readByte();
    }*/
    printf("avant: %02X\n", sResult);
     
    //SerialPort_readByte();
     
        if (ReadSerialPort(sResult,1024) > 0)
    	{
    			printf("La reponse fut: %02X\n", sResult);
    			fflush (stdout);
    	}
        //ResetSerialPort();
    //sleep(5);
        return 1;
    }

  4. #4
    Membre régulier
    Profil pro
    Inscrit en
    Avril 2006
    Messages
    107
    Détails du profil
    Informations personnelles :
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Avril 2006
    Messages : 107
    Points : 124
    Points
    124
    Par défaut
    Salut,
    Voila le code que j'utilisais pour configurer et utiliser le port série :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    27
    28
     
    #ifndef fonctionsSeriepointh
    #define fonctionsSeriepointh
     
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <termio.h>
    #include <sys/time.h>
    #include <sys/types.h> 
     
    enum {VRAI=1, FAUX=-1}booleen;
     
    int ByteWaiting(int theDevice,unsigned int timeOut);
    unsigned int ReadBytes(int theDevice,unsigned char *theBytes,unsigned int maxBytes);
    void WriteBytes(int theDevice,unsigned char *theBytes,unsigned int numBytes);
    void FlushBytes(int theDevice);
    int ConfigureDevice(int theDevice,unsigned int baudRate,unsigned char dataBits,unsigned char stopBits,unsigned char parity,int cooked);
    void GetDeviceConfiguration(int theDevice,unsigned int *baudRate,unsigned char *dataBits,unsigned char *stopBits,unsigned char *parity);
    int ConfigureFlowControl(int theDevice,int wantControl);
    void GetDeviceStatus(int theDevice,int *CTS,int *DCD);
    void SetDTR(int theDevice,int DTR);
    int OpenDevice(char *theName,int *theDevice);
    void CloseDevice(int theDevice);
    int messageDispo(int port1, int port2);
    #endif
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
     
     
     
    #include "fonctionsSerie.h"
     
    fd_set readfds;
     
     
    int messageDispo(int port1, int port2){
    /*SE REPORTER A LA PAGE DE MAN POUR COMPRENDRE : 
    http://www.linux-kheops.com/doc/man/manfr/man-html-0.9/man2/select.2.html    */
    	int portPret;
    	FD_ZERO(&readfds);		// efface l'ensemble
    	FD_SET(port1,&readfds);	// on ajoute les 2 ports series à l'ensemble à surveiller
    	FD_SET(port2,&readfds);
    	//on attend indefiniment qu'il y ai quelquechose a lire sur l'un des deux ports :
    	if(select(FD_SETSIZE,&readfds,NULL,NULL,NULL)>0)
    	{
    		//on regarde sur quel port il s'est passé quelque chose
    		if (FD_ISSET(port1,&readfds)){ 
    			//le port1 est pret en lecture
    			//printf("port1 pret en lecture\n");
    			portPret=port1;
    			}
    		if (FD_ISSET(port2,&readfds)) { 
    			//le port2 est pret en lecture
    			//printf("port2 pret en lecture\n");
    			portPret=port2;
    			}
    	}
    	//on fait une petite pause afin d'avoir le temps de recevoir tout 
    	//le message sur le port serie.
    	usleep(1000);
    	//on renvoit le numéro du port qui est pret
    	return(portPret);
    }
     
     
    unsigned int ReadBytes(int theDevice,unsigned char *theBytes,unsigned int maxBytes)
    {
    	unsigned int numRead;
    		//li ce qu'il y a dans le tampon du port serie
    		if((numRead=read(theDevice,theBytes,maxBytes))>0)
    		{
    			return(numRead);
    		}
    	//retourne faux s'il ny avait rien et donc qu'on a rien lu.
    	return(0);
    }
     
    void WriteBytes(int theDevice,unsigned char *theBytes,unsigned int numBytes)
    // Write theBytes to theDevice.
    {
    	write(theDevice,theBytes,numBytes);
    }
     
    void FlushBytes(int theDevice)
    // Flush any bytes that may be waiting at theDevice
    {
    	ioctl(theDevice,TCFLSH,0);		// flush the input stream
    }
     
    int ConfigureDevice(int theDevice,unsigned int baudRate,unsigned char dataBits,unsigned char stopBits,unsigned char parity,int cooked)
    // set up data transmission configuration of theDevice
    // NOTE: if any of the passed parameters is invalid, it will be set
    // to an arbitrary valid value
    // baudRate is: 50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
    // dataBits is 7 or 8
    // stopBits is 1 or 2
    // parity is 0=none,
    //           1=odd,
    //           2=even
    // cooked : #include <sys/time.h>1 if you want to set up the serial port to be used as a terminal.
    // if there is a problem, return false
    {
    	struct termios
    		terminalParams;
    	speed_t
    		theSpeed;
     
    	if(ioctl(theDevice,TCGETS,&terminalParams)!=-1)	// read the old value
    	{
    		switch(baudRate)
    		{
    			case 50:
    				theSpeed=B50;
    				break;
    			case 75:
    				theSpeed=B75;
    				break;
    			case 110:
    				theSpeed=B110;
    				break;
    			case 134:
    				theSpeed=B134;
    				break;
    			case 150:
    				theSpeed=B150;
    				break;
    			case 200:
    				theSpeed=B200;
    				break;
    			case 300:
    				theSpeed=B300;
    				break;
    			case 600:
    				theSpeed=B600;
    				break;
    			case 1200:
    				theSpeed=B1200;
    				break;
    			case 1800:
    				theSpeed=B1800;
    				break;
    			case 2400:
    				theSpeed=B2400;
    				break;
    			case 4800:
    				theSpeed=B4800;
    				break;
    			case 9600:
    				theSpeed=B9600;
    				break;
    			case 19200:
    				theSpeed=B19200;
    				break;
    			case 38400:
    				theSpeed=B38400;
    				break;
    			case 57600:
    				theSpeed=B57600;
    				break;
    			case 115200:
    				theSpeed=B115200;
    				break;
    			case 230400:
    				theSpeed=B230400;
    				break;
    			case 460800:
    				theSpeed=B460800;
    				break;
    			default:
    				theSpeed=B9600;
    				break;
    		}
    		cfsetospeed(&terminalParams,theSpeed);
    		cfsetispeed(&terminalParams,theSpeed);
     
    		terminalParams.c_cflag&=~CSIZE;		// mask off the data bits
    		switch(dataBits)
    		{
    			case 7:
    				terminalParams.c_cflag|=CS7;
    				break;
    			case 8:
    			default:
    				terminalParams.c_cflag|=CS8;
    				break;
    		}
     
    		terminalParams.c_cflag&=~CSTOPB;	// mask off the stop bits
    		switch(stopBits)
    		{
    			case 1:
    				break;
    			case 2:
    				terminalParams.c_cflag|=CSTOPB;
    				break;
    			default:
    				break;
    		}
     
    		terminalParams.c_cflag&=~(PARENB|PARODD);	// mask off the parity bits
    		switch(parity)
    		{
    			case 0:
    				break;
    			case 1:
    				terminalParams.c_cflag|=(PARENB|PARODD);	// odd parity
    				break;
    			case 2:
    				terminalParams.c_cflag|=PARENB;		// even parity
    				break;
    			default:
    				break;
    		}
     
    		terminalParams.c_cflag|=CREAD;		// allow reading
     
    		if(cooked)							// use this when setting up the serial port to be used as a terminal
    		{
    			terminalParams.c_iflag=ICRNL;
    			terminalParams.c_oflag=OPOST|ONLCR;
    			terminalParams.c_lflag=ISIG|ICANON|ECHO|ECHOE|ECHONL;
    		}
    		else
    		{
    			terminalParams.c_iflag=0;
    			terminalParams.c_oflag=0;
    			terminalParams.c_lflag=0;
    		}
    		terminalParams.c_cc[VMIN]=0;		// read returns immediately if no characters
    		terminalParams.c_cc[VTIME]=0;
     
    		if(ioctl(theDevice,TCSETS,&terminalParams)!=-1)
    		{
    			return(VRAI);
    		}
    	}
    	return(FAUX);
    }
     
    void GetDeviceConfiguration(int theDevice,unsigned int *baudRate,unsigned char *dataBits,unsigned char *stopBits,unsigned char *parity)
    // return the configuration of theDevice
    // baudRate is: 50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200,230400,460800
    // dataBits is 7 or 8
    // stopBits is 1 or 2
    // parity is 0=none,
    //           1=odd,
    //           2=even
    {
    	struct termios
    		terminalParams;
     
    	if(ioctl(theDevice,TCGETS,&terminalParams)!=-1)	// read the old value
    	{
    		switch(cfgetospeed(&terminalParams))
    		{
    			case B50:
    				*baudRate=50;
    				break;
    			case B75:
    				*baudRate=75;
    				break;
    			case B110:
    				*baudRate=110;
    				break;
    			case B134:
    				*baudRate=134;
    				break;
    			case B150:
    				*baudRate=150;
    				break;
    			case B200:
    				*baudRate=200;
    				break;
    			case B300:
    				*baudRate=300;
    				break;
    			case B600:
    				*baudRate=600;
    				break;
    			case B1200:
    				*baudRate=1200;
    				break;
    			case B1800:
    				*baudRate=1800;
    				break;
    			case B2400:
    				*baudRate=2400;
    				break;
    			case B4800:
    				*baudRate=4800;
    				break;
    			case B9600:
    				*baudRate=9600;
    				break;
    			case B19200:
    				*baudRate=19200;
    				break;
    			case B38400:
    				*baudRate=38400;
    				break;
    			case B57600:
    				*baudRate=57600;
    				break;
    			case B115200:
    				*baudRate=115200;
    				break;
    			case B230400:
    				*baudRate=230400;
    				break;
    			case B460800:
    				*baudRate=460800;
    				break;
    			default:
    				*baudRate=0;
    				break;
    		}
     
    		switch(terminalParams.c_cflag&CSIZE)
    		{
    			case CS7:
    				*dataBits=7;
    				break;
    			case CS8:
    				*dataBits=8;
    				break;
    			default:
    				*dataBits=0;
    				break;
    		}
     
    		*stopBits=1;
    		if(terminalParams.c_cflag&CSTOPB)
    		{
    			*stopBits=2;
    		}
     
    		*parity=0;
    		if(terminalParams.c_cflag&PARENB)
    		{
    			if(terminalParams.c_cflag&PARODD)
    			{
    				*parity=1;
    			}
    			else
    			{
    				*parity=2;
    			}
    		}
    	}
    }
     
    int ConfigureFlowControl(int theDevice,int wantControl)
    // if wantControl is true, configure theDevice to use CTS/RTS hardware
    // flow control, if false, turn off flow control
    // NOTE: when flow control is off, we must drive our RTS line to the
    // modem active at all times
    // if there is a problem, return false
    {
    	struct termios
    		terminalParams;
     
    	if(ioctl(theDevice,TCGETS,&terminalParams)!=-1)	// read the old value
    	{
    		if(wantControl==1)
    		{
    			terminalParams.c_cflag|=CRTSCTS;		// set flow control
    		}
    		else
    		{
    			terminalParams.c_cflag&=~CRTSCTS;		// clear flow control
    		}
    		terminalParams.c_cc[VMIN]=0;				// read returns immediately if no characters
    		terminalParams.c_cc[VTIME]=0;
    		if(ioctl(theDevice,TCSETS,&terminalParams)!=-1)
    		{
    			return(1);
    		}
    	}
    	return(0);
    }
     
     
     
    int OpenDevice(char *theName,int *theDevice)
    // Open theName immediately for both read/write
    // (do not block under any circumstances)
    // return a device handle.
    // NOTE: since the device can be opened BEFORE it is locked,
    // this function MUST NOT modify the parameters of the device
    // or in any way mess with it!!
    // if there is a problem, set the error, and return false
    {
    	struct termios terminalParams;
     
    	if((*theDevice=open(theName,O_NDELAY|O_RDWR|O_NOCTTY))!=-1)	
    	{
    		if(ioctl(*theDevice,TCGETS,&terminalParams)!=-1)		
    		// attempt to read configuration, just to verify this is a serial device
    		{
    			return(VRAI);
    		}
    		close(*theDevice);
    	}
    	return(FAUX);
    }
     
    void CloseDevice(int theDevice)
    // Close theDevice
    {
    	close(theDevice);
    }
    À utiliser de la manière suivante :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    /*on ouvre les ports*/
    	OpenDevice("/dev/ttyS0", &portSerie1);
    	OpenDevice("/dev/ttyS1", &portSerie2);
    	/*on configure les transmissions*/
    	ConfigureDevice(portSerie1,9600,8,1,0,0);
    	ConfigureDevice(portSerie2,9600,8,1,0,0);
    	ConfigureFlowControl(portSerie1,0);
    	ConfigureFlowControl(portSerie2,0);
    	/*on vide les tampons systemes des ports séries*/
    	FlushBytes(portSerie1);
    	FlushBytes(portSerie2);
    	/*--ports series pret a lutilisation--*/
    Il te faut les droits sur le(s) port(s) série (chmod)
    En espérant que ça t'aide.

  5. #5
    Membre à l'essai
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    18
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2006
    Messages : 18
    Points : 11
    Points
    11
    Par défaut
    merci bien, mais le code que j'ai reposté juste avant était fonctionnel

Discussions similaires

  1. Communication port série linux
    Par Matrix33 dans le forum Shell et commandes GNU
    Réponses: 3
    Dernier message: 25/04/2014, 11h47
  2. Pb fonction read sur port série - GCC LINUX
    Par Signal40 dans le forum POSIX
    Réponses: 5
    Dernier message: 02/08/2010, 20h33
  3. Lecture sur port série sous Linux
    Par DangerousBowlOfJelly dans le forum C
    Réponses: 6
    Dernier message: 28/03/2008, 17h00
  4. Communication à sens unique sur port série
    Par ViveLesQuads dans le forum Windows XP
    Réponses: 3
    Dernier message: 15/12/2007, 17h58
  5. [Débutant] Réception sur port série
    Par Tophe59 dans le forum Langage
    Réponses: 43
    Dernier message: 28/06/2004, 11h04

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo