Compile-time 'Undefined reference' error for functions defined in a .cpp source file that are called in my main project file

Firstly, static keeps a function from ever being exported globally:

static void pedometerInit() // Initialising all pedometer algorithm variables

should not be static.

Secondly, extern does not define a variable, it merely tells the compiler that "this variable exists somewhere. Find it at link time." - however you're not actually defining those variables anywhere.  In addition to the extern hints in the .h file you need to have the variables in the .cpp file for the compiler to be able to find them.

int activity_state; // activity_state=1 for RUN and activity_state=0 for WALK
float * speedarray; // Dynamic array for storing speed
int speedindex;
float * timearray; // Dynamic array for storing time
int timeindex;

unsigned int localPort;

void pedometerInit() // Initialising all pedometer algorithm variables
{
 ... your code ...
}


It is inferred from your question that the Arduino is getting powered through the USB port.  As you say the Arduino appears "gone" from the computer when you light up too many LEDs.

All USB ports are only obliged to supply 500mA with out the USB Device (the Arduino) negotiating for more power from the USB Host.  If the load goes beyond 500mA, the USB Host (the computer) can limit the power my reducing the voltage.  At some point the Atmel processor on the Arduino will stop working.

There are many tutorial on how to use LED strips on the web.  Most will indicate power from a larger than normal power supply is necessary.  Also, that the LED strip power should be connected directly to an appropriately chosen power supply.

The following image from this web page illustrates this:

(Note: In this picture PIN 6 was chosen to communicate with the LED strip.  Your specific application (program or sketch) may use a different pin. Also, realize that the power supply in the picture is wired to only power the LED strip. The Arduino still needs to be powered.)


freeMemory() function from memoryfree library not returning decreased value in arduino UNO

You are assuming that, just because you created a variable, it will be stored in memory. That is often not the case.

The compiler is reasonably intelligent. And there are lots of CPU registers in the AVR core. If there is a free register available for a temporary local variable like that, why would it waste time and effort putting it into memory when it can just keep it in a register?

Also, since you don't really do anything with the variable, chances are the compiler is just throwing it away.

Marking a variable volatile will remove both those problems, and you may see different results.


Multiple rgb control plus calculation help

It's not advised to connect leds in parallel, with only one common resistor. Slight difference in forward voltage of the leds will create big current differences. This will make some leds appear brighter that neighboring leds. It can also damage the brighter led since too much current can flow through them. So you need to add a resistor to each led, and common the other side of these resistors to the transistor.

Second bigger error is that there isn't any resistor between the arduino pin and the base of the transistor. Without it there is nothing limiting the current going into the base, which could fry the arduino pin.


Arduino Modbus Master code to read data using arduino uno from EB meter

The response is received when ModbusRtu library object is again in the IDLE state after a request was sent. In your code based on the example from the library, the response is ready in state 2 which follows state 1 where the request was sent. If in state 2 when the master object state changes to IDLE, you can use the response in array au16data.


Arduino SPI - MOSI not writing any data but clock works

In addition to @Talk2's answer SPI.transfer(...) transfers one byte of data. Your array is made of int which means each entry is 2 bytes long.

Instead you should use SPI.transfer16(...) to transfer 16-bit values.


How to power two stacked motor shields with one 3S Lipo battery (11.1V)?

You can avoid using a linear voltage regulator. Try using this voltage regulator.

You will get 5 Volts 2 Amp output which should be easy to connect to motor shield's input power ports.


Why does a delay make my stepper stop? And why does the break command raise an error?

... why the break command raises and error?

Because you are using it wrong! break will end a loop, and is used in the switch...case statements. Read the documentation for break if you need to know more

  I have fixed it, the delay at the end fixes it for some reason. I don’t know why though.

You haven't really fixed it if you don't know why. It seems that you are trying to directly control a 5 wire stepper, i assume your pins must drive a transistor or something as the arduino pins themselves will not work.

The reason it works is because the stepper takes time to energize and move, if you don't wait long enough it won't work, your serial.print must be long enough, as the delay(1) should produce a 1ms delay which is too short.

You are driving your stepper wrong, you have the code setup for a half-step control, but you have 9 states, state 8 in not needed.

you are duplicating effort you don't need with both _steps and _switches, they always have the same value.

you can do better on your code as well:

int dir = 1
int c = 0

// in loop
c += dir

if (c > max)
{
  dir *= -1
  c = max
}

if (c < min)
{
  dir *= -1
  c = min
}

With this you don't have to check the direction to modify your variables.


How can program/arduino restarted by IDE?

When you open the serial monitor (or even just go to the serial port menu) the serial port is opened. When the serial port is opened the DTR line is asserted.  This is the method that the Arduino uses to reset so that you can access the bootloader and upload a new sketch.

Every time you open the serial port - through whatever means you choose - you reset the board, whether you like it or not.

There are a number of "fixes" for this - the simplest is to add a large (say 10µF) capacitor between the RESET and GND pins of the Arduino to filter out the reset pulse that would otherwise reboot the board.

There are also ways of disabling the reset within Windows, but that requires you to write your own software to interface with the board instead of using the serial monitor.

Some boards also come with a method of completely detaching the reset signal from the USB interface, but modifying the board itself isn't for beginners.

Just remember that once you have disabled reset through whatever means you will have to re-enable it (resolder the track you cut, remove the capacitor, whatever) before you can upload a new sketch.


MP3 Shield stacked on DMX Shield - Arduino Uno

Yes, overlapping is a problem, by default the MP3 Shield uses digital pins 2(DREQ),6(mp3CS),7(mp3DCS),8(RST),9(SD-CS),11(MOSI),12(MISO),13(SCK)

The Tinkerkit DMX Master Shield R4 uses 2(RE-ENn),3(VTX),4(VRX),5(DE-EN),6(D6)

So there are conflicts with D2 DREQ vs RE-ENn and D6 mp3CS vs D6.

The DMX Master Shield basically converts the UNO's serial to DMX. If nothing is at first included into the Sketch for this, then the problem is with only D6. Leave this jumper OFF. And I suspect the MP3 Shield will work stacked.

To use them together you can move the pins, as demonstrated at https://www.youtube.com/watch?v=behMgV3tUr4. Noting that is for different pins. And of course you will need to subsequently change their definition, in the sketch.


How to send data in response to HTTP get request from ESP8266?

@Gerben answered my question in a comment all credit goes to him. I retype it here maybe it helps someone in the future.

I had to send two new line after setting up the header

//header
client.print("\r\n\r\n");
clinet.print("Hello, I'm comming from ESP!!");

And in jQuery I get it like this:

$.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
    var receivedData=data;  //=Hello, I'm comming from ESP!!
});

It is simple but it may help some newbie like me.


Choosing the right mosfet to switch on-off a neopixel strip

You refer to a 2N2222 handling 800 mA.  However, the 2N2222 datasheet shows 600 mA as its maximum rating for Collector Current – Continuous.  Moreover, from the On Characteristics table, Collector – Emitter Saturation Voltage at 500 mA current could be as high as 1 V.  In typical circuits with high base drive it usually is less, eg about 0.2 V typical with 50 mA base drive, which is more current than a typical AVR output is rated for.  Anyhow, the Neopixels won't operate if your switch drops any significant voltage from the supply.  Using a 2N2222 might work ok, or briefly, or intermittently, or not at all  – depending on the quality of the  2N2222 and the amount of base drive.

You refer to a FQP30N06L handling 62 Amperes.  However, the FQP30N06L datasheet shows 32 A as its rating for Drain Current - Continuous (vs 128 A for Drain Current - Pulsed, which is irrelevant here).

Using a FQP30N06L at its maximum 32 A continuous drain current would require careful heatsinking and perhaps 10 V of VGS drive to achieve low RDS(on), like 27 mΩ. With low VGS of say 3.3 V, RDS(on) might be twice as much.  For example, if it were 45 mΩ, going above 4 or 5 A current would be problematic without careful heatsinking:  4 A → P = 4²·0.045 = 0.72 W, enough to heat up a not-heatsinked unit's junction by about 45℃ or 80℉.

But the FQP30N06L should work ok for your 600 mA typical-case scenario, and also should be ok with the 2 A worst-case as well.


As you have surmised, the problem is that the LCD retains what was there before and you need to clear it away.

That means, as the numbers increase you get, say,

4
10
48
89
194
309

etc.

When they go down though, because the LCD remembers what was there, only the characters you print will be replaced:

309 (309)
194 (194)
894 (89 - the 4 remains from before)
484 (48 - the 4 remains from before)
104 (10 - the 4 remains from before)
404 (4 - the 04 remains from before)

Also, as you have noticed, clearing the whole screen is not very nice since it makes it flash.

To combat that it is important that you only overwrite the characters that you need to overwrite and leave those that want to stay.  There's two common ways of doing this:

Append enough spaces after the number to force an overwrite:

lcd.print(throttle);
lcd.print("   "); // 3 spaces should be enough for 3 extra digits

Format the data with snprintf():

char temp[5]; // enough room for 4 numbers and one NULL character
snprintf(temp, 5, "%4d", throttle); // %4d = 4 digits, right aligned
lcd.print(temp);

The latter method, though it is more complex and uses more resources, can be preferred because it creates a much nicer output with the numbers properly right-aligned.  Also arbitrarily adding spaces after the number could overwrite things you want to keep.

You could also achieve a similar result doing it manually:

if (throttle < 10) lcd.print(" "); // 0-9 add one space
if (throttle < 100) lcd.print(" "); // 0-99 add one space
if (throttle < 1000) lcd.print(" "); // 0-999 add one space
lcd.print(throttle);

Just like with cats, there's many ways to skin this problem...


MAX72XX with 8 digit 7 segment display library

I have a library for driving the MAX7219 chip connected to a 7-segment display. It is at: https://github.com/nickgammon/MAX7219

Example of use:

#include <SPI.h>
#include <bitBangedSPI.h>
#include <MAX7219.h>

const byte chips = 1;

// 1 chip, bit banged SPI on pins 6, 7, 8
MAX7219 display (chips, 6, 7, 8);  // Chips / LOAD / DIN / CLK

void setup ()
  {
  display.begin ();
  display.sendString ("HELLO");
  }  // end of setup

void loop () { }

In operation displaying a number:

More details at: Interfacing LED displays with the MAX7219 driver


Set higher baud rate for Serial and in Serial Monitor. It slows down the processing and the mySerial buffer overflows.


For which type of serial communication is Arduino Severino designed?

Looking at the schematic of that board it uses a very crude signal inversion for the RS-232.  This allows it to work of a standard RS-232 signal direct from a computer - just.

It's far from ideal and really should use a MAX232 (or similar) chip for the interface.

Your FT232 adaptor should bypass that chunk of the circuit and connect direct to pins 0 and 1 of the Arduino clone.  The DTR pin of the FT232 should connect to the RESET pin of the Arduino clone via a 100nF capacitor to allow the IDE to reset the board to enter the bootloader.  Oh, and of course, connect the ground to your Arduino clone too (something Arduino users often forget).

You can follow the serial breakout board portion of the Arduino breadboard tutorial and apply it to your board.


if (len > 8) pwdReadBuffer[len] = 0;

This line is unsafe.  You declared pwdReadBuffer to be only 8 bytes in size, but this line of code will either do nothing, or write outside of the target buffer, with unpredictable results.

You make a related mistake here:

if (len > 8) lampCmdRead[len] = 0;

First the test should be >= but again, such a value would be beyond the end of the target buffer.

Also consider that if you receive 8 or more characters, you will have no room for a terminating null in pwdReadBuffer, and so cannot pass it to anything that expects a null terminated string.

If you want to use null-terminate storage for a string of up to 8 bytes size, you need 9 bytes of storage.  And of course you need to only use in-range indices to access the elements.


Two things:

You need to put a delay in between your read requests. Currently you're reading way too fast, every few milliseconds you're hitting the DHT. Max interval should be every two seconds or so.
Add a 10k resistor between pin 1 and 2 of the DHT.

I'd bet adding a delay, or using the simpleTimer library to control how frequently you read from the DHT will clear this up.


Unless you have some project constraints which make it mandatory to use naked ESP8266, why not use a NodeMCU to communicate with the Arduino in a master/slave relation over I2C?

#include <Wire.h>
#define I2CAddressESPWifi 8

in setup()

Wire.begin(D1,D2); // SCL D1 SDA D2

then call from anywhere inside your loop() call this function

char readSlave(int x) { // send current time
  String xY = String(x);
  char c;
  int charArrayLength = xY.length()+1;
  char bufferChar[charArrayLength];
  Wire.beginTransmission(8);
  xY.toCharArray(bufferChar, charArrayLength);
  Wire.write(bufferChar);
  Wire.endTransmission();
  delay(10);
  Serial.print("wire sent: [");
  Serial.print(x);
  delay(50);//Wait for Slave to calculate response.
  int counter = 0;
  char buffMe[32];
  int bytesIn = Wire.requestFrom(8,32);
  while (Wire.available()) {
    delay(2);
    buffMe[counter] = Wire.read();
    /*
    c = Wire.read();
    Serial.print(c);
    */
    counter++;
  }
  delay(10);
  Wire.endTransmission();
  delay(500);
  Serial.print("] bytesIn: [");
  Serial.print(bytesIn);
  Serial.print("] buffMe: [");
  Serial.print(buffMe);
  Serial.print("]");
  return buffMe;
}

and your arduino will be waiting (setup)

Serial.begin(9600);
// slave listens for call from master NodeMCU
Wire.begin(I2CAddressESPWifi);  // predefined as `8` or whatever address you choose
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);

and at the end of your code

void receiveEvent(int howMany) {
  if (howMany) {
    Serial.print("bytes[");
    Serial.print(howMany);
    Serial.print("] Received[");
    char charIn[howMany];
    int counter = 0;
    while (Wire.available()) {
      char c = Wire.read();
      charIn[counter] = c;
      //Serial.print(c);
      counter++;
    }
    delay(10);
    //do something with command from master
  }
}
void requestEvent() {
  char bufferChar[20] = "slave answer string";  // automatically null terminated extra character at end
  Serial.println(bufferChar);
  Wire.write(bufferChar);
}


trigger a function of a Arduino Uno from signal received by LoRa module

I'm assuming you have read the datasheet for the SX1278.  If not, please refer to it at:
SX1278 Datasheet
On page 69 you will see a couple of tables regarding the functions possible on the digital I/O (i.e. DIO) pins:

I'm not clear what exactly you are looking for or which mode you are operating in (you have provided almost no information about your project) but all the information you might need is available on these DIO pins.
You can connect the appropriate pin or pins to some of the edge sensitive lines on your Arduino and define and enable an INTERRUPT in your code.  So when the event you are waiting for happens, an interrupt will occur, you can go and read the data and do whatever with it.


You need to add this to your setup():

pinMode(A0, INPUT);

...to set the pin for reading.

Since you're reading an input that's already pulled up (in the middle of a voltage divider), that should be all. However, you can turn on the internal pull-up with:

digitalWrite(A0, HIGH);

...while the pin is in input mode.

More details here:

http://arduino.cc/en/Reference/PinMode

http://arduino.cc/en/Tutorial/AnalogInputPins


You will have to play some games to make it work.  CAN is a bus with dominate and recessive states.  This is how it arbitrates.  When a unit starts sending a message and another starts concurrently they will both keep transmitting until one is sending a dominate signal and the other is recessive.  At that point the unit placing the recessive signal on the bus backs off and waits until the bus is idle before re-trying.

You can simulate this with a few transistors (not real CAN but will work).  Monitor the bus with the receive side and drive it with the transistor with a pull up resistor.  When the transistor is on that is the dominate state when the transistor is off that is the recessive state.  This automatically places a priority order to each unit. Also you cannot operate with 1 CAN device, each message has to be acknowledged by another. It is imperative that you receive what you send.  Transceivers are very cheep on eBay and they have the Maxim chip which is very good.
Good Luck,
Gil


Is there an Arduino motor shield library?

From Chrisl's comment: https://github.com/gallingern/arduino-motor-shield-r3

You don't really need a library though as the code is simple enough:

void setup() {

  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin

}

void loop(){

  //forward @ full speed
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  delay(3000);

  digitalWrite(9, HIGH); //Engage the Brake for Channel A
}

From here.


Communication Protocol Best Practices and Patterns

There are a lot of ways to write a serial protocol depending on what functionality you might want and how much error checking you need.

Some of the common things you see in point to point protocols are:

End of message

The simplest ASCII protocols just have an end of message character sequence, often \r or \n as this is what gets printed when the enter key is hit. Binary protocols might use 0x03 or some other common byte.

Start of message

The problem with just having end of message is that you don't know what other bytes have already been received when you send your message. These bytes would then be prefixed to the message and cause it to be interpreted wrongly. For example, if the Arduino just woke from sleep there might be some garbage in the serial buffer. To get around this you have a start of message sequence. In your example, ^,  in binary protocols often 0x02

Error Checking

If the message can be corrupted we need some error checking. This could be a checksum or a CRC error or something else.

Escape Characters

It could be that the checksum adds to a control character, such as the 'start of message' or 'end of message' byte, or the message contains a value equal to a control character. The solution is to introduce an escape character. The escape character is placed before a modified control character so that the actual control character is not present. E.g. if a start character is 0x02, using the escape character 0x10 we can send the value 0x02 in the message as the byte pair 0x10 0x12 (byte XOR control character)

Packet number

If a message is corrupted we could request a resend with a nack or retry message, but if multiple messages have been sent then only the latest message can be resent. Instead the packet can be given a number that rolls over after a certain number of messages. For example, if this number is 16, the transmitting device can store the last 16 messages send and if any were corrupted the receiving device can request a resend using the packet number.

Length

Often in binary protocols you see a length byte which tells the receiving device how many characters are in the message. This adds another level of error checking as if the correct number of bytes were not received then there was an error.

Arduino specific

When coming up with a protocol for Arduino the first consideration is how reliable is the communications channel. If you are sending over most wireless mediums, XBee, WiFi, etc, there is already built in error checking and retries and thus no point in putting these in your protocol. If you are sending over RS422 for a couple of kilometres then it will be necessary. The things I would include are the start of message and end of message characters, as you have. My typical implementation looks something like:

>messageType,data1,data2,…,dataN\n

Delimiting the data parts with a comma allows for easy parsing, and the message is sent using ASCII. ASCII protocols are great because you can type messages into the serial monitor.

If you want a binary protocol, maybe to shorten the message sizes, you will have to implement escaping if a data byte can be the same as a control byte. Binary control characters are better for systems where the full spectrum of error checking and retries is desired. The payload can still be ASCII if desired.


How to make a pairing and mode button on a remote control receiver

Remote sends a number before the command bits. The receiver checks if this number is the same with the number that corresponds with the position of the switches.
You can do the same in software. Have the first few bits be some number. The receiver can then check if the first few bits of the received "message" matches that number. If it doesn't it will just throw it out.
This is the same method used with IR-remote controls. The signal from your VCR remote will also be received by your TV. But the TV sees that the code doesn't match the one it's expecting. So it will ignore those.


The Time are functions do not work correctly when the processor clock speed is set at 128K

Add a new entry in boards.txt with the new value for f_cpu. Note that the timing functions will become far less precise at so low a speed.


Nothing is working even though every thing is right & it is new?

In these cases it helps to break down the problem in pieces.

If the internal LED on pin 13 blinks with your code it means that the software side is OK so far (code, Arduino type, compiling, uploading etc), so I suggest looking at the physical side of things.

Do you have a multimeter available? If so, connect it between pin 13 and ground and it should show you if the output works.

Finally, is the LED working? When you connect it between 5V and GND (with a resistor!) it should light up.


Multiple buttons activating different methods for an LED strip

Inside each inner loop, just test the switches and return if they are pressed.

eg.

//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<100; j++) {  //do 100 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (int i=0; i < strip.numPixels(); i=i+3)
      {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();
      delay(wait);

      // give up if switches pressed
      if (digitalRead (inPin(1)) == HIGH ||
          digitalRead (inPin(2)) == HIGH ||
          digitalRead (inPin(3)) == HIGH )
        return;

      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

  am having trouble getting it to work for a third

If that doesn't help please explain the nature of this "trouble".

You may need to debounce the switch presses. And you may need to wait for them to release the switch, eg.

 if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
           stopCycle();
           while (digitalRead(inPin(1)) == HIGH)
              {  }   // wait for switch release
           delay (10);  // debounce
           theaterChaseRainbow(50);
       }


Duplicate libraries while compiling for ESP32 in the Arduino IDE

#include "filename.h" will look in the sketch folder

#include <filename.h> will look in the path, defined in File | Preferences, edit preferences.txt, search for sketchbook.path


How can I reset the program on an Arduino Uno while the device isn't recognised by my computer at all?

I had the same problem with my Arduino Leonardo. But when I kept the reset button pressed and plugged it into my laptop, it got recognised again. But since you're using an arduino uno it might also be the atmega16u2 which isn't working properly. If holding the reset button while plugging in the arduino to the laptop doesn't work, try to reset your atmega16u2 chip on the arduino. This is the chip which makes the communication from USB possible.

To reset the atmega16u2 follow this tutorial


How to Connect TFT LCD display with NodeMCU?

According to its web site, the TFT module does have SPI interface. https://www.jixin.pro/product/717.html
The site is in Chinese though.


How to generate gcode for Arduino Mega 2560 and Ramps 1.4 CNC Router

For generating g-code from an SVG, you could try to parse the SVG into a set of relative commands, and using the relative commands to generate G-code. Since you were originally using the frame as a 3d printer and now you want to use this as a CNC machine, you could try to invert the data. But, for generating the code I would go read up on how to parse the various file formats, and read the specs on each of the formats. However, most of the file formats you listed are proprietary, and you won't be able to find an open spec for them.

Of the formats that you listed, it would probably be the easiest to parse the SVG, as it's an open spec, and is a lot like XML.

This is going to be really difficult to actually do, because you're essentially reimplementing a full CNC controller.

I would start with getting 2 dimensional stuff down like drawing shapes and setting routing depth.

Some Resources

Here are some resources that might help you with parsing the various file formats. I only listed the ones that have an open standard.

http://www.w3schools.com/svg/default.asp
This link describes the SVG format, and it does a fairly decent job at it.
http://en.wikipedia.org/wiki/G-code
http://en.wikipedia.org/wiki/STL_%28file_format%29


This error is shown continuosly after first time it compiles successfully

There is a bug that causes this error when you use the Arduino IDE with files located under OneDrive.

The simplest solution is to move any files that will be used with the Arduino IDE out of OneDrive to any other convenient location on your computer. It looks like you have your sketchbook folder located in the OneDrive so you will want to change that via the Arduino IDE's File > Preferences > Sketchbook location. The Arduino IDE does not automatically move the files from the previous sketchbook folder to the new folder so you will need to either move any files to the new sketchbook folder or else reinstall them.

There are some possible workarounds if you want to to continue using the Arduino IDE with OneDrive listed in the issue report:
https://github.com/arduino/arduino-builder/issues/254


You start logging set to LOW and then test if it is high, since it isn't you go to the else clause, you call exit(0) and kill your processor, hence your code never gets executed!

volatile boolean logging = LOW;

...

void loop()
{
   if(logging == HIGH) // starts low
   {
    ... // never executed
   }
   else
   {
    ... //
    exit(0); // now your Arduino is dead!
   }
}

The ellipses (...) are where i snipped your code out.

exit(0) turns off interrupts and loops forever with while(1); which has the effect of a full, power-consuming halt; exit(0) should have a sleep call in it, because what exit(...) does isn't very useful for an Arduino!


Why wifiManager.setTimeout(60) is not working?

Try using setConfigPortalTimeout(60) instead of setTimeout(60)

Because it has been updated in version 0.10 of WiFiManager library.
see : https://github.com/tzapu/WiFiManager#010


Is it possible to write data to a fat file system on SPI flash using an arduino?

The first and most important problem is not the filesystem. Currently on the board the USB port is connected to the internal MCU, which in turn is connected via SPI to the flash chip. The internal MCU is the master on the SPI bus. But the SPI bus does not support multiple masters on one bus. So just connecting the external MCU to the SPI lines as master would not work.
I see 2 possible ways to go here:

You can unsolder the flash chip from the board and add a fitting multiplexer chip, which can switch the SPI lines between the two masters. That effectively gives you only one master on the SPI bus at any time. This way would be rather hacky and difficult for a beginner. It might also be important to keep an eye on the capacitance of the bus, since it might run with rather high speed. A too high capacitance (for example through using a breadboard) might result in erroneous communication.
Then you could use one of the FAT libraries. I don't know them in detail, but I think you could also use them for a simple SPI flash chip. You just would need to implement the lower level access functions, that the FAT library needs.

Or you could try to use a USB host board with your external MCU and try to write data through the USB port. I don't have much experience with USB host boards, so I cannot really tell you, if and how exactly this is possible with the available hardware (the board will most likely implement an USB interface like a simple flash USB stick).

All in all I think, this would be rather hacky. Your board is not really made for changing the data through another microcontroller. Depending on what exactly you want to achieve, you might want to go to a different hardware setup.


Two data outputs to be displayed on one 16x1 lcd display

You can use

lcd.setCursor(x, y);

To set the cursor.

Than you can output text with

lcd.print("Text");

Make sure you add spaces in case there is already text written to overwrite older text.

You can also use

lcd.clear();

to clear the display, but this might result in flickering if you do it too often.

Another possibility is to create a 16 character string

char lcdText[16];

and write characters in this string and set it at once with:

lcd.setCursor(0, 0);
lcd.print(lcdText);


Timer interrupt library for new Arduino based on MCU SAMD21

Do you know a library to do this?

it is generally very difficult to find a library that does precisely what your application wants. in fact, the purpose of a library is so that it is generic enough for you to tailor it for your specific application.

in this particular case, what you wanted to do is quite simple:

1) read through the datasheet;

2) figure out how the timer works;

3) figure out how the power management works;

4) configure timer isr to wake up the mcu periodically; an overflow isr is typically all you need;

5) run the task directly in the isr if is it short or set a flag for its execution in the loop;

6) upon completion, put the mcu to sleep.

all you need is to tackle the little steps above and you will get it done in no time, and learn a ton about your device.

device datasheet is the best friend of any embedded engineer, not the worst enemy.


Sound quality is poor using a piezo in TinkerCad

To pack the comments into a proper answer to the question:

As Majenko stated in the comments, Tinkercad is a simulation. The codes doesn't get compiled and uploaded to hardware. Instead Tinkercad interprets the code on the fly. Simulations are not perfect clones of the real hardware, so you cannot expect the same performance from it as from the real Arduino. Also it is not build for producing high quality sound. The focus is entirely on simulating how the Arduino works.

If you are using this with a real Arduino you most likely will not have the glitches in sound.

What you are currently hearing is not a problem of Arduino, but of Tinkercad. You could file a problem with the developer, but probably they will not think this is an issue, or they will give it a very low priority.


Which side should I connect the resistor on?

Resistor on any side of led will intercept current flow.
Just use another analogy with water, tube and water tap.


Which device to use to measure AC current using Arduino?

Some sort of Current Transformer usually does the trick.  You run the AC line (not the neutral) through a ferrite core and it converts current into an output voltage.  You can find them packaged like this one with a web search.


Your logic is wrong. If you update previousMillis with millis() value in the first line, you are always subtracting the time difference between the the first and second lines of your code (which is the same you are doing in the loop inside flash()). If what you need is to get the time passed since the program started running, you need to have a fixed variable for that in setup() instead of updating it every time in loop().

Even so, I don't see why millis() is necessary in your case. Using delay() would be much more simple and still get the job done. Example:

void setup() {
delay(250);
}

void loop(){

    for(int i = 0; i < 9; i++){
        digitalWrite(LED, HIGH);
        delay(time);
        digitalWrite(LED, LOW);
        delay(time);

        delay(1000 - 2*time); //Delays the loop exactly one second per iteraction
    }

}


It depends how you installed it.

If you downloaded the tarball and extracted it then it's wherever you extracted it.

If you used a package manager to install it then they could be anywhere - you should look at the package manager software fedora uses (yum? it's been a while) to see how to find what files a package installs.

If you are running a modern version of Arduino (I know Debian based packages are from the stone age) then the board manager installs will be in ~/.arduino15


How to find the time of any point on the graph on an Arduino serial plotter or Processing software?

The Arduino Serial Plotter is not meant for this. It just directly draws, what you send. You can solve this in processing, by calculating the time from the number of the current sample (which is what you see on the x axis in your plot) via the used sampling rate.


What is the maximum wire length for serial communication between two Arduinos?

You need to specify

The order of range you are interested in - is it in the order of metres, tens of metres, kilometers or interstate ?:-) . ALL are possible with suitable compromise.
How you intend to connect to the circuit - direct Arduino pins, high/low buffer, differential drivers, ...

If you use 5V/0V "unipolar" then at say 9600 baud you can get many metres with suitable drivers. If you use an Arduino pin directly wire resistance and inductance will start to matter as range increases.

At 300 baud you can achiever hundreds of metres with twisted pair cables. As range increases aspects like cross-talk from the other circuit and external noise increase in importance. At longer ranges having 4 wires with signal + ground twisted together in each case helps BUT it is likely that at ranges of interest 2 wires plus ground will work OK.

If you are prepared to use enough voltage and slow enough signalling you can signal over thousands of miles - as was done with very early telegraph cables. The thousands of volts needed and signalling speeds of perhaps a few bits per second will be a disincentive in most cases.


