programme communication pc et regulateur sous rs232

programme communication pc et regulateur sous rs232 - C#/.NET managed - Programmation

Marsh Posté le 23-03-2011 à 23:29:02    

bonjour,
est ce que quelqu'un peut me dire ou je peux trouver un code en c# qui permet de communiquer entre un PC et un régulateur à l'aide du rs232 et qui permet de écrire et de lire des trames en protocole bisynchrone
merci pour vous aide.

Reply

Marsh Posté le 23-03-2011 à 23:29:02   

Reply

Marsh Posté le 24-03-2011 à 10:43:43    

Reply

Marsh Posté le 25-03-2011 à 21:48:06    

Bonjour,
Je suis arrivé à résoudre des problèmes de compilation d'un programme qui fait la communication port serie mais j'ai un autre problème c'est que les boutons créer dans l'interface ne sont pas actifs c'est à dire lorsque je clic sur le bouton « clear » par exemple rien ce que j’écris ne s’efface pas.
S’il vous plait aidez moi à résoudre ce problème cette partie est la premier étape dans mon projet de fin d'étude et je dois avance vite.
Merci en avance.
 
voici le code du programme:
 

Code :
  1. #region Namespace Inclusions
  2. using System;
  3. using System.Linq;
  4. using System.Data;
  5. using System.Text;
  6. using System.Drawing;
  7. using System.IO.Ports;
  8. using System.Windows.Forms;
  9. using System.ComponentModel;
  10. using System.Collections.Generic;
  11. using SerialPortTerminal.Properties;
  12. using System.Threading;
  13. using System.IO;
  14. #endregion
  15. namespace SerialPortTerminal
  16. {
  17. #region Public Enumerations
  18. public enum DataMode { Text, Hex }
  19. public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
  20. #endregion
  21. public partial class frmTerminal : Form
  22. {
  23. #region Local Variables
  24. // The main control for communicating through the RS-232 port
  25. private SerialPort comport = new SerialPort();
  26. // Various colors for logging info
  27. private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };
  28. // Temp holder for whether a key was pressed
  29. private bool KeyHandled = false;
  30. private Settings settings = Settings.Default;
  31. #endregion
  32. #region Constructor
  33. public frmTerminal()
  34. {
  35. // Load user settings
  36. settings.Reload();
  37. // Build the form
  38. InitializeComponent();
  39. // Restore the users settings
  40. InitializeControlValues();
  41. // Enable/disable controls based on the current state
  42. EnableControls();
  43. // When data is recieved through the port, call this method
  44. comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
  45. comport.PinChanged += new SerialPinChangedEventHandler(comport_PinChanged);
  46. }
  47. void comport_PinChanged(object sender, SerialPinChangedEventArgs e)
  48. {
  49. // Show the state of the pins
  50. UpdatePinState();
  51. }
  52. private void UpdatePinState()
  53. {
  54. this.Invoke(new ThreadStart(() =>
  55. {
  56. // Show the state of the pins
  57. chkCD.Checked = comport.CDHolding;
  58. chkCTS.Checked = comport.CtsHolding;
  59. chkDSR.Checked = comport.DsrHolding;
  60. }));
  61. }
  62. #endregion
  63. #region Local Methods
  64. /// <summary> Save the user's settings. </summary>
  65. private void SaveSettings()
  66. {
  67. settings.BaudRate = int.Parse(cmbBaudRate.Text);
  68. settings.DataBits = int.Parse(cmbDataBits.Text);
  69. settings.DataMode = CurrentDataMode;
  70. settings.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
  71. settings.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
  72. settings.PortName = cmbPortName.Text;
  73. settings.ClearOnOpen = chkClearOnOpen.Checked;
  74. settings.ClearWithDTR = chkClearWithDTR.Checked;
  75. settings.Save();
  76. }
  77. /// <summary> Populate the form's controls with default settings. </summary>
  78. private void InitializeControlValues()
  79. {
  80. cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
  81. cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));
  82. cmbParity.Text = settings.Parity.ToString();
  83. cmbStopBits.Text = settings.StopBits.ToString();
  84. cmbDataBits.Text = settings.DataBits.ToString();
  85. cmbParity.Text = settings.Parity.ToString();
  86. cmbBaudRate.Text = settings.BaudRate.ToString();
  87. CurrentDataMode = settings.DataMode;
  88. RefreshComPortList();
  89. chkClearOnOpen.Checked = settings.ClearOnOpen;
  90. chkClearWithDTR.Checked = settings.ClearWithDTR;
  91. // If it is still avalible, select the last com port used
  92. if (cmbPortName.Items.Contains(settings.PortName)) cmbPortName.Text = settings.PortName;
  93. else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = cmbPortName.Items.Count - 1;
  94. else
  95. {
  96. MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);
  97. this.Close();
  98. }
  99. }
  100. /// <summary> Enable/disable controls based on the app's current state. </summary>
  101. private void EnableControls()
  102. {
  103. // Enable/disable controls based on whether the port is open or not
  104. gbPortSettings.Enabled = !comport.IsOpen;
  105. txtSendData.Enabled = btnSend.Enabled = comport.IsOpen;
  106. //chkDTR.Enabled = chkRTS.Enabled = comport.IsOpen;
  107. if (comport.IsOpen) btnOpenPort.Text = "&Close Port";
  108. else btnOpenPort.Text = "&Open Port";
  109. }
  110. /// <summary> Send the user's data currently entered in the 'send' box.</summary>
  111. private void SendData()
  112. {
  113. if (CurrentDataMode == DataMode.Text)
  114. {
  115. // Send the user's text straight out the port
  116. comport.Write(txtSendData.Text);
  117. // Show in the terminal window the user's text
  118. Log(LogMsgType.Outgoing, txtSendData.Text + "\n" );
  119. }
  120. else
  121. {
  122. try
  123. {
  124. // Convert the user's string of hex digits (ex: B4 CA E2) to a byte array
  125. byte[] data = HexStringToByteArray(txtSendData.Text);
  126. // Send the binary data out the port
  127. comport.Write(data, 0, data.Length);
  128. // Show the hex digits on in the terminal window
  129. Log(LogMsgType.Outgoing, ByteArrayToHexString(data) + "\n" );
  130. }
  131. catch (FormatException)
  132. {
  133. // Inform the user if the hex string was not properly formatted
  134. Log(LogMsgType.Error, "Not properly formatted hex string: " + txtSendData.Text + "\n" );
  135. }
  136. }
  137. txtSendData.SelectAll();
  138. }
  139. /// <summary> Log data to the terminal window. </summary>
  140. /// <param name="msgtype"> The type of message to be written. </param>
  141. /// <param name="msg"> The string containing the message to be shown. </param>
  142. private void Log(LogMsgType msgtype, string msg)
  143. {
  144. rtfTerminal.Invoke(new EventHandler(delegate
  145. {
  146. rtfTerminal.SelectedText = string.Empty;
  147. rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);
  148. rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
  149. rtfTerminal.AppendText(msg);
  150. rtfTerminal.ScrollToCaret();
  151. }));
  152. }
  153. /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
  154. /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
  155. /// <returns> Returns an array of bytes. </returns>
  156. private byte[] HexStringToByteArray(string s)
  157. {
  158. s = s.Replace(" ", "" );
  159. byte[] buffer = new byte[s.Length / 2];
  160. for (int i = 0; i < s.Length; i += 2)
  161. buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
  162. return buffer;
  163. }
  164. /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
  165. /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
  166. /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
  167. private string ByteArrayToHexString(byte[] data)
  168. {
  169. StringBuilder sb = new StringBuilder(data.Length * 3);
  170. foreach (byte b in data)
  171. sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
  172. return sb.ToString().ToUpper();
  173. }
  174. #endregion
  175. #region Local Properties
  176. private DataMode CurrentDataMode
  177. {
  178. get
  179. {
  180. if (rbHex.Checked) return DataMode.Hex;
  181. else return DataMode.Text;
  182. }
  183. set
  184. {
  185. if (value == DataMode.Text) rbText.Checked = true;
  186. else rbHex.Checked = true;
  187. }
  188. }
  189. #endregion
  190. #region Event Handlers
  191. private void lnkAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  192. {
  193. // Show the user the about dialog
  194. (new frmAbout()).ShowDialog(this);
  195. }
  196. private void frmTerminal_Shown(object sender, EventArgs e)
  197. {
  198. Log(LogMsgType.Normal, String.Format("Application Started at {0}\n", DateTime.Now));
  199. }
  200. private void frmTerminal_FormClosing(object sender, FormClosingEventArgs e)
  201. {
  202. // The form is closing, save the user's preferences
  203. SaveSettings();
  204. }
  205. private void rbText_CheckedChanged(object sender, EventArgs e)
  206. { if (rbText.Checked) CurrentDataMode = DataMode.Text; }
  207. private void rbHex_CheckedChanged(object sender, EventArgs e)
  208. { if (rbHex.Checked) CurrentDataMode = DataMode.Hex; }
  209. private void cmbBaudRate_Validating(object sender, CancelEventArgs e)
  210. { int x; e.Cancel = !int.TryParse(cmbBaudRate.Text, out x); }
  211. private void cmbDataBits_Validating(object sender, CancelEventArgs e)
  212. { int x; e.Cancel = !int.TryParse(cmbDataBits.Text, out x); }
  213. private void btnOpenPort_Click(object sender, EventArgs e)
  214. {
  215. bool error = false;
  216. // If the port is open, close it.
  217. if (comport.IsOpen) comport.Close();
  218. else
  219. {
  220. // Set the port's settings
  221. comport.BaudRate = int.Parse(cmbBaudRate.Text);
  222. comport.DataBits = int.Parse(cmbDataBits.Text);
  223. comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
  224. comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
  225. comport.PortName = cmbPortName.Text;
  226. try
  227. {
  228. // Open the port
  229. comport.Open();
  230. }
  231. catch (UnauthorizedAccessException) { error = true; }
  232. catch (IOException) { error = true; }
  233. catch (ArgumentException) { error = true; }
  234. if (error) MessageBox.Show(this, "Could not open the COM port. Most likely it is already in use, has been removed, or is unavailable.", "COM Port Unavalible", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  235. else
  236. {
  237. // Show the initial pin states
  238. UpdatePinState();
  239. chkDTR.Checked = comport.DtrEnable;
  240. chkRTS.Checked = comport.RtsEnable;
  241. }
  242. }
  243. // Change the state of the form's controls
  244. EnableControls();
  245. // If the port is open, send focus to the send data box
  246. if (comport.IsOpen)
  247. {
  248. txtSendData.Focus();
  249. if (chkClearOnOpen.Checked) ClearTerminal();
  250. }
  251. }
  252. private void btnSend_Click(object sender, EventArgs e)
  253. { SendData(); }
  254. private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
  255. {
  256. // If the com port has been closed, do nothing
  257. if (!comport.IsOpen) return;
  258. // This method will be called when there is data waiting in the port's buffer
  259. // Determain which mode (string or binary) the user is in
  260. if (CurrentDataMode == DataMode.Text)
  261. {
  262. // Read all the data waiting in the buffer
  263. string data = comport.ReadExisting();
  264. // Display the text to the user in the terminal
  265. Log(LogMsgType.Incoming, data);
  266. }
  267. else
  268. {
  269. // Obtain the number of bytes waiting in the port's buffer
  270. int bytes = comport.BytesToRead;
  271. // Create a byte array buffer to hold the incoming data
  272. byte[] buffer = new byte[bytes];
  273. // Read the data from the port and store it in our buffer
  274. comport.Read(buffer, 0, bytes);
  275. // Show the user the incoming data in hex format
  276. Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));
  277. }
  278. }
  279. private void txtSendData_KeyDown(object sender, KeyEventArgs e)
  280. {
  281. // If the user presses [ENTER], send the data now
  282. if (KeyHandled = e.KeyCode == Keys.Enter) { e.Handled = true; SendData(); }
  283. }
  284. private void txtSendData_KeyPress(object sender, KeyPressEventArgs e)
  285. { e.Handled = KeyHandled; }
  286. #endregion
  287. private void chkDTR_CheckedChanged(object sender, EventArgs e)
  288. {
  289. comport.DtrEnable = chkDTR.Checked;
  290. if (chkDTR.Checked && chkClearWithDTR.Checked) ClearTerminal();
  291. }
  292. private void chkRTS_CheckedChanged(object sender, EventArgs e)
  293. {
  294. comport.RtsEnable = chkRTS.Checked;
  295. }
  296. private void btnClear_Click(object sender, EventArgs e)
  297. {
  298. ClearTerminal();
  299. }
  300. private void ClearTerminal()
  301. {
  302. rtfTerminal.Clear();
  303. }
  304. private void tmrCheckComPorts_Tick(object sender, EventArgs e)
  305. {
  306. // checks to see if COM ports have been added or removed
  307. // since it is quite common now with USB-to-Serial adapters
  308. RefreshComPortList();
  309. }
  310. private void RefreshComPortList()
  311. {
  312. // Determain if the list of com port names has changed since last checked
  313. string selected = RefreshComPortList(cmbPortName.Items.Cast<string>(), cmbPortName.SelectedItem as string, comport.IsOpen);
  314. // If there was an update, then update the control showing the user the list of port names
  315. if (!String.IsNullOrEmpty(selected))
  316. {
  317. cmbPortName.Items.Clear();
  318. cmbPortName.Items.AddRange(OrderedPortNames());
  319. cmbPortName.SelectedItem = selected;
  320. }
  321. }
  322. private string[] OrderedPortNames()
  323. {
  324. // Just a placeholder for a successful parsing of a string to an integer
  325. int num;
  326. // Order the serial port names in numberic order (if possible)
  327. return SerialPort.GetPortNames().OrderBy(a => a.Length > 3 && int.TryParse(a.Substring(3), out num) ? num : 0).ToArray();
  328. }
  329. private string RefreshComPortList(IEnumerable<string> PreviousPortNames, string CurrentSelection, bool PortOpen)
  330. {
  331. // Create a new return report to populate
  332. string selected = null;
  333. // Retrieve the list of ports currently mounted by the operating system (sorted by name)
  334. string[] ports = SerialPort.GetPortNames();
  335. // First determain if there was a change (any additions or removals)
  336. bool updated = PreviousPortNames.Except(ports).Count() > 0 || ports.Except(PreviousPortNames).Count() > 0;
  337. // If there was a change, then select an appropriate default port
  338. if (updated)
  339. {
  340. // Use the correctly ordered set of port names
  341. ports = OrderedPortNames();
  342. // Find newest port if one or more were added
  343. string newest = SerialPort.GetPortNames().Except(PreviousPortNames).OrderBy(a => a).LastOrDefault();
  344. // If the port was already open... (see logic notes and reasoning in Notes.txt)
  345. if (PortOpen)
  346. {
  347. if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
  348. else if (!String.IsNullOrEmpty(newest)) selected = newest;
  349. else selected = ports.LastOrDefault();
  350. }
  351. else
  352. {
  353. if (!String.IsNullOrEmpty(newest)) selected = newest;
  354. else if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
  355. else selected = ports.LastOrDefault();
  356. }
  357. }
  358. // If there was a change to the port list, return the recommended default selection
  359. return selected;
  360. }
  361. }
  362. }


Message édité par gilou le 26-03-2011 à 02:34:14
Reply

Marsh Posté le 26-03-2011 à 11:36:40    

T'as bien branché l’événement Click sur ta méthode ?
 
Un truc genre btnClear.Click += new EventHandler(btnClear_Click);
 
Normalement c'est à faire générer par le designer.
 
Sinon, ton code est atroce hein. Aucune séparation de l'UI et de la classe d'accès au port COM. Indentation horrible (fait CTRL+E+D pour formater automatiquement dans visual)

Reply

Marsh Posté le 26-03-2011 à 14:16:59    

Bonjour,
moi je suis débutant en développement et je n'ai pas travaillé avec ce langage avant.
s'il vous plait si vous avez de remarque pour améliorer mon code n'hésiter pas pour m'aider .
merci

Reply

Sujets relatifs:

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed