aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Embedded_SW/Embedded/Modules/Thread/Thread_Winder.c
blob: f8b0efb174089d824b3312224c4f2ce13d7b6cf1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
#ifndef MODULES_THREAD_THREAD_H_
#define MODULES_THREAD_THREAD_H_

#include "PMR/common/MessageContainer.pb-c.h"
#include "PMR/Hardware/HardwareMotor.pb-c.h"
#include "PMR/Hardware/HardwareMotorType.pb-c.h"
#include "PMR/Hardware/HardwareDancer.pb-c.h"
#include "PMR/Hardware/HardwareDancerType.pb-c.h"
#include "PMR/Hardware/HardwareWinder.pb-c.h"
#include "PMR/Hardware/HardwarePidControl.pb-c.h"
#include "PMR/Hardware/HardwareConfiguration.pb-c.h"
#include "PMR/Printing/JobSpool.pb-c.h"
#include "PMR/Printing/JobSpoolType.pb-c.h"

#include "drivers/Motors/Motor.h"
#include "../control/pidalgo.h"

#include "thread_ex.h"
#include "drivers/SSI_Comm/SSI_Comm.h"

#define NORMAL_COEF_DIVIDER 100
typedef struct
{
    uint32_t startoffsetpulses;
    uint32_t spoolbackingrate;
    uint32_t segmentoffsetpulses;// the spool winding initial length in mm
    uint32_t milimetersperrotation;
    uint32_t SpoolBottomBackingRate;// the angle of the bottom of the spool
    double NumberOfRotationPerPassage;  // how many rotations per spool passage
    double diameter;
}InternalWinderConfigStruc;
typedef struct
{
    bool                m_isEnabled;
    int32_t             m_SetParam;
    float               m_mesuredParam;
    float               m_preError;
    float               m_integral;
    float               m_calculatedError;
    bool                m_isReady;
    uint32_t            m_ingnoreValue;
    PID_Config_Params   m_params;
}MotorControlConfig_t;

#ifdef FOUR_WINDERS
#define SCREW_2_Motor  HARDWARE_MOTOR_TYPE__MOTO_SPARE2_1
#define SCREW_3_Motor  HARDWARE_MOTOR_TYPE__MOTO_SPARE1_1
#define SCREW_4_Motor  HARDWARE_MOTOR_TYPE__MOTO_RDANCER
#define Winder_2_Motor HARDWARE_MOTOR_TYPE__MOTO_SPARE2_2
#define Winder_3_Motor HARDWARE_MOTOR_TYPE__MOTO_SPARE1_2
#define Winder_4_Motor HARDWARE_MOTOR_TYPE__MOTO_RLOADARM
#endif


#define MAX_THREAD_FEED_MOTORS (WINDER_MOTOR+1)
#define MAX_SYSTEM_DANCERS NUM_OF_ROTENC

extern TimerMotors_t ThreadMotorIdToMotorId[MAX_THREAD_MOTORS_NUM];

#ifdef FOUR_WINDERS
extern Dancers_4_Winders ThreadMotorIdToDancerId[MAX_THREAD_MOTORS_NUM];
#else
extern HardwareDancerType ThreadMotorIdToDancerId[MAX_THREAD_MOTORS_NUM];
#endif

extern HardwarePidControlType ThreadMotorIdToControlId[MAX_THREAD_MOTORS_NUM];

extern bool BreakSensorenabled;
extern int32_t BreakSensordebouncetimemilli;

extern bool SampleWinding;


//extern MotorDriverConfigStruc                MotorsCfg[NUM_OF_MOTORS];
extern HardwarePidControl           MotorsControlpre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/*
 * Thread_Winder.c
 *
 *  Created on: 25 áîøõ 2018
 *      Author: shlomo
 */
#include"include.h"
#include "thread.h"

#include "drivers/Motors/Motor.h"
#include "StateMachines/Printing/PrintingSTM.h"
#include "Modules/Control/Control.h"
#include "Modules/Control/MillisecTask.h"

#include "modules/General/process.h"

#include "Common/report/report.h"

#include "drivers/FPGA/FPGA.h"

