text:
channels on logic level shifter outputs high
so I have a logic level shifter which is TXS0108E ,I use it to shift the eps32 ouput volatge to 5v to be used with motor driver ,when I test it with multimeter , all the channels on the B side outputs high (5v) without connecting anything on the A side, my connection is this :

it is normal...

So how can the driver know if it is high or low if it is all the time high

an unconnected pin of the converter when powered is HIGH. the input must pull it down to change the state and that state is reflected on output.

Oh I didn't know that , thanks.


text:
Externally powering Arduino while reading voltage off it via USB
I have an Arduino UNO R3 where I’ve set Pin 13 to “HIGH” (as shown here) and I’ve connected an LED to Pin 13 and GND which glows brightly using a USB attached to my MacBook Air providing (I think) 5V.
Now, I’m powering the Arduino externally using a 3V (1.5+1.5) battery and the 5V/GND connection. The green light blinks showing the Arduino is being powered and the bulb glows since it’s the same circuit.
Now, I wish to connect the USB to the Arduino and basically read the voltage of the LED via Pin 13 and the GND connection. Of course, I could accomplish this by simply attaching a multimeter but that’s not the problem since it’s not the true aim of the project (which I can state if required but it’s more complicated and not too different).
But when I connect the USB the LED glows brighter and the voltage across it is around 3.5V (higher than what the battery is supplying). I want the computer to read the voltage of the battery and not supply the arduino with it’s own power. How do I accomplish this (note: I’m allowed to break certain circuitry on the Arduino but I’d prefer to do this as last resort)?
Basically, how do I read voltage readings on a computer off an arduino without powering the arduino i.e. How do I convert the USB port and my computer into a multimeter with the arduino?
(I'm very new to experimenting with this so may have made crushing mistakes. Any help is appreciated)

why do you want to do this? ... you can measure the battery voltage without using the battery to power the arduino ... otherwise, use an external USB serial adapter

When powering the Uno with 3V at its 5V input, then its underpowered. It might work (since the microcontroller on it is technically capable of working at 3V), but it might be unstable, especially when your batteries voltage goes lower while you are emptying them. And: Please explain what you want to learn from the voltage on the LED pin? It is mainly determined by the LEDs forward voltage and the resistor values in relation to the current supply voltage. And are you adding another LED to that pin? Since pin 13 already is connected to an LED you would need to also take that into account.

Pin 13 is a digital pin, it does not have the capability to read voltage. You need to use one of the analog pins to read voltage, they are prefixed with the letter "A" (A0 for example). You also need to note the Analog reference (maximum voltage reference point for the A/D) is the Arduino's +5 volt supply so if that changes so will the readings. You will get 0 with zero input and 1023 when the voltage matches the reference voltage. Note this voltage cannot exceed VCC by more than a very small amount (0.6V)or you will damage the Arduino. The USB supplies about 4.5 volts, depending on the protection circuit. If you power it via Vin with the appropriate voltage it will have nominally 5 volts and of course the ever changing battery voltage. All of these change your reference voltage changing your voltage measurement. The best solution is to power it externally and then connect the battery - to ground and the battery + to one of the A/D inputs. With a little math in your code you will have a voltmeter. There are many fine examples on line complete with code for the Arduino.

source: Stack Exchange

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

sort: votes


text:
Chain of, or one big if sentence
(This might be more of a common C question)
I want to test several conditions in an IF-sentence
if(variable) {            // fastest check
  if(register) {          // a bit slower
    if(read_peripheral) { // very slow check
      // [do something]
    }
  }
}

It seems obvious that I want to start with the fastest check, and move on to the slower ones afterwards, potentially avoiding to check them if the above was false.
Now since I need to check quite a few conditions, I'd like to know if the following is the same, or if all conditions will be evaluated prior to making a decision?
if(variable && register && read_peripheral) {
  // [do something]
}

Putting them all in a single condition like that is absolutely fine. C/C++ uses "short circuit evaluation" which means it will stop as soon as it's determined the outcome. If everything is combined using logical AND operators (&&) then that means it will stop as soon as one of them evaluates to false.
For example:
 if (blah() && foo()) { ... }

If blah() returns false, it will never call foo() at all because it already knows the overall outcome is false.
The reverse happens with the logical OR operator (||):
 if (blah() || foo()) { ... }

If blah() returns true in this case, it won't call foo(). That's because it already knows the overall outcome is true.

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


text:
What is Vin for the EthernetPOE board?
I am working on a project that needs to drive a relay board. I'm looking at the ETHERNET board with PoE and according to the documentation here (http://arduino.cc/en/Main/ArduinoBoardEthernet) the output of the PoE module is 9V.
Is that the voltage to expect out of the Vin pin?
The Relay board that I want to use (http://numato.com/downloads/dl/file/id/29/product/47/user_manual.pdf) specifies that it wants a 7-12V power supply.
I want to confirm that this is the case so I can use the voltage out of the PoE and I don't need to add a separate DC power supply to this system.

I wouldn't expect you to take any power from V-in-, but it actually seems like you can!
If you take a look at the schematic for the Rev.3 Arduino Ethernet, you can see the power rails from Ethernet is connected to Vin. (V1+, V1-, V2+, V2- --> Vin in the leftmost part of the schematic)

Thanks! I actually just received the boards and measured it. I got 10V on Vin and the Numato board looks like a shield that shares Vin through the bottom pins. However with the POE module the shield doesn't exactly fit, so I'm just running the wires from Vin to the Numato Vin pin.

Your question is a little confusing, so let me give you a couple pieces of information.
First things first - the VIn pin on the Arduino is strictly for power going to the Arduino board, you shouldn't be drawing power from this pin. The documentation in the link you sent is a little misleading on this - it's basically saying 9v is coming OUT of the PoE module, and going IN to the VIn on the Arduino itself. If you wanted to tap into this 9v power, you should connect to the PoE module VOut instead.
PoE by default can deliver 37-57 volts or 42-57 volts, depending on what type of PoE you're using (which 802.3 specification). Wikipedia has a good overview of this information.
That being said, the Arduino Ethernet board you're using can't handle this voltage by itself - unless these boards have changed, they require an additional PoE module, which is basically just a DC-to-DC buck converter that will convert the high PoE voltage down to 9v or 12v. At this point, the Arduino's built-in converter can consume that 9 or 12v and distribute it at 5v across the board.
Now, to your problem - you want to power a relay that requires 7-12v. You could theoretically connect the relay to the VOut of the PoE module, giving you 12v. However, if the relay draws too much power for too long, you will either get brownouts (and your Arduino will restart) or potentially damage the Arduino board. Unless the relay draws a lot of current or is being powered for extended periods, you should be fine. If you want to be more thorough, you could put a large capacitor between your PoE module and the relay.
You should NOT try to connect the relay directly to the PoE VOut, as the voltage will be far too high.

I think the PoE is not following 802.* standards. "the output of the PoE module is 9V."

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


text:
How to convert a reading to percentage in Arduino
I am using this example on how to use a photoresistor to detect the value of light that the sensor is getting but I want to convert the reading of the resistor to a percentage but I can't use the map() function from the Arduino docs but I can implement something similar to it
so I created this simple function
float photo_resistor(int pinNum)
{
    float reading = analogRead(pinNum);
    if (reading == 54)
    {
     return 0.0;
    }
    return (reading - 54)/(100/920);

}

as in the docs I want to use an output range from 0 to 100 and the minimum reading i got is 54 and the maximum is 974
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
// this becomes (x - 54)*(100 - 0 ) / ( 974 - 54) + 0;
// (x-54)/(100/920);

but this does not output a value from on the scale from 0-100

your question is about arithmetic, not about Arduino

think of a basket that can hold 20 apples maximum ... there are 6 apples in the basket ... how full is the basket, expressed in percent?

You wrote:

return (reading - 54)/(100/920);

In C++, 100/920 is zero. This is because, when both operands are
integers, the division operator performs an integer division. You can
overcome this problem by making sure that at least one of the operands
is a floating point number. For instance, 100.0/920 is roughly 0.1087.
However, your division is backwards. You probably mean
return (reading - 54) * (100.0/920);

I'd use return max(0.0, min(100.0, (reading-54.0)*(100.0/920))); -- this makes sure that no values outside the range 0.0 .. 100.0 are ever returned, even when another photoresistor with slightly different tolerances is being used.

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


text:
PWM on Wemos D1 Mini (esp8266 chip) does not work
I am working on a hobby project: creating an rc-(radio controlled)-toy car.
I'm working with a Wemos D1 Mini (esp8266) microcontroller, L298N H-bridge (for controlling the motor) and I'm using the Arduino IDE to program it all.
The project is quite simple: make the car drive around via an virtual joystick on an app. The project is quite fun and a nice learning experience for me. The project is going pretty well until this point.
I can move the car forwards and backwards with a constant speed, but I'm not able to change the speed via a PWM signal. Actually, I'm not even sure if it is even possible to create a PWM signal on the Wemos D1 Mini, I have never done it before on this specific controller. I'm not an electrical engineer, so I'm not really familiar with very specific details about the controller itself.
Can somebody help me create a PWM signal to control the speed of the car?
This is what I have got now, very basic stuff:
void setup() {
  pinMode(D2, OUTPUT);
  pinMode(D5, OUTPUT);
  pinMode(D6, OUTPUT);
  pinMode(D7, OUTPUT);
  pinMode(D8, OUTPUT);
}

void forward() {
  digitalWrite(D5, LOW);
  digitalWrite(D6, HIGH);
}

void backward() {
  digitalWrite(D5, HIGH);
  digitalWrite(D6, LOW);
}

void setVelocity(int value){
  analogWrite(D2, value);
}

void loop() {
  setVelocity(1023);
  forward();
}

Thanks in advance!
Sincerly,
Stefan

how did you try to change the speed?

@jsotola presumably analogWrite to the enable pin on D2.

@timemage that is unknown

Yes, D2 is the enable pin! @timemage

I think I'm going to switch to a different microcontroller

See here regarding about the change in default for range in analogWrite calls. Your code is producing a 50% duty cycle waveform at 1KHz if told to setVelocity to 128.

You don't have to switch to a different microcontroller. As @timemage's link pointed out, if you're using an ESP8266 core >= 3.0.0, you could either reduce the range of analogWrite from 0..255 or put analogWriteRange(1023); in your setup().

At one point analogWrite as it was implemented in the esp8266-core had defaulted to a 10-bit range. This is no longer the case. It defaults to 8-bit range now.
In any case analogWrite is implemented to clamp the given value to be within the range.
If you were not experimenting in the bottom quarter of the velocity range with your code as written then you would have seen full velocity.
You can change to working with the 8-bit range or use analogWriteRange(new_range) or analogWriteResolution(bits) as this mentions.
Your code as is will produce a 50% duty cycle 1Khz signal on D2 if setVelocity is given 128 with the current core.

Thanks for your swift response! It turns out... my ESP8266 board core was very outdated :( I think that was the problem. And you are right it is 8 bit now! I'm very happy it works now! Thanks for your help, very much appreciated!


text:
Can we use more than one timer when programming an Atmega32/16?
I tried to do a simple program using the ATmega16 microcontroller, the program is to toggle two LEDs the first one by using timer0 interrupt and the other using timer2 interrupt.

If you put them on correct pins, you can setup timers to toggle them without any software handling. Also yes, you can have more than one ISR and even all the timers running at the same time

Yes, you can. However there is one thing to note:
Only one ISR can run at once.
That means that if one LED wants to toggle while the other one is in the process of toggling it will have to wait until that first ISR is finished before it can toggle.
For simple LED toggling that won't be noticeable, but it's something you need to bear in mind if you are doing multiple things that require precise timing.

Yes, we can.
(stackexchange wants the body of the answer to be at least 30 characters, so I have to add some filler. Truth is, for answering the question as asked, there is nothing more to say.)


text:
No text in the IDE menu items
I installed arduino 1.8.19 (64-bit) on a Fedora Linux 35 Workstation Edition system. When I started the IDE, and selected the "Open" menu icon, the menu item list appeared, but there was no text displayed with the items. I could open sub-menu items, but there was still no text. It looked like:

I tried several other 1.8.x versions, but with the same result. I haven't found any discussion about this on the Web. so I suspect that it is problem with my configuration. Nevertheless, any suggestions will be most welcome. I have not tried to install the IDE on Windows 10, but that is an option.

wow, that is frustrating ... what is your specific question?

You may want to run it from a terminal and check the output there for clues that you may then want to add to the question.

My specific question is, "What can I do to be able to see the menu items?"
I installed the IDE on Windows 10 and it runs as expected.

Starting the IDE from the command line gives an error, but I don't what it implies nor how to eliminate it.
Gtk-Message: 01:05:10.314: Failed to load module "pk-gtk-module"

google pk-gtk-module

Thanks, jsotola. So far a Google search has turned up 3 suggestions. Sadly, none of them have helped.

Install PackageKit-gtk3-module. dnf responds that it already is installed
Create a new gtk2.cnf that points to /usr/lib64/gtk-2.0/modules. Didn't resolve it.
Extract the missing library from a Fedora 16 system (in the archives) and move it to the "modules" directory.

The 3rd suggestion resolved the missing library, but, alas, did not resolve this issue of no text being displayed. So I am still hoping for suggestions.

There is a incompatibility between Arduino 1.8.19 and Fedora 35. On another PC, where I was running an older version of Arduino, I upgraded to Fedora 36 and the upgrade warned me of the incompatibility with the older Arduino and Fedora 36 and said it was deleting Arduino. After the Fedora upgrade completed, I installed Arduino 1.8.19 and it worked as expected. When I upgraded the original PC, the one with the no text in the menus, to Fedora 36, the menus also worked as expected. Hallelujah!! So, all is well and I have my answer. Thanks for your replies.


text:
String of raw data to Char Hex Array for Bitmap
I'm trying to transfer a monochrome ~4kb image file over WebBT to an ESP32 via BLE.
The EPD display looks for an unsigned char array to represent a bitmap. So..it should be in the format of something like
`const unsigned char epd_bitmap_123_1 [] PROGMEM = {
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};`

I've been successfully able to chunk, serialize, and reassemble an ArrayBuffer of the image from JS to the mcu in C++ (as a String).
I can verify that printing the Hex String on the board is the same as what's given from JS.
However, the image does not display properly on my EPD.
    class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
     //String value of raw data from JS ArrayBuffer..I can only get data as String with BLECharacteristic...
     std::string value = pCharacteristic->getValue();

     //Converting of String above into a Hex String
     string s2;
     stringstream ss;
     for (const auto &item : total) {
       ss << hex << int(item);
     }
     s2 = ss.str();

     //Converting Hex String into Char Array for EPD
     char * const cstr2 = new char [s2.length()+1];
     std::strcpy (cstr2, s2.c_str());

     //Displaying final Char array on EPD
     display.clearBuffer();
     display.drawBitmap(0,0,(unsigned char *)cstr2,296,128,EPD_BLACK);
     display.display();
};

Any idea what's going wrong here? I'm thinking it's something with encoding.

The display doesn't want a hex string. It wants pure binary data. the 0xff and similar are only the human representation in the code. It corresponds to the binary representation 0b11111111.

So the display works when passing something like const unsigned char epd_bitmap_123_1 [] PROGMEM = {     0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
I was hoping //Converting Hex String into Char Array for EPD      char * const cstr2 = new char [s2.length()+1];      std::strcpy (cstr2, s2.c_str()); would result in something of that format, but it does not appear to be working correctly.

EPD expects monochrome bitmap. So I get this is just array of bits representing either black or white.
Official doc says its expects a byte[] http://adafruit.github.io/Adafruit-GFX-Library/html/class_adafruit___g_f_x.html#a805a15f1b3ea9eff5d1666b8e6db1c56
So I guess my confusion is how a const unsigned char [] can be a byte[].
Regardless..how can I then convert anything I have (original string version of raw data, or subsequent converted Hex string) into said Byte array?
Thanks!

There are a couple of misunderstanding of the fundamental C++/Arduino programming concepts, 1)epd_bitmap_123_1 [] is not a string (a string is an array of unsigned char terminated by a \0 in C++), it is an array of unsigned char (a.k.a. uint8_t in C++, or byte in Arduino). 2) When passing in an array to a function as an argument, C++ automatically pass in the pointer of the array, so there is no need to cast it with (unsigned char *).

If the Adafruit_GFX::drawBitmap() is expecting a const uint8_t bitmap[], it would be easier that you just declare your epd_bitmap_123_1 [] as const uint8_t epd_bitmap_123_1 [] PROGMEM so that no casting is required.

Great, thanks for the clarification, I understand it wants a Byte array now. The problem is that I'm sending over an ArrayBuffer of bytes, but my BLE callback can only obtain a string representation of this. Printing out this string representation yields bunch of weird chars (mostly backwards '?')...
So..converting that string to a Hex string does in fact get the same bytes that were present from the JS array buffer. How to then convert this hex string into a byte array?

Note: The converted hex string I get would just be in format of "FFFF", as opposed to, "0xFF, 0xFF".


text:
Fingerprint sensor with external memory source
I am building a door lock that we will use at a local MakerSpace-club in my city, and we had this idea about building a fingerprint lock with parts compatible with Arduino.
What we are aiming to do is create a database that holds all our customers and their associated information. Fingerprint data being one of them.
So my question is: Is it possible to have a fingerprint sensor store and compare fingerprint data with an external source such as a MySQL database, instead of using the on-board memory?
So basically: When a customer puts his finger on the sensor, the Arduino board grabs the fingerprint data and queries our database for a match through its WiFi shield. If match is found: Log entry and unlock the door.
Google is not helping me out here.

Yes, all you need is a computer or another device that grabs the data via wifi and store it in a database.
You can simply send requests from arduino to computer and the PC does the search and returns the info back.
If you use XBees for communication, just install some serial communication with your preferred language and start sending and receiving data. The database will be accessed through that high level program and data will flow via XBees.


text:
Arduino Command Line Interface - How to change boardsmanager.additional.urls
I am building a Travis CI job to test my Arduino Library and it needs to install external board definitions.
Is there a way that I can set the boardsmanager.additional.urls from the command prompt like it would have been done in the Preferences window?
Or should I create preferences.txt file? (If so where does that live in a Linux environment)

The location of preferences.txt is shown near the bottom of the preferences page.  It takes two or three clicks to open it in gedit.

Found the solution:
arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json"

Note that since Arduino IDE 1.6.4 preferences set via --pref are only saved if you also use the --save-prefs option. See: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc#history


text:
Stop at the end of a track
I would like to create a camera dolly for capturing timelapse movies.
i.e. something like this:
http://youtu.be/Qce1f6SKEMU
Whats a reliable way to detect the end of the track and stop the stepper motor moving the camera? In other words how is it possible to get the current position of the camera and stop the motor before the track ends to prevent crashing into the bumpers?

Many thanks for all of your answers. I think I need to get familiar with all of the mentioned methods to finally decide what's the best for my project.

The simplest way is to have an opto-interrupter fitted at one end of the track (IR LED and IR Phototransistor), and a small bit of plastic or whatever on the dolly which interrupts the IR beam.
Printers have been doing it that way with their print heads for decades.
http://www.martyncurrey.com/connecting-an-photo-interrupter-to-an-arduino/

Many methods exist:
References to unpowered means the switch does not draw power when not operated. When a motor is activated it will draw power.

Mechanical switch- microswitch is the most common (as per Spiked3's suggestion). Contamination and weather may be issues (depending on how waterproof your camera is). No power needed for actual switch.
Optical (a la Majenko). Some environmental issues. Effect of ambient light needs to be considered.
Capacitive. Can be fully sealed. Need to be powered.
Magnetic - Hall (powered) and Reed (unpowered).

Whatever is used, the current and voltage ratings need to be compatible with the load. In many cases the actual switch will need a transistor or relay or similar to provide the power drive to the dolly motor. This is not hard to do but needs to be noted.

An end of track signalling method that is relatively unaffected by environmental issues is to use a magnet and magnet detector. The most common detectors are either a "Hall sensor" IC or a reed switch.
Reed switches are mechanical and more fragile than Hall sensors but need no power when unoperated and can be bought in ready made encapsulations that are robust enough to be reliable. Properly implemented a reed switch can be essentially indestructible.
Hall sensors need to be powered but power levels are small compared to eg dolly motor current and low current versions are available.
Both Hall sensors and reed switches have a degree of "hysteresis" - the point in the travel where they operate is past the point where they release again, but this is easily allowed for in practice.

Reed switch demonstration - 38 seconds video - simple and obvious.
Instructables DIY powered dolly wity reed swithes
Sparkfun magnetic door switch set and encapsulated reed switch and magnet.
Hall sensor theory of operation
Many ideas here for using hall sensors.
Reed switches


text:
Power source for Arduino uno, sparkfun usb shield and adafruit motor shield
I'm having trouble powering my boards altogether. Right now, I'm using 8x AA batteries to power everything. Running my arduino with one shield runs fine, but not with both shields stacked on top of my arduino. I've even tried powering it with an extra 4x AA batteries on my motor shield, but it still won't run. The way it's stacked is; arduino uno board, usb host shield then motor shield.

We don't know how your batteries are connected, or what power requirements your devices all have.

I have a 8xAA battery holder that's connected to the arduino uno via the 2.1mm plug and on my motor shield I have 2 DC motors and 2 servo motors that all require 6v. If that is what you mean by power requirements(?) If you mean power requirements for boards, I know that with the uno, it is suggested I use between 9v-12v, so I just went by the 12V.  @IgnacioVazquez-Abrams

Sounds odd. Do the lights on the boards turn on? Are the sparkfun and adafruit shields pin compatible? Sometimes shields by different companies use the same pins for transmitting data.

I can power a Mega, motor shield and a wifi shield connected to 2 motors, a servo and a variety of sensors using 4-5 AA batteries, so 8 should be more than adequate for your needs.

Yes, the lights on all boards are turned on. I've tried again with all boards stacked on top of each other and realised that the USB host shield works when I disconnect 2 servos from the motor shield. However, the DC motors from the motor shield still does not work. I'll look into the pins now. But if they do use the same pins for transmitting data, is there a solution for that? Thanks @bladepanthera

If that is the case, you might have to get clever with some rewiring of pins. I had to do that for my adafruit wifi shield as it uses the same pins as my arduino motor shield. Cross that bridge if it comes to it, though!

Can I ask, how did you find out that they used the same pins? @bladepanthera

Documentation for the boards. They usually clearly describe which pins are being used.

IF your motors are powered VIA the Arduino board "there will be problems". The motors should receive power directly from the battery on their own voltage input line. If the power goes via the SArduino board you have a good chance of noise problems AND if the Arduino voltage regiulator is used you will exceed its ratings for all except the tiniest of motors. As ever a circuit diagram is essentially mandatory. Words are often very ambiguous in situations like this. Your actual question gives no clues at all and your comments cannot be interpreted with certainty.

I've already tried powering the motor shield with it's own power source using 4xAA battery holder, while at the same time powering the arduino with 8xAA battery holder. But the motors still won't move when it's stacked on top of the usb host shield and arduino board. @RussellMcMahon

(1) Circuit diagram !!!!!!!!!!!!!!!!!! please (2) When you say "still won't move" the meaning is potentially broad. ... when you do what? When what is connected how. Saying shields stacked on top of each other is about information free - that's what shields do. | You say "USB host shield" Which one? Web reference? Maker?  What happens i it is absent, if you know? If you don't know, why not? | What happens if you power the motor boaard stand alone and the assert the motor activating pins with a jumperto +5V or whatever is required ? If you have not done it you should do so and report back. ||

You say the motors do not move but, why should they? Have you chcked at the shield input that the signal that is meant to make them move is appearing at thje pin that you think it should ? This can be done with a meter oran LED and a resistor. etc. | At the moment from our viewpoint you are supplying semi random pieces of information with their relatrionshiop not obvious and gaaaps. You need to supply a coherent consistent complete picture if you want to maximise use of the available hive mind.

Did you check about pin compatibility? And what code are you using to run the motors? The standard example?

AA batteries are fine for small hobby motors - the issue is that you shouldn't be running the motors off the same regulator as the logic circuitry.  Ideally you would not run the motors off a regulator at all, but rather choose some suitable for the voltage of the pack itself.  You may however need to obtain a lower dropout regulator for the Arduino, or reduce it's operating voltage to 3.3v - the stock 5v regulator may start to drop out if the battery pack voltage dips below 7.something volts under load of the motors.

Its a very bad idea to power everything from the same battery source. Most motors, especially ESP, generate large current spikes, rather than draw a small current throught. AA batteries are not designed for this.
You can get away with using AA batteries for micro-controllers, shields. However, keep motors on a sweater power supply. There are batteries for specific motor types, and these will typically have a high current rating. Of course, without a circuit diagram, I cannot go into details. I'll update my answer when you do.

It's not "a very bad idea" it merely requires some care - and a lower dropout regulator than stock wouldn't be a bad idea.  What is a problem is trying to run the motors off the logic regulator.


text:
Controlling 2WD car chassis with PS3 controller
I'm having trouble with controlling my car with the PS3 joystick, and there hasn't been any example codes out there. I'm using;

PS3USB library from USB_Host_shield_2.0 library
Freetronics H Bridge shield http://www.freetronics.com.au/collections/shields/products/hbridge-dual-channel-h-bridge-motor-driver-shield#.VXMqXUJJmgM

This is my code;
include <PS3USB.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
//PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

bool printAngle;
uint8_t state = 0;

int motora1 = 4;
int motora2 = 7;
int motoraspeed = 6;
int motorb1 = 3;
int motorb2 = 2;
int motorbspeed = 5;

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nPS3 USB Library Started"));
  pinMode(motora1, OUTPUT);
  pinMode(motora2, OUTPUT);
  pinMode(motoraspeed, OUTPUT);
  pinMode(motorb1, OUTPUT);
  pinMode(motorb2, OUTPUT);
  pinMode(motorbspeed, OUTPUT);
  delay(5000);
}

void loop() {
  Usb.Task();

  if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

    //go forward
     if (PS3.getAnalogHat(LeftHatY) == 0) {
       Serial.print(F("\r\nLeftHatY: "));
      Serial.print(PS3.getAnalogHat(LeftHatY));
         digitalWrite(motora1, HIGH);
          digitalWrite(motora2, LOW);
          digitalWrite(motoraspeed, 255);
        digitalWrite(motorb1, HIGH);
        digitalWrite(motorb2, LOW);
        digitalWrite(motorbspeed, 255);
}

//go backward
if (PS3.getAnalogHat(LeftHatY) == 255) {
       Serial.print(F("\r\nLeftHatY: "));
      Serial.print(PS3.getAnalogHat(LeftHatY));
           digitalWrite(motora1, LOW);
  digitalWrite(motora2, HIGH);
  digitalWrite(motoraspeed, 255);
  digitalWrite(motorb1, LOW);
  digitalWrite(motorb2, HIGH);
  digitalWrite(motorbspeed, 255);
}

//turn left
if (PS3.getAnalogHat(RightHatX) == 0) {
       Serial.print(F("\r\RightHatX: "));
      Serial.print(PS3.getAnalogHat(RightHatX));
           digitalWrite(motora1, HIGH);
  digitalWrite(motora2, LOW);
  digitalWrite(motoraspeed, 200);
  digitalWrite(motorb1, LOW);
  digitalWrite(motorb2, HIGH);
  digitalWrite(motorbspeed, 200);
}

   //turn right
   if (PS3.getAnalogHat(RightHatX) == 255) {
       Serial.print(F("\r\RightHatX: "));
      Serial.print(PS3.getAnalogHat(RightHatX));
          digitalWrite(motora1, LOW);
  digitalWrite(motora2, HIGH);
  digitalWrite(motoraspeed, 200);
  digitalWrite(motorb1, HIGH);
  digitalWrite(motorb2, LOW);
  digitalWrite(motorbspeed, 200);
}

As of now, when I look at my code in the serial monitor, I get the following;
LeftHatY: 131
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127

The numbers adjust as I'm moving the joystick around but just keeps going even though I'm not moving the joystick around. Any help would be appreciated, thanks

I found three issues:

You don't have a # before the include on line 1.
There is no } at the end of the void loop().
You forgot to include an if statement for when the joystick is idle.

Try this code:
#include <PS3USB.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
                  //PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

bool printAngle;
uint8_t state = 0;

int motora1 = 4;
int motora2 = 7;
int motoraspeed = 6;
int motorb1 = 3;
int motorb2 = 2;
int motorbspeed = 5;

void setup() {
    Serial.begin(115200);
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); //halt
    }
    Serial.print(F("\r\nPS3 USB Library Started"));
    pinMode(motora1, OUTPUT);
    pinMode(motora2, OUTPUT);
    pinMode(motoraspeed, OUTPUT);
    pinMode(motorb1, OUTPUT);
    pinMode(motorb2, OUTPUT);
    pinMode(motorbspeed, OUTPUT);
    delay(5000);
}

