效果:
按天建文件夹,按小时建文件
从串口读取库伦计的打印内容,过滤掉干扰字符后用scanf将关注的数字分离出来之后写入txt文件
matlab从txt文件中读入数据绘图分析
完整源码
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#define PATH_TTYDEVICE "/dev/ttyUSB0"
#define MAX_BUF_SIZE 100
FILE *fp = NULL;
FILE *fp1 = NULL;
void Stop(int signo)
{
fclose(fp1);
printf("oop! stop!!!\n");
_exit(0);
}
int CreateDir(const char *sPathName)
{
char DirName[256];
strcpy(DirName, sPathName);
int i,len = strlen(DirName);
for(i=1; i<len; i++)
{
if(DirName[i]=='/')
{
DirName[i] = 0;
if(access(DirName, 0)!=0)
{
if(mkdir(DirName, 0755)==-1)
{
printf("mkdir error\n");
return -1;
}
}
DirName[i] = '/';
}
}
return 0;
}
int CreateFile(const char *path)
{
FILE *f;
if(access(path, 0)!=0) {
f = fopen(path, "w+");
if( f == NULL) {
printf("create file failed \r\n");
return -1;
}
else {
fclose(f);
return 0;
}
}
return -1;
}
void getdate(char *date, char *hour)
{
struct tm *my_tm;
time_t t1;
t1 = time(&t1);
my_tm = localtime(&t1);
sprintf(date, "%04d-%02d-%02d" ,my_tm->tm_year + 1900, my_tm->tm_mon + 1, my_tm->tm_mday);
sprintf(hour, "%02d" ,my_tm->tm_hour);
//printf("current my_tm : %04d-%02d-%02d %02d:%02d:%02d\n\r", my_tm->tm_year + 1900, my_tm->tm_mon + 1, my_tm->tm_mday,my_tm->tm_hour, my_tm->tm_min, my_tm->tm_sec );
}
void analyse(char *Buf)
{
float v,c,w,t;
char time[15];
char *buf = Buf;
/*skip letter just analyse number */
while(1) {
if (*buf >= '0' && *buf <= '9') {
break;
}
buf++;
}
sscanf(buf,"%fV,%fA,%fAh,%s\r\n",&v,&c,&w,time);
if (v>25.0) {
v= 25.0;
}
if (c > 5.0) {
c = 5.0;
}
if (w > 80.0) {
w = 80.0;
}
fprintf(fp1, "%f %f %f\r\n",v,c,w);
}
int main(int c, char *args[])
{
char buf[MAX_BUF_SIZE];
char path[20];
int size,ret;
int index=0;
char date[30];
char hour[3];
signal(SIGINT, Stop);
fp = fopen(PATH_TTYDEVICE, "r+");
if (fp == NULL) {
printf("failed: can not open tty device \r\n! ");
return -1;
}
while(1) {
memset(date,0,sizeof(date));
memset(hour,0,sizeof(hour));
getdate(date,hour);
memset(path,0,sizeof(path));
sprintf(path,"%s/",date);
CreateDir(path);
memset(path,0,sizeof(path));
sprintf(path,"./%s/%s.txt",date,hour);
ret = CreateFile(path);
if (ret == 0 ) {
if (fp1 != NULL) {
fclose(fp1);
}
fp1 = fopen(path, "w+");
if (fp1 == NULL) {
printf("failed: can not open txt file to save the result! \r\n ");
return -1;
}
}
fseek(fp, 0, SEEK_SET);
size = fread(buf+index, 1,1,fp);
if (buf[index] != 0) {
if(buf[index] == '\n') {
if (index > 10) {
printf("read from tty : \r\n");
printf("%s\r\n", buf);
analyse(buf);
}
index = -1;
memset(buf, 0, MAX_BUF_SIZE);
}
index++;
}
}
fclose(fp);
fclose(fp1);
_exit(0);
}
matlab M文件
%读取库仑计打印到txt中的数据进行绘图分析
path = 'E:\VMWareShare\14.txt';
data=load(path);
V=data(:,1);
C=data(:,2);
W=data(:,3);