public int write_flash(long addr, Flash_Length len, byte[] data) { int i = 0; for (; i < data.Length; i++) //判断要写入的数据是否全为0xff { if (data[i] != 0xff) { break; } } if (i == data.Length) { return(0); //如果是,则不再写入,直接返回 } string addr_str = addr.ToString("X8"); addr_str = addr_str.Substring(6, 2) + addr_str.Substring(4, 2) + addr_str.Substring(2, 2) + addr_str.Substring(0, 2); string tmp = AB161X_Cmds.CMD_HEAD + "0701" + AB161X_Cmds.CMD_WRIT + CRC8Calculate(data, data.Length).ToString("X2") + addr_str; byte[] write_buf = HexToByte(tmp); try { _sp.DiscardInBuffer(); _sp.Write(write_buf, 0, write_buf.Length); _sp.Write(data, 0, data.Length); } catch (Exception) { } int have_read = 0; //已经读出的数据 int need_read = 11; //还需要读出的数据 DateTime dt = DateTime.UtcNow; while ((need_read - have_read > 0) && (((TimeSpan)(DateTime.UtcNow - dt)).TotalSeconds < 2)) { try { have_read += _sp.Read(write_buf, have_read, need_read - have_read); } catch (Exception) { return(-1); } } if ((have_read == 11) && (write_buf[0] == 0x05) && (write_buf[1] == 0x5b) && (write_buf[4] == 0x07) && (write_buf[5] == 0x07)) { return(0); } return(-1); }
public int read_flash(long addr, Flash_Length len, byte[] data) { byte[] read_buff = new byte[10240]; //10K string len_str = null; string addr_str = addr.ToString("X8"); addr_str = addr_str.Substring(6, 2) + addr_str.Substring(4, 2) + addr_str.Substring(2, 2) + addr_str.Substring(0, 2); switch (len) { case Flash_Length.LEN_256B: len_str = "01"; break; case Flash_Length.LEN_1KB: len_str = "02"; break; case Flash_Length.LEN_4KB: len_str = "04"; break; case Flash_Length.LEN_8KB: len_str = "06"; break; default: len_str = "01"; break; } string tmp = AB161X_Cmds.CMD_HEAD + "0700" + AB161X_Cmds.CMD_READ + len_str + addr_str; byte[] write_buf = HexToByte(tmp); try { _sp.DiscardInBuffer(); _sp.Write(write_buf, 0, write_buf.Length); } catch (Exception) { } int have_read = 0; //已经读出的数据 int need_read = 269; //还需要读出的数据 DateTime dt = DateTime.UtcNow; while ((need_read - have_read > 0) && (((TimeSpan)(DateTime.UtcNow - dt)).TotalSeconds < 2)) { try { have_read += _sp.Read(read_buff, have_read, need_read - have_read); } catch (Exception) { return(0); } } if ((read_buff[0] == 0x05) && (read_buff[1] == 0x5b) && (read_buff[2] == 0x09) && (read_buff[3] == 0x01) && have_read == 269) { Array.Copy(read_buff, 13, data, 0, 256); return(256); } else { return(0); } }