void loop() {
    Usb.Task();

    if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

        if (PS3.getAnalogHat(LeftHatY) == 0) { //go forward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 255);
        } else if (PS3.getAnalogHat(LeftHatY) == 255) { //go backward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 255);
        } else if PS3.getAnalogHat(RightHatX) == 0) { //turn left
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 200);
        } else if (PS3.getAnalogHat(RightHatX) == 255) { //turn right
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 200);
        } else { //stop moving
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 0);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 0);
        }
    }
}


text:
Why is Toolchain Not Updated with Arduino IDE Install on Mac
I have not been doing any Arduino work for about a year.  The last time I ran the Arduino IDE was in the previous version of MacOS.  Now that I have updated to the latest MacOS Version Catalina (10.15.2) I discovered that the IDE will not compile because the avr-g++ compiler is 32 bit and will not execute on the now 64-bit required MacOS.
So I did the obvious thing.  I went to the arduino.cc web site and downloaded the latest version of Arduino IDE thinking that this should solve the problem.  I updated to version 1.8.11 of the IDE but the 32-bit problem persisted.
I finally decided that the IDE was updating (new Arduino IDE app) but that the avr toolchain was not being updated.  To force this update, I deleted the entire avr toolchain from my ~/Library folder.  Now, re-running the IDE is all it took:  It discovered the toolchain missing and re-installed and installed with the correct 64 bit binaries (which were part of the new Arduino App all the time).
Perplexing -- why was the toolchain not updated with the install?  Is it a requirement to delete the existing toolchain before doing a new install of the Arduino App?

