text:
CNY70 from 3.3v instead of 5v?
I would like to use a CNY70 with arduino that is not 5v but 3.3v powered. On the web there most tutorials use 5v and 200 + 10k resistors (e.g. here and here). So as far as I understand for 3.3v I would have to use lower ones.
Can someone explain how those 200 or 10k were calculated? How could I use CNY70 with 3.3v (if it's possible at all) ?

That 200R is current limiting resistor. For 5V power supply and 1.3V forward voltage drop on LED that means about 19mA through resistor: If = (5V-1.3V)/200R = 18.5 mA. With 3.3V power supply you'll get about 10mA with the same resistor.

and what about 10k on the transistor ?

That's just a pull-up resistor. It's basically "pick one between 1K and 100K". So even internall pull up resistor on the input should be sufficient. It depends on wire length, its capacitance and so on. Longer lines means stronger pull ups. Well, technically it should match line impedance, so there will be no signal reflections, but it's valid on much higher frequencies.

The CNY70 is just an IR LED and IR Phototransistor.  You can treat the IR LED (emitter) portion of it just like any LED and size the resistor appropriately.
The receiver is just a phototransistor which can operate at anything from about 1V up to 32V with no need to adjust anything.  The resistor used there is merely a pullup resistor.  You can think of the receiver as a button. When enough IR light falls on it it turns "on".
On an Arduino you could even get away without the pullup resistor and use an input in INPUT_PULLUP mode.

I'm total noob, but with 200 resistor, the LED might not get enough current to power up from 3.3 so I should lower it? Or not?

The lower the resistor the brighter the LED will be and the more sensitive the sensor. The higher the resistor the dimmer the LED will be and the less sensitive the sensor. Most people erroneously size the resistor to the maximum current of the LED thinking that is good - however brightness is non-linear, and halving the current doesn't halve the brightness.  You will get about 2/3 the current, but that's still more than enough to "power up" the LED.

Thanks! Must be something else wrong then, I'll double check my wiring


text:
Where do I get the wider arduino pro micro from?
I have a bunch of boards already fabricated for a game controller that uses the arduino pro micro. I ran out of the arduinos and ordered more. But the new ones are 0.6" wide from pin to pin, and my boards are 0.8". I got narrower pro micros. Now that I'm looking for it online they all seem to be the narrower ones. Same pinout, but they have a smaller version of the MEGA32U4. It also had a USB mini connector instead of USB micro, but for my purposes that doesn't really matter.
Does anyone know where I can get the older 0.8" width version?

It's open source. Make them yourself?

Thanks, and I could, but the point was to not have to remake my other boards. I've already updated the controller board to fit the new pro micro size. It would be easier to just make more of them than to build more pro micros. It has fewer components.

If you are going through the trouble of building a custom board, why integrate a development board, i.e. the micro; instead you should just make the boards to implement the AVR chip directly. This is what development boards are for; the micros probably cost 4x or more than the parts on them.

Micro PCB is narrower then Pro Micro PCB

Please add URL's to stuff you refers to!

Where do you live? ebay appear to have some wider ones (https://www.ebay.com/itm/New-Pro-Micro-ATmega32U4-5V-16MHz-Replace-ATmega328-Arduino-Pro-Mini-/191673953805)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How to splitting values in int serial read values
I get values in serial read using the following code,
int32_t bytesSent = 0;

if (mySerial.available()) {
    bytesSent = mySerial.read();
}

Output:
Serial.write(bytesSent); gives -1199/1211 value.
I need to split this value into two values. That should separate using "/" point.
Value 1 - -1199
Value 2 - 1211
The following code is used for char type values separate when numberArray3[20] = "-1199/1211"
    char numberArray3[20];

   int len = strlen(numberArray3);
   int pos = strcspn(numberArray3,"/");

   char First[20];
   char Second[20];

   strncpy(Second, numberArray3+pos+1, len);
   strncpy(First, numberArray3, pos);
   Serial.println(First);
   Serial.println(Second);

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Parse UNIX-time from char[]
I want to parse a large number to sync time on my arduino. For this i send it a string with the current time in Unix time format wich looks somethink like this:

1535441277

For this I just call a php script wich echos the time() function.
But with  string.toInt()I'm unable to parse it. I suppose the number is too large for an int or a long. But I can't put it directly into the setEpoch() method from the RTCzero libary because it accepts as input datatype only uint32_t. So how can I parse large numbers on a system where double isn't implemented. And I don't just try to parse the entire HTTP-Response. I iterate thru the response and at the relevant line I write all the chars into a char-Array. I also have removed the \r and \n chars.

On 32 bit systems, uint32_t is usually the same as unsigned int and unsigned long. You should be able to parse the number using strtoul(), which is quite standard and returns an unsigned long.

Thanks for the quick response. I also found another solution: Before echoing the time remove a large chuck of the time by just removing the current timestamp on the server-side. Later on I add the exact same amount when using the setEpoch() function. I know that's not very elegant but it works for me.

How do you share the time base (that large chunk) between the Arduino and the PC?

@DmitryGrigoryev, subtract epoch time of the first second of this year

So you already have current time set on both Arduino and the PC?

@DmitryGrigoryev, read the question. he gets the time with HTTP GET request to his service on the server

@Juraj I totally don't see that in the question.

@DmitryGrigoryev, It is expert's translation of " I just call a php script wich echos the time() function."

@Juraj But that's the string he's having a hard time parsing in the first place, isn't it? Also, GET request goes from Arduino to the server, and the output of time goes the other way around.


text:
ATmega328P-PU blink example not working
I moved from an Arduino to a bare ATmega328P-PU (to save energy). First I wanted to start a blink-script to verify that it's all working. For this I flashed the bootloader and uploaded the blink-script on the microprocessor. On the arduino the internal pin was successfully blinking. Then I unmounted the ATmega and put it into a breadboard.
I wired everything up. The LED to GND and pin 13, on the other side I put in 5V from a battery, and GND of course. Between the LED and GND I added 220 Ohm and surprisingly if I power it over battery inside the Arduino the internal LED blinks but my own LED (the one with 220 ohms) does not. If I power the arduino over USB both of them blink.
Do you have any ideas on how I can fix this?

Have you attached a 16MHz Crystal with 22 Pico farad capacitors to the Atmega on the breadboard ??? It's essential and you didn't mention this.

Please add your wiring scheme in both of the states when it's blinking succssfully  and when it's not, because it's not very clear what you mean.

I'll do that as soon as I'm at home again. And no I haven't added any of these parts yet. But doesn't the ATmega have an internal 8 MHz clock? How can I use that one?

You will have to "burn the bootloader" to setup the fuses to use the internal 8MHz but if you programed the ATMega328 as an Arduino Uno you will need to attach these components

This might help you alot
The ATMega328 is 8bit AVR microcontroller with a wide variety of things, in order for this IC to work it's essential to have a "Clock Source".as default of Arduino UNO it uses a 16MHz Crystal oscillator with two 22pF capacitors in order to generate the clock signal so, if you took the ATMega328 from the Arduino and put it in a breadboard you should connect these components in order it to work as well as pulling up RESET pin to VCC.
The Atmega328 has a lot of internal calibrated oscillators, from them are 8MHz and 1MHz and alot more, but in order to them to work you need to configure them first by setting up things called "high fuses and low fuses" these control alot of things in the microcontroller from them they determine the clock source.
As how to burn the bootloader to set fuses is not the topic of the question, I won't come to details about it.

Re “a lot of internal calibrated oscillators”: it's actually one oscillator with a programmable prescaler (i.e. frequency divider).

@EdgarBonet Okay maybe I have missed that one ... Thanks for your note. Shall I edit the answer or leave it ?

You may edit if you want. Otherwise do not worry: I am just nitpicking, and yours is a perfectly good answer.


text:
Use 5V SD-Adapter on 3.3V System
I want to use a Catalex Micro SD Card Adapter in Combination with my Arduino MKR GSM 1400. The problem is, that the Arduino uses 3.3V to operate but the SD Adapter needs 5V (or at least 4.5V) to operate properly. Can I just use the 5V output of my Arduino to power the adapter, or will a higher voltage destroy the arduino when using it over a longer period of time? And if so, how can I use my MKR GSM 1400 with a SD-module? Maybe by unsing a step up/down converter in my circuit or just switch to a module that uses 3.3V?

I have seen in several Catalex schematics that show pin 13 of the 74ABT125 is connected directly to GND. This would be correct?

Catalex Micro SD Card Adapter has built-in level converter in a form of 74LVC125A 3-state buffer. This buffer chip needs 1.65 to 3.6V voltage supply. The +5V from your Arduino is lowered to 3.3V by the adapter (as seen in the schematics, just change 74ABT125 to 74LVC125A).
Link to 74LVC125A
Link to Catalex Adapter schematic
To operate the adapter you would need a certain logic level. Your Arduino provides signals with 3.3V level. This fits perfectly to the adapter.
The answer is yes, you can connect your Catalex SD card adapter with your Arduino.
Good luck

So how should I wire it? Just connect to SD-VCC with the 5V output of the Arduino . And put both ground pins together and the arduino won't be affected by this higher voltage because on all the other pins (cs,mosi,miso and sck) it will send all the data with 2V high an 0.8V low? So nothing over 3.3V wich would harm this arduino?

The SD card is a 3.3 V device. The 5 V module with SD card adapter steps down the voltage for powering the card and has logic level conversion for card's SPI pins.
If you want to connect SD card to a 3.3 V board it is better to use a simple breakout board without power and signal conversion.
I do not recommend you to connect a 5 V SPI device to MKR SPI pins without logic level conversion.
EDIT: smajli analyzed in his answer the logic level conversion chip used on the adapter you use. it doesn't output more than 3.3 V and you can use it powered from 5 V. but it is still a workaround.

why is it a workaround if it has even bulit in such a chip? so can i use it safely and no 3.3v electronics can get damaged? of course if the wiring is right

it is a workaround because the voltage conversion is obsolete. you should us an adapter without conversion.

ok, thanks i'll buy a 3.3V sd adapter

You can use the adapter because:

the adapter uses an AMS1117 to generate 3.3V to supply the SD card and the level shifter
the level shifter is a 74LVC125 which uses 3.3V and works with 3.3V (and accepts up to 5V as input level)

The adapter works for 3.3V and 5V systems as long as 5V power is available.


text:
Send big amouts of data to PHP script via gsm module SIM800L
I'm looking for a way to get lots of sensory data from my Arduino Micro to a PHP script.
My current attempt is using the following AT-commands:
Sent: [AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_0.00,m_584,h_42,td_22,d_21x44x54]
Res: [AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_]

As you can see I send a long GET-parameter to my server with shortened parameter Names like t0 for temperature sensor number zero, l for light and so on.
In the response from my SIM800l I get back a string with exactly 63 characters, so I assume there's some lenght limitation there on the SIM-module.
After that command when it tries to finish the HTTP request I get a lot of errors as AT-command responses and no GET data arrives on my script.

I check wheter or not data has arrived with the following function on my server:
ob_start();
echo "Var_dump of GET\n";
var_dump($_GET);

echo "Var_dump of POST\n";
var_dump($_POST);
$vd_res = ob_get_clean();

file_put_contents('postdump.log', $vd_res."\n",FILE_APPEND);

When typing some data directly into the browser it saves my sent data in postdump.log so I'm pretty sure the SIM-module can't handle the given amount of data.
Do you have any idea how I can send bigger amounts of data all at once? For energy saving purposes I would prefer if it would be possible in only a single request.

I get back a string with exactly 63 characters, - I guess you're using SoftwareSerial, and using the silly delay(1000) way of waiting for a response that I see all over the place...?

Do you have any idea how I can send bigger amounts of data all at once? For energy saving purposes I would prefer if it would be possible in only a single request.

Do a POST request. You can send huge amounts of data in the body.

In the response from my SIM800l I get back a string with exactly 63 characters, so I assume there's some lenght limitation there on the SIM-module.

Nope.
I guess you're doing something like:
sendCommand("AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_0.00,m_584,h_42,td_22,d_21x44x54");
delay(1000);
printResponse();

The problem there is that you're relying on the internal buffer of SoftwareSerial (or HardwareSerial if you use a real serial port). You wait for a predefined time for characters to arrive, and then after that time print them out.  The serial code has a 64 byte buffer.
I see that kind of code all over the place, and it's the worst possible way of reading serial. Whoever posted the first instance of such code and started this chain of evil should be taken outside and shot.
Instead you must read the serial properly. Being lazy like that doesn't work.
Read this blog post to learn more about reading serial data properly.

Thank you very much. My problem was in fact the buffer limit. I made a workaround where I would add every GET paramater seperatly in a function and only at the end I made a commit by writing \r\n so it gets interpreted as one big command.

@The_javascript_King, the answer was not about TX buffer

With "buffer limit" I meant the limit given by SoftwareSerial


text:
Can an arduino Uno control led, sound and smoke?
I'm pretty new to this and I've not seen anyone answer this question yet - so I figured I would ask.
I have a vape mod that is set up to expel smoke with a trigger. I want to merge this trigger to the arduino so that the arduino can then have 2 single buttons. One would trigger a specific led set (8 LEDS), the vape mod, and sound through 2 external speakers for about 5 seconds. I'd like the second button would trigger another specific LED set (8), vape mod and sound (through two external speakers) for 3 seconds. I have acquired a 555 chip, which I've researched can control the timing of the triggers yet can't find anything about how much power is needed for these types of things.
If I'm able to have the LEDs, Sound, and Vape mod separately how do I combine these to control them all with a single push of a trigger?
However, again, the main thing I'm wanting to know is if an Arduino Uno can trigger all of these devices at a single time or if it would drain too much power?
Any help is truly appreciated! Also, if there is anything that you think I need to take into consideration that I haven't already - feel free to make suggestions. Like I said, I'm just starting out and I know I should start with simpler projects but I'm just really interested in whether or not this can be done.
All the best,

the arduino can most likely do all of that ... it is impossible to guess for sure because you have provided almost no information about the devices

An Arduino is a microcontroller. It can do all the logic for your project, including the timing. You won't need a 555 timer. However, the Arduino does not output enough current to drive an 8-LED strip or a smoke machine directly. You'll need an external power supply with enough current to drive those things, and will need to rig transistors to switch the power to those things on and off. A high current MOSFET transistor works very well for most DC applications.

If the load is inductive like a motor or relay, you'll likely need a "flyback diode" to protect the transistor from being fried by the surge of reverse current (back EMF) from the inductor. See this link: https://en.wikipedia.org/wiki/Flyback_diode

You'll need to post a lot more details if you want concrete help.

The arduino has more than enough processing power to manage those tasks mentioned. You probably won't need that 555. Playing music is possible as long as the arduino doesn't have to process the file itself. But switching on an external player is no problem (with what so ever circuitry).
The electrical power is another story, you probably will need extra power-supplies, but nobody can say without knowing your exact setup.

Thank you. I apologize.  Everything was delivered today. I can include the set up equipment once I get home. I appreciate the replies.


text:
How to make an arduino webserver over USB? without ethernet shield nor wifi chip
I would like to begin to understand ethernet handshakes by integrating an Ethernet over USB protocol within an arduino mega or nano. Is there something about the ethernet protocol that requires more  components? I know that USB to ethernet adapters exist. In this scenario, it would be more like a USB to arduino webserver experiment, except the arduino webserver would also be providing the IP address to the laptop during the initial handshake.
Shouldnt it be possible to create a simple router from an ATMega2560, where you plug in an arduino to a computer, and the computer is assigned an IP address on the ATMega's network?
Likewise, couldnt you then serve small files from the ATMega to a web browser through this IP connection?
I know this sounds dumb and like over engineering. But i promise i am not crazy and that this could be useful. USB to Ethernet adapters and drivers exist, so i am not sure that there is a hardware limitation. In other words, while ethernet normally requires 4 data lines and USB 2.0 has only 2 data lines, there are still kernel drivers that allow USB to work fine in this way. Likewise the ATMega has only 2 available data lines. So couldnt you begin by simulating a USB to Ethernet device firmware using the ATMega?
A new avenue here that isnt available with Serial connections would be that you could access the ATMega from a web browser, whereas in other driver modes the browser doesnt have the permission to communicate with the Mega.
Why or why not? / How could this be done?

it is unclear what you are talking about ... where would the USB ethernet adapter plug in?

the computer is assigned an IP address on the ATMega's network? This requires that the Arduino also be running a DHCP server. If all you want is to serve small files, why not emulate a USB storage device?

@jsotola There is no Ethernet port nor USB ethernet adapter. There is one connection, from the USB line to the AT Mega.

@Reinderien Yes a DHCP server would be needed, except the server would only have one client. I want the files to be html/javascript, executed through a web browser like chrome or firefox

i guess web browsers can still access File URIs. Still, i am wondering how to do this for learning purposes and other reasons, like is a shield needed? Or can you do it all without one?

https://playground.arduino.cc/Code/SerialIP/

You cannot change what the Arduino's USB does. The USB is not provided by the ATMega2560, but by the USB to UART interface chip.
On a genuine Arduino that may be an ATMega16U2 which could be reprogrammed, but on Chinese clones it most often isn't.
You would need to start with a board that has a real "native" USB connection, such as the Arduino Leonardo (ATMega32U4) or the much more capable (though deprecated) Arduino Due.
Then you would need to create not only the USB "CDC/ECM" device profile, but also the IP stack on top of it to handle the IP data, then a TCP later on top of that to handle the socket data.
The actual CDC/ECM device itself is very simple - much like the CDC/ACM (USB serial) device it's really just a dumb pipe that sends and receives raw Ethernet frames. Interpreting those frames and managing TCP/IP sessions and streams is a far more involved process and would be the bulk of the work. You'd probably want to take an existing standalone IP stack implementation and replace the existing layer 2 code with the CDC/ECM interface instead.
An alternative, as advocated by @Juraj, is to use IP over Serial. This uses a serial protocol (SLIP) to encapsulate the IP frames and has a rudimentary cut-down IP stack in it. However this is old technology and is not well supported by operating systems any more. For example the home versions of Windows no longer have any SLIP support (it used to be provided through "DUNS" - the Dial UP Network Server - which no longer exists).

Try the Web Serial API instead. Example usage.

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

More information is needed. For example, please provide a link to the Web Serial API webpage and then provide a summary of what this API does and how it solves the problem the OP is asking.

I do not see any way using the Web serial API would help the question asker with their goal of  understanding Ethernet handshakes


text:
Are there any standard ways of reporting a runtime error?
I'm new to Arduino but I'm an experienced programmer. I'm wondering if there are any common functions for reporting errors in Arduino programs? For example, in JavaScript we have the alert() function, or on Unix you can write a message to standard error and exit.
Ideally, if the serial port is available then an error message would be printed there, or if there is an LED then maybe we should blink it. This would need to be configurable based on what the programmer wants to do with available hardware.
Looking the example sketches, error reporting seems pretty horrible. I'm wondering if any libraries handle this better?

How you report an error depends entirely on what communication channels you have available and what kind of error reporting is appropriate for your design. There can be no "standard" since every design is different. Welcome to the embedded world. When you have no OS and no screen and keyboard you have to make do with what resources you have.

I myself have resorted to blinking an LED with morse code to indicate different error conditions.

I don't see any reason why there couldn't be a standard macro call that libraries use to set an error condition. (The default implementation could be a no-op.) I guess it doesn't exist, though?

As pointed out by Majenko in a comment, you can hardly define a standard
facility for error reporting when you don't know what kind of I/O
hardware will be available on any particular project. Printing to the
serial port is the most common method though, as it tends to always be
available during the development phase, while the Arduino is tethered to
the development computer. I personally tend to just do something like
Serial.println(F("Error: the warp field coil is busted."));

and be consistent with the error prefix, so that a program receiving
this can tell it's an error by matching the line against /^Error: /.
While it is OK for user code, reporting errors through Serial is
certainly not a good practice for library code. Alas, it is done way
too often in Arduino libraries. I've seen at least one library (don't
remember which one) that allows the user to provide a reference to a
Print object (defaulting to Serial) to be used for this purpose.
This is way better, as it allows the user to handle the error messages
any way she chooses. It is also very easy to turn off the error
reporting altogether by implementing a do-nothing Print, which would
be a /dev/null of sorts.
Note that the avr-libc allows you to print to stderr, as long
as you have first implemented stderr->put... While this method is the
closest you can get to the standards you are used to, it may not be
portable to non-AVR Arduinos. And it is worth noting that we tend to
avoid the printf() family of functions on Arduinos, as they tend to be
quite large compared to the print() and println() methods.


text:
SPI: test by connecting MOSI to MISO
Is it possible to test a SPI connection by wiring the MISO directly to the MOSI pin?  I'm working on a low-level SPI implementation, and I want to check that the library is basically working.  It would be nice to be able to test the connection itself without additional hardware.

If you short MISO to MOSI, make sure there are no other devices connected to the bus.

Do you have an oscilloscope? This can be used to check whether SPI is working.

@EdgarBonet There are no other devices.

@MichaelT I don't unfortunately, might need to get one at some point.

For posterity, the reason my test wasn't working is because the MOSI pin was not set to output mode.

Yes, you can - and it's something I often do when doing low-level electrical testing an SPI interfacce.  For every clock that you send out the data presented on MOSI will get reflected on MISO.  So if you were to (using the Arduino SPI library) do:
uint8_t x = SPI.transfer(0x38);

then x should equal 0x38.
I find this especially useful on systems with remappable pins to confirm that the pins are configured correctly in the board configuration for proper SPI operation.

Great, thanks for confirming.  Based on reading the timing diagram it seemed like it should, but it's not for me.  Now I can know with more certainty that the problem must lie with my code, not with the concept.

Usually the SPI Master clocks data out while the Slave clocks data back in. So if you were sending and receiving 8 bits per transaction you can clock out 8 bits and at the same time clock in 8 bits for a total of 8 clocks.  This is described in this Wikipedia paragraph. That said, often the first 8 clocks are used to transmit a command and an additional 8 clocks are used to retrieve the result.
If you looped MOSI to MISO you would clock in what you clocked out. You would complete the entire transaction in 8 clocks. At a low level I'm thinking this does not matter. But at a higher level the software would have to be re-written to accommodate this weirdness.

Cool.  It won't matter for the higher level programming, I only care about running a very simple test to check that my library works (it currently doesn't, lol).

