Arduino HID keyboard keycodes not working properly - arduino

I'm working on a project where I can use an IR remote to hook up to my PC and control it because I have a projector connected to it that I want a remote for. I've figured out all of the IR remote stuff and have also been able to configure my Arduino UNO as an HID keyboard (I know there are better solutions for HID devices than Arduino UNO but the way I want this set up makes it so I have to use an UNO). However when I try to send key inputs to my PC it acts like its pressing the Control button (for example if I press A on my actual keyboard after pressing a button on the remote it selects everything on the page I am currently on). I've tried a bunch of different keycodes and looked at other people's code and couldn't find where I am going wrong here is the code I have for my project so far:
#include <IRremote.hpp>
#include <HID.h>
#include <IRremote.h>
int RECV_PIN = 7;
uint8_t buf[8] = { 0 };
void setup() {
Serial.begin(9600);
IrReceiver.begin(RECV_PIN, ENABLE_LED_FEEDBACK);
delay(200);
}
void loop(){
if (IrReceiver.decode()) {
int i;
int command = IrReceiver.decodedIRData.command;
IrReceiver.stop();
switch (command) {
case 70:
Serial.println("Volume +");
buf[2] = 0x80;
Serial.write(buf, 8);
break;
/*
There are a bunch more case statements with different IR commands that
correlate to functions I want the remote to do
*/
}
releaseKey();
delay(500);
IrReceiver.start(8000);
IrReceiver.resume();
}
}
void releaseKey() {
buf[0] = 0;
buf[2] = 0;
Serial.write(buf, 8);
}

Removing the line that prints "Volume +" was the solution. That was apparently not a valid command for the HID firmware. Remember to always simplify your code to the simplest possible thing that should work but doesn't, so you can solve problems like that yourself.

Related

my serial port did not show my sensor data properly

Hey i got a bit problem with my Arduino and sensor
Here is what i tried ;
#define USE_ARDUINO_INTERRUPTS true // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h> // Includes the PulseSensorPlayground Library.
#include <SoftwareSerial.h>
SoftwareSerial blue(0,1);
const int PulseWire = 0; // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13; // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;
PulseSensorPlayground pulseSensor;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
blue.begin(9600);
pulseSensor.analogInput(PulseWire);
pulseSensor.blinkOnPulse(LED13); //auto-magically blink Arduino's LED with heartbeat.
pulseSensor.setThreshold(Threshold);
pulseSensor.begin();
}
void loop() {
// put your main code here, to run repeatedly:
int myBPM = pulseSensor.getBeatsPerMinute();
if(myBPM>200){
myBPM-100;
}
if (pulseSensor.sawStartOfBeat()) {
Serial.println(myBPM);
blue.println(myBPM);
}
delay(10);
}
this code I got from the example library and modified it.
so i want to send data to my android using Bluetooth but this sensor kinda ticked me off because whenever i use it with my HC-06 Bluetooth module it suddenly got a hearth beat without i even touching it and it just sends so much data ignoring the delay I set.
I just need to slowly sending data just like a second but the data didn't show up
so anyone can help?
I read your code and I noticed this piece of code
if(myBPM > 200){ myBPM - 100; }
that is poorly written if (I understand correctly) you want to check the size of myBPM and if it is larger than 200 then it should be subtracted 100.
it should be:
myBPM = myBPM - 100; not myBPM - 100;
I hope my answer will help you. Have a nice day!

Trying to build a counter/stopwatch with arduino. is this wired correctly?