#include "drivers/FPGA/FPGA_SPI_Comm.h"
#include "drivers/FPGA/FPGA_GPIO/FPGA_GPIO.h"

#include  <PMR/Diagnostics/EventType.pb-c.h>
#include "Modules/AlarmHandling/AlarmHandling.h"

#include <driverlib/timer.h>
#include <inc/hw_ints.h>
#include <inc/hw_memmap.h>


#define MAX_WINDER_SPEED_CALCULATION 200

uint32_t Winder_ScrewAtOffsetCallback(uint32_t deviceID, uint32_t BusyFlag);
uint32_t Winder_PrepareStage2(uint32_t deviceID, uint32_t ReadValue);
void ScrewTimerInterruptInit(void);
void ScrewsStopControlTimer (void);
void ScrewsStartControlTimer (void);

bool     Winder_ScrewHoming = false;
bool     ScrewCurrentDirection = false;  //holds current screw direction
uint32_t ScrewDirectionChangeCounter = 1; //holds the current number of runs of the screw  - will be used to build the cone
//uint32_t ScrewChangeCounter = 0;
//uint32_t ScrewChangeLimit = 0;
uint32_t CalculationDirectionChangeCounter = 1; //holds the current number of runs of the screw  - will be used to build the cone
uint16_t WinderMotorSpeed[MAX_WINDER_SPEED_CALCULATION];
uint16_t WinderMotorSpeedCounter = 0;
bool     WinderMotorSpeedRollOver = false;
double   ScrewSpeed = 0;
double   ScrewRunningTime = 0;
uint32_t ScrewNumberOfSteps = 0;     //holds the current number of steps for the next screw run - will be used to build the cone
bool     SCREW_TimerActivated = false;
uint32_t ScrewControlId = 0xFF;

InternalWinderConfigStruc InternalWinderCfg = {0};

uint32_t ScrewLocationLimitSwitch = 0,ScrewLocationStart = 0;
uint32_t ScrewLocationRun[3];

uint32_t Winder_Init(void)
{
    ScrewTimerInterruptInit();
    return OK;
}


uint32_t InternalWinderConfigMessage(HardwareWinder* request)
{
    uint32_t status = PASSED;

    InternalWinderCfg.milimetersperrotation = request->millimeterperrotation;

    return status;
}
uint32_t InternalWindingConfigMessage(JobSpool* request)
{
    uint32_t status = PASSED;

    InternalWinderCfg.segmentoffsetpulses = request->segmentoffsetpulses;
    InternalWinderCfg.spoolbackingrate = request->backingrate;
    InternalWinderCfg.startoffsetpulses = request->startoffsetpulses;
    InternalWinderCfg.SpoolBottomBackingRate =  request->bottombackingrate;
    InternalWinderCfg.NumberOfRotationPerPassage = 3.1415926*2;//request->rotationsperpassage;
    InternalWinderCfg.diameter = request->diameter;

    return status;
}
/*
 *uint32_t Winder_Prepare(void *JobDetails)

 * 1. move home to the limit switch (check that the cart is clear from the limit switch, start moving, with acceleration to maximal speed. enable interrupt on the limit switch, upon interrupt stop.
 * report ready to the job STM
 */
