AOS Team / Mbed 2 deprecated mbed_AOS_proj

Dependencies:   C12832 EthernetInterface HTTPClient USBDevice mbed-rtos mbed Speaker

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "HTTPClient.h"
00003 #include "C12832.h"
00004 #include "EthernetInterface.h"
00005 #include <string>
00006 #include <stdlib.h>     /* srand, rand */
00007 #include "rtos.h"
00008 #include <sstream>
00009 #include "USBAudio.h"
00010 #include "Speaker.h"
00011  
00012 /*
00013 Account: mbedTokyoTech
00014 Psswd: kalle123
00015 Email: ricli877@student.liu.se
00016  
00017 $consumerKey = 'XHO3e2fiS44d5i7xc6mvtvDdZ';
00018 $consumerSecret = '9U4WOjRnpM5Pj0Qv4f6406jTRfN65YY5GeE5PRXHuhPfSiWhEN';
00019 $accessToken = '4761221959-n4ojXEYR4DZSA4eeqt1WetVHHrZWTUNLJJ9ql3o';
00020 $accessTokenSecret = 'SXM05FPIW9SUgTYYgpk4buPcypwXIsLDIY3TRns01WRJP';
00021 */
00022 
00023 // frequency: 48 kHz
00024 #define FREQ 48000
00025 
00026 // 1 channel: mono
00027 #define NB_CHA 1
00028 
00029 // Length of an audio packet: each ms, we receive 48 * 16bits ->48 * 2 bytes. As there is one channel, the length will be 48 * 2 * 1
00030 #define AUDIO_LENGTH_PACKET 48 * 2 * 1
00031  
00032 RawSerial pc(USBTX, USBRX);
00033 
00034 //Variables for audio streaming
00035 
00036 // USBAudio
00037 USBAudio audio(FREQ, NB_CHA, 8000, 1, 0x7180, 0x7500);
00038 
00039 // Ticker to send data to the speaker at the required frequency
00040 Ticker tic;
00041 
00042 // Buffer where one audio packet will be stored (LENGTH_AUDIO_PACKET/2 because we are storing int16 and not uint8)
00043 int16_t buf2[AUDIO_LENGTH_PACKET/2];
00044 
00045 // Show if an audio packet is available
00046 volatile bool available = false;
00047 
00048 // Index of the value which will be send to the speaker
00049 int index_buf = 0;
00050 
00051 // Previous value sent to the speaker
00052 uint16_t p_val = 0;
00053 
00054 // Speaker connected to the AnalogOut output. The audio stream received over USb will be sent to the speaker
00055 AnalogOut speaker(p18);
00056  
00057 DigitalIn button(p14);
00058  
00059 EthernetInterface eth;
00060  
00061 C12832 lcd(p5, p7, p6, p8, p11);
00062  
00063 HTTPClient http;
00064  
00065 BusIn joy(p15,p12,p13,p16);
00066  
00067 Mutex locker;
00068 
00069 Speaker speaker2(p26);
00070 
00071 int toggle_flag = 1;
00072 
00073 // sting buffers for tweeting
00074 char str[512];
00075 char buf[512];
00076     
00077 int enX[17] = {75,37,19,93,59,21,80,65,27,45,47,49,54,94,62,104,28};
00078 int enY[19] = {30,16,25,5,15,22,13,7,6,23,24,2,28,21,20,14,17,19,3};
00079  
00080 int foodX[23] = {2,38,105,109,99,30,97,26,5,40,121,24,101,69,84,48,34,9,118,29,25,70,1};
00081 int foodY[13] = {11,29,2,23,6,24,28,5,1,27,9,7,13};
00082  
00083 //Stuff for the snakegame + joystick
00084 int score = 0;
00085 int s2 = 0;
00086 int xPos = 50, yPos = 10;
00087 int xDim = 128, yDim = 32;
00088 int step = 4;
00089 int xFood = foodX[0], yFood = foodY[0], xKiller=enX[0], yKiller=enY[0];
00090 int foodIndex = 1;
00091 int enemyIndex = 1;
00092  
00093 bool gameOver = false;
00094 bool gameOverScreen = false;
00095  
00096  
00097 int k = 0;
00098  
00099 int i = 0, j = 0;
00100  
00101 bool hit2 = false;
00102 //Function that checks if the food was eaten, returns true if it was.
00103 bool hitFood(){
00104     if(abs(xFood - i) < 5 && abs(yFood - j) < 5) {
00105         score = score + 1;
00106         return true;
00107     }
00108     return false;
00109 }
00110 bool hitEnemy(){
00111     if(abs(xKiller - i) < 5 && abs(yKiller - j) < 5) {
00112         return true;
00113     }
00114     return false;
00115 }
00116 //Function that creates new food
00117 void createNewFood(){
00118     xFood = foodX [foodIndex % sizeof(foodX)];
00119     yFood = foodY [foodIndex % sizeof(foodY)];
00120    
00121     xKiller = enX[enemyIndex % sizeof(enX)];
00122     yKiller = enY[enemyIndex % sizeof(enY)];
00123    
00124     while(abs(xKiller - xFood) < 5 || abs(yKiller - yFood) < 5){
00125         enemyIndex = enemyIndex + 1;
00126         xKiller = enX[enemyIndex % sizeof(enX)];
00127         yKiller = enY[enemyIndex % sizeof(enY)];
00128     }
00129    
00130     foodIndex = foodIndex + 1;
00131     enemyIndex = enemyIndex + 1;
00132 }  
00133  
00134 void setUpGame() {
00135     score = 0;
00136     xPos = 50, yPos = 10;
00137     xDim = 128, yDim = 32;
00138     step = 4;
00139     xFood = foodX[0], yFood = foodY[0], xKiller=enX[0], yKiller=enY[0];
00140     foodIndex = 1;
00141     enemyIndex = 1;
00142 }
00143 
00144 void gameOverFun(){
00145     //speaker2.PlayNote(969.0, 0.5, 1.0);
00146     //speaker2.PlayNote(800.0, 0.5, 1.0);
00147     lcd.cls();
00148     lcd.locate(xDim / 2 - 10, yDim / 2);
00149     lcd.printf("Game Over");
00150 } 
00151    
00152 //Function that actually draws the snake and handles the user input
00153 void playSnake(void const *args)
00154 {
00155     while(true) {
00156          if(gameOver){
00157                 Thread::wait(10000);
00158             }
00159         
00160         if (!gameOver && !gameOverScreen) {
00161             //locker.lock();
00162             setUpGame();
00163             
00164             while(!gameOverScreen) {
00165                 //pc.printf("Inne");
00166                 //Handles joystick-input
00167                 
00168                 if(joy) {
00169                     if(joy == 0x4) {                    //Right Left
00170                         k=0;
00171                         i = i - step;
00172                         if(i < 0) i = xDim + i;
00173                     } else if(joy == 0x8) {             //Right Left
00174                         k=1;
00175                         i = (i + step) % xDim;
00176                     } else if(joy == 0x1) {             //Up Down
00177                         k=2;
00178                         j = j - step;
00179                         if(j < 0) j = yDim + j;
00180                     } else if(joy == 0x2) {             //Up Down
00181                         k=3;
00182                         j = (j + step) % yDim;
00183                     }
00184                 }else {
00185                     if(k == 0) {
00186                         i = i - step;
00187                         if(i < 0) i = xDim + i;
00188                     } else if(k == 1) {
00189                         i = (i + step) % xDim;
00190                     } else if(k == 2) {
00191                         j = j - step;
00192                         if(j < 0) j = yDim + j;
00193                     } else if(k == 3) {
00194                         j = (j + step) % yDim;
00195                     }
00196                 }
00197                 lcd.cls();
00198                 lcd.locate(i,j);
00199        
00200                 int r = 3;
00201                 //To move the score to not interfere with game
00202                 if(i < xDim / 2) lcd.locate(xDim-10, 10);
00203                 else lcd.locate(10,10);
00204                 lcd.printf("%i", score);
00205                
00206                 //Draw snake
00207                 lcd.fillcircle(i, j, r, 1);
00208                
00209                 //Draw enemy
00210                 lcd.locate(xKiller,yKiller);
00211                 lcd.printf("X");
00212                 bool hitE = hitEnemy();
00213                
00214                 //Draw food
00215                 lcd.fillcircle(xFood, yFood, 2, 1);
00216                 hit2 = hitFood();
00217                
00218                 //To see if food was eaten
00219                 if(hit2)
00220                     createNewFood();
00221                 else if(hitE){
00222                     //tic.detach();
00223                     gameOver = true;
00224                     gameOverScreen = true;
00225                     gameOverFun();
00226                 }
00227                 Thread::wait(50); // Used to control the speed of the game
00228             }
00229         }
00230     }
00231 }
00232  
00233 // Replace all occurrences of s2 with s3 in s1
00234 void rep(std::string &s1, const char * s2, const char * s3) {
00235     size_t index = 0;
00236     while (index < s1.size()) {
00237         index = s1.find(s2, index);
00238         if (index == std::string::npos) break;
00239         s1.replace(index, strlen(s2), s3);
00240         index += strlen(s3);
00241     }
00242 }
00243  
00244 // Tweet msg
00245 void tweet(std::string msg) {
00246     std::string url ("http://www.rickardlindstedt.com/proxy.php?msg=");
00247     //pc.printf("Message: %s\n", msg.c_str());
00248     //pc.printf("\nTrying to post data...\n");
00249    
00250     // replace special characters with URL-safe ones
00251     rep(msg, " ", "%20");
00252     rep(msg, "#", "%23");
00253     rep(msg, ":", "%3A");
00254     
00255    
00256     url = url + msg;
00257    
00258     //pc.printf("URL: %s\n", url.c_str());
00259    //pc.printf("i tweet3");
00260     // send HTTP request
00261     int ret = http.get(url.c_str(), str, 128);
00262     //pc.printf("i tweet4");
00263     if (ret == HTTP_OK)
00264     {
00265       //pc.printf("Success!\n");
00266     }
00267     else
00268     {
00269       //pc.printf("Error #%d\n", ret);
00270     }
00271     
00272     //Used to restart game
00273     setUpGame();
00274     //pc.printf("Response code: %d\n", http.getHTTPResponseCode());
00275     
00276 }
00277  
00278 // Set up ethernet network interface
00279 void setUpNetwork() {
00280     eth.init();
00281     eth.connect();
00282     //pc.printf("IP: %s", eth.getIPAddress());
00283 }
00284  
00285 void tweetHighscore(void const *args){
00286     //tic.detach();
00287     //available = false;
00288     setUpNetwork();
00289     while(true) {
00290         //locker.lock();
00291         if (gameOver) {
00292             //pc.printf("I game over");
00293             //tic.detach();
00294             std::string msg;
00295             ostringstream convert;
00296             convert << "Score: " << score << ", " << xKiller;
00297             msg = convert.str();
00298             tweet(msg);
00299             //pc.printf("efter tweet(msg)");
00300             locker.lock();
00301             gameOver = false;
00302             bool kalle = true;
00303             while(kalle){
00304                 if(joy) kalle = false;
00305             }
00306             gameOverScreen = false;
00307             locker.unlock();
00308         }
00309         //locker.unlock();
00310         Thread::wait(1000);
00311     }
00312 }
00313 
00314 // Function executed each 1/FREQ s
00315 void tic_handler() {
00316     float speaker_value;
00317 
00318     if (available) {
00319         // Convert 2 bytes in float
00320         speaker_value = (float)(buf2[index_buf]);
00321         
00322         // Speaker_value between 0 and 65535
00323         speaker_value += 32768.0;
00324 
00325         // Adjust according to current volume
00326         speaker_value *= audio.getVolume();
00327         
00328         
00329         // As two bytes has been read, we move the index of two bytes
00330         index_buf++;
00331         
00332         // If we have read all the buffer, no more data available
00333         if (index_buf == AUDIO_LENGTH_PACKET/2) {
00334             index_buf = 0;
00335             available = false;
00336         }
00337     } else {
00338         speaker_value = p_val;
00339     }
00340     
00341     p_val = speaker_value;
00342 
00343     // Send value to the speaker
00344     speaker.write_u16((uint16_t)speaker_value);
00345 }
00346 
00347 int main()
00348 {
00349     
00350     // Attach a function executed each 1/FREQ s
00351     tic.attach_us(tic_handler, 1000000.0/(float)FREQ);
00352     //pc.printf("hej");
00353     createNewFood();
00354     //pc.printf("after create food");
00355     Thread threadSnake(playSnake);
00356     Thread threadTweet(tweetHighscore);
00357     //pc.printf("after threads");
00358     
00359     
00360     while (1) {
00361         // Read an audio packet
00362         /*if(gameOver){
00363             
00364              tic.detach();
00365              
00366              
00367          }*/
00368             audio.read((uint8_t *)buf2);
00369             available = true;
00370         
00371     }
00372    /*while(true) {
00373         Thread::wait(500);
00374     }*/
00375 }