I find that what you say is a good approach.  That is, beyond the basics of sending / receiving bits of data, these simple serial interfaces such as SPI are often modified.  Some use 8 bit transactions.  Others use 12 or even 16 bits.  Some ignore the received data during transmission of a command.  Others clock in generic information unrelated to the command just to not let the bandwidth go to waste.


text:
LED Matrix Display with dissimilar brightness
So far I have seen in LED matrix related projects that the brightness is controlled in an entirety manner. That means the   brightness of total display can either be reduced or increased. How can we display only a part of the display with more brighter than the remaining matrix? Appreciate if anyone provide some pseudo logic to achieve this.

Let us say the matrix is made of simple grid of LEDs (monochrome) and to control the display using multiplexing technique by shift registers. I agree that the brightness can be controlled by duty cycle if it is a single one. My question is how to achieve dissimilar brightness in a grid LED matrix by PWM/duty cycle methods. For example, if I want to display time in HH:MM pattern in which the HH part of the display to be more brighter than MM part.

There's two options:

Use a matrix driver that supports different brightnesses per pixel, or:
Rapidly display a different arrangement of pixels in quick succession. The pixels that are on more often are brighter.

Option 1 basically does option 2 in hardware.
The theory is simple:  For one LED you can vary the brightness by using PWM - that switches the LED on and off very rapidly. The longer it is on the brighter it appears.
You can do the same with a matrix of pixels. Instead of dealing with one pixel though you are dealing with, in effect, a series of "images". Each "image" has a different combination of pixels. The more "images" you have the greater variation you can get in your pixel brightnesses.
For example if you first display a frame of:
. . . . . . . .
. . # # # # . .
. # . . . . # .
. # . . . . # .
. # . . . . # .
. # . . . . # .
. . # # # # . .
. . . . . . . .

followed by the image:
. . . . . . . #
. . # # # # # .
. # . . . # # .
. # . . # . # .
. # . # . . # .
. # # . . . # .
. # # # # # . .
# . . . . . . .

then you will get a bright circle(ish) shape with a dimmer slash through it.
The only problem with this method is flicker. You have to have your matrix refreshing very fast. The more "images" you have to display in sequence the more it will flicker and the faster you will have to refresh your matrix to compensate.

LED brightness is normally controlled by how long a given LED is lit.  An LED that is on for 70ms and off for 30ms will be brighter then an LED that is on for only 30ms and off for 70ms.
So, the answer is to shorten the amount of time which the LED is on and lethen the time the LED is off for only those LEDs in your display which are to be dimmer.
This is usually referred to as the duty cycle of the LED.  On an Arduino, the PWM or Pulse Width Modulator feature of the embedded processor is normally used to create the duty cycle signal for an LED.

Depends on what LEDs your matrix is made of. One option would be to make it from 'smart' LEDs at each location, such as WS2812B. These are a chip and 3 LEDs in one package, usually a 5050 size SMD package, but they can also be had in thru hole packages, and can be found built up into boards also (look at Sparkfun and Adfruit for examples). Serial data is sent in, with a 0-255 value for each LED, the control chip then drives the 3 LEDs with the PWM level commanded - 0/255 for off, 128/255 for 1/2 on for example, 255/255 for full on.  The data is passed from device to device to load them up, so for example an 8x8 matrix would need 8x8x3 = 192 bytes of data sent in to load the display. The Arduino then doesn't need to do any more until the matrix needs to change.  WS2812B needs some fancy timing to send in 0/1 data in a combined data/clock signal line, options are the Neopixel library or the FastLed.h library for Arduino, to send data in at up to 800 KHz rate. There is also another version of the chip that uses seperate clock and data lines, SPI.transfer I think can be used to send in data even faster.  I don't recall that device's part number off hand, I've not used it.
For premade 8x8 modules using single color LEDs, then as described in other answers  MAX7219 is often used, with 15 levels of brightness available for the whole display.

Short answer: You likely can't, at a hardware level.
The only way you'd be able to do this is to vary the duty cycle of each individual LED in the matrix (the percent of on-time vs. off-time).
The device would have to support that. Edit your question with the model number of the LED matrix you're using and it's spec sheet.
(Note that if you're using a simple grid of LEDs and row/column addressing you could use PWM to get some control over brightness, but you'd probably already be using multiplexing of the LEDs, which makes varying brightness per LED more complex.)


text:
Power supply affecting sensor readings ESP8266 and JSN-SR04T-2.0
I have an ESP8266 Wemos D1R2 Board with a JSN-SR04T-2.0 ultrasonic range finder and everything works perfectly when I have the device connected to my computer USB or via a 12V battery into the onboard regulator via the external power jack. However when I use a 240V AC to 12V DC transformer to power the setup my readings become quite erratic. I have checked the voltage coming out of the power supply (12.48v) and the voltage going to the sensor (3.28V,  I have it coming off the 3.3V pin) and it is the same on each type of power supply so the onboard regulator is working. Can anyone advise what might cause this? The transformer provides 1A which is more than enough as I have measured the peak usage at <100ma

In what sense are your readings "erratic"?  You need to explain.

In the working config I get consistent values for the distance that when converted from the echo time match the tape measure I have between the sensor and the test object. In the erratic version the measurements vary considerably, e.g. for an object 150cm an erratic sample would be 107, 58, 86, 107, 36cm

So the power supply is a switching supply and my sensor is housed in a small aluminium case as it needs to live outdoors and I found that if I connected the case to earth on the same circuit the readings are consistent and correct, I assume this may be something to do with RF from the switching supply don't understand why and could have that totally wrong

The JSN-SR04T-2.0 ultrasonic range finder is rated to 5Volts. giving it 3.3 volts may not be enough. from my limited knowledge it should work if you give it a separate power supply and not depend on the 3.3 volts of the ESP.

According to the datasheet here: https://www.jahankitshop.com/getattach.aspx?id=4635&Type=Product it is rated 3-5V. Note that once I pulled the device out of the aluminium case it has been working fine


text:
MPU9250 with Arduino Nano and Arduino Nano 33 BLE
I am trying to read sensor data from two MPU9250s with both one Arduino Nano and a Arduino Nano 33 BLE using SPI. As for the Arduino nano, I was successful to acquire the sensor data and output it in the serial monitor. However, unlike the old Nano device, the new Nano 33 BLE does not output any sensor readings in its serial monitor. Sometimes and very rarely though, I do receive a couple of readings (usually not more than 1-2 readings), after which no readings are received. Apparently, at least the sensor initialization seems to be always working on the 33 BLE device as my code runs past the Sensor OK messages in the setup routine.
I have been using bolderflight's MPU9250 library for talking to the sensors.
I've also tried reading only one sensor at a time, but that didn't really help, as I still didn't receive sensor readings. I didn't try I2C so far, mainly due to a lack of time.
Any ideas of what to try or why things might have gone wrong are appreciated.
Here's my code:
#include "MPU9250.h"

MPU9250 SENSOR1(SPI, 9);
MPU9250 SENSOR2(SPI, 10);
int status1, status2;

void setup() {
  // serial to display data
  Serial.begin(115200);
  while(!Serial) {}

  // start communication with IMU
  status1 = SENSOR1.begin();
  if (status1 < 0) {
    Serial.println("Sensor 1 error!");
    Serial.println(status1);
    while(1) {}
  }
  Serial.println("Sensor 1 OK");

  status2 = SENSOR2.begin();
  if (status2 < 0) {
    Serial.println("Sensor 2 error!");
    Serial.println(status2);
    while(1) {}
  }
  Serial.println("Sensor 2 OK");
}

void loop() {
  // read the sensor
  SENSOR1.readSensor();
  SENSOR2.readSensor();
  // display the data
  Serial.print("X: ");
  Serial.print(SENSOR1.getAccelX_mss(),6);
  Serial.print(" ");
  Serial.println(SENSOR2.getAccelX_mss(),6);
  Serial.print("Y: ");
  Serial.print(SENSOR1.getAccelY_mss(),6);
  Serial.print(" ");
  Serial.println(SENSOR2.getAccelY_mss(),6);
  Serial.print("Z: ");
  Serial.print(SENSOR1.getAccelZ_mss(),6);
  Serial.print(" ");
  Serial.println(SENSOR2.getAccelZ_mss(),6);
  delay(100);
}

Can the library used with the Nano 33? Old Nano and Nano 33 are not the same

To be honest, that is what I am not really certain of. But from what I understood, it should be... but I might have missed something.


text:
Arduino accepting only alternate characters
I am writing an Arduino code to receive SMS from a SIM800 module and then send the same message back to the sender. My code is as follows:
#include<SoftwareSerial.h>

SoftwareSerial mySerial(9, 10);//Connect to pin 9&10 on GSM module

const byte numChars = 128; //character size
char receivedChars[numChars]; // Store data read from SMS
boolean newData = false; //flag to check if new data has arrived

void setup() {
 Serial.begin(9600);
 mySerial.begin(9600);
 Serial.println("<Arduino is ready>");
 mySerial.println("AT");
 mySerial.println("AT+CMGF=1"); //text mode
 mySerial.println("AT+CNMI=1,2,0,0,0");
 mySerial.println("AT+CSQ"); //Check signal strength
   while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

void loop() {
  //code for checking sms
  scanSMS();
  //Print if a new data arrived
  showNewData();
  delay(25000);
}

void scanSMS() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '#'; //Start and end markers. Eg. SMS body will be sent as #status#
    char endMarker = '#';
    char rc;
    while (Serial.available())
    {
      mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
    }

    while (mySerial.available() > 0 && newData == false) {
      Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port

      rc = mySerial.read();

      if (recvInProgress == true) {
        if (rc != endMarker) {
          receivedChars[ndx] = rc;
          ndx++;
          if (ndx >= numChars) {
            ndx = numChars - 1;
          }
        }
        else {
          receivedChars[ndx] = '\0'; // terminate the string
          recvInProgress = false;
          ndx = 0;
          newData = true;
          }
        }
      else if (rc == startMarker) {
        recvInProgress = true;
      }
    }
}