The boards packages maintained by Boards Manager and associated tools are installed in .arduino15 folder. The AVR boards package bundled with IDE is only used when there is no AVR boards package version in the .arduino15 folder.
To locate the .arduino15 folder open Preferences in IDE and there at the bottom of the window is displayed the location of the preferences file with full path to .arduino15 folder.
The content of .arduino15 folder is not changed with IDE update.

If content is not changed in .arduino15 folder than how is it installed in the first place.  I never explicitly installed that folder.  It is certain that Arduino app does indeed install it because after deleting the folder a new copy was indeed installed merely by re-running Arduino (rerun, not install).

@K7PEH, of course the folder is created if it doesn't exist and the preferences file is stored there. but boards packages are installed there only if you install them with the Boards Manager in IDE


text:
UART Transmission Incorrect on ATTiny826
I'm currently trying to test an extremely simple circuit where I use an ATTiny86 to output some arbitrary values via serial to an Arduino micro. The problem I am facing is that all of the values being written to the TX pin of the device are wrong. I am using an oscilloscope to measure the values as well as the arduino micro.
The oscilloscope images attached display what I am seeing when I measure the Tx/Rx line between the ATTiny and the Micro. Basically, the values that I try to send are not being sent correctly. The actual waveform looks alright, but the binary representation as measured by the scope and the micro are the same incorrect value. I have some examples shown below:
I cannot for the life of me figure out why the data is being corrupted in such a way. I've added extra images to hopefully help someone decode why this is happening.
Sent: [01 02 03 A5 FF 7E] --> Recieved [C1 D0 58 FA 9E]