uint32_t Winder_Prepare(void)
{
    uint32_t status = 0;
    //JobTicket* JobTicket = JobDetails;
    //float process_speed = JobTicket->processparameters->dyeingspeed;
    double ScrewSpeed = 1500;//(process_speed*MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].pulleyradius);  // we will use pulley radius of the screw for this purpose, as of now
    //MotorSetMaxSpeed (HARDWARE_MOTOR_TYPE__MOTO_SCREW,InternalWinderCfg.segmentoffsetpulses);
    //REPORT_MSG(ScrewSpeed, "Winder_Prepare");
    /*
     * 1. move home to the limit switch (check that the cart is clear from the limit switch, start moving, with acceleration to maximal speed. enable interrupt on the limit switch, upon interrupt stop.
     * 2. move back x steps - according to thehw specifications and bobine definitions in the job. move for a predefined number of steps. get a callback when done
     * report ready to the job STM
     */

    /*if (FPGA_Read_limit_Switches(GPI_SW_SPOOL_EXISTS)==LIMIT)
    {
        REPORT_MSG(LIMIT, "No cone in winder");
        PrepareReady(Module_Winder,ModuleFail);
        AlarmHandlingSetAlarm(EVENT_TYPE__WINDER_CONE_DOES_NOT_EXIST,true);
        return ERROR;
    }*/

    ScrewLocationRun[0] = 0;
    ScrewLocationRun[1] = 0;

    if (FPGA_Read_limit_Switches(GPI_LS_SCREW_RIGHT)==LIMIT)
    {
        //REPORT_MSG(LIMIT, "Winder_Prepare at limit");
        Winder_PrepareStage2(0,0);
    }
    else
    {
        //REPORT_MSG(ScrewSpeed, "Winder_Prepare");
        Winder_ScrewHoming = true;
        //REPORT_MSG(MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].directionthreadwize, "Winder_Prepare move to limit");
        status = MotorMovetoLimitSwitch (HARDWARE_MOTOR_TYPE__MOTO_SCREW,MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].directionthreadwize, ScrewSpeed, GPI_LS_SCREW_RIGHT, Winder_PrepareStage2,2000);
    }
    return status;
}
/*
 * uint32_t Winder_PrepareStage2(uint32_t deviceID, uint32_t ReadValue)
 *  2. move back x steps - according to thehw specifications and bobine definitions in the job. move for a predefined number of steps. get a callback when done
 * report ready to the job STM
 */

uint32_t Winder_PrepareStage2(uint32_t deviceID, uint32_t ReadValue)
{
    uint32_t status=OK;
    uint32_t numOfSteps = InternalWinderCfg.startoffsetpulses*MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].microstep;

    //MotorSetMaxSpeed (HARDWARE_MOTOR_TYPE__MOTO_SCREW,InternalWinderCfg.segmentoffsetpulses);
    //REPORT_MSG(numOfSteps, "Winder_PrepareStage2");
    //Read_Screw_Encoder();
    //ScrewLocationLimitSwitch = Screw_RotEnc.Position;
    //REPORT_MSG(ScrewLocationLimitSwitch, "Winder_PrepareStage2 Encoder Location");


    REPORT_MSG(millisecondCounter/*MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].maxfrequency*/, "Winder_PrepareStage2");
    if (ReadValue != LIMIT)
    {
        LOG_ERROR(ReadValue,"Screw failed to reach the limit switch!!");
        //returned with a timeout
        Winder_ScrewAtOffsetCallback(0,0);
    }
    else
    {
        status |= MotorMoveWithCallback(HARDWARE_MOTOR_TYPE__MOTO_SCREW, (1-MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].directionthreadwize),numOfSteps, Winder_ScrewAtOffsetCallback,1000);
    }
     //set motor location 0 here
        return status;

}

uint32_t Winder_ScrewAtOffsetCallback(uint32_t deviceID, uint32_t BusyFlag)
{
    //SetMotHome(HARDWARE_MOTOR_TYPE__MOTO_SCREW);  //set this point as the spool home
    //MotorSetMaxSpeed (HARDWARE_MOTOR_TYPE__MOTO_SCREW,temp_MaxFrequency);

    //Read_Screw_Encoder();
    //ScrewLocationStart = Screw_RotEnc.Position;

    REPORT_MSG(ScrewLocationStart, "Winder_ScrewAtOffsetCallback Encoder Location");

    ScrewCurrentDirection = false;
    ScrewLocationRun[ScrewCurrentDirection] = Screw_RotEnc.Position;
    ScrewSpeed = 0;
    ScrewControlId = 0xFF;
    ScrewNumberOfSteps = 0;
    REPORT_MSG(millisecondCounter, "Winder_ScrewAtOffsetCallback");
    MotorStop (HARDWARE_MOTOR_TYPE__MOTO_SCREW,Soft_Hiz); //per L6470 errata between mov and run commands
    PrepareReady(Module_Winder, ModuleDone);
    return OK;
}

/*
 * this is the main operational function of the screw - run back and forth until stopped
 */
/*
    InternalWinderCfg.segmentoffsetpulses = request->segmentoffsetpulses;
    InternalWinderCfg.spoolbackingrate = request->backingrate;
    InternalWinderCfg.startoffsetpulses = request->startoffsetpulses;
    InternalWinderCfg.SpoolBottomBackingRate =  request->bottombackingrate;
    InternalWinderCfg.NumberOfRotationPerPassage = request->rotationsperpassage;
 *
Calculate the number of steps.
Initial home position = ...
Initial out movement = ScrewNumberOfSteps
if DirectionChangeCounter %= backingrate : reduce one from the  ScrewNumberOfSteps
if DirectionChangeCounter %= bottombackingrate && direction was out: ADD one to the  ScrewNumberOfSteps,
// WRONG? if the flag is raised - lower it and reduce one from the  ScrewNumberOfSteps
30:100 - 70
30:99 - 69
30:98 - 68
29:98 - 69
29:97 -68
InternalWinderCfg.segmentoffsetpulses
  int32_t backingrate;
  int32_t bottombackingrate;
  
numOfSteps = InternalWinderCfg.startoffsetpulses*MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].microstep;
*/
char ScrewStr[100];
//char TempScrewStr[100];
double WinderReferenceSpeed=0;
int32_t  TotalWinderSpeed=0;
bool Add100 = false;
double Rotations = 6.0;
uint32_t Screw100msecDirectionChange(uint32_t deviceID, uint32_t BusyFlag)
{
    //uint32_t Steps;
    double temp,tempScrewSpeed;
    double screw_horizontal_speed = 0;
    double RotationsPerSecond;
    int32_t Averagewinderspeed = 0;

    //ScrewChangeCounter++;
    //if ((ScrewChangeCounter>3)&&(ScrewChangeCounter<(ScrewChangeLimit-2))) //do not take the winder speed near the limits
    {
        TotalWinderSpeed-=WinderMotorSpeed[WinderMotorSpeedCounter];
        WinderMotorSpeed[WinderMotorSpeedCounter] = CurrentControlledSpeed[WINDER_MOTOR];
        TotalWinderSpeed+=WinderMotorSpeed[WinderMotorSpeedCounter];
        if (WinderMotorSpeedCounter++>=MAX_WINDER_SPEED_CALCULATION)
        {
            if (WinderMotorSpeedRollOver == false)
            {
                Add100 = true;
                LOG_ERROR(Add100, "Add100 = true");
            }
            WinderMotorSpeedCounter=0;
            WinderMotorSpeedRollOver=true;
        }
    }

    if (ScrewDirectionChangeCounter == CalculationDirectionChangeCounter)
        return OK;

    ScrewCurrentDirection = 1-ScrewCurrentDirection;
    CalculationDirectionChangeCounter++;
    //REPORT_MSG(ScrewLocationRun[1] - ScrewLocationRun[0], "Screw Run NumberOfSteps");
    //usnprintf(ScrewStr, 100, "Winder Encoder: 0 0x%x 1 0x%x diff %d ",ScrewLocationRun[0],ScrewLocationRun[1],abs(ScrewLocationRun[1] - ScrewLocationRun[0]));
    //usnprintf(ScrewStr, 100, "Winder Encoder: 0 %d 1 %d diff %d ",ScrewLocationRun[0],ScrewLocationRun[1],ScrewLocationRun[1] - ScrewLocationRun[0]);
    //Report(ScrewStr,__FILE__,__LINE__,ScrewLocationLimitSwitch,RpWarning,ScrewLocationStart, 0);

    if (ScrewCurrentDirection == 1-MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].directionthreadwize) //next time going out
    {
        if (Add100 == true) //once per job
        {
            ScrewNumberOfSteps += 100;
            Add100 = false;
        }

        if ((CalculationDirectionChangeCounter/2)%InternalWinderCfg.spoolbackingrate == 0)
        {
            ScrewNumberOfSteps--;
            REPORT_MSG(ScrewNumberOfSteps, "Head Backing ScrewNumberOfSteps");

        }
    }
    else //next time going back
    {
        if ((CalculationDirectionChangeCounter/2)%InternalWinderCfg.SpoolBottomBackingRate == 0)
        {
            ScrewNumberOfSteps++;
            REPORT_MSG(ScrewNumberOfSteps, "Bottom Backing ScrewNumberOfSteps");
        }
    }
    if (WinderMotorSpeedRollOver)
    {
        /*for (i=0;i<MAX_WINDER_SPEED_CALCULATION;i++)
        {
            TotalWinderSpeed+=WinderMotorSpeed[i];
        }*/
        Averagewinderspeed = TotalWinderSpeed/MAX_WINDER_SPEED_CALCULATION;
        //REPORT_MSG(winderspeed, "WinderSpeedUpdated");
        //Report("WinderSpeedUpdated",__FILE__,__LINE__,TotalWinderSpeed,RpWarning,Averagewinderspeed,0);

        WinderReferenceSpeed = Averagewinderspeed;
    }
    screw_horizontal_speed = ScrewNumberOfSteps /  Rotations;//InternalWinderCfg.NumberOfRotationPerPassage;
    if (Rotations > 6.6)//7.0)
        Rotations = 6.0;
    RotationsPerSecond =  WinderReferenceSpeed / (double)MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_WINDER].pulseperround;
    tempScrewSpeed = screw_horizontal_speed*RotationsPerSecond;
    //ROM_IntMasterDisable();
    CurrentControlledSpeed[SCREW_MOTOR] = ScrewSpeed;
    temp = SYS_CLK_FREQ;
    temp *= ScrewNumberOfSteps;
    temp /= tempScrewSpeed;
    if ((ScrewRunningTime != temp)||(ScrewSpeed != tempScrewSpeed))
    {
        ScrewSpeed = tempScrewSpeed;
        ScrewRunningTime = temp;//(SYS_CLK_FREQ*Steps)/ScrewSpeed;
        //ROM_IntMasterEnable();
        //usnprintf(TempScrewStr, 100, "Winder: Horizon,Rotation, PPR, RPP{ %d, %d ,%d, %d} ",(int)screw_horizontal_speed,(int)RotationsPerSecond,(int)InternalWinderCfg.NumberOfRotationPerPassage,(int)MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_WINDER].pulseperround);
        //usnprintf(ScrewStr, 100, "Winder: Steps,Speed, Time, WinderSpeed{ %d, %d ,%d, %d} ",(int)ScrewNumberOfSteps,(int)ScrewSpeed,(int)temp,(int)WinderReferenceSpeed);
        //        Report(logmsg[index],__FILE__,__LINE__,index,RpWarning,index,  Counter[index]);
        //        #warning PID is now only proportional (above)
        //Report(TempScrewStr,__FILE__,__LINE__,0,RpWarning,0, 0);
        //Report(ScrewStr,__FILE__,__LINE__,ScrewCurrentDirection,RpWarning,CalculationDirectionChangeCounter, 0);
        //REPORT_MSG(temp , "new winder speed");
        //Report("new winder speed",__FILE__,ScrewNumberOfSteps,temp,RpWarning,ScrewSpeed,0);
    }

    /********************************************************************************/
    //ROM_IntMasterEnable();
    return OK;

}

