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 :

Développement en C# avec VS2008


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Nouveau membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2012
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Avril 2012
    Messages : 5
    Par défaut Développement en C# avec VS2008
    Bonjour,
    j'ai un souci dans mon développement en C# avec visual studio 2008.

    Je cherche a envoyer des donnée du PC1 vers PC2 en les reliant d'un cable RS232 et mon code se bloque au meme endroit sur les deux ordis sur la fonction SerialPort1.Write lorsque je veux clique sur le bouton1 qui est mon bouton ENVOYER sur Windows Form.

    Donc je ne peux recevoir les donnée que j'envoie puisque ça bloque et je ne trouve pas mon erreur.
    Voici mon code
    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
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
     
     
    namespace td5
    {
        public partial class Form1 : Form
        {
            const int MAXDATA = 512;
            const byte TERMINATEUR = 0x0A;
            public int giIndex ;
            byte[] MyReceiveBuffer = new byte[MAXDATA];
     
     
     
            public Form1()
            {
                InitializeComponent();
                System.Windows.Forms.TextBox.CheckForIllegalCrossThreadCalls = false;
                giIndex = 0 ;
            }
     
            private void button2_Click(object sender, EventArgs e)
            {
                textBox2.Text = "";
            }
     
     
            private void Form1_Load(object sender, EventArgs e)
            {
                if (serialPort1.IsOpen == false)
                    serialPort1.Open();
     
                textBox3.AppendText("Programme demarré" + Environment.NewLine);
     
                serialPort1.ReadExisting();
     
            }
     
            private void button1_Click(object sender, EventArgs e)
           {
                serialPort1.Write(textBox1.Text);
           }
     
            private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            {
                int iNbByteReceived;
                string szCommande;
     
     
                ASCIIEncoding ascii = new ASCIIEncoding();
                iNbByteReceived = serialPort1.BytesToRead;
     
                textBox3.AppendText("reception de " + iNbByteReceived.ToString() + "octets");
                textBox3.AppendText(Environment.NewLine);
     
                if (iNbByteReceived != 0)
                {
                    serialPort1.Read(MyReceiveBuffer, giIndex, iNbByteReceived);
                    giIndex = giIndex + iNbByteReceived;
     
                    if (MyReceiveBuffer[giIndex - 1] == TERMINATEUR) 
                    {
                        szCommande = ascii.GetString(MyReceiveBuffer, 0, giIndex - 2);
     
                        textBox2.Text = textBox2.Text + szCommande;
     
                        giIndex = 0;
                        //textBox2.AppendText("caractere CR reçu " + Environment.NewLine);
     
                      /*  switch (MyReceiveBuffer.ToString()) 
                        {
                            case "\r"             : textBox1.AppendText("\r<Executed/>"); break;
                            case "initlogging\r"  : textBox1.AppendText("initlogging\rthis command will change the scan length and/or initialize logging\rrepeat the command to verify\r<Executed/>"); break;
                            case " startnow\r"    : textBox1.AppendText(" "); break;
                            case "Stop\r"         : textBox1.AppendText("Stop"); break;
                        }
    */
     
                    }
                }
     
            }
     
            private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                switch (listBox1.SelectedItem.ToString())
                {
                    case "300"  :  serialPort1.BaudRate = 300; break;
                    case "600"  :  serialPort1.BaudRate = 600; break;
                    case "1200" :  serialPort1.BaudRate = 1200; break;
                    case "2400" :  serialPort1.BaudRate = 2400; break;
                    case "4800" :  serialPort1.BaudRate = 4800; break;
                    case "9600" :  serialPort1.BaudRate = 9600; break;
                    default     :  serialPort1.BaudRate = 9600; break;
     
                }
            }
        }
     }
    Merci de votre aide

  2. #2
    Invité
    Invité(e)
    Par défaut
    Je vois déjà un point qui me parait très bizarre, tu ouvres ton port avant de configurer la vitesse. Normalement on configure le port avant de l'ouvrir.

    Tu devrais aller voir a cette adresse il y a des chose intéressante pour configurer et utilisé le port serie.

    http://msdn.microsoft.com/fr-fr/libr...erialport.aspx

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Décembre 2011
    Messages
    62
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2011
    Messages : 62
    Par défaut
    As-tu un message d'erreur ?

    J'ai également rencontré un soucis avec les ports séries, mais maintenant ça marche, voici mon code, ça peut peut-être t'aider

    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
     
    using System;
    using System.Linq;
    using System.Data;
    using System.Text;
    using System.Drawing;
    using System.IO.Ports;
    using System.Windows.Forms;
    using System.ComponentModel;
    using System.Collections.Generic;
     
    using System.Threading;
    using System.IO;
     
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            private SerialPort sp = new SerialPort();
            public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
            private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };
            public string trame = string.Empty;
     
            public Form1()
            {
                InitializeComponent();
     
                sp.BaudRate = 4800;
                sp.Parity = Parity.None;
                sp.StopBits = StopBits.One;
                sp.DataBits = 8;
                sp.ReceivedBytesThreshold = 1;
                sp.RtsEnable = true;
                sp.Handshake = Handshake.None;
                sp.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
     
            }
     
            private void button1_Click(object sender, EventArgs e)
            {
                bool erreur = false;
     
                // Si le port est ouvert, il faut le fermer
                if (sp.IsOpen) sp.Close();
                else
                {
                    // Réglage paramètre du port
                    sp.PortName = cmbPortName.Text;
     
                    try
                    {
                        // Ouvrir le port
                        sp.Open();
                    }
                    catch (UnauthorizedAccessException) { erreur = true; }
                    catch (IOException) { erreur = true; }
                    catch (ArgumentException) { erreur = true; }
     
                    if (erreur)
                        MessageBox.Show("Impossible d'ouvrir le port COM. Très probablement, il est déjà en cours d'utilisation, a été supprimé, ou n'est pas disponible.", "COM Port indisponible", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    else
                        MessageBox.Show("Connexion réussi","Port disponible");
                }
            }
     
            // Connexion à la fenêtre du terminal
            private void Log(LogMsgType msgtype, string msg,string s)
            {
                rtfTerminal.Invoke(new EventHandler(delegate
                {
                    rtfTerminal.SelectedText = string.Empty;
                    rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);
                    rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
                    rtfTerminal.AppendText(msg);
                    rtfTerminal.ScrollToCaret();
                }));
     
                textBox1.Invoke(new EventHandler(delegate
                {
                    textBox1.SelectedText = string.Empty;
                    textBox1.AppendText(s);
                    textBox1.ScrollToCaret();
                }));
            }
     
            //Convertit un tableau d'octets en une chaîne formatée de chiffres hexadécimaux.
            private string ByteArrayToHexString(byte[] data)
            {
                StringBuilder sb = new StringBuilder(data.Length * 3);
                foreach (byte b in data)
                    sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
                return sb.ToString().ToUpper();
            }
     
            private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                // Si le port est ouvert, le fermer
                if (!sp.IsOpen) return;
                // Obtenir le nombre d'octets en attente dans le tampon du port
                int bytes = sp.BytesToRead;
                // Créez une zone tampon (tableau d'octets) pour stocker les données entrantes
                byte[] buffer = new byte[bytes];
                // Lire les données du port et de le stocker dans la mémoire tampon
                sp.Read(buffer, 0, bytes);
                // Montrer à l'utilisateur les données entrantes dans un format hexadécimal
                Log(LogMsgType.Incoming, ByteArrayToHexString(buffer), ByteArrayToHexString(buffer).Substring(0, 2));
            }
     
        }
    }

  4. #4
    Nouveau membre du Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2012
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Avril 2012
    Messages : 5
    Par défaut
    merci d'avoir répondu je vais lire les propriétés du serialPort et reprendre un morceau de ton code Narizuke en espérant que j'arrive à le faire marcher.

    a+

Discussions similaires

  1. Réponses: 9
    Dernier message: 08/01/2007, 10h41
  2. Développer un Gui avec Netbeans
    Par mounap dans le forum NetBeans
    Réponses: 4
    Dernier message: 31/10/2006, 12h09
  3. Comment lancer une application qui a été développée sous Unix avec le navigateur IE
    Par diamonds dans le forum Applications et environnements graphiques
    Réponses: 2
    Dernier message: 26/09/2006, 14h43
  4. [FLASH MX] Développement de site avec flash
    Par steeves5 dans le forum Flash
    Réponses: 1
    Dernier message: 14/12/2005, 13h11
  5. [CVS] Développer en équipe avec Eclipse et CVS
    Par ledoc_01 dans le forum Eclipse Java
    Réponses: 4
    Dernier message: 16/12/2003, 14h01

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