/*PRINT IF THERE IS A NEW DATA*/
void showNewData() {
 if (newData == true) {
   SendMessage(receivedChars);
 newData = false;
 }
}

/*SEND BACK WHATEVER SMS IS RECEIVED*/
void SendMessage(String receivedChars)
{
  Serial.print("here");
  mySerial.println("AT+CMGS=\"+xxxxxxxxxx\"\r"); // Replace x with mobile number
  mySerial.println("Humidity Alert!");// The SMS text you want to send
  mySerial.print(receivedChars);
   mySerial.println((char)26);// ASCII code of CTRL+Z
}

The issue is that the module seems to receive only alternate characters instead of the whole message. For example, if I send the text #program#, the Arduino will only print porm or rga. Am I missing something here? Any help is highly appreciated.

You wrote:
Serial.write(mySerial.read());
rc = mySerial.read();

Here you are calling mySerial.read() twice, and thus reading two
characters from the port's input buffer. You then forward the first
character through Serial, and process the second one. Note that you
should normally not read two characters unless you have tested that
mySerial.available() >= 2.
You probably want to forward and process one character at a time, thus
only call mySerial.read() once within this loop:
rc = mySerial.read();  // read from mySerial
Serial.write(rc);      // forward through Serial
// now process rc


text:
How to detect when a key is played on a musical keyboard
I have a musical keyboard (Casio CTK3500) which has an USB B to A output. I want to know a way to connect one (or more) of the wires from the USB cable to Arduino so that it can detect when a key is being played on the keyboard (maybe by detecting a voltage change, but I cannot seem to detect enough voltage change to do that).
I don't need to know which key is being played or anything like that. I just want to detect when a key is being played on the keyboard.
Any help is much appreciated.

USB is a complete (and also complex) communication protocol. You cannot just monitor one line for voltage changes. You would need a USB host chip and write the driver software, that is able to handle this specific USB device. That is not an easy and fast task to do. What happens, when you connect the keyboard to a PC? As what kind of device does it enumerate in the device manager (assuming Windows here)? Do you need special drivers for it to work, or does it work with Windows out of the box?

If it behaves like a normal MIDI device on USB, then this question might be relevant

Check out this item entitled 'Get input from USB musical keyboard to Arduino digital input' @ https://forum.arduino.cc/t/get-input-from-usb-musical-keyboard-to-arduino-digital-input/1265142

" I just want to detect when a key is being played on the keyboard." ... then it may be easier to crack open the keyboard and solder some wires between it and the Arduino. But is that what I would do? No, I'd grab a Linux computer (like a Raspberry Pi), install the USB MIDI drivers and monitor the output. The latter would be a lot easier then trying to figure out how to cleverly use an Arduino. And by "clever" I mean surmount all the problems you will encounter using an Arduino. Starting with finding an Arduino with a HOST USB PORT.

if you just want to detect a key press, use the headphone jack; it will have (ac) voltage on it when a key is pressed.

There is absolutely no way you can "detect a voltage change" in a USB signal to tell you whether or not a key is being pressed. The USB protocol is quite complex, see USB communications. Basically zeroes and ones are being transmitted very quickly at at least 1.5 Mbit/s.
The keyboard you mention appears to have a MIDI port. That is much more likely to be usable to see if keys are being pressed.
I did a post a while ago about a MIDI decoder which would let you detect things like that.
Example code here:
//  MIDI_decoder
//
//  Author:  Nick Gammon
//  Date:    11th April 2012.
//  Version: 1.2
//  Released into the public domain.

//  Version 1.1: Amended to allow for repeated parameters to the same channel message
//    eg. 0x90 0x45 0x46 0x47 0x48 does a "note on" for two notes
//  Version 1.2: Removed "repeating" for system messages.
//  Version 1.3: Amended to allow for RealTime messages to be ignored

#include <SoftwareSerial.h>
#include <Streaming.h>

// Plug MIDI into pin D2 (MIDI in serial)

SoftwareSerial midi (2, 3);  // Rx, Tx

#define MESSAGE(which, desc) const char control_ ## which [] PROGMEM = desc;

MESSAGE (0, "Bank Select (MSB)");
MESSAGE (1, "Modulation Wheel or Lever (MSB)");
MESSAGE (2, "Breath Controller (MSB)");
MESSAGE (3, "Undefined (MSB)");
MESSAGE (4, "Foot Controller (MSB)");
MESSAGE (5, "Portamento Time (MSB)");
MESSAGE (6, "Data Entry (MSB) (MSB)");
MESSAGE (7, "Channel Volume (formerly Main Volume) (MSB)");
MESSAGE (8, "Balance (MSB)");
MESSAGE (9, "Undefined:9 (MSB)");
MESSAGE (10, "Pan (MSB)");
MESSAGE (11, "Expression Controller (MSB)");
MESSAGE (12, "Effect Control 1 (MSB)");
MESSAGE (13, "Effect Control 2 (MSB)");
MESSAGE (14, "Undefined (MSB)");
MESSAGE (15, "Undefined (MSB)");
MESSAGE (16, "General Purpose Controller 1 (MSB)");
MESSAGE (17, "General Purpose Controller 2 (MSB)");
MESSAGE (18, "General Purpose Controller 3 (MSB)");
MESSAGE (19, "General Purpose Controller 4 (MSB)");
MESSAGE (20, "Undefined:20 (MSB)");
MESSAGE (21, "Undefined:21 (MSB)");
MESSAGE (22, "Undefined:22 (MSB)");
MESSAGE (23, "Undefined:23 (MSB)");
MESSAGE (24, "Undefined:24 (MSB)");
MESSAGE (25, "Undefined:25 (MSB)");
MESSAGE (26, "Undefined:26 (MSB)");
MESSAGE (27, "Undefined:27 (MSB)");
MESSAGE (28, "Undefined:28 (MSB)");
MESSAGE (29, "Undefined:29 (MSB)");
MESSAGE (30, "Undefined:30 (MSB)");
MESSAGE (31, "Undefined:31 (MSB)");
MESSAGE (32, "Bank Select (LSB)");
MESSAGE (33, "Modulation Wheel or Lever (LSB)");
MESSAGE (34, "Breath Controller (LSB)");
MESSAGE (35, "Undefined:35 (LSB)");
MESSAGE (36, "Foot Controller (LSB)");
MESSAGE (37, "Portamento Time (LSB)");
MESSAGE (38, "Data Entry (LSB)");
MESSAGE (39, "Channel Volume, formerly Main Volume (LSB)");
MESSAGE (40, "Balance (LSB)");
MESSAGE (41, "Undefined:41 (LSB)");
MESSAGE (42, "Pan (LSB)");
MESSAGE (43, "Expression Controller (LSB)");
MESSAGE (44, "Effect control 1 (LSB)");
MESSAGE (45, "Effect control 2 (LSB)");
MESSAGE (46, "Undefined:46 (LSB)");
MESSAGE (47, "Undefined:47 (LSB)");
MESSAGE (48, "General Purpose Controller 1 (LSB)");
MESSAGE (49, "General Purpose Controller 2 (LSB)");
MESSAGE (50, "General Purpose Controller 3 (LSB)");
MESSAGE (51, "General Purpose Controller 4 (LSB)");
MESSAGE (52, "Undefined:52 (LSB)");
MESSAGE (53, "Undefined:53 (LSB)");
MESSAGE (54, "Undefined:54 (LSB)");
MESSAGE (55, "Undefined:55 (LSB)");
MESSAGE (56, "Undefined:56 (LSB)");
MESSAGE (57, "Undefined:57 (LSB)");
MESSAGE (58, "Undefined:58 (LSB)");
MESSAGE (59, "Undefined:59 (LSB)");
MESSAGE (60, "Undefined:60 (LSB)");
MESSAGE (61, "Undefined:61 (LSB)");
MESSAGE (62, "Undefined:62 (LSB)");
MESSAGE (63, "Undefined:63 (LSB)");
MESSAGE (64, "Damper Pedal on/off (Sustain): < 64 is off, otherwise on");
MESSAGE (65, "Portamento On/Off: < 64 is off, otherwise on");
MESSAGE (66, "Sostenuto On/Off: < 64 is off, otherwise on");
MESSAGE (67, "Soft Pedal On/Off: < 64 is off, otherwise on");
MESSAGE (68, "Legato Footswitch: < 64 is Normal, otherwise Legato");
MESSAGE (69, "Hold 2: < 64 is off, otherwise on");
MESSAGE (70, "Sound Controller 1 (default: Sound Variation) (LSB)");
MESSAGE (71, "Sound Controller 2 (default: Timbre/Harmonic Intens.) (LSB)");
MESSAGE (72, "Sound Controller 3 (default: Release Time) (LSB)");
MESSAGE (73, "Sound Controller 4 (default: Attack Time) (LSB)");
MESSAGE (74, "Sound Controller 5 (default: Brightness) (LSB)");
MESSAGE (75, "Sound Controller 6 (default: Decay Time - see MMA RP-021) (LSB)");
MESSAGE (76, "Sound Controller 7 (default: Vibrato Rate - see MMA RP-021) (LSB)");
MESSAGE (77, "Sound Controller 8 (default: Vibrato Depth - see MMA RP-021) (LSB)");
MESSAGE (78, "Sound Controller 9 (default: Vibrato Delay - see MMA RP-021) (LSB)");
MESSAGE (79, "Sound Controller 10 (default undefined - see MMA RP-021) (LSB)");
MESSAGE (80, "General Purpose Controller 5 (LSB)");
MESSAGE (81, "General Purpose Controller 6 (LSB)");
MESSAGE (82, "General Purpose Controller 7 (LSB)");
MESSAGE (83, "General Purpose Controller 8 (LSB)");
MESSAGE (84, "Portamento Control (LSB)");
MESSAGE (85, "Undefined:85");
MESSAGE (86, "Undefined:86");
MESSAGE (87, "Undefined:87");
MESSAGE (88, "High Resolution Velocity Prefix (LSB)");
MESSAGE (89, "Undefined:89");
MESSAGE (90, "Undefined:90");
MESSAGE (91, "Effects 1 Depth");
MESSAGE (92, "Effects 2 Depth (formerly Tremolo Depth)");
MESSAGE (93, "Effects 3 Depth");
MESSAGE (94, "Effects 4 Depth (formerly Celeste [Detune] Depth)");
MESSAGE (95, "Effects 5 Depth (formerly Phaser Depth)");
MESSAGE (96, "Data Increment (Data Entry +1) (see MMA RP-018)");
MESSAGE (97, "Data Decrement (Data Entry -1) (see MMA RP-018)");
MESSAGE (98, "Non-Registered Parameter Number (NRPN) - (LSB)");
MESSAGE (99, "Non-Registered Parameter Number (NRPN) - (MSB)");
MESSAGE (100, "Registered Parameter Number (RPN) - (LSB)");
MESSAGE (101, "Registered Parameter Number (RPN) - (MSB)");
MESSAGE (102, "Undefined:102");
MESSAGE (103, "Undefined:103");
MESSAGE (104, "Undefined:104");
MESSAGE (105, "Undefined:105");
MESSAGE (106, "Undefined:106");
MESSAGE (107, "Undefined:107");
MESSAGE (108, "Undefined:108");
MESSAGE (109, "Undefined:109");
MESSAGE (110, "Undefined:110");
MESSAGE (111, "Undefined:111");
MESSAGE (112, "Undefined:112");
MESSAGE (113, "Undefined:113");
MESSAGE (114, "Undefined:114");
MESSAGE (115, "Undefined:115");
MESSAGE (116, "Undefined:116");
MESSAGE (117, "Undefined:117");
MESSAGE (118, "Undefined:118");
MESSAGE (119, "Undefined:119");
MESSAGE (120, "All Sound Off");
MESSAGE (121, "Reset All Controllers");
MESSAGE (122, "Local Control On/Off: 0 off, 127 on");
MESSAGE (123, "All Notes Off");
MESSAGE (124, "Omni Mode Off (+ all notes off)");
MESSAGE (125, "Omni Mode On (+ all notes off)");
MESSAGE (126, "Mono Mode On (+ poly off, + all notes off)");
MESSAGE (127, "Poly Mode On (+ mono off, +all notes off)");

