我正在运行一段C代码,它从10 Dynamixel个伺服电机(ID,位置,角度,负载 - 扭矩)获取信息并将它们打印到屏幕上并将其写入日志文件(watchdog_log.txt)。
#include <stdio.h>
#include <stdlib.h>
#include <termio.h>
#include <unistd.h>
#include <string.h>
#include <dynamixel.h>
#include <math.h>
#include <dynamixelAX.h>
#include "utils_v2.h"
#include "low_level_v2AX.h"
#include "low_level_v2.h"
// Control table address
#define P_GOAL_POSITION_L 30
#define P_GOAL_POSITION_H 31
#define P_PRESENT_POSITION_L 36
#define P_PRESENT_POSITION_H 37
#define P_MOVING 46
// Defulat setting
#define DEFAULT_BAUDNUM 34 // 1Mbps
#define DEFAULT_BAUDNUM_AX 1
#define DEFAULT_ID 1
int main()
{
FILE *fp;
/* Get actuator ID from command line argument */
int baudnum = 34;
int baudnum_AX = 1;
int deviceIndex = 0;
int deviceIndex_AX = 1;
int current;
float load, angle;
int i=0;
int MOTOR_CHAIN[13]={-1,1,1,0,0,0,-1,1,1,0,0,0,-1};
int MOTOR_CHAIN_AX[18]={2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2};
int MOTOR_HOME[13]={404,444,3216,2037,2289,512,860,661,879,3474,1747,512}; //0, 6 and 12 are dummy
int MOTOR_HOME_AX[18]={512,512,512,512,512,512,512,512,512,512,512,512,512,512,512,512,512,512,};
char report[1000];
char buffer[50];
strcpy(report,"***********\n");
/* Initialise Open USB2Dynamixel */
if( dxl_initialize(deviceIndex, baudnum) == 0 )
{
printf( "Failed to open USB2Dynamixel!-chain'0'\n" );
printf( "Press Enter key to terminate...\n" );
}
else
printf( "Successfully opened USB2Dynamixel 0!\n" );
if( dxl_initializeAX(deviceIndex_AX, baudnum_AX) == 0 )
{
printf( "Failed to open USB2Dynamixel!-chain'1'\n" );
printf( "Press Enter key to terminate...\n" );
}
else
printf( "Successfully opened USB2Dynamixel 1!\n" );
/* Ping all devices */
printf("Pinging devices...");
for( i=0; i<=12; i++)
{
dxl_ping(i);
if (dxl_get_result() == COMM_RXSUCCESS)
{
current = (fabs(dxl_read_word(i, 0x34)-512)*10);
load = dxl_read_word(i, 0x28);
if (load>=1024)
load=(load-1024)*0.1;
else load=load*0.1;
int theta = dxl_read_word(i, 36);
angle = counttoangle(MOTOR_CHAIN[i], MOTOR_HOME[i], theta);
printf("ID: %d success, Load: %3.1f, Count = %d, Angle = %3.2f\n", i, load, theta, angle) ;
sprintf(buffer,"ID: %d success, Load: %3.1f, Count = %d, Angle = %3.2f\n",i, load, theta, angle);
strcat(report,buffer);
}
else printf("ID: %d failure\n",i);
}
//File operations
strcat(report,"***********\n\n\n");
fp = fopen("watchdog_log.txt","w"); /* append file (add text to a file or create a file if it does not exist.*/
fprintf(fp,"%s",report); /*writes to file*/
fclose(fp); /*done!*/**
/* Close device */
dxl_terminateAX();
return 0;
}
我在Ubuntu上使用'watch'命令每秒运行一次代码,以便不断监视屏幕上代码的输出。
watch -n 1 ./watchdog
未完成文件操作时,终端上的输出正常。但是当文件写入完成后,终端会给出bizzare输出:
正常输出
Bizzare输出
对上述问题的任何帮助将不胜感激。
答案 0 :(得分:0)
乍一看,问题在于你的变量:
char report[1000];
char buffer[50];
sprintf(buffer,"ID: %d success, Load: %3.1f, Count = %d, Angle = %3.2f\n",i, load, theta, angle);
字符串的最小大小大于50个字节!
因此,您可以尝试增加字符串变量的大小或计算所需的大小,并将它们分配到堆中......