Sent: 0xAA (0b10101010) --> Recieved: 0xB4 (0b10110100)

Sent: 0x55 (0b01010101) --> Recieved: 0x8B (0b10001011)

Sent: 0x81 (0b10000001) --> Recieved: 0xA1 (0b10100001)

Simplified Schematic:

Code on Attiny
#include <Arduino.h>

#define LED_PIN PIN_PC3

void setup() {
    // Initialize Serial1 communication at 19200 baud rate (or adjust as needed)
    Serial1.begin(19200, SERIAL_8E1);
}

void loop() {
    // Array of hexadecimal values to send
    uint8_t hexArray[] = {0x01, 0x02, 0x03, 0xA5, 0xFF, 0x7E};  // Example hex values

    // Loop through the array and write each value to Serial1
    for (int i = 0; i < sizeof(hexArray); i++) {
        Serial1.write(hexArray[i]);  // Write each value to Serial1
    }

    // Add a delay to avoid flooding Serial1
    delay(1000);  // 1 second delay
}

you don't have the grounds connected

why do you believe that the problem is with the transmitted data?

@jstola grounds are connected as USB and ATTiny are run on same power/gnd net. Even with GND connected directly I get the same results.
I believe it's due to the transmission of the data because I am recieving the same incorrect results on both the Micro and via the oscilloscope. I have had success reading the UART of an UNO and Micro via the same oscilloscope, same code, same settings, but it does not work with the ATTiny.

the oscilloscope pictures show correct data ... the baud rate may be too high ... try lowering the baud rate

I tried lowering it down to 9600 and 2400 but I still get exactly the same data in the oscilloscope and micro. I also tried increasing it to 115200 and got the same effect.

set the baud rate to 18000? ... I can't run a test right now to see if it is a valid value ... leave the receiver  at 19200

@jstola, That almost seems to have worked. I changed it to 18000, no dice, but then I changed it to 16000 and it worked. My thinking now is that the ATTiny Clock is set to 20Mhz but platformIO is assuming it is using the 16MHz internal clock. The ratio of 16:20 is 0.8; 0.8 * 19200 = 15360, and it seems to work at this baud rate. Does this sound like I'm on the right track?

You are sending 11 bits per transmission, 1 start bit, 8 data bits, 1 even parity bit, and 1 stop bit. The records and the source show it.
The time to send 10 bits (start bit to parity bit) can easily be read from the single byte transmissions. It is about 415 µs. So the time for one bit is about 41.5 µs.
The time to send 6 bytes 11 bits each = 66 bits is about 2750 µs. So the time for one bit is again about 41.5 µs.
The reciprocal value gives us the baudrate, which is about 24100 bits per second. The oscilloscope's serial decoder and the Arduino's UART expect a standard baudrate, most probably you use 19200. No surprise that they interpret the bits as other values, as they sample the line at different times.
Therefore, the system clock of your ATtiny826 is not what the compiler thinks it is. Check that, and correct it.
The transmission is not corrupted, all bits are exactly as they should. It is just the speed, derived from the ATtiny's clock.

Thanks! I set the board clock in platformio.ini by updating the line:
board_build.f_cpu = 20000000L
I must have told the device to use the 20MHz internal clock instead of the 16MHz internal when I set up the updi programmer. This is now working as intended.

@PatrickVoorhoeve The quotients match. Perfect!


text:
Arduino Serial to USB=>serial data issue
I am using Mega 2560 to receive serial data from another device but the data appears on the serial terminal are strange characters. then i connected my USB to serial cable (HL-340) to the device and tried in serial terminal(Termite), data is landing fine.
Replaced Arduino with another one since I believed there could be a problem, but the problem persisted.
for further investigation i have connected my Arduino (Mega-2560) to my serial(USB->Serial) cable directly to receive data on the terminal but strangely even this is showing the wrong data (Arduino terminal is displaying the wright data but the data appears on the other terminal is wrong) sendind "c" receiving "N"...
what could be the reason for this..its a simple code to print character on the screen.
Thx

You have an rs232 cable not a UART cable.

Google "Arduino MAX232"

