How to write piano program in C/C++ [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to write a C program for piano in which the node of piano is controlled by mouse movement. But as in linux #include<dos.h> and #include<conio.h> is not exist, so i am getting error . Is there any alternative library present in linux for #include<conio.h> and #include<dos.h> ?
I have tried the code following.
#include <dos.h>
#include <graphics.h>
union REGS in, out;
void detect_mouse ()
{
in.x.ax = 0;
int86 (0X33,&in,&out); //invoke interrupt
if (out.x.ax == 0)
printf ("\nMouse Failed To Initialize");
else
printf ("\nMouse was Succesfully Initialized");
}
void showmouse_graphics ()
{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");
in.x.ax = 1;
int86 (0X33,&in,&out);
getch ();
closegraph ();
}
void detect ()
{
int button;
while (!kbhit () )
{
in.x.ax = 3;
int86 (0X33,&in,&out);
button=out.x.bx&7
switch(button)
{
case 1:
print(“left button pressed\n”);
break;
case 2:
print(“right button pressed\n”);
break;
case 4:
print(“middle button pressed\n”);
break;
case 3:
print(“left and right button pressed\n”);
break;
case 5:
print(“left and middle button pressed\n”);
break;
case 6:
print(“right and middle button pressed\n”);
break;
case 7:
print(“all the three buttons pressed\n”);
break;
default:
print(“No button pressed\n”);
}
delay (200); // Otherwise due to quick computer response 100s of words will get print
}
}
void hide_mouse ()
{
in.x.ax = 2;
int86 (0X33,&in,&out);
}
int main ()
{
detect_mouse ();
showmouse_graphics ();
detect ();
hide_mouse ();
return 0;
}

For #include<conio.h> you can use #include <curses.h> which will give you almost all the functionalities. Getchar
For #include<dos.h> it's not usable in any other operating system than DOS and there isn't really something similar with all the functionalities in linux. But you can use usleep(microseconds) in linux when you include #include <unistd.h>.
Or you can use sleep_for in c++:
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono; // nanoseconds, system_clock, seconds
sleep_for(nanoseconds(20));
For Generating Sound, it seems that this post tries to do something similar/could help with your problem:
Generate Sound Frequency using GCC

Related

MBed program gets stuck

I have written some code with the help of Mbed framework, which is either supposed to take user input and then display sensor values or display the value after 15mins. When I try to execute this code, it is getting stuck at line 21 (display.printf("Inside loop\n");).
I am not able to understand why is it so and what is the fix for this problem so that the switch block gets executed. How to I solve this? FYI, although not important, the microcontroller I am using is STM32 bluepill (STM32F103C8T6).
#include "mbed.h"
#include "Sensor_input.h"
#include "Ticker.h"
#include "Dht11.h"
//#include "USBSerial.h"
Serial display(PA_2, PA_3, 9600);
char* a;
Dht11 DhtSensor(PA_4);
Ticker t;
Sensor_input Soil(PB_7, PB_6, 8);
float *SensorData;
void getSensorData();
int main ( void ){
uint8_t choice = 0;
display.printf("Enter 1 or 2:\n1.Greenhouse stats\n2.Return Control to System");
choice = display.putc(display.getc());
while(1){
display.printf("Inside loop\n");
wait_ms(15000);
switch(choice)
{
case 1:
display.printf("Inside case 1");
a = Soil.readTemp();
display.printf("Temperature: %f\n",DhtSensor.getCelsius());
display.printf("Humidity: %f\n",DhtSensor.getHumidity());
display.printf("Soil water content: %c\n ",*a);
break;
case 2:
/*<GreenHouse object>*/
/*Might have to proceed with timer*/
display.printf("Inside case 2");
t.attach(&getSensorData,4500);
display.printf("Temperature: %f\n",a[0]);
display.printf("Humidity: %f\n",a[1]);
display.printf("Soil water content: %c\n ",a[2]);
break;
default:
break;
}
}
}
void getSensorData(){
static float a[3];
a[0]=DhtSensor.getCelsius();
a[1]=DhtSensor.getHumidity();
a[2]=(int)Soil.readTemp();
}
Your switch statement is probably being executed, but always in the 'default' case. You can test this out by putting a print statement in the default.
When you request a char from the display, it will return the input as an ASCII-character. This means, if you enter '1' on the display, it will give you (as the ASCII table says) 0x31 (decimal 49) and not the value of 1. So you have to change your case to "case '1':" or "case 0x31:" and the equivalent for the second case.

UWP C++/CX: Current system time & Stopwatch

So, I am creating a C++ UWP application that when opened, displays current date and time. In addition, I need to also find a way so that I can display the day of the week as well. For the day of the week, I am using this code:
#include <ctime>
#include <time.h>
#include <chrono>
//under Mainpage::Mainpage()
time_t timeObj = time(nullptr);
tm aTime;
localtime_s(&aTime, &timeObj);
String ^ weekofdayout;
switch (aTime.tm_wday)
{
case 1:
weekofdayout = "Monday";
break;
case 2:
weekofdayout = "Tuesday";
break;
case 3:
weekofdayout = "Wednesday";
break;
case 4:
weekofdayout = "Thursday";
break;
case 5:
weekofdayout = "Friday";
break;
default:
weekofdayout = "(NULL)";
break;
}
timetext->Text += weekofdayout;
However, whenever I run it, the textbox returns: (NULL) the default case. I don't know whats causing it.
I have taken the system time before successfully in windows forms c++ with this code:
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) {
DateTime datetime = DateTime::Now;
this->label3->Text = datetime.ToString();}
I was unable to port this over to UWP C++ because I think it uses the system namespace. Any ideas on how I would be able to recreate the same effect in c++?
For the stopwatch, I haven't found any real documentation online regarding UWP C++ stopwatch but I did find this: https://iot-developer.net/windows-iot/uwp-programming-in-c/timer-and-timing/stopwatch It isn't for C++ UWP but it is for C# UWP. I tried to make my own timer with a global function but it just freezes the program until the code is done running:
int seconds = 0;
for (int i = 0; ; i++)
{
seconds++;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
if (stopwatch == false)
{
break;
}
}
return seconds;
I'm pretty stumped, usually, I would find the answer online but due to the low documentation of UWP C++, I have no idea where to find the answer.

How to implement kbhit() and gethch() in C++ on linux [duplicate]

This question already has answers here:
Using kbhit() and getch() on Linux
(5 answers)
Closed 6 years ago.
I'm trying to build a primitive snake game.
The function void Input() calls _kbhit() and _getch()
But the problem is that I can't implement these function 'cause conio.h isn't included in the gcc package in linux. Is there an alternative way to accomplish the tasks of _kbhit() and _getch() without using conio header file ?
void Input() // handle controls
{
if(_kbhit()) // boolean positive if key is pressed
{
switch(_getch()) // gets ascii val of key pressed
{
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver = true;
break;
}
}
}
These functions are sort of "illegal" and are not used anymore in standard C++.
The ncurses library can be helpful.
ncurses, by the way, defines TRUE and FALSE. A correctly configured ncurses will use the same data-type for ncurses' bool as the C++ compiler used for configuring ncurses.
Here is an example illustrating how ncurses could be used like the conio example:
#include <ncurses.h>
int main()
{
initscr();
cbreak();
noecho();
scrollok(stdscr, TRUE);
nodelay(stdscr, TRUE);
while (true) {
if (getch() == 'g') {
printw("You pressed G\n");
}
napms(500);
printw("Running\n");
}
}

My xlib code can listen to keyboard events but it fails for some windows

