Aller au contenu


Photo
- - - - -

[Résolu] Comparaison de deux string qui ne fonctionne pas ;


  • Veuillez vous connecter pour répondre
5 réponses à ce sujet

#1 Beetlejuice

Beetlejuice

    Membre

  • Membres
  • 15 messages

Posté 12 septembre 2012 - 01:57

Salut,

Voila j'ai un petit soucis. J'ai modifier un robosapien en lui ajoutant une carte arduino 2009 .
Mon programme permet , soit de faire echo de la telecommande d'origine, soit de prendre le controle avec l'arduino.

Tout fonctionne bien, que ce soit avec la telecommande ou en envoyant des commande avec l'arduino ( interphaser entre le recepteur IR et la carte mere du robot ) .

Cependant pour mes test, je souhaite entrer des commandes dans le moniteur serie et c'est la que ça cloche :

L'entrée est bien stockée dans ma variable string , mais la condition if ne semble pas etre respectée pour que le changement de la valeur a envoyer a l' IR du robot se fasse :


if (inputString == "RSTurnRight") serialCommand= 0x80;


Avec des " serial.print " j'ai pu débugger et voir qu'effectivement la valeur de serialCommand ne change pas .

J'ai essayé :

if (inputString == "RSTurnRight")
{
serialCommand= 0x80;
}

Mais ça ne change rien ...

Quelqu'un a une idée de mon erreur ?

Voici le code complet :

int IRIn = 2;            // We will use an interrupt
int IROut= 3;            // Where the echoed command will be sent from

boolean RSEcho=true;      // Should Arduino Echo RS commands
boolean RSUsed=true;      // Has the last command been used
volatile int RSBit=9;     // Total bits of data
volatile int RSCommand;   // Single byte command from IR
int bitTime=516;          // Bit time (Theoretically 833 but 516)
                          // works for transmission and is faster
int last;                 // Previous command from IR
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
int serialCommand(0xEF); // Command sent via serial


void setup()                    
{
  pinMode(IRIn, INPUT);     
  pinMode(IROut, OUTPUT);
  pinMode(10,OUTPUT);
  digitalWrite(IROut,HIGH);
  attachInterrupt(0,RSReadCommand,RISING);
  last=0xEF; // Set last command as " noOp "
  Serial.begin(115200);
}

// Receive a bit at a time.
void RSReadCommand() 
{
  delayMicroseconds(833+208);  // about 1 1/4 bit times
  int bit=digitalRead(IRIn); 
  if (RSBit==9) 
  { // Must be start of new command
    RSCommand=0;
    RSBit=0;
    RSUsed=true;
  }
  if (RSBit<8) 
  { 
    RSCommand<<=1;
    RSCommand|=bit;
  }
  RSBit++;
  if (RSBit==9) RSUsed=false;
}

// send the whole 8 bits
void RSSendCommand(int command) {
  digitalWrite(IROut,LOW);
  delayMicroseconds(8*bitTime);
  for (int i=0;i<8;i++) {
    digitalWrite(IROut,HIGH);  
    delayMicroseconds(bitTime);
    if ((command & 128) !=0) delayMicroseconds(3*bitTime);
    digitalWrite(IROut,LOW);
    delayMicroseconds(bitTime);
    command <<= 1;
  }
  digitalWrite(IROut,HIGH);
  delay(250); // Give a 1/4 sec before next
}

void loop() 
{ 
  if (!RSUsed) 
  {
    if (RSCommand==0x8E && last==0x8E) 
    {
      RSEcho=!RSEcho;
    }
    last=RSCommand;
    // print code received from the remote
    Serial.print("IR Code : ");
    Serial.println(RSCommand);
    if (!RSEcho)
    {
      digitalWrite(10,HIGH);  // Turn on LED let us know we have control our wedge                                         
      Serial.println("Arduino control ON ");
    }

    else 
    {
      digitalWrite(10,LOW);   // No longer in control
      Serial.println("Arduino control OFF ");
      RSSendCommand(RSCommand);
    }

    RSUsed=true;
  }


  while (Serial.available()) 
  {
    // get the new byte:
    char inChar = (char)Serial.read(); 
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') 
    {
      Serial.print ("inputString value: " );
      Serial.println (inputString);

      if (inputString == "RSTurnRight") serialCommand= 0x80;
      if (inputString == "RSRightArmUp") serialCommand= 0x81;
      if (inputString == "RSRightArmOut") serialCommand= 0x82;
      if (inputString == "RSTiltBodyRight") serialCommand= 0x83;
      if (inputString == "RSRightArmDown") serialCommand= 0x84;
      if (inputString == "RSRightArmIn") serialCommand= 0x85;
      if (inputString == "RSWalkForward") serialCommand= 0x86;
      if (inputString == "RSWalkBackward") serialCommand= 0x87;
      if (inputString == "RSTurnLeft") serialCommand= 0x88;
      if (inputString == "RSLeftArmUp") serialCommand= 0x89;
      if (inputString == "RSLeftArmOut") serialCommand= 0x8A;
      if (inputString == "RSTiltBodyLeft") serialCommand= 0x8B;
      if (inputString == "RSLeftArmDown") serialCommand= 0x8C;
      if (inputString == "RSLeftArmIn") serialCommand= 0x8D;
      if (inputString == "RSStop") serialCommand= 0x8E;
      if (inputString == "RSWakeUp") serialCommand= 0xB1;
      if (inputString == "RSBurp") serialCommand= 0xC2;
      if (inputString == "RSRightHandStrike") serialCommand= 0xC0;
      if (inputString == "RSNoOp") serialCommand= 0xEF;
      Serial.print (" Value sent : " );
      Serial.println (serialCommand,HEX);

      RSSendCommand(serialCommand);
      Serial.println (" Command sent to robosapien " );
      // clear the string:
      inputString = "";
    }
  }
}



#2 R1D1

R1D1

    Modérateur et Membre passionné

  • Modérateur
  • PipPipPipPipPip
  • 1 211 messages
  • Gender:Male
  • Location:Autriche

Posté 12 septembre 2012 - 02:42

Salut,

Vire tes conditions et appelle la fonction d'envoi avec une valeur en dur. Si ça marche, le problème ne vient pas de là.

Utiliser une String pour faire du réseau et de la transmission de packet, ça me semble bizarre ... Et le résultat de "inputString +=" assez aléatoire ... Regarde les méthodes associées à la classe pour ça, ça sera plus propre.
D'ailleurs, pourquoi passer par un "RSblabla" ? Quelle est l'information récupérée envoyée par la télécommande ? N'y a-t-il pas une valeur en hexa (sous forme d'octet) dans la trame plutôt qu'une chaîne de caractères ?

En général, le switch case ne fonctionne pas sur autre chose que des char ou des int, mais je n'ai rien vu de précisé pour Arduino. S'il fonctionne, change tes if if if if if ...

Si tu nous mets une sortie console, ça peut être bien aussi.
R1D1 - Calculo Sed Ergo Sum -- en ce moment, M.A.R.C.E.L.
Avatar tiré du site bottlebot

#3 Beetlejuice

Beetlejuice

    Membre

  • Membres
  • 15 messages

Posté 12 septembre 2012 - 05:27

Merci pour tes conseils :yes:

J'ai déja essayé avec la une valeur directe et cela fonctionne bien, par exemple avec un capteur de distance IR, le robot reçois bien les ordre d'arret, rotation, etc ..

J'avait fait un essai avec des switch / case , mais effectivement, il attends un int ou un char . J'aurai bien aimé faire un programme plus propre qu'avec tous ces if .


Le résultat de "inputString +=" , est correct, les lignes contenant les " serial.print " m'affiche dans la console la valeur de la variable inputString et celle-ci correspond bien au mot que j'ai envoyé via la console . J'utilise cette façon de faire car la liaison série envoie le mot caractère par caractère .

Je ne suis pas sur l'ordi avec lequel je programme pour l'arduino, je posterai ce que dit la console tout a l'heure .

J'ai oublié de préciser que le compilateur ne me retourne aucune erreurs . Ce qui est étrange c'est que cela fonctionnait a un moment ...

#4 thermo_nono

thermo_nono

    Membre chevronné

  • Membres
  • PipPipPipPip
  • 825 messages

Posté 12 septembre 2012 - 06:37

Si tu veux virer la liste de "if", tu peux créer deux tableaux :
le premier contiendra : tabl01 = ["RSTurnRight", "RSRightArmUp", "RSRightArmOut"... etc...]
le second contiendra : tabl02 = ["0x80", "0x81", "0x82"... etc...]

puis, à la place de la liste de "if" tu met une boucle :
for (int i=0;i<=18;i++) {
if (inputString == tabl01[i]) serialCommand=tabl02[i];
}

(il existe une commande "for each" ou un truc dans le genre qui te permettrait de rajouter ou supprimer des commandes encore plus facilement)

#5 Beetlejuice

Beetlejuice

    Membre

  • Membres
  • 15 messages

Posté 13 septembre 2012 - 08:01

Ah ben oui !! merci, j'y avait même pas pensé :ok:

#6 Beetlejuice

Beetlejuice

    Membre

  • Membres
  • 15 messages