uint32_t WinderPresegmentReady(uint32_t deviceID, uint32_t ReadValue)
{
    return PreSegmentReady(Module_Winder,ModuleDone);
}

uint32_t Winder_Presegment(void *SegmentDetails, uint32_t SegmentId)
{
    //JobTicket* JobTicket = JobDetails;
    double screw_horizontal_speed = 0;
    double RotationsPerSecond;
	double temp = 0;
    if (dyeingspeed == 0)
    {
        LOG_ERROR (dyeingspeed," job speed zero");
        return ERROR;
    }

    if (SegmentId == 0) // do all this only in the beginning of the job. do not touch after that (assuming spool does not change mid job)
    {
        ScrewCurrentDirection = (1-MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].directionthreadwize);

        //     * speed is set by the winding parameters and by winder rotational speed (read POSITION every 10msec)
        //     * calculate
        //     * 1. calculate speed according to JobTicket->processparameters->dyeingspeed
        //     * calculation input: traverse length in milimeters/pulses, number of rotations per traverse ==> length of traverse per rotation.
        ScrewNumberOfSteps = InternalWinderCfg.segmentoffsetpulses;//*MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].microstep;
        ScrewNumberOfSteps -= 100;
        screw_horizontal_speed = ScrewNumberOfSteps /  InternalWinderCfg.NumberOfRotationPerPassage;
        // calculation input#2: number of rotations per second - (basically: speed/winder perimeter. later - according to winder actual speed - calculate according to winder position accumulation in the last second.
        //RotationsPerSecond = dyeingspeed / (MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_WINDER].pulleyradius * PI);
        RotationsPerSecond =  OriginalMotorSpd_2PPS[WINDER_MOTOR] / MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_WINDER].pulseperround;
        // calculation input#3: speed = rotation per second * traverse per rotation = traverse per second. speed set: traverse per second (mm) * pulses per mm.
        ScrewSpeed = screw_horizontal_speed*RotationsPerSecond;

        //MotorSetMaxSpeed (HARDWARE_MOTOR_TYPE__MOTO_SCREW,ScrewSpeed);
        usnprintf(ScrewStr, 100, "SCREW speed Rot/sec %d horizon %d pulses %d",(int)RotationsPerSecond,(int)screw_horizontal_speed,(int)ScrewSpeed);
        //REPORT_MSG(segmentfirst_speed,ScrewStr);
        Report(ScrewStr,__FILE__,__LINE__,RotationsPerSecond,RpWarning,ScrewSpeed,0);
        SendJobProgress(0.0,0,false, ScrewStr);

        CurrentControlledSpeed[SCREW_MOTOR] = ScrewSpeed;
        OriginalMotorSpd_2PPS[SCREW_MOTOR] = ScrewSpeed;
        WinderReferenceSpeed = OriginalMotorSpd_2PPS[WINDER_MOTOR];
        //screw_horizontal_speed = InternalWinderCfg.milimetersperrotation
    //     * 2. determine optimal micro-step setting
    //     * 3. calculate cart travel length from winding parameters
    //     * 4. start move of travel length
    //     * 5. register motor nBusy callback. this callback will flip between move(traverse length, hardstop) and goto(0), with handline og the coneshape and adjusting maxspeed
        temp = SYS_CLK_FREQ;
        temp *= ScrewNumberOfSteps;
        temp /= ScrewSpeed;
        ScrewRunningTime = temp;//(SYS_CLK_FREQ*InternalWinderCfg.segmentoffsetpulses)/ScrewSpeed;
        REPORT_MSG(ScrewNumberOfSteps,"Winder pre segment - ScrewNumberOfSteps");
        REPORT_MSG(ScrewRunningTime,"Winder pre segment - ScrewRunningTime");
