Commander votre Robot à l’aide d’un Wii Nunchuck (et un Arduino) (3 / 4 étapes)

Étape 3: programmation

The Wii Nunchuck est maintenant connecté au port i2c de l’Arduino. Pour ceux d'entre vous (moi y compris) qui ne comprennent pas vraiment ce que signifie ne vous inquiétez pas, rassurez-vous, juste, c’est une bonne chose. Si vous souhaitez en savoir plus des détails nitty gritty qu’ils se trouvent (ici)

(un grand Merci à Tchad à windmeadow.com pour faire de la recherche et l’écriture très facilement compris Arduino code pour interagir avec le nunchuck Wii, le programme ci-dessous inclut son code pratiquement inchangé).

Ce qu’il fait

  • Le programme par défaut pour le contrôle à l’aide de la manette wiimote. Si vous poussez le manche vers l’avant votre robot ira vers l’avant, marche arrière, en arrière et ainsi de suite.
  • Si vous maintenez enfoncée la touche « Z » (gros celui sur le front). Votre robot va maintenant passer selon l’inclinaison de la nunchuck. Inclinaison vers l’avant pour aller de l’avant...
  • Enfin, si cela ne fonctionne pas tout à fait le programme enverra l’état des boutons de la Wiimote, manette de jeu et accéléromètres, chaque seconde sur le port USB de l’Arduino. (il suffit d’ouvrir la fenêtre de débogage à 9600 pour voir ces données)

Pour ceux qui souhaitent simplement obtenir ça va.

Copie et collage

  • Copiez le code de l’Arduino par en dessous
  • Collez-le dans l’environnement de développement Arduino.
  • Télécharger et commencer à jouer

En utilisant le Code dans votre propre programme

  • Tout d’abord initialiser le nunchuck en appelant nunchuck_init () ;
  • Ensuite, chaque fois que vous souhaitez mettre à jour les valeurs de la nunchuck dans votre croquis appellent readNunchuck() ;
  • À côté de l’accès directement les valeurs appellent getNunValue(Variable Constant) ; (ex. YAXIS)
  • Enfin si vous souhaitez utiliser l’accéléromètre mais ont il réduit à un certain nombre de Gs (ie. 1 g = 1 force de gravité). vous pouvez appeler getXGs() ; getYGs() ; ou getZGs() ;