Posté 13 septembre 2012 - 12:16

Problème résolu :lol:

En fait le retour de chariot était ajouté a la commande envoyée, donc forcèment ça ne marchait pas !

Pour être clair, par exemple mon if testait si RSBurp\n était pareil que RSBurp

Il a donc suffit de sortir " inputString += inChar; " de la boucle while .


Voila le code modifié et fonctionnel si jamais quelqu'un en a besoin .

int IRIn = 2;            // We will use an interrupt
int IROut= 3;            // Where the echoed command will be sent from

boolean RSEcho=true;      // Should Arduino Echo RS commands
boolean RSUsed=true;      // Has the last command been used
volatile int RSBit=9;     // Total bits of data
volatile int RSCommand;   // Single byte command from IR
int bitTime=516;          // Bit time (Theoretically 833 but 516)
// works for transmission and is faster
int last;                 // Previous command from IR
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
int serialCommand(0xEF); // Command sent via serial

// Array for commands and Ir codes
String commandName[19] = {
  "RSTurnRight", "RSRightArmUp", "RSRightArmOut", "RSTiltBodyRight", "RSRightArmDown", 
  "RSRightArmIn", "RSWalkForward", "RSWalkBackward", "RSTurnLeft", "RSLeftArmUp", 
  "RSLeftArmOut", "RSTiltBodyLeft", "RSLeftArmDown", "RSLeftArmIn", "RSStop", 
  "RSWakeUp", "RSBurp", 
  "RSRightHandStrike", "RSNoOp"
};

int commandIrCode[19] = {
  0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 
  0x8B, 0x8C, 0x8D, 0x8E, 0xB1, 0xC2, 0xC0, 0xEF
};

void setup()                    
{
  pinMode(IRIn, INPUT);     
  pinMode(IROut, OUTPUT);
  pinMode(10,OUTPUT);
  digitalWrite(IROut,HIGH);
  attachInterrupt(0,RSReadCommand,RISING);
  last=0xEF; // Set last command as " noOp "
  Serial.begin(115200);
}

// Receive a bit at a time.
void RSReadCommand() 
{
  delayMicroseconds(833+208);  // about 1 1/4 bit times
  int bit=digitalRead(IRIn); 
  if (RSBit==9) 
  { // Must be start of new command
    RSCommand=0;
    RSBit=0;
    RSUsed=true;
  }
  if (RSBit<8) 
  { 
    RSCommand<<=1;
    RSCommand|=bit;
  }
  RSBit++;
  if (RSBit==9) RSUsed=false;
}

// send the whole 8 bits
void RSSendCommand(int command) {
  digitalWrite(IROut,LOW);
  delayMicroseconds(8*bitTime);
  for (int i=0;i<8;i++) {
    digitalWrite(IROut,HIGH);  
    delayMicroseconds(bitTime);
    if ((command & 128) !=0) delayMicroseconds(3*bitTime);
    digitalWrite(IROut,LOW);
    delayMicroseconds(bitTime);
    command <<= 1;
  }
  digitalWrite(IROut,HIGH);
  delay(250); // Give a 1/4 sec before next
}

void loop() 
{ 
  if (!RSUsed) 
  {
    if (RSCommand==0x8E && last==0x8E) 
    {
      RSEcho=!RSEcho;
    }
    last=RSCommand;
    // print code received from the remote
    Serial.print("IR Code : ");
    Serial.println(RSCommand);
    if (!RSEcho)
    {
      digitalWrite(10,HIGH);  // Turn on LED let us know we have control our wedge                                         
      Serial.println("Arduino control ON ");
    }

    else 
    {
      digitalWrite(10,LOW);   // No longer in control
      Serial.println("Arduino control OFF ");
      RSSendCommand(RSCommand);
    }

    RSUsed=true;
  }


  while (Serial.available()) 
  {
    // get the new byte:
    char inChar = (char)Serial.read(); 
   
    // if the incoming character is a newline
    
    if (inChar == '\n') 
    {
      Serial.print ("inputString value: " );
      Serial.println (inputString);
      // Test if the serial sent command exist and if ok, give the corresponding Ir code to " commandIr "
      for (int i=0;i<=18;i++) {
        if (inputString == commandName[i]) serialCommand=commandIrCode[i];
      }
      Serial.print (" Value sent : " );
      Serial.println (serialCommand,HEX);

      RSSendCommand(serialCommand);
      Serial.println (" Command sent to robosapien " );
      // clear the string:
      inputString = "";
      // add it to the inputString:
    }
    else inputString += inChar;

  }
}









0 utilisateur(s) li(sen)t ce sujet

0 members, 0 guests, 0 anonymous users