const char * const messagesTable [128] PROGMEM =
{
control_0, control_1, control_2, control_3, control_4,
control_5, control_6, control_7, control_8, control_9,
control_10, control_11, control_12, control_13, control_14,
control_15, control_16, control_17, control_18, control_19,
control_20, control_21, control_22, control_23, control_24,
control_25, control_26, control_27, control_28, control_29,
control_30, control_31, control_32, control_33, control_34,
control_35, control_36, control_37, control_38, control_39,
control_40, control_41, control_42, control_43, control_44,
control_45, control_46, control_47, control_48, control_49,
control_50, control_51, control_52, control_53, control_54,
control_55, control_56, control_57, control_58, control_59,
control_60, control_61, control_62, control_63, control_64,
control_65, control_66, control_67, control_68, control_69,
control_70, control_71, control_72, control_73, control_74,
control_75, control_76, control_77, control_78, control_79,
control_80, control_81, control_82, control_83, control_84,
control_85, control_86, control_87, control_88, control_89,
control_90, control_91, control_92, control_93, control_94,
control_95, control_96, control_97, control_98, control_99,
control_100, control_101, control_102, control_103, control_104,
control_105, control_106, control_107, control_108, control_109,
control_110, control_111, control_112, control_113, control_114,
control_115, control_116, control_117, control_118, control_119,
control_120, control_121, control_122, control_123, control_124,
control_125, control_126, control_127
};  // end of messagesTable

const int noRunningStatus = -1;

int runningStatus;
unsigned long lastRead;
byte lastCommand;

void setup() {
  //  Set MIDI baud rate:
  midi.begin(31250);
  Serial.begin(115200);
  Serial.println ();
  Serial.println (F("MIDI Decoder. Author: Nick Gammon."));
  runningStatus = noRunningStatus;
} // end of setup

void RealTimeMessage (const byte msg)
  {

  } // end of RealTimeMessage

// get next byte from serial (blocks)
int getNext ()
  {

  if (runningStatus != noRunningStatus)
    {
    int c = runningStatus;
    // finished with look ahead
    runningStatus = noRunningStatus;
    return c;
    }

  while (true)
    {
    while (midi.available () == 0)
      {}
    byte c = midi.read ();
    if (c >= 0xF8)  // RealTime messages
      RealTimeMessage (c);
    else
      return c;
    }
  } // end of getNext

const char * notes [] = { "C ", "C#", "D ", "D#", "E ", "F ", "F#", "G ", "G#", "A ", "A#", "B " };

// interpret a note in terms of note name and octave
const char * getNote ()
  {
  byte note = getNext ();
  byte octave = note / 12;
  Serial << notes [note % 12] << F("(") << _DEC (octave - 1) << F(")");
  return " ";
  }  // end of getNote

// dump a system exclusive message in hex
void showSystemExclusive ()
  {
  int count = 0;
  while (true)
    {
    while (midi.available () == 0)
      {}
    byte c = midi.read ();
    if (c >= 0x80)
      {
      Serial << endl;
      runningStatus = c;
      return;
      }

    Serial << _HEX (c) << " ";
    if (++count > 32)
      {
      Serial << endl;
      count = 0;
      }
    } // end of reading until all system exclusive done
  }  // end of showSystemExclusive

/* Print a string from Program Memory directly to save RAM */
void printProgStr (const char * str)
{
  char c;
  if(!str) return;
  while((c = pgm_read_byte(str++)))
    Serial.print(c);
} // end of printProgStr

// show a control message by looking up in the table
void showControlMessage ()
  {
   byte message =  getNext () & 0x7F;
   byte param = getNext ();
   // get address from progmem, display each byte
   printProgStr ((const char *) pgm_read_word(&(messagesTable[message])));
   // show parameter in hex
   Serial << ": 0x" << _HEX (param) << endl;
  }  // end of showControlMessage

void loop()
{
  byte c = getNext ();

  if (((c & 0x80) == 0) && (lastCommand & 0x80))
    {
    runningStatus = c;
    c = lastCommand;
    }

  // channel is in low order bits
  int channel = (c & 0x0F) + 1;

  // show time since last message in microseconds
  char buf [15];
  ltoa (micros () - lastRead, buf, 10);
  byte spaces = 10 - strlen (buf);
  for (byte i = 0; i < spaces; i++)
    Serial << " ";

  // show elapsed time
  Serial << buf << ": ";
  lastRead = micros ();

  // messages start with high-order bit set
  if (c & 0x80)
    {
    lastCommand = c;
    switch ((c >> 4) & 0x07)
      {
      case 0:
        Serial << F("Note off channel = ") << channel << F(", note = ") << getNote () << F(", velocity = ") << getNext () << endl;
        break;

      case 1:
        Serial << F("Note  on channel = ") << channel << F(", note = ") << getNote () << F(", velocity = ") << getNext () << endl;
        break;

      case 2:
        Serial << F("Polyphonic pressure channel = ") << channel << F(", note = ") << getNote () << F(", pressure = ") << getNext () << endl;
        break;

      case 3:
        Serial << F("Control change channel = ") << channel << ", ";
        showControlMessage ();
        break;

      case 4:
        Serial << F("Program change channel = ") << channel << F(", program = ") << getNext () << endl;
        break;

      case 5:
        Serial << F("After-touch pressure channel = ") << channel << F(", value = ") << getNext () << endl;
        break;

      case 6:
        Serial << F("Pitch wheel change channel = ") << channel << F(", value = ") << (getNext () | getNext () << 7) << endl;
        break;

      case 7:  // system message
        {
        lastCommand = 0;           // these won't repeat I don't think
        Serial << "System: ";
        switch (c & 0x0F)
          {
          case 0:
            Serial << F("Exclusive (in hex)") << F(", vendor ID = ") << getNext () << endl;
            showSystemExclusive ();
            break;

          case 1:
            Serial << F("Time code: value/type = ") << getNext () << endl;
            break;

          case 2:
            Serial << F("Song position pointer, value = ") << (getNext () | getNext () << 7) << endl;
            break;

          case 3:
            Serial << F("Song select, song = ") << getNext () << endl;
            break;

          case 4:
            Serial << F("Reserved (4)") << endl;
            break;

          case 5:
            Serial << F("Reserved (5)") << endl;
            break;

          case 6:
            Serial << F("Tune request") << endl;
            break;

          case 7:
            Serial << F("End of exclusive") << endl;
            break;

          case 8:
            Serial << F("Timing clock") << endl;
            break;

          case 9:
            Serial << F("Reserved (9)") << endl;
            break;

          case 10:
            Serial << F("Start") << endl;
            break;

          case 11:
            Serial << F("Continue") << endl;
            break;

          case 12:
            Serial << F("Stop") << endl;
            break;

          case 13:
            Serial << F("Reserved (13)") << endl;
            break;

          case 14:
            Serial << F("Active sensing") << endl;
            break;

          case 15:
            Serial << F("Reset") << endl;
            break;

          }  // end of switch on system message

        }  // end system message
        break;
      }  // end of switch
    }  // end of if
  else
    Serial << _HEX(c) << endl;

}  // end of loop

You need a modest amount of hardware to convert the MIDI signal into something you can plug into the Arduino.


text:
What sensors to measure grass growth?
I would like to make a small project, which would allow me to recognize if the grass has grow enough to lawn. I don't know too much the ecosystem of available sensors for such problem. And I have a lot of grass and some irregular areas to clean once in a while.
Is that something I can do with an arduino and some sensors, or should I need to use more processing power and cameras/AI?
TIA!

measure the grass indirectly ... keep track of the weather and of the irrigation schedule

@jsotola that seems a quite complex model to implement, depending on a lot of variables, which in final terms is more expensive than using some cheap sensors.

My idea: Two light sensors on a short stick embedded in the ground. If the top sensor detects light, but the bottom one does not it means that it's daytime, and grass is long enough that it covered the bottom sensor. You will probably need several of those, because there is no guarantee that grass will actually cover the bottom sensor, and you will need to filter out random elements by testing if values don't change to much.

That's an idea. In fact we could just need one that's not covered by the grass, to contrast the light of all others that could be at ground level...

I think having them in close proximity pairs would be better for detecting things like building shadow at the end of the day or a dog laying on the grass for an hour.

might not work in the real world because the lens will be dirty in a month or so.

Be sure not to mow only the gras not the sensors :D


text:
Repair Arduino with too much voltage exposure
I have used the 5V pin instead of the Vcc pin to operate some sensors on the Arduino MKR GSM 1400. Altough the operating voltage is 3.3V.Because of that it doesn't work properly anymore, some analog sensor values are clearly wrong and the GSM module works only occasionally. Is there any way to repair this myself or send is somewhere, or should I buy a new one?

some analog sensor values are clearly wrong ... are you sure? .... you gave inadequate information

Unless you tell exactly what you did, it’s hard to say which part might have been damaged. Connecting 5V to some external sensor in itself isn’t a problem.

I put 5V into an input pin. But only 3.3v are allowed

Buy a new one. Anywhere willing to repair such a thing would probably charge 10x the value of the product in time alone.