Annexe 1 - _SERB_WiiNunchuckControl.pde

 //START OF NUNCHUCK PREAMBLE - For more in depth information please visit the original source of this code http://www.windmeadow.com/node/42 //------------------------------------------------- /* * Wiring Details * white - ground * red - 3.3+v - 5 volts seems to work * green - data - Analog 4 * yellow - clock - Analog 5 */ #include #include #undef int #include uint8_t outbuf[6]; // array to store arduino output int cnt = 0; // counter used for nunchuck comunication int ledPin = 13; int nunchuckValues[] = {0,0,0,0,0,0,0,0,0,0}; //An array to store the nuncheck values /* * The index of each value within the nunchuckValues[] array * ie. XSTICK value is stored at nunchuckValues[XSTICK] (0) */ #define XSTICK 0 //The joystick values #define YSTICK 1 #define XAXIS 2 //The three accelerometer values #define YAXIS 3 #define ZAXIS 4 #define ZBUTTON 5 //Front button values (0 when pressed) #define CBUTTON 6 #define XAXISDELTA 7 //Change in accelerometer data from last read; #define YAXISDELTA 8 #define ZAXISDELTA 9 //Nunchuck G calculating Constants /* * For scaling the raw values from the nunchuck into G values * Details on callibration and the maths can be found at * http://www.wiili.org/index.php/Motion_analysis (Copied from http://www.wiili.org/index.php/Motion_analysis) Zero Points x_0 = (x_1 + x_2) / 2\,y_0 = (y_1 + y_3) / 2\,z_0 = (z_2 + z_3) / 2\, One G points x = \frac{x_{raw} - x_0}{x_3 - x_0}y = \frac{y_{raw} - y_0}{y_2 - y_0}z = \frac{z_{raw} - z_0}{z_1 - z_0} */ /* Not all of these are used and could be deleted (kept to make interpretting math's * Easier 0-Zero G Value 1-Value when laying on table 2-Value when resting on nose * 3-Value when resting on side (left side up) */ #define X0 500 #define X1 500 #define X2 500 #define X3 711 #define Y0 465 #define Y1 481 #define Y2 621 #define Y3 449 #define Z0 578 #define Z1 785 #define Z2 575 #define Z3 582 //END OF NUNCHUCK PREAMBLE - For more in depth information please visit the original source of this code http://www.windmeadow.com/node/42 //------------------------------------------------------ //-------------------------------------------------------------------------- // START OF ARDUINO CONTROLLED SERVO ROBOT (SERB) PREAMBLE #include #define LEFTSERVOPIN 10 #define RIGHTSERVOPIN 9 #define MAXSPEED 10 //due to the way continuous rotation servos work maximum speed is reached at a much lower value than 90 (this value will change depending on your servos) (for Parallax servos) Servo leftServo; Servo rightServo; int leftSpeed = 100; //sets the speed of the robot (left servos) //a percentage between -MAXSPEED and MAXSPEED int rightSpeed = 100; //sets the speed of the robot (both servos) //a percentage between -MAXSPEED and MAXSPEED int speed = 100; //used for simple control (goForward, goBackward, goLeft, and goRight //a percentage between 0 and MAXSPEED // END OF ARDUINO CONTROLLED SERVO ROBOT (SERB) PREAMBLE //-------------------------------------------------------------------------- long lastPrint; //a long variable to store the time the wiimote state was last printed #define PRINTINTERVAL 1000 //the number of milliseconds between outputting the nunchuck state over the usb port #define DEADBAND 20 //A percentage away from center that is interpretted as still being zero void setup(){ Serial.begin(9600); //Starts the serial port (used for debuging however makes servos jumpy) nunchuck_init (); // send the nunchuck initilization handshake serbSetup(); // adds the servos and prepares all SERB related variables lastPrint = millis(); } void loop(){ readNunchuck(); //Reads the current state of the nunchucks buttons and accelerometers if(!getNunValue(ZBUTTON)){ moveWiiAcelerometer(); //moves the wii deoending on the nunchucks acceleration values }else{ moveWiiJoystick(); } if((millis() - lastPrint) > PRINTINTERVAL){ //If a second has passed since last printing nunchuck values print them printData(); //print nunchuck values Serial.println(); //add an enter lastPrint = millis(); //store current time as lastPrint } } void moveWiiAcelerometer(){ moveDifferential(getYGs() * (float)100,getXGs()*(float)100); } void moveWiiJoystick(){ moveDifferential(map(getNunValue(YSTICK),30,220,-100,100),map(getNunValue(XSTICK),30,220,-100,100)); } //Takes in a speed and a direction input (like a joystick) and translates it to speed commands void moveDifferential(int speed1, int direction1){ speed1 = deadBandFilter(speed1); direction1 = deadBandFilter(direction1); setSpeedLeft(speed1 + direction1); setSpeedRight(speed1 - direction1); } int deadBandFilter(int value){ if(value > -DEADBAND && value < DEADBAND){value = 0;} else{ if(value > 0){value = value - DEADBAND * 100 / (100-DEADBAND);} else{value = value + DEADBAND * 100 / (100-DEADBAND);} } return value; } //START OF NUNCHUCK ROUTINES //------------------------------------------------------------------------------------------------------- //Calculates and returns the xAxis acceleration in Gs float getXGs(){ return ((float)getNunValue(XAXIS) - X0) / (X3 - X0); } //Calculates and returns the yAxis acceleration in Gs float getYGs(){ return ((float)getNunValue(YAXIS) - Y0) / (Y2 - Y0); } //Calculates and returns the zAxis acceleration in Gs float getZGs(){ return ((float)getNunValue(YAXIS) - Z0) / (Z1 - Z0); } //START OF NUNCHUCK Reading CODE - For more in depth information please visit the original source //of this code http://www.windmeadow.com/node/42 //--------------------------------------------------------------- void readNunchuck(){ Wire.requestFrom (0x52, 6); // request data from nunchuck while (Wire.available ()) { outbuf[cnt] = nunchuk_decode_byte (Wire.receive ()); // receive byte as an integer digitalWrite (ledPin, HIGH); // sets the LED on cnt++; } // If we recieved the 6 bytes, then go print them if (cnt >= 5) { nunchuckValues[XSTICK] = outbuf[0]; nunchuckValues[YSTICK] = outbuf[1]; int tempNun_xAxis = outbuf[2] * 2 * 2; int tempNun_yAxis = outbuf[3] * 2 * 2; int tempNun_zAxis = outbuf[4] * 2 * 2; nunchuckValues[ZBUTTON] = 0; nunchuckValues[CBUTTON] = 0; // byte outbuf[5] contains bits for z and c buttons // it also contains the least significant bits for the accelerometer data // so we have to check each bit of byte outbuf[5] if ((outbuf[5] >> 0) & 1) { nunchuckValues[ZBUTTON] = 1; } //checking if Z button is pressed (0=pressed 1=unpressed) if ((outbuf[5] >> 1) & 1) { nunchuckValues[CBUTTON] = 1; } //checking if C button is pressed (0=pressed 1=unpressed) if ((outbuf[5] >> 2) & 1) { tempNun_xAxis += 2; } //adding second least significant bit to x_axis if ((outbuf[5] >> 3) & 1) { tempNun_xAxis += 1; } //adding least significant bit to x_axis if ((outbuf[5] >> 4) & 1) { tempNun_yAxis += 2; } //adding second least significant bit to y_axis if ((outbuf[5] >> 5) & 1) { tempNun_yAxis += 1; } //adding least significant bit to x_axis if ((outbuf[5] >> 6) & 1) { tempNun_zAxis += 2; } //adding second least significant bit to z_axis if ((outbuf[5] >> 7) & 1) { tempNun_zAxis += 1; } ////adding least significant bit to x_axis nunchuckValues[XAXISDELTA] = tempNun_xAxis - nunchuckValues[XAXIS]; nunchuckValues[XAXIS] = tempNun_xAxis; nunchuckValues[YAXISDELTA] = tempNun_yAxis - nunchuckValues[YAXIS]; nunchuckValues[YAXIS] = tempNun_yAxis; nunchuckValues[ZAXISDELTA] = tempNun_zAxis - nunchuckValues[ZAXIS]; nunchuckValues[ZAXIS] = tempNun_zAxis; } cnt = 0; send_zero (); // send the request for next bytes} int getNunValue(int valueIndex){ return nunchuckValues[valueIndex];} void nunchuck_init (){ Wire.begin (); // join i2c bus with address 0x52 Wire.beginTransmission (0x52); // transmit to device 0x52 Wire.send (0x40); // sends memory address Wire.send (0x00); // sends sent a zero. Wire.endTransmission (); // stop transmitting} void send_zero () { Wire.beginTransmission (0x52); // transmit to device 0x52 Wire.send (0x00); // sends one byte Wire.endTransmission (); // stop transmitting} // Encode data to format that most wiimote drivers except// only needed if you use one of the regular wiimote driverschar nunchuk_decode_byte (char x) { x = (x ^ 0x17) + 0x17; return x;} //END OF NUNCHUCK CODE - For more in depth information please visit the //original source of this code http://www.windmeadow.com/node/42 //--------------------------------------------------------------- //------------------------------------------------------------------------//START OF ARDUINO CONTROLLED SERVO ROBOT (SERB) ROUTINES /* * sets up your arduino to address your SERB using the included routines*/void serbSetup(){ setSpeed(speed); pinMode(LEFTSERVOPIN, OUTPUT); //sets the left servo signal pin //to output pinMode(RIGHTSERVOPIN, OUTPUT); //sets the right servo signal pin //to output leftServo.attach(LEFTSERVOPIN); //attaches left servo rightServo.attach(RIGHTSERVOPIN); //attaches right servo goStop();} /* * sets the speed of the robot between 0-(stopped) and 100-(full speed) * NOTE: speed will not change the current speed you must change speed * then call one of the go methods before changes occur.*/ void setSpeed(int newSpeed){ if(newSpeed >= 100) {newSpeed = 100;} //if speed is greater than 100 //make it 100 if(newSpeed <= 0) {newSpeed = 0;} //if speed is less than 0 make //it 0 speed = newSpeed * MAXSPEED / 100; //scales the speed to be //between 0 and MAXSPEED} /* * sets the speed of the robots rightServo between -100-(reversed) and 100-(forward) * NOTE: calls to this routine will take effect imediatly*/ void setSpeedRight(int newSpeed){ if(newSpeed >= 100) {newSpeed = 100;} //if speed is greater than 100 //make it 100 if(newSpeed <= -100) {newSpeed = -100;} //if speed is less than -100 make //it -100 rightSpeed = newSpeed * MAXSPEED / 100; //scales the speed to be //between -MAXSPEED and MAXSPEED rightServo.write(90 - rightSpeed); //sends the new value to the servo} /* * sets the speed of the robots leftServo between -100-(reversed) and 100-(forward) * NOTE: calls to this routine will take effect imediatly*/ void setSpeedLeft(int newSpeed){ if(newSpeed >= 100) {newSpeed = 100;} //if speed is greater than 100 //make it 100 if(newSpeed <= -100) {newSpeed = -100;} //if speed is less than -100 make //it -100 leftSpeed = newSpeed * MAXSPEED / 100; //scales the speed to be //between -MAXSPEED and MAXSPEED leftServo.write(90 + leftSpeed); //sends the new value to the servo} /* * sends the robot forwards */void goForward(){ leftServo.write(90 + speed); rightServo.write(90 - speed);} /* * sends the robot backwards */void goBackward(){ leftServo.write(90 - speed); rightServo.write(90 + speed);} /* * sends the robot right */void goRight(){ leftServo.write(90 + speed); rightServo.write(90 + speed);} /* * sends the robot left */void goLeft(){ leftServo.write(90 - speed); rightServo.write(90 - speed);} /* * stops the robot */void goStop(){ leftServo.write(90); rightServo.write(90);} //END OF ARDUINO CONTROLLED SERVO ROBOT (SERB) ROUTINES//--------------------------------------------------------------------------- //START OF PRINT ROUTINES (can delete if not using)//--------------------------------------------------------------- //Prints the Nunchucks last read data (must call NUN_readNunchuck(); before callingvoid printData(){ Serial.print("XJoy= ");Serial.print (getNunValue(XSTICK), DEC); Serial.print ("\t"); Serial.print("YJoy= ");Serial.print (getNunValue(YSTICK), DEC); Serial.print ("\t"); Serial.print("XGs= ");Serial.print (getXGs() * 1000, DEC); Serial.print ("\t"); Serial.print("YGs= ");Serial.print (getYGs() * 1000, DEC); Serial.print ("\t"); Serial.print("ZGs= ");Serial.print (getZGs() * 1000, DEC); Serial.print ("\t"); Serial.print("ZBut= ");Serial.print (getNunValue(ZBUTTON), DEC); Serial.print ("\t"); Serial.print("YBut= ");Serial.print (getNunValue(CBUTTON), DEC); Serial.print ("\t");} //END OF PRINT ROUTINES//-------------------------------------------------------------------- 

