#include <avr/wdt.h>
#include <SoftwareSerial.h>
#include <EEPROM.h> #define FPIN 13
#define E2PROM_OFFSET 16 SoftwareSerial mySerial(, ); // RX, TX
unsigned long lastSendTime=;
unsigned long lastReceiveTime=;
unsigned long SafeKey=987654321UL; // Max 4,294,967,295
byte RecCache[];
volatile int CacheIndex=; void setup() {
// put your setup code here, to run once:
pinMode(FPIN,OUTPUT);
digitalWrite(FPIN,LOW); Serial.begin();
delay();
Serial.println("Ready!"); //========Start========== //=========End=============
unsigned long sk=123456789UL;
if(_ReadSafeKey(sk)){
SafeKey=sk;
} //========Wifi Config=============
initWifi();
setCache(,); } void loop() {
// put your main code here, to run repeatedly:
handleTXR();
} void initWifi(){
mySerial.begin();
delay();
mySerial.println("AT+RST");
delayAndRead(); mySerial.println("AT+CIPMUX=1");
delayAndRead();
mySerial.println("AT+CIPSERVER=1");
delayAndRead();
} void handleTXR(){ while(mySerial.available()){
byte c=(byte) mySerial.read();
RecCache[CacheIndex++]=c; }
if(CacheIndex>){
CacheIndex=;
setCache(,);
} int bIndex=bIndexOf("$F",);
if(bIndex>=){
int eIndex=bIndexOf("$E",bIndex);
if(eIndex>bIndex){
//Extra Data
int dataLen= eIndex - (bIndex +);
byte data[dataLen];
for(int i=;i<dataLen;i++){
data[i]= RecCache[bIndex+ +i] ; } for(int w=(eIndex +);w<CacheIndex && w<;w++){
RecCache[w-(eIndex + )]=RecCache[w];
}
CacheIndex = CacheIndex - (eIndex +);
setCache(CacheIndex,); lastReceiveTime=millis();
handleCmd(data,dataLen); }
} if(CacheIndex>){
CacheIndex=;
setCache(,);
} } void setCache(int start,int endIndex){
for(int i=start;i<endIndex;i++){
RecCache[i]=;
}
}
boolean bStartsWith(byte data[],int len, String fStr){
int fLen=fStr.length() ;
byte fBytes[fLen + ];
fStr.getBytes(fBytes,fLen+); if(len<=)return false;
if(len<fLen)return false;
byte flag=;
for(int j=;j<fLen;j++){
if(fBytes[j]!=data[j])
{
flag=;
break;
} }
if(flag) return true; return false;
} int bIndexOf(String fStr,int start){
int fLen=fStr.length() ;
byte fBytes[fLen + ];
fStr.getBytes(fBytes,fLen+); for(int i=start;i<(CacheIndex + -fLen);i++){ if(RecCache[i]==fBytes[])
{
byte flag=;
for(int j=;j<fLen;j++){
if(fBytes[j]!=RecCache[i+j])
{
flag=;
break;
}
}
if(flag)return i;
}
}
return -;
} void handleCmd(byte data[], int len){ // Serial.println("\n=============");
// for(int i=0;i<len;i++){
// Serial.print(data[i],DEC);
// Serial.print(",");
// } if(bStartsWith(data,len,"HB:")){
hbCmd();
}else if(bStartsWith(data,len,"F:")){ fireCmd(data,len);
}else if(bStartsWith(data,len,"SetSK:")){
setSKCmd(data,len);
}else if(bStartsWith(data,len,"ClsSK:")){
clsSKCmd(data,len);
}
} void hbCmd(){
byte bs[];
unsigned long mlis=millis();
long2byte(mlis,bs);
byte msg[]={,,,,,,,,,,};
Serial.println(mlis);
replyBytes(true,"HB",bs,);
} void fireCmd(byte data[], int len){
byte safeBytes[]={,,,}; for(int i=;i<;i++){
safeBytes[i]=(byte)data[+i]; }
unsigned long sk= bytes2long(safeBytes);
byte duration=data[];
if(duration>) duration=;
if(duration<=)duration=; if(sk!=SafeKey){
reply(false,"F","Safe Key not match!");
return;
}
reply(true,"F","");
digitalWrite(FPIN,HIGH);
delay(duration * );
digitalWrite(FPIN,LOW);
} void setSKCmd(byte data[], int len){
byte safeBytes[]={,,,};
for(int i=;i<;i++){
safeBytes[i]=(byte)data[+i];
//Serial.println(safeBytes[i],DEC);
}
unsigned long sk= bytes2long(safeBytes);
if(sk!=SafeKey){
reply(false,"SetSK","Safe Key not match!");
return;
} byte newSafeBytes[]={,,,};
for(int i=;i<;i++){
newSafeBytes[i]=(byte)data[+i]; }
unsigned long newSK= bytes2long(newSafeBytes);
_StorageSafeKey(newSafeBytes);
SafeKey=newSK; reply(true,"SetSK","");
} void clsSKCmd(byte data[],int len){
if(bStartsWith(data,len,"ClsSK:pwdashitdingke")){
_ClsSafeKey();
reply(true,"ClsSK",""); }else{
reply(false,"ClsSK","-_!");
}
} void reply(bool isOk,String cmd,String msg){
String rStr="";
if(isOk){
rStr="$FOK-" + cmd +":" +msg +"$E";
mySerial.println("AT+CIPSEND=0," + (String)rStr.length());
delay();
mySerial.println(rStr);
}else{
rStr="$FEE-" + cmd +":" +msg +"$E";
mySerial.println("AT+CIPSEND=0," + (String)rStr.length());
delay();
mySerial.println(rStr);
} } void replyBytes(bool isOk,String cmd,byte msg[],int msgLen){
String rStr="";
int sendLen=;
if(isOk){
rStr="$FOK-" + cmd +":" ;
sendLen= rStr.length() + msgLen +; //2 is "$E"
mySerial.println("AT+CIPSEND=0," + (String)sendLen);
delay();
mySerial.print(rStr);
for(int i=;i<msgLen;i++){
mySerial.write(msg[i]);
}
mySerial.println("$E");
}else{
rStr="$FEE-" + cmd +":" ;
sendLen= rStr.length() + msgLen +; //2 is "$E"
mySerial.println("AT+CIPSEND=0," + (String)sendLen);
delay();
mySerial.print(rStr);
for(int i=;i<msgLen;i++){
mySerial.write(msg[i]);
}
mySerial.println("$E");
} } void cls(){
while(mySerial.available()){
mySerial.read();
}
} void delayAndRead(int waitTime){
delay(waitTime);
while(mySerial.available()){
Serial.write(mySerial.read());
}
} void _StorageSafeKey(byte skBytes[]){
String flag="SK-OK";
int i=;
for(int address=E2PROM_OFFSET;address<(E2PROM_OFFSET + );address++){
EEPROM.write(address,flag.charAt(i++));
//Serial.print((char)EEPROM.read(address));
} i=;
for(int address=(E2PROM_OFFSET + );address< (E2PROM_OFFSET + +);address++){
EEPROM.write(address,skBytes[i++]);
}
} void _ClsSafeKey(){
for(int address=E2PROM_OFFSET;address<(E2PROM_OFFSET + );address++){
EEPROM.write(address,(byte)0xFF);
//Serial.print((char)EEPROM.read(address));
}
} boolean _ReadSafeKey(unsigned long &b){
b=;
int address=;
String tmp="";
char readChar=' ';
for(int address=E2PROM_OFFSET;address<(E2PROM_OFFSET + );address++){
readChar=(char)EEPROM.read(address);
tmp +=readChar;
} if(tmp!="SK-OK"){
return false;
} byte skBytes[]={,,,};
int i=;
for(int address=(E2PROM_OFFSET + );address< (E2PROM_OFFSET + +);address++){
skBytes[i]=(byte)EEPROM.read(address); i++;
}
//Serial.println(tmp);
b= bytes2long(skBytes);
return true;
} void long2byte(unsigned long res,byte targets[] ) {
targets[] = (byte) (res & 0xff);// 鏈�浣庝綅
targets[] = (byte) ((res >> ) & 0xff);// 娆′綆浣�
targets[] = (byte) ((res >> ) & 0xff);// 娆¢珮浣�
targets[] = (byte) (res >> );// 鏈�楂樹綅,鏃犵鍙峰彸绉汇�� } unsigned long bytes2long(byte buf[]) {
unsigned long firstByte = ;
unsigned long secondByte = ;
unsigned long thirdByte = ;
unsigned long fourthByte = ;
int index = ;
firstByte = (0x000000FFU & ( buf[index+]));
secondByte = (0x000000FFU & ( buf[index + ]));
thirdByte = (0x000000FFU & ( buf[index + ]));
fourthByte = (0x000000FFU & ( buf[index ]));
index = index + ;
return ((unsigned long) (firstByte << | secondByte << | thirdByte << | fourthByte)) & 0xFFFFFFFFUL;
}