There are two basic solutions to your problem, an active one and a passive one, and which is best (or will even work) depends on the rest of your setup.

The active solution requires a device called a multiplexer.  This is basically a switch and it selects one of its inputs to route through to its output, so it can be used to connect your input pin to the output of one of the sensors.  It requires an extra IO pin, though, so is pretty pointless as you could just use that IO pin as an input from the second sensor.  It does mean, though, that both sensors can be active at once and you just select one to read the output from.

The passive solution is called open drain or open collector (if you are using TTL not CMOS terminology).  This means you convert each of the outputs of the sensors into a switch using a transistor (NPN BJT or N-Channel MOSFET) to connect your input pin to ground.  When then transistors are off the input pin is pulled up through a pullup resistor (could be internal or external to the IO pin).  When one sensor's output activates it turns on the transistor which then pulls the input pin low.  This means that you can only have one sensor active at a time, so they have to be triggered by separate output pins.

Open Drain is how things like I2C support multiple devices on the same bus without any voltage conflicts.


What you made so far is only turn on and off LED according to button state. I believe there's more efficient code out there, but you can try:

int x = 11;

 void setup() {
 for(int i=11; i <= 18; i++) pinMode(i, OUTPUT); //assuming the led is on pin 11-18
 }

 void turnLED(int num)
 {
     for(int i=11; i <= 18; i++)
         if (num==i) digitalWrite(i,HIGH); else
                     digitalWrite(i,LOW);
 }

 void loop() {

    if (digitalRead(buttonRight))
    {
        x++;
        if (x>18) x=18;
    }
    else if (digitalRead(buttonLeft))
    {
        x--;
        if (x<11) x=11;
    }
    turnLED(x); //turn LED on according to value of 'x'
    delay(500);
}


V-USB is a software-only implementation of a low-speed USB device for Atmel’s AVR® microcontrollers

No host support here, sorry.
The USB host shield handles the hardware bit and simplifies the software bit. It is up to the firmware to support the various USB profiles. Version 2.0 of the library supports CDC with a few devices; check to see if they would be correct for your purpose.


Don't use Serial.parseInt(). It is very very wrong. The whole idea behind how it operates is completely wrong and teaches bad practices and methods.

Part of your way of speeding it up is half-way to doing it properly.

You require a delimiter to say "this is the end of the number". Relying on time in a system that is inherently asynchronous is just plain daft. You have chosen to add a space. A better choice is to use a proper line ending "\n".

Then you should either read the serial character-by-character and parse it as it arrives until you find the EOL character, or read it character by character into a string (NOT a String, a "string" - a C string - a character array terminated by a NULL character), and then use atoi() etc to convert it to the numerical format you want.

Many of the methods that Arduino provide are not suitable for professional use and should be avoided at all cost lest they teach you the completely wrong way of doing things.


Arduino Uno and Leonardo SPI clock can't be measured

Please note the SPI clock will only be active while it is shifting data. So simply put the spi.transfer in a hard loop

#include <SPI.h>

void setup() {
  SPI.begin();
  while (1) {
    SPI.transfer(0x00);
  }
}


Running an LCD keypad shield from a separate power source

You can use a different power source, but the two circuit need to have a common ground, since all electrical signals are relative to ground. So connect a wire from GND on the LCD to GND on your Arduino and everything should work as expected.


The liquid crystal library has to be installed in the same folder as the wire library:

libraries/Wire/Wire.h (etc)
libraries/LiquidCrystal/LiquidCrystal_I2C.h (etc)

There is a hard-coded path in the liquid crystal library pointing to the wire library that is relative to where the liquid crystal library is, which is done to get around the problem that the Arduino library doesn't recurse libraries. It's not actually needed since including the Wire library in the IDE is enough to tell it where to find it for the liquid crystal library, so I don't really know why they did it that way.


The OP wrote:

The issue turned out to be that the SPI pins on the MEGA are assigned differently than the UNO, and the code was actually working the whole time. I cant thank you enough for helping me, even if it turned out to be in vain.


Is Fastled.io library suitable for SMD50500 led strip?

No. FastLED is for addressable LEDs (like the WS2812B). Yours aren't addressable. You just need to set the colour you want with the PWM outputs of your Arduino. Changing the PWM values is not hard and you don't need a library to do it for you.


There's lots of misunderstandings here, but here's the gist of it.

What you want to do is a perfect application of an Arduino. No need to buy a coulomb counter, instead, you should make one with your Arduino.

  I would then add this amp/second value to a variable.

First correction, it's an amp*second, NOT an amp/second. You are multiplying amps by the number of seconds that current value existed.

amp*seconds / 3600 = amp*hours. Read about that here: https://en.wikipedia.org/wiki/Ampere_hour. Multiply that by the voltage over that same time period and you've got amps*hours*volts = (amps*volts)*hours = Watts*hours = units of energy! Remember, your house electricity it purchased in units of kilowatt hours, which is kilowatts*hours, or kWhr. And in engineering units a joule is  the standard unit of energy, and it is simply Watts*seconds. So, you can convert kWhr to joules like this, where units are in square brackets [].

Joules = kWhr * 1000 [Whr/kWhr] * 3600 [sec/hr] = [Watts*sec] = [Joules]

So, 1 kWhr x 1000 x 3600 = 3600000 Joules = 3600kJ

  I would also increment another variable for each second.

That doesn't make any sense. Don't do that. You've already captured the seconds by adding your new bit of amps*seconds to your old sum of it.

DO account for voltage too! What you're really after is energy, which can be expressed in units of joules or kWhr, as already described above.

  Is it too much a stretch to poll the amperage every second and call it amp*second?

(my corrections in bold)

No, absolutely not! That's exactly what an amp*second is! It's the current, amps, times the number of seconds that current existed. That's a coulomb counter!

  How can I make this more accurate?

This is the part where the engineer and programmer (you) determines the quality of the result.

Don't assume 1 second elapsed because you told it to. Measure it for each and every measurement!
The smaller the time interval, the more accurate, since it allows you to capture the small current fluctuations, so use a smaller time slice than 1 second. I'd start with 10ms.
Measure voltage AND current AND actual time elapsed on this loop as close to the same time as possible.
Do NOT use blocking techniques, such as delay() or delayMicroseconds().
What you're doing when you're multiplying a new amp reading x seconds, and adding it to the previous sum is called numerical integration. You're simply numerically integrating, or summing, the area under the Amp (y-axis)-time (x-axis) curve, or, if you're doing what I'm saying to do intead: the Watt (y-axis)-time (x-axis) curve, where the area under the curve is the total energy collected. Don't do rectangular integration, do trapezoidal integration following the trapezoidal rule! It's more accurate!
Calibrate your clock! An Arduino's clock can be off by a couple percent. Figure out how much it's off by comparing its clock output over, say, 10 minutes, and comparing it to a better clock source, say...an internet time server displaying the atomic clock in Colorado or wherever it is. Then, multiply each measurement by a scaling factor to fix it!
On the same lines as above, ideally you'd also compensate in real-time for temperature, as the clock frequency drifts with temperature.
Calibrate the voltage measurement.
Calibrate the current measurement.

Extra: when is trapezoidal integration most beneficial?

The merits of trapezoidal integration can be argued, and it's probably not as important as I originally made it sound, but it is super easy to implement, so why not!? Also, it is most important when:

The time sampling rate is super low.
The rate of change of readings (ie: their derivative, or slope) is super high.
The readings consistently have a rising slope (rectangular integration _under_estimates the area in this case) OR a consistently falling slope (rectangular integration _over_estimates in this case).
When you care about real-time readings in this instant, not just overall trends or averages. This is because trapezoidal integration instantly removes overestimation and underestimation error which can accumulate over short periods but then "de-accumulates", or is negated, over long periods, when the opposite slope occurs in the data.
When the readings consistently rise at a different rate than the fall, as this results in asymmetric accumulation of error. This means that the rectangular integration error accumulated by the values rising distance delta_y will NOT be fully negated by error in the opposite direction when the values fall distance delta_y. Therefore, even over long periods, rather than seeing the error negated, it will accumulate more and more over time. [Note: I'd need to analytically/numerically play with this hypothesis for a while to prove it conclusively to myself, but I'm pretty sure it is correct].

Full coulomb counter example in code:

Here's a full coulomb counter example in code. You just need to implement a few functions to read samples and do calibrations is all.

I'm borrowing the timestamp-based cooperative multitasking part of this code from my answer about cooperative multitasking here, so go check it out for more information on that.

As written, this code compiles, but I haven't wired anything up or tested it. Here's the compilation output:

  Sketch uses 3750 bytes (12%) of program storage space. Maximum is 30720 bytes.
  Global variables use 262 bytes (12%) of dynamic memory, leaving 1786 bytes for local variables. Maximum is 2048 bytes.

coulomb_counter.ino:

Jump to the bottom for the setup() and loop() functions. They are both really short.

/// Coulomb counter example
/// By Gabriel Staples
/// See: https://arduino.stackexchange.com/questions/75932/calculating-amp-hrs-of-a-solar-panel/75937#75937