Articles Liés

Commander votre Robot à l’aide de téléphone portable

Commander votre Robot à l’aide de téléphone portable

CE tutoriel complet est également disponible sur mon site WebBonjour monde dans ce post je vais vous montrer comment faire pour contrôler le robot à l'aide de téléphone portable. Contrôler un robot à l'aide de téléphone portable n'est pas si compliqu
Construisez votre Robot Internet sous contrôle vidéo-Streaming avec Arduino et Raspberry Pi

Construisez votre Robot Internet sous contrôle vidéo-Streaming avec Arduino et Raspberry Pi

< le Instructable et le code sont prêts. Profitez ! Laissez un commentaire avec vous vos commentaires! >Je suis (aka LiquidCrystalDisplay / Itay), un élève de 14 ans d'Israël par l'apprentissage dans l'école secondaire Junior Max Shein avancées des
Maison bras robotisé à l’aide de pièces Standard en utilisant Arduino et un traitement GUI

Maison bras robotisé à l’aide de pièces Standard en utilisant Arduino et un traitement GUI

J'ai récemment pris sa retraite et une des choses que je me suis promis était que lorsque j'ai prenaient leur retraite j'allais terminer tous les projets que j'ai dû courir dans ma tête depuis que je suis un adolescent. C'est une cinquantaine d'année
Projet Robot Bug - avec wii nunchuck

