//update analog out for all ax, set/clear enable for inverter, set/clear brake

void set_motors()
{
  byte currentmotor=0;
  for (currentmotor=0;currentmotor<max_ax;currentmotor++)
  {

    unsigned int val;

//adapt values: former 0 was max minus speed, null_speed was stop, 4095 was max plus speed  
    if (speed[currentmotor]>null_speed)  //plus
      {
        val=speed[currentmotor]-null_speed;
        mot_onP(currentmotor);
        setbrake(currentmotor,false);
      }
    else if (speed[currentmotor]<null_speed)  //minus
      {
        val=abs(speed[currentmotor]-null_speed);
        mot_onM(currentmotor);
        setbrake(currentmotor,false);
      }
    else 
      {
        val=0; //stop
        mot_off(currentmotor);
        setbrake(currentmotor,true);
      }

    Serial.println(currentmotor,val);

    digitalWrite(mux_enable,LOW);


    if ((currentmotor & 1) !=0) digitalWrite(mux_a0,HIGH); else digitalWrite(mux_a0,LOW);
    if ((currentmotor & 2) !=0) digitalWrite(mux_a1,HIGH); else digitalWrite(mux_a1,LOW);
    digitalWrite(mux_a2,LOW);

 
    for (int i=12; i>0; i--) {
      if ((val & (1 << (i-1)))>0) 
        digitalWrite(ltc_data,HIGH);
      else 
        digitalWrite(ltc_data,LOW);
    
      delayMicroseconds(1);
      digitalWrite(ltc_clk,HIGH);
      delayMicroseconds(1);
      digitalWrite(ltc_clk,LOW);
      delayMicroseconds(1);
    }  
    digitalWrite(ltc_load,LOW);
    delayMicroseconds(1);
    digitalWrite(ltc_load,HIGH);
  
    delayMicroseconds(400);

    digitalWrite(mux_enable,HIGH);

//probably not needed:
//delayMicroseconds(400);

  }

}


void mot_onP(int id)
{
 digitalWrite(startpinsP[id],true);
}
void mot_onM(int id)
{
 digitalWrite(startpinsM[id],true);
}

void mot_off(int id)
{
 digitalWrite(startpinsP[id],false);
 digitalWrite(startpinsM[id],false);
}

void setbrake(int ax, bool val)
{
  digitalWrite(brakepins[ax],not val);
  if (val) Serial.print("Setting brake on ax ");
  else Serial.print("Release brake on ax ");
  Serial.println(ax);
}