/// @brief      A function-like macro to get a certain set of events to run at a desired, fixed
///             interval period or frequency.
/// @details    This is a timestamp-based time polling technique frequently used in bare-metal
///             programming as a basic means of achieving cooperative multi-tasking. Note
///             that getting the timing details right is difficult, hence one reason this macro
///             is so useful. The other reason is that this maro significantly reduces the number of
///             lines of code you need to write to introduce a new timestamp-based cooperative
///             task. The technique used herein achieves a perfect desired period (or freq)
///             on average, as it centers the jitter inherent in any polling technique around
///             the desired time delta set-point, rather than always lagging as many other
///             approaches do.
///
///             USAGE EX:
///             ```
///             // Create a task timer to run at 500 Hz (every 2000 us, or 2 ms; 1/0.002 sec = 500 Hz)
///             const uint32_t PERIOD_US = 2000; // 2000 us pd --> 500 Hz freq
///             bool time_to_run;
///             uint32_t actual_period_us;
///             CREATE_TASK_TIMER(PERIOD_US, time_to_run, actual_period_us);
///             if (time_to_run)
///             {
///                 run_task_2();
///
///                 // OR, if `run_task_2()` needs the actual period that just occurred, for
///                 // whatever reason, you may pass it in to your `run_task_2()` function:
///                 run_task_2(actual_period_us);
///
///                 // OR, just do all your code right here instead of in `run_task_2()`
///             }
///             ```
///
///             Source: Gabriel Staples
///             https://stackoverflow.com/questions/50028821/best-way-to-read-from-a-sensors-that-doesnt-have-interrupt-pin-and-require-some/50032992#50032992
/// @param[in]  period_desired_us  (uint32_t) The desired delta time period, in microseconds;
///                             note: pd = 1/freq; the type must be `uint32_t`.
/// @param[out] time_to_run     (bool) A `bool` whose scope will enter *into* the brace-based scope block
///                             below; used as an *output* flag to the caller: this variable will
///                             be set to true if it is time to run your code, according to the
///                             timestamps, and will be set to false otherwise.
/// @param[out] actual_period_us  (uint32_t) The actual period, in us, since the last time it was
///                             time to run--ie: since the last time `time_to_run` was set to true.
/// @return     NA--this is not a true function
#define CREATE_TASK_TIMER(period_desired_us, time_to_run, actual_period_us)                                            \
{ /* Use scoping braces to allow multiple calls of this macro all in one outer scope while */                          \
  /* allowing each variable created below to be treated as unique to its own scope */                                  \
    time_to_run = false;                                                                                \
                                                                                \
    /* set the desired run pd / freq */                                                                                \
    const uint32_t PERIOD_DESIRED_US = period_desired_us;                                                              \
    static uint32_t t_start_us = micros();                                                                             \
    uint32_t t_now_us = micros();                                                                                \
    uint32_t period_us = t_now_us - t_start_us;                                                                        \
    actual_period_us = period_us;                                                                                \
                                                                                \
    /* See if it's time to run this Task */                                                                            \
    if (period_us >= PERIOD_DESIRED_US)                                                                                \
    {                                                                                \
        /* 1. Add PERIOD_DESIRED_US to t_start_us rather than setting t_start_us to t_now_us (which many */            \
        /* people do) in order to ***avoid introducing artificial jitter into the timing!*** */                        \
        t_start_us += PERIOD_DESIRED_US;                                                                               \
        /* 2. Handle edge case where it's already time to run again because just completing one of the main */         \
        /* "scheduler" loops in the main() function takes longer than PERIOD_DESIRED_US; in other words, here */       \
        /* we are seeing that t_start_us is lagging too far behind (more than one PERIOD_DESIRED_US time width */      \
        /* from t_now_us), so we are "fast-forwarding" t_start_us up to the point where it is exactly */               \
        /* 1 PERIOD_DESIRED_US time width back now, thereby causing this task to instantly run again the */            \
        /* next time it is called (trying as hard as we can to run at the specified frequency) while */                \
        /* at the same time protecting t_start_us from lagging farther and farther behind, as that would */            \
        /* eventually cause buggy and incorrect behavior when the (unsigned) timestamps start to roll over */          \
        /* back to zero. */                                                                                \
        period_us = t_now_us - t_start_us; /* calculate new time delta with newly-updated t_start_us */                \
        if (period_us >= PERIOD_DESIRED_US)                                                                            \
        {                                                                                \
            t_start_us = t_now_us - PERIOD_DESIRED_US;                                                                 \
        }                                                                                \
                                                                                \
        time_to_run = true;                                                                                \
    }                                                                                \
}

// Convert microseconds to seconds
#define US_TO_SEC(us) ((us)/1000000UL)
// Convert Joules to KWh (Kilowatt*hours)
#define JOULES_TO_KWHRS(joules) ((joules)/3600/1000)

/// @brief      Obtain a corrected time measurement from a raw time measurement.
/// @details    Assuming you have done experiments to determine your microcontroller (mcu)
///             clock's error, you can correct for it with this function. Pass in a time
///             measurement the mcu has timed directly, and get back a corrected value.
/// @param[in]  raw_sec     A raw time measurement, in seconds
/// @return     A corrected time measurement, in seconds
float do_time_correction(float raw_sec)
{
    // You determine the correct calibration constant. Perhaps it is 0.9813, or perhaps it is
    // 1.19.... You will need to determine this for each individual mcu.
    constexpr float TIME_CORRECTION_CONST = 1.0; // default: 1.0
    float corrected_sec = raw_sec*TIME_CORRECTION_CONST;
    return corrected_sec;
}

/// @brief      Obtain a new instantaneous (at this moment) current reading, in Amps
/// @param      None
/// @return     Current, in Amps
float get_current()
{
    // you implement this
}

/// @brief      Obtain a new instantaneous (at this moment) voltage reading, in Volts
/// @param      None
/// @return     Voltage, in Volts
float get_voltage()
{
    // you implement this
}

/// @brief      Run the coulomb counter task to sum the total energy received from the solar panels
/// @param[out] total_energy_joules_p  (optional) A pointer to a float to receive back the total
///                         energy value acquired, in Joules (Watts*sec). Pass in `nullptr` to not
///                         receive back this value. Note that the previously-cached value is
///                         passed out in the event it's not time to calculate a new value.
///                         The return value of this function will indicate whether a new value
///                         or cached value is passed out here.
/// @param[in]  reset_sum   (optional) pass in true to reset the internally-stored "total energy
///                         acquired" value during this call (prior to performing the latest
///                         power_watts_avg calculation, if it is time for that).
/// @return     true if a new total_energy_joules value was just calculated and passed back via the
///             pointer above, or false if an old, cached value was passed out instead since it
///             wasn't time to obtain and calculate a new value.
bool run_coulomb_counter(float* total_energy_joules_p = nullptr, bool reset_sum = false)
{
    // Set this task to run at 100 Hz
    constexpr uint32_t PERIOD_DESIRED_US = 10000; // 10000us = 10ms, or 100Hz run freq

    static float total_energy_joules = 0;

    if (reset_sum)
    {
        total_energy_joules = 0;
    }

    bool time_to_run = false;
    uint32_t actual_period_us;
    CREATE_TASK_TIMER(PERIOD_DESIRED_US, time_to_run, actual_period_us);
    if (time_to_run)
    {
        // Time to obtain new samples and perform some numerical integration to obtain the total
        // energy received.

        // the previous power calculation, in watts; required for trapezoidal integration
        static float power_watts_old = 0;

        // take new samples, & calculate power from those samples
        float current_amps = get_current();
        float voltage = get_voltage();
        float power_watts = current_amps*voltage;

        float actual_period_sec = US_TO_SEC((float)actual_period_us);
        actual_period_sec = do_time_correction(actual_period_sec);

        // Perform trapezoidal integration to obtain the "area under the curve", which is equal to
        // the energy in joules. Imagine a plot where the y-axis is power and the x-axis is time. If
        // you split the x-axis up into segments of width PERIOD_DESIRED_US, then the trapezoidal
        // area under the curve, within each of those time segments, is equal to time_delta x
        // (power_old + power)/2. This is the energy (Joules) obtained during that time period.
        float power_watts_avg = (power_watts + power_watts_old)/2;
        power_watts_old = power_watts; // prepare for next iteration
        float energy_joules = actual_period_sec*power_watts_avg;

        total_energy_joules += energy_joules;
    }

    if (total_energy_joules_p != nullptr)
    {
        // output this value back to the user
        *total_energy_joules_p = total_energy_joules;
    }

    return time_to_run;
}

void setup()
{
    // do whatever you need to here
    Serial.begin(115200);
}

void loop()
{
    // Energy, in Joules, or Watt*seconds. To convert to Watt*hours, simply divide by 3600 [sec/hr]
    float total_energy_joules;
    bool new_measurements_made = run_coulomb_counter(&total_energy_joules);

    // Let's do an event-based print where we print the latest total_energy_joules value at a rate
    // of 2 Hz, which is typical for digital displays showing information expected to be read by
    // us slow humans. Since the run_coulomb_counter() task is running at 100 Hz, that means we
    // need to print the latest value every 50 runs.
    if (new_measurements_made)
    {
        static uint16_t run_count = 0;
        run_count++;
        if (run_count % 50 == 0)
        {
            float total_energy_kwh = JOULES_TO_KWHRS(total_energy_joules);
            Serial.print("total energy received (J) = ");
            Serial.print(total_energy_joules);
            Serial.print("; (kWh) = ");
            Serial.println(total_energy_kwh);
        }
    }
}

References:

[my own answer about generic, timestamp-based cooperative multitasking] https://stackoverflow.com/questions/50028821/best-way-to-read-from-a-sensors-that-doesnt-have-interrupt-pin-and-require-some/50032992#50032992


It seems that you'll have to do some extended modifications to the design. In fact, all Arduino Pins (D0 - D13, A0-A5) are connected to components on the board and thus in use.

Schematics and Code: https://mega.nz/#F!Xbg1FA5L!qGah_HlLFJ_NKxv7ILLY2g folder "5 SCH".

This means that the only way that you'll get new components into this project are:

removing components  and re-programming the firmware to not use them

e.g., the two tracking-sensors left&right -> A2 and A3 are free
e.g., the speaker pin (D13). Who needs a speaker?

restructuring components

e.g. for the analog sensors: instead of using the Arduino's analog pins, throw a I2C ADC module (e.g. ADS1115) in the build and change the firmware to get the analog values via that new module; making this project use an I2C bus will free all analog pins and cost 2 pins (SCL + SDA). The I2C bus has the additional benefit of being able to connect more than one device to it -- you can e.g. put a I2C GPIO expander (e.g. MCP23017) on it to gain 16 more digital I/O -- more than the Uno had to begin with.