Projet Robot Bug - avec wii nunchuck

Projet Robot BugCe que le robot doit avoir :Objet en mouvement, licht ledLe matériel du robot doit se composer de 3 types différents de matérielLes imprimantes 3D sont nécessaires dans le processus de réalisation de ce projet.Étape 1: Composants Proj
Ajout d’un visage et housses à votre Robot

Ajout d’un visage et housses à votre Robot

Ce Instructable est sur l'ajout d'un visage à votre robot avec des yeux de LED. Construire le robot ici.Étape 1: Matériaux et outilsVous aurez besoin de ces matériaux pour ce projet :(1) robot(2) les résistances 200ohm(2) de 5 MM LED(3) pieds de fil
Wii Nunchuck comme contrôleur généraliste via carte Arduino

Wii Nunchuck comme contrôleur généraliste via carte Arduino

Rappel des faits :J'ai fait une planche à roulettes électrique autonome qui est orientée à l'aide d'un Wii Nunchuck en utilisant le levier de commande de pouce sur le dessus ou en l'inclinant gauche ou droite, selon qui des deux boutons à l'extrémité
ESP8266 et Visuino : télécommande WiFi Smart voiture Robot avec Wii Nunchuck

ESP8266 et Visuino : télécommande WiFi Smart voiture Robot avec Wii Nunchuck

