PWiiBot.cpp
00001 #include <WProgram.h>
00002 #include <Wire/Wire.h>
00003 #include <string.h>
00004 #include <stdio.h>
00005 #include <AFMotor/AFMotor.h>
00006
00007 AF_DCMotor motor1(1, MOTOR12_64KHZ);
00008 AF_DCMotor motor2(2, MOTOR12_64KHZ);
00009
00010
00011 uint8_t outbuf[6];
00012 char storebuf[200];
00013 int cnt = 0;
00014 int ledPin = 13;
00015
00016
00017
00018 char
00019 nunchuk_encode_byte (char x)
00020 {
00021 x = x - 0x17;
00022 x = (x ^ 0x17);
00023 return x;
00024 }
00025
00026 void receiveEvent (int howMany)
00027 {
00028
00029 while (Wire.available ())
00030 {
00031 if (howMany == 2)
00032 {
00033 int addr = Wire.receive ();
00034 int data = Wire.receive ();
00035
00036 if (addr == 1)
00037 {
00038 Serial.print("Set motor 1 dir to ");
00039 Serial.print(data);
00040 Serial.print("\r\n");
00041 motor1.run(data&(FORWARD|BACKWARD|BRAKE|RELEASE));
00042 }
00043
00044 if (addr == 2)
00045 {
00046 Serial.print("Set motor 1 to ");
00047 Serial.print(data);
00048 Serial.print("\r\n");
00049 motor1.setSpeed(data);
00050 }
00051
00052 if (addr == 3)
00053 {
00054 Serial.print("Set motor 2 dir to ");
00055 Serial.print(data);
00056 Serial.print("\r\n");
00057 motor2.run(data&(FORWARD|BACKWARD|BRAKE|RELEASE));
00058
00059 }
00060
00061 if (addr == 4)
00062 {
00063 Serial.print("Set motor 2 to ");
00064 Serial.print(data);
00065 Serial.print("\r\n");
00066 motor2.setSpeed(data);
00067 }
00068
00069 }
00070
00071 }
00072
00073 }
00074
00075 void requestEvent ()
00076 {
00077
00078 outbuf[0] = nunchuk_encode_byte (125);
00079 outbuf[1] = nunchuk_encode_byte (126);
00080 outbuf[2] = nunchuk_encode_byte (227);
00081 outbuf[3] = nunchuk_encode_byte (241);
00082 outbuf[4] = nunchuk_encode_byte (140);
00083 outbuf[5] = nunchuk_encode_byte (1);
00084
00085
00086
00087
00088 Wire.send (outbuf, 6);
00089 }
00090
00091 void
00092 setup ()
00093 {
00094 beginSerial (19200);
00095 Serial.print ("Finished setup\n");
00096 Wire.begin (0x52);
00097 Wire.onReceive (receiveEvent);
00098 Wire.onRequest (requestEvent);
00099
00100 motor1.setSpeed(0);
00101 motor2.setSpeed(0);
00102
00103 }
00104
00105
00106
00107 void
00108 loop ()
00109 {
00110 delay (100);
00111 }
00112
00113
00114
00115
00116 int main()
00117 {
00118 init();
00119 setup();
00120
00121 for(;;)
00122 loop();
00123
00124 return 0;
00125 }
00126
00127