海阔凭鱼跃,天空任鸟飞.

---------送给帮助过我进步的人,以及我帮助他进步的人

导航

關於串口編程的一些總結

Posted on 2006-12-29 18:40  Hu Yong Yuan  阅读(525)  评论(0)    收藏  举报

     串口通訊兩種方式:


         1.被動接收(我是這樣稀稱呼),即串口通訊設被不停的發送有起始位和接收位的數據.而程式收到數據後根據接收位和起始位,將數據剝出來.進行處理.我給地磅寫的就是利用這種(後面貼出原碼).

  1using System;
  2using System.Drawing;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Windows.Forms;
  6using System.Data;
  7using System.IO;
  8namespace weight
  9{
 10    /// <summary>
 11    /// Form1 的摘要描述。
 12    /// </summary>

 13    public class Form1 : System.Windows.Forms.Form
 14    {
 15        private AxMSCommLib.AxMSComm comm;
 16        
 17        bool cop=false;
 18        bool ctrlcop=false;
 19        string strCollect="";
 20         int iswrite=0;
 21        int btnum=0;
 22        /// <summary>
 23        /// 設計工具所需的變數。
 24        /// </summary>

 25        private System.ComponentModel.Container components = null;
 26        public Form1()
 27        {
 28            //
 29            // Windows Form 設計工具支援的必要項
 30            //
 31            InitializeComponent();
 32
 33            //
 34            // TODO: 在 InitializeComponent 呼叫之後加入任何建構函式程式碼
 35            //
 36        }

 37
 38        /// <summary>
 39        /// 清除任何使用中的資源。
 40        /// </summary>

 41        protected override void Dispose( bool disposing )
 42        {
 43            if( disposing )
 44            {
 45                if (components != null
 46                {
 47                    components.Dispose();
 48                }

 49            }

 50            base.Dispose( disposing );
 51        }

 52
 53        Windows Form 設計工具產生的程式碼
 93
 94        /// <summary>
 95        /// 應用程式的主進入點。
 96        /// </summary>

 97        [STAThread]
 98        static void Main() 
 99        {
100            Form f = new Form1();
101            f.ShowInTaskbar=false;
102                Application.Run(f);
103        }

104
105        private void axMSComm1_OnComm(object sender, System.EventArgs e)
106        {
107        
108            
109            byte [] bt;
110            char  chBegin='\u0002';
111            char  chEnd='\u0003';
112            bool ctrlCp=true;
113            bt=(byte [])comm.Input;
114            comm.InBufferCount=0;
115                comm.OutBufferCount=0;
116            string strIn;
117            
118            strIn=System.Text.ASCIIEncoding.ASCII.GetString(bt);
119            
120            for(int i=0;i<bt.Length;i++)
121            {
122                
123                if((char)bt[i]==chBegin)
124                {
125                    strIn=System.Text.ASCIIEncoding.ASCII.GetString(bt,i+1,10);
126                    strCollect+=strIn;
127                    break;
128                }

129                
130                
131
132            }

133
134        
135            if(strCollect.Length==10)
136            {
137                string str="";
138                try
139                {
140                    
141
142                    int wei=int.Parse(strCollect.Substring(7,1));
143            
144                
145                    switch(wei)
146                    {
147                        case 0
148                            str=strCollect.Substring(0,7);
149                            break;
150                        case 1:
151                            str=strCollect.Substring(0,6)+"."+strCollect.Substring(6,1);
152                            break;
153                        case 2:
154                            str=strCollect.Substring(0,5)+"."+strCollect.Substring(5,2);
155                            break;
156                        case 3:
157                            str=strCollect.Substring(0,4)+"."+strCollect.Substring(4,3);
158                            break;
159                        case 4:
160                            str=strCollect.Substring(0,3)+"."+strCollect.Substring(3,4);
161                            break;
162    
163                    }

164                    
165                    if(str.Length!=8return;
166                    
167                    FileStream  fs=new FileStream("c:\\temp\\weight.txt",FileMode.Append,FileAccess.Write,FileShare.Write);
168                    fs.Close();
169                    StreamWriter sw=new StreamWriter("c:\\temp\\weight.txt",false,System.Text.Encoding.ASCII);
170                    sw.Write(str);
171                    sw.Close();
172                
173                        Application.Exit();
174                    
175                }

176                catch
177                {
178                        
179                    
180                }

181                finally
182                {
183                
184                    
185                    
186                    
187                }

188            }

189            else
190            {
191                    
192        
193                        
194                
195            }

196            
197        
198        }

199
200        private void Form1_Load(object sender, System.EventArgs e)
201        {
202            comm.PortOpen=true;
203            
204            comm.OutBufferCount=0;
205        
206
207        }

208
209    
210        private void Form1_Disposed(object sender, EventArgs e)
211        {
212            
213        }

214
215        private void Form1_Activated(object sender, System.EventArgs e)
216        {
217            this.Visible=false;
218        }

219
220        
221    }

222}

223


         2.命令應答.這種方式是程式和通訊設備進行交互:程式向設備發出供應商指定的命令,一般在說明書上有,設備跟據命令向程式返饋數據(後有原碼).代碼中有鍵盤鉤子,用於偵測用戶鍵盤計錄(copy他人的,稼接過來.忘具體名字了).

  
  11using System;
  2  2using System.Drawing;
  3  3using System.Collections;
  4  4using System.ComponentModel;
  5  5using System.Windows.Forms;
  6  6using System.Data;
  7  7using System.Threading;
  8  8using System.Runtime.InteropServices;
  9  9using System.Reflection;
 10 10
 11 11namespace ppcom
 12 12{
 13 13    /**//// <summary>
 14 14    /// Form1 的摘要描述。
 15 15    /// </summary>
 16 16    
 17 17    public class Form1 : System.Windows.Forms.Form
 18 18    {
 19 19        private System.Windows.Forms.TextBox textBox1;
 20 20        private System.Windows.Forms.Button button1;
 21 21        private System.Windows.Forms.Splitter splitter1;
 22 22        string strIn;
 23 23        string strNum="";
 24 24        private System.Windows.Forms.ComboBox cbRthread;
 25 25        private System.Windows.Forms.Label label1;
 26 26        private System.Windows.Forms.Label label2;
 27 27        private System.Windows.Forms.ComboBox comboBox1;
 28 28        private System.Windows.Forms.Label label3;
 29 29        private System.Windows.Forms.Label label4;
 30 30        private System.Windows.Forms.ComboBox comboBox2;
 31 31        private System.Windows.Forms.Label label5;
 32 32        bool clboard=true;//是否清空剪切板
 33 33        bool ctrlreset=true;
 34 34        
 35 35        bool ctrlKey=true,ctrlCaps=true,ctrlF1=true;
 36 36        private System.Windows.Forms.NotifyIcon notifyIcon1;
 37 37        private System.Windows.Forms.Label label6;
 38 38        private System.Windows.Forms.ComboBox cbSign;
 39 39        private AxMSCommLib.AxMSComm axMSComm1;
 40 40    
 41 41        private System.ComponentModel.IContainer components;
 42 42
 43 43        public Form1()
 44 44        {
 45 45            //
 46 46            // Windows Form 設計工具支援的必要項
 47 47            //
 48 48            InitializeComponent();
 49 49//            tb.KeyPress += new KeyPressEventHandler(keypressed);
 50 50
 51 51
 52 52            //
 53 53            // TODO: 在 InitializeComponent 呼叫之後加入任何建構函式程式碼
 54 54            //
 55 55            HookStart();
 56 56            
 57 57        }

 58 58        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
 59 59        static int hKeyboardHook = 0
 60 60        HookProc KeyboardHookProcedure;
 61 61
 62 62        public const int WH_KEYBOARD = 13;
 63 63        [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
 64 64        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, 
 65 65            IntPtr hInstance, int threadId);
 66 66
 67 67        [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
 68 68        public static extern bool UnhookWindowsHookEx(int idHook);
 69 69        [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
 70 70        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);  
 71 71        [DllImport("kernel32.dll")]
 72 72        static extern int GetCurrentThreadId(); 
 73 73
 74 74        public struct KeyMSG
 75 75        {
 76 76            public int vkCode;  
 77 77            public int scanCode; 
 78 78            public int flags;  
 79 79            public int time; 
 80 80            public int dwExtraInfo; 
 81 81        }

 82 82
 83 83        /**//**//**//// <summary>
 84 84        ///
 85 85        /// </summary>
 86 86        /// <param name="nCode"></param>
 87 87        /// <param name="wParam"></param>
 88 88        /// <param name="lParam"></param>
 89 89        /// <returns></returns>
 90 90        /// 
 91 91        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
 92 92        {    
 93 93            
 94 94            KeyMSG m = (KeyMSG) Marshal.PtrToStructure(lParam, typeof(KeyMSG));
 95 95            
 96 96            if ((int) m.vkCode == 113)
 97 97            {    
 98 98            
 99 99                
100100                axMSComm1.Output="CR00\r\n";
101101                axMSComm1.OutBufferCount=0;
102102
103103            }

104104            if ((int) m.vkCode == 20)
105105            {    
106106                if(ctrlCaps==true)
107107                {
108108                
109109                    if(cbSign.SelectedIndex==0)
110110                    {
111111                        cbSign.SelectedIndex=1;
112112                        this.Text="";
113113                    
114114                    }

115115                    else
116116                    {
117117                        cbSign.SelectedIndex=0;
118118                        this.Text="";
119119                    }

120120                    ctrlCaps=false;
121121                }

122122                else
123123                {
124124                    
125125                
126126                    ctrlCaps=true;
127127                }

128128
129129            }

130130            
131131            if ( (int) m.vkCode == 192)
132132            {
133133                if(ctrlKey==true)
134134                {
135135//                    axMSComm1.Output="IN";
136136//                    axMSComm1.Output="RES2";
137137//                    axMSComm1.Output="PRI\r\n";
138138//                    
139139                    axMSComm1.Output="GA00\r\n";
140140                    ctrlKey=false;
141141                    ctrlreset=false;
142142                    
143143                }

144144                else
145145                {
146146                    ctrlKey=true;
147147                }

148148                return 1;
149149            }

150150            return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam); 
151151        }

152152
153153        /**//**//**//// <summary>
154154        /// 安??子
155155        /// </summary>
156156        public void HookStart()
157157        {
158158            if(hKeyboardHook == 0)
159159            {
160160                KeyboardHookProcedure = new HookProc(KeyboardHookProc);
161161                hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardHookProcedure, IntPtr.Zero,GetCurrentThreadId());
162162                hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD,KeyboardHookProcedure,Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);
163163                // 如果?置?子失?
164164                if(hKeyboardHook == 0 )    
165165                {
166166                    HookStop();
167167                    throw new Exception("SetWindowsHookEx failed.");
168168                }

169169            }

170170        }

171171
172172        /**//**//**//// <summary>
173173        /// 卸??子
174174        /// </summary>
175175        public void HookStop()
176176        {
177177            bool retKeyboard = true;
178178            if(hKeyboardHook != 0)
179179            {
180180                retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
181181                hKeyboardHook = 0;
182182            }
 
183183            if (!(retKeyboard)) 
184184            {
185185                throw new Exception("UnhookWindowsHookEx  failed.");
186186            }

187187        }

188188
189189        /**//// <summary>
190190        /// 清除任何使用中的資源。
191191        /// </summary>
192192        protected override void Dispose( bool disposing )
193193        {
194194            if( disposing )
195195            {
196196                if (components != null
197197                {
198198                    components.Dispose();
199199                }

200200            }

201201            base.Dispose( disposing );
202202        }

203203
204204        Windows Form 設計工具產生的程式碼Windows Form 設計工具產生的程式碼
413413
414414        /**//// <summary>
415415        /// 應用程式的主進入點。
416416        /// </summary>
417417        [STAThread]
418418        static void Main() 
419419        {
420420            Application.Run(new Form1());
421421        }

422422//        void keypressed(Object o, KeyPressEventArgs e)
423423//        {
424424//            // The keypressed method uses the KeyChar property to check 
425425//            // whether the ENTER key is pressed. 
426426//
427427//            // If the ENTER key is pressed, the Handled property is set to true, 
428428//            // to indicate the event is handled.
429429//            if(e.KeyChar == (char)13)
430430//                e.Handled=true;
431431//        }
432432
433433        private void Form1_Load(object sender, System.EventArgs e)
434434        {
435435                axMSComm1.PortOpen=true;
436436//            axMSComm1.Output="RST";
437437//            axMSComm1.Output="EXT3";
438438//            axMSComm1.Output="IN";
439439//            axMSComm1.Output="TOL1";
440440//            axMSComm1.Output="RES2\r\n";
441441        }

442442
443443        private void axMSComm1_OnComm(object sender, System.EventArgs e)
444444        {
445445//            MessageBox.Show("111");
446446                
447447            byte[] bytIn; 
448448            object objIn; 
449449            float fltC;
450450            //            int i; 
451451          
452452            axMSComm1.InputMode=MSCommLib.InputModeConstants.comInputModeBinary; 
453453            axMSComm1.InputLen =short.Parse(cbRthread.Text); 
454454            objIn=axMSComm1.Input;  
455455            bytIn =(byte [])objIn;  
456456
457457            
458458            strIn = System.Text.ASCIIEncoding.ASCII.GetString(bytIn);
459459            if(strIn.IndexOf(',')>0) strIn=strIn.Substring(strIn.IndexOf(',')+1);
460460                textBox1.Text=strIn;
461461            if(cbSign.SelectedIndex==0)
462462                fltC=Math.Abs((float)Math.Round(float.Parse(strIn)*float.Parse(comboBox2.Text),2));
463463            else
464464            fltC=(float)Math.Round(float.Parse(strIn)*float.Parse(comboBox2.Text),2);
465465                    
466466            System.Windows.Forms.Clipboard.SetDataObject(fltC.ToString(),clboard);
467467            if(ctrlreset==false)
468468            {
469469                SendKeys.Send("^v");
470470                SendKeys.Send("{TAB}");
471471
472472                axMSComm1.OutBufferCount=0;
473473                ctrlreset=true;    
474474            
475475
476476                //                System.Threading.Thread.Sleep(500);
477477            }

478478            
479479        
480480        }

481481
482482        private void button1_Click(object sender, System.EventArgs e)
483483        {
484484            axMSComm1.Output="GA00\r\n";
485485        }

486486
487487        private void cbRthread_SelectedIndexChanged(object sender, System.EventArgs e)
488488        {
489489            axMSComm1.RThreshold=short.Parse(cbRthread.Text);
490490        }

491491
492492        private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
493493        {
494494        if(comboBox1.Text.Trim()=="") clboard=true;
495495            else
496496            clboard=false;
497497        }

498498
499499        private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
500500        {
501501//            MessageBox.Show("11");
502502        }

503503
504504        
505505
506506    
507507        
508508        
509509
510510        
511511
512512    }

513513}

514514
515