Que voiture smart définit lorsqu'il est combiné avec Les Modules des pilotes automobile L298N, offre une des façons plus faciles à rendre les voitures robot. J'ai déjà fait une Instructable sur comment vous pouvez contrôler la voiture Smart avec Ardu
COMMANDE manuelle / autonome ROBOT (à l’aide de la TECHNIQUE de FUSION de capteur)

COMMANDE manuelle / autonome ROBOT (à l’aide de la TECHNIQUE de FUSION de capteur)

DTMF ou Dual Tone Multiple Frequency est chouette petite voie de contrôle des machines à votre téléphone portable. Cette instructable vous, lecteur doux montre comment faire un moins cher que la saleté DTMF contrôlée robot qui peut également fonction
Comment faire pour extraire des jeux Wii à votre ordinateur à l’aide d’une clé usb.

Comment faire pour extraire des jeux Wii à votre ordinateur à l’aide d’une clé usb.

Cette instructable va vous montrer comment ripper une copie d'un jeu Wii à votre ordinateur en utilisant seulement une clé USB et votre Wii et comment compresser pour le stockage.Vous aurez besoin de plusieurs choses pour y arriver :Configuration mat
Ajouter Internet-contrôle Pi framboise du robot à l’aide de Runmyrobot.com

Ajouter Internet-contrôle Pi framboise du robot à l’aide de Runmyrobot.com

Comment partager votre Robot avec le monde et laisser les autres gens à jouer avec lui à l'aide de runmyrobot.com. Ce site est beta test, mais cela devrait fonctionner. Si vous avez des questions, faites-nous savoir en les affichant sur la page du si
Guide étape par étape pour la commande de robot Micro magicien (compatible Arduino)

Guide étape par étape pour la commande de robot Micro magicien (compatible Arduino)

le Magicien Micro de DAGU est un contrôleur compatible Arduino low cost, conçu spécialement pour les débutants qui veulent construire un petit robot. Le jury a un certain nombre d'accessoires utiles, construite en sorte que dans la plupart des cas le
Créer un simulateur robotique à l’aide de traitement

Créer un simulateur robotique à l’aide de traitement

Si vous commencez à écrire du code pour un robot, il est inévitable de passer par un certain nombre d'itérations jusqu'à ce qu'il fonctionne comme prévu. Arduino déjà c'est plus facile mais surtout avec les robots marche complexes, il peut être une t
GOduino III - la commande de robot Arduino-basé de maquette facile

GOduino III - la commande de robot Arduino-basé de maquette facile

mises à jour16 novembre 2012 en vedette sur DangerousPrototypes.com http://goo.gl/N4DIC3 octobre 2012: J'ai conçu un adaptateur PCB pour aider position IR & 90 degrés de capteurs à ultrasons pour planche à pain pour soutenir des projets de robot GOdu
Pleo télécommande avec Wii Nunchuck

Pleo télécommande avec Wii Nunchuck

décrit cette instructable comment télécommande Pleo (un dinosaure robot amical : http://www.pleoworld.com) avec des gestes en utilisant une configuration de format de poche. Vous pouvez étendre la majeure partie de cette instructable pour contrôler d