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

Entrée/Sortie Java Discussion :

Transmission / Réception par le COM1


Sujet :

Entrée/Sortie Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Invité1
    Invité(e)
    Par défaut Transmission / Réception par le COM1
    Bonjour, n'ayant pas trouvé de documentation concernant le port USB, donc j'ai décidé d'utiliser le port série (COM1) avec javax,comm

    voici le code que j'ai testé et ça marche

    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
     
    import java.util.*;
    import javax.comm.*;
    import com.sun.comm.Win32Driver;
     
    public class port {
    	public static void main(String[] args) {
    		//initialisation du driver
    		Win32Driver w32Driver= new Win32Driver();
    		w32Driver.initialize();
     
    		//récupération de l'énumération
    		Enumeration portList=CommPortIdentifier.getPortIdentifiers();
     
    		//affichage des noms des ports
    		CommPortIdentifier portId;
    		while (portList.hasMoreElements()){
    			portId=(CommPortIdentifier)portList.nextElement();
    			System.out.println(portId.getName());
    		}
    	}
     
    }
    2eme étape c'est l'envoie et la réception d'une donnée, et la je ne sais pas comment faire, je doit avoir un émetteur et un récepteur

    quelqu'un aurait il une idée

    merci

  2. #2
    Invité1
    Invité(e)
    Par défaut
    Bonjour a tous,

    après des recherches j'ai trouvé ce tutoriel de Mr Christophe Jollivet (Utilisation de l'api javax.comm pour les ports séries),

    http://christophej.developpez.com/tu...vacomm/#L2.3.3

    voici le code que j'ai utilisé:

    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
     
    import javax.comm.*;
    import com.sun.comm.Win32Driver;
    import java.io.*;
    import java.util.*;
     
    public class port implements Runnable, SerialPortEventListener {
       static CommPortIdentifier portId;
       static CommPortIdentifier saveportId;
       static Enumeration        portList;
       InputStream           inputStream;
       SerialPort           serialPort;
       Thread           readThread;
     
       static String        messageString = "1234";
       static OutputStream      outputStream;
       static boolean        outputBufferEmptyFlag = false;
     
       public static void main(String[] args) {
          boolean           portFound = false;
          String           defaultPort;
     
          Win32Driver w32Driver= new Win32Driver();
          w32Driver.initialize();
     
          // determine the name of the serial port on several operating systems
          String osname = System.getProperty("os.name","").toLowerCase();
          if ( osname.startsWith("windows") ) {
             // windows
             defaultPort = "COM1";
          } else if (osname.startsWith("linux")) {
             // linux
            defaultPort = "/dev/ttyS0";
         } else if ( osname.startsWith("mac") ) {
             // mac
             defaultPort = "????";
          } else {
             System.out.println("Sorry, your operating system is not supported");
            return;
          }
     
          if (args.length > 0) {
             defaultPort = args[0];
          } 
     
          System.out.println("Set default port to "+defaultPort);
     
    		// parse ports and if the default port is found, initialized the reader
          portList = CommPortIdentifier.getPortIdentifiers();
          while (portList.hasMoreElements()) {
             portId = (CommPortIdentifier) portList.nextElement();
             if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals(defaultPort)) {
                   System.out.println("Found port: "+defaultPort);
                   portFound = true;
                   // init reader thread
                   port reader = new port();
                } 
             } 
     
          } 
          if (!portFound) {
             System.out.println("port " + defaultPort + " not found.");
          } 
     
       } 
     
       public void initwritetoport() {
          // initwritetoport() assumes that the port has already been opened and
          //    initialized by "public nulltest()"
     
          try {
             // get the outputstream
             outputStream = serialPort.getOutputStream();
          } catch (IOException e) {}
     
          try {
             // activate the OUTPUT_BUFFER_EMPTY notifier
             serialPort.notifyOnOutputEmpty(true);
          } catch (Exception e) {
             System.out.println("Error setting event notification");
             System.out.println(e.toString());
             System.exit(-1);
          }
     
       }
     
       public void writetoport() {
          System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());
          try {
             // write string to serial port
             outputStream.write(messageString.getBytes());
          } catch (IOException e) {}
       }
     
       public port() {
          // initalize serial port
          try {
             serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
          } catch (PortInUseException e) {}
     
          try {
             inputStream = serialPort.getInputStream();
          } catch (IOException e) {}
     
          try {
             serialPort.addEventListener(this);
          } catch (TooManyListenersException e) {}
     
          // activate the DATA_AVAILABLE notifier
          serialPort.notifyOnDataAvailable(true);
     
          try {
             // set port parameters
             serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, 
                         SerialPort.STOPBITS_1, 
                         SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {}
     
          // start the read thread
          readThread = new Thread(this);
          readThread.start();
     
       }
     
       public void run() {
          // first thing in the thread, we initialize the write operation
          initwritetoport();
          try {
             while (true) {
                // write string to port, the serialEvent will read it
        	     writetoport();
                Thread.sleep(1000);
             }
          } catch (InterruptedException e) {}
       } 
     
       public void serialEvent(SerialPortEvent event) {
    	      switch (event.getEventType()) {
    	      case SerialPortEvent.BI:
    	      case SerialPortEvent.OE:
    	      case SerialPortEvent.FE:
    	      case SerialPortEvent.PE:
    	      case SerialPortEvent.CD:
    	      case SerialPortEvent.CTS:
    	      case SerialPortEvent.DSR:
    	      case SerialPortEvent.RI:
    	      case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    	         break;
    	      case SerialPortEvent.DATA_AVAILABLE:
    	         // we get here if data has been received
    	         byte[] readBuffer = new byte[20];
    	         try {
    	            // read data
    	            while (inputStream.available() > 0) {
    	               int numBytes = inputStream.read(readBuffer);
    	            } 
    	            // print data
    	            String result  = new String(readBuffer);
    	            System.out.println("Read: "+result);
    	         } catch (IOException e) {}
     
    	         break;
    	      }
    	   } 
     
    }
    ça marche très bien, j'ai shunté les broches 2 et 3 du COM1 pour voir le résultat

    maintenant il me reste plus qu'a séparer le code de transmission de celui de la réception et supprimer les parties dont je n'est pas besoin.

    Bonne journée

  3. #3
    Membre confirmé
    Inscrit en
    Avril 2009
    Messages
    126
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 126
    Par défaut netbeans et rs232
    salut


    j'ai presque même principe d'application

    j'ai télécharge le fichier qui contient :
    **comm.jar
    **javax.comm.properties
    **win32com.dll

    ---> win32com.dll dans dans le répertoire Windows/system32
    ---> dans le répertoire de mon projet j'ai créé un dossier "lib" et je met comm.jar et javax.comm.properties
    ---> sous netbeans :cilk droit sur Libraries add jar/fl ---ajouter comm.jar

    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
    import javax.comm.*;
    import com.sun.comm.Win32Driver;
    import java.util.Enumeration;
    public class New {
    //initialisation du driver
    Win32Driver w32Driver= new Win32Driver();
    w32Driver.initialize();
    //récupération de l'énumération
    Enumeration portList=CommPortIdentifier.getPortIdentifiers();
    //affichage des noms des ports
    CommPortIdentifier portId;
    while (portList.hasMoreElements()){
    	portId=(CommPortIdentifier)portList.nextElement();
    	System.out.println(portId.getName());
    }
    }
    ====> pacakage w32Driver soes not exist !!!!!!!

  4. #4
    Invité1
    Invité(e)
    Par défaut
    Citation Envoyé par pikamo Voir le message
    salut
    ====> pacakage w32Driver soes not exist !!!!!!!
    bjr, essaies ça: tu edit le fichier "javax.comm.properties" avec le bloc notes et tu rajoutes cette ligne

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    driver=com.sun.comm.Win32Driver
    et merci à slim_java je vais essayer avec cette API

    bonne journée

  5. #5
    Membre confirmé
    Inscrit en
    Avril 2009
    Messages
    126
    Détails du profil
    Informations forums :
    Inscription : Avril 2009
    Messages : 126
    Par défaut
    salut
    w32Driver , elle marche chez moi
    merci
    mais mnt je veux utiliser ton code mais d'autre façon.
    ton code reçoit un message "result" a condition qu'il au début envoyer un message "1234 ".
    j'ai notifier ton code pour envoyer une seul fois:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    public void writetoport(String s)
    c'est bien marcher
    mon but de faire :
    une fonction comme "public void writetoport(String s)" pour simplement envoyer .
    et une autre fonction pour lire de port .
    pour me facilite l'appel après dans une autre class?
    j'ai essaye ce code mais il ne marche pas
    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
    import javax.comm.*;
    import com.sun.comm.Win32Driver;
    import java.io.*;
    import java.util.*;
     
    public class Open {
    static CommPortIdentifier portId;
    static CommPortIdentifier saveportId;
    static Enumeration        portList;
    InputStream           inputStream;
    SerialPort           serialPort;
    static OutputStream      outputStream;
     
    public static void main(String[] args) {
     boolean           portFound = false;
     String           defaultPort ;
     
     Win32Driver w32Driver= new Win32Driver();
     w32Driver.initialize();
     
     
     defaultPort = "COM1";
     
    System.out.println("Set default port to "+defaultPort);
    //ports analyser et si le port par défaut est trouvé, initialisé le lecteur
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
    portId = (CommPortIdentifier) portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    if (portId.getName().equals(defaultPort)) {
    System.out.println("Found port: "+defaultPort);
    portFound = true;
     
        }
      }
    }
    if (!portFound) {
    System.out.println("port " + defaultPort + " not found.");
          }
    }
       public Open() {
          // initalize port série
          try {
             serialPort = (SerialPort) portId.open("ecrirers232", 2000);
          } catch (PortInUseException e) {}
     
          try {
             inputStream = serialPort.getInputStream();
          } catch (IOException e) {}
    }
       public void initwritetoport() {
    //initwritetoport () suppose que le port a déjà été ouvert et
    //initialisé par "nulltest publique ()"
    try {
    // obtenir le flux sortant
    outputStream = serialPort.getOutputStream();
    } catch (IOException e) {}
    }
     public void writetoport(String s) {
          System.out.println("Writing \""+s+"\" to "+serialPort.getName());
          try {
     // Donnez votre chaîne sur le port série
             outputStream.write(s.getBytes());
          } catch (IOException e) {}
       }
      public void run() {
    // première chose que dans le fil, on initialise l'opération d'écriture
          initwritetoport();
     
     
     // écrit une chaîne dans le port, le serialEvent vais le lire
        	     writetoport("hello");
     
             }
     
       }

  6. #6
    Membre Expert
    Avatar de slim_java
    Homme Profil pro
    Enseignant
    Inscrit en
    Septembre 2008
    Messages
    2 272
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Enseignement

    Informations forums :
    Inscription : Septembre 2008
    Messages : 2 272
    Par défaut
    Citation Envoyé par samy larson Voir le message
    Bonjour, n'ayant pas trouvé de documentation concernant le port USB
    salut.
    sinon , tu peux essayer cette API

Discussions similaires

  1. Codage des entiers dans socket (réception par java)
    Par theanthony33 dans le forum C#
    Réponses: 3
    Dernier message: 26/06/2010, 21h16
  2. Transmission/Réception partielle de structure via socket
    Par Djakisback dans le forum Réseau
    Réponses: 39
    Dernier message: 11/12/2009, 10h57
  3. Réponses: 2
    Dernier message: 04/01/2009, 15h55
  4. [PHP-JS] Transmission variable par URL avec champ caché
    Par Interface dans le forum Langage
    Réponses: 2
    Dernier message: 03/09/2007, 19h09
  5. Emission / Réception par port série
    Par odSen dans le forum C
    Réponses: 28
    Dernier message: 06/01/2006, 18h45

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