初学者请教两个问题
c#新手,本身C基础就比较薄弱,编用modbus通信的简单程序,用serialport控件。问题1:初始化控件用的是public,为什么调用这个控件会提示上下文不存在?怎么定义全局变量呢
问题2:函数返回类型可以是字节形式吗?
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using
using
namespace MODBUS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void init()
{
SerialPort com;
com = new SerialPort();
com.BaudRate = 9600;
com.PortName = "COM1";
com.Open();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void plc_send(string addr, string num) //发送
{
byte[] send_buf = new byte[7];
byte[] recv_data = new byte[3];
byte c, d;
byte e, f;
c = (byte)(Convert.ToInt32(addr.Substring(0, 2), 16));
d = (byte)(Convert.ToInt32(addr.Substring(2, 2), 16));
e = (byte)(Convert.ToInt32(num.Substring(0, 2), 16));
f = (byte)(Convert.ToInt32(num.Substring(2, 2), 16));
send_buf[0] = Convert.ToByte(textBox1.Text);
send_buf[1] = 3;
send_buf[2] = c;
send_buf[3] = d;
send_buf[4] = e;
send_buf[5] = f;
recv_data[0] = crc_calc(send_buf)[0];
recv_data[1] = crc_calc(send_buf)[1];
send_buf[6] = recv_data[0];
send_buf[7] = recv_data[1];
string str = Convert.ToBase64String(send_buf);
com.Write(str);
}
private void button1_Click(object sender, EventArgs e)
{
string addr;
string num;
addr = textBox3.Text;
num = textBox4.Text;
plc_send(addr, num); //发送命令
}
private void button2_Click(object sender, EventArgs e)
{
byte[] data = Convert.FromBase64String(com.Read);
}
private void upper_com_ret(byte[] recv_data) //返回
{
byte[] ret_buff = new byte[1000];
ret_buff[0] = Convert.ToByte(textBox1.Text);
ret_buff[1] = 3;
ret_buff[2] = 1;
ret_buff[3] = Convert.ToByte(textBox2.Text);
ret_buff[4] = recv_data[0];
ret_buff[5] = recv_data[1];
}
private byte[] crc_calc(byte[] send_buf) //CRC校验
{
byte[] crc_buf = new byte[3]; //CRC寄存器
crc_buf[0] = 0xFF;
crc_buf[1] = 0xFF;
for (int i = 0; i <= send_buf.Length; i++)
{
crc_buf[1] = (byte)(crc_buf[1] ^ send_buf[i]);
for (int flag = 0; flag <= 7; flag++)
{
crc_buf[0] = (byte)(crc_buf[0] >> 1);
crc_buf[1] = (byte)(crc_buf[1] >> 1);
if ((crc_buf[1] & 0x01) == 0x01)
{
crc_buf[0] = (byte)(crc_buf[0] ^ 0xA0);
crc_buf[1] = (byte)(crc_buf[1] ^ 0x01);
}
if ((crc_buf[1] & 0x01) == 0)
{
crc_buf[0] = (byte)(crc_buf[0] >> 1);
crc_buf[1] = (byte)(crc_buf[1] >> 1);
}
}
}
byte[] ret_dat = new byte[3];
ret_dat[0] = crc_buf[0];
ret_dat[1] = crc_buf[1];
return ret_dat;
}
}
}