Arduino Code:
  1. #include "AFMotor.h"
  2. #include "IRremote.h"
  3.  
  4. AF_DCMotor motor1(1);
  5. AF_DCMotor motor2(2);
  6.  
  7. int RECV_PIN = 9;
  8. IRrecv irrecv(RECV_PIN);
  9. decode_results results;
  10. int car_state;
  11.  
  12. void setup() {
  13. irrecv.enableIRIn(); // Start the receiver
  14. //turn on motor
  15. motor1.setSpeed(255);
  16. motor2.setSpeed(255);
  17.  
  18. Serial.begin(9600);
  19. Serial.print("Ready");
  20.  
  21. motor1.run(RELEASE);
  22. motor2.run(RELEASE);
  23.  
  24. }
  25.  
  26. int compare(unsigned int oldval, unsigned int newval) {
  27. if (newval < oldval * .8) {
  28. return 0;
  29. }
  30. else if (oldval < newval * .8) {
  31. return 2;
  32. }
  33. else {
  34. return 1;
  35. }
  36. }
  37.  
  38. #define FNV_PRIME_32 16777619
  39. #define FNV_BASIS_32 2166136261
  40.  
  41. unsigned long decodeHash(decode_results *results) {
  42. unsigned long hash = FNV_BASIS_32;
  43. for (int i = 1; i + 2 < results->rawlen; i++) {
  44. int value = compare(results->rawbuf[i], results->rawbuf[i + 2]);
  45. // Add value into the hash
  46. hash = (hash * FNV_PRIME_32) ^ value;
  47. }
  48. return hash;
  49. }
  50.  
  51. void loop() {
  52.  
  53. if (irrecv.decode(&results)) {
  54. unsigned long hash = decodeHash(&results);
  55.  
  56. switch (hash) {
  57. case 0xBB78C8E7: // Forward
  58. car_state = 1;
  59.  
  60. Serial.println("Forward");
  61. break;
  62. case 0x8902E8AB: // Reverse
  63. car_state = 2;
  64.  
  65. Serial.println("Reverse");
  66. break;
  67. case 0x4070260B: // Left
  68. car_state = 3;
  69.  
  70. Serial.println("Left");
  71. break;
  72. case 0x7262C647: // Right
  73. car_state = 4;
  74.  
  75. Serial.println("Right");
  76. break;
  77. case 0x20934FE3: // Stop
  78. car_state = 5;
  79.  
  80. Serial.println("Stop");
  81. break;
  82. default:
  83. Serial.print("Unknown ");
  84. Serial.println(hash, HEX);
  85. }
  86. irrecv.resume(); // Resume decoding (necessary!)
  87. }
  88. if (car_state == 1 ) {
  89. Serial.println("Forward");
  90. motor1.run(FORWARD);
  91. motor2.run(FORWARD);
  92. }
  93. if (car_state == 2 ) {
  94. Serial.println("Reverse");
  95. motor1.run(BACKWARD);
  96. motor2.run(BACKWARD);
  97. }
  98. if (car_state == 3 ) {
  99. Serial.println("Left");
  100. motor1.run(BACKWARD);
  101. motor2.run(FORWARD);
  102. delay(200);
  103. motor1.run(RELEASE);
  104. motor2.run(RELEASE);
  105. }
  106. if (car_state == 4) {
  107. Serial.println("Right");
  108. motor1.run(FORWARD);
  109. motor2.run(BACKWARD);
  110. delay(500);
  111. motor1.run(RELEASE);
  112. motor2.run(RELEASE);
  113. }
  114. if (car_state == 5) {
  115. Serial.println("Stop");
  116. motor1.run(RELEASE);
  117. motor2.run(RELEASE);
  118. }
  119. }