i am trying to make a stopwatch and counter project for arduino. Code aside, is this wired correctly?
The top button is to start the stopwatch, second is the button to start the counter (every press increases by one), and the bottom button should be to reset any of them. the green light is to show the stopwatch is selected and blue is to show the counter is selected. the lcd is to display everything obviusly. Also, what is the best way to learn to code this and how long would it take? Thanks.
This is the code as per your requirement. I have defined pins as per above connections. counter mode has minutes and seconds and it does not contain milliseconds as I am encountering problem to implement it. You can suggest me if you have got any way. Counter mode selection button is the same button which is going to be used to increment the counter.
#include <LiquidCrystal.h>
LiquidCrystal mylcd(7,6,5,4,3,2);
int counter_sel=12,stopwatch_sel=11,reset1=10,stopwatch_led=9,counter_led=8;
void setup()
{
mylcd.begin(16,2);
mylcd.setCursor(0,0);
mylcd.print("Counter and ");
mylcd.print("Stopwatch");
delay(1000);
pinMode(counter_sel,INPUT);
pinMode(stopwatch_sel, INPUT);
pinMode(reset1, INPUT);
pinMode(counter_led,OUTPUT);
pinMode(stopwatch_led, OUTPUT);
}
void loop()
{ int state1=digitalRead(counter_sel);
int state2=digitalRead(stopwatch_sel);
if (state1==0) {delay(300); counter(); } // call counter function
else if (state2==0) {delay(300); stopwatch(); } // call stopwatch function
}
void counter()
{ mylcd.clear();
digitalWrite(counter_led,1);
mylcd.setCursor(0,0);
mylcd.print("Counter Mode :");
short int i=0;
while(1)
{
int rst=digitalRead(reset1);
if (rst==0) { delay(300); break;}
int state1=digitalRead(counter_sel);
if (state1==0) { i++; delay(200);}
mylcd.setCursor(0,1);
mylcd.print(i);
}
digitalWrite(counter_led,0);
}
void stopwatch()
{
mylcd.clear();
digitalWrite(stopwatch_led,1);
long int ms=millis();
byte sec=0, mins=0;
mylcd.setCursor(0,0);
mylcd.print("Stopwatch Mode : ");
while(1)
{
mylcd.setCursor(0,1);
int state1=digitalRead(reset1);
if (state1==0){delay(300); break; }
if (sec==59) {mins++; sec=0;}
if ((millis()-ms)>1000) {sec++; ms=millis(); }
mylcd.print(mins);
mylcd.setCursor(3,1);
mylcd.print(":");
mylcd.setCursor(5,1);
mylcd.print(sec);
mylcd.print(":");
//mylcd.print(millis()-ms);
}
digitalWrite(stopwatch_led,0);
}
As much as I can see, and considering what you explained above, the connections are correct. But the thing is you need to make it clear as much as you can, because due to intersecting point in LCD connection, it would be very much harder to debug and resolve the connection problem, for that you must make it neat. To learn to code this stuff there is no rocket science, just use your wisdom, and start reading books, blogs, articles on arduino ide(which is too simple too use), c programming and microcontrollers , and youtube videos are the great source to learn to code, you should have handful experience of c programming, that's all.

How to program own Wifi "Mute" Stomp Box to remote control a Behringer X32 Rack?