//        MotorSetDirection (HARDWARE_MOTOR_TYPE__MOTO_SCREW, ScrewCurrentDirection);
        //ScrewDirection = 1-ScrewDirection;
        REPORT_MSG(SegmentId,"Winder pre segment - SegmentId");
        REPORT_MSG(ScrewSpeed,"Winder pre segment - ScrewSpeed");
        //MotorSetSpeedDirect(HARDWARE_MOTOR_TYPE__MOTO_SCREW,ScrewSpeed);
        ScrewsStartControlTimer ();
        ScrewControlId = AddControlCallback(Screw100msecDirectionChange, eHundredMillisecond,TemplateDataReadCBFunction,0,0,0);
        ScrewDirectionChangeCounter = 1;
        CalculationDirectionChangeCounter = 1;
        memset (WinderMotorSpeed,0,sizeof(WinderMotorSpeed) );
        WinderMotorSpeedCounter=0;
        TotalWinderSpeed = 0;
        WinderMotorSpeedRollOver=false;
        Add100 = false;
        LOG_ERROR(Add100, "Add100 = false");
   }
    PreSegmentReady(Module_Winder,ModuleDone);

    return OK;
}
uint32_t Winder_End(void)
{
    //stop screw
    ScrewNumberOfSteps = 0;
    if (ScrewControlId != 0xFF)
    {
        RemoveControlCallback(ScrewControlId,Screw100msecDirectionChange);
        ScrewControlId = 0xFF;
    }
    CurrentControlledSpeed[SCREW_MOTOR] = 0;
    ScrewsStopControlTimer();
    //move the cart to the edge so the spool can be easily replaced
    //MotorMovetoLimitSwitch (HARDWARE_MOTOR_TYPE__MOTO_SCREW,MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].directionthreadwize, 1000, GPI_LS_SCREW_RIGHT, NULL,0);
    MotorStop(HARDWARE_MOTOR_TYPE__MOTO_SCREW,Hard_Hiz);
    return OK;
}
void Winder_ScrewHomeLimitSwitchInterrupt(void)
{
    //uint32_t status;
    //handle glitch - send information to the next time that the motor stops
    if  (Winder_ScrewHoming)
    {
        MotorStop(HARDWARE_MOTOR_TYPE__MOTO_SCREW,Hard_Hiz); //stop ASAP
    }
    MotorSetDirection(HARDWARE_MOTOR_TYPE__MOTO_SCREW,MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].directionthreadwize);//make sure to move the cart out
}
void Winder_ScrewOutLimitSwitchInterrupt(void)
{
    //handle glitch - send information to the next time that the motor stops
    //uint32_t status;
    MotorSetDirection(HARDWARE_MOTOR_TYPE__MOTO_SCREW,1-MotorsCfg[HARDWARE_MOTOR_TYPE__MOTO_SCREW].directionthreadwize);//make sure to move the cart out
}

