Ejemplo n.º 1
0
int main()
{  
  // install signal handler
  if (signal(SIGINT, endall) == SIG_ERR)
    printf("[FAILED] to install SIGINT handle\n");

  // we're reading directly from serial
  ArduinoSerial arduino(ARDUINO_SERIAL);

  char buffer[BUFFER_S];
  memset(buffer, '\0', BUFFER_S);

  // our main loop
  while(1) 
  {
    // getLine() blocks until we get a newline or cr
    // and fills buffer with stuff
    arduino.getLine( buffer);
    printf("%s", buffer);
    
    // this message looks like "p\n"
    if( buffer[0] == 'p')
    {
      printf("got play\n");
      lo_address server = lo_address_new(SERVER, SERVER_PORT);
      lo_send(server, "/playtrigger", "");
      lo_address_free(server);;
    }
    // get rid of previous data
    memset(buffer, BUFFER_S, '\0');
  }
  return 0;
}
Ejemplo n.º 2
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQuickView *view = new QQuickView;
    ArduinoMgr arduino(0);
    view->engine()->rootContext()->setContextProperty("arduino", &arduino);

    view->setSource(QStringLiteral("qrc:/arduino.qml"));
    view->show();

    return app.exec();
}
Ejemplo n.º 3
0
int main(int argc, char *argv[]) {
  char* serialPort = argv[1];

  if (!Arduino::init(serialPort)) {
    printf("Cannot open serial port %s.\n", serialPort);
    return -1;
  }

  for (int nid = 4; nid <= 4; nid++) {
    Arduino arduino(nid);

    printf("Init node #%d\n", nid);

    arduino.pinMode(LED_OUT, OUTPUT);
    arduino.delay(1000);
    printf("done\n");

    for (int i=0; i<3; i++) {
      int val;

      printf("LED on\n");
      arduino.digitalWrite(LED_OUT, HIGH);
      arduino.delay(1000);
      printf("done.\n");

      val = arduino.analogRead(PHOTO_AIN);
      printf("Photo value: %d (%d %%)\n", val, val * 100 / 1023);
      arduino.delay(1000);

      printf("LED off\n");
      arduino.digitalWrite(LED_OUT, LOW);
      arduino.delay(1000);
      printf("done.\n");

      val = arduino.analogRead(PHOTO_AIN);
      printf("Photo value: %d (%d %%)\n", val, val * 100 / 1023);
      arduino.delay(1000);

      printf("LED slowly on\n");
      for (int i=0; i<=255; i++) {
        arduino.analogWrite(LED_OUT, i);
        arduino.delay(10);
      }
      printf("done.\n");
    }
  }
}
Ejemplo n.º 4
0
int main()
{  
  // install signal handler
  if (signal(SIGINT, endall) == SIG_ERR)
    printf("[FAILED] to install SIGINT handle\n");

  // we're reading directly from serial
  ArduinoSerial arduino(ARDUINO_SERIAL);

  char buffer[BUFFER_S];
  memset(buffer, '\0', BUFFER_S);

  // our main loop
  while(1) 
  {
    int velocity = -1 , id = -1;
    
    // getLine() blocks until we get a newline or cr
    // and fills buffer with stuff
    int size = arduino.getLine( buffer);
    printf("%s", buffer);
    
    // our input looks like "i 123 v 4567"
    // so that id would be 123 and velocity would be 456
    sscanf(buffer, "i %d v %d\n", &id, &velocity);
    if( id != -1 && velocity != -1)
    {
      // show what we got
      printf( "s = %d, id = %d, vel = %d\n", size, id, velocity);

      int min = 0;
      int max = NUM_VIDEOS;
      int newint = rand()%(max-min + 1) + min; 

      lo_address server = lo_address_new(SERVER, SERVER_PORT);
      lo_send(server, "/stopall", "i", velocity);
      //      lo_send(server, "/playloop", "i", id);
      /* now we're sending a random video number because we have more videos than buttons, plus dave wanted it to be random anyway */
      lo_send(server, "/playloop", "i", newint);
      lo_address_free(server);
    }
    // get rid of previous data
    memset(buffer, BUFFER_S, '\0');
  }
  return 0;
}
Ejemplo n.º 5
0
void arduinoListener::run()
{
    while (true) {
        garbage = std::system("lsusb > arduinoListener.txt");
        QFile arduino("arduinoListener.txt");
        if (arduino.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&arduino);
            QString file = in.readAll();
            arduino.close();
            if ((test = file.contains("Arduino")) == true) {
                emit arduinoConnect();
                break;
            }
            else
                usleep(5000);
        }
    }

}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{

    //CONNECT TO ARDUINO
    ArduSerialStream arduinoSerial("/dev/ttyUSB0",SerialStreamBuf::BAUD_115200);
    arduinoSerial.openSerial();
    if(arduinoSerial.IsOpen()){
        cout << "Connection succeed" << endl;
    }else{
        cout << "Connection did NOT succeed" << endl;
        return -1;
    }

    ArduinoInterface arduino(&arduinoSerial);
    arduino.pinMode(3,OUTPUT);


    /********************************************************/

    //ARDUINO PROGRAM

    //blink
    while(true){
        if(arduino.digitalRead(8) == 1 ){
            arduino.digitalWrite(3,HIGH);
            arduino.delay(1000);
            arduino.digitalWrite(3,LOW);
            arduino.delay(1000);
        }else{
            arduino.delay(10);
        }
    }

    /********************************************************/

    //CLOSE ARDUINO CONNECTION
    arduinoSerial.closeSerial();

    return 0;
}
Ejemplo n.º 7
0
int main()
{
  // install signal handler
  if (signal(SIGINT, endall) == SIG_ERR)
    printf("[FAILED] to install SIGINT handle\n");

#ifdef ARDUINO_SERIAL
  // we're reading directly from serial
  ArduinoSerial arduino(ARDUINO_SERIAL);
#endif

  char buffer[BUFFER_S];
  memset(buffer, '\0', BUFFER_S);

  // our main loop
  while(1) 
  {
    char io[100];

    int size = arduino.getLine( buffer);
    
    printf("%s", buffer);
    
    sscanf(buffer, "%s\n", io);
    printf("--%s--", io);

    lo_address server = lo_address_new(SERVER, SERVER_PORT);
   int out =  lo_send(server, io, "i", 0 );
    printf("lo_send out: %i\n", out);

    // get rid of previous data
    for( int i=0; i < size; ++i)
      buffer[i] = '\0';

  }
  return 0;
}
Ejemplo n.º 8
0
int main(int ac, const char **av)
{
	// Create application window
	WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, _T("Douceur"), NULL };
	RegisterClassEx(&wc);
	HWND hwnd = CreateWindow(_T("Douceur"), _T("Douceur"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);

	// Initialize Direct3D
	if (CreateDeviceD3D(hwnd) < 0)
	{
		CleanupDeviceD3D();
		UnregisterClass(_T("Douceur"), wc.hInstance);
		return 1;
	}

	// Show the window
	ShowWindow(hwnd, SW_SHOWDEFAULT);
	UpdateWindow(hwnd);

	// Setup ImGui binding
	ImGui_ImplDX11_Init(hwnd, g_pd3dDevice, g_pd3dDeviceContext);

	// Load Fonts
	// (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
	//ImGuiIO& io = ImGui::GetIO();
	//io.Fonts->AddFontDefault();
	//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
	//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
	//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
	//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
	//io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());

	bool show_test_window = true;
	ImVec4 clear_col = ImColor(114, 144, 154);
	// Main loop
	MSG msg;
	ZeroMemory(&msg, sizeof(msg));

	std::string arduinoMsg;
	std::string arduinoDisplayMsg;
	bool messageEnded = true;

	FMOD::System *fmodSystem;
	FMOD::System_Create(&fmodSystem);

	FMOD::Sound        *sound = 0;
	FMOD::Channel      *channel = 0;
	FMOD::ChannelGroup *mastergroup = 0;

	fmodSystem->init(128, FMOD_INIT_NORMAL, 0);

	fmodSystem->getMasterChannelGroup(&mastergroup);

	fmodSystem->createSound("../DouceurExternal/audio-samples/Yamaha-1.wav", FMOD_LOOP_NORMAL, 0, &sound);

	unsigned int soundLength = 0;
	sound->getLength(&soundLength, FMOD_TIMEUNIT_MS);

	Serial arduino("COM6");
	Board  board(fmodSystem);

	while (msg.message != WM_QUIT)
	{
		fmodSystem->update();

		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			continue;
		}
		ImGui_ImplDX11_NewFrame();

		static bool first = true;
		static int from = 0;
		static int to = 400;
		static float freq = 1.f;
		static float pan = 0.f;
		static float pitch = 0.f;
		if (!first)
		{
			fmodSystem->playSound(sound, mastergroup, false, &channel);
			first = true;
			to = soundLength;
			channel->getFrequency(&freq);
			channel->getPitch(&pitch);
		}

		{
			ImGui::SetNextWindowPos(ImVec2(10, 10));
			ImGui::Begin("FPS", nullptr, ImVec2(0, 0), 0.3f, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings);
			ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
			ImGui::End();
		}

		if (false)
		{
			ImGui::Begin("SoloudTest");

			bool changed = ImGui::SliderInt("from", (int*)&from, 0, soundLength - 1);
			changed |= ImGui::SliderInt("to", (int*)&to, 1, soundLength);
			changed |= ImGui::SliderFloat("freq", &freq, 0, 500000.f);
			changed |= ImGui::SliderFloat("pan", &pan, -1.f, 1.f);
			changed |= ImGui::SliderFloat("pitch", &pitch, 0.f, 10.f);
			if (changed)
			{
				if (from >= to)
				{
					from = to - 1;
				}
				channel->setLoopPoints(from, FMOD_TIMEUNIT_MS, to, FMOD_TIMEUNIT_MS);
				channel->setFrequency(freq);
				channel->setPan(pan);
			}
			ImGui::End();
		}

		if (false)
		{
			ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);     // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
			ImGui::ShowTestWindow(nullptr);
		}

		board.updateGui();

		//Arduino test
		{
			if (arduino.IsConnected())
			{
				if (ImGui::Begin("Arduino test"))
				{
					char buffer[2048];
					if (messageEnded)
					{
						arduino.WriteData("A", 1);
						messageEnded = false;
					}
					while (!messageEnded)
					{
						int count = arduino.ReadData(buffer, 2047);
						if (count)
						{
							buffer[count] = '\0';
							if (buffer[count - 1] == '@')
							{
								buffer[count - 1] = '\0';
								messageEnded = true;
							}
							arduinoMsg += buffer;
						}
						else
						{
							break;
						}
					}
					if (messageEnded)
					{
						board.updatePadsVoltage(arduinoMsg);

						arduinoDisplayMsg = arduinoMsg;
						arduinoMsg.clear();
					}
					ImGui::TextWrapped(arduinoDisplayMsg.c_str());
					ImGui::Text("Message size : %i", arduinoDisplayMsg.size());
				}
				ImGui::End();
				board.displayPadsVoltage();
			}
		}

		// Rendering
		g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_col);
		ImGui::Render();
		g_pSwapChain->Present(0, 0);
	}

	ImGui_ImplDX11_Shutdown();
	CleanupDeviceD3D();
	UnregisterClass(_T("Douceur"), wc.hInstance);

	return EXIT_SUCCESS;
}
Ejemplo n.º 9
0
int jeu(SDL_Surface* ecran,int choix,int difficulte,int ArduinoClavier)
{





SDL_Event event; //pour pouvoir gerer les events
SDL_ShowCursor(SDL_DISABLE);//On n'affiche plus le curseur
SDL_Surface *imageDeFond = NULL, *Note = NULL, *Note_do = NULL, *Note_re = NULL, *Note_mi = NULL, *Note_fa = NULL, *Note_sol = NULL, *Note_la = NULL, *Note_si = NULL; //Initialisation des images : on crée un pointeur pour chaque image auquel on met la valeur NULL
SDL_Rect positionFond,positionNote[TAILLE_MAX], positionNote_do,positionNote_re,positionNote_mi,positionNote_fa,positionNote_sol,positionNote_la,positionNote_si; //Initialisation des positions des images

//Initialisation positions x et y
int i; for(i=0;i<TAILLE_MAX;i++)
        {positionNote[i].x=0; positionNote[i].y=0;} //Initialisation de TOUTES les notes du morceau

positionNote_do.y = positionNote_re.y = positionNote_mi.y = positionNote_fa.y = positionNote_sol.y = positionNote_la.y = positionNote_si.y = 658;
positionNote_do.x = 265;
positionNote_re.x = 408;
positionNote_mi.x = 548;
positionNote_fa.x = 690;
positionNote_sol.x = 834;
positionNote_la.x = 973;
positionNote_si.x = 1117;
positionFond.x = 0;
positionFond.y = 0;


imageDeFond = SDL_LoadBMP("images/fond.bmp");//on indique ou est l'image de fond


//Images
Note = SDL_LoadBMP("images/notes/note.bmp") ;
Note_do = SDL_LoadBMP("images/notes/do.bmp");
Note_re = SDL_LoadBMP("images/notes/re.bmp");
Note_mi = SDL_LoadBMP("images/notes/mi.bmp");
Note_fa = SDL_LoadBMP("images/notes/fa.bmp");
Note_sol = SDL_LoadBMP("images/notes/sol.bmp");
Note_la = SDL_LoadBMP("images/notes/la.bmp");
Note_si = SDL_LoadBMP("images/notes/si.bmp");
SDL_SetColorKey(Note, SDL_SRCCOLORKEY, SDL_MapRGB(Note->format, 0,0, 255));//transparence
//

 FILE* fichier = NULL;//pour lire la "partition"




/***********Musique***************
*********************************/

FMOD_SYSTEM *system;
FMOD_SOUND *musique;//musique :/
FMOD_RESULT resultat;
FMOD_System_Create(&system);
FMOD_System_Init(system, 1, FMOD_INIT_NORMAL, NULL);

/* On ouvre la musique en fonction du choix et on ouvre la partition qui correspond (c'est gros pour pas grand chose)*/
switch(choix)
{
    case 0 :
    resultat = FMOD_System_CreateSound(system, "musiques/FrereJacques.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/FrereJacques.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 1 :
    resultat = FMOD_System_CreateSound(system, "musiques/Muse.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Muse.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 2 :
    resultat = FMOD_System_CreateSound(system, "musiques/AuClairDeLaLune.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/AuClairDeLaLune.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 3 :
    resultat = FMOD_System_CreateSound(system, "musiques/Titanic.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Titanic.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 4 :
    resultat = FMOD_System_CreateSound(system, "musiques/MJ.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/MJ.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 5 :
    resultat = FMOD_System_CreateSound(system, "musiques/Clocks.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Clocks.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 6 :
    resultat = FMOD_System_CreateSound(system, "musiques/Laputa.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Laputa.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 7 :
    resultat = FMOD_System_CreateSound(system, "musiques/YMCA.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/YMCA.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 8 :
    resultat = FMOD_System_CreateSound(system, "musiques/Changes.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Changes.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 10 :
    resultat = FMOD_System_CreateSound(system, "musiques/Dancing_in_the_Dark.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Dancing_in_the_Dark.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 11 :
    resultat = FMOD_System_CreateSound(system, "musiques/Born_to_Run.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Born_to_Run.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 12 :
    resultat = FMOD_System_CreateSound(system, "musiques/Bruno Mars.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Bruno Mars.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 13 :
    resultat = FMOD_System_CreateSound(system, "musiques/Bad day.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Bad day.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 15 :
    resultat = FMOD_System_CreateSound(system, "musiques/The Fray.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/The Fray.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 16 :
    resultat = FMOD_System_CreateSound(system, "musiques/Led Zep.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Led Zep.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 17 :
    resultat = FMOD_System_CreateSound(system, "musiques/Naruto.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Naruto.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 18 :
    resultat = FMOD_System_CreateSound(system, "musiques/Somebody to love - Queen.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Somebody to love - Queen.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 19 :
    resultat = FMOD_System_CreateSound(system, "musiques/Viva.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Viva.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    default:
    break;

}


   if (resultat != FMOD_OK)//verification que la musique marche
    {
        fprintf(stderr, "Impossible de lire le fichier audio.wav\n");
        exit(EXIT_FAILURE);
    }

//Bruit pour le fail (on est obligé de créer un autre systeme pour pas arreter la musique)
FMOD_SYSTEM *systemf;
FMOD_SOUND *fail = NULL;
FMOD_System_CreateSound(systemf, "fail.wav", FMOD_CREATESAMPLE, 0, &fail);
FMOD_RESULT resultatf;

    /* Création et initialisation d'un objet système */
    FMOD_System_Create(&systemf);
    FMOD_System_Init(systemf, 1, FMOD_INIT_NORMAL, NULL);

    /* Chargement du son et vérification du chargement */
    resultatf = FMOD_System_CreateSound(system, "fail.wav", FMOD_CREATESAMPLE, 0, &fail);
    if (resultatf != FMOD_OK)
    {
        fprintf(stderr, "Impossible de lire le fichier audio.wav\n");
        exit(EXIT_FAILURE);
    }

 /****************************
 Initialisation pour le texte
 ******************************/
    char caracteres[20] = "",caracteres2[20] = ""; // Tableau de char suffisamment grand pour le score
    TTF_Init(); //Initialisation de la banque de donnée pour le texte
    int compteur=0; //Pour le score
    SDL_Surface *score = NULL;
    SDL_Rect position;
    TTF_Font *police = NULL, *police2 = NULL; //TTF_OpenFont doit stocker son résultat dans une variable de type TTF_Font
    SDL_Color couleurNoire = {0, 0, 0}; //couleur police => noir
    police = TTF_OpenFont("police.ttf", 70);//police choisie, taille police
    police2 = TTF_OpenFont("score.ttf", 70);//police choisie, taille police
//////////////////////////////////////////////

 /***************************************************
        +Lecture du fichier texte (Yacine)
        +On met les notes a leur place (do,ré...)
            en fonction de la difficulté
 **************************************************/



char chaine[TAILLE_MAX]="";
int debut[TAILLE_MAX ];
int note[TAILLE_MAX ];
int tempsFin = 0 ;
 int j=0,compteurNotes=0;
 while (fgets(chaine, TAILLE_MAX, fichier) != NULL) //tant que le fichier n'a pas été totalement parcouru (fgets s'incremente automatiquement)
   {

        ///Easy
       if (difficulte==0){
    if (compteurNotes%3==0)//Pour la difficulté, on ne prend qu'une note sur 3 quand on a choisi l'option facile
            {
                sscanf(chaine, "%d - %d", &debut[j], &note[j]); // recupere la note et la date

switch (note[j])//On met en place les notes
{

   case 0 : //do
        positionNote[j].x = 250;
        break;
   case 1 : //ré
        positionNote[j].x = 395;
        break;
   case 2 : //mi
        positionNote[j].x = 525;
        break;
   case 3 : //fa
        positionNote[j].x = 680;
        break;
   case 4 : //sol
        positionNote[j].x = 820;
        break;
   case 5 : //la
        positionNote[j].x = 960;
        break;
   case 6 : //si
        positionNote[j].x = 1100;
        break;
    case 8 : // Pour la fin
        tempsFin = debut[j];
        positionNote[j].x = 20000;//pour pas afficher la note
   default :
        break;

        }
        j++;
            }
            compteurNotes++;
            }

        ///Normal
       if (difficulte==1){
    if (compteurNotes%2==0)//Pour la difficulté, on ne prend qu'une note sur deux quand on a choisi l'option facile
            {
                sscanf(chaine, "%d - %d", &debut[j], &note[j]); // recupere la note et la date

switch (note[j])//On met en place les notes
{

   case 0 : //do
        positionNote[j].x = 250;
        break;
   case 1 : //ré
        positionNote[j].x = 395;
        break;
   case 2 : //mi
        positionNote[j].x = 525;
        break;
   case 3 : //fa
        positionNote[j].x = 680;
        break;
   case 4 : //sol
        positionNote[j].x = 820;
        break;
   case 5 : //la
        positionNote[j].x = 960;
        break;
   case 6 : //si
        positionNote[j].x = 1100;
        break;
    case 8 : // Pour la fin
        tempsFin = debut[j];
        positionNote[j].x = 20000;//pour pas afficher la note
   default :
        break;

        }
        j++;
            }
            compteurNotes++;
            }

        ///Difficile
        if (difficulte==2){
            //On prend toutes les notes
                    sscanf(chaine, "%d - %d", &debut[j], &note[j]); // recupere la note et la date

switch (note[j])//On met en place les notes
{

   case 0 : //do
        positionNote[j].x = 250;
        break;
   case 1 : //ré
        positionNote[j].x = 395;
        break;
   case 2 : //mi
        positionNote[j].x = 525;
        break;
   case 3 : //fa
        positionNote[j].x = 680;
        break;
   case 4 : //sol
        positionNote[j].x = 820;
        break;
   case 5 : //la
        positionNote[j].x = 960;
        break;
   case 6 : //si
        positionNote[j].x = 1100;
        break;
    case 8 : // Pour la fin
        tempsFin = debut[j];
        positionNote[j].x = 20000;//pour pas afficher la note
   default :
        break;

        }
        j++;
            }


   }


 //////////////////////////////////////////////

int pourcent[TAILLE_MAX] = {0},pourcentFinal=0,totalNotes=0;//Pour le pourcentage de réussite
int k=0;//notes 1,2,3....
int tempsDebut=SDL_GetTicks();//SDL_GetTicks donne le temps qu'il s'est écoulé depuis le lancement du programme, on retire donc le temps qu'il s'est écoulé entre le lancement et le début du morceau
int a=0,z=0,e=0,r=0,t=0,y=0,u=0;//notes
int tempsPrecedent = 0, tempsActuel = 0, tempsNote[7]; //Timer (temps note permet de savoir a quel instant t la note a été jouée
int continuer = 1;

 //Boucle jeu

 if (ArduinoClavier) arduino(1);//On lance arduino pour avoir le numéro port série qui correspond

while (continuer)
{


/* On joue la musique au bon moment de manière à ce qu'elle soit synchronisée avec les notes qui défilent */
if ((tempsActuel>=2700)&&(tempsActuel<=2750))FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, musique, 0,NULL);


    /* On efface l'écran */
SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 255,255, 255));//255,255, 255 veut dire qu'on met un ecran noir
    /* On remet le fond */
SDL_BlitSurface(imageDeFond, NULL, ecran, &positionFond);

tempsActuel = SDL_GetTicks() - tempsDebut; //temps




/************************************************
 + On affiche les notes
 + On fait descendre les notes le long des lignes
    J'ai galeré pour ca !
*************************************************/


    if(tempsActuel>=debut[k+1]) k++; // passage à la note suivante



int l=k;

    do
    {
           if (tempsActuel>=debut[0]) positionNote[l].y= positionNote[l].y+tempsActuel/10*2-tempsPrecedent/10*2;//descente de la note en utilisant le temps comme réference (elle met du coup 2.7sec a desendre) (la condition corrige le bug de la 1ere note)

            if (positionNote[l].y>575) positionNote[l].y=10000; // si la note arrive en bas on la fait "disparaitre"

        SDL_BlitSurface(Note, NULL, ecran, &positionNote[l]);//on affiche les notes
        l--;
    }while(l>=0);



///La boucle do while est la car il faut la faire au moins une fois quand il n'y a qu'un seule note
///Pour afficher les notes précédentes (sinon on a qu'une seule note affichée)


/*Pour sortir du morceau à la fin*/
if (tempsActuel >= tempsFin) continuer = 0;



///


tempsPrecedent = tempsActuel; // comme on utilise le temps pour la boucle d'avant on le met ici (on pourrait le mettre à la toute fin, ce qui serait plus logique mais ici on comprend mieux)



/**************************************************************
*************************************************************
Fonction pour les touches
***********************************************************
**********************************************************/



/******************************************************
Switch pour savoir quelle touche a étée enfoncée. Si
une touche est enfoncée on donne a la variable la valeur
1 et on enregistre le temps a laquelle la note a été
"jouée"
*******************************************************/

SDL_PollEvent(&event);
switch(event.type)
{
case SDL_QUIT:
exit(EXIT_FAILURE);
break;
case SDL_KEYDOWN: /* Si appui sur une touche*/

    switch(event.key.keysym.sym)
    {
        case SDLK_q: //a
        a=1;
        tempsNote[0]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_w: //z
        z=1;
        tempsNote[1]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_e: //e
        e=1;
        tempsNote[2]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_r: //r
        r=1;
        tempsNote[3]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_t: //t
        t=1;
        tempsNote[4]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_y: //y
        y=1;
        tempsNote[5]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_u: //u
        u=1;
        tempsNote[6]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_ESCAPE:
        continuer=0;
        break;
        default:
        break;
    }
break;

}




/*****************************************************************
On a donné à une variable la valeur 1 si l'evenement a été
réalisé, pour que deux évenements soient pris en compte en même
temps on laisse l'action que provoque l'evenement durer 250ms
(on utlise le temps enregistré avant pour savoir quand 250ms
 sont écoulées)
ce qui donne l'impression que les evenements sont simultannés
Si la variable=0, l'action n'est pas réalisée
******************************************************************/
if (a)
    {
        SDL_BlitSurface(Note_do, NULL, ecran, &positionNote_do);
        if(tempsActuel-tempsNote[0]>250) a=0;
    }
if (z)
    {
        SDL_BlitSurface(Note_re, NULL, ecran, &positionNote_re);
        if(tempsActuel-tempsNote[1]>250) z=0;
    }
if (e)
    {
        SDL_BlitSurface(Note_mi, NULL, ecran, &positionNote_mi);
        if(tempsActuel-tempsNote[2]>250) e=0;
    }
if (r)
    {
        SDL_BlitSurface(Note_fa, NULL, ecran, &positionNote_fa);
        if(tempsActuel-tempsNote[3]>250) r=0;
    }
if (t)
    {
        SDL_BlitSurface(Note_sol, NULL, ecran, &positionNote_sol);
        if(tempsActuel-tempsNote[4]>250) t=0;
    }
if (y)
    {
        SDL_BlitSurface(Note_la, NULL, ecran, &positionNote_la);
        if(tempsActuel-tempsNote[5]>250) y=0;
    }
if (u)
    {
        SDL_BlitSurface(Note_si, NULL, ecran, &positionNote_si);
        if(tempsActuel-tempsNote[6]>250) u=0;
    }


/*****************************************************************
Cette partie permet de déterminer quels boutons poussoirs sont enfoncés a partir du nombre
renvoyé par la fonction arduino.
Si un bouton est enfoncé on lui attribue un caractère propre, ainsi lors des tests de succès
cette information sera gérée exactement comme les évènements au clavier.


Bugs  incompréhensibles liés a l'ajout d'arduino:
On ne peux plus quitter la partie en cours (parfois si)
Au début de certains morceaux  des notes bizarres s'affichent
mais cela revient a la normale après 2-3 secondes.


                          Auteur : Yacine Saoudi
******************************************************************/

if (ArduinoClavier)
{

int arduinoIu=0;
arduinoIu=arduino(0);

char boutonArd[8];
sprintf(boutonArd, "%d", arduinoIu);
//on transforme le nombre stocké dans arduinoIu en chaine de caractère.

//cela permet de tester la présence ou non d'un caractère dans celle ci:
if(strstr(boutonArd, "1")!=NULL) a=1;
if(strstr(boutonArd, "2")!=NULL) z=1;
if(strstr(boutonArd, "3")!=NULL) e=1;
if(strstr(boutonArd, "4")!=NULL) r=1;
if(strstr(boutonArd, "5")!=NULL) t=1;
if(strstr(boutonArd, "6")!=NULL) y=1;
if(strstr(boutonArd, "7")!=NULL) u=1;

}



/***********************************************************************
Fonction réussit ou raté (si la note est "jouée" au bon moment)
************************************************************************/


l=k;//on teste toutes les notes qui on étées affichées

    do
    {
        //réussi
        if ((a)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 250))  {compteur++; pourcent[l]=1;} //compteur => score
        if ((z)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 395))  {compteur++; pourcent[l]=1;} //pourcent => la note spécifique l est réussie ou non (1= réussi)
        if ((e)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 525))  {compteur++; pourcent[l]=1;}
        if ((r)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 680))  {compteur++; pourcent[l]=1;}
        if ((t)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 820))  {compteur++; pourcent[l]=1;}
        if ((y)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 960))  {compteur++; pourcent[l]=1;}
        if ((u)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 1100)) {compteur++; pourcent[l]=1;}
        //fail
        /*
        if ((a==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 250)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((z==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 395)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((e==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 525)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((r==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 680)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((t==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 820)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((y==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 960)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((u==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 1100)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL); //son de fausse note
        */
        l--;
    }while(l>=0); //j'aime bien les do while (mêmes raisons qu'au dessus)



/***********************************
Fonction pour le texte, ici le score
et le nom du morceau
************************************/

//En cas d'erreur (plus propre)
if(TTF_Init() == -1)
{

    fprintf(stderr, "Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError());
    exit(EXIT_FAILURE);
}

/*score*/


     /* Écriture du texte dans la SDL_Surface texte en mode Solid (car il change souvent)*/
     sprintf(caracteres, "Score : %d", compteur);
     SDL_FreeSurface(score);//On efface la surface précédente (sinon ca prend 2go de RAM)
     score = TTF_RenderText_Solid(police, caracteres, couleurNoire);

    //Position score//
        position.x = 20;
        position.y = 450;
        SDL_BlitSurface(score, NULL, ecran, &position); /* Blit du texte*/

/*titre*/

   /* Titre en fonction du choix */
   switch (choix)
   {
       case 0 :
       sprintf(caracteres2, "Frère Jacques");
       break;
       case 1 :
       sprintf(caracteres2, "Starlight - Muse");
       break;
       case 2 :
       sprintf(caracteres2, "Au Clair de la Lune");
       break;
       case 3 :
       sprintf(caracteres2, "Titanic");
       break;
       case 4 :
       sprintf(caracteres2, "Black or White - MJ");
       break;
       case 5 :
       sprintf(caracteres2, "Clocks - Coldplay");
       break;
       case 6 :
       sprintf(caracteres2, "Laputa");
       break;
       case 7 :
       sprintf(caracteres2, "YMCA");
       break;
       case 8 :
       sprintf(caracteres2, "Changes");
       break;
       case 10 :
       sprintf(caracteres2, "Dancing in the Dark");
       break;
       case 11 :
       sprintf(caracteres2, "Born to Run");
       break;
       case 12 :
       sprintf(caracteres2, "Just the way you are");
       break;
       case 13 :
       sprintf(caracteres2, "Bad day");
       break;
       case 15 :
       sprintf(caracteres2, "The Fray");
       break;
       case 16 :
       sprintf(caracteres2, "Starway to heaven");
       break;
       case 17 :
       sprintf(caracteres2, "Naruto");
       break;
       case 18 :
       sprintf(caracteres2, "Somebody to love - Queen");
       break;
       case 19 :
       sprintf(caracteres2, "Viva la Vida - Coldplay");
       break;
       default :
       break;
   }

     SDL_FreeSurface(score);//On efface la surface précédente (sinon ca prend 2go de RAM)
     score = TTF_RenderText_Solid(police2, caracteres2, couleurNoire);

    //Position score//
        position.x = 20;
        position.y = 60;
        SDL_BlitSurface(score, NULL, ecran, &position); /* Blit du texte*/


////////////////////////////////////////////////////////////////////////////////////////

/* On met à jour l'affichage */
SDL_Flip(ecran);

if (continuer==0) CloseCOM   ();//On ferme le port série
}

/******************************************************
Fonction pour obtenir le pourcentage de réussite
On utilise la variable pourcent (faire une vraie fonction
                                 de ca serait facile mais
                                 inutile)
Bug a corriger : Si on finit pas le morceau le pourcentage
est faux (narmol)
*****************************************************/

for(totalNotes=0;totalNotes<k;totalNotes++)
{
    if (pourcent[totalNotes]==1) pourcentFinal++;
}
 pourcentFinal=pourcentFinal*100/totalNotes;//on fait le pourcentage (il faut finir le morceau pour que le pourcentage soit juste)





///////////////////////////////////////////
/*Sortie de boucle*/
/////////////////////////////////////////
//Libération de l'espace
    //images
SDL_FreeSurface(imageDeFond);
SDL_FreeSurface(Note);
SDL_FreeSurface(Note_do);
SDL_FreeSurface(Note_re);
SDL_FreeSurface(Note_mi);
SDL_FreeSurface(Note_fa);
SDL_FreeSurface(Note_sol);
SDL_FreeSurface(Note_la);
SDL_FreeSurface(Note_si);
    //pour la musique
FMOD_Sound_Release(musique);
FMOD_Sound_Release(fail);
FMOD_System_Close(system);
FMOD_System_Release(system);

//return compteur;//le score (le pourcentage est plus interessant)
return pourcentFinal;//le pourcentage de réussite
}
int main(int argc, const char *argv[])
{
  // Parse the command line.
  size_t realParams = 0;
  int count = 10;
  bool arrivalTime = false;

  for (size_t i = 1; i < argc; i++) {
    if (argv[i] == std::string("-count")) {
      if (++i > argc) {
        std::cerr << "Error: -count parameter requires value" << std::endl;
        Usage(argv[0]);
      }
      count = atoi(argv[i]);
      if (count < 1) {
        std::cerr << "Error: -count parameter must be >= 1, found "
          << argv[i] << std::endl;
        Usage(argv[0]);
      }
    } else if (argv[i] == std::string("-arrivalTime")) {
      arrivalTime = true;
    } else if (argv[i][0] == '-') {
        Usage(argv[0]);
    } else switch (++realParams) {
      case 1:
        g_arduinoPortName = argv[i];
        break;
      case 2:
        g_arduinoChannel = atoi(argv[i]);
        break;
      default:
        Usage(argv[0]);
    }
  }
  if (realParams != 2) {
    Usage(argv[0]);
  }

  // Construct the thread to handle the photosensor
  // reading from the Ardiuno.
  DeviceThreadVRPNAnalog  arduino(CreateStreamingServer);

  //-----------------------------------------------------------------
  // Wait until we get at least one report from the device
  // or timeout.  Make sure the report sizes are large enough
  // to support the channels we're reading.
  struct timeval start, now;
  vrpn_gettimeofday(&start, NULL);
  size_t arduinoCount = 0;
  std::vector<DeviceThreadReport> r;
  if (g_verbosity > 0) {
    std::cout << "Waiting for reports from Arduino:" << std::endl;
  }
  double lastArduinoValue;
  do {
    r = arduino.GetReports();
    if (r.size() > 0) {
      if (r[0].values.size() <= g_arduinoChannel) {
        std::cerr << "Report size from Arduino: " << r[0].values.size()
          << " is too small for requested channel: " << g_arduinoChannel << std::endl;
        return -3;
      }
      lastArduinoValue = r.back().values[g_arduinoChannel];
    }
    arduinoCount += r.size();

    vrpn_gettimeofday(&now, NULL);
  } while ( (arduinoCount == 0)
            && (vrpn_TimevalDurationSeconds(now, start) < 20) );
  if (arduinoCount == 0) {
    std::cerr << "No reports from Arduino" << std::endl;
    return -5;
  }

  //-----------------------------------------------------------------
  // Construct a RenderManager to use to send images to the screen,
  // and register the display update we'll use to make
  // the images (black or white) to test the rendering latency.
  if (g_verbosity > 0) {
    std::cout << "Run an OSVR server for us to connect to and place"
      << " the photosensor in front of the screen at the location"
      << " whose latency you want to render." << std::endl;
  }
  osvr::clientkit::ClientContext context(
    "com.reliasolve.RenderManagerLatencyTest");
  osvr::renderkit::RenderManager *render =
    osvr::renderkit::createRenderManager(context.get(),"OpenGL");
  if ((render == nullptr) ||
    (!render->doingOkay())) {
    std::cerr << "Could not create RenderManager" << std::endl;
    return 1;
  }

  // Set callback to handle setting up rendering in a display
  render->SetDisplayCallback(SetupDisplay);

  // Open the display and make sure this worked.
  osvr::renderkit::RenderManager::OpenResults ret = render->OpenDisplay();
  if (ret.status == osvr::renderkit::RenderManager::OpenStatus::FAILURE) {
    std::cerr << "Could not open display" << std::endl;
    delete render;
    return 2;
  }

  //-----------------------------------------------------------------
  // Wait a bit for any DirectMode switching/power on to happen.
  vrpn_SleepMsecs(1000);

  //-----------------------------------------------------------------
  // Render a dark scene for half a second and then read the Arduino value
  // to get a baseline for dark.  Half a second is an arbitrary number that
  // should be larger than the latency present in the system.
  // Then render another dark scene right at the end so our vertical
  // retrace timing should be correct for the bright scene.
  g_red = g_green = g_blue = 0;
  render->Render();
  vrpn_SleepMsecs(500);
  r = arduino.GetReports();
  if (r.size() == 0) {
    std::cerr << "Could not read Arduino value after dark rendering" << std::endl;
    delete render;
    return 3;
  }
  double dark = r.back().values[g_arduinoChannel];
  if (g_verbosity > 1) {
    std::cout << "Dark-screen photosensor value: " << dark << std::endl;
  }
  render->Render();

  //-----------------------------------------------------------------
  // Render a bright scene for half a second and then read the Arduino value
  // to get a baseline for bright.  Half a second is an arbitrary number that
  // should be larger than the latency present in the system.
  // Then render another bright scene right at the end so our vertical
  // retrace timing should be correct for the bright scene.
  g_red = g_green = g_blue = 1;
  render->Render();
  vrpn_SleepMsecs(500);
  r = arduino.GetReports();
  if (r.size() == 0) {
    std::cerr << "Could not read Arduino value after bright rendering" << std::endl;
    delete render;
    return 4;
  }
  double bright = r.back().values[g_arduinoChannel];
  if (g_verbosity > 1) {
    std::cout << "Bright-screen photosensor value: " << bright << std::endl;
  }
  double threshold = (dark + bright) / 2;
  if (threshold - dark < 10) {
    std::cerr << "Bright/dark difference insufficient: " << threshold - dark
      << std::endl;
    return 5;
  }
  if (g_verbosity > 1) {
    std::cout << "Threshold photosensor value: " << threshold << std::endl;
  }
  render->Render();

  //-----------------------------------------------------------------
  // Do as many iterations as we're asked for, reporting the latency
  // between when we asked for rendering and when we saw the screen
  // brightness go from below halfway between dark and bright to
  // above halfway between.
  std::vector<double> pre_delays_ms, post_delays_ms;
  for (size_t i = 0; i < count; i++) {
    // Render dark and wait long enough for it to settle.
    // As above, do another render after the sleep so we're running
    // the sytem as if it were rendering every frame.
    g_red = g_green = g_blue = 0;
    render->Render();
    vrpn_SleepMsecs(500);
    r = arduino.GetReports();
    render->Render();

    // Store the time, render bright, store the after-render time,
    // and then wait for the bright to have finished.
    // As above, do another render after the sleep so we're running
    // the sytem as if it were rendering every frame.
    g_red = g_green = g_blue = 1;
    struct timeval pre_render;
    vrpn_gettimeofday(&pre_render, NULL);
    render->Render();
    struct timeval post_render;
    vrpn_gettimeofday(&post_render, NULL);
    vrpn_SleepMsecs(500);
    r = arduino.GetReports();
    render->Render();

    // Find where we cross the threshold from dark to bright and
    // report latency to pre-render and post-render times.
    for (size_t t = 1; t < r.size(); t++) {
      if ((r[t - 1].values[g_arduinoChannel] < threshold) &&
          (r[t].values[g_arduinoChannel] >= threshold)) {
        if (g_verbosity > 1) {
          if (arrivalTime) {
            pre_delays_ms.push_back(vrpn_TimevalDurationSeconds(r[t].arrivalTime, pre_render) * 1e3);
            post_delays_ms.push_back(vrpn_TimevalDurationSeconds(r[t].arrivalTime, post_render) * 1e3);
          } else {
            pre_delays_ms.push_back(vrpn_TimevalDurationSeconds(r[t].sampleTime, pre_render) * 1e3);
            post_delays_ms.push_back(vrpn_TimevalDurationSeconds(r[t].sampleTime, post_render) * 1e3);
          }
          std::cout << "Latency from pre-render: "
            << pre_delays_ms[i]
            << "ms, from post-render: "
            << post_delays_ms[i]
            << std::endl;
        }
        break;
      }
    }
  }

  //-----------------------------------------------------------------
  // Compute and report statistics on the measurements.
  print_stats("Pre-delay (ms)", pre_delays_ms);
  print_stats("Post-delay (ms)", post_delays_ms);

  //-----------------------------------------------------------------
  // We're done.  Shut down the threads and exit.
  return 0;
}