I´m totally new to coding, this is even my first post here. Im tryng this because nobody sells what I want/need ;-).
I achived already quite a bit, but at this moment I´m getting lost with a lot of things (I read a lot about coding in general and in special with Arduino the last 8 dayas)... but let me explain first what my intention on this project is:
I want to build a "Stomp Box" to mute a Behringer X32 Rack (wireless) Channels/Mutegroups/Buses, just Mute On/Off.. nothing else.
This Box should have 4-6 "stompers" (buttons), each of this buttons should have a different Mute function.
Also the current state of the Channel/Mutegroup/Bus should be indicated by LED´s green if unmuted or red if muted.
Therfore the box needs to evaulate the current state of the designated Channel/Mutegroup/Bus, because it could change also from other remote devices.
And then switch to the opposite state when pressing/stomping on designated button.
I´d like to have code where I can easily change the action of a button, Like:
button1 = /ch/01/mix/on ,i 1
button2 = /config/mute/1 ,i 1
button3 = /dca/1/on ,i 1
so in case I need a differnt Channel/Mutegroup/Bus for another event simply edit and recode my ESP32 Node Kit
So here is my code I already have:
#include "WiFi.h"
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <SPI.h>
#include <OSCMessage.h> //https://github.com/CNMAT/OSC
#define WIFI_NETWORK "xxxxxxxxxx" //SSID of you Wifi
#define WIFI_PASSWORD "xxxxxxxxxxx" //Your Wifi Password
#define WIFI_TIMEOUT_MS 20000 // 20 second WiFi connection timeout
#define WIFI_RECOVER_TIME_MS 30000 // Wait 30 seconds after a failed connection attempt
int muteOn = 0;// 0=Mute
int muteOff = 1;// 1=Unmute
int input;
WiFiUDP Udp;
const IPAddress outIp (192, 168, 10, 129); //Mixers IP
const unsigned int outPort = 10023; //X32 Port
//variables for blinking an LED with Millis
const int led = 2; // ESP32 Pin to which onboard LED is connected
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 300; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED
void connectToWiFi(){
Serial.print("Zu WLAN verbinden...");
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_NETWORK, WIFI_PASSWORD);
unsigned long startAttemptTime = millis();
while(WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < WIFI_TIMEOUT_MS){
Serial.println(".");
delay(100);
}
if(WiFi.status() != WL_CONNECTED){
Serial.println("Nicht Verbunden!");
//optional take action
}else{
Serial.print("WLAN Verbunden mit ");
Serial.println(WIFI_NETWORK);
Serial.println(WiFi.localIP( ));
}
}
void setup() {
Serial.begin(115200);
connectToWiFi();
Udp.begin(8888);
pinMode(led, OUTPUT);
// Port defaults to 3232
// ArduinoOTA.setPort(3232);
// Hostname defaults to esp3232-[MAC]
// ArduinoOTA.setHostname("myesp32");
// No authentication by default
// ArduinoOTA.setPassword("admin");
// Password can be set with it's md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop(){
ArduinoOTA.handle();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
ledState = not(ledState);
// set the LED with the ledState of the variable:
digitalWrite(led, ledState);
}
input=Serial.read();
if (input=='0'){
// welcher status hat der kanal?
// wenn Kanal gemutet dann unmute und umgekehrt
Serial.println("Mute!");
delay(100);
sendMute(); //send Mute to Mixer
Serial.println("...");
}
if (input=='1'){
Serial.println("UnMute!");
delay(100);
sendUnMute();
Serial.println("...");
}
}
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg("/ch/01/mix/on");
msg.add(muteOn);
Udp.beginPacket(outIp, outPort);
msg.send(Udp); // send the bytes to the SLIP stream
Udp.endPacket(); // mark the end of the OSC Packet
msg.empty(); // free space occupied by message
delay(20);
}
void sendUnMute() {
//the message wants an OSC address as first argument
OSCMessage msg("/ch/01/mix/on");
msg.add(muteOff);
Udp.beginPacket(outIp, outPort);
msg.send(Udp); // send the bytes to the SLIP stream
Udp.endPacket(); // mark the end of the OSC Packet
msg.empty(); // free space occupied by message
delay(20);
}
So I testet this via serial Monitor, when I input "0" and click send, the mixer mutes channel 1 and on input "1" channel 1 becomes unmuted, so far so good... (OSCMessage msg("/ch/01/mix/on"); ... section.
What bothers me here in special is, I had to hardcode the command "/ch/01/mix/on", because I am not able to declare a variable? for this string? I am already so confused that I don´t know if I even have the terms right :-(
BTW: There are a lot solutions out there how to do it with MIDI, but MIDI is not wireles and I think for my project overkill. I also did some some research on github.com/CNMAT/OSC but I don´t get it... (crying)...
I found also a post here, but this didn´t helped either... :-(
Any advice on that how I can reach my goal?--
Any help is much apprceiated... even in German (my native language... )
PS: Yes I´m a begginner and I admit it. But at least I managed how to connect and flash this thing even via OTA in the last 8 days, so please be easy on me.
Not wanting to hardcode your commands is a good instinct.
The Arduino language is C++, which is (mostly) a superset of C. C and C++ use a preprocessor which lets you define constants and test for their presence.
For instance, you could write:
#define CHAN01_MIX_ON_COMMAND "/ch/01/mix/on"
and then use CHAN01_MIX_ON_COMMAND anywhere you want to use that constant, like so:
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg(CHAN01_MIX_ON_COMMAND);
Then if you ever need to change the string "/ch/01/mix/on" you can just change it in one location and not worry about finding every instance of it in your code.
Writing the names in #define statements is a convention people usually follow in order to make it more clear that they're constants.
You have to write the #define line before you use the constant you defined, so putting it at the start of the file (after any #include lines and before your first function) is a good practice. Or if you have several you might put them all in their own file called something like commands.h (the .h means header file)and then include that at the start of any file that needs it like so:
#include "commands.h"
This #include statement would insert the contents of the file commands.h into the file that the statement is in.
When you have several #define statements, keeping them all together in one place (whether it's at the top of the file or in their own file) is also a good practice so that you have one central place to find them and update them if you need to.
Some people will assign the string constant to a variable like so:
char *channel01_mix_on_cmd = "/ch/01/mix/on";
Here char means "a character" - like one letter or number or symbol. The * means pointer to, which lets you use an array of characters. Simple strings in C and C++ are just arrays of characters (or a pointer to the first character), with a special hidden character at the end set to numeric value 0 (not the character '0'). C++ also has a string datatype called std::string and Arduino programs have String but those are both overkill here. They all let you work with strings; String is much easier to use than char * but both have strengths and weaknesses.
Like the #define, you'd also place that outside a function near the start of the file. It defines a global variable that would be available to any function that references it.
You'd also use the variable anywhere they want the string. It's the same idea as using #define, just done slightly differently. For instance:
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg(channel01_mix_on_cmd);
Using a variable here is an attempt to save storage by not having multiple copies of the string. It's not necessary; C/C++ compilers have for a very long time detected this and stored only one copy of the string. It might save space if your code is split into multiple files.
Saving space on CPUs like the ESP32 and ESP8266 is important because they have so little memory. #define is fine here because the compiler does it automatically for you.
You can create the command string with sprintf.
so for example:
#define CHANNELON "on"
#define CHANNELOFF "off"
int channel;
int mute;
char messageString[100];
// some code that calculates the channel number and the mute state:
channel = 1;
mute = 1;
// then check the mute state and create the command string:
if (mute)
{
// to turn off a channel:
sprintf(messageString,"/ch/%02d/mix/%s",channel,CHANNELOFF);
}
else
{
// to turn on a channel:
sprintf(messageString,"/ch/%02d/mix/%s",channel,CHANNELON);
}
// send the command:
OSCMessage msg(messageString);
the %02d will substitute an integer with a zero in front,
if it's smaller than 10 and that is always 2 characters long.
so if channel is 1, the result would be 01

Code upload results in 'USB device has malfunctioned' Windows error

I am having the same problem as described in this post on the Arduino forums. I have a slight deviation in that I am using an Arduino Leonardo, but otherwise the core problem is the same.
Trying to upload a sketch to my board results in Windows stating my 'USB device has malfunctioned and Windows does not recognize it'. The COM port used for the board then disappears, as with the post above.
I tried the solution posted by Louis Davis in the linked post, which allowed me to successfully reset the board and upload a known good sketch. When this is completed, the board is able to be recognised by Windows again, and the COM port reappears; the board can be used without issue.
I have two Leonardos and I have confirmed by replicating steps across both that it is my specific code which is causing the Windows error to appear, not down to a hardware issue.
Could anyone offer pointers on what in the below code is causing this? (Code is fully commented to describe purpose/methods used)
//Code including basic setup/loop and a function I created, asking for readings to be taken from 3 sensors
//when called, and to then assign the results to global variables
//The loop function should then print the global variables in question and wait for a while before repeating
//the process
#include <Wire.h> //using an I2C breakout (accelerometer)
#include "SparkFun_MMA8452Q.h" //accelerometer breakout's library
MMA8452Q accel; //create an instance of this accelerometer
int FSR_pin = A1; //force resistor pin
const int PHOTO_pin = A0; //phototransistor pin
//declare variables to use to take a base reading, to later measure against for changes
int base_PHOTO = 0;
int base_FSR = 0;
byte base_ORIEN = 0; //using the method recommended in the accelerometer's startup page to get orientation
//readings, which they say is passed back as a byte; section 'Reading Portrait/Landscape'
//on this page https://learn.sparkfun.com/tutorials/mma8452q-accelerometer-breakout-hookup-guide
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Wire.begin();
}
void baseReading() {
base_FSR = analogRead(FSR_pin);
base_PHOTO = analogRead(PHOTO_pin);
base_ORIEN = accel.readPL();
}
void loop() {
// put your main code here, to run repeatedly:
baseReading(); //call my own function to get base readings
Serial.println(base_FSR);
Serial.println(base_PHOTO);
Serial.println(base_ORIEN);
delay(5000);
}
int takeReading() {
}
I have taken readings from each sensor individually using test sketches from the component manufacturers; the problem only appeared when I tried to combine them into one bit of code. Here's a hyperlink to the accelerometer breakout guide referenced in the above code.
Solved: The code was missing the line accel.init(); from the setup function.
I first ruled out the FSR & phototransistor I was using, as running code for only these components performed as expected. That left the MMA8452Q's code to look at.
I'd been using the manufacturer's guide as linked above for the accelerometer, and Example #3 (orientation reading) from its library to write my code out; I managed to drop the init and assumed the problem was with the new .readPL method I had put in.
The example code uses .begin instead of .init, and also uses this as part of a print statement, so I didn't immediately catch on that the purpose of its inclusion was the same.
The fixed code is as follows:
//Code including basic setup/loop and a function I created, asking for readings to be taken from 3 sensors when called and assigned to global variables
//The loop function should then print the global variables in question and wait for a while before repeating the process
#include <Wire.h>
#include "SparkFun_MMA8452Q.h"
MMA8452Q accel;
int FSR_pin = A1;
const int PHOTO_pin = A0;
//variables to use to take a base reading, to later measure against for changes
int base_PHOTO = 0;
int base_FSR = 0;
byte base_ORIEN = 0;
void setup() {
Serial.begin(9600);
Wire.begin();
accel.init(); //The new line, which allows this to run as intended
}
void baseReading() {
base_FSR = analogRead(FSR_pin);
base_PHOTO = analogRead(PHOTO_pin);
base_ORIEN = accel.readPL();
}
void loop() {
baseReading();
Serial.println(base_FSR);
Serial.println(base_PHOTO);
Serial.println(base_ORIEN);
delay(5000);
}

'Keyboard' was not declared in this scope - Arduino coding

I'm writing a simple program for an Arduino that will take the input of 2 buttons and output simulated keys for 2 different functions to use in Clone Hero.
Arduino editor (both online and local versions) spit out
'Keyboard' was not declared in this scope
The offline editor asks if Keyboard.h is included... Which it obviously is.
Any ideas why?
// Keyboard - Version: Latest
#include <Keyboard.h>
//btnWhammy is the button to replace whammy bar function
//btnSP is the button to replace star power activation
//Set Clone Hero to register j for whammy and k for star power
//declaring constant integers for the pins on the Arduino
const int btnWhammy = 2;
const int btnSP = 13;
//Declaring integers for the state of the button press
int btnWhammyState = 0;
int btnSPState = 0;
void setup() {
//Initialisation of the pins as inputs
pinMode(btnWhammy, INPUT);
pinMode(btnSP, INPUT);
}
void loop() {
//Setting the button states to the read of the digital pin (LOW is off, HIGH is on)
btnWhammyState = digitalRead(btnWhammy);
btnSPState = digitalRead(btnSP);
//If the whammy button is pressed, send 'j' to the keyboard, wait 100ms then release all keys
if (btnWhammyState == HIGH) {
Keyboard.press('j');
delay(100);
Keyboard.releaseAll();
}
//If the Star Power button is pressed, send 'k' to the keyboard, wait 100ms then release all keys
if (btnSPState == HIGH) {
Keyboard.press('k');
delay(100);
Keyboard.releaseAll();
}
}
This is a classic mistake -- you are probably compiling for a non-Leonardo board, like a Uno. The Keyboard.h library is not included because it is not present for the board you are compiling with.
I took your code and compiled it for Leonardo -- no issues. For Uno, I get the same error as you...
keyboard key was not declared in this scope i found a very simple and working trick of this problem just go to your main file where you declare all other keys that you are facing not declare
#include <DigiKeyboard.h>
#define KEY_UP_ARROW 0x52
#define KEY_DOWN_ARROW 0x51
#define KEY_LEFT_ARROW 0x50
#define KEY_RIGHT_ARROW 0x4F
#define KEY_TAB 0x2B

Resources