void loop() stops running after an hour or so

A year ago I had the same problem, it seems there is a bug with the String library. I recomed you this:
1- Easy: use the String library on development, but for the "release" change everything to use C native strings (char name [SIZE])
2- Complex (and worse in my op.): set an interrupt every half an hour (or whenever with margin before it crashes) that activates an output connected to the reset pin of the Arduino. I've seen this on the internet but couldn't make it work.
Link to Arduino Forum's thread


Arduino OTA port not updating in Arduino IDE

I found an workaround for Windows:

disable IPv6 from Network Configuration
disable/enable network interface
restart Arduino IDE

You should see your OTA device in port list, in Arduino IDE.


Even if your device is not so heavy, a 9V battery has a maximum practical current draw in the 10s of milliamps. It's not a good choice for operating motors.

A better choice would be AA, C, D, or Lithium-Ion/Lithium-Polymer batteries, wired in series to produce the desired voltage.


Taken from http://www.arduino.cc/en/Reference/SoftwareSerial:

Limitations

The library has the following known limitations:

If using multiple software serial ports, only one can receive data at a time.

If your project requires simultaneous data flows, see Paul Stoffregen's AltSoftSerial library. AltSoftSerial overcomes a number of other issues with the core SoftwareSerial, but has it's own limitations. Refer to the AltSoftSerial site for more information.

If you look at SoftwareSerial's code, you'll understand the limitation:

/* static */
inline void SoftwareSerial::handle_interrupt()
{
  if (active_object)
  {
    active_object->recv();
  }
}

Basically, the code waits for an interrupt to detect state changes on the pin, and directs it to the "active" serial object.

Hope this helps.


The DevKit is a development board by ESP32 manufacturer Espressif to demonstrate ESP32 usage and to support prototyping.
The NodeMcu is a board by NodeMcu intended for the NodeMcu Lua language firmware.
There is no standard pinout. The labels on the DevKit are io pin numbers of the MCU.
You can use both development boards with the ESP32 "Arduino boards support package".


Are there any reasons to pick Nano over Micro?

The main difference between the ATmega32u4 and the ATmega328P is that the 32u4 has onboard USB. When ATmega328P are used in an Arduino they are often coupled with an FTDI USB to serial chip. The FTDI chip is about $5 so this may be where the extra cost comes in.

Having the USB chip separate is actually not a bad thing:

The Atmega328P consumes less power than the ATmega32u4
FTDI chips are common, so the drivers are on most computers, whereas the 32u4 requires an .inf file to be loaded on Windows.
The FTDI chip uses the FTDI vendor and product ID and thus can be used in large-quantity commercial projects whereas the ATmega32u4 would require purchase of a vendor id and product id from the USB group. (My conclusion after reading around the net a bit, please correct if wrong).


Arduino - ServoMotor Control and SoftwareSerial

When SoftwareSerial enters an interrupt each time it receives a character and busy-waits (delays) to time in each data sample as the bits in the character come in.  No other interrupt service routines can run while this is happening.  It also turns off interrupts when it sends.
The servo library for the AVR uses timer interrupts to generate the servo position signals.
When characters are being received, SoftwareSerial will interfere with the generation of the servo position signal because only one interrupt service routine can run at a time.
You may be able to mitigate the problem adding significant delay between characters sent, reducing the total number of characters sent.  This would limit the interference and give servo time to get back to its correct position from however far it managed to deviate over the course of an inbound serial character.
There are also alternative libraries that use the AVR's Input Capture feature on an ICP pin to do some of the work of serial in hardware, and that may work for you.  Here's one example library.
@ocrdu has rightly prompted me to add that there are servo libraries that will do the servo signal generation in hardware.


Choosing wireless tech for lowest possible lag

I've used NRF24L01+ chipset 2.4GHz wireless modules with Arduino before, and found them to be great, and super cheap (~$10 for 10 of them on ebay!). They have 3 modes of transmission: 250kbps, 1Mbps, and 2Mbps. The range decreases accordingly with higher bitrate, but the time spent sending a message does too. There are multiple Arduino libraries (e.g. RF24, Mirf, RadioHead) and tutorials for using the modules (see http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01). They also have built-in mesh networking modes which may or may not be of use.

Versions with an RP-SMA antenna connector and an advertised range of up to 1000m are also available for about $5 each. I would recommend using one of these for the referee's button at least, depending on the range you need.

According to Charles Hallard of hallard.me, The non-amplified chips can get 30m line-of-sight range in 250kbps mode, and I have verified this in my own testing.

According to user sporadic on diychristmas.org, sending a 32 byte payload in 250kbps mode takes 1432µs from the start of Tx mode on the transmitter to receiving the full message on receiver. This decreases to 444µs on 1Mbps mode and 283µs on 2Mbps mode.

Given these statistics, they fall well within 2ms latency for triggering, suitable for your application, and they use very little power. It's up to you to work out the best balance of latency, range and expense.


Laser emitter + receiver for Arduino (Arduino to Arduino communication)

Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Looks like the receiver module has a low-pass filter. That could reduce the baud-rate depending on the RC-factor (10 Kohm * 10 nF gives a cut-off frequency of 1.6 kHz). I would recommend checking the actual components. The above is a guesstimate.

Cheers!


How to send an integer through pyserial with Python to an Arduino and get back the same result?

Use Serial.write() on Arduino to send raw bytes. print converts them to text.

read is not blocking, it doesn't wait for a byte and returns -1 if the receive buffer is empty. Check if read returned -1 or use Serial.available() to get the number of bytes in the RX buffer.

Serial 'echo':

void loop() {
  if (Serial.available()) {
    Serial.write(Serial.read());
  }
}


For the hardware serial port, the buffer is 64 and I was reading at least 100 times. Every read will clear one byte of data from the serial buffer at a time.
For the software serial port, you do a dummy read and then check whether the buffer is empty or not using
    while(mySerial.available()>0)  {
       dummy = mySerial.read();
    }

So, in summary, you have to read the buffer until it is empty.
Useful notes:

You should be knowing when to expect actual data and when not to
have a way to identify the valid messages (some fixed header bytes)
have a way to validate the contents (checksum)

Leave a comment if you have any questions


Those are examples for keys. You need one key and you can choose any text with any length.

Did you see this line in the example:

sha.initHmac((uint8_t*)"Jefe",4);

It uses the key "Jefe" with a length of 4.
You can use your own key, but you also need the length.

char myKey[] = "abece123*";
int length = strlen(myKey);
sha.initHmac((uint8_t*)myKey, length);


So euhmm, I removed a couple of Serial.print() frome my code and now everything is working. Still I have no clue to what happened, but it works now...


Arduino Mega failure after first use of Mega Shield power connector

I want to make this obvious to the casual reader:  Mega Sensor Shields -- all versions I've data on -- run the power connector to +5V.

The power connector is not power in, as defined by the base board.  In fact, there is no direct way to get to the base board regulator from the shield.  (A pin exists for Vin, but it isn't connected to anything on the shield.  It's mechanical support.)

It's intended to supply more current to devices connected via the shield than the base board does.

There is a jumper that disconnects the sensor shield +5 rail from base board power to allow independent +5 volts distribution to the shield attached devices.


Interfacing accelerometer LSM303DLH with Arduino UNO using I2C

Are you using one module bought from Adafruit?

Make sure the connection is correct between the sensor and Arduino, then make sure that the script doesn’t get stuck when the Wire is begun.

Another thing that you need to make sure, is to have the correct address, it depends from board and each one can have a different one or a selector.

This can be helpful to figure out what the wiring is


I fully agree with Edgar Bonet.

My opinion is keeping a 'matrix' is better, or actually one array (of structs), where each array elements stores all information for one measurement (which is stored inside one struct). This has some benefits:

Data of one measurement is consecutive in memory, so you can easily transfer it (to some external memory or sending it). It's exact one struct (and you can use sizeof(struct_item) to know how many bytes you have to transfer.
It's good practice in general to keep information together, creating 5 always-equal length arrays seems strange.
If for some reason you want to make a single array dynamic or change it to a ring buffer for example, you can easily add/remove items (instead of dynamically changing 5 arrays).
Locality of change (see comments of Kwasmich/DuncanC)

There is also one benefit about having separate arrays (where each array stores one type of information, like an acceleration or timestamp: when you have a function (especially in another class) that only needs one of them, you can specifically send that array (or pointer/reference), so the other information is hidden from that function.


Is AREF a stable output Ref voltage with analogReference(INTERNAL)

No, it is not acceptable.

The datasheet states:

  AVCC is connected to the ADC through a passive switch. The internal 1.1V reference is generated from the internal bandgap reference (VBG) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC, and the reference voltage can be made more immune to noise by connecting a capacitor between the AREF pin and ground. VREF can also be measured at the AREF pin with a high impedance voltmeter. Note that VREF is a high impedance source, and only a capacitive load should be connected in a system.

The 1.1V reference is only presented on the AREF pin for the purpose of adding an external bypass capacitor, or for measuring it using a very high impedance meter. Any load applied to the pin will cause the reference voltage to droop.

While it may work in certain circumstances it's certainly not recommended. If you want to use it externally you should buffer it through a high-impedance unity-gain voltage follower:

simulate this circuit – Schematic created using CircuitLab


The issues regarding efficiency of power are:

The CPU speed
The Voltage
The Power Regulator (not supply)
The Peripherals

Address each one of these and don't over look any of them. Or any sub component. But note that some are more impacting than others.

while it is possible to lower the speed, It is more practical to just sleep. As you have indicated you are going to do.
Running at 3V instead of 5V is a big savings. Note that the 328 can run as low as 1.8V
DON'T use Linear Regulators. Most all Arduino's have a 7-12V to 5V(or 3.3V) Linear Regulator. This just burns the difference between the supply (aka battery) and the VCC, used.
pay attention to the peripherals. Likely this means getting rid of not needed devices. Example the USB to Serial chip that exists on the Nano. What is the lowest voltage can the radio run at? Must it run at a regulated voltage. Use the largest possible resistor values. Such as on pull ups. A 500K pull up will draw less current than a 10K. Where if too big any capacitance may slow it down. Which is likely acceptable.

One of the biggest savings is running directly off of the Battery without a Linear Regulator. Where the ATmega328P can run from 3V down to 1.6V. It would be recommend to use the Brown Out detector.

Also note that ALL batteries have a self discharge rate.  This will determine the maximum possible life of the battery, then minus your devices consumption.


Below is a simple rewrite of the Master Writer/Slave Receiver Wire Tutorial, https://www.arduino.cc/en/Tutorial/MasterWriter, for a vector of floating-point numbers.

Master Writer Sketch

#include <Wire.h>

const int DEVICE = 8;

void setup() {
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  const int VEC_MAX = 6;
  float vec[VEC_MAX];
  uint8_t* vp = (uint8_t*) vec;

  Wire.requestFrom(DEVICE, sizeof(vec));
  while (Wire.available()) {
    *vp++ = Wire.read();
  }

  for (int i = 0; i < VEC_MAX; i++) {
    Serial.println(vec[i]);
  }

  delay(500);
}

Slave Receiver Sketch

#include <Wire.h>

const int DEVICE = 8;
const int VEC_MAX = 6;
float vec[VEC_MAX] = { ... };

void setup() {
  Wire.begin(DEVICE);
  Wire.onRequest(requestEvent);
}

void loop() {
  delay(100);
}

void requestEvent() {
  Wire.write((uint8_t*) vec, sizeof(vec));
}

  Is it possible to send a float Array over I2c

So I would answer - Yes.


I used to use gamepads as input device for USB many years ago. I simply soldered wires paralel to buttons and shortcut them to "simulate" the button press - it worked nice and reliable.

With Arduino - I would measure the voltage on the button in question with Voltmeter - if the voltage is less then Vcc of Arduino (5Volts), I would simply connect Arduino ground to lower side (negative) of the button and output pin to the high side of the button. Then I would set that pin for Input to have the button released (from Arduino side) and to LOW + Output to have it pressed. (maybe I would first shortcut the button with Ampermeter to see, that no more, than 100mA is sinking there).

If the sink is more, or the voltage is more, then I would use relay and shortcut the button with the relay, switching the relay with Arduino.

( something like this http://www.instructables.com/id/Home-Automation-How-to-Add-Relays-to-Arduino/?ALLSTEPS )


127.0.0.1 is not the address of your computer.  That is the address of the "loopback" interface - a virtual interface that allows a device to talk to itself.

That means that when you are using the MQTT server itself you can connect, because it's all the same computer.  However the ESP8266 is trying to connect to itself, not the MQTT server.

You need to replace 127.0.0.1 with the actual IP address of your MQTT server.

The simplest way of getting your computer's IP address is to open a terminal window and type:

hostname -I


Yes, you can power the Arduino using a USB phone charger.

The Arduino Uno draws less than 100mA when connected by itself. So ideally you would want the USB phone charger to provide at least 100mA. All of the USB chargers I have come across to date provide more than 400mA. Most of the modern USB chargers provide upwards of 1A for fast charging of your phone.

A USB(2) port of a laptop can provide up to 700mA to the Arduino (500mA continuous).

In terms of the overall current draw, it really depends on what you have connected to the Arduino. LEDs generally draw 20mA or less per LED. Some screens can draw anything from <100mA to a couple of amps. Most of the screens I have come across draw less than 1A. It really depends on the devices you want to connect.

For the most part, a USB charger will be sufficient.


Arduino nano 33 ble vs ble sense. Power consumption, etc

The official page for the Nano 33 BLE Sense mentions various things including the datasheet for the light sensor. That appears to be much more sophisticated than an LDR.
According to the sensor documentation (above):

Upon  power-up,  POR,  the  device  initializes  and  immedi-ately enters the low power SLEEP state. In this operational state  the  internal  oscillator  and  other  circuitry  are  not  active,  resulting  in  ultra-low  power  consumption.

You would have to read the documentation for the other devices to check these things. Personally I haven't used one, and Arduino claim it "is a completely new board". So, you may not find a lot of people that can answer those questions.
Keeping power consumption low is quite a complex field. You need to look at clock speeds, sleep states, peripheral power consumption and so on.


How to delay so that LED stays on a bit longer?

Insert a delay of 500ms?

function cycle() {
    for ( var i = 0; i < bytes.length; i++ ) {
        console.log(bytes[i]);
        sr.send(bits[i]);
        delay(500);
    }
  }


SIM800C, CPIN: NOT READY (ERROR CODE : +CME ERROR: 10)

The antenna is too close to the module. You probably used the spiral antenna. Try using the PCB antenna with long (10cm) cable.
Had the same problem, solved with the antenna.


How can I upload .hex files to a Pro Micro using Linux?

I had the same issue, and it was caused by udev, I found the answer here

It's some obscure bug

Tweaking udev rules solved the problem for me, now all is good, here is the procedure: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules


To convert my comments to an answer:

You can use the register names directly. They are defined in the boards/chips core. To read them, simply use the names in your calculations. Write to the registers by setting the value of the registers name (like a variable: TCNT0 = 0;). Be sure to look into the datasheet, to check the behavior of that register.


Error on Uploading Program to ESP8266 via Foca v2.2 (USB to TTL Adapter)

by the comments I think you are not understanding correctly how to connect Reset and GPIO_0 of ESP. To set esp-01 into flash mode (to program) you need to set GPIO_0 Low (GND) and then also apply Low on RST ESP pin.
To debug the things and be certain that there is no hardware problem let just start by doing these connections:

Foca v2.2 <-> ESP =1
      TXD <-> RXD
      RXD <-> TXD
      GND <-> GND
  Arduino <-> ESP 01
     3.3V <-> 3.3V
     3.3V <-> CH_PD
     GND  <-> GND

Now, with a wire, connect GPIO_0 to ground. With another wire, briefly connect RST of the ground to make ESP reset. You should be now in flash mode. Remove the connection on GPIO_0 and make it float. Now upload the code.

Note: this is basically the option C on the link you provide. If you have some buttons you can make it too:

(source: arduinesp.com)

Now, does the code upload in Arduino IDE?

If the answer is still no, try to add a small capacitor between 3.3v and ground.

If the answer is yes, now you can move on and try the other options described in the link you provide. I recommend using the option A:

(source: arduinesp.com)

Any generic npn transistor should work


Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding

First stop for me is always the connections (which you've done), the sketch itself (which doesn't sound likely) and then the COM port / baud rate.  If your sketch involves anything with the serial connection, ISR's or power supplies, that could be an issue with the Arduino not listening.  It sounds like you've covered this as well by trying simple sketches.  Next, check the COM port on the host computer (sometimes it changes in Windows) and inside the IDE, the baud rate, and open the IDE serial port and wander through baud rate settings until you get something legible as a response in the serial window.  Also, double check inside the IDE that you still have the correct board selected.  Occasionally / rarely, I've had to reboot Windows to cure the problem.

The good news is, this pain is significant enough that you don't usually make the mistake again, and will probably never forget how you solved it....


Use callbacks in Arduino with pointers to functions (will functions persist in memory?)

Your functions won't cease to exist. All of the code in your compiled and linked code image gets loaded into code-memory (Flash) and it stays there throughout the run, through resets, and through power-cycles, until another image is loaded over it.
Are you confusing pointers to functions with pointers to a function's local variables which occupy RAM memory, specifically within the function's stack-frame which is transient, being created and "destroyed" as the function gets called and returns - and successive stack-frames won't necessarily be created in the same place.


No. You must connect AVcc even if you're not using the ADC.  According to the datasheet:

  AVCC is the supply voltage pin for the A/D Converter, Port C (3:0), and ADC (7:6). It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that Port C (5:4) use digital supply voltage, VCC.


The purpose of the serial input buffer is to prevent data-loss between your program's Serial.read() calls. If you really want to allow long messages to accumulate in it, here is one of many articles that describes how you can increase the size of the buffer in the Arduino core-code. But this is a system-wide solution to one program's design problem - it imposes the memory overhead of that larger buffer on all programs whether they need it or not, or you have to define a new board-type in the boards file (the technique in the above article) and remember to use it for programs that need the larger buffer.

A better approach is to do your own buffering, by defining within your program, a buffer large enough for your largest message (plus the zero terminator), collect bytes from the serial input buffer into your own buffer often enough to not let the serial buffer overflow; then detect when your own buffer has a complete message before you "/* Do stuff */ ".

You appear to be asking about a situation in which you will know in advance what the length of the next message will be; in that case, you can count bytes until you've collected the whole message.

In other situations, the message may have a terminator such as the NewLine character, or the message may contain the length within the first few bytes, in which case you'd wait for those bytes, convert them to an integer, and use that number to detect the end of message.

Update:

  But it doesn't explain to me really why I can't send it more bytes
  afterwards until I've read the entire input buffer.

I can't offer much help there; I've no experience using .readbytes(); I just read bytes as they arrive until I've got what I wanted. But my notes on it say it "Reads chars into a buffer. Terminates when len bytes have been read, or it times out" (1 sec, I think; there may be a call to change that, too). I'd also consider the possibility of the 64 byte serial buffer having over-flowed; doesn't sound like it but strange things can cause strange things....

"but I rarely work this close to the hardware"
That's the fun and the challenge of embedded systems!


Do I have to use an RTC to build a clock?

How does a RTC module works?

It counts. As simple as that. Once a second it ticks and counts up. It also remembers - most have a battery backup and will continue ticking when you turn the main power off.

  I have to use it "like a rule" (if it is necessary or unnecesary) in my clock?

If you want accuracy and continuation, yes.  An RTC is designed to tick at (as close as reasonably possible) once per second. Trying to do that with just an Arduino is incredibly difficult. The ceramic resonator on an Arduino is not as accurate as the quartz crystals used with an RTC. After a week you may find you are an hour out.


need to get values from a function with structure pointer argument and print on serial terminal

You can't just print a structure. After all, how is the program supposed to know how it is supposed to be displayed?

Do you want just the raw data, or do you want it formatted in a human readable form?

For just the raw data you need to cast the pointer to a type that can be printed as an array. For example:

Serial.write((uint8_t *)&rs485Msg, sizeof(struct rs485_message_t));

To print it in a human readable form you will need to take each value that you want to see and print it separately with any data manipulation that you may want.  For example:

Serial.print("Checksum 0: ");
Serial.println(rs485Msg.CS0, HEX);

Another thing you can do is to change your structure into a class and inherit the Printable class.  You can then implement the size_t printTo(Print &p); member function which sends the data to the p object for printing in the format you want.  Then you can just print it directly as you are trying to do in your code.


Both red and blue led of ESP8266 stays on

If you have too, you can find the firmware for the ESP8266 here and re-flash it.

There's some good info here about the instruction set.

With respect to your issue of the blue (traffic) light staying on, I can't imagine that the baud command would have caused an issue. Perhaps you need to double check your circuit and make sure that the Rx pin of the ESP8266 is not being held high.

What happens with only 3.3V and GND connected to the ESP8266?

Also the output you're getting is similar to the output from “AT+GMR”. Are you sending it that in a loop by chance?


Have you connected the GND pin from the UNO to the breadboard?  I can't hardly tell.  But it looks like you are also using 5V to power it?

How are you powering the UNO?  Is it just 3.3V?  I'm powering mine with a 5V but have level converters connected.

Mine:


Here is a summary of all this. On an ATmega328P (Arduino Uno, Nano,
etc.), the Arduino core library uses the timers as follows:

Timer 0

timing and delay functions, using the TIMER0_OVF interrupt
“fast” PWM at 980 Hz on pins 5 and 6 (PD5 and PD6)

Timer 1

“phase-correct” PWM at 490 Hz on pins 9 and 10 (PB1 and PB2)

Timer 2

“phase-correct” PWM at 490 Hz on pins 3 and 11 (PD3 and PB3)

All three timers have their prescalers set to 64. TIMER0_OVF is the
only timer interrupt enabled by default.

Note that libraries can use the timers for their own purposes. Servo
for instance uses Timer 1 for doing interrupt-based PWM.


How do you extend the wires from the arduino board to both fsr sensors to be placed on both chairs (one for each)

In ADC sampling there will always be noise.  Longer cables may increase that noise.  Sensors with lower resistance tend have less noise.  For these reasons it would be better to start from a schematic, part numbers and / or specifications rather than a picture.

There are a number of ways to reduce noise.  Hardware solutions include twisted pair and shielded cables.  Software solutions include averaging multiple samples and removing outliers.

If all you are asking is if you can use longer cables, the answer is yes as long as you can tolerate the or compensate for additional noise if any.


Why are my if statements acting like the condition is always true?

Microcontroller pins tend to read LOW when left floating (but not always!). However, pin 1 is used to communicate with the USB-UART converter, and I believe it is set HIGH in the idle state. So assuming you are not pressing any buttons, keys 2-8 will be in the LOW state by default, but key 1 will be HIGH. Hence when defaultCase = HIGH;, the first if is triggered. When defaultCase = LOW; all if's but the first one fire up. Solution — don't use digital pin 1 (edit: avoid pin 0 and maybe 13 as well).

Edit: The answer above refers to the original code without the pull-up resistors enabled.


request for a member "X" in something not a structure or a union

A .c file is compiled with C compiler. If you include Wire.h which contains a class definition, the C compiler doesn't understand it and generates errors.

If your angle.c file doesn't have C code not compatible with C++, then change the extension of the file to .cpp and it will be compiled with C++ compiler.


It is a preloaded sketch and will be overwritten when you upload your first sketch into the Arduino.

Typically it's the Arduino Blink sketch which can be found here:

https://www.arduino.cc/en/Tutorial/Blink

Which has the following (functional) content:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}


Using Keyboard library for ISO-UK layout

The USB keyboard protocol has no concept of characters. It doesn't know and doesn't care what character a key represents. Instead each code represents the location of the key on the keyboard, and it's down to the software on the computer to map those locations into characters through its own keyboard map.
So the Arduino has to do the opposite when you want to "print" text through the keyboard - convert that text into the locations of the keys on the keyboard. And it does that through the _asciimap array in Keyboard.cpp.
To use any other keyboard layout than US you need to modify that map so that each ASCII value points to the correct location for that character as defined in your computer's keyboard map.
You can find the list of keyboard location codes (named in this document after the US keycap decals) here (page 53) which you can then use to map any changes.
For example in _asciimap a double quote is listed as:
     0x34|SHIFT,    // "

Which maps to Keyboard ' and " in USB. But for UK you want that to be shift-2, which is Keyboard 2 and @ in a US layout.  That entry is hex 1F.
So changing the quote to be a shifted 0x1F should give you the quote you desire:
    0x1F|SHIFT, // "

You would need to do the same to all other characters that need re-mapping (including ). Some may take a little trial and error to work out what the equivalent key on a UK keyboard is, since some keys are in physically different locations (most notably there is no key to the left of Z on a US keyboard, but there is an extra one to the right of ]).
Unfortunately the Arduino Keyboard library doesn't provide a way for a user to give their own keyboard map. Instead you have to modify the source code of the library itself.


