Advertisement
Guest User

design_ex2_v2 (still not done)

a guest
Feb 20th, 2020
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.50 KB | None | 0 0
  1. #include <mpu6050_esp32.h>
  2. #include <WiFi.h> //Connect to WiFi Network
  3. #include <TFT_eSPI.h> // Graphics and font library for ST7735 driver chip
  4. #include <SPI.h> //Used in support of TFT Display
  5. #include <string.h> //used for some string handling and processing.
  6.  
  7. TFT_eSPI tft = TFT_eSPI(); // Invoke library, pins defined in User_Setup.h
  8.  
  9. char network[] = "EECS_Labs"; //SSID for 6.08 Lab 2.4 GHz devices
  10. char password[] = ""; //Password for 6.08 Lab 2.4 GHz devices
  11. char dormnetwork[] = "MIT";
  12. const char USER[] = "yimingz";
  13.  
  14.  
  15. uint8_t state = 0;
  16. #define IDLE 0 //example definition
  17. #define PEAK 1 //example definition
  18. #define TROUGH 2
  19. #define BACKGROUND TFT_GREEN
  20. #define BALL_COLOR TFT_BLUE
  21.  
  22.  
  23. const int DT = 400; //milliseconds
  24. const int EXCITEMENT = 10000; //how much force to apply to ball
  25. const uint8_t BUTTON_PIN = 16; //CHANGE YOUR WIRING TO PIN 16!!! (FROM 19)
  26. const int MAX_NUM_OF_COORDS = 1000;
  27.  
  28. uint32_t primary_timer; //main loop timer
  29. char* drawing_id; // last drawing_id returned from post request
  30.  
  31. //storage of ball positions
  32. float x_positions[MAX_NUM_OF_COORDS];
  33. float y_positions[MAX_NUM_OF_COORDS];
  34. int ball_position_index = 0;
  35. char ball_position_buffer[5*MAX_NUM_OF_COORDS];
  36. int ball_position_buffer_counter = 0;
  37. int coords[2*MAX_NUM_OF_COORDS];
  38. int num_of_coords = 0;
  39.  
  40.  
  41. //positions, velocities, and accelerations:
  42. float x_pos = 64; //x position
  43. float y_pos = 32; //y position
  44. float x_vel = 0; //x velocity
  45. float y_vel = 0; //y velocity
  46. float x_accel = 0; //x acceleration
  47. float y_accel = 0; //y acceleration
  48. float x,y,z; //variables for grabbing x,y,and z values
  49.  
  50.  
  51. //physics constants:
  52. const float MASS = 1; //for starters
  53. const int RADIUS = 2; //radius of ball
  54. const float K_FRICTION = 0.15; //friction coefficient
  55. const float K_SPRING = 0.9; //spring coefficient
  56.  
  57. //boundary constants:
  58. const int LEFT_LIMIT = RADIUS; //left side of screen limit
  59. const int RIGHT_LIMIT = 127-RADIUS; //right side of screen limit
  60. const int TOP_LIMIT = RADIUS; //top of screen limit
  61. const int BOTTOM_LIMIT = 159-RADIUS; //bottom of screen limit
  62.  
  63. //IMU constants:
  64. const float resting_x_acc = 0.05;
  65. const float resting_y_acc = 0.03;
  66.  
  67. //HTTP request constants
  68. const int RESPONSE_TIMEOUT = 6000; //ms to wait for response from host
  69. const int POSTING_PERIOD = 20000; //periodicity of getting a number fact.
  70. const int GETTING_PERIOD = 10000;
  71.  
  72. const uint16_t IN_BUFFER_SIZE = 1000; //size of buffer to hold HTTP request
  73. const uint16_t OUT_BUFFER_SIZE = 1000; //size of buffer to hold HTTP response
  74. char request_buffer[IN_BUFFER_SIZE]; //char array buffer to hold HTTP request
  75. char response_buffer[OUT_BUFFER_SIZE]; //char array buffer to hold HTTP response
  76. char get_response_buffer[OUT_BUFFER_SIZE];
  77.  
  78. bool pushed_last_time; //for finding change of button (using bool type...same as uint8_t)
  79. uint32_t posting_timer = 0;
  80. uint32_t last_time = 0;
  81. bool havePosted = false;
  82.  
  83. float old_acc[3]; // array with x,y,z accelerations
  84. float older_acc[3];
  85. MPU6050 imu; //imu object called, appropriately, imu
  86.  
  87. void step(float x_force=0, float y_force=0 ){
  88. //update acceleration (from f=ma)
  89. x_accel = (x_force-K_FRICTION*x_vel)/MASS;
  90. y_accel = (y_force-K_FRICTION*y_vel)/MASS;
  91. //integrate to get velocity from current acceleration
  92. x_vel = x_vel + 0.001*DT*x_accel; //integrate, 0.001 is conversion from milliseconds to seconds
  93. y_vel = y_vel + 0.001*DT*y_accel; //integrate!!
  94. //
  95. moveBall();
  96. }
  97.  
  98. void moveBall(){
  99. if(x_pos + 0.001*DT*x_vel > RIGHT_LIMIT) {
  100. x_pos = RIGHT_LIMIT - K_SPRING*(x_pos + 0.001*DT*x_vel - RIGHT_LIMIT);
  101. x_vel = -K_SPRING*x_vel;
  102. }
  103. else if(x_pos + 0.001*DT*x_vel < LEFT_LIMIT) {
  104. x_pos = LEFT_LIMIT + K_SPRING*(LEFT_LIMIT - (x_pos + 0.001*DT*x_vel));
  105. x_vel = -K_SPRING*x_vel;
  106. }
  107. else {
  108. x_pos = x_pos + 0.001*DT*x_vel;
  109. }
  110. if(y_pos + 0.001*DT*y_vel > BOTTOM_LIMIT) {
  111. y_pos = BOTTOM_LIMIT - K_SPRING*(y_pos + 0.001*DT*y_vel - BOTTOM_LIMIT);
  112. y_vel = -K_SPRING*y_vel;
  113. }
  114. else if(y_pos + 0.001*DT*y_vel < TOP_LIMIT) {
  115. y_pos = TOP_LIMIT + K_SPRING*(TOP_LIMIT - (y_pos + 0.001*DT*y_vel));
  116. y_vel = -K_SPRING*y_vel;
  117. }
  118. else {
  119. y_pos = y_pos + 0.001*DT*y_vel;
  120. }
  121. }
  122.  
  123.  
  124. void setup() {
  125. Serial.begin(115200); //for debugging if needed.
  126. pinMode(BUTTON_PIN,INPUT_PULLUP);
  127. tft.init();
  128. tft.setRotation(2);
  129. tft.setTextSize(1);
  130. tft.fillScreen(BACKGROUND);
  131. Serial.begin(115200); //begin serial comms
  132. delay(100); //wait a bit (100 ms)
  133.  
  134. WiFi.begin(dormnetwork,password); //attempt to connect to wifi
  135. uint8_t count = 0; //count used for Wifi check times
  136. Serial.print("Attempting to connect to ");
  137. Serial.println(network);
  138. Wire.begin();
  139. delay(50); //pause to make sure comms get set up
  140. if (imu.setupIMU(1)){
  141. Serial.println("IMU Connected!");
  142. }else{
  143. Serial.println("IMU Not Connected :/");
  144. Serial.println("Restarting");
  145. ESP.restart(); // restart the ESP (proper way)
  146. }
  147. while (WiFi.status() != WL_CONNECTED && count<12) {
  148. delay(500);
  149. Serial.print(".");
  150. count++;
  151. }
  152. delay(2000);
  153. if (WiFi.isConnected()) { //if we connected then print our IP, Mac, and SSID we're on
  154. Serial.println("CONNECTED!");
  155. Serial.println(WiFi.localIP().toString() + " (" + WiFi.macAddress() + ") (" + WiFi.SSID() + ")");
  156. delay(500);
  157. } else { //if we failed to connect just Try again.
  158. Serial.println("Failed to Connect :/ Going to restart");
  159. Serial.println(WiFi.status());
  160. ESP.restart(); // restart the ESP (proper way)
  161. }
  162.  
  163. x_positions[0] = (int) x_pos;
  164. y_positions[0] = (int) y_pos;
  165. ball_position_buffer_counter = snprintf(ball_position_buffer, 5*MAX_NUM_OF_COORDS, "%d,%d&", (int) x_pos, (int) y_pos);
  166.  
  167. step(); // apply no initial force
  168. pushed_last_time = false;
  169. primary_timer = millis();
  170. }
  171.  
  172. void loop() {
  173. ball_position_index++; // Increment first since we already did index = 0 in setup()
  174. x_positions[ball_position_index] = x_pos;
  175. y_positions[ball_position_index] = y_pos;
  176. imu.readAccelData(imu.accelCount);
  177. x = imu.accelCount[0]*imu.aRes;
  178. y = imu.accelCount[1]*imu.aRes;
  179. z = imu.accelCount[2]*imu.aRes;
  180.  
  181. float acc[] = {x,y,z};
  182. float avg_acc[3];
  183.  
  184. for(int i=0; i<3; i++) {
  185. avg_acc[i] = (acc[i] + old_acc[i] + older_acc[i])/3;
  186. }
  187.  
  188. for(int i=0; i<3; i++) {
  189. older_acc[i] = old_acc[i];
  190. old_acc[i] = acc[i];
  191. }
  192.  
  193. step((avg_acc[0]-resting_x_acc) * 100 * MASS, (avg_acc[1]-resting_y_acc) * 100 * MASS);
  194. tft.fillCircle(x_pos,y_pos,RADIUS,BALL_COLOR); //draw new ball location
  195.  
  196. if((ball_position_buffer_counter >= 0 && ball_position_buffer_counter < 5*MAX_NUM_OF_COORDS) && ball_position_index<(sizeof(x_positions)/sizeof(int))) {
  197. ball_position_buffer_counter += snprintf(ball_position_buffer+ball_position_buffer_counter, 5*MAX_NUM_OF_COORDS-ball_position_buffer_counter, "%d,%d&", (int) x_positions[ball_position_index], (int) y_positions[ball_position_index]);
  198. }
  199.  
  200. // TESTING ONLY
  201. // post request test
  202. if (millis()-posting_timer > POSTING_PERIOD) {
  203. char body[5000]; //for body
  204. sprintf(body,"{\"user\":\"%s\",\"drawing\":\"%s\"}",USER,ball_position_buffer);//generate body, posting to User, 1 step
  205. int body_len = strlen(body); //calculate body length (for header reporting)
  206. sprintf(request_buffer,"POST http://608dev.net//sandbox/etchsketch HTTP/1.1\r\n");
  207. strcat(request_buffer,"Host: 608dev.net\r\n");
  208. strcat(request_buffer,"Content-Type: application/json\r\n");
  209. sprintf(request_buffer+strlen(request_buffer),"Content-Length: %d\r\n", body_len); //append string formatted to end of request buffer
  210. strcat(request_buffer,"\r\n"); //new line from header to body
  211. strcat(request_buffer,body); //body
  212. strcat(request_buffer,"\r\n"); //header
  213. //Serial.println(request_buffer);
  214. do_http_request("608dev.net", request_buffer, response_buffer, OUT_BUFFER_SIZE, RESPONSE_TIMEOUT,true);
  215. //Serial.println("RESPONSE!!!");
  216. //Serial.println(response_buffer);
  217. char token[5];
  218. sprintf(token,"%c",':');
  219. char* ptr = strtok(response_buffer, token);
  220. ptr = strtok(NULL, token);
  221. drawing_id = ptr;
  222. Serial.println("DRAWING ID IN POST");
  223. Serial.println(drawing_id);
  224. memset(request_buffer, 0, strlen(request_buffer));
  225.  
  226. posting_timer = millis();
  227. havePosted = true;
  228. }
  229.  
  230. // get request test
  231. if(millis() - last_time > GETTING_PERIOD) {
  232. if(havePosted) {
  233. Serial.println("DRAWING ID FOR GET REQUEST");
  234. Serial.println(drawing_id);
  235. sprintf(request_buffer,"GET http://608dev.net//sandbox/etchsketch?drawing_id=%s HTTP/1.1\r\n", drawing_id);
  236. strcat(request_buffer,"Host: 608dev.net\r\n"); //add more to the end
  237. strcat(request_buffer,"\r\n");
  238. do_http_request("608dev.net", request_buffer, get_response_buffer, OUT_BUFFER_SIZE, RESPONSE_TIMEOUT, true);
  239. Serial.println(get_response_buffer);
  240.  
  241. char token[5];
  242. sprintf(token,"%c",'~');
  243. char* ptr = strtok(get_response_buffer, token);
  244. ptr = strtok(NULL, token);
  245. strcpy(ball_position_buffer,ptr);
  246. Serial.println("BALL POSITION BUFFER");
  247. Serial.println(ball_position_buffer);
  248.  
  249. memset(x_positions, 0, MAX_NUM_OF_COORDS);
  250. memset(y_positions, 0, MAX_NUM_OF_COORDS);
  251. memset(coords, 0, 2*MAX_NUM_OF_COORDS);
  252. // GET REQUEST
  253. int_extractor(ball_position_buffer, coords);
  254. Serial.println("COORDS");
  255. for(int i=0; i<100; i++) {
  256. Serial.println(coords[i]);
  257. }
  258. num_of_coords = 0;
  259. for(int i=0; i<MAX_NUM_OF_COORDS; i++) {
  260. if(coords[i] <= 159 && coords[i] > 0) {
  261. num_of_coords++;
  262. }
  263. else {
  264. break;
  265. }
  266. }
  267.  
  268. num_of_coords /= 2;
  269.  
  270. Serial.println("NUM OF COORDS!!!!");
  271. Serial.println(num_of_coords);
  272.  
  273. // Clear background, update x,y arrays, and draw the balls
  274. tft.fillScreen(BACKGROUND);
  275. for(int i=0; i<num_of_coords; i++) {
  276. x_positions[i] = coords[2*i];
  277. y_positions[i] = coords[2*i+1];
  278. tft.fillCircle(x_positions[i],y_positions[i],RADIUS,BALL_COLOR);
  279. }
  280.  
  281. ball_position_index = num_of_coords-1;
  282. ball_position_buffer_counter = 0;
  283. // TODO FIGURE OUT ball_position_buffer_counter
  284. }
  285. else {
  286. Serial.println("ERROR: NO DRAWING ID");
  287. }
  288. last_time = millis();
  289. }
  290.  
  291. while (millis()-primary_timer < DT); //wait for primary timer to increment
  292. primary_timer = millis();
  293. }
  294.  
  295.  
  296. // Int extractor function (from Ex 2) with both ',' and '&' as delimiters
  297. void int_extractor(char* data_array, int* output_values){
  298. if(sizeof(data_array)/sizeof(char) == 0) {
  299. return;
  300. }
  301. int ind=0;
  302. char token[5];
  303. sprintf(token,"%c%c",',','&');
  304. char* ptr = strtok(data_array, token);
  305. if(ptr == NULL) {
  306. return;
  307. }
  308. output_values[ind] = atoi(ptr);
  309. ind++;
  310. while(ptr != NULL) {
  311. ptr = strtok(NULL, token);
  312. if(ptr == NULL) {
  313. break;
  314. }
  315. output_values[ind] = atoi(ptr);
  316. ind++;
  317. }
  318. }
  319.  
  320.  
  321. /*----------------------------------
  322. * char_append Function:
  323. * Arguments:
  324. * char* buff: pointer to character array which we will append a
  325. * char c:
  326. * uint16_t buff_size: size of buffer buff
  327. *
  328. * Return value:
  329. * boolean: True if character appended, False if not appended (indicating buffer full)
  330. */
  331. uint8_t char_append(char* buff, char c, uint16_t buff_size) {
  332. int len = strlen(buff);
  333. if (len>buff_size) return false;
  334. buff[len] = c;
  335. buff[len+1] = '\0';
  336. return true;
  337. }
  338.  
  339. /*----------------------------------
  340. * do_http_request Function:
  341. * Arguments:
  342. * char* host: null-terminated char-array containing host to connect to
  343. * char* request: null-terminated char-arry containing properly formatted HTTP request
  344. * char* response: char-array used as output for function to contain response
  345. * uint16_t response_size: size of response buffer (in bytes)
  346. * uint16_t response_timeout: duration we'll wait (in ms) for a response from server
  347. * uint8_t serial: used for printing debug information to terminal (true prints, false doesn't)
  348. * Return value:
  349. * void (none)
  350. */
  351. void do_http_request(char* host, char* request, char* response, uint16_t response_size, uint16_t response_timeout, uint8_t serial){
  352. WiFiClient client; //instantiate a client object
  353. if (client.connect(host, 80)) { //try to connect to host on port 80
  354. if (serial) Serial.print(request);//Can do one-line if statements in C without curly braces
  355. client.print(request);
  356. memset(response, 0, response_size); //Null out (0 is the value of the null terminator '\0') entire buffer
  357. uint32_t count = millis();
  358. while (client.connected()) { //while we remain connected read out data coming back
  359. client.readBytesUntil('\n',response,response_size);
  360. if (serial) Serial.println(response);
  361. if (strcmp(response,"\r")==0) { //found a blank line!
  362. break;
  363. }
  364. memset(response, 0, response_size);
  365. if (millis()-count>response_timeout) break;
  366. }
  367. memset(response, 0, response_size);
  368. count = millis();
  369. while (client.available()) { //read out remaining text (body of response)
  370. char_append(response,client.read(),OUT_BUFFER_SIZE);
  371. }
  372. if (serial) Serial.println(response);
  373. client.stop();
  374. if (serial) Serial.println("-----------");
  375. }else{
  376. if (serial) Serial.println("connection failed :/");
  377. if (serial) Serial.println("wait 0.5 sec...");
  378. client.stop();
  379. }
  380. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement