Advertisement
JonD1988

ESP32CarRobotWebServer

Nov 18th, 2022
1,638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 15.20 KB | None | 0 0
  1. //Rev 4 Was Developed on 11/18/2022 by Jonathan DeWitt - Rev 0 thru Rev 3 all were partially completed versions of Rev 4.  They were saved as developement points so that progress was not lost along the way of developing Rev 4. Open the WiFi in your phone and connect to the ssid named in this code using the password named in this code.  Then go to your web browser and enter the ip address 192.168.4.1.  You should then be able to control the shown buttons.  If your web browser hangs then go back to the WiFi on your phone, forget the ssid named in this sketch.  Then reconnect to it.  When it asks if you want to remain connected even though there is no internet say yes and select don't ask the question again.  Even then you'll still probably have to forget and reconnect to that ssid.
  2.  
  3. #include <WiFi.h>
  4. #include <AsyncTCP.h>
  5. #include <ESPAsyncWebServer.h>
  6. #include <SparkFun_TB6612.h> //Library used to control TB6612FNG - See Reference 1
  7. #include <FastLED.h> //Needed to control LEDs - In this case WS2812B
  8.  
  9. #define AIN1 19 //ESP32 GPIO 19 Connected to TB6612FNG Pin AIN1
  10. #define BIN1 17 //ESP32 GPIO 17 Connected to TB6612FNG Pin BIN1
  11. #define AIN2 21 //ESP32 GPIO 21 Connected to TB6612FNG Pin AIN2
  12. #define BIN2 16 //ESP32 GPIO 16 Connected to TB6612FNG Pin BIN2
  13. #define PWMA 22 //ESP32 GPIO 22 Connected to TB6612FNG Pin PWMA
  14. #define PWMB 4 //ESP32 GPIO 4 Connected to TB6612FNG Pin PWMB
  15. #define STBY 18 //ESP32 GPIO 18 Connected to TB6612FNG Pin STBY
  16. #define horn_Buzz 13 //ESP32 GPIO 13 Connected to Horn Buzzer Red Wire
  17.  
  18. //#ifdef ESP_H //See Reference 7
  19. #define PWM1_Ch    0
  20. #define PWM1_Res   8
  21. void tone ( int tonePin, int toneFreq ) {
  22.   Serial.print( "my tone called for pin " );
  23.   Serial.print( tonePin );
  24.   Serial.print( " with frequency " );
  25.   Serial.println( toneFreq );
  26.   ledcSetup( PWM1_Ch, toneFreq, PWM1_Res );
  27.   ledcWrite( PWM1_Ch, 127 ); // 50% duty cycle
  28. }
  29. void noTone( int tonePin ) {
  30.   Serial.print( "my noTone called for pin " );
  31.   Serial.println( tonePin );
  32.   ledcWrite( PWM1_Ch, 0 ); // 0% duty cycle
  33. }
  34.  
  35. FASTLED_USING_NAMESPACE //From DemoReel100Rev4.ino Used for LED Control
  36. #define LED_TYPE    WS2812
  37. #define COLOR_ORDER GRB //From DemoReel100Rev4.ino Used for LED Control
  38. #define NUM_LEDS    4 //From DemoReel100Rev4.ino Used for LED Control
  39. CRGB leds[NUM_LEDS]; //Defins an leds array with NUM_LEDS number of elements i.e. LED 1 is accessed through leds[0], LED2 is accessed through leds[1] etc.
  40. #define BRIGHTNESS 96 //From DemoReel100Rev4.ino Used for LED Strip Control
  41. #define FRAMES_PER_SECOND 120 //From DemoReel100Rev4.ino Used for LED Strip Control
  42. #define DATA_PIN 23 //LED strip data pin connected to ESP32 GPIO 23
  43.  
  44. char command;
  45. int speedCar = 100; // Variable to store the PWM speed of the car 50 - 255.
  46. int speed_Coeff = 4;
  47.  
  48. //These constants are used to allow you to make your motor configuration line up with function names like forward.  Value can be 1 or -1
  49. const int offsetA = 1; //From Reference 4
  50. const int offsetB = 1; //From Reference 4
  51.  
  52. //Initializing motors.  The library will allow you to initialize as many motors as you have memory for.  If you are using functions like forward
  53. // that take 2 motors as arguements you can either write new functions or call the function more than once.
  54. Motor motor1 = Motor(AIN1, AIN2, PWMA, offsetA, STBY); //From Reference 4
  55. Motor motor2 = Motor(BIN1, BIN2, PWMB, offsetB, STBY); //From Reference 4
  56.  
  57. int lightFState=0, lightBState=0; //Stores the state of the front and back lights
  58.  
  59. // Replace with your network credentials
  60. const char* ssid = "JonDeWittsESP32WiFiCar1";
  61. const char* password = "123456789";
  62.  
  63. const char* PARAM_INPUT_1 = "output";
  64. const char* PARAM_INPUT_2 = "state";
  65.  
  66. // Create AsyncWebServer object on port 80
  67. AsyncWebServer server(80);
  68.  
  69. const char index_html[] PROGMEM = R"rawliteral(
  70. <!DOCTYPE HTML><html>
  71. <head>
  72.  <title>"ESP32 WiFi Car"</title>
  73.  <meta name="viewport" content="width=device-width, initial-scale=1">
  74.  <link rel="icon" href="data:,">
  75.  <style>
  76.    html {font-family: Arial; display: inline-block; text-align: center;}
  77.    h2 {font-size: 3.0rem;}
  78.    p {font-size: 3.0rem;}
  79.    body {max-width: 600px; margin:0px auto; padding-bottom: 25px;}
  80.    .switch {position: relative; display: inline-block; width: 120px; height: 68px}
  81.    .switch input {display: none}
  82.    .slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 6px}
  83.    .slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 3px}
  84.    input:checked+.slider {background-color: #b30000}
  85.    input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}
  86.  </style>
  87. </head>
  88. <body>
  89.  <h2>"ESP32 WiFi Car"</h2>
  90.  %BUTTONPLACEHOLDER%
  91. <script>function toggleCheckbox(element) {
  92.  var xhr = new XMLHttpRequest();
  93.  if(element.checked){ xhr.open("GET", "/update?output="+element.id+"&state=1", true); }
  94.  else { xhr.open("GET", "/update?output="+element.id+"&state=0", true); }
  95.  xhr.send();
  96. }
  97. </script>
  98. </body>
  99. </html>
  100. )rawliteral";
  101.  
  102. // Replaces placeholder with button section in your web page
  103. String processor(const String& var){
  104.   //Serial.println(var);
  105.   if(var == "BUTTONPLACEHOLDER"){
  106.     String buttons = "";
  107.     buttons += "<h4>Forward</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"1\" " + outputState(1) + "><span class=\"slider\"></span></label>";
  108.     buttons += "<h4>Reverse</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"2\" " + outputState(2) + "><span class=\"slider\"></span></label>";
  109.     buttons += "<h4>Left</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"3\" " + outputState(3) + "><span class=\"slider\"></span></label>";
  110.     buttons += "<h4>Right</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"4\" " + outputState(4) + "><span class=\"slider\"></span></label>";
  111.     buttons += "<h4>Stop</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"5\" " + outputState(5) + "><span class=\"slider\"></span></label>";
  112.     buttons += "<h4>Horn</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"6\" " + outputState(6) + "><span class=\"slider\"></span></label>";
  113.     buttons += "<h4>Headlights</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"7\" " + outputState(7) + "><span class=\"slider\"></span></label>";
  114.     buttons += "<h4>Taillights</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"8\" " + outputState(8) + "><span class=\"slider\"></span></label>";
  115.     return buttons;
  116.   }
  117.   return String();
  118. }
  119.  
  120. String outputState(int output){
  121.   if(digitalRead(output)){
  122.     return "checked";
  123.   }
  124.   else {
  125.     return "";
  126.   }
  127. }
  128.  
  129. void setup(){
  130.   // Serial port for debugging purposes
  131.   Serial.begin(115200);
  132.  
  133.   speedCar = 235; //Hard codes motors to go at maximum speed that won't cause a brownout
  134.  
  135.   pinMode(AIN1,OUTPUT); //Sets specified pin as an output
  136.   pinMode(BIN1,OUTPUT); //Sets specified pin as an output
  137.   pinMode(AIN2,OUTPUT); //Sets specified pin as an output
  138.   pinMode(BIN2,OUTPUT); //Sets specified pin as an output
  139.   pinMode(PWMA,OUTPUT); //Sets specified pin as an output
  140.   pinMode(PWMB,OUTPUT); //Sets specified pin as an output
  141.   pinMode(STBY,OUTPUT); //Sets specified pin as an output
  142.  
  143.   FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); //For LED Strip - See DemoReel100
  144.   FastLED.setBrightness(BRIGHTNESS); //Set master brightness control for LED strip
  145.  
  146.   //Reference 5 Code for Horn
  147.   #ifdef ESP_H
  148.   ledcAttachPin( horn_Buzz, PWM1_Ch );
  149.   #else
  150.   // LilyPad!
  151.   pinMode(horn_Buzz, OUTPUT);
  152.   #endif
  153.  
  154.   WiFi.softAP(ssid, password);
  155.  
  156.   // Print ESP Local IP Address
  157.   Serial.println(WiFi.localIP()); //Reference 2
  158.  
  159.   // Route for root / web page
  160.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  161.     request->send_P(200, "text/html", index_html, processor);
  162.   });
  163.  
  164.   // Send a GET request to <ESP_IP>/update?output=<inputMessage1>&state=<inputMessage2>
  165.   server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
  166.     String inputMessage1;
  167.     String inputMessage2;
  168.     // GET input1 value on <ESP_IP>/update?output=<inputMessage1>&state=<inputMessage2>
  169.     if (request->hasParam(PARAM_INPUT_1) && request->hasParam(PARAM_INPUT_2)) {
  170.       inputMessage1 = request->getParam(PARAM_INPUT_1)->value();
  171.       inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
  172.       //digitalWrite(inputMessage1.toInt(), inputMessage2.toInt()); //Actual writes output pin inputMesssage1 to state inputMessage2
  173.     }
  174.     else {
  175.       inputMessage1 = "No message sent";
  176.       inputMessage2 = "No message sent";
  177.     }
  178.     //Serial.print("Button: ");
  179.     //Serial.print(inputMessage1);
  180.     //Serial.print(" - Set to: ");
  181.     //Serial.println(inputMessage2);
  182.  
  183.     if(inputMessage1.toInt() == 1 && inputMessage2.toInt() == 1) //Forward Pushbutton is Pressed
  184.     {
  185.       command = 'F';
  186.       Serial.println(command);
  187.       motor1.drive(speedCar,50);
  188.       motor2.drive(-speedCar,50);
  189.     }
  190.     if(inputMessage1.toInt() == 1 && inputMessage2.toInt() == 0) //Forward Pushbutton is Released
  191.     {
  192.       command = 'S';
  193.       Serial.println(command);
  194.       stopVehicle();
  195.     }
  196.     else if (inputMessage1.toInt() == 2 && inputMessage2.toInt() == 1) //Reverse Pushbutton is Pressed
  197.     {
  198.       command = 'B';
  199.       Serial.println(command);
  200.       motor1.drive(-speedCar,50);
  201.       motor2.drive(speedCar,50);
  202.     }
  203.     else if (inputMessage1.toInt() == 2 && inputMessage2.toInt() == 0) //Reverse Pushbutton is Released
  204.     {
  205.       command = 'S';
  206.       Serial.println(command);
  207.       stopVehicle();
  208.     }
  209.      else if (inputMessage1.toInt() == 3 && inputMessage2.toInt() == 1) //Left Pushbutton is Pressed
  210.     {
  211.       command = 'L';
  212.       Serial.println(command);
  213.       motor1.drive(-speedCar,50); //Motor A goes opposite direction from forward
  214.       motor2.drive(-speedCar,50); //Motor B keeps going forward
  215.     }
  216.     else if (inputMessage1.toInt() == 3 && inputMessage2.toInt() == 0) //Left Pushbutton is Released
  217.     {
  218.       command = 'S';
  219.       Serial.println(command);
  220.       stopVehicle();
  221.     }
  222.     else if (inputMessage1.toInt() == 4 && inputMessage2.toInt() == 1) //Right Pushbutton is Pressed
  223.     {
  224.       command = 'R';
  225.       Serial.println(command);
  226.       motor1.drive(speedCar,50); //Motor A keeps going forward
  227.       motor2.drive(speedCar,50); //Motor B goes opposite direction from forward
  228.     }
  229.     else if (inputMessage1.toInt() == 4 && inputMessage2.toInt() == 0) //Right Pushbutton is Released
  230.     {
  231.       command = 'S';
  232.       Serial.println(command);
  233.       stopVehicle();
  234.     }
  235.     else if (inputMessage1.toInt() == 5 && inputMessage2.toInt() == 1) //Stop Pushbutton is Pressed
  236.     {
  237.       command = 'S';
  238.       Serial.println(command);
  239.       stopVehicle();
  240.     }
  241.     else if (inputMessage1.toInt() == 6 && inputMessage2.toInt() == 1) //Horn Pushbutton is Pressed
  242.     {
  243.       command = 'U';
  244.       Serial.println(command);
  245.       hornH();
  246.     }
  247.     else if (inputMessage1.toInt() == 6 && inputMessage2.toInt() == 0) //Horn Pushbutton is Released
  248.     {
  249.       command = 'Z';
  250.       Serial.println(command);
  251.       hornL();
  252.     }
  253.     else if (inputMessage1.toInt() == 7 && inputMessage2.toInt() == 1) //Headlights Pushbutton is Pressed
  254.     {
  255.       command = 'D';
  256.       Serial.println(command);
  257.       lightsFrontH();
  258.     }
  259.     else if (inputMessage1.toInt() == 7 && inputMessage2.toInt() == 0) //Headlights Pushbutton is Released
  260.     {
  261.       lightsFrontL();
  262.     }
  263.     else if (inputMessage1.toInt() == 8 && inputMessage2.toInt() == 1) //Taillights Pushbutton is Pressed
  264.     {
  265.       command = 'O';
  266.       Serial.println(command);
  267.       lightsBackH();
  268.     }
  269.     else if (inputMessage1.toInt() == 8 && inputMessage2.toInt() == 0) //Taillights Pushbutton is Released
  270.     {
  271.       lightsBackL();
  272.     }
  273.        
  274.     request->send(200, "text/plain", "OK");
  275.   });
  276.  
  277.   // Start server
  278.   server.begin();
  279. }
  280.  
  281. void loop() {
  282.   //commandEval(command); //Calls the commandEval function to actually take action that the commands received mandate
  283. }
  284.  
  285. //Function Definitions
  286. void stopVehicle()
  287. {
  288.   motor1.brake();
  289.   motor2.brake();
  290. }
  291.  
  292. void hornH() //Function turns the horn on
  293. {
  294.   //digitalWrite(horn_Buzz, HIGH); //This works fine with the small buzzer
  295.   tone(horn_Buzz, 523); //Sets the horn_Buzz pin high at a frequency of 523 Hz which is a high c note
  296. } //End of hornH function
  297.  
  298. void hornL() //Function turns the horn off
  299. {
  300.   //digitalWrite(horn_Buzz, LOW);
  301.   noTone(horn_Buzz);
  302. } //End of hornL function
  303.  
  304. void stopPeriph() //Function turns off all of the peripherals at once (i.e. front lights, back lights, and horn)
  305. {
  306.   lightsFrontL(); //Turns front lights output low
  307.   lightsBackL(); //Turns back lights output low
  308.   hornL(); //Turns horn output low
  309. } //End of stopPeriph function
  310.  
  311. void lightsFrontH() //Function turns the front lights on
  312. {
  313.   //float brightF = 0.75;
  314.   //int brightness = 255*brightF;
  315.   //fill_solid(leds[0], 1, CRGB::Green);
  316.   //fill_solid(leds[1], 1, CRGB::Green);
  317.   leds[0].r=0;
  318.   leds[0].g=255;
  319.   leds[0].b=0;
  320.   leds[1].r=0;
  321.   leds[1].g=255;
  322.   leds[1].b=0;
  323.   //Serial.println("Front light code executed.");
  324.   FastLED.show();
  325. } //End of lightsFrontH function
  326.  
  327. void lightsFrontL() //Function turns the front lights off
  328. {
  329.   leds[0].r=0;
  330.   leds[0].g=0;
  331.   leds[0].b=0;
  332.   leds[1].r=0;
  333.   leds[1].g=0;
  334.   leds[1].b=0;
  335.   FastLED.show();
  336. } //End of lightsFrontL function
  337.  
  338. void lightsBackH() //Function turns the back lights on
  339. {
  340.   //fill_solid(leds[2], 1, CRGB::Red);
  341.   //fill_solid(leds[3], 1, CRGB::Red);
  342.   leds[2].r=255;
  343.   leds[2].g=0;
  344.   leds[2].b=0;
  345.   leds[3].r=255;
  346.   leds[3].g=0;
  347.   leds[3].b=0;
  348.   //Serial.println("Back light code executed.");
  349.   FastLED.show();
  350. } //End of lightsBackH function
  351.  
  352. void lightsBackL() //Function turns the back lights off
  353. {
  354.   leds[2].r=0;
  355.   leds[2].g=0;
  356.   leds[2].b=0;
  357.   leds[3].r=0;
  358.   leds[3].g=0;
  359.   leds[3].b=0;
  360.   FastLED.show();
  361. } //End of lightsBackL function
  362.  
  363. //Reference 1- https://randomnerdtutorials.com/esp32-async-web-server-espasyncwebserver-library/
  364. //Reference 2- https://randomnerdtutorials.com/esp32-cam-access-point-ap-web-server/
  365. //Reference 3- https://randomnerdtutorials.com/esp32-esp8266-web-server-outputs-momentary-switch/
  366. //Reference 4- "MotorTestRunESP32.ino" located in D:\Stuff\Projects\ESP32 Control\RC Vehicles\ESP32 3D Printed\Sketches
  367. //Reference 5- https://forum.sparkfun.com/viewtopic.php?t=56631
  368. //Reference 6- https://dronebotworkshop.com/tb6612fng-h-bridge/
  369. //Reference 7- https://github.com/sparkfun/SparkFun_TB6612FNG_Arduino_Library
  370. //Reference 8- https://github.com/FastLED/FastLED/wiki/Controlling-leds
  371. //Reference 9- ESP32RCCarRev4.ino located in D:\Stuff\Projects\ESP32 Control\RC Vehicles\ESP32 3D Printed\Sketches\Bluetooth
  372. //Reference 10- Didn't Use But May Need to For Future Improvements https://randomnerdtutorials.com/esp32-esp8266-web-server-outputs-momentary-switch/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement