Скрипт для револьверной головки токарного станка - рабочий.

KFlop, KStep, KAnalog, KMotion...
Аватара пользователя
ukr-sasha
Мастер
Сообщения: 3401
Зарегистрирован: 21 мар 2011, 07:47
Репутация: 2180
Настоящее имя: Украинец Александр Григорьевич
Откуда: Киев, Украина
Контактная информация:

Скрипт для револьверной головки токарного станка - рабочий.

Сообщение ukr-sasha »

Скрипт для револьверной головки токарного станка - рабочий и с комментариями.
Ранняя версия для 8-ми инструментов была с ошибкой.
В папке со скриптом должен лежать файл KflopToKMotionCNCFunctions.c

Код: Выделить всё

//---------------------------------------------------
// Файл настройки  револьверной головки станка 16А20
// Версия 2.0 07.07.2016г
// Автор Украинец А.Г., г.Киев, 2016г.
//---------------------------------------------------
#include "KMotionDef.h"
#define TMP 10 // which spare persist to use to transfer data
#include "KflopToKMotionCNCFunctions.c"
#define GATH_OFF 0  // define the offset into the Gather buffer where strings are passed
int DoPC(int cmd);
int DoPCFloat(int cmd, float f);
int DoPCInt(int cmd, int i);
int MsgBox(char *s, int Flags);
int SetVars(int poff, int varoff, int n);
int GetVars(int varoff, int n, int poff);

main()
{
int FixtureIndex,Units, TWORD, HWORD, DWORD;
SetBitDirection(154,1); // пин как выход
SetBitDirection(156,1); // пин как выход
ClearBit (154);//forvard
ClearBit (156);//revers

//определяем пины , как ВХОД
SetBitDirection(136,0); // для инструмента №1
SetBitDirection(137,0); // для инструмента №2
SetBitDirection(138,0); // для инструмента №3
SetBitDirection(139,0); // для инструмента №4
SetBitDirection(140,0); // для инструмента №5
SetBitDirection(141,0); // для инструмента №6
SetBitDirection(142,0); // вход токового датчика
int ToolN=0;
//проверяем номер инструмента
if (ReadBit(136))
ToolN=1;
if (ReadBit(137))
ToolN=2;
if (ReadBit(138))
ToolN=3;
if (ReadBit(139))
ToolN=4;
if (ReadBit(140))
ToolN=5;
if (ReadBit(141))
ToolN=6;

GetMiscSettings(&Units, &TWORD, &HWORD, &DWORD); // читаем переменные: единицы измерения, T, H, D
printf("Units=%d T=%d  H=%d  D=%d\n",Units, TWORD, HWORD, DWORD);

if (ToolN == 0 || TWORD > 6) // проверка, в позиции ли револьверка и не больше ли 6 номер инструмента
  {
         StopCoordinatedMotion();  //feedhold
         MDI("M5 M8 M2 M30 G92.1");  //  остановка программы и очистка оффсетов
         int Answer;
         char s[100];
         if (ToolN == 0 )
    sprintf(s,"Револьверная головка не в позиции  \n");
         else
    sprintf(s,"Номер инструмента больше 6!  \n");
         Answer = MsgBox(s,MB_ICONEXCLAMATION);
  }
else
  {
         if (ToolN != TWORD+1)
   {

			  SetBit(154);//если номер не совпадает то устанавливаем бит
			  int TimeI=0;
	   
			  do //  проверяем входы пока не выполниться условие
			  {       
				  if (ReadBit(136)) ToolN=1;
				  if (ReadBit(137)) ToolN=2;
				  if (ReadBit(138)) ToolN=3;
				  if (ReadBit(139)) ToolN=4;
				  if (ReadBit(140)) ToolN=5;
				  if (ReadBit(141)) ToolN=6;
				  
				  //printf("ToolN=%d\n", ToolN);
				  
				  WaitNextTimeSlice();
				  Delay_sec(0.1);
				  TimeI++;
				  if (TimeI == 50) break;  //        ждем пока не пройдет 5 секунд и выходим из цикла - надо подбирать                                            
			  }
			  while (ToolN != TWORD+1);
			  
			  if (TimeI != 50) // если вышли из цикла не по превышению времени ожидания
				{
					  ClearBit(154);// останавливаем проворот револьверки
					  Delay_sec(0.5);// ждем пол секунды
					  SetBit(156);// включаем реверс - затягивание барабана
					  while (!ReadBit(142)); // ждем сигнал окончания затяжки барабана
					  ClearBit(156);// останавливаем затяжку барабана
				}
			  else
				{
					StopCoordinatedMotion();  // в противном случае авария и всё выключаем
					MDI("M5 M8 M2 M30 G92.1");  // 
					int Answer;
					char s[100];
					sprintf(s,"Револьверная головка неисправна!  \n");
					Answer = MsgBox(s,MB_ICONEXCLAMATION);
			}
   }
         else
			  printf("Револьверка в позиции!\n");
  }
}
// 
int SetVars(int varoff, int n, int poff)
{
   persist.UserData[PC_COMM_PERSIST+2] = n;                                        // number of elements
   persist.UserData[PC_COMM_PERSIST+3] = poff;    // persist offset (doubles)
   return DoPCInt(PC_COMM_SET_VARS,varoff);                                        // Var index and Cmd
}
int GetVars(int varoff, int n, int poff)
{
   persist.UserData[PC_COMM_PERSIST+2] = n;                                        // number of elements
   persist.UserData[PC_COMM_PERSIST+3] = poff;    // persist offset (doubles)
   return DoPCInt(PC_COMM_GET_VARS,varoff);                                        // Var index and Cmd
}
#define GATH_OFF 0  // define the offset into the Gather buffer where strings are passed
// Trigger a message box on the PC to be displayed
// defines for MS Windows message box styles and Operator
// response IDs are defined in the KMotionDef.h file
int MsgBox(char *s, int Flags)
{
   char *p=(char *)gather_buffer+GATH_OFF*sizeof(int);
   int i;
   do // copy to gather buffer w offset 0
   {
        *p++ = *s++;
   }while (s[-1]);
   persist.UserData[PC_COMM_PERSIST+2] = Flags;  // set options
   DoPCInt(PC_COMM_MSG,GATH_OFF);
   return persist.UserData[PC_COMM_PERSIST+3];
}
// put the MDI string (Manual Data Input - GCode) in the
// gather buffer and tell the App where it is
int MDI(char *s)
{
   char *p=(char *)gather_buffer+GATH_OFF*sizeof(int);
   int i;
   do // copy to gather buffer w offset 0
   {
        *p++ = *s++;
   }while (s[-1]);
   // issue the command an wait till it is complete
   // (or an error - such as busy)
   return DoPCInt(PC_COMM_MDI,GATH_OFF);
}
// Put a Float as a parameter and pass the command to the App
int DoPCFloat(int cmd, float f)
{
   int result;
   persist.UserData[PC_COMM_PERSIST+1] = *(int*)&f;
   return DoPC(cmd);
}
// Put an integer as a parameter and pass the command to the App
int DoPCInt(int cmd, int i)
{
   int result;
   persist.UserData[PC_COMM_PERSIST+1] = i;
   return DoPC(cmd);
}
// Pass a command to the PC and wait for it to handshake
// that it was received by either clearing the command
// or changing it to a negative error code
int DoPC(int cmd)
{
   int result;
   persist.UserData[PC_COMM_PERSIST]=cmd;
   do
   {
      WaitNextTimeSlice();
   }while (result=persist.UserData[PC_COMM_PERSIST]>0);
   //printf("Result = %d\n",result);
   return result;
}

Вернуться в «KFlop»