5V usb surge protection for circuit board?

A polyfuse will limit current not voltage.

There are transient protection diodes which switch on if voltage exceeds a given level, which are often used in conjunction with a polyfuse. The diodes cause excessive current to flow, effectively turning on the polyfuse for extended overload, or just absorbing shorter transients. The Raspberry Pi uses a SMBJ5.0A device to suppress transients.

You should NOT need any of this if you use a reasonable power supply.


Taking voice input from raspberry pi and sending converted text to arduino to turn on relays

Probably the easiest way would be to set up a serial link between them, although there are many ways it could be done; This link looks helpful, as both boards have serial capability, or USB with Pi as host & Arduino as slave should work perfectly well (but a more expensive bit of wire).

An alternative might be an Arduberry?

On the Pi side, there is a sort of meta-answer here - obviously, the Raspberry Pi stackexchange would be the better forum to look at that half of the project.


Switch case inside a switch case with serial input

What happens of the if (Serial.available() > 0) call fails?  That's the problem, because when there isn't anything available it's skipping the second switch statement.

On a point of style it actually might be better to implement the inner switch as a separate function. Imagine what your code will look like with 5 cases in the outer switch, each with 5 cases in the inner switches.

Also it might be worth, for debugging purposes, to always have a default statement, at least then you will know what key it was that you pressed.


Can you output to D+ and D- so that Arduino Uno can be used as a USB device?

Not with an Uno, no. You can only use USB Serial (CDC/ACM) through the on-board USB chip[1].

Your best bet is probably with a Teensy 3 (or 3.1 or whatever they are up to now) which has built-in support for USB MIDI emulation.

1: I believe there is MIDI firmware for the USB chip on the Uno, but installing that requires a hardware programmer and then breaks the normal sketch upload.


Shared 5v power for Due dedicated application

Yes it is possible. You just need to connect both Grounds


WindowsError(31, 'A device attached to the system is not functioning.') in arduino

I got this error.  Then switching USB ports fixed the problem.  Showed up on COM3 in either place. I just switched from a built-in USB port to on off a hub, and it started working.


What is commonly done to stop a servo after reaching desired position?

You do not "stop" a servo.

A servo is always running.  In a general sense, the servo is a control loop that takes as input a position target and applies force to hold at the requested target.  If you want the target to be maintained, then the servo must be running.

A servo motor contains electronics that are internally turning a DC motor on and off as necessary to hold the target position.  If the target does not match the current position, it turns on the motor to turn until the two match.  Once the output shaft reaches what you requested, the electronics inside the servo motor turn the motor "off".  Off meaning the DC motor is drawing little or no current.  The servo control loop is always running comparing the shaft position to a target.

If you powered off the entire servo motor, the position is not under control and could move.  For many applications if you unplugged the wires, the gears and motors apply enough friction that it would not turn.  But in general, you do not count on friction to make things work.

Do I use...Servo.Write(desired position) to keep it from turning?

Yes.  To tell a servo to stay at one position, you can just keep sending it the same target.

But you do not have to Write() again and again.  If you want, you can keep track of what the last setting was and apply only when you have a change.   For example, you can code like this:

if(position_target != position_last_set) {
  Servo.Write(position_target);
  position_last_set = position_target;
}

Regardless of your code, under the hood, Servo is constantly transmitting the position target to the servo motor.


Reading digital port with pullup via Firmata

Never mind, I found out what the problem is. The Firmata SDK (Remote Wiring) for Windows just completely ignores the PULLUP pin mode. There are PR (https://github.com/ms-iot/remote-wiring/pull/102) which fixes this, now it's working just fine.


Access serial monitor on linux cli? Using arduino-cli?

Programs such as screen, minicom or (my favorite)
picocom are useful if you want bidirectional communication
between the Arduino and the host computer. If you only want to read
what the Arduino sends, that can be done with cat:
stty -F /dev/ttyACM0 raw 115200
cat /dev/ttyACM0


How would one send radio signals from Arduino at a non-standard frequency

The standard 433MHz senders obviously don't work, since they have a totally different frequency.

I think "433 MHz" is used as a band name, with 433 MHz actually being at the lower limit of a band that covers approximately 40 MHz. Your garage door opener will likely be referred to as a "433 MHz garage door opener", even though it operates at 447.54 MHz.
For your experiments, you might try the HC-12 module. It's billed as a 433 MHz radio, but in fact it covers 433 MHz to 473 MHz in 100 bands with 400 kHz spacing, so it will cover your desired 447.54 MHz. The link above has some Arduino code examples that might help get you started. And of course there is much more information on this topic if you're interested.