#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. npm 安装cnpm

    npm install -g cnpm --registry=https://registry.npm.taobao.org

  2. 10 python 封装----@property的用法

    1.基本概念 在python中用双下划线开头的方式将属性隐藏起来(设置成私有的) #其实这仅仅这是一种变形操作 #类中所有双下划线开头的名称如__x都会自动变形成:_类名__x的形式: class A ...

  3. WP runtime local setting

    https://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdata.localsettings. ...

  4. WP runtime 获取cookie

    HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter(); HttpCookieManager http ...

  5. 使用Jena执行SPARQL的Select和Ask查询

    使用Jena执行SPARQL的Select和ask查询 提供基本的接口和实现类,可在其他代码中直接调用 Select查询 接口 /** * The interface Select dao. * 本体 ...

  6. Haskell语言学习笔记(26)Identity, IdentityT

    Identity Monad newtype Identity a = Identity { runIdentity :: a } instance Functor Identity where fm ...

  7. The requested resource (/) is not available解决办法

    The requested resource (/) is not available HTTP Status 404(The requested resource is not available) ...

  8. 疯狂JAVA——第六章 面向对象(下)

    6.1包装类 java为了照顾程序员的传统习惯,所以提供了八种基本数据类型.但也带来不方便,例如所有引用类型都继承自Object类,都可当做Object类型变量使用.但基本数据类型的变量就不可以.如果 ...

  9. node集成mysql——pool连接池

    安装 mysql npm install mysql or cnpm install mysql 创建db.js,实现mysql操作模块 var mysql = require('mysql'); v ...

  10. Fragment 实现拍照,相册选图,设置头像功能

    设置不成功,http://bbs.csdn.net/topics/391112964 采纳问题回答:这个是fragment没有收到这个回调,原因不多说了,,,你用你对应的ragment.startAc ...