You need to be careful. Normal devices that have a "Serial" interface actually have an RS232 interface. While the data transmission scheme is similar with the "Serial" interface on the Uno/Mega (UART on TTL logic), RS232 has totally different voltage levels (up to -15 to +15V), which can kill your Arduino.
To connect an RS232 device to an Arduino you need a level converter (to convert between the RS232 levels and the TTL (Transistor Transistor Logic) level of the Arduino. The chip MAX232 is typically used for this. There are many resources about that on the web and even ready to use modules, which are equipped with a MAX232 and a RS232/Serial plug.


text:
Why does Arduino Nano 33 IoT always choose the weakest WiFi BSSID?
I have an Arduino Nano 33 IoT configured to connect to my WiFi network with a pretty straightforward code:
#include <WiFiNINA.h>

int status = WL_IDLE_STATUS;
status = WiFi.status();
while (status != WL_CONNECTED) {
    status = WiFi.begin(ssid, pass);
    if (status == WL_CONNECTED) break;
    delay(5000);
}

My problem is that in an environment with multiple access points sharing the same SSID (roaming environment) my Arduino is constantly connecting to the weakest one of the access points.
I verified with WiFi Explorer on my laptop that multiple access points are in reach at the same location where the Arduino is placed and for some reason my Arduino decides to connect to the base station with BSSD ending :CA:81, which is paradoxly the weakest one:

Is there a way to address this issue?

From you're list you'd only get the choice of the first two as the NINA is a b/g/n only module I think. But not sure why it's not connecting to :58:E2 if it has the same SSID.

What happens when you set the second accesspoint in the list to channel 11?

@ocrdu Unfortunately changing channel to 11 and resetting the Arduino did not help :(

@DanSheppard Yes, exactly.

On Nano 33 IoT the WiFi network adapter is NINA esp32 module with Arduino's nina-fw. nina-fw is written with the use of ESP-IDF framework by the esp32 manufacturer Espressif.
To connect to an AP the ESP-IDF has a configuration function, which takes a structure with settings. One of the settings is wifi_scan_method and nina-fw uses WIFI_FAST_SCAN. The alternative is WIFI_ALL_CHANNEL_SCAN.

WIFI_FAST_SCAN Do fast scan, scan will end after find SSID match AP

There is no simple solution for this. I don't know why they changed the setting. If it should be configurable then the firmware and the WiFiNINA library have to change to support it.
Or you can get the sources of the firmware, change the setting, build the firmware (it is not trivial) and flash it to NINA on your Nano.

This is a VERY good clue, but I think we should complete this answer with a working code. According to the changelog (https://github.com/arduino/nina-fw/blob/master/CHANGELOG), the WiFiNINA library has changed the default behaviour from WIFI_ALL_CHANNEL_SCAN to WIFI_FAST_SCAN between versions v1.2.1 and v1.2.2 in 2018. They also added a setScanMethod in v2.0.0 (in 2021), sadly, this version is not yet available in the Arduino package manager. I can't really find an Arduino specific documentation for calling esp_wifi_set_config based on your answer. I guess I can downgrade to 1.2.0...

@adamsfamily, setScanMethod was added in esp32 Arduino WiFi library which has nothing do do with Nano 33 IoT

All right but how to configure WIFI_ALL_CHANNEL_SCAN with the Arduino library? I'm not able to call the esp_wifi_set_config as the Arduino IDE complains that the function does not exist :( Should I fork the Arduino WiFiNINA library and hardcode complete scan? I am very surprised that this is the default behaviour because connecting to the strongest base stations is key in a WiFi environments, especially in IoT. I'm surprised that no one else has the same problem?

@adamsfamily the esp_wifi_set_config  is used in firmware running in the NINA module, not in the WiFiNINA library which is used in the main SAMD MCU

Ok, let me restate my question :-) Do you see any possible solution for the Arduino Nano 33 IoT?

@adamsfamily, no simple solution. I don't know why the changed the setting. if it should be configurable then the firmware and the WiFiNINA library have to change to support it. Or you can get the sources of the firmware, change the setting, build the firmware (not easy) and flash it to NINA on your Nano (easy)

Got it. In that case your answer should be the accepted answer. May I suggest editing it so that it says: "Reason:   Solution: No easy solution, because "? I think this will help others. BTW I'm very-very surprised that nobody complained about it, selecting the strongest AP critical in a multi-AP environment where they share the same SSID...

@yes, I added that to the answer.  I did build modified versions of the nina-fw. It is simpler on Linux.

Thanks, I accepted the answer. I'll try to report this towards the Arduino development team because I think this is really essential.


text:
Can the USB interface IC be identified via code alone?
I know that the master controller can be found in verbose upload output in IDE, but I have a few boards from different manufacturers and my smartphone camera is apparently insufficient to take a legible picture. Is there something I can do from the PC, either via official IDE or otherwise, that will return usb controller chipset?

did you look into driver details in Windows Device Manager?

Which property do I need?, meaninng, there is a dropdown under Property, Which option contains the chip?
c
ETA:N/M It's Driver Description. If you write an answer I will accept.

If the Device Manager does not give a sufficient answer directly, it tells you the VID:PID combination that identifies each USB device. Use this numbers to ask your favorite web search engine.


text:
How to connect Draw wire encoder to Arduino Uno?
Hello Stack Community,
I am new to Arduino, and I am trying to figure out how to connect a draw wire encoder to Arduino and collect data from it.
I have attached a link of the product that I currently have, which also has datasheet, incase anyone needs more information.
https://www.kuebler.com/en/products/measurement/linear-measuring-systems/product-finder/product-details/A30
I know that the encoder's output is through analog, but I am having trouble with connections as well.
To summarize, how can I connect the encoder to Arduino Uno?
Lastly, I am using the encoder to measure linear distance of linear actuators.

The simplest way is to use the version with potentiometer output:

simulate this circuit – Schematic created using CircuitLab
Connect the wiper to an analog input (A0 in the example), and use the analog reference voltage as "supply" voltage.

Hi Busybee, Thanks so much. It worked, well. I was able to convert analog values to digital values and then to volts. Since I am converting digital values to volt: I will have 0 digital value = 0 volts & 1023 digital value = 5 volts, I also know that 0 volts = 0 mm & 5 volts = 600 mm (based on draw wire encoder max & min range). Based on all of this how to convert volts to millimeters, any idea?

Why not simply multiply by 1000? -- Oh, BTW, you might like to mark the answer, comments with "thank you" are kind of frowned upon. ;-) This will help future visitors of this site, too, to decide which question/answer to read.


text:
Nano RP2040 Connect with Wired Ethernet. Do I lose IoT functionality and OTA updates? Any suggestions?
So, we have a project that is developing nicely on the RP2040, and currently uses WiFi. However, a new use-case is emerging where it may need to be in a noisy industrial environment. As such it makes sense for it to be physically connected (ethernet) rather than wifi (industrial environments can be very noisy, and not every factory has a full high quality wifi).
I know there are SPI modules such as a board based on the W5500 chipset, but they beg questions:

will I lose the IoT and OTA update capability this way?
Can I get PoE via a module as well, so my customers have an easier installation?
The RP2040 is an ideal unit for us - IoT and OTA updates, with huge flash as well, so I'm not sure there's a sensible alternative (unless anyone can suggest one!). Everything else we need is in the arduino libraries as well, so that is also a great fit for us.

lose IoT functionality ... what does this mean?


text:
AsyncMqttclient publish affects accelerometer readings
Using M5StickC ESP32 with built-in MPU6886 accelerometer to read vibrations. In the loop() section the code gets 10 readings per second and if the readings exceed a threshold, it starts publishing the results in a JSON MQTT message on asyncmqttclient, again 10 publishes per second. The period of full publishing continues on until the readings fall back under the threshold+5 seconds.
However,when it starts publishing 10 messages per second, the accelerometer readings go haywire and the values are higher than they should be in reality. This is the results under asyncmqttclient publish:

The blue ellipse is just one knock. Goes up and down, and the vibration ends there. However the green ellipse part is the period where the code sends the publish messages, they should normally be down and silent like this:

This second graph values are from the same code, the only difference is i commented out the asyncmqttclient publish mqtt command. If i use pubsubclient it also gives the correct values.
if (eq_status) { // Earthquake still happening
  eq_time_count++ ;

  if (((slta && !staLta.checkTrigger()) || (!slta && eq_time_count > eq_pet)) || (master && !slave_eq_state)) { // EQ Ends...
      eq_status = false;
      eq_time_count = 0;

      updateState("LISTENING");

      publish_mqtt(MQTT_PUB_EVENT, updateEvent(ax,ay,az,pga).c_str(), 0, true);

      digitalWrite(M5_LED, HIGH);
      if (SPK_HAT) ledcWriteTone(spkChannel, 0);
      lcd.set_brightness(lcd_brightness);
  } else {
    /* THIS IS THE PROBLEMATIC PART */
    publish_mqtt(MQTT_PUB_EVENT, updateEvent(ax,ay,az,pga).c_str(), 0, true);
    /*client.publish(MQTT_PUB_EVENT,updateEvent(ax,ay,az,pga).c_str());*/

  }
} else {
    if (flush_update) { // Send periodic event update message
    flush_event++;
    if (flush_event > (flush_period*10)) {
      publish_mqtt(MQTT_PUB_EVENT, updateEvent(ax,ay,az,pga).c_str(), 0, true);
      flush_event = 0;
    }
  }
}

I think there could be something wrong with either asyncmqttclient or espasyncTCP, or could there be any other cause?

Decreasing 10 publishes per second to 5 publishes helps a lot. Is it a problem of message buffer?

I could be missing something. But this might be viewed as too general a question. Perhaps if you broke it down more and tested those smaller aspects of the project before coming here we could better help.  In the mean time, the MPU-6886 can be I2C or SPI.  Have you tried both?  And the async-mqtt-client has its own web page.  Have you looked there for answers ... through the open issues?

"Is it a problem of message buffer?"  Maybe.  I am not familiar with ESP32 I2C HW.  Or, if you are using a SW implemented I2C (or SPI, you didn't say which mode you set the MPU-6886 to) to talk to the MPU-6886 it may be adversely affected by the async-mqtt-client SW.  This is an embedded environment, not a real OS.  If async-mqtt-client is using a lot of the CPUs time, this may impact the expected operation of your code or features (like I2C) your code is depending on.

I am using I2C, couldn't find the SPI library of it. asyncmqttclient has no information in this kind of problem. I heavily suspect that the problem may be about the TCP buffer since decreasing the publishes per second helped. But I still don't have any clue how it can affect the accelerometer read values.


text:
How to get the signal strength of the network connected with the ESP8266
I am using ESP8266 module with Arduino Uno.I don't know how to get the signal strength of the network with which ESP8266 is connected.Please help..

The page http://tomeko.net/other/ESP8266/ names the following command:

AT+CWLAP     // list available access points

According to the example given there, this returns a list of items looking like this:

+CWLAP:(3,"UPC784xxx",-75,"70:54:d2:xx:xx:xx",1)

where "APs are sorted by channel and values are: (security, "name", signal strength, MAC, channel) where for security: 0 = open, 1 = WEP, 3 = WPA, 4 = WPA2".
Thus you can use AT+CWJAP? to obtain the name of the network you're connected to and get the signal strength from the respective item in the list provided by AT+CWLAP.
See http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module for a reference of commands.

The security is wrong. Correct are (according to the documentation 0.2 from March 20, 2015): 0 = open, 1 = WEP, 2 = WPA_PSK, 3 = WPA2_PSK, 4 = WPA_WPA2_PSK.


text:
How to connect twenty different serial devices to an Arduino Mega?
I want to connect 20 serial devices to the same Arduino Mega.How to do this?I know that multiplexing is the way but how to do that

How much data needs to move around for each device? do the devices ever need to start their own transmissions or can the arduino get everything done by polling them? how often are they transmitting?

What kind of serial communication? SPI, I2C, UART? What devices? Specifics would be helpful here.

all of them are working on RS232

everything is same as GSM , every devices send data at speed of nearly 1 bit per second

Please edit your question and clearly identify the specific protocols you are asking about.  I'm not aware of any GSM data rates as slow as 1 bps; most are thousands of bps to hundreds of thousands.

You can use the SoftwareSerial library and declare instances to communicate with your serial devices. I am not sure if you can declare 20 such different instances but if at all you do, use the function: listen() to switch between those serial devices. This, probably, is as close as it gets to multiplexing as you mentioned.
I've tried with 2 such SoftwareSerial instances for communicating with GPS module and GSM module and the listen() function worked flawlessly.
Cheers!

You say that they are working on RS232 - which is an electrical standard.  You may mean that they use standard UART style asynchronous serial communications - perhaps at 0 to 5V electrical levels.
It depends on how fast you need to communicate, and how continuously you need to communicate.   If you can choose when to communicate with each device, you may be able to use Soft Serial with multiple pins.  Be aware that it cannot both transmit and receive at the same time (one or the other), and it can only communicate with one port at a time.  So it might work for you if you can communicate with one device for a while, then ignore it while you check with other devices, one at a time.
Otherwise maybe not.  For example, if you need to receive from many devices at times of their choosing so you need an always-on hardware UART for each device.  There are 4 hardware UARTs in the MEGA, so 4 would be your limit.
There are things like external UART peripherals, but managing that would likely be very hard for you.


text:
ModbusMaster.h - changing node
I'm using the ModbusMaster.h library on a project, with arduino-uno and a TTL/RS-485 converter, and the function has to identify the slave that it is communicating. The slaves goes from 1 to 16. After I've begun the connection,
ModbusMaster node(1);
node.begin(9600);

I have to send a message, and if this massage returns an error, I have to change the slave number, until I got an valid answer. But I didn't find any functions to close this connection, or to delete it, I even have tried,
delete &node;

but it didn't work. I'm trying to close this connection so I could begin another one with another node, because I didn't find a function to change the slave number.

I see no function to change the _u8MBSlave other that the constructor. My C isn't great by you might try something like node = ModbusMaster(2);

Generally speaking, you should never call delete on something unless you originally created it with new. Attempting to delete an object from the stack could cause your program to crash or misbehave in other ways.

Indeed that would not work. But why not ModbusMaster* node = new ModbusMaster(id), then send, check for error, if so delete *node, ++id, repeat? Not the most efficient, but simple. (You could also add a function to change the id to the library.)

Gerben, it didn't work, =/. Thanks for the tip Peter. Fuenfundachtzig, how do you pronunciate that? O.o, but it didn't work either. But to solve, I had to create a function that keep creating another nodes, and every time it made a new node, it'll send a request, and if the request was an error, it passes to create another node, if the answer was a success, it would made: ModbusMaster node4(4) "if the success was on the 4th try", then: node4.begin(); node = node4;

Maybe this question is too old and the API has changed, so my answer is reference.
The ModbusMaster constructor does not accept parameters.
From reading the source code, the method begin(uint8_t slave, Stream &serial) just initializes variables and can be called again with a new slave value without the need to destroy the ModbusMaster object.
Reference:
[1] https://github.com/4-20ma/ModbusMaster/blob/master/src/ModbusMaster.cpp, line 61.


text:
Port Manipulation - fastest implementation
I'm working on an Arduino program but am getting bogged down on what is the 'correct' implementation. I understand that multiple versions may work, so for my needs the 'correct' version will be the fastest (i.e. executing in the fewest clock cycles)
I need to set three analog input pins on my Mega 2560 - let's call them PF2-0.

I could use pinMode() - but that performs some extra checks that I want to leave out.
I could use _BV() in the process, but that's another function call I wish to avoid.

So, using port manipulation, I can write:
DDRF = 0x07; //PF2, PF1, PF0 as input
PORTF = 0x07; // Disable pullups

This should configure my three pins as inputs - and reduce any extraneous function calls. This should even be faster than writing:
DDRF = (1 << PF2) | (1 << PF1) | (1 << PF0)

Is this the fastest implementation?
*To be honest, I'm not sure how to profile this to know for sure.

Fastest way is to write nothing: all the pins start as inputs by default.

I could use _BV() in the process, but that's another function call I wish to avoid. - it isn't a function, it's a macro. And the compiler optimizes the results. As Edgar Bonet points out, using it three times in one line and ORing the results together, gives you a single machine instruction which executes in one cycle (plus another to write to the register). You can't improve on that.

DDRF = 0x07; //PF2, PF1, PF0 as input - surely that makes them outputs?

@NickGammon, you're correct of course - I was confused.

The standard Arduino way of doing this is to use pinMode(). It's not
fast, but it's easy to understand, especially for beginners. And it's
portable across architectures.
If you want to go fast, then you should skip the Arduino functions and
use port manipulation, and avr-libc. The standard avr-libc way of doing
what you want is:
DDRF = _BV(PF2)   // set PF2 as output
     | _BV(PF1)   // also PF1
     | _BV(PF0);  // and PF0

This compiles to two assembly instructions: one for loading a CPU
register with the constant, and the other to copy the register to the
DDRF IO port. Notice that you set the bits for the pins you want to set
as outputs, and you clear the bits for the inputs. By default, all the
pins start as inputs.
The _BV() here is not a function call: it's a macro that expands to
(1 << (x)). The way you write the expression to the right of the =
sign is irrelevant as long as it is recognised to be a compile-time
constant. If you want to see for yourself, you can disassemble the
generated binary with the command
avr-objdump -S -C my_prog.elf > my_prog.lst

You get an assembly listing interspersed with your source. Doing this on
the example above yields:
    DDRF = _BV(PF2)   // set PF2 as output
         | _BV(PF1)   // also PF1
         | _BV(PF0);  // and PF0
100:    87 e0           ldi r24, 0x07   ; 7
102:    80 bb           out 0x10, r24   ; 16

Here, the ldi instruction means “load immediate”, i.e. load a register
(r24) with a constant value (0x07). The “out” instruction copies that
register into port 0x10 (namely DDRF). Both are single cycle
instructions, so the whole sequence takes two CPU cycles.

AFAIK the compiler should be smart enough to use bit manipulation instructions when in presence of _BV().
When unsure, you can always add -save-temps to the gcc options, to see what the compiler actually does. It will not give you profiling information, but you can see in detail how your C gets turned into assembly.
Remember to pay attention to what level of optimization you use. You should use the same that will be employed in the final version of your code (probably O2).

Probably -Os...


text:
Issue with removing files progrmatically created under "/www/..."
I am having an issue with removing temporarily files I am creating under the /www directory. I have a subdir, "/www/csv",  where csv formatted files are being written based on sensor data. The files are created on-demand on the YUN, placed in the /www/csv dir, with the whole process driven by a REST call and an AJAX implementation in a browser.  The files are created with no problem with a Filesystem.open(path, FILE_WRITE); call. I can also use the Process calls from the bridge library to rename the file after it is full written. However, if I try to use Process calls (i.e. p.begin("rm");, etc, etc) to remove the files after use, the files are never deleted. I also tried the "mv" the files to /tmp so they would get cleaned up by the OS eventually, but that fails also. I have the rights to /www and /www/csv set to "777". I am assuming this is an access rights issue, however I am unsure what user my REST calls are running as (it would be whatever the default is for a YUN as I have created no additional users on the system).
Thanks in advance,
Pete

what user OWNS the files?  If it is root, then root has to delete, even if perms are 777.  Rather than sudo the rm i would chown.   (p.s. 777 is NEVER the answer).

Are you closing the files before attempting to delete them?

@Tyson Everything runs as root under the Yun so I doubt chown would help.

Owner is ROOT and the process runs as ROOT. Files are closed before attempting to 'rm' or 'mv' the files. I've changed the design to stream the XML directly to the calling web page vs. writing a temp file under /www and having the web page reference it as a static XML page. AT some point I'll go back to try to understand why this didn't work in the first place. To support this change I had to add call to the DOM parser since the REST call responses by default use a TEXT Mine type in the response header. Does anyone know how to define a custom Mime response header using REST calls?

@PeteD Please post this as an answer and mark this question closed.


text:
Bluetooth hc-06 and Standalone Atmega168(possible?)
I am making a project that requires bluetooth communication between a Raspberry Pi(equipped with a bluetooth dongle) and a standalone atmega168 circuit.
I want to be able to transfer information serially between the two devices over bluetooth.
I have selected the hc-06 for the arduino and some usb bluetooth dongle for the PI.
I would like to know if connecting the hc-06's TX and RX pins to the RX and TX (respectively) pins of my atmega will work or not. If not, I would like to know how to achieve that (bluetooth on a standalone arduino-powered microcontroller)

Sound fine to me.

The HC-0x Bluetooth transceivers are a drop-in replacement for a serial connection. Once the transceiver is configured (with baud-rate, device name, and pairing PIN #) you can plug it in in place of a serial line and expect to communicate. The device will take care of pairing and accepting a connection from the master device with no need for any code support from the AVR.
I use a separate program on an Arduino or a breadboarded AVR to configure my HC-06es. They retain their configuration across a power-down, and in fact, there is no hardware support for resetting them to a standard configuration; you need a program that figures out their current baud-rate in order to reconfigure them. It can save a bunch of hassle if you write down their configurations whenever you change them.

I have read somwewhere that a circuit for usb to serial is needed. I think that is for converting usb to serial(and back). Is it so ?

You'll need a USB to serial converter to connect your at mega to a computer through USB. But when you want to reprogram your atmega just use the arduino as ISP tutorial.

No circuitry is needed on the Arduino or AVR side; the HC-0x devices are directly pin-to-pin compatible, making them very convenient for standalone AVR devices. If you were thinking of the FTDI (or similar) serial to USB converters on Arduino boards, HC-0x devices don't need one.


text:
Is it possible for the Arduino's digital pin mode to flip from OUTPUT to INPUT unexpectedly?
I have an Arduino project (data logger intended to sample 100 samples per second for months) with firmware that is too long to post. It mostly works as supposed to, but I have a confusing issue I can't figure out: rarely, the indicator LEDs (driven by digital pins) stop working. By rarely, I mean if I run 20 devices for two weeks, maybe one will develop the issue, so it's very hard to test empirically but it's frequent enough that it matters. I know it's not a hardware problem because they start again after a reset. The device apparently continues working fine apart from the LED issue when this happens.
I have three hypotheses:

There's a logic problem in my firmware code. I'm skeptical because the relevant block of code is pretty simple.
A memory overflow or some similar problem causes the program to fail at this one particular task but not others. I'm a little skeptical because the device reports free stack in the metadata every second and it's always over 40 bytes; I may be misunderstanding memory use though.
Somehow, the digital pin (4) driving the LED gets flipped from OUTPUT to INPUT. There's definitely no pinMode(4, INPUT) command anywhere in my code though, so if this is happening it's not my code doing it.

Let's suppose it isn't #1. Considering #2: is it likely that a weird memory issue is causing a very specific failure while not affecting core functions of the device?
Considering #3, is there anyway the register setting a pin to INPUT or OUTPUT could be flipped unexpectedly? It sounds crazy to me but I want to rule it out.
The platform is similar to the Arduino Pro (3.3V, 8 MHz, ATMEGA328p) and I'm running the current IDE version (1.8.13). Thanks for any help.

of course pins can flip unexpectedly ... you just have to make sure that your program does only expected actions

Is the LED going off or going to Input? You normally see that because if a LED is attached to an input pin, it is glimming instead of on or off (because there's some current going out of an input pin).

The LED stops blinking, although it seems very unlikely to me that the relevant code stops running. The pin getting set to INPUT could explain how the LED could stop blinking visibly while the code is still running as normal. The LED's series resistor is only 470 ohms which is much less than the pin's high-impedance state, so even if it did supply some current it probably wouldn't be enough for short-blink visibility in daylight.

Concerning 2.: it's not trivial to get information about free ram on a non-multitasking system, because it will only give you the free ram at the point at which you call the corresponding "get_free_ram()" function. If you call this function in a high scope (e.g. in loop()) it will return something completely different than when you call it in deeper scope, where local variables, return addresses, etc. are also stored in ram. If you don't use dynamic memory allocation, it will always give the same result, but that probably is not the "high-water-mark" of ram usage.

The fact that it is possible to set them incorrectly is why, in some projects where I'm concerned about this, I'll add a small series resistance to an inbound signal.  Should the pin become OUTPUT and driven in an opposing direction to the signal, the resistance serves to prevent a short through both devices.  The possibility is always there, whether you have an outright bug, or instability, or flash corruption.
With pinMode the opportunity to accidentally set your port to the wrong direction is maybe a bit worse than for code that directly manipulates the data direction register.  pinMode calls typically don't get inlined, because pinMode on the Arduino is a fairly complicated function at runtime for what it actually does.  So, there's this generic code that can be jumped to that will set various ports to either direction, as opposed to smaller chunks of code that contain instructions that set specific ports to specific settings.
INPUT roughly takes your digital pin out of the circuit.  And INPUT_PULLUP sort of does that, with the exception that internal to the AVR there's going to be 20k - 50k of resistance going to "5V".  Knowing that, you can test your hypothesis three.  When you find your project in the state where the LED isn't lit, take some some resistance (say 1K) and use it to pull the pin toward "5V".  Then pull it to GND.  Watch the voltage at the pin with a meter.  Based on what you have attached and what you see for a voltage, you can determine whether it has entered the INPUT or INPUT_PULLUP state.  You'll also be able to see if it's just being driven to whatever state you're calling "not working" ("off" I'm guessing).
You can take all the guess work out of what voltages to see in each scenario if you upload a sketch that sets the pin in question to the INPUT, INPUT_PULLUP, OUTPUT/HIGH, and OUTPUT/LOW states and measure the voltage at the pin when you pull it to each rail with your resistor.  Later you can consult the table you've built to see what has happened.
There's only so much to say about this, particularly your first two ideas, without seeing the code and other details.  Just that sometimes otherwise simple code has bugs in it.  In an ATMega328P project, 40 bytes is not a lot of free space at all.  To give you an idea what sort of problem this can trigger: The Arduino implementation of new that's in the 1.8.3 core will happily blow away your register file and whatever else it can get to after that, if the underlying malloc reports not enough memory.  Basically new continues to initialize the object it thinks was allocated even when the pointed returned is nullptr.  The __malloc_margin is 128 in the 1.8.3.  So if you try to malloc with 40 bytes distance between the stack and heap, you will trash your program state, perhaps even setting a data direction register in the process.


text:
Arduino loses its program under unusual conditions
I have a pretty complicated setup: an ATMEGA328p chip (found in the Uno, Duemilanove, etc.) on a Diavolino board (from EvilMadScientist) running at 8 MHz (instead of the normal 16 MHz).  This should be basically the same thing as the 3.3V arduino pro from the code's point of view.  On top of this is a custom shield including a bunch of digital and analog devices with SPI, I2C, and serial interfaces.
This is supposed to run for days or weeks at a time.  In normal conditions--on the ground outside--it does fine.  However, in two recent tests, it lost its program and stopped working.  One of these was in a cold low-pressure chamber (-40 C/F).  The other was outside mounted on a flying quadcopter.  Reprogramming it fixed the problem; before reprogramming, neither a reset nor power-cycling would get any response from it.
Has anyone ever heard of an arduino bricking itself like that?  My best idea for how this could happen is that somehow the chip was put into a state where it treated incoming serial data as a new program to run.  Also, I'm speculating that connections between the two boards could have been disrupted by thermal contraction or vibration in those tests.
Thanks for any help!

Are you using the watchdog timer at all? It would be virtually impossible for random serial data to be treated as new code.

According to the datasheet it will operate at between -40 °C and 85 °C. -40 C/F - I'm not familiar with the temperature unit "C/F".

Did you disable brownout detection?

C/F just meant it's at both -40 C and -40 F because those are the same.  I don't know anything about the watchdog timer, so I would assume I'm not using it.

And, I did not disable brownout detection.

I would suggest that you reproduce the issue and then use a device capable of reading the flash, to confirm that it's still identical to the .hex file that was used to program the board.
I know that the AVRDragon can do it and maybe also cheaper USB ISP programmers can do it too.
But it seems that you are not alone.
Flash memories like those used in uC work by trapping electrons in wells of charge, so that they pseudo-permanently affect the silicon.
Very low temperatures can change the properties of the insulation, letting many more electrons than usual to escape.
Try to wrap the board in a thermal airtight insulator, possibly providing local heating. That should solve your problems.

Thanks!  Any idea how the quadcopter failure could have happened?  Could vibration somehow cause a similar effect?

I doubt vibration is the cause. Do you have any strong electromagnetic field nearby the processor or any of the cables? Or, more likely, it's a different problem.

Yes, the quadcopter has four brushless motors and two radio transmitters.  Could interference from those really disrupt the flash memory?

As I wrote, most likely not.
But can you reproduce the problem with the quadcopter?
Because it should be easy to remove each potential source of disruption (motors, radios) and see if the memory is still corrupted/wiped.


text:
What are the implications of running an ATmega328P at 8 MHz and 3.3 V with the Arduino system?
I'm working on a custom arduino that will run at 3.3 V with no regulators or USB chips (for power consumption).  I've heard that overclocking the chip at 16 MHz/3.3 V is generally fine, but I'd like to stay within spec anyway.
First: to run at 8 MHz, do I just need to replace the crystal?  Or is there anything else I have to do?
Second: Do I need to make any code changes to reflect the new speed?  I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.  Will any of these be broken?  Will the code run noticeably slower?
Third: How can I program the chip?  Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?
Fourth: Will power consumption change at 8 MHz?
Thanks!

There are plenty of 3.3V Arduino-compatible boards, Sparkfun Pro mini being one example. It is supported by the IDE so all clock-specific adjustments will be made for you once you pick it from the 'boards' dropdown.

At 8MHz you'll probably be okay using the internal oscillator instead of a crystal. Beware when you compile code that when you for example pick "Pro Mini 328p at 8MHz" that 8 gets applied to code, so I wouldn't suggest compiling for 16MHz and then transplanting or you may find that a delay(1000) takes two seconds as a simple example. And check out power saving/sleep in the H2OhNo code. (Another moment when I suggest you get any programmer at all instead of limiting yourself to serial uploads, search Tindie for "ISP.")

The formula seems to be volt*5.9-6.6=mhz (valid between 1.8v and 4.5v), so at 3.3v, this would give 12.8mhz. Be aware that, if you are running at 12.8mhz, ANY drop below 3.3v MAY cause problems (and very hard to diagnose, too!) or you MAY get away with it.
However, Arduino Atmega328p chips have a "brown-out" detection set at 4.3v - any drop below that, the chip shuts down. You can get an ISP (AKA ICSP) to change the fuses - go to http://www.engbedded.com/fusecalc/ to work out what to set fuses to. You can also use the ISP to read the current fuses, or indeed reprogram the chip without an Arduino board - all my projects have a 6-pin header. If you do this, before reprogramming using the Arduino board, you will have to "Burn Bootloader" (in the tools menu). Note that programming can still be done via Arduino IDE.
Alternatively, if you want to go "light" (and have an ISP), you can change the fuses to use the internal 8mhz clock - this frees up 2 extra pins, too! Be aware, however, that the internal clock may drift 1.2 hours per day (=5%), compared to 1.7 seconds per day (=20 parts per million) on a typical quartz crystal. If you don't use it for timekeeping, this probably doesn't matter.
You will need to make changes to the timing, for your code - you need to add a boards.txt with correct settings for your chip/clockspeed etc - you can copy the settings from the entry for the board, change the name, and change the setting "build.f_cpu"; restart (or start) your Arduino IDE, go to "Tools->Board" and select the board you added.
You can move the chip on/off the board, and reprogram it there (note that the board selected in Tools->Board is the FINAL board, not the programming board). Be careful plugging/unplugging it - eventually, you WILL bend the pins! Alternatively, you can use ISP (ICSP), as mentioned above - much recommended. ISP programming will also work if the chip is factory default, so long as it has a working clock.
How much power is used by the chip depends hugely on what you do with it - not just clock speeds, clock source, etc but also sleep modes. If you are sleeping a lot, it may draw less when running faster than running slower - if almost all your time is asleep, then the power consumption should be counted per clock cycle, not per second - if your clock is half the speed, and half current, then you draw the same current per instruction. Since the rest of your time is spent asleep, you get no benefit. See http://www.gammon.com.au/power for a very good breakdown of power usage, tips on how to save power, etc.
If you slow your clock down too much, serial and i2c may become unreliable (unless you slow down the speed), but I would expect to be able to go down to  1mhz before this to be a problem - a 1mhz chip trying to do 9600bps has 104 instructions per bit of data transferred. i2c runs at 100khz, so you get 10 instructions per bit (at 1mhz) - possibly pushing it. 8mhz should be fine. Test, test, test.
UPDATE:
There are 3 possible settings for the brown-out detection - there are 3 possible values for the AtMega328p: disabled, 1.8v, 2.7v, and 4.3v. I was under the impression (above) that Arduinos were normally set to 4.3v; apparently that is not the case (see comment below). I recall seeing somewhere that there was brownout detection. This is something to keep in mind, if your arduino resets, especially when putting larger loads on the battery (running motors, multiple leds etc).

Thanks for this response!  I'm a bit baffled by what you said about the brownout detector shutting down below 4.3 V.  I'm running at 3.7 V now and it works fine; didn't have to make any changes to the fuses.

@user40, see "UPDATE" section at the bottom of my post.

First: to run at 8 MHz, do I just need to replace the crystal? Or is there anything else I have to do?

No, run on the internal oscillator as suggested by AMADANON Inc.
Alternatively, set the "divide clock by 8" fuse (which would run it at 2 MHz from a 16 MHz crystal) and then in code change the division back up to 2. ie.
#include <avr/power.h>

void setup ()
  {
  // slow clock to divide by 2
  clock_prescale_set (clock_div_2);
  } // end of setup

Or for programming in another Uno leave the fuse alone, program at 16 MHz and then drop the clock down in the target chip, hoping it works long enough at 3.3V to execute that first instruction. The safest thing would be to just install an 8 MHz crystal or resonator on the target board. However if timing is not critical run with the internal oscillator.

Second: Do I need to make any code changes to reflect the new speed? I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.

If you tell the IDE you have an 8 MHz processor (eg. a Lilypad) then it should adjust delays, baud rate calculations etc. appropriately.

Will any of these be broken?

I2C and SPI are self-clocked. They can run at a variety of rates. I doubt there will be any problems with them. As for serial, providing the calculations are done right a wide range of baud rates should still be available.

Will the code run noticeably slower?

Well yes, it will run at half speed compared to 16 MHz.

Third: How can I program the chip? Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?

You can do that. Or you could connect up an ICSP header or an FTDI header and program it in situ.
Examples here: http://www.gammon.com.au/breadboard

Fourth: Will power consumption change at 8 MHz?

Yes, it is reduced somewhat.
You can reduce it considerably more by using other techniques as described at http://www.gammon.com.au/power, and referred to by AMADANON Inc.

Thanks Nick!  I've actually read your website before and it helped me cut my power consumption radically.  As a result, AAs and AAAs are now a viable power source for this device, which is a big deal because weight matters.  So thanks for that website too--it's a huge service to the community and really helpful to people like me.


text:
Why does a simple LED Blink not work using mbed.h PWM and Arduino Nano BLE?
I have set up a very simple test program to blink an builtin LED using PWM. Following the mbed example and setting the period to 4 seconds (0.25 Hz) and duty cycle to 0.5, the expected behaviour is for the LED to be on for 2 seconds and off for 2 seconds. However, the actual behaviour is that the LED flashes extremely quickly (almost imperceptable to the eye).
#include "mbed.h"

mbed::PwmOut ledPin = mbed::PwmOut(P0_13); //builtin led pin

void setup() {
  ledPin.period(4.0f);
  ledPin.write(0.0f);
}

void loop() {
  // put your main code here, to run repeatedly:
  ledPin.write(0.5f);
}

I have tried adding delay() and wait_ns() with different times in the main loop, tried having the main loop empty and setting the duty cycle in the setup() function as well as changing the period to larger numbers just in case it was in milliseconds all to no avail. Not quite sure what I'm missing from this extremely simple example.

According to mbed example, to create an instance of PwmOut object, it should be PwmOut ledPin(P0_13). For the setup(), set the duty cycle to 50% with ledPin.write(0.5f);, and delete the code within the loop() as itself is already a while(1) loop.


text:
How to use LiPo powered Arduino Nano BLE when it's charging (with a charging circuit and a boost converter)?
I have a project where Arduino Nano 33 BLE (3.3V operating voltage) is powered by a LiPo battery. The battery is charged using Adafruit's MicroLipo Charger it is then connected to Adafruit's MiniBoost to boost the voltage to 5V and that powers the Arduino through Vin as well as a logic level converter.
Ideally I'd like to use the device while it's charging. The MicroLipo charger provides a USB C breakout board providing a 5V pin. Is it a bad idea to connect 5V output from the boost converter and from USB C to th same power rail as shown in the frtizing sketch? My gut says try it, my brain says this is a dumb idea.
Is there a way I could use something as a switch which takes in 5V from both the cable and the battery only uses the battery when cable voltage is 0V (not connected)?

I would definitely not do that. You try to short the USB 5 V with the 3.7 V of the LiPo battery. If VBat on the charger is not protected, 5V will produce a loading current that might destroy the battery. I also have to tell you, the resistor for the LED on your schematics has no meaning. Both legs of the resistor and one leg of the LED are on the same rail of breadboard. For a power selector the following link might help https://arduino.stackexchange.com/questions/39805/can-you-charge-and-use-a-lipo-battery-at-the-same-time

For example Seeed studio Xiao BLE has the same MCU and also battery "pads" + charging circuit
And of course then you can't use constructs like while (!Serial); in setup

"Ideally I'd like to use the device while it's charging", this is not an Arduino question, it is an electronic question. In order to use the device while charging, you need a "load sharing" circuit, otherwise your battery might not get fully charged. Read this Microchip App Note. The load sharing circuitry disconnect the battery from the  load (i.e. your device) while charging and directly supply the 5V from USB to the load, and when the USB/5V is not present, the battery will supply the power to the load.


text:
What do I need for a plug?
I've manage to build myself an RFID music player which I'm pretty chuffed with. It's definitely a bit home made but it woks and I'm proud of it. I don't know what plug type to buy to sort my problem below:
As you can see from the second photo, my wiring is a big mess. I've wired up all the components on the lid (the RFID reader, three buttons, and a speaker) with 21 single plug wire connections. As you can clearly see from the photo, it's a dogs breakfast of wires. Worse, the wiring is fragile and connections can break when I open and close the box.
The fix, I think, is fairly simple: to wire up a multi-wire plug connection between the lid and the box. That is have all the wires from the lid feed into one side of a plug, and all the wires on the bottom feed into the other side of the plug. That way, I can bundle all the wires up and attach them neatly out of the way, with the only moving part being the large multi-wire plugs.
I would really like one plug (male and female) with at least 21 pins, or few smaller pinned plugs to clean everything up. I don't know what to search for - when I google search for plugs, wiring harness, connections, etc, I get a variety of plugs and wires that just don't seem quite what I'm looking for.
Ideally, I'd like to be able to set up the plug by just screwing in each of the bare tinned wire ends. That way, alls I have to do is cut each single wire plug off, strip back the wire, tin it, then screw it into the plug in the right spot. Do that 21 times for each side and hey presto: 2 neat plugs.
Can someone please let me know what plug type I need? Or any other helpful suggestions?

The reason there is unshrunk heat shrink wrap on the wires is that I thought shrink wrap would make the single wire plug connections a bit more permanent. I only actually shrunk the two loose connections, and decided against shrinking the rest lest it prevent me removing the connections should I need to.

please do not add explanations into a comment ... use the edit button and add it to your question ... anyway, your question is not about arduino

I would also suggest just using pin headers and female dupont connectors. You can get them with  like 2 rows of multiple contacts (as you need it). Thats the easiest for the typical 0.1" pitch and they are durable enough to hold for the limited number of times, that you need to disconnect them.

gentleman, sorry, I reopen the question. I think it is on topic here. It is too basic for EE SE. simple circuits and wiring a project around Arduino is 'Arduinoing'

You could have use say 4 long stand-off spacers and mounted the circuit board on the underside of the lid (as you have done with the RFID reader), possibly inverting it for easier access to the arduino usb socket and SD card, so the lid could be removed without stressing the wiring.
If you had used a printed circuit board then edge connectors would have been a possibility.
I suppose you could use 0.1" header pins on the circuit board and use DuPont or similar connectors.


text:
Have I ruined my Arduino Nano with my terrible soldering (technique and tools!)
So I bought a Arduino Nano and a very cheap soldering iron and solder from Alibaba. I was attempting to solder in some connections and failing pretty hard. A small resister popped off when trying to solder a wire to ground. I was pretty good when soldering in high school...but it's been a while since then.
By just plugging it into my computer, I was able to upload a simple program which switches the LED on and off - and that still works.
I'm not clearly not competent enough and I don't have a good enough soldering iron to do surface mount soldering to repair it. So I'm wondering if it'll still do what I want it to do.
My overall aim is to build a simple music player for my 3 year old.
My question is, what does that resistor do? Have I ruined the board?

Is that the spot up near the top-right? What colour was the "resistor"? Brown? Judging by an image I found on the Internets it is actually the DTR reset capacitor, probably 0.1 µF.

You obviously solder without any solder flux. Learn for example from https://www.youtube.com/watch?v=oqV2xU1fee8

@KIIV I can attest I soldered with solder. Lots of solder.
What I did not do, was clean the board of residue and check for the correct technique for soldering wires to pinholes. I also used incredibly cheap soldering iron and solder from Alibaba. I've now rectified all those elements and am wondering whether I should just chuck the board or its still usable.

I was able to upload a simple program which switches the LED on and off - and that still works - sounds usable to me.

From what I can work out, the two reset pins are now dead. It looks like the other resister (capacitor?) was connected in series to the capacitor that was lost. I can't work out what else was connected to that...

@NickGammon I know it kinda works but with one tiny component missing, something is definitely broken. If I know what function doesn't work, then I know whether I can still do my project.

You haven't answered either of my questions in the comments (where is the component?, what colour is it?) but judging by the position I think it is on the board it is the 0.1 µF capacitor which is part of the reset circuitry. It is designed to briefly pull /RESET low on power-up, or when DTR is asserted.

If I know what function doesn't work, then I know whether I can still do my project.

Either the board works or it doesn't. There won't be "some function" that won't work. You may have problems resetting it but simply pressing the reset button on the other side (if there is one) should have the same effect.
I suggest you get a better soldering iron with a smaller tip. Also practice soldering a bit. The wire you show in the photo should have a blob of solder around it, not going "raw" into the hole as you have it. I also don't see how you can somehow unsolder a capacitor which is a couple of millimetres away from the pins on the edge of the board. Definitely more practice required.
A common technique with boards like the Nano is to solder a line of pins down each side like this:

Then plug the whole thing into a breadboard and wire up your project on the breadboard. Then you don't need to worry about your soldering technique so much (once you have soldered on the pins, and you can get a friend to help you).

Thanks Nick for the comment. After a bit of practice and borrowing a different soldering iron, it turns out the issue was largely my cheap soldering iron. It was not getting up to temperature properly, so I was leaving it heating the joint for way too long before being able to melt the solder. I appreciate the help.