I have this code to listen to keyboard events of the active window:
#include<X11/Xlib.h>
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
#include <thread>
using namespace std;
#define IR_MODE 8192
#define SHIFT_MODE 16
#define US_MODE 0
static int ErrorHandler (Display *display, XErrorEvent *error)
{
cout<< "An error ocurred. We don't know anything.";
return 0;
}
int main()
{
Display *d = XOpenDisplay(0);
if(d == 0)
{
cout<< "Cannot open display\n";
exit(0);
}
Window root = DefaultRootWindow(d);
XSetErrorHandler(ErrorHandler);
Window current_window;
int rev;
XGetInputFocus(d,&current_window,&rev);
XSelectInput(d,current_window, KeyPressMask | KeyReleaseMask | FocusChangeMask);
while(true)
{
XEvent e;
XNextEvent(d, &e);
switch(e.type)
{
case FocusOut:
XGetInputFocus(d,&current_window,&rev);
if(current_window == PointerRoot || current_window == None)
{
current_window = root;
}
XSelectInput(d,current_window, KeyPressMask | KeyReleaseMask | FocusChangeMask);
break;
case KeyPress:
{
cout<< "key pressed\n";
break;
}
case KeyRelease:
cout<< "key released\n";
break;
}
}
XCloseDisplay(d);//*/
}
It works for many windows. But it fails for some windows, specially for gnome applications, e.g. nautilus. Why does this happen and how can I solve the problem?
The program just tries to listen to keyboard without interfering anything. As if the keyboard is being tapped with a difference: the program doesn't intend to lose language layout info. When a key is pressed, some information including ASCII codes are chosen and attached to the key event according to language layout and then the key event is sent. The program needs the key event with the information attached to it. So The program does not intend to Grab keyboard. It does not care for active or focused window. It just tries to listen to keys even if the program's window is not active. There are programs which check regularly with XQueryKeymap, but I'm not going to use that. Because it uses up CPU and then it will be more than just a fair listener. Also if checking is not frequent some keys may escape.
I guess your program does not work with GTK3 windows which uses xinput2. This is true if GTK3 was built without --disable-xinput.
AFAIK XSelectInput() won't work with xinput2, you need XISelectEvents() for such windows.
Look at meta_core_select_events() function from Mutter sources. It works both for xinput2 and traditional windows. This patch may be also helpful.

Run two functions at the same time [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have two functions. How would i run two functions at the same time? I Know should use threading.
I need a example for Multi Threading . I am using Visual Studio 2010
You can use _beginthread
void CalculatePrimes(void*)
{
// Do something
}
void TransmitFile(void*)
{
// Do domething
}
int main()
{
uintptr_ x = _beginthread(CalculatePrices,0,NULL);
uintptr_ y = _beginthread(TransmitFile,0,NULL);
return 0;
}
If you've got access to C++11 you can use std::thread :
void CalculatePrimes()
{
// Do something
}
void TransmitFile()
{
// Do domething
}
int main()
{
std::thread x(CalculatePrices);
std::thread y(TransmitFile);
// Both function are now running an different thread
// We need to wait for them to finish
x.join();
y.join();
return 0;
}
And, if you want to get down to the metal you can use the CreateThread api :
DWORD WINAPI CalculatePrimes(void *)
{
// Do something
return 0;
}
DWORD WINAPI TransmitFile(void *)
{
// Do something
return 0;
}
int main()
{
HANDLE x=::CreateThread(NULL,0,CalculatePrimes,NULL,0,NULL);
HANDLE y=::CreateThread(NULL,0,CalculatePrimes,NULL,0,NULL);
// Wait for them to finish
::WaitForSingleObject(x,INFINITE);
::WaitForSingleObject(y,INFINITE);
return 0;
}
The MSDN reference for < thread > only goes back to VS2012,not VS2010. You could update to VS2012 (you also need to be running Win 7 or Win 8) Here is a link to a zip of a windows console program written in C that copies a file using two threads, creating a thread to do the writes. It uses windows mutexes and semaphores to implement an inter-thread single linked list messaging interface.
mtcopy.zip
If you are using MFC, you could use AfxBeginThread to create a CWinThread:
UINT SomeFunction(LPVOID pParam)
{
CSomeObject * pObject = (CSomeObject*)pParam;
// do stuff
return 0; // thread completed successfully
}
int main()
{
CSomeObject pObject = new CSomeObject;
AfxBeginThread(SomeFunction, pObject);
...
return 0;
}
For more information, see MSDN for AfxBeginThread.