How do i detect Key release C++ - c++

So i am making a software to help me with an arduino project, it is supossed to be like PUTTY. I programed the arduino to play different notes from Q-I(C4-C5) and the software is supossed to play thoes notes but i need to make it detect when the Key is pressed and released, how do i do that? I searched and found something but it is not working like it's supposed to here is the code:
int main(){
int KeyGet;
while(1)
{
KeyGet = getch();
if (GetKeyState(0x51) & 0x8000)
{
cout<<"key is pressed"<< endl;
}
else if(GetKeyState(0x51)& 0x0001)
{
cout<<"key is released"<< endl;
}
}
return 0;
The program just prints "key is pressed" when i press Q(0x51) and not "key released" as it should, insted it prints "key released" when i press something else other the Q. And i tried GetAsyncKeyState and tried
If (GetKeyState(0x51) != 0)
it still doesent work.

GetKeyState() requires a window and a message loop to keep the state machine updated. But you do not have a message loop. Also, getch() would swallow any key press+release anyway.
Also, GetKeyState(0x51) & 0x0001 is not the right way to detect a key release. That bit is meant for detecting the toggle state of togglable keys like CapsLock, etc.
In your example, you would need to get rid of getch() and use GetAsyncKeyState() instead, eg:
int main(){
bool down = false;
while (1) {
if (GetAsyncKeyState(0x51) < 0) {
if (!down) {
down = true;
cout << "key is pressed" << endl;
}
}
else {
if (down) {
down = false;
cout << "key is released"<< endl;
}
}
Sleep(0);
}
return 0;
}
Otherwise, you can use a WH_KEYBOARD[_LL] hook via SetWindowsHookEx() instead, so you can receive actual key down/up notifications in real-time.

Related

c++ raspberry pi 4 - Get keyboard keys input without enter/validation?

I've been searching for a while, and I don't achieve to find any way to get the input keys of my keyboard, to use them in my program...
Context : I'm starting on robotics, and C++, and I'd simply like to command a motor.
The idea is that "if I press the up arrow, the motor turns, if I press the down arrow, the motor stops" and that's it, no need to validate something or anything like that...
I am with raspbian, through VNC (controlling from my real computer), and the actual code is executed in the terminal.
I'll see later on to make that more complex.
I went through 20 or more pages and didn't find anything helpful... Isn't there an easy way to do something that seems so basically useful?
Some spoke about conio library, but apparently it's outdated, curses/ncurses took its place,but I didn't achieve to find/have anything working...
http://www.cplusplus.com/forum/general/74211/
Create a function to check for key press in unix using ncurses
Capture characters from standard input without waiting for enter to be pressed
This is apparently C code, and not C++, moreover, I don't really understand that...
How to detect key presses in a Linux C GUI program without prompting the user?
This, maybe? But it makes no sense to me (beginner in C++)
How can I get the keyboard state in Linux?
here they speak of "allegro", but apparently, it don't work on the PI 45 yet... and no idea how to install that anyway
http://www.cplusplus.com/forum/general/47357/
Does someone knows a simple little code that I can copy-past to do that, or any way? I'm quite shocked to not have something similar to windows C++ programming where it seems so simple
I mean something like "Keyboard.GetKeyStates(Key)"
I'll continue my research anyway, but please, help !
EDIT :
Apparently, the library SDL (SDL2) can help me do this...
I tried to implement it, it doesn't give any result...
Here is the code I got up to now (I deleted a good part that is useless in here), basically, it's a copy-past from internet SDL official web page :
#include <iostream>
#include <wiringPi.h> //Raspberry pi GPIO Library
#include <cstdio>
#include <csignal>
#include <ctime>
#include <chrono> //library for counting time
#include <thread> //for "this thread sleep"
#include <SDL2/SDL.h> //for getting the keyboard buttons events
bool RUNNING = true; // global flag used to exit from the main loop
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
GPIO Pins definition
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/
int SPser = 13, SPclk = 19, SPrclk = 26; //Define the output pins used
int Optocoupler = 17; //define the input pins used
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
SDL definition
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/
//void PrintKeyInfo( SDL_KeyboardEvent *key );
//void PrintModifiers( SDLMod mod );
//SOME CODE
// Callback handler if CTRL-C signal is detected
void my_handler(int s) {
std::cout << "Detected CTRL-C signal no. " << s << '\n';
RUNNING = false;
}
//###################################################################################
int main(int argc, char *args[]) {
// Initialize wiringPi and allow the use of BCM pin numbering
wiringPiSetupGpio();
//Initialize SDL
if (SDL_Init(SDL_INIT_EVENTS) != 0) {
SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
return 1;
}
else
{
SDL_Log("SDL initialized");
}
SDL_Event event;
// Register a callback function to be called if the user presses CTRL-C
std::signal(SIGINT, my_handler);
while(RUNNING)
{
while( SDL_PollEvent( &event ) )
{
std::cout << "SDL While \n" << '\n';
//When the user presses a key
switch( event.type )
{
case SDL_KEYDOWN:
std::cout << "Key press detected \n" << '\n';
//printf( "Key press detected\n" );
break;
case SDL_KEYUP:
std::cout << "Key release detected \n" << '\n';
//printf( "Key release detected\n" );
break;
default:
break;
}
}
//std::cout << "Works??" << '\n';
/*for( i = 0; i <= 15; i++ )
{
//std::cout << "data input i =" << i << '\n';
if (i==0){
//std::cout << "if array " << i << '\n';
DataArr[i]=1;
DataArr[15]=0;
}
else{
j=i-1;
DataArr[j]=0;
DataArr[i]=1;
//std::cout << "in else i" << i << " and j " << j << '\n';
}
SendData(DataArr);
}*/
}
std::cout << "Program ended ...\n";
}
As I followed "dumbly" the tutorial, this should work, but the while loop is never entered as the "std::cout << "SDL While \n" << '\n';" is never shown...
But, as it achieve to compile, I guess the SDL library was installed correctly and things work...
When executing the code, it writes "SDL initialized", then, nothing... pressing keys do nothing
I'm still not sure how to check if the library is installed correctly, but when I type in de command prompt "sudo apt-get install libsdl2-dev", it shows a few lines and says "0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded"
If you are on linux, you should use termios to stop the buffering
#include <termios.h>
void set_no_buffer()
{
struct termios term;
tcgetattr(0, &term);
term.c_lflag &= ~ICANON;
tcsetattr(0, TCSANOW, &term);
}
and then getchar() to get a character without entering

SDL event.window.windowID vs GetWindowID()

What is the difference between the output of event.window.windowID and SDL_GetWindowID()?
Why is it that std::cout << m_SDLEvent.window.windowID << std::endl;
outputs 1819558491 in console while std::cout << SDL_GetWindowID(m_SDLWindow) << std::endl; outputs 1 ?
How would I achieve getting the right ID of my SDL_Window* in the method below?
void InputManager::Update()
{
SDL_PollEvent(&m_SDLEvent);
switch (m_SDLEvent.type)
{
case SDL_QUIT:
std::cout << m_SDLEvent.window.windowID << std::endl;
SDL_HideWindow(SDL_GetWindowFromID(m_SDLEvent.window.windowID));
break;
}
}
You're seeing garbage window ID because you access an inactive union field. That's undefined behavior.
You can only access m_SDLEvent.window if m_SDLEvent.type == SDL_WINDOWEVENT.
But if m_SDLEvent.type == SDL_QUIT, you have to use m_SDLEvent.quit structure, which has no field for window id (because SDL_QUIT is not specific to a window, but means that the entire application should be closed).
Okay so HolyBlackCat's answer brought me to the right direction.
Instead of using SDL_QUIT (which is the quit event for the entire app, not one window) I should've checked for SDL_WINDOWEVENT_CLOSE which is an SDL_WINDOWEVENT which can be received by m_SDLEvent.window.event instead of m_SDLEvent.type
So the code now looks like this:
void InputManager::Update()
{
SDL_PollEvent(&m_SDLEvent);
if (m_SDLEvent.type == SDL_WINDOWEVENT)
{
switch (m_SDLEvent.window.event)
{
case SDL_WINDOWEVENT_CLOSE:
std::cout << m_SDLEvent.window.windowID << std::endl;
SDL_HideWindow(SDL_GetWindowFromID(m_SDLEvent.window.windowID));
break;
}
}
}
Now std::cout << m_SDLEvent.window.windowID << std::endl; outputs the correct ID.

GetKeyState function?

Why after I press the directional arrow ON, the function GetKeyState continues to give me a value greater than 0?
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
for(int i = 0; i < 1000; ++i)
{
if(GetKeyState(VK_UP))
{
cout << "UP pressed" << endl;
}
else
cout << "UP not pressed" << endl;
Sleep(150);
}
return 0;
}
From the documentation:
The key status returned from this function changes as a thread reads
key messages from its message queue. The status does not reflect the
interrupt-level state associated with the hardware. Use the
GetAsyncKeyState function to retrieve that information.
Since you are not processing messages, you'll want to call GetAsyncKeyState instead.
Test for the key being pressed like this:
if (GetAsyncKeyState(VK_UP) < 0)
// key is pressed
GetKeyState doesn't return a "boolean-like".
Take a look at the documentation :
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
It seems that you need to do :
if (GetKeyState(VK_UP) & 0x8000)
{
//Your code
}
else
{
// Not pressed
}
0x8000 if the result is a short or -127/-128 if the result is a char. Check the "return value" section of the documentation to see what you want
and also, GetKeyState() function, can be used for normal character keys like 'a' ~ 'Z'. (it's not case sensitive)
if (GetKeyState('A' & 0x8000)
{
// code for Pressed
}
else
{
// code for Not Pressed
}

destroyWindow (from opencv) closes all windows and stops c++ program

I'm writing an live video processing program in c++, and want to be able to toggle three windows with the same mjpeg stream, in color, grayscale, and monochrome. I have all the image feeds running, but, since my screen is small, I want to be able to toggle them on and off individually. To do this, I have written the code below, but calling destroyWindow("[windowname]"); stops the whole program, instead. I've already read the documentation, and putting void in front of it doesn't help. Can anybody tell me what I'm doing wrong?
Here's the code (it's in an infinite loop, until the break you see below is called):
imshow("Color", imageColor);
imshow("Monochrome", imageMonochrome);
imshow("Grayscale", imageGrayscale);
int keyPressed = waitKey(0);
if (keyPressed > 0)
{
cout << keyPressed;
cout << "key was pressed\n";
// Press C to toggle color window
if (99 == keyPressed)
{
if (colorOpen)
{
cout << "Color window closed\n";
void destroyWindow("Color");
colorOpen = false;
}
if (!colorOpen)
{
cout << "Color window opened\n";
imshow("Color", imageColor);
colorOpen = true;
}
}
// Press M to toggle monochrome window
if (109 == keyPressed)
{
if (monochromeOpen)
{
cout << "Monochrome window closed\n";
void destroyWindow("Monochrome");
monochromeOpen = false;
}
if (!monochromeOpen)
{
cout << "Monochrome window opened\n";
imshow("Monochrome", imagebw);
monochromeOpen = true;
}
}
// Press G to toggle grayscale window
if (103 == keyPressed)
{
if (grayscaleOpen)
{
cout << "Grayscale window closed\n";
void destroyWindow("Grayscale");
grayscaleOpen = false;
}
if (!grayscaleOpen)
{
cout << "Grayscale window opened\n";
imshow("Grayscale", image);
grayscaleOpen = true;
}
}
// Break out of infinite loop when [ESC] is pressed:
if (27 == keyPressed)
{
cout << "Escape Pressed\n";
break;
}
}
The code you pasted terminates after calling destroyWindow (by running off the end of main). If that's not what you want to happen, write code that does something else after calling destroyWindow. Perhaps you want a loop?

RtMidi MIDI control signals to Ableton Live

I'm trying to write a C++ app using RtMidi to send control signals via my Tascam FireOne MIDI Controller to Ableton Live. So far, I have it successfully sending Note On + Off Signals, Volume Up + Down Signals, etc. via my MIDI Controller to my digital piano using 'a' and 's' keypresses.
// midiout.cpp
#include <iostream>
using namespace std;
#include <signal.h>
#include <windows.h>
#include <conio.h>
#include "RtMidi.h"
int main()
{
std::vector<unsigned char> message;
int i, keyPress;
int nPorts;
char input;
RtMidiOut *midiout = 0;
// midiOUT
try {
midiout = new RtMidiOut();
// Check available ports.
nPorts = midiout->getPortCount();
if ( nPorts == 0 ) {
cout << "No ports available!" << endl;
goto cleanup;
}
// List Available Ports
cout << "\nPort Count = " << nPorts << endl;
cout << "Available Output Ports\n-----------------------------\n";
for( i=0; i<nPorts; i++ )
{
try {
cout << " Output Port Number " << i << " : " << midiout->getPortName(i) << endl;
}
catch(RtError &error) {
error.printMessage();
goto cleanup;
}
}
cout << "\nSelect an output port number :" << endl;
cin >> keyPress;
while( keyPress < 0 || keyPress >= midiout->getPortCount() )
{
cout << "\nIncorrect selection. Please try again :" << endl;
cin >> keyPress;
}
// Open Selected Port
midiout->openPort( keyPress );
keyPress = NULL;
bool done = false;
cout << "Press a key to generate a message, press 'Esc' to exit" << endl;
while(!done)
{
keyPress = _getch();
input = keyPress;
cout << input << " is: " << keyPress << endl;
switch ( keyPress )
{
case 97 :
// Process for keypress = a
// Note On: 144, 60, 90
message.push_back( 144 );
message.push_back( 60 );
message.push_back( 90 );
midiout->sendMessage( &message );
break;
case 115 :
// Process for keypress = s
// Note Off: 128, 60, 90
message.push_back( 128 );
message.push_back( 60 );
message.push_back( 90 );
midiout->sendMessage( &message );
break;
case 27 :
// Process for keypress = esc
done = true;
break;
}
message.clear();
keyPress = NULL;
}
}
catch(RtError &error) {
error.printMessage();
exit( EXIT_FAILURE );
}
cleanup:
delete midiout;
return 0;
}
I tried sending control signals in the same manner as above but this time with control values in the message bytes in place of the note-on or note-off values.
When ableton live is running, I press a key to send a signal but the app locks up and doesn't return to the start of the while loop to receive input from the next keypress.
edit: I've just noticed that even the above code (which usually runs fine) freezes when ableton live is running and I press a key.
further edit: I downloaded a really neat app called MIDI Monitor, which can monitor MIDI data being transferred: http://obds.free.fr/midimon -- my MIDI controller device has two ports -> one for MIDI and one for control. When I'm monitoring control, I can send midi signals and vice versa. However, if, for example, I'm monitoring control and I try to send some CC type data the program locks. Could this be a device driver problem? –
Does anyone know what is going wrong here?
Just one comment - your exception handling is a little weird.
I'd wrap the whole code (initialization and all) in a try/catch(RtError &err) block, and lose most of the other try/catch blocks.
In particular, I don't know what your catch(char * str) stuff will achieve, and you have no catch at all if openPort() throws.
First of all, try sending a different CC and mapping it to some arbitrary control in Ableton, just to see if it's working. The volume controls you are trying to alter behave slightly differently than regular CC's. Specifically, you should check out the MIDI organization's recommended practice for incrementing/decrementing controllers (note that 0x60 == 96), namely when they write:
This parameter uses MSB and LSB separately, with MSB adjusting sensitivity in semitones and LSB adjusting sensitivity in cents. Some manufacturers may even ignore adjustments to the LSB.