uint32_t  Screw_timerBase = TIMER3_BASE;        //Timer handle

void ScrewTimerInterruptInit(void)
{
    ROM_TimerConfigure(Screw_timerBase, TIMER_CFG_PERIODIC);   // 32 bits Timer
    ROM_TimerEnable(Screw_timerBase, TIMER_A);
    ROM_IntEnable(INT_TIMER3A);
    ROM_TimerIntEnable(Screw_timerBase, TIMER_TIMA_TIMEOUT);
}
void ScrewsStopControlTimer (void)
{
    SCREW_TimerActivated = false;
    ROM_TimerDisable(Screw_timerBase, TIMER_A);
    //ROM_IntDisable(INT_TIMER3A);
    //ROM_TimerIntDisable(Screw_timerBase, TIMER_TIMA_TIMEOUT);
}
void ScrewsStartControlTimer (void)
{
    if (SCREW_TimerActivated == true)
        return;
    SCREW_TimerActivated = true;
    //ROM_TimerConfigure(Screw_timerBase, TIMER_CFG_PERIODIC);   // 32 bits Timer
    TimerEnable(Screw_timerBase, TIMER_A);
    ROM_IntEnable(INT_TIMER3A);
    //IntPrioritySet(Screw_timerBase, 0x40);
    ROM_TimerIntEnable(Screw_timerBase, TIMER_TIMA_TIMEOUT);
    ROM_TimerLoadSet(Screw_timerBase, TIMER_A,(int)1200000/*10 millisec*/ );
    Report("ScrewsStartControlTimer direction,speed ", __FILE__,__LINE__,ScrewCurrentDirection, RpMessage, ScrewSpeed, 0);
    return;
}

int random = 0;
void ScrewTimerInterrupt(int ARG0)
{
    ROM_TimerIntClear(Screw_timerBase, TIMER_TIMA_TIMEOUT);  // Clear the timer interrupt
    ROM_IntMasterDisable();

    //Read_Screw_Encoder();
    //ScrewLocationRun[ScrewCurrentDirection] = Screw_RotEnc.Position;

    if (SCREW_TimerActivated == true)
    {
        ROM_TimerLoadSet(Screw_timerBase, TIMER_A,(int)ScrewRunningTime);
        MotorSetDirection (HARDWARE_MOTOR_TYPE__MOTO_SCREW, ScrewCurrentDirection);
        MotorSetSpeedDirect(HARDWARE_MOTOR_TYPE__MOTO_SCREW,ScrewSpeed+random);
      //  ScrewChangeCounter = 0;
      //  ScrewChangeLimit = ScrewRunningTime/12000000;
        ScrewDirectionChangeCounter++;
    }
    else
    {
        TimerDisable(Screw_timerBase, TIMER_A);
    }
    ROM_IntMasterEnable();
    Rotations+=0.01;

    return ;

}