Feeding 5 volts into an input most likely cause the protection diode on that input to conduct the 5 volts onto the 3.3 volt supply. That in turn would exceed the voltage on all the 3.3 volt connected parts. Likely to cause more damage than just to the affected input.
The cost of shipping and labour to repair the board would exceed the cost of buying a new replacement board. A repair would require too many parts to be replace. And replacement would be required of even parts that might appear to work because the risk of failure would be high.
Buy a new board and be confident that it will work.


text:
Updating ATmega16u2
I have the UNO Mini Strong from www.diymore.cc.
I am having the issue of keyboard.h not being recognized.
I have been trying to find the firmware mentioned in https://www.arduino.cc/en/Hacking/DFUProgramming8U2 from here https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/firmwares/atmegaxxu2 but, page is gone!
Does anyone know where the firmware can be found and should this work on the board I am trying to use?

I tried to make a little research and it looks that the hardware folder was cleared (see here).
The json file made me think that now this is shipped like libraries, so through a dedicated package which gets downloaded later.
Consequently I checked in the installation folder and... there it is!
In the folder <arduino install dir>\hardware\arduino\avr\firmwares\atmegaxxu2 you will find a lot of hex files (e.g. Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex)
I checked on my portable installation of arduino 1.8.5, but it should be there also for installed versions

Great. I found the file. I'll update later on the outcome. Thank you.

While I was researching the DFU programming, I found this, https://github.com/NicoHood/HoodLoader2/wiki which I believe is exactly what I need. Check the example for Serial Keyboard. I will not be able to set this up until next week. I'll post an update.


text:
HX711 with NodeMcu
I am trying to make a scale that measuring weight. In internet i did some researches so i got some questions.
I have this module as a HX711
And square 3 wired loadcells( Red,White,Black Wired).
My mcu is Noedmcu V3. When i check from the Visual Studio Code, it says Adafruit Huzzah. This MCU's operation voltage is 3.3v and got ESP8266EX chip.
Some Hx711 modules (ex. sparkfun red board) got VDD pin for logic level. But my module has not. Can i operate this hx711 and loadcell with 3.3 volts?
If i cant, i can use 5volts for excitation voltages but communication will be on 5Volts. My mcu operating on 3.3volts. can i add voltage divider to  DT,SCK pins to regulate voltage around 3.3volts? Is it proper solution?
Or if you have any hint about that, can you share with me?

Vdd pin is for a power connection, not for a logic signal .. it can also be labeled as Vcc ... use the datasheet to determine the required power supply voltage

My hx 711 has no vdd. Only has vcc. In sparkfuns hook up guide  They said :
Note: VCC is the analog voltage to power the load cell. VDD is the digital supply voltage used to set the logic level. PRO TIP: In many cases, you can just short VCC and VDD together. If your microcontroller uses 3.3V logic however, you'll want to connect VCC to 5V and VDD to 3.3V.
But my question is I have 3.3volt mcu and hx 711 wants 5volt. Can i use voltage divider for DT and SCK lines to decrease voltage to 3.3 volts.

i have the same issue. tried modifying the board to separate VCC and VDD (they are connected by a copper trace hidden under the chip) but it did not work. It seems the chip does not care for VCC pin (pin 1 on datasheet) and only listens to VDD


text:
Spiffs vs Eeprom on esp8266
In my project, i have some data to save permanently. After some research i got many examples and informations to do that with eeprom. I used it effectively.
After all i decide to deep dive to esp8266 and i got some information about spiffs.
Now i know what spiffs is and what its purpose. But i am wondering what is difference between eeprom vs spiffs?
I know both of them using flash memory as same and we can write and store data with them but why spiffs? Why eeprom ? What are their pros and cons or etc.?

Thanks for the answers. I completed some missing parts about it

I don't think it makes any difference from a hardware point of view. The benefits of using the eeprom library is that it avoids rewriting unchanged data (if you use spiffs you might want to implement that as well) and that the esp is compatible with the arduino environment, where there is a real eeprom.
On the other hand, SPIFFS has its advantages (e.g. easy upload, space). It's up to you...

On the ESP8266 there's very little to choose from between the two. It all really boils down to what you want to store and how you best want to access it.
EEPROM emulation is ideal for small bits of data - configuration values and that sort of thing. Where you just want to store a few of values that would seldom change.
SPIFFS though is better at dealing with large amounts of data. Since it's a filesystem it can store actual files, and that makes it ideal for serving images and static data for web pages, for example.
A SPIFFS filesystem can be built on your PC from files of your choice and then uploaded over serial using mkspiffs and esptool.py or the SPIFFS tool that can be installed into the Arduino IDE. That means the files are very easy to update.
SPIFFS is not so great when it comes to writing data though - experiments have shown that it gets quite slow when writing often.  EEPROM doesn't suffer from such a problem, but then you can't write as much data to EEPROM as you can to SPIFFS.
So that's really all there is to it. Neither is "better" than the other, but each is better suited to different ways of working or to different styles of data.

If I save measured data as CSV with SPIFFS, and config data on the EEPROM, can there every be a conflict because the libs write at the exact same location?

No, because SPIFFS and EEPROM are different things.

@Majenko Different in name and API, but under the hood both use the same hardware, namely Flash. The EEPROM on the OP's device is merely an emulation.


text:
Audio Recording using Arduino BT module
I want to take audio signal through mic connected to Arduino and then transfer it to PC using BT module. I want to do it with BT (HC05) and Arduino Mega. I need audio packages at 44 KHz and 24-32 bits per sample.
Can I use AudioInI2S library to receive audio samples? Does HC05 support this type of communication?
I want to save and analyze the audio samples later on. I have worked on Arduino before but I am totally new to audio streaming and I am not sure where to begin from. Any guidance would be appreciated.

In short: No and no.

Can I use AudioInI2S library to receive audio samples?

No.  The library is not for the Mega:

This library provides simple way to play and analyze audio data using Arduino on SAMD21 based boards (i.e Arduino or Genuino Zero, MKRZero or MKR1000 Board) using the I2S bus.

Does HC05 support this type of communication?

No.  The HC05 is a serial module. It works at baud rates that are far to low to transfer the data in a timely fashion, and can't send data in a form the PC sees as audio (so you'd need to write your own translation software to convert serial data into an audio file).

Any guidance would be appreciated.

Just buy a cheap bluetooth headset.

Thank you for your reply. Can you suggest any other Bluetooth module that can support my frequency range?

Bluetooth headset is not an option as it is a part of some project that I am working on.


text:
Serial throughput using AltSoftSerial on Arduino
My project involves a commercially available device that can be remotely controlled by a computer over RS232. I'd like to put an Arduino Pro Mini, which has a second serial port provided by the AltSoftSerial Library, between the device and the computer. One of the Arduino's serial ports will connect to the device under control, and the other will connect to the computer. One function of the Arduino will be to simply read incoming data on one port and immediately write it to the other port. I'm not yet sure how heavy the serial traffic will be, although my early impression is that it will come from sporadic, user-initiated commands and resulting responses.
Assuming all baud, stop bit, data bits and parity are configured correctly, is what I'm proposing possible with the AltSoftSerial Library? Is it likely that this approach will introduce delays and/or errors that are prohibitive?

That would depend on unspecified details.  There are plenty of cheap MCUs with two hardware UARTs or a UART and USB you can use as a proxy to present another virtual one to a PC if the timing is sufficiently loose.

Did you consider Arduino mega? It has more than 1 true hardware UART which means there is no software involved in transmission and reception. Otherwise, you have to go with the best software library to simulate the second serial port. All depends on what you want to achieve which is still not clearly mentioned in the question


text:
Establishing wireless comm. between PC and arduino pro micro to exchange speech and gyro data
I have a client project to make a wireless head-mounted mouse. What wireless module should I use so that I can exchange data between my laptop and the arduino pro micro through the USB port like a wireless mouse? I am using an MPU6050 accelero+gyroscope sensor for cursor movement and Electrohouse Voice Recognition module V3.1 for speech recognition. To exchange such data between PC and arduino, I found a lot of options. Hence, I am confused. Please help me decide what to use so that cost efficiency and effectiveness can be acheived. Should I use bluetooth, RF shield , XBEE or any other module?

The wireless medium you choose is largely irrelevant.  The important thing to realise is that it's not (in most cases) the wireless medium that is communicating with the computer.
Most wireless mice use the nRF24L01+ (or rather the integrated SoC equivalent) to communicate. They use a USB dongle plugged into the computer for that communication. The computer has no clue what an nRF24L01+ is, but it does know what a USB mouse is. So there is a microcontroller in the dongle which receives data from the nRF24L01+ and interprets it, and sends the right instructions over USB to make the computer think it's a USB mouse.
What the data is that's sent over the wireless, and exactly what form that wireless connection takes, is completely irrelevant as far as the computer is concerned.  In general one if the SoC equivalent to the nRF24L01+ (such as the nRF52810) is chosen because it's a single chip solution with a simple to use wireless protocol, which makes for cheap and easy development and implementation.
The only exception to this general rule (and there is always an exception to every rule) is Bluetooth. This is because there is the concept (as far as the computer is concerned) of a Bluetooth mouse. So it is possible, using the right Bluetooth adaptor on your Arduino, for the computer itself to see the Arduino as a Bluetooth mouse. This can be harder to implement using small microcontrollers, but results in a potentially lower cost solution with fewer components.
The simplest solution for you, though, is probably:

One Arduino that has a native USB connection (Pro Micro, Leonardo, etc - anything ATMega32U4 based)

This will be connected directly to the computer and programmed to emulate a USB mouse