注意,unsigned int 跟int 最好只用一种,混合使用是有些莫名其妙的问题

arduino 串口数据啊按字节分析的更多相关文章

  1. 【Debug】串口发送数据时部分字节被拉长,出现帧错误,原因MCU进入低功耗模式导致串口时钟停了!

    串口发送数据时部分字节被拉长,出现帧错误,原因MCU进入低功耗模式导致串口时钟停了!

  2. Arduino - 串口操作函数与示例代码大全

    来源:https://blog.csdn.net/iracer/article/details/50334041 Arduino - 串口操作函数与示例代码大全 本文总结了Arduino常用串口操作函 ...

  3. 修改Arduino串口缓冲区大小(转)

    本帖节选自<Arduino程序设计基础>第二版5.1.6串口缓冲区       在之前的示例程序中,我们都是采用人工输入测试数据的方式检验程序效果,Arduino每接收到一次数据,就会将数 ...

  4. Arduino 串口通讯参考笔记 - Serial 类库及相关函数介绍

    声明: 本ID发布的所有文章及随笔均为原创,可随意转载,单转载文章必须注明作者 aiyauto 及包含原文出处地址 http://www.cnblogs.com/aiyauto/p/7071712.h ...

  5. Arduino串口的一些高级用法

    1.配置串口通信数据位.校验位.停止位通常我们使用Serial.begin(speed)来完成串口的初始化,这种方式,只能配置串口的波特率.而使用Serial.begin(speed, config) ...

  6. Arduino 串口的一些高级用法

    来源: 1.配置串口通信数据位.校验位.停止位 通常我们使用Serial.begin(speed)来完成串口的初始化,这种方式,只能配置串口的波特率. 而使用Serial.begin(speed, c ...

  7. Arduino 串口库函数

    库函数目录 if (Serial) available() availableForWrite() begin() end() find() findUntil() flush() parseFloa ...

  8. Android(Linux)实时监控串口数据

    之前在做WinCE车载方案时,曾做过一个小工具TraceMonitor,用于显示WinCE系统上应用程序的调试信息,特别是在实车调试时,用于监控和显示CAN盒与主机之间的串口数据.因为需要抢占市场先机 ...

  9. [转] TCP数据包重组实现分析

    PS: 这个实现对于某些特定情况未必是最佳实现,可以用数组来代替队列来实现 参照TCP/IP详解第二卷24~29章,详细论述了TCP协议的实现,大概总结一下TCP如何向应用层保证数据包的正确性.可靠性 ...

随机推荐

  1. RAD 10.1多标签页bug

    frm->Parent= ActiveControl取不到了 ::setparent(frm-> 多屏幕显示器,次副屏幕上无法最大化了. ::SetParent(myform->Ha ...

  2. 使用SendMessage进行进程间通信

    Imports System.Runtime.InteropServices Public Class Monitor <DllImport("user32.dll", Ch ...

  3. as3 XML类和XMLList类的区别

    一.XML类和XMLList类的区别       AS3.0中,处理XML主要用到两个主类,XML类和XMLList类,这两个类的很多内容是共通的.应该有人会问,XML和XMLList的区别是什么? ...

  4. Putty全屏/退出全屏快捷键

  5. Effective C++笔记——day01

    1.当我们看到赋值符号时,请小心,因为"="也可以用来调用copy构造函数 Widget w3 = w2; //调用copy构造函数,而不是copy赋值操作符 2.不明确的行为: ...

  6. python2限制函数传入的关键字参数

    在Python2 中,可以通过使用**kwargs,在函数中配合使用kwargs.pop(key, False)实现获取限制关键字参数值,如果未传入则设置默认值,当所有需要的关键字参数都pop完毕,如 ...

  7. Haskell语言学习笔记(58)Bifoldable

    Bifoldable class Bifoldable p where bifold :: Monoid m => p m m -> m bifold = bifoldMap id id ...

  8. 打地鼠Demo

    using UnityEngine; using System.Collections; public enum MoleStates { NormalState,// 初始状态 UpState,// ...

  9. CentOS7系列搭建Openvpn

    环境:CentOS Linux release 7.3.1611 (Core) 查看os版本命令:[root@openvpn ~]# cat /etc/redhat-release 命令记录如下: y ...

  10. centos7 opencc 安装

    繁体字转换:http://xh.5156edu.com/jtof.php 转换的有问题http://tool.lu/zhconvert/ git网址:https://github.com/BYVoid ...