如何用C语言在Linux下给cc2530实现一个简单的上位机(下)
四、 上位机功能函数
结构体
#define DEV_ID_LED_ON 0X1
#define DEV_ID_LED_OFF 0X2
#define DEV_ID_DELAY 0X3
#define DEV_ID_GAS 0X4
struct data{
unsigned char device;
unsigned char crc;
unsigned short data;
};
函数
void uart_init(void )
{
int nset1,nset2;
serial_fd = open( "/dev/ttyUSB0", O_RDWR);
if(serial_fd == -1)
{
printf("open() error\n");
exit(1);
}
nset1 = set_opt(serial_fd, 115200, 8, 'N', 1);
if(nset2 == -1)
{
printf("set_opt() error\n");
exit(1);
}
}
int Menu()
{
int option;
system("clear");
printf("\n\t\t************************************************\n");
printf("\n\t\t** ALARM SYSTERM **\n");
printf("\n\t\t** 1----LED **\n");
printf("\n\t\t** 2----GAS **\n");
printf("\n\t\t** 0----EXIT **\n");
printf("\n\t\t************************************************\n");
while(1)
{
printf("Please choose what you want: ");
scanf("%d",&option);
if(option<0||option>2)
printf("\t\t choose error!\n");
else
break;
}
return option;
}
// RxData[]: | device | data |crc | # |
void led()
{
int lednum = 0;
int onoff;
char cmd[4];
//选择led灯
while(1)
{
printf("input led number :[1 2]\n#");
scanf("%d",&lednum);
//check
if(lednum<1 || lednum >2)
{
printf("invalid led number\n");
system("clear");
continue;
}else{
break;
}
}
printf("operation: 1 on , 0 off\n");
scanf("%d",&onoff);
if(onoff == 1)
{
cmd[0] = DEV_ID_LED_ON;
}else if(onoff == 0)
{
cmd[0] = DEV_ID_LED_OFF;
}else{
printf("invalid led number\n");
return;
}
cmd[1] = lednum;
//fulfill crc area
cmd[2] = cmd[0]^cmd[1];
cmd[3] = '#';//表示结束符
tcflush(serial_fd, TCIOFLUSH);
int i = 0;
for(i=0;i<4;i++)
{
printf("%d ",cmd[i]);
}
printf("\n");
write(serial_fd,&cmd,sizeof(cmd));
sleep(1);
大林上位机机器视觉_苏州电工培训_苏州PLC培训_苏州上位机培训_苏州机器视觉培训_苏州工业机器人培训_最适合电工及plc编程人员学习的上位机机器视觉课程 大林老师:15861139266(微信同号)
}
// RxData[]: | device | data |crc | # |
void gas()
{
int len ;
unsigned short GasLevel;
struct data msg;
char gas[4]={0};
char cmd[4];
cmd[0] = DEV_ID_GAS;
cmd[3] = '#';//表示结束符
write(serial_fd,&cmd,sizeof(cmd));
sleep(1);
len = read(serial_fd,&msg,sizeof(struct data));
//转换读取的gas数据格式
GasLevel = msg.data;
gas[0] = GasLevel / 100 + '0';
gas[1] = GasLevel / 10%10 + '0';
gas[2] = GasLevel % 10 + '0';
printf("%s\n",gas);
getchar();
}
void run()
{
int x;
while(1)
{
x=Menu();
switch(x)
{
case 1:
led();
break;
case 2:
gas();
break;
case 0:
printf("\n\t\t exit!\n\n");
close(serial_fd);
exit(0);
default:
fg=1;
break;
}
if(fg)
break;
}
}
int main()
{
uart_init();
run();
return 0;
}
五、 运行结果
1. 上位机运行界面
2. 点亮led灯
点亮led1:
3. 灭灯
4. 读取烟雾传感器数据
版权所有:江苏和讯自动化设备有限公司所有 备案号:苏ICP备2022010314号-1
技术支持: 易动力网络