One Arduino that best suits your sensors (probably doesn't really matter what for this. Mini? Micro? Nano? Uno? They would probably all do fine).

To this you attach your sensors, your voice recognition, etc.

A pair of wireless connectivity modules of some form

I'd recommend the nRF24L01+ - simple to use, has a very convenient packet-based protocol, cheap, and there's plenty of examples and libraries out there.  These are connected to both Arduinos and are used to communicate between them.
Then it's up to you to decide what information gets sent between the Arduinos to make the one connected directly to the PC send the right mouse movements.

Is the module you mentioned suitable for sending both speech data and cursor movement data to the pc from the user arduino? I ask this because the click operations and cursor movement operations are to be sent via the user side arduino. Can the module handle sending this amount of data? Like voice commands such as select, enter , options and cursor movement .?

Your VR module handle all that data doesn't it?

Yes, everything worked nicely andd without delay through the usb cable when i spoke a command to the VR module while moving the cursor. Can the nRF24L01 module send this data without delay?

So you're not sending large amounts of data them. Just a command to click the mouse.

If the VR module is anything like the ones I have used in the past, it's "Audio -> Microphone -> VR Module -> [serial] -> Arduino -> Do whatever you want". It's the "do whatever you want" bit that is the communication over wireless. That could be a single bit in a single byte.


text:
How to send and receive multiple integer values through serial comm for Arduino Micro and HC05 bluetooth?
I need to send gyroscope values and a voice command flag and counter with a start and end marker through serial in the format <2,4,5,6> through Arduino Software serial using the HC05 Bluetooth module between Arduino Micro boards. I can send values in the struct format. But it seems that the order of the struct gets changed after a few seconds of receiving on the other side. How can I send these values in the mentioned format? I am new to this. Please help me out. It would also help if I could get suggestions on how to receive and parse this data of this format in the correct order/way.

why do you use SoftwareSerial? Micro has Serial1 for RX/TX pin

@Juraj , I need to monitor the values since the transmission is so fast and needs the least latency possible. Besides, I could never get my bluetooth modules to work on hardware serial. Please provide me with a demo code or some link. Are there two hardware serial on Arduino Micro? I'm not sure. Please enlighten me.

there is USB named Serial and UART named Serial1. pins RX/TX are Serial1

@Juraj , I have been trying wireless communication using Serial but not Serial1. Is that the reason I am unable to send? Also, the question still remains how I can send, receive and parse the data to be sent in the format <2,3,4,5>

where are you sending the serial data?

@jsotola , arduino micro to arduino micro. Sending the values of gyroscope sensor and voice command flag. I wanna move the mouse cursor using that data.

Try Google Protobuf it's really awsome. I use it every time when I connect C# app to STM but it can be used in this case as well. U use Protobuf to encode your message and COBS do remove zeros from message so you can slap it on the end to know when the packet ends

Google Protobuf does work on AVR Arduino?


text:
How to fix Master-Slave communication between Arduino Micros Not Working and no serial monitor output problem?
I needed to send MPU6050's accelerometer and gyroscope data and voice recognition module's voice command status flag through the HC-05 Bluetooth module to receiver Bluetooth and Arduino. But because both Bluetooth HC-05 and voice recognition module use software serials, and not more than one software serial can function at a time, I had to search for a solution. I found that one solution is to alternate the serials. But my project is a wireless head mouse project. So, to decrease the mouse cursor lag, I need HC-05 and voice recognition module V3.1 to work parallelly. So, I went to implement the Master/slave approach to use two Arduino boards (one for the collection and calculation of data from MPU and voice recognition module) and the other for just getting these values and sending this data through HC-05. But I got stuck right in the basics. I tried to send data between two interconnected Arduino Micros in Master/Slave manner which uses I2C protocols, but it didn't work. I got nothing on the serial monitor set to 9600 bauds and "Newline" selected on the slave board's Serial monitor. The code I used was from the Arduino examples itself.
Circuit connections between Arduino Micros:
A4->A4
A5-> A5
Gnd-> Gnd
These connections are from the Example tutorials on this website which I followed and double-checked.
I tried both Master Writer &Slave Receive, and also Master reader & Slave sender.
Master Writer & Slave Receiver sketch respectively
// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup()
{
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop()
{
  Wire.beginTransmission(4); // transmit to device #4
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

    // Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup()
{
  Wire.begin(4);                // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop()
{
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
  while(1 < Wire.available()) // loop through all but the last
  {
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

Master Reader & Slave Sender sketch respectively
// Wire Master Reader
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Reads data from an I2C/TWI slave device
// Refer to the "Wire Slave Sender" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop() {
  Wire.requestFrom(8, 6);    // request 6 bytes from slave device #8

  while (Wire.available()) { // slave may send less than requested
    char c = Wire.read(); // receive a byte as character
    Serial.print(c);         // print the character
  }

  delay(500);
}

// Wire Slave Sender
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Sends data as an I2C/TWI slave device
// Refer to the "Wire Master Reader" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
}

void loop() {
  delay(100);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Wire.write("hello "); // respond with message of 6 bytes
  // as expected by master
}

Why not just use one Arduino (or arduino-like) board that has more than one UART? There are plenty of options.

@Majenko the problem is that this project is assigned to me by a client I know. And he told me to do it under a low budget. So, I have to make it for the low budget using my code. And also, there are only a two Arduino boards that support the functions needed. One of them being the Arduino Micro, and the other the Arduino Due.

I guess you looked at the tutorials for the Ardiuno Uno. On the Micro the I2C lines are not on A4 and A5. This pinout diagram states, that they are on D2 and D3. So try connecting these together


text:
How to Fix mouse cursor lag on voice & movement based head mouse in wireless setting?
For my head mouse project which is based on the voice recognition module V3.1 for left click, double click, right-click operations, I am facing a problem. I am using 433Mhz Radio Frequency one-way Transceiver for sending data. When I use the MPU 6050 accelerometer and gyroscope for mouse cursor movement and the voice recognition module together on only one Arduino board, the mouse cursor moves smoothly and the voice commands work smoothly. But when I use the 433Mhz RF one-way transmitter for one Arduino board to calculate the mouse movement and figure out the voice command to send it in a wireless manner and receive the values and voice commands using the receiver module of the rf433 Mhz, the mouse cursor starts to lag. It doesn't move smoothly. Please help me solve the problem. The code and circuit diagram are given below:

Transmitter.ino
  /*433 MHz RF Module Transmitter Demonstration 1
  RF-Xmit-Demo-1.ino
  Demonstrates 433 MHz RF Transmitter Module
  Use with Receiver Demonstration 1

  DroneBot Workshop 2018
  https://dronebotworkshop.com
*/

// Include RadioHead Amplitude Shift Keying Library
#include <RH_ASK.h>
// Include dependant SPI Library
#include <SPI.h>
#include <SoftwareSerial.h>
#include "VoiceRecognitionV3.h"
#include <Mouse.h>
#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>

VR myVR(8,9);    // 9:RX 8:TX

uint8_t records[7]; // save record
uint8_t buf[64];

MPU6050 mpu;
int16_t ax, ay, az, gx, gy, gz, oax, oay, oaz, ogx, ogy, ogz;
int16_t vx, vy;
//
#define leftRecord    (0)
#define rightRecord   (1)
#define doubleRecord  (2)

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf     --> command length
           len     --> number of parameters
*/
void printSignature(uint8_t *buf, int len)
{
  int i;
  for(i=0; i<len; i++){
    if(buf[i]>0x19 && buf[i]<0x7F){
      Serial.write(buf[i]);
    }
    else{
      Serial.print("[");
      Serial.print(buf[i], HEX);
      Serial.print("]aurav");
    }
  }
}

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf  -->  VR module return value when voice is recognized.
             buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
             buf[1]  -->  number of record which is recognized.
             buf[2]  -->  Recognizer index(position) value of the recognized record.
             buf[3]  -->  Signature length
             buf[4]~buf[n] --> Signature
*/
void printVR(uint8_t *buf)
{
  Serial.println("VR Index\tGroup\tRecordNum\tSignature");
  Serial.print(buf[2], DEC);
  Serial.print("\t\t");

  if(buf[0] == 0xFF){
    Serial.print("NONE");
  }
  else if(buf[0]&0x80){
    Serial.print("UG ");
    Serial.print(buf[0]&(~0x80), DEC);
  }
  else{
    Serial.print("SG ");
    Serial.print(buf[0], DEC);
  }
  Serial.print("\t");

  Serial.print(buf[1], DEC);
  Serial.print("\t\t");
  if(buf[3]>0){
    printSignature(buf+4, buf[3]);
  }
  else{
    Serial.print("NONE");
  }
  Serial.println("\r\n");
}

struct dataStruct{
  int16_t moveX;
  int16_t moveY;
  int flag;
  }myData;

byte tx_buf[sizeof(myData)] = {0};

// Create Amplitude Shift Keying Object
RH_ASK rf_driver;
int flag = 15;

void setup()
{

   /** initialize */

  Wire.begin();
  mpu.initialize();
  if (!mpu.testConnection()) {
    while (1);
    }

  myVR.begin(9600);
  Serial.begin(115200);
  Serial.println("Elechouse Voice Recognition V3 Module\r\nControl LED sample");

  if(myVR.clear() == 0){
    Serial.println("Recognizer cleared.");
  }else{
    Serial.println("Not find VoiceRecognitionModule.");
    Serial.println("Please check connection and restart Arduino.");
    while(1);
  }

  if(myVR.load((uint8_t)leftRecord) >= 0){
    Serial.println("leftRecord loaded");
  }

  if(myVR.load((uint8_t)rightRecord) >= 0){
    Serial.println("rightRecord loaded");
  }

  if(myVR.load((uint8_t)doubleRecord) >= 0){
    Serial.println("doubleRecord loaded");
  }

    // Initialize ASK Object
    rf_driver.init();
    if(!rf_driver.init()) Serial.println("Init failed");

}

void loop()
{

  int ret;

  ret = myVR.recognize(buf, 50);
    const char *msg = "Welcome to the Workshop!";

  if(ret>0){

  switch(buf[1]){

    case leftRecord:
    flag = 0;
    break;

    case rightRecord:
    flag = 1;
    break;

    case doubleRecord:
    flag = 2;
    break;

    default:
    flag=3;
    Serial.println("Record function undefined");
    break;
    }
    /** voice recognized */
    printVR(buf);
  }

  mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  oax = ax+72;
  oay = ay-382;
  oaz = az-505;
  ogx = gx+99;
  ogy = gy-29;
  ogz = gz-50;

  vx = gx/200;
  vy = -gz/200;
  myData.moveX = vx;
  myData.moveY = vy;
  myData.flag = flag;

  memcpy(tx_buf, &myData, sizeof(myData));
  byte bufSize = sizeof(myData);
  Serial.println("movX\tmovY\tmovZ\toax\toay\toaz\togx\togy\togz\tvx\tvy:");
  Serial.print(myData.moveX, HEX);
  Serial.print("\t");
  Serial.print(myData.moveY, HEX);
  Serial.print("\t");
  Serial.print(myData.flag, HEX);
  Serial.print("\t");
  Serial.print(oax, DEC);
  Serial.print("\t");
  Serial.print(oay, DEC);
  Serial.print("\t");
  Serial.print(oaz, DEC);
  Serial.print("\t");
  Serial.print(ogx, DEC);
  Serial.print("\t");
  Serial.print(ogy, DEC);
  Serial.print("\t");
  Serial.print(ogz, DEC);
  Serial.print("\t");
  Serial.print(vx, HEX);
  Serial.print("\t");
  Serial.println(vy, HEX);

  rf_driver.printBuffer("Buffer values [vx, vy, status flag respectively]: ", tx_buf, bufSize); //each value is 16 bit. and serail monitor will show in 8 + 8 = 16 bit format
    rf_driver.send((uint8_t *)tx_buf, bufSize);
    //Serial.println();
    rf_driver.waitPacketSent();

    flag = 15;
    delay(1);

}

Receiver.ino
// Include RadioHead Amplitude Shift Keying Library
#include <RH_ASK.h>
// Include dependant SPI Library
#include <SPI.h>
#include <Mouse.h>
#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>

#define leftRecord    (0)
#define rightRecord   (1)
#define doubleRecord  (2)
// Create Amplitude Shift Keying Object
RH_ASK rf_driver;

struct dataStruct{
  int moveX, moveY, flag;
  }myData;

void setup()
{
    // Initialize ASK Object
    Wire.begin();
    rf_driver.init();
    // Setup Serial Monitor
    Serial.begin(115200);
    if(!rf_driver.init()) Serial.println("Init failed");
}

void loop()
{
    // Set buffer to size of expected message
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);
    // Check if received packet is correct size
    if (rf_driver.recv(buf, &buflen))
    {
      int i;

      // Message with a good checksum received, dump it.
  rf_driver.printBuffer("Got:", buf, buflen);
        memcpy(&myData, buf, sizeof(myData));
        Serial.println("");

        Serial.print("moveX: ");
        Serial.print(myData.moveX);

        Serial.print("  moveY: ");
        Serial.print(myData.moveY);

        Serial.print("  Command Status: ");
        Serial.print(myData.flag);

      // Message received with valid checksum
      Serial.print(" Message Received: ");
      Serial.println((char*)buf);

      Mouse.move(myData.moveX, myData.moveY);

  if(myData.flag!=15){

  switch(myData.flag){

    case leftRecord:
    Mouse.click(MOUSE_LEFT);
    delay(10);
    break;

    case rightRecord:
    Mouse.click(MOUSE_RIGHT);
    delay(10);
    break;

    case doubleRecord:
    Mouse.click(MOUSE_LEFT);
    Mouse.click(MOUSE_LEFT);
    delay(10);
    break;
    default:
    break;
    }

    }
}
}

In general, you want to stream some data. and the mouse lag is one of the main obstacles in data streams; lag. so many classic causes such as buffer over-runs and timing problems come to mind.
The cheap 433MHz modules are not a good choice in case of streams. they lack any robust protocol, ACKing and security.
I would do this things to make it better:

use a better transmitter. maybe the cheap nRF24L01 ones.
use a bigger buffer
use two threads on the transmitter side. (e.g. use something like this, but two threads). one thread to collect data and writing it to a buffer, the next one to send data using nrf. furtunately, the nRF24 can send up to 32Bytes in one buffer transmission and the SPI interface is fast enough to fill it's buffer as quick as possible.
if you have to, use another thread to calculate movements from MPU6050. so you don't have to read it continuouesly and send all that raw data to reciever. you may use some interpolation on the receiver side though.

But when I use the nRF24L01 the Arduino turns on and then turns off. I've tried this with the Arduino Leonardo as well as the Micro. How can I fix this? It also causes power surges and overheating occassionally.

make sure the power pins are correct. this problem is mainly due to VCC/GND pins being swaped


text:
fixing drifting issue for elechouse voice recog module v3.1 and MPU6050 sensor for head mouse even after doing sensor calibration?
For my head mouse project which is based on the voice recognition module V3.1 for left click, double click, right click operations, MPU 6050 accelerometer and gyroscope for cursor movement, I am facing a problem. When I just use the MPU 6050 accelerometer and gyroscope sensor for cursor movement, the mouse cursor moves smoothly (calibration has been done). But when I integrate it with the voice recognition module, the cursor starts to drift. My code is given in this post too.
I have been using an arduino pro micro for this project. Please help. I have calibrated my MPU6050 , so it does not drift while working alone. But after integration with voice recog module (including calibration) , the drifting problem returns. I am powering the setup using a USB cable connected from the laptop to the arduino.
N.B: This is a project from a client. According to requirements, I need to make the head mouse wireless. I need suggestions for that too.

#include <SoftwareSerial.h>
#include "VoiceRecognitionV3.h"
#include <Mouse.h>
#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>

VR myVR(8,9);    // 9:RX 8:TX

uint8_t records[7]; // save record
uint8_t buf[64];

MPU6050 mpu;
int16_t ax, ay, az, gx, gy, gz, oax, oay, oaz, ogx, ogy, ogz;
int vx, vy;

#define leftRecord    (0)
#define rightRecord   (1)
#define doubleRecord  (2)

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf     --> command length
           len     --> number of parameters
*/
void printSignature(uint8_t *buf, int len)
{
  int i;
  for(i=0; i<len; i++){
    if(buf[i]>0x19 && buf[i]<0x7F){
      Serial.write(buf[i]);
    }
    else{
      Serial.print("[");
      Serial.print(buf[i], HEX);
      Serial.print("]aurav");
    }
  }
}

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf  -->  VR module return value when voice is recognized.
             buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
             buf[1]  -->  number of record which is recognized.
             buf[2]  -->  Recognizer index(position) value of the recognized record.
             buf[3]  -->  Signature length
             buf[4]~buf[n] --> Signature
*/
void printVR(uint8_t *buf)
{
  Serial.println("VR Index\tGroup\tRecordNum\tSignature");
  Serial.print(buf[2], DEC);
  Serial.print("\t\t");

  if(buf[0] == 0xFF){
    Serial.print("NONE");
  }
  else if(buf[0]&0x80){
    Serial.print("UG ");
    Serial.print(buf[0]&(~0x80), DEC);
  }
  else{
    Serial.print("SG ");
    Serial.print(buf[0], DEC);
  }
  Serial.print("\t");

  Serial.print(buf[1], DEC);
  Serial.print("\t\t");
  if(buf[3]>0){
    printSignature(buf+4, buf[3]);
  }
  else{
    Serial.print("NONE");
  }
  Serial.println("\r\n");
}

void setup()
{
  /** initialize */
  Wire.begin();
  if (!mpu.testConnection()) {
    while (1);
    }

  myVR.begin(9600);
  Serial.begin(115200);
  Serial.println("Elechouse Voice Recognition V3 Module\r\nControl LED sample");

  if(myVR.clear() == 0){
    Serial.println("Recognizer cleared.");
  }else{
    Serial.println("Not find VoiceRecognitionModule.");
    Serial.println("Please check connection and restart Arduino.");
    while(1);
  }

  if(myVR.load((uint8_t)leftRecord) >= 0){
    Serial.println("leftRecord loaded");
  }

  if(myVR.load((uint8_t)rightRecord) >= 0){
    Serial.println("rightRecord loaded");
  }

  if(myVR.load((uint8_t)doubleRecord) >= 0){
    Serial.println("doubleRecord loaded");
  }

}

void loop()
{
  int ret;
  ret = myVR.recognize(buf, 50);

  mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  oax = ax-265;
  oay = ay+387;
  oaz = az+474;
  ogx = gx-109;
  ogy = gy+35;
  ogz = gz+150;

  vx = gx/120;
  vy = -gz/120;

  Mouse.move(vx, vy);

  if(ret>0){

  switch(buf[1]){

    case leftRecord:
    Mouse.click(MOUSE_LEFT);
    delay(100);
    break;

    case rightRecord:
    Mouse.click(MOUSE_RIGHT);
    delay(100);
    break;

    case doubleRecord:
    Mouse.click(MOUSE_LEFT);
    Mouse.click(MOUSE_LEFT);
    delay(100);
    break;

    default:
    Serial.println("Record function undefined");
    break;
    }
    /** voice recognized */
    printVR(buf);
  }
}

Your problem is most likely the use of SoftwareSerial for your VR module communication. SoftwareSerial is notorious for breaking things. It disables interrupts, and hogs the CPU.
You should be using the hardware serial port instead which, on the Pro Mini, is completely separate to USB communication.


text:
Concern myself with current draw from digital pins used as INPUT with internal pullups?
My project is using a genuine Arduino Mega 2560, probably 3-4 yrs old since purchased (I don't see any revision numbers on the PCB).  It's being used to read a lot of switches, buttons and drive some LED's and displays.
When using a digital pin as INPUT with the internal 10k pullup enabled, do I need to consider the draw with respect to the 200mA total through all pins?  Is it simply the 10k ohm resistor with 5V so 0.5mA?  Can I just ignore it? (there's only so many pins I suspect I can ignore it)
I've seen several posts/pages about driving LED's using transistor arrays powered by an external source and those spec sheets describe the transistor input currents so I can estimate the draws for those elements, but not sure if I need to concern myself with the Arduino pins used as INPUT.

The pull-up resistors of the I/O pins are specified as 20 to 50 kΩ, so they are not going to source more than 250 µA at 5 V. The “Typical characteristics” section of the data sheet shows a current of the order of 140 µA.

I found them to be about 34kΩ - 37kΩ: Read how I found that here: https://majenko.co.uk/blog/measuring-arduino-internal-pull-resistors

In case of a button, the 0.15mA of current only flows while the button is pressed. Zero current flows when the button isn't pressed, which is probably most of the time. I think it's pretty safe to ignore these currents.

I think Gerben is right. The pull-up resistors connect +5V to the solid state capacitors on the CMOS inputs, which have virtually infinite resistance to DC current. The pull-ups will only draw current when the pin is grounded, and shortly afterwords.

You are right. The current through digital inputs is so low, that you can normally ignore it.
And the 0.5mA, that you calculated don't flow all the time, just, when the corresponding button is pressed and thus shorted to ground, because only then a current will flow through the pullup resistor. The current into the actual input hardware is even smaller. So, as long as not all buttons are pressed at once, the current will be even lower as calculated.
Buttons are somewhat voltage devices. They don't need a specific amount of current, just of voltage. So the actual value of pullup/pulldown resistors are not critical. LEDs in contrast are current devices. They need a specific current to light up, which is often higher, than the maximum output current of a digital pin. Thus they are often driven with an additional transistor.


text:
Receiving two values over serial port using servos
So I have a java program that picks up the mouses x and y coords on the display and I would like to send those to my arduino and then move my two servos to those locations (I have two servos ontop of each other, one for x and one for y).
The java (processing) code i have is below
void draw(){  //same as loop in arduino
  background(52, 152, 219); // background color of window (r, g, b) or (0 to 255)
  //lets give title to our window
  fill(0, 255, 0);               //text color (r, g, b)
  textFont(font);
  text("Ripple Effect Maker", 80, 30);  // ("text", x coordinate, y coordinat)
  ellipse(mouseX, mouseY, 33, 33);
  int x = mouseX;
  int y = mouseY;
  port.write(x+":"+y);
  println(x+":"+y);
  //println("y="+y);
  delay(100);
}

I don't have much arduino code because I can't seem to find a way to split the data into two seperate variables and then move the servos to their corresponding variables.
Thanks for the help!

https://majenko.co.uk/blog/reading-serial-arduino

Your problem is that you aren't providing anything to split the data on. You just send the X and y coordinates with a : between X and y. There's nothing between the y and the next X.
By changing the line
port.write(x+":"+y);

To
port.write(x+":"+y+"\n");

You then get the linefeed character to split your data on.