Unusual behaviour over serial communication

Knowing the entire setup would help.  For instance, knowing if the RS232 source will drive the Arduino input's dangerously past the Arduino's power rails.

If you have connected a real RS232 signal to the Arduino, the +12 to -12 volt swings could adversely affect the processor.  Causing unexpected behavior.  In such a case you would need a converter like this one.

Over driving inputs is discussed in this Stack Exchange question where the highest scoring answer says:

  If you violate the spec sheet normal operating conditions requirements
  you can expect to experience abnormal operating conditions. These may
  range fro perfectly normal opration through complete maloperation...

That answer also links to this tutorial about logic level conversion.

Finally, there is this tutorial which specifically addresses converting RS232 to safe TTL level signals appropriate for a micro processor.


Multiple slave(sender) to one master (receiver)

You cannot have 2 devices with the same address at the I2C bus. If they both try to send at the same time with different data, the data will either get corrupted, or one of the slaves will stop to send. You cannot request data from more than 1 device at once with I2C.

You have to give the slaves different addresses. Then you have to do the requests sequentially, first a request (with the corresponding read) to the first slave and after that is done, you can start a second request (with the corresponding read).

Besides that, the reading code is not good. You are testing in the condition of the while loop, if there is anything to read (which can be only 1 byte), but then you read 2 bytes. In your case you only have to read 1 byte, since you also request only 1 byte. In the case, when you request more than 1 byte, you can either check, if there are enough bytes in the buffer (with something like if(Wire.available()>=2) ), or you can just work through the buffer byte by byte (with while(Wire.available()){ data = Wire.read();} , note the single read in the while loop).


Have a look at the current requirements of the SG90 and compare this to the maximum current available from an Arduino Uno.

Another thing to look at is how much current your computer's USB port can supply. My laptop, for example, can only supply 500mA per USB port.

My advise is to use a separate 5V power supply for the servo.


Adafruit GPS breakout has their own library setup.
Below is the code I use for my telemetry. Notice I'm using HardwareSerial though.
You can just change that into SoftwareSerial.

#include <SoftwareSerial.h>
#include <Adafruit_GPS.h>
#define GPSECHO false // Disables GPS breakout debug

boolean usingInterrupt = false;

HardwareSerial gpsSerial = Serial1;
Adafruit_GPS GPS(&Serial1);

SoftwareSerial XBee(2, 3); // For wireless

unsigned int REFRESH = 20;

double lat_deg, lon_deg, lat_min, lon_min;
char lat, lon;

void setup()
{
  Serial.begin(115200);

  GPS.begin(115200);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_5HZ); // Either 1HZ or 5HZ
  GPS.sendCommand(PMTK_API_SET_FIX_CTL_5HZ);
  GPS.sendCommand(PGCMD_ANTENNA);

  useInterrupt(true);
}

SIGNAL(TIMER0_COMPA_vect)
{
  char c = GPS.read();
#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;
#endif
}

void useInterrupt(boolean v)
{
  if(v)
  {
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  }
  else
  {
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

void loop()
{
  if(GPS.newNMEAreceived())
  {
    if(!GPS.parse(GPS.lastNMEA()))
    {
      writeData(1, true);
      Serial.print(GPS.hour, DEC); Serial.print(F(","));
      Serial.print(GPS.minute, DEC); Serial.print(F(","));
      Serial.print(GPS.seconds, DEC); Serial.print(F(","));
      Serial.print((int)GPS.fix); Serial.print(F(","));
      Serial.print((int)GPS.fixquality); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999"));
    }
    else if(GPS.fix)
    {
      writeData(1, true);
      parseGPS(GPS.latitude, GPS.longitude);
      Serial.print(GPS.hour, DEC); Serial.print(F(","));
      Serial.print(GPS.minute, DEC); Serial.print(F(","));
      Serial.print(GPS.seconds, DEC); Serial.print(F(","));
      Serial.print((int)GPS.fix); Serial.print(F(","));
      Serial.print((int)GPS.fixquality); Serial.print(F(","));
      Serial.print(lat_dd, 8); Serial.print(F(","));
      Serial.print(lon_dd, 8); Serial.print(F(","));
      Serial.print(GPS.speed); Serial.print(F(","));
      Serial.print(GPS.angle); Serial.print(F(","));
      Serial.print(GPS.altitude); Serial.print(F(","));
      Serial.print(GPS.satellites);
    }
  }
  delay(REFRESH);
}

void parseGPS(float _latitude, float _longitude)
{
  lat_deg = (int) (_latitude / 100);
  lon_deg = (int) (_longitude / 100);

  lat_min = _latitude - (lat_deg * 100);
  lon_min = _longitude - (lon_deg * 100);

  lat_dd = (double) lat_deg + ((double) lat_min / 60);
  lon_dd = (double) lon_deg + ((double) lon_min / 60);

  lat = GPS.lat; lon = GPS.lon;

  if (lat == 'S') lat_dd = -lat_dd;
  if (lon == 'W') lon_dd = -lon_dd;
}

void writeData(float data, boolean next)
{
  Serial.print(data);
  if (next) Serial.print(F(","));
}


ESP8266 - Error: unknown opcode or format name 'jmp'

The proper way to reset the esp8266 when using the Arduino IDE is to call ESP.reset(). You may need to #include <Esp.h>, but almost all esp8266 headers you include to use any of its functionality will have included it already.


Can I change this code to use a potentiometer instead of a push button

This is a simple sketch that shows how to read a potentiometer and do something with the value, namely, adjust the delay of the blinking led.

[Source: https://www.arduino.cc/en/tutorial/potentiometer]

/* Analog Read to LED
 * ------------------
 *
 * turns on and off a light emitting diode(LED) connected to digital
 * pin 13. The amount of time the LED will be on and off depends on
 * the value obtained by analogRead(). In the easiest case we connect
 * a potentiometer to analog pin 2.
 *
 * Created 1 December 2005
 * copyleft 2005 DojoDave <http://www.0j0.org>
 * http://arduino.berlios.de
 *
 */

int potPin = 2;    // select the input pin for the potentiometer
int ledPin = 13;   // select the pin for the LED
int val = 0;       // variable to store the value coming from the sensor

void setup() {
  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT
}

void loop() {
  val = analogRead(potPin);    // read the value from the sensor
  digitalWrite(ledPin, HIGH);  // turn the ledPin on
  delay(val);                  // stop the program for some time
  digitalWrite(ledPin, LOW);   // turn the ledPin off
  delay(val);                  // stop the program for some time
}

So, in every loop iteration you read the potPin and using that value for delay.

AnalogRead gives you a value between 0-1023, which you have to adjust to give the desired value for temperature control. That is all you need.

Use map function to adjust the value. Look at https://www.arduino.cc/reference/en/language/functions/math/map/


Ramping up and down arduino motor due to ultrasonic sensor input

The speed seams to be defined by a an analog write to SpRMotor and SpLMotor. You did that once (with value 170)  in the setup. If you use variables for that (e.g. speedValueL and speedValueR) you can change their values as you need it and write it to the PWM channels on each forward, backward, left or right statement.

A short example:

int SpRMotor = 5;  //speed Right Motor
int MotorA1 = 7; //Right Motor = +
int MotorA2 = 6; //Right Motor = -
int MotorB1 = 8; //Left Motor = -
int MotorB2 = 9; //Left Motor = +
int SpLMotor = 10;  //speed Left Motor

int TriggerPIN1 = 3;//right
int EchoPIN1 = 2;
int TriggerPIN2 = 12;//left
int EchoPIN2 = 11;

int speedValueL = 0;
int speedValueR = 0;

void setup()
{
  pinMode(TriggerPIN1,OUTPUT);
  pinMode(EchoPIN1,INPUT);
  pinMode(TriggerPIN2,OUTPUT);
  pinMode(EchoPIN2,INPUT);

  pinMode(MotorB1, OUTPUT);
  pinMode(MotorB2, OUTPUT);
  pinMode(MotorA1, OUTPUT);
  pinMode(MotorA2, OUTPUT);
  pinMode(SpLMotor, OUTPUT);
  pinMode(SpRMotor, OUTPUT);

  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  Serial.begin(9600);
}

void loop()
{
  int limit;
  int sampledata1, sampledata2;
  sampledata1 = distance(TriggerPIN1, EchoPIN1);
  Serial.print("distance1: ");
  Serial.print(sampledata1);
  delay(100);
  sampledata2 = distance(TriggerPIN2, EchoPIN2);
  Serial.print(" distance2: ");
  Serial.println(sampledata2);
  delay(100);
  limit = 10;
  if( (15> sampledata1 >= limit) && (15> sampledata2 >= limit) )
  {
    Serial.print("True");
    // Just my guess - do what fits for you
    speedValueL = 170;
    speedValueR = 170;

    forward();
    delay(100);
  }

  if (sampledata2  >= 15 )
  {
    // Just my guess - do what fits for you
    speedValueL = 200;
    speedValueR = 0;

    turnRight();
  }

  if (sampledata1  >= 15 )
  {
    // Just my guess - do what fits for you
    speedValueL = 0;
    speedValueR = 200;

    turnLeft();
  }

  if ( ( limit > sampledata1 ) && ( limit> sampledata2 ) )
  {
    // Just my guess - do what fits for you
    speedValueL = 0;
    speedValueR = 0;

    Stop();
  }
}

void forward()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, HIGH);
  digitalWrite(MotorB1, HIGH);
  digitalWrite(MotorB2, LOW);
}

void turnRight()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, LOW);
  digitalWrite(MotorB1, HIGH);
  digitalWrite(MotorB2, LOW);
}

void turnLeft()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, HIGH);
  digitalWrite(MotorB1, LOW);
  digitalWrite(MotorB2, LOW);
}

void Stop()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, LOW);
  digitalWrite(MotorB1, LOW);
  digitalWrite(MotorB2, LOW);
}

int distance( int trig, int echo )
{
  digitalWrite( trig, LOW );
  delayMicroseconds( 2 );
  digitalWrite( trig, HIGH );
  delayMicroseconds( 10 );
  digitalWrite( trig, LOW );
  long timedelay = pulseIn( echo, HIGH );
  int distance = 0.0343 * ( timedelay / 2);

  return distance;
}


If you use the Arduino IDE Board Manager to install the support for ESP boards
an ESP8266 can be programmed in EXACTLY the same way as you program an Arduino.

This mean you will now be able to follow the Cactus Micro sample up to the point where you upload CMTempTest.ino.

The problem with the HubTest.ino code is that relies on having a serial link between the Cactus board's main processor and its ESP8266 network slave processor.  You don't have that so all the AT commands are not going to work.

However you do have a number of examples that come with the ESP addition to the IDE and in there will be a network client example.  You need to look at how that code forms a connection and make HubTest.ino work in that way.  I can't tell you exactly what to do (I don't know) but any lines that are AT related need to be replaced by "proper" networking code.


Seems too simple:

float x = n1 + n2 * 0.1;

Is there a trick?

Edit: The method proposed by Michel Keijzers, namely

float x = n1 + n2 / 10.0;

(I removed the redundant casts) can be slightly more accurate, but takes
longer to compute, because division is significantly slower than
multiplication on the Uno. Computing n2/10.0 always yields the
correctly rounded result, namely the float that best approximates the
exact mathematical result. On the other hand, n2*0.1 involves two
rounding operations: one at compile time, in the representation of 0.1
(which is not an exact float), another at run time, which rounds the
result of the multiplication. If n2 is between 0 and 8, you end up
getting the correctly rounded result anyway, just as with n2/10.0.
However, if n2 is 9, then

n2*0.1 yields 0.900000035762786865234375 (error ≈ 3.6e-8)
n2/10.0 yields 0.89999997615814208984375 (error ≈ -2.4e-8)

The former carries a rounding error 1.5 larger than the latter.


Differential voltage measurement with Arduino UNO

You do not need to do any kind of differential measurement here. The
Arduino analog input measures voltages relative to ground. Then, as long
as the Arduino and the power supply share a common ground, you should be
fine.

On the other hand, you may need a voltage divider. I have seen a few
sensors interfaced the same way (GND, +24V and signal), which output a
voltage between 0 and +10 V. That could fry the Arduin, and maybe
also the sensor. Check the datasheet to see the maximum voltage the
sensor can output, and use a voltage divider to get that safely into the
0 – +5 V range.


Is there a way to make wiring a bare microprocessor to a shield easier?

You can make adapter boards (one for each mcu model).

The bottom side (male headers) would plug to the breadboard and the upper side would have female headers with the same pinout as an Arduino board (female hearers placed in the appropriate positions to match Arduino shields).

Such a board shouldn't be difficult to design.

Here is an image that resembles what I describe

It would adapt the pinout of a bare AVR to the pinout of a typical Arduino so that shields can by directly plugged on top of it.

Also a pinout diagram may come handy to speedup things when you use a bare chip with Arduino code.
(image source)

Another similar solution is a small printed sticker placed on top of the AVR
(image source)


Using digital weighing scales with INA125p

Fixed (to some extent)! Faulty connection between the INA125p and the plint it was sitting in. I refitted it and i'm now getting varied readings with the scales, but that's to be expected with the noise the INA125p generates.


Android  HC-05  Arduino communication issue

As mentioned by @alex.forencich, SoftwareSerial is not designed to support simultaneous bi-directional communication.

I found a link to AltSoftSerial library on Arduino site, and this lib seems to work properly in my setup.

To convert from SoftwareSerial to AltSoftSerial you need to change the pins that HC-05 is connected to (on Arduino Uno these are pins 8,9), and to make this minor change in the code:

//#include <SoftwareSerial.h>
//SoftwareSerial swSerial(10, 11);

#include <AltSoftSerial.h>
AltSoftSerial swSerial;


You are reading A5 but in your diagram you show it hooked up to A0:

Change your code to this and I believe it will work:
const int sensor= A0; // Assigning analog pin A0 to variable 'sensor'

void setup() {
  pinMode(sensor,INPUT); // Configuring sensor pin as input
  Serial.begin(9600);
}

void loop() {

  float reading=analogRead(sensor); //Reading the value from sensor
  float vout= (reading*5000)/1024;
  float temp= vout/10;

  Serial.print("in DegreeC= ");
  Serial.print(temp);
  Serial.println("");

  delay(500); //Delay of 1 second for ease of viewing

}

The data you are reading from A5 is indeterminate and just happens to decrease as A0 increases.
================================================================================
UPDATE:
Ok, so you corrected yourself and are reading the correct pin in spite of what your schematic shows.  Please explain this:
float vout= (reading*5000)/1024;
float temp= vout/10;

I think you want:
float vout = (reading/1024.0) * 5000.0;
float temp = vout/10.0;

You are carelessly mixing floating point and integer math.


analogRead always returns 1023 - Arduino Mega 2560

I had a similar problem when I ported my code from an Arduino Due to an Arduino Mega. I was able to solve this problem by adding the following call in the setup function.

analogReference(DEFAULT);

It seems that in some other Arduinos, the analog reference will be selected automatically, but at least the Arduino Mega needs it.


Split up Arduino code into multiple files using Arduino IDE

There is no need to use an #include directive for the additional .ino file.
Before compilation starts, the Arduino IDE concatenates all .ino files in your sketch into a single file, starting with the .ino file that matches the sketch folder name, followed by the rest of the .ino files in alphabetical order. So there is no difference between one massive .ino file and breaking the same code among multiple .ino files, other than the greater ease of navigating the code via tabs. After a bit more processing, this file is compiled as C++.
Reference:
https://arduino.github.io/arduino-cli/latest/sketch-build-process/#pre-processing


WDT settings will remain unchanged, even after a reset. So the timer will keep running and therefore keep resetting the device. Which causes the blinking. Power cycling will clear the WDT settings.

PS I didn't read the code, as uncommented register writes are pretty much unreadable.


is any windows application available for accelerometer based computer mouse


It's likely an issue related to the modules'  electric supply. The effects can be packet loss (even down to zero bps) or loss of communication with the module.

Two things have to be covered with the nRF modules for them to work:

current draw (i.e. power),
decoupling/filtering (i.e. bypass capacitors).

Since you don't mention specific devices, I'm assuming you refer to an 'antenna' module with SMA (or RP-SMA) connector.

The Nordic Semiconductor nRF24l01+ that is typically used in these modules has a maximum power consumption well below 100mW.

A module with power amplifier (PA) draws significantly more power than the nRF chip alone, the total power consumption will be larger than 100mW.

An Arduino can only supply power according to it's onboard regulator capabilities.
The Minis (and Micros) feature a smaller regulator that cannot drive both the Atmel AVR microcontroller and the PA.

Solution:

provide a separate 3.3V regulator for the nRF module(s),
place a capacitor directly at the modules' connector's supply pins.

Link:

https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo#PP


How can I switch from ArduinoOTA to ESPhome safely?

I've found that when a flash fails with a space error, I've usually specified the wrong flash size option in Arduino (under Tools->Flash Size).  Depending on the version of Arduino you're using, try picking the one with "No SPIFFS" or FS:none that matches the size of your flash memory.  Once you make that change, recompile and reupload.


I never use TLE9879, but I could guess of why it doesn't work as expected.

For ATMega328p-based Arduino boards (i.e. Uno, Nano and Pro Mini), it has pin 11, 12 and 13 as SPI’s MOSI, MISO and SCLK signals, but at the same time these signals are also available on those board’s In-Circuit Serial Programming (ICSP) header pin 4, 1 and 3, except for Pro Mini which does not have a dedicated ICSP header.

This however is not the case for Arduino Leonardo and Arduino Micro which are based on ATMega32U4, for those boards, the SPI is only available on ICSP header. This is one of the reasons that some of the Arduino shields designed for Arduino Uno does not work with Arduino Leonardo when SPI communication is involved.

Based on the information of TLE9879, the SPI port is connected to pin 11-13 so it is designed to work with Arduino Uno but will not work for Arduino Leonardo.


A better solution would be to use a PNP transistor to control the EN pin. A PNP is ON when the input to it is LOW (or lower than the collector minus 0.7V, that is).

Take this circuit, for instance:

simulate this circuit – Schematic created using CircuitLab

When the GPIO is HIGH the transistor Q1 is turned off (GPIO >= VCC-0.7). Also if the GPIO pin is disconnected it is turned off because R3 pulls it up to VCC.

Set the GPIO LOW and Q1 turns on since the base is now lower than VCC-0.7V. With Q1 turned on it connects the EN pin to ground, so it becomes LOW.

If you replace the PNP with an NPN (there's more chance you have one in your bits box) you can basically invert the logic:

simulate this circuit

Now when the GPIO is LOW or pulled down by R3 Q1 is off and EN is pulled HIGH. Set the GPIO HIGH and Q1 turns on and connects EN to ground setting it LOW.

In both these scenarios the EN pin defaults to HIGH. If you want it to default to LOW until you activate the GPIO pin (i.e., during bootloader operation when the GPIO is in INPUT mode) you can reverse R3 so it becomes a pull-down (for the PNP) or a pull-up (for the NPN).


Teensy4.1 has 55 digital IO (serial) pins at up to 200MHz. The USB port supports 480mbps, and ethernet is 10/100mbps. You're limited to 32 DMA channels, though (complicated but these are used to access onboard peripherals/memory). You don't have much contiguous ram, either.
Now, you haven't explained what you're doing with this data. This matters because even though the CPU is running at 600MHz, asymmetric encryption is slow. Are you trying to perform real-time encrypted communication? Are you just sending or receiving data as well?
Nothing stopping you from asymmetrically encrypting on a Teensy. You can find the source code for the OpenSSL functions RSA_public_encrypt and RSA_private_decrypt.
This question goes into calculating how many CPU cycles are needed to encrypt X bytes of data.
However, asymmetric encryption has problems: Like I said, it's slow - specifically RSA, and the size of the data you can encrypt depends on the size of your key and padding.
If you want to communicate in something resembling real-time, you want to use hybrid encryption. You should read about how TLS works; the short version is that an asymmetric handshake occurs where the two parties agree on a symmetric key. Once you decide what your data actually is, you can quantize it (eg. TLS 'chunks' are up to 16KB which are then sent as multiple TCP packets) then both parties use the symmetric key to send/receive - which can encrypt large data chunks without issue.


Your sketch is running on borrowed memory.
Every time the loop function runs, the new text is concatenated with strcat() and the buffer msg_out is never reset.
The first time 12 bytes are used, the second time 23 bytes, the third time 34, and so on.

The solution in the answer by @VE7JRO will fix that, but I prefer not to use dtostrf() and transmit binary data.

I see a few other problems as well:

Why do you want to transmit readable ASCII text? Use binary data.
Either float numbers or integers. For example an integer in 1/100 degrees.
The RadioHead library uses a lot of memory. You can not use an other
library that uses also a lot of memory.
The value of '5' for dtostrf is the minimal width,
so you better make those arrays for example 20 bytes.
I prefer to put those arrays temporarily on the stack.
The DHT11 is not accurate. If you upgrade to a better sensor with I2C,
then you need more libraries (the Wire library and a sensor library),
and you might run out of sram memory.
When using the RadioHead library in default mode, it uses three
pins (rxPin=11, txPin=12, pttPin=10). You better add a comment
section to your sketch to explain that you should not use those pins.
You have already a
conflict at pin 10 for the DHT sensor and the pttPin.

The old and no longer supported VirtualWire library has some bugs, but it uses less memory than the RadioHead library. The RadioHead library is not optimized for Arduino boards like the Uno, Nano, Leonardo, and others. It even requires to #include <SPI.h> because that is often used with transceivers, even if the SPI bus is not used in RH_ASK mode (thanks to @VE7JRO for explaining this in the comment below).

The easiest way to transmit more than one value is with an array.

float myData[2];
myData[0] = 23.456;
myData[1] = 68.0;
rf_driver.send((uint8_t *)myData, sizeof(myData));

The sizeof() is not a real function, it tells the compiler to fill in the size of that variable. Since a float is 4 bytes, you may also fill in the number 8 for the second parameter.

There are a number of solutions for the receiver. I like to use a pointer to the buffer, but perhaps it is easier to copy them to variables with memcpy().

float myData[2];
if (driver.recv(buf, &buflen)) {
  if (buflen == sizeof(myData) {  // extra check
    memcpy((uint_8 *)myData, buf, sizeof(myData));
    Serial.println(myData[0]);
    Serial.println(myData[1]);
  }
}

When the receiver is also an Arduino board, then there should be no problem. When the receiver is something else, you might have to check if the byte-order is the same. The float variable of a Arduino is 100% IEEE compatible, but sometimes it is easier to use only integers.

The most common way is to use a struct. A struct is a package that can hold all sorts of data (integers, bytes, arrays, and so on). The receiver and the sender should have exactly the same definition for the struct of course.


Serial communication arduino mega and D1 Wemos Mini

Apart from ensuring you're wiring TX -> RX and connecting all grounds, you can use SerialTransfer.h to automatically packetize and parse your data for inter-Arduino communication without the headace. The library is installable through the Arduino IDE and includes many examples.

Here are the library's features:

  This library:

  can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
  works with "software-serial" libraries
  is non blocking
  uses packet delimiters
  uses consistent overhead byte stuffing
  uses CRC-8 (Polynomial 0x9B with lookup table)
  allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
  can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  char buff[] = "hi";

  myTransfer.txObj(buff, sizeof(buff));
  myTransfer.sendData(sizeof(buff));
  delay(100);
}

Example RX Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  if(myTransfer.available())
  {
    char buff[40];

    myTransfer.rxObj(buff, sizeof(buff));

    Serial.println("New Data: ");
    Serial.write(buff, sizeof(buff));
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}


Please post the code where you call the library. In particular where do you make an instance of IRControl?

I am guessing you are doing it at global scope which means you are probably running into the C++ static initialization order fiasco.

What it is: http://www.parashift.com/c++-faq/static-init-order.html

How to prevent it: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html

To prevent this, you should not be doing this in the class constructor:

irrecv = new IRrecv(RECV_PIN);
pinMode(RECV_PIN , INPUT);
irrecv->enableIRIn();

Instead, make a begin function (like most Arduino classes do) and call that from setup.


More missed messages with longer cables with nRF24L01+?

the Antenna is interfering with the signals because of its proximity to the point on the bread board where you are connecting the wires, as Majenko said.

If you rotate the nRF24L01 board 180 degrees you will increase the distance between the wires and the antenna and this will reduce the interference, but because of the way radio waves propagate there is also a chance that it may make it worse.  The radio wave propagate from the antenna in a share particular to the antenna.  I don't know what shape this antenna puts out, I'd expect it to be omnidirectional (all ways) because of its purpose.  However all directions are not equal because of reflections, the shape of the antenna, defects in the shape of the antenna, etc and if the pattern of the propagation can be mapped you can identify the make of board and if the mapping is accurate enough even the instance of the board itself.

So, to cure interference:

Increase the distance this reduces the power of the interference by the square of the distance.
Change the orientation, usually by something other than 90 or 180 degrees.
Shield the wires.

In short move the antenna further away from the wires, can you use MF DuPont wires to remove the radio from the breadboard all together.  The fact it won't sit still and is sliding all over you desk will probably help with reflections.


How detect I2C errors with requestFrom()

The Wire library does not give you any possibility to get error states, when requesting bytes from a slave. Basically you are stuck with the number of bytes being read.
Though you can read some information from that. If the number of bytes is zero, the slave didn't answer (either because its not there, or because it cannot send any byte currently). This equals a NACK by the slave after the address byte.
Other than that the I2C protocol doesn't give any more information. On requesting the slave is sending data and the master is acknowledging it. That means, that the slave cannot generate a NACK in this process. In fact that also means, that the returned number of bytes can only be zero (on NACK on address) or equal to the number of requested bytes, since after the address ACK from the slave the master will continue to generate clock pulses, until it has read all bytes, that it wanted. If the slave doesn't have any more data to send before that, it cannot stop the transmission. It would just stop driving the data line, resulting in all high data bytes (0xFF).
Also I doubt, that it would be really useful in your case. I2C is made for small distances, mostly on the same PCB. It can be used for longer distances, but your mileage may vary. If your setup really can corrupt the communication on the I2C lines, your biggest problem will be a stuck bus. The I2C protocol is generally not prepared for noisy environments and it incorporates states, where the devices on the bus can wait infinitely. This is also reflected in the Wire library. That means, that big noise on the lines will often lead to the bus being stuck in the middle of a transaction, needing you to reset the devices (not only the slaves, but also the master) to get the bus free again. I would go so far to say, that is it more likely to get the bus stuck, than to get corrupted data. So any information about errors is not really helping you here, since you won't get out of requestFrom() in the first place. Your code can very well get stuck there.
I suggest, that you test your setup thoroughly with the wanted run times. If the bus gets stuck too often for you, then you should make your setup more robust (shielded cables, or using an extra MCU with the I2C slave and using a more robust communication interface between main MCU and extra MCU).


How to read data directly from lcd display

I would recommend ditching the the digitalRead in this case - it is performed sequentially, and is rather slow.
As you only need to read 8 input lines, consider using Port register: The Arduino Uno comes with a total of three Ports which "hold" all of the I/O pins.
Those are

PORTB = Digital Pins 8 through 13 plus the crystal pins
PORTC = Analog Input 0 through 5, reset pin
PORTD = Digital Pin 0 through 7

Since you need the RX and TX lines (Digital pin 0 and 1) for your serial communication, you will have to split the signal onto two registers.

I would recommend connecting D0 through D3 to Digital Pins 8 through 11 for the first four bits (meaning they'll go to bits 3 to 0 of Port B), and D4 through D7 to Analog Pins 0 To 3 (meaning they'll go to bits 3 to 0 of Port C).
RW goes to Pin 7, RS to Pin 6, E to Pin 5.

The code you would then use to read the data would be this:
    uint8_t byte_displaydata = 0x00;
    uint8_t RW = 7;
    uint8_t RS = 6;
    uint8_t E = 5;

void setup() {
  Serial.begin(1200); //perhaps increase this a bit
  pinMode(RW, INPUT); //some speed is lost compared to register manipulation, but that is likely insignificant
  pinMode(RS, INPUT);
  pinMode(E,INPUT);
  DDRB &= ~((1 << DDRB0) | (1 << DDRB1) | (1 << DDRB2) | (1 << DDRB3)); //technical not necessary since they're initialized with 0
  DDRC &= ~((1 << DDRC0) | (1 << DDRC1) | (1 << DDRC2) | (1 << DDRC3));
  PORTB &= ~((1 << PORTB0) | (1 << PORTB1) | (1 << PORTB2) | (1 << PORTB3)); //disable internal pullups
  PORTC &= ~((1 << PORTC0) | (1 << PORTC1) | (1 << PORTC2) | (1 << PORTC3));

}

void loop() {
  if(digitalRead(RS) == HIGH && digitalRead(E) == HIGH){
    byte_displaydata = 0x00; //reset byte_displaydata
    byte_displaydata = PINB << 4; //push PINB bits 3 to 0 to bits 7 to 4
    byte_displaydata |= (PINC & 0x0F); //filter PINC bits 3 to 0 and OR them into result bits 3 to 0
    Serial.println(byte_displaydata,BIN);
  }
}

Please note that I have not tested this, and only recently have gotten started in AVR / Arduino.
If anyone can look this over, I'd greatly appreciate it.

Source: Microchip ATmega328P datasheet, Arduino pin mapping


Same way you would handle any error in an embedded system; either try to recover from it if you can, or use whatever communications mechanism you have to let the user know that something failed.

I normally use a combination of Serial.println in case I happen to have a serial connection at the time, and also a blinking pattern on an LED (which most boards I use have). As an example, look at my code here: https://github.com/jayeye/jardino/blob/master/libard/WiFiSPIFFSConfig/src/WiFiSPIFFSConfig.cpp#L11. error() will do a sequence of slow and then fast blinks, and either return if I think the error is recoverable and I'm merely warning the user, or just stay in an infinite loop and keep blinking in despair :)

Obviously this is not an original idea -- think beep codes!


Need lot GPIO pins on arduino mega - what are restrictions?

All those pins should be available. But if you want to use Pin change interrupts, you have to check which pins are usable.


Optimizing ext. SPI ADC for speed and verify the speed

Don't use digitalWrite().
Don't use delay().
Don't flood your Serial connection with useless junk ("analog value =")

You may also consider using lower level SPI operations instead of the SPI library, which is completely blocking and slows you down. At least consider the use of SPI.transfer16(...) which is more efficient than two SPI.transfer(...) calls.


connect arduino to battery with 12V motor

I am looking at this(instructable with circuit picture) tutorial for making a self-balancing robot.
  However, I am confused about how the battery connects to the arduino.

Well, it seems he has attached a 9V battery through a voltage regulator, to the Arduino.
Which is bullshit.

You can put the 9V directly into the barrel-jack of the Arduino. You actually should. Putting 5V on the barrel jack is not within the specs. (https://www.arduino.cc/en/main/arduinoBoardUno)

  I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply.

Well, the motors only get 9V in this diagram (which might work neverthless). But bear in mind that 9V batteries won't last long.

I'm not sure what you mean by "Green device", the HC-05 or the L293D?
Anyway, the L293D are quadruple high-current half-H drivers, which basically is a way to switch 12V on/off/invert based on the 5V inputs (from Arduino).
You could do this with some circuitry, but I suggest picking up a "motor driver (arduino)"

  How should I get a charger cable and solder on the battery wires to
  the charger?

You can't charge regular 9V batteries.

  Is the connection to the Aruino necessary?

The specific connection he shows? No.
Power to the Arduino board? Yes.


Decoupling cap for self-powered LED matrix and LED strip

No, there is no need. The matrix already has plenty of decoupling on it, including a large electrolytic for the incoming power and a small ceramic on each of the chips.


Using a lot of interrupts on a single Arduino

On a Uno, all of the digital and analog pins can trigger a pin-change interrupt. That gives you 20 inputs straight away. The Mega also has pin change interrupts but not on all its pins. The pins that the Mega supports for pin-change interrupts are documented on the Software Serial page.

  Not all pins on the Arduino Mega and Arduino Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

(Note that the Atmega2560 chip itself supports more pin change interrupts, however those extra ones are not brought out to header pins on the Arduino board).

That's still quite a few (18 if I counted correctly). Plus the hardware interrupt pins: 2, 3, 18, 19, 20, 21.

  Right now I'm using 4, but i want to reach up to 60 sensors, and a minimum of 16

To reach 60 you probably want an input shift register such as the 74HC165 - you can daisy-chain them together to get lots of inputs. However you would have to poll to see if pins changed.

Otherwise you could use something like the MCP23017 chip, which has 16 input/output pins, and supports interrupts. You can use 4 of them (interfacing with I2C) and thus get 64 inputs. There is a shield that has 4 of those chips on it:

With suitable software (see my page about I2C) you could configure for interrupts and read any of those 64 inputs when they change.

  Do I have to keep checking all the time for every sensor one by one?

No, because you can configure the interrupts as open-drain, which means you can connect them all together (if you want to). Or, you could bring out the interrupts for the 4 x MCP23017 chips to four interrupt inputs on the Mega (that narrows down for you which chip caused the interrupt). Then you can read the chip's register(s) to find the state of the pins - either at the time of the interrupt, or right now.

However you might find that it is actually faster to just poll the chips (say) 100 times a second. There is some overhead to using I2C, you can also get SPI versions of that chip (MCP23S17) which would operate a bit faster.

Alternatively, the 74HC165, whilst simpler, could also turn out to be overall faster if you just poll rapidly.

  And the sensor sense a lot of movement per second, won't that cause trouble for the Arduino?

You need to define "a lot" and "trouble". You won't do billions of read a second. You can probably do thousands. What would you do with thousands of readings anyway? The time taken to process them would probably be the limiting factor.

  At the same time I'm using a GPS, no problem for the usage of Serial and I2C together right?

No problem, because serial input is interrupt-driven. Within reason, you can do both at once.


Why doesn't the Ethernet W5100 shield work on Gigabit switch?

The fix for this is to solder a 120 Ohm resistor between pins 1-2 and 3-6 of the RJ45 socket (where pin 1 is closest to the left side of the socket when looking at the top of the board. (Credit to keithsw1111 for the fix)

See https://forum.arduino.cc/index.php?topic=372779.0 for full details.

I know this was asked a long time ago however this post comes up quite high on a google search of the issue so its good to have reference to the fix.


It could be something else (in the RFID low freq ~ 125khz) like a HID card.
Also it could be an NFC (high freq 13.56Mhz) that its not compatible with the RC522.

Do you have access to a phone with NFC, to start ruling out what could it be?


I don't know where to start.

You did not provide a full sketch. There is, for example, no Serial.begin1() in sight.
You did not provide enough information about the device. If you don't want to tell us what it is, then give an indication of its age. In the 1980's it was common to have 7E1 format (7 data bits, even parity, 1 stop bit).
You have to be sure what the baudrate is. To detect a wrong baudrate, you need a oscilloscope or logic analyzer. When the device has a processor and the baudrate is derived from it's clock, the baudrate could be different from the specified baudrate by a few percentage. That is already a problem with the Arduino.
It could be a problem with inverse voltage levels. What does the device use as idle and as active level ? The Arduino Mega uses +5V at the TX pin when idle, and low is active. That means that the TX pin is normally high, and the first low pulse is the start bit.
The device could return an error code instead of an echo.
Your SkRead function can be improved:
Using a String object to collect the incoming data and after that converting the String object to a unsigned char array to use it, is not the most elegant solution. You could just use a unsigned char array to read the incoming data.
It is not okay to add something to the millis value. That is a problem when millis does a rollover (after 50 days or so).
Normally a character is read as soon as it is available. You wait until 8 characters are in a buffer. No one else does that.

To solve this puzzle you need more information. Try to capture the RX and TX signals with a oscilloscope or logic analyzer. Or else try to write a very small sketch that creates the problem.

My best guess is that it is not your sketch, but perhaps a combination of inverse levels, parity and baudrate.

[ADDED]
After writing down the bits over the serial bus, it might indeed be inverse voltage levels and maybe something with 7 bits or parity. That would also explain the last bytes to be 255. Those 255 are not valid data.


Can two electronic speed controllers be connected to the same ground pin?

You can connect all the grounds together and the circuit will be safe. If the BEC outputs 5V, you can feed it directly to the Arduino's 5V pin. Any more volts and you'll need to feed the BEC output to the Arduino's VIN pin.


Loop runs as long as loop needs to run.

Instructions in a CPU run sequentially. The more instructions there are the longer it takes to run.

The more code you put in loop the longer loop will run.

There are two ways to know how long each iteration of loop will take:

Profiling: Actively time each iteration of loop, though be warned, the act of timing will affect the amount of time taken.
Cycle counting. Compile the source into assembly and total up the number of clock cycles needed for all the instructions (including calls to functions). Arduous for small loops, a gargantuan task for anything else.

Also note that many external factors can affect how long loop() takes to run - such as serial communication speed, etc.


Arduino metronome - Change time signature on button press

You must have resistors in series with the LEDs. See The care and feeding of LEDs. 330 ohms in series with each LED would be about right in your situation.

With no resistors you are drawing far too much current from the output pins. That would drop the voltage and the processor would reset. Thus it goes back to the default of 4 beats per measure.

It also damages both the processor and the LEDs.

You can tell if the processor resets by putting extra code into setup. For example, after setting the pins to outputs:

 for (int i = 0; i < 10; i++)
    {
    digitalWrite (3, HIGH);
    delay (200);
    digitalWrite (3, LOW);
    delay (200);
    }

If you see pin 3 flashing 10 times, you know the processor has reset.

I think your problem now is that you have a floating input for the switch. When I tried your sketch, with a couple of modifications, it worked fine.

My code:

/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 12;
int buttonState = 0;
int bpm = 120;
/**************************************/
void setup()
{
  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {
    pinMode(thisPin, OUTPUT); //initialize thisPin as an output
    pinMode(6, INPUT);
  }
  pinMode(keyPin, INPUT_PULLUP);
}

/****************************************/
void loop()
{

  //iterate over the pins
  //turn the led on from lowest to the highest

  if (digitalRead(keyPin) == LOW && ts == 2) {
    ts = 3;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 3) {
    ts = 4;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 4)
  {
    ts = 2;
    delay(2000);
  }

  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {

    bpm = pulseIn(6, HIGH);
    //bpm = 1000;

    pinMode(speaker, OUTPUT);
    if (ts > 4)
    {
      if (count > 3)
        for (int a = 4; a <= ts; a++) {
          digitalWrite(a - 3, HIGH);
        }
    }
    else
      digitalWrite(thisPin, HIGH);

    if (count == 1)
      tone(speaker, 1500, 100);
    else
      tone(speaker, 1000, 100);

    unsigned long now = millis ();
    while (millis () - now < (bpm - 52))
      {
      // quit delay if switch pressed
      if (digitalRead(keyPin) == LOW)
        break;
      }

    pinMode(speaker, INPUT);
    digitalWrite(thisPin, LOW);

    count++;
    if (count > ts)
      count = 1;

  } // end of for each pin

} // end of loop

Note that the input from the switch is now INPUT_PULLUP which means it is pulled HIGH by an internal resistor. Thus, the tests are now for == LOW rather than == HIGH.

Also, instead of a delay for the timing of the metronome, I changed it to testing millis() and seeing if time is up. Otherwise you have to hold the switch down for the entire time that a cycle repeats.


Your question is a little confusing, so let me give you a couple pieces of information.

First things first - the VIn pin on the Arduino is strictly for power going to the Arduino board, you shouldn't be drawing power from this pin. The documentation in the link you sent is a little misleading on this - it's basically saying 9v is coming OUT of the PoE module, and going IN to the VIn on the Arduino itself. If you wanted to tap into this 9v power, you should connect to the PoE module VOut instead.

PoE by default can deliver 37-57 volts or 42-57 volts, depending on what type of PoE you're using (which 802.3 specification). Wikipedia has a good overview of this information.

That being said, the Arduino Ethernet board you're using can't handle this voltage by itself - unless these boards have changed, they require an additional PoE module, which is basically just a DC-to-DC buck converter that will convert the high PoE voltage down to 9v or 12v. At this point, the Arduino's built-in converter can consume that 9 or 12v and distribute it at 5v across the board.

Now, to your problem - you want to power a relay that requires 7-12v. You could theoretically connect the relay to the VOut of the PoE module, giving you 12v. However, if the relay draws too much power for too long, you will either get brownouts (and your Arduino will restart) or potentially damage the Arduino board. Unless the relay draws a lot of current or is being powered for extended periods, you should be fine. If you want to be more thorough, you could put a large capacitor between your PoE module and the relay.

You should NOT try to connect the relay directly to the PoE VOut, as the voltage will be far too high.


If you are using a microprocessor, specifically an Arduino, then what you need to do is send the signal from the 'switch' (as defined by Mark Smith) into a digital input port and then let the Arduino make the electronics pause before reversing.  From you post it sounds like (and I am probably wrong) you have put the switch in between the power source and the actuator.

(Diagram by Majenko)


Installing the Arduino bootloader would make it easier to upload you sketch from the Arduino IDE.
Installing the Arduino bootloader via DFU is probably the easiest method. Alternatively use ISP, but you'd need a programmer for that, or use a separate Arduino board with the ArduinoAsISP sketch running on it.


tldr; -lc means "link with the libc.a library"

The compiler takes your source code (*.c, *.ino) and produces "object" files ending in *.o.

The linker takes those compiled modules and links them all together to make the final executable, linking symbols in one file (such as variable references and function calls) with the definitions in the others (the actual variables and functions). But it also takes libraries - predefined collections of object files - and links those in as well, if necessary.

Libraries are files of the form lib*.a (a is for "archive"), and are distributed by software vendors as easy containers for their modules. The compiler/linker itself also uses them as the implementations for languages features such as printf() and digitalWrite(). The most fundamental library is libc.a - the library containing the standard C implementation.

When you want to get the linker to use a library, you give it the -l option, with the library name appended (not including the lib prefix and .a extension). In short, -lc means "link with the libc.a library".

But if your development machine has support for numerous processors, there will be a number of libc.a files on it - how does the linker know where to look? Another linker option is -L (note uppercase), which defines the directories to look in to find libraries. The linker will look through the directories in turn until it finds the referenced library.

If you attempt to link modules that have been compiled for different processors, you will get linker errors when it does a sanity check. The reason your fix worked is because it now uses the correct directories to find what it is looking for.


First you need to setup the second DHT sensor and a second file. Please replace the X by the number of the pin your second sensor is connected to after #define DHTPIN2

#define DHTPIN 8
#define DHTPIN2 X
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
File data_file, data_file2;

In setup() you need to also start the second dht sensor:

dht.begin(); //This command will start to receive the values from dht22
dht2.begin(); //This command will start to receive the values from dht22

In loop() you have to open the second data file in addition to the first one:

data_file = SD.open("data.txt", FILE_WRITE);
if (data_file) {
getData();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data.txt");
}
data_file2 = SD.open("data2.txt", FILE_WRITE);
if (data_file2) {
getData2();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data2.txt");
}

Although not the most efficient/elegant solution, this requires you to duplicate your void getData() function as void getData2() to work for the second sensor/file, by replacing dht by dht2 and data_file with data_file2.
This would do the logging on the two sensors in sequence.
If you want the logging in parallel you need to add the measurement and writing of the second sensor/file into the void getData() function.


Integer values of the Arduino have the MSB left and the LSB right. The shiftOut() function let's you choose, how the order should be timewise. If you provide LSBFIRST, the function will start the transmit with the LSB (on the right) and then go left to the MSB. Otherwise it will start with the MSB and then go right to the LSB. So this effects only the time order of the bits, in that they get transmitted.


Correct position for buttonState in my FSM

You should also introduce a button state to have the FSM working as a FSM

 bool buttonState = false;

in the loop you check for the press/release and change the state:

if (digitalRead(buttonPin) == LOW && buttonState == true) buttonState == false;
if (digitalRead(buttonPin) == HIGH && buttonState == false) buttonState == true;

inside your function you only go for buttonState eg

statusType noLightFunction() {
if (buttonState == false) {  // Button is NOT pressed

    return (yellowLight);

  } else {       // Button is pressed

    return (whiteLight);
  }
}

The button acts as a toogle switch as long as you keep it pressed (or released) nothing will change only the state changes caise an action to happen. I personally use "speaking" vars I still know years later so instead of
buttonState I use buttonIsPressed but thats flavour


Timezones are political constructs, same as summer/winter time switch rules.
You'd need a map to look up the country/region and its current local time zone.
Your commercial car satnav is probably/perhaps equipped with such map information.


Powering arduino and sensors and motor damaging 16x2 LCD?

In some instances, it is a known issue that certain LCD's pull more power from the arduino than is sustainable depending on the power source.

A few suggestions:

Put something like a 100-200 ohm resister in the 5V to the LCD and connect just that and GND, then measure the voltage drop across said resister.  That will give you the current with ohms law, if its much more than 4mA its a faulty LCD or a fault in your wiring.

You should also check the pins for continuity errors, or shorts.

Another idea, is to make sure the voltage, and amperage coming from the 5vdc step down you are using is adequate for the task at hand.

And finally, you'll need to calculate the complete pull on your power source. i.e. you'll need to know how much load your bigeasy driver pulling from the 12vdc power supply, as well as how much your 5v stepdown is using. if they are exceeding the output of the PSU, you can run into issues.

I ran into a similar issue with my own project, using an arduino Uno with grbl + 3x easydriver motor controllers, & mega 2560 + lcdkeypad shield. Powering the easydrivers with 12vdc & using a voltage stepdown module also gave me issues, as it didn't provide enough current for the stepper motor drivers and the LCD + mega + uno from the 5vdc. I was overloading the power supply, and the 5v wasn't producing the correct power requirements.

I bought a better power supply that had 24, 12, 7, and 5v on it, and haven't had an issue since.


Trying to send .wav files between NodeMCU

You could just program the NodeMCUs and skip the Megas; they have sufficient pins to drive an SD card. There's so much wrong with your code: opening and closing the same file so many times and then having to seek for every chunk because of the previous nastiness, writing and reading bytes singly instead of just passing in a buffer, among others. I also hope you know that you didn't send only the WAV data to the transmitting NodeMCU; there's a bunch of stuff (CRLF, file size, etc) before that.

Your particular problem's most likely the fact that your Mega "server" is just sending chunks continuously to the NodeMCU, never minding if the latter is reading them quickly enough that its serial buffer doesn't overflow, especially considering you're sending data over the network between chunks. You should also note that UDP isn't exactly the most reliable protocol; it's connection-less and so packets will be lost. It's generally used if packet loss isn't a big deal (in your case, it is) or if upper layers implement error control.

What you need to implement is a way for each party to confirm that they've received the next chunk before the their sender transmits the next. The Mega needs to wait for a 'go-ahead' from the NodeMCU before sending the next chunk; for instance, the NodeMCU can reply each chunk with the number of bytes it actually read, so you can know if you should reduce your chunk size to not overwhelm the NodeMCU buffer.

The packets sent over the network also need to be tagged with a sequence number (because of aforementioned error control). The NodeMCU at the receiver needs to acknowledge the packet it received each packet, perhaps by sending that packet's number to the transmitting NodeMCU. This will help ensure all packets are received and in order. Or you could just use TCP which already implements these and more.


How can I play music using a speaker and Micro SD card Module?

This Arduino project is one of the most simple and fun projects you
  can build with Arduino in 10-15 minutes. The result of this make will
  be an Arduino Audio Player which will play “.wav” files. It consist of
  a speaker, a simple transistor acting as an amplifier and a micro-SD
  card adapter with a micro-SD in it through which the .wav files are
  loaded and played.

https://diyhacking.com/arduino-audio-player/


DC Motor Speed Measurement using Rotary Encoder

Just a couple of remarks:

start should be volatile, but you can remove it and simply check
that time1 != 0.
there is no point in calling millis() twice inside the interrupt
service routine:

void speed(void) {
  unsigned long now = millis();
  time1 = now - time_11;
  time_11 = now;
}


How to get Arduino to talk to two seperate motors wirelessly?

You'll probably need 3 "controllers", of which the one in the middle of the room might need to be a full-featured Arduino. Depending on the the needed libraries of your bluetooth receivers at the remote servos, it seems likely that you could use ATTinys in place of more feature-filled Arduino, but you would still have to think of the ATTinys as Arduinos or at least the glue controller to translate commands from Bluetooth to servo signals (PWM).

You could provide us with more details, such what particular bluetooth modules or transceivers you plan to use; some might provide an asynchronous serial interface, others might present an I2C or SPI interface, and given the small flash and RAM size in the ATTiny line, you would need to evaluate the code and associated libraries needed to operate it on such a processor.

The answer to your question is, "Maybe", given the small amount of detail you have provided.


You should write ";" end of each lines.
analogWrite(11, 64);
delay(1000);
analogWrite(11, 0);
delay(1000);


Help me for interfacing Arduino with AMTP32M VOICE IC

Finely i try the below code for serial mode. it's worked perfectly...
type def union
  {
unsigned char BYTE;
struct
{
    unsigned        BIT0:1;
    unsigned        BIT1:1;
    unsigned        BIT2:1;
    unsigned        BIT3:1;
    unsigned        BIT4:1;
    unsigned        BIT5:1;
    unsigned        BIT6:1;
    unsigned        BIT7:1;
};
}ByteToBit;

void Play(unsigned char Val)
{
  ByteToBit SectionNo;

  SectionNo.BYTE = Val;

CLOCK = 1;
DATA  = 0;
CLOCK = 0;

DATA  = SectionNo.BIT0;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT1;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT2;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT3;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT4;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT5;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT6;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT7;
CLOCK = 1;
CLOCK = 0;

DATA  = 0;
CLOCK = 1;
DATA  = 1;

return ;
}

 void main(void)
 {
    unsigned char SectionNo;

CLOCK = 1;
DATA  = 1;

SectionNo = 0x00;
while(1)
{
    Play(SectionNo);
    Delay_1mS();        // Wait for BUSY set up time...
    while(BUSY);        // Voice playing...
    SectionNo++;
}

return ;
}


LED not blinking when using a transistor

Without a common reference (ground) between the Arduino power supply and the external power-supply, again, you have a floating base, as you can't know what the Arduino's 5v output (or local ground) looks like to the external circuit.

Connect the two grounds. That should correct the LED brightness with respect to the Arduino output pin level. Then, if you need the external circuit to behave in a specific way when the base is disconnected from the Arduino, add a 10K resistor from the transistor base to the external +5 if you want the LED to be on, or to ground, if you want it to be off. Again, I'm guessing at both the pullup/pulldown value (but 10K should be in the ballpark) and the switching sense ('On' or 'Off' for base at +5), but from the expectation state in your point (2.), I think I have it right.

Update: But see @EdgarBonet's comment to me about BJT's. I'd still avoid leaving an input floating as a matter of practice, but it seems not relevant in your circuit.


How can you reduce the clock frequency of an Arduino Mega?

You can set the clock prescaler for that:

void setup() {
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();
}

This is explained in section 10.12 and 10.13 of the
ATmega2560
datasheet.

Of course, changing the clock frequency will mess with the time-related
function (millis(), delay() and co.) and the baud rate of the serial
port.

Edit: Here is a small program to demonstrate the slowing of the
clock:

//#define SLOW_CLOCK

void setup()
{
#ifdef SLOW_CLOCK
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();
#endif
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    digitalWrite(LED_BUILTIN, HIGH);
    delay(500);
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
}

This makes the LED flash at 1 Hz. If you uncomment the line
#define SLOW_CLOCK, it instead flashes at 0.5 Hz.


There is a mismatch in the code.
The Arduino loop function assumes that readPMSdata needs to be called just once for valid data but the function readPMSdata itself assumes that it will be called over and over again until a enough bytes are received and are valid.

The solution is to let the Arduino loop call readPMSdata over and over again, until it has valid data. It returns true when it has valid data, so that can be used in a if statement.
This might cause troubles with the rest of the code in the loop. The delay(250); may no longer be used and I don't know the best place to go into sleep mode. Therefor I removed the powerdown.

void loop() {
  if( readPMSdata(&Serial))        // call it many times to collect data
  {
    // there is valid data from the sensor
    DateTime now = rtc.now();
    test = SD.open("test.txt", FILE_WRITE);

    tString = String(now.hour()) + ":" + String(now.minute()) + ":" + String(now.second()) + " - ";

    sString = String(data.pm10_standard) + "," + String(data.pm25_standard) + "," + String(data.pm100_standard);

    if (test) {
      test.print(tString);
      test.println(sString);
      test.close();
  }
}


Arduino - Turn on LED when Potentionmeter is used

When the function blinkLED() is triggered, there is this delay,.. does the whole loop()-function wait, too?

Yes, when you call a function it doesn't return until it is done, and delay is blocking.

You can rewrite a bit like this:

int ledPin = 13;

int pin[] =             {A0, A1, A2, A3};
int cc[] =              {20, 21, 22, 23};
int potiValues[] =      {0,  0, 0, 0};
int potiValuesTmp[] =   {0, 0, 0, 0};

void setup() {
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
}

unsigned long lastFlash;
int flashesToGo;
const unsigned long flashTime = 50; // ms

void loop() {
    // READ EVERY PIN
    for(int i=0; i<=3; i++){
        potiValues[i] = map(analogRead(pin[i]), 0, 1023, 0, 127);
        if(abs (potiValues[i] - potiValuesTmp[i]) > 3) {
            // NEW VALUE RECEIVED - MAKE OUTPUT
            Serial.print("Pin ");
            Serial.print(pin[i]);
            Serial.print(" - ");
            Serial.print("Value: ");
            Serial.println(potiValues[i]);
            flashesToGo = 10;
            potiValuesTmp[i] = potiValues[i];
        }
    }

   // flash LED if required

   if (flashesToGo > 0)   // need more flashing?
      {
      // is it time to toggle the LED?
      if (millis () - lastFlash >= flashTime)
        {
        // toggle LED
        if (digitalRead (ledPin) == HIGH)
          digitalWrite (ledPin, LOW);
        else
          digitalWrite (ledPin, HIGH);
        // remember when we did it
        lastFlash = millis ();
        // count down
        flashesToGo--;  // one less flash
        } // end of time for another flash
      }
   else
     digitalWrite (ledPin, LOW);  // ensure LED off

}

What this does is add to the main loop a few lines of code that toggle the LED after a certain time is up (50 ms currently). It counts down the number of toggles from a desired starting point (eg. 10) until they are all done. This means that the LED will flash without blocking.

Each time you detect a new analog reading the number of flashes is reset back to the maximum.

I modified your test for if the analog reading changed to be:

if(abs (potiValues[i] - potiValuesTmp[i]) > 3)

I found that without that, the LED flashed continually because the readings were slightly different each time (eg. 51, 52, 51, 50) which would probably just be error in the ADC reading.

With that change, it doesn't count as "changed" unless the reading changes by 3 (you could make it more, or less than that).

  I want the LED to blink up just once - when I turn one of the potentiometers

In that case change:

flashesToGo = 10;

to:

flashesToGo = 2;

That is one HIGH and one LOW (one flash in total).


How to calculate the needed voltage and current to supply for Arduino

Voltage is simple - a device has a requirement and that is what you have to provide. In the case of the servos that is a range of voltages that it can use. So 5V is a good voltage.  The Arduino can take 5V if you feed it in to the 5V pin or the USB port, or 7-12V if you feed it in to the barrel jack.

The current you cannot calculate. You haven't provided enough information. The calculation, when you have the information, is quite simple: for all the devices on the same power supply add the currents requirements together. The supply has to be able to provide at least that amount of current.


Arduino IDE 1.8.13 won't launch properly

Note: Below, technician 274 (the original poster) commented:

It ended up working, after following alpinelinux wiki and installing
the IDE using flatpak.

Part of the problem is how confusing the message is.
No such file or directory is not actually referring to the java file.  It's referring to the ld-linux.so interpreter specified in the elf file.
If you run the file command on the java executable, you'll see output that looks like:
./java/bin/java: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.9, not stripped

If you look for /lib/ld-linux.so.2, you're going to find that you don't have one, and that's the file it's complaining about.
Alpine Linux apparently uses Musl and the java binaries were compiled for glibc, which is normal for desktop Linux.  On a typical desktop Linux system, that the java that ships with the Arduino IDE was compiled for, all kinds of executables make use of ld-linux.so.2.  On your Alpine system, you'll find they're referring to /lib/ld-musl-i386.so.1 instead.  From this vantage point, it's more of a Linux problem than an Arduino one, but I thought it might as well have something of an answer to point people toward relevant looking resources:

https://wiki.alpinelinux.org/wiki/Running_glibc_programs
https://github.com/sgerrand/alpine-pkg-glibc

You may find it's easier to replace the java interpreter, but that won't be enough, because the Avrdude and GCC binaries will also expect ld-linux.so.2.
In the end, it may be easier to just not use Alpine Linux.


The only SoftwareSerial you a declaring is SoftwareSerial mySerial(10, 11); // RX, TX

(And you you didn't use it afterwards).

If the hardware serials Serial1, Serial2 or Serial3 are available
(and already declared in the arduino.h header depends on the board you are using.


They are actually named in a different manner.

Your camera module has i2c interface.

SIOC is nothing but Serial Input Clock , same as SCL - i2c clock

Similarly , SDA and SIOD are the same - i2c data

HREF and HS are the same too - Hsync signal

MCLK and XCLK are the same too - system clock

Here is a useful link:

https://www.google.co.in/amp/www.instructables.com/id/OV7670-Arduino-Camera-Sensor-Module-Framecapture-T/%3famp_page=true

Cheers !


ATTiny85 Digispark clones failing USB handshake - how to program them?

I had problems too - SHORT: all about USB-hub or PC's root-hub and extension cables +Luck.

My ebay items were going under the name "Digispark Kickstarter ATTINY85 Arduino Micro USB Development Board" and naturally it came with no Digispark-(c)-right infringing markings from China. I kept my fingers crossed that my items would at least be AVRisp-programable..

So in high hopes I plugged in my China import into my trusty USB HUB2.0(which I always use at least as a current limiter) – after testing it first on a powerbank (>5secs blinky-blink)  .. checked for enumeration (which it did-but no driver yet) .. installed the DPinst[64].exe drivers.. and then kept getting messages like >>device failed to enumerate<<, etc. - the list of my failures:

determined directly plugged into a PC's USB root-hub rigged/minimalistic usb devices do not enumerate at all (all 0s)
with a certain USBAmale-to-USBAfemale extension cable with plastic-encasing(female side) the USBA device’s was not allowed to go "in" probably just for some millimeters to short.. the Data-lamella do not connect correct – just power's okay (blinky-blink) .. but no Windows device-recognition .. No-No!
AND reminding the FTDI black-listing dilemma I used PCs without out the drivers still – using the good old “USBview.exe” program to check on the enumeration (on all my available device the same .. previously plugged into my driver-enable PC or just into an “out of the fab”-one

idVendor:           0x16D0
idProduct:          0x0753
bcdDevice:          0x010B

so no mis-configuration of the bootloader through a >possibly mallign< Digispark clone dis-configurator (as I was thinking the FTDI schemes .. of course FTDI only did it to protect their name X-) – to stop getting accused for faulty devices coming from cheap chinese fake or clone-producers)
* EVEN tried to deinstall the Drivers with DPinst[64].exe /D .. which gave me .. Yes .. yet again “Drivers all installed properly!”..

.. and IN THE END .. I just went back to my old, initial “USB HUB-behind root-hub” configuration .. and Abra-ca-Zang .. the device just enumerated and registered as “Digispark Bootloader” (windows device manager under libusb-win32 Usb Devices)

and all went okay - reprogramming with the Arduino IDE - NO FUZZ!
.. The !very same! config I was using on my “first testings” (minus some fair time and headaches of debugging)

So my advice .. always do a Basic-Test on a USB Powerbank, USE an USB-Hub, check your cables - use ones you trusted before! – try as many options as you (may) have .. and use the tools at your hand .. down to PC-progs or an logic-analyzer or an Beagle USB / protocol analyer to check where the problem may be.. trace back your tracks and even retry..

There may be a suprise for you at the end of the rainbow!


How can I indicate that I am using ATmega2560 so that Arduino libraries understand it?

There are two things that have to be considered here.

One is telling the code what board you are using, so it can compile in the right optional parts, and the other is getting the right pin mappings.

The first can be covered simply with a compilation flag:

-DARDUINO_MEGA2560

That defines the macro ARDUINO_MEGA2560 which is used in some places to know which board you are using.

Second is the pin mappings.  These are stored in the file pins_arduino.h and each board variant has its own copy.  You need to ensure that this file (and be sure to get the right one) is included in your code in the right places to ensure that the pins can be mapped right.  If you are including the whole Arduino core (which it sounds like you must be in order for things to even have a hope of working) then you just need to ensure that you have the compiler set up to include the right copy of the pins_arduino.h file.

That means making sure you have an include path in your compile command line which points to where the pins_arduino.h file is before anything else Arduino core related.

-IC:\Path\to\arduino\mega2560\variant

or

-I/path/to/arduino/mega2560/variant


How do I connect an accelerometer (GY-521) to a SparkFun Thing Dev (ESP8266)?

A4 and A5 on the Arduino double as the I2C pins SDA and SCL.  You are communicating with I2C, not analog.

The ESP8266 doesn't have I2C in hardware, but there is a software-based I2C implementation which can work on any pins.  The pinout you show has I2C labeled on pins 2 and 14. While you can use those you could use any two pins of your choosing.

Note that I2C on the ESP8266 has a slightly different begin function:

Wire.begin(2, 14);

That is where the pins you want to use are assigned - in this case, pin 2 for SDA and pin 14 for SCL.


Use the TCS3200 color sensor without the included LEDs

The photodiodes in the device itself have filters so it should theoretically be possible to use it without auxiliary light sources. Note, however, that the green and blue sensors have two sensitivity peaks and so using it outdoors without an infrared filter is not advised.


Do all arducam need the "Arducam-F Shield"?

You have three requirements:

Good quality (colour)
High resolution
Fast operation

Those three requirements together mean you cannot use a normal Arduino.

The Arduino has nether the memory nor processing power to directly communicate with a camera module.
The ones you can communicate with have internal buffer memory and use a slow UART interface to transfer a frame. That is not fast.
The Arduino cannot deal with a large picture regardless of speed. All you can do is pass the image through to somewhere else for processing. Slowly.

So you can either have very low resolution or slow speed.

So use a Raspberry Pi or something similar which is more capable of using a camera (indeed, the Pi has a dedicated camera connection).


What is the relationship between the gain on the receiver and the delay time

I am looking at the read and recv methods in the software serial library and I don't see any checks for start bits, so what's the point of writing one in the write method?

The start bit is absolutely essential in serial comms. In the graphic below, the start bit is marked "B" - which distinguishes it from "idle" data which is "A". Once received, the receiver then waits 1.5 bit times and starts clocking in the remaining bits. (Starting at "C" in the diagram, and then moving on for a total of 8 bits).

Without a start bit, how would the receiver know when the byte started? Imagine you wanted to send 0xFF (all 1 bits). Without a start bit that would be indistinguishable from the idle state.

In the graphic, "D" is the stop bit. Why have a stop bit? We need one (which is a "1" bit), so that we can detect the transition from the stop bit in the previous byte (a "1") and the start bit in the next byte (a "0").

In the graphic, "E" is the start bit for the next byte.

  I don't see any checks for start bits ...

SoftwareSerial has a pin-change interrupt set up to detect that the receiving pin has changed state (to a zero usually). That is your start bit. You don't see it in the loop, because it has already arrived, otherwise you wouldn't be in the receive loop in the first place.


Add Serial.begin(115200); in setup() and use Serial.println() or Serial.print() to print to Serial.

In Arduino IDE open Serial Monitor and set baud rate to 115200.

EDIT: The question turned out to be about Serial Plotter. Maximilian Gerhardt answered in a comment :

  If you want multiple data streams (graphs) you need to seperate them
  by a comma: Serial.println( String(digitalRead(outputA)) + "," +
  String(digitalRead(outputB)));


OP didn't really specify the actual requirements other than detecting movement and wanting to use PIR while in motion.

PIR (Passive Infrared) implies looking for warm bodies.  In general, PIR motion sensors look for the presence of thermal radiation that moves between the individual parts of the sensor.  On TV it is shown that you can fool PIR detectors by carrying a large cold panel between you and the detector. ;-)

They also detect reflected thermal radiation that is moving.   It does not need to be a direct view.  So moving the sensor around outside would pick up a lot of reflected IR sunlight changes.  And certainly incandescent lights would do the same since about 80% of their emitted energy is IR.

The way they are designed, (with lenses like a bee's eye) they are more likely to detect your own arms swinging back as you walk and generate false alarms that way.  So you would need some kind of mounting arrangement that only allowed it to "see" directly behind.  And even then only in a dark room.

PIR sounds like a lot of trouble for an application like this.  (As in, probably not suitable)

Here is a decent instructable that explains how they work:  http://www.instructables.com/id/PIR-Motion-Sensor-Tutorial/

If PIR is not a be-all requirement, here is an alternative to be considered, even though it would require some work to get it right:

Radar

Here is a nice, inexpensive radar unit that will arrive eventually on the slow boat, and the price is right.  It could work well in motion if you program it to detect changes that occur at speeds faster than your own motion.  And you would want to program a pulse gate it so it only senses objects at more than a certain distance behind you.

Anyway, in the spirit of hacking, I offer this idea:

LFS-DC04 2.7GHz Microwave Radar Module DC 5V

http://www.ebay.com/itm/262662221979

It is small enough to wear.  But it is slow, so I wouldn't recommend using it to detect intruders with violent intent.  I believe it would be good mounted on a bicycle-pulled trailer or something like that, to make sure you know if something is coming up on you too fast.

Product Introduction:

1.Model:LFS-DC04
2.Frequency:2.7GHz
3.Size:40*22mm
4.Input Voltage:DC 5V
5.Output Type:level signal output
6.Connection Method:VCC,GND connect with positive negative input, OUT,GND signal connect with output
7.Installation Height:1-3.5m
8.Sensing Ditance:5-8m
9.Delay Time:30s(quick testing mode is 4s)
10.Sensing Angle:360 degree

It is low enough power that it shouldn't fry your kidneys.  Probably very similar to sitting next to a high-power WiFi router all the time, or like having a cellphone in your pocket with WiFi and 4G turned on all the time.


Sending Analog Input Data from Serial Port to Google Sheets

Use Google's time stamp format: MM-dd-yyyy hh:mm:ss, see Google Sheets API v4 - Date and Number Formats.
There are a few ways. For example:

A PC connected to the Internet with software on it that listens for data form the Arduino. It would get the Arduino data over serial then send that via the Internet to Google.
A Wi-Fi, or network, shield connected to the Internet. You could then use Google's API to send the data directly from the Arduino, see Google Sheets API v4 - Writing.
Or - as you mentioned - physically get the SD card and manually upload.


Timer2 Compare Interrupt not working as expected

So you're right that CTC is acting weird. I've noticed this few years ago too on different board, but I've always suspected asychronous mode (I've added 32k RTC Xtal on Arduino Mega).

However Fast PWM mode with OCR2A as a TOP value seems to be working:

class TimerTwo
{
  public: //methods
    void initialize();
    void attachInterrupt(void (*isr)());
    void detachInterrupt();
    void (*isrCallback)() = nullptr;
};

TimerTwo Timer2;

ISR(TIMER2_COMPA_vect) { //ISR on Compare Match A
  Timer2.isrCallback();
}

void TimerTwo::initialize() {
  cli();

  OCR2A = 124;                        // = (16*10^6) / (2000*64) - 1 (must be <256)
  TCCR2A = _BV(WGM21) | _BV(WGM20);   // turn on fast PWM mode with top in OCR2A
  TCCR2B = _BV(WGM22) | _BV(CS22);    // Set CS22 bit for 64 prescaler
  TCNT2  = 0;                         // initialize counter value to 0

  sei();
}

void TimerTwo::attachInterrupt(void (*isr)()) {
  isrCallback = isr;
  TIMSK2 |= _BV(OCIE2A);
}

void TimerTwo::detachInterrupt() {
  TIMSK2 &= ~_BV(OCIE2A);
  isrCallback = nullptr;
}

volatile uint32_t counter = 0;
void isrHandler() {
  ++counter;
}

void setup() {
  Serial.begin(115200);
  Timer2.initialize();
  Timer2.attachInterrupt(&isrHandler);
}

void loop() {
    static uint32_t counter_old = 0;
    Serial.println(counter - counter_old);
    counter_old = counter;
    delay(500);
}

EDIT: Ok, so after some digging on this issue I've found that setting CTC mode might cause OCR2A corruption (I guess?) . It seems to be working if you reorder the settings to:

  TCCR2B = 0;          // stop the timer and reset WGM22
  TCCR2A = _BV(WGM21); // turn on CTC mode with top in OCR2A
  OCR2A  = 124;        // = (16*10^6) / (2000*64) - 1 (must be <256)
  TCNT2  = 0;          //initialize counter value to 0
  TCCR2B = _BV(CS22);  // Set CS22 bit for 64 prescaler (for starting the timer)


Why my Galileo isn't getting a IP address?

I really don't know why, but after I initialized the Ethernet interfaceifconfig eth0 up it started working properly. I don't know why this time this command was needed and the others didn't.


esp8266 cant make more than one request at time

https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#bearssl-client-secure-and-server-secure

  Secure clients and servers require siginificant amounts of additional
  memory and processing to enable their cryptographic algorithms. In
  general, only a single secure client or server connection at a time
  can be processed given the little RAM present on the ESP8266

you have two BearSSL::WiFiClientSecure instances at time. it is simple to change your code to first free the first SSL client object.


How to separate a specific frequency signal from a summation of a few signals?

What exactly are you trying to do?  If you want to measure THD from an external signal, an Arduino is probably not the best choice.  It only has 10-bit ADCs and they are DC-coupled. You can build a simple circuit (https://www.daqarta.com/dw_rrll.htm) to shift an AC-coupled input to DC for the Arduino, but you will still have only 10-bit resolution.  I haven't looked deep enough into the library that chrisl mentions to see how big an FFT it can perform in the limited RAM of an Arduino, but I suspect the spectral resolution would be so poor as to be unhelpful for real-world THD measurements.
The way you describe the signal makes me think that this is an academic exercise, not a real-world problem.  If so, you don't need an Arduino or any other hardware, just run the FFT on your main computer.   If you do need to make real-world measurements, an ordinary sound card on your computer is a better way to go.  See https://www.daqarta.com/dw_0d0t.htm for an example.  The sound card approach has the added advantage that it can generate a low-distortion test signal to drive the device whose distortion you are trying to measure.  That allows a "trick" (called "Spectral Line Lock" in the example) to get even better resolution, by making the test signal synchronous with the sample rate so you don't need window functions.
If you really want to measure THD with an Arduino, consider an approach used in what used to be called a "wave analyzer".  The block diagram is shown here:
https://www.daqarta.com/dw_0h0p.htm.  This is essentially a one-spectral-line analyzer, which actually can be more selective than an FFT.  You basically multiply the input signal by the sine and cosine of the reference frequency (the fundamental) and then rectify and filter the results, and combine RMS-wise.  That gives you the fundamental value (or any individual harmonic you tune the reference to), so to get THD you divide by the RMS of the overall input signal.


Is there any way I can connect the RAM of a computer to Arduino?

No, you can't connect your normal desktop computer memory to your Arduino. For a number of reasons:

Computer memory (at least for the past 20 years) is DDR SDRAM. That's Synchronous Dynamic RAM. It requires very strict timing and synchronous (clock based) data transfers with clocks measured in the hundreds of MHz - something the Arduino cannot do.
You need lots and lots of I/O pins to interface with SDRAM. I mean, just look at all those pins - how would you connect all those up to a little Arduino?
Being DRAM you need to use quite a complex process to keep the data refreshed and stop the capacitance of each cell from draining away. Yes, that side of things is do-able, but not child's play.

The only way you will be able to interface DDR SDRAM with an Arduino is through some intermediate interfacing system that can do all the above for you. Your best candidate is to design an SPI to DDR conversion chip using an FPGA and Verilog or VHDL. That way you can communicate with the FPGA using SPI (or you could choose I2C if you like, or a simple 8-bit parallel protocol) and the FPGA then does all the grunt work that the Arduino isn't capable of.

However, while you're at it, you may as well put a CPU core in the FPGA (e.g., NIOS II or something) and do away with the Arduino altogether...


Arduino Micro Cannot get Interrupt 6 work on PIN 7

I've used following code and loopback from pin 8 to pin 7:

// loopback:  pin 8 -> pin 7

void setup() {
  pinMode(7, INPUT_PULLUP);
  pinMode(8, OUTPUT);
  pinMode(LED_BUILTIN_TX, OUTPUT); // to see pin 8 logic level on TX led
  pinMode(LED_BUILTIN, OUTPUT); // toggled by ISR

  EICRB |= _BV(ISC60);  // Triggers on edge
  EIMSK |= _BV(INT6);   // activates the interrupt
}

ISR(INT6_vect) {
  PINC = _BV(PC7);  // toggle led 13 (@ PC7)
}

void loop() {
  digitalWrite(8, HIGH);
  digitalWrite(LED_BUILTIN_TX, HIGH);

  delay(500);
  digitalWrite(8, LOW);
  digitalWrite(LED_BUILTIN_TX, LOW);
  delay(500);

}

And it works perfectly. Only problem I can imagine is to figure out correctly which pin is really 7 as label is on the right side of pin (not under nor left).


LED doesn't register as LOW after a switch has cut all power to it

The diagram is open to several different interpretations, depending on what's inside the four-terminal switch.  On many such SPST switches, two adjacent terminals are connected to each other inside it, and the other two likewise.  Which are which in the diagram isn't indicated.

That aside, what is clear from the diagram is that pin 2 is connected by wires to +5V, and will always read in as high.

Edit 1:
The schematic [posted later] is unclear.  It should be arranged so that solid lines represent wires or pins, with solid lines between things that are connected.  Place items in the drawing to reduce unnecessary and confusing crossing lines.  For example, supposing that the dashed line from pin 2 of R1 represents a wire between pin 2 of R1 and pin 2 of LED1, it is unclear whether the wire bends around the top right pin of S1 (can't read number) or connects with that pin on its way to LED1.  For another example, nothing is shown connecting to pin 1 of R1, and only one long dashed line connects the R1/S1/LED1 group to the Uno.


Does analogueRead() change the way a number is represented etc?

There is no change in representation. analogRead() reads two I/O
registers, ADCL and ADCH, which on the Uno are memory-mapped to
addresses 0x0078 and 0x0079 respectively. It returns the result in a
register pair, r24 and r25, which per the AVR C calling
conventions is the
standard way of returning a 16-bit number. Thus, r24 holds the value
read from ADCL, and r25 the value read from ADCH. That's it. No
conversion whatsoever.

There is a change in interpretation... of sorts. The function is
declared as returning an int, which on the AVR is a 16-bit signed
integer, whereas it could be argued that the I/O registers contain an
unsigned number. However, since the sign bit will always be zero, the
signed/unsigned distinction is moot: either way the result will be
interpreted as a number between 0 and 1023.

Edit: As a clarification: the ADC register (which is another
name for the ADCL/ADCH register pair) is a 16-bit I/O register. At
the end of a conversion, it holds the 10-bit result right-adjusted into
this 16-bit space, zero-padded on the left, as follows:

-------- ADCH --------- --------- ADCL --------
0  0  0  0  0  0  r9 r8 r7 r6 r5 r4 r3 r2 r1 r0
----------------- ADC (16 bits) ---------------

where the bits r9..r0 represent the 10-bit conversion result. Since the
MSB is zero, it is irrelevant whether you interpret it as a sign bit or
as a regular unsigned bit.

Just for completeness, it could be noted that it is possible (though not
through the Arduino core library) to configure the ADC to left-adjust
the result, as follows:

-------- ADCH --------- --------- ADCL --------
r9 r8 r7 r6 r5 r4 r3 r2 r1 r0 0  0  0  0  0  0
----------------- ADC (16 bits) ---------------

In this case, the MSB could be one, at it would obviously be incorrect
to interpret it as a sign bit.

As a side note, the avr-libc defines ADC as
(*(volatile uint16_t *)(0x78)), which is unsigned. And it makes sense
considering that, unlike the users of Arduino core, the users of
avr-libc are supposed to know they have the choice to get a
left-adjusted result.


The fastest means of communicating with the Arduino is SPI. Ethernet shields use that (as do SD cards). It's quite fast, but it has limits. The fastest the SPI clock can go is the CPU (MCU) clock rate divided by 2 (per bit), that is one byte every 16 CPU clock cycles. There is also an overhead of a couple of clock cycles between bytes, so you can reckon on 888,888 bytes absolute maximum (ie. about 868 kHz) on an Arduino running at 16 MHz.

However that's just throwing the data away. It needs to be stored somewhere, compared to something, acted upon. That all takes clock cycles.

That is for the 16 MHz Arduinos. The Teensy 3.1 apparently runs at 72 MHz which is somewhat faster. I haven't timed SPI on that, presumably you can get a faster transmission rate, but I suspect that the ARM processors also take more instructions to do the same thing, so the 72 MHz might not be quite as fast as it looks.

Then you have the issue of how fast you can get data in and out of the Ethernet card, and how fast you can do whatever-it-is you want to do with it, in the processor.


How to filter or eliminate earths magnetic field readings around 3D Magnetic sensor?

Earth magnetic field is pretty constant. In your measurements it will show up as an offset that you could subtract, but of course it will change if the sensor rotates.

Whatever measurement noise you see certainly doesnt' come from Earth. Either your setup is close to a local source of magnetic radiation (inductors, wires with high alternating current), or your sensor picks up noise from its power supply. Put your sensor away from high currents, power it with batteries and see how much noise you'll get in that case.


That water level sensor uses bare metal which is in contact with the water. The PH sensors are sensitive for that kind of voltage in the water, even if it would be 0V.

There are isolated PH sensor amplifier modules. On forums are often discussions whether to ground an aquarium or not for a PH sensor. With a isolated PH sensor, you avoid most of those problems.

There are also non-contact water level sensors. For example capacitive sensor or even sensors that can be attached on the outside. Some sensors use the water pressure, but I don't know if this one is isolated: https://www.sparkfun.com/products/10221


sleep() is something different. You are probably want to use delay(1000) instead.

sleep() comes from libsam and is not very well documented for use within the Arduino environment. There is probably a conflicting timer or interrupt between sleep() and the Audio.h library. So sticking with delay() is probably your best option.


I have five pushbuttons that refer to a specific pin number. I need an efficient code to set the variable for the pin with state 1. What can I use?

There are 5 push buttons each which correspond to a certain pin let us use 1 to 5 for an example. I want to set a variable, ActiveButton which will be set equal to the the only pin in the one state.

Here is a short snippet of what I think, that you want. This is quite a long shot, since your question is not clear enough.
int ActiveButton = -1; // Initialize ActiveButton with -1 (no button is active)
int button_pins[] = {1, 2, 3, 4, 5}; //Array with pin numbers of the buttons

void loop(){
    for(int i=0;i < sizeof(button_pins)/sizeof(button_pins[0]); i++){
        if(digitalRead(button_pins[i])){ //if the i-th button was pressed
            ActiveButton = button_pins[i]; // assign i-th button pin number to variable
            break; // Break, since we have found our pressed button, ignore all following pins
        }
    }
}

This will assign the pin number of the pressed button to the variable. The condition in the for loop
sizeof(button_pins)/sizeof(button_pins[0])

will make the code loop over all elements of the button_pins array. sizeof(button_pins) returns the number of bytes in the button_pins array. Then we divide through the number of bytes in the first element to get the number of elements in the array.


Arduino tone frequency isn't always precise

As far as I know, tone() implements pin toggling in software (using timer interrupt), so it's possible that the frequency is lower when there's a lot of activity and higher when the CPU is mostly idle.

Try calling your beeping code alone inside an otherwise empty sketch and with no external hardware, and check out whether the sound is higher than you expect.


What does the 'arduino' avrdude programmer do?

Yes, the -c option specifies the methods of interacting with the device's loader.

The source code of the arduino programmer is http://svn.savannah.nongnu.org/viewvc/trunk/avrdude/arduino.c?root=avrdude&view=markup

Specifically, '-c arduino' chooses the client side code tailored to the bootloader in the Arduino Uno.  Looking at the code in the above link, it tweaks the DTR and RTS lines to get the Ardunino into an stk500 compatible mode, and then invokes the stk500 protocol.


Re  “Am I doing something wrong?”, yes :)

The sizeof(allOutputPins) expression returns the size of allOutputPins[] in terms of bytes, so is 24 because the array contains 12 two-byte integers.  The loop's last 12 pinMode() calls will be garbage.

Among other ways of fixing the problem, you could change the expression to sizeof(allOutputPins)/sizeof(int) [which has the same value, 12, as (sizeof allOutputPins)/sizeof(int); eg see the syntax entries for the sizeof operator at cppreference.com] or you could change the base type of the array to byte or uint8_t.


Pause running program using a pushbutton

The problem in this code is that the for loops are blocking with delay for 1.2 seconds and only once that ends does the code come back around to check the button.  You should instead use the loop function itself to handle the looping and use the Blink Without Delay method of timing to handle the timing.  In that way the loop function is never blocked from running and can run thousands of times per second, never missing any presses of the buttons.  And also in this way you would be able to pause the program at any point, not just once every 1.2 seconds.


Electric meter with Arduino and RS485 module

Using readBytes would do the same as your C# code. readBytes is blocking. It will wait for every byte until timeout. Default timeout is 1 second. If the count of bytes is smaller then the size of the buffer, it will wait a second after the last byte received. You can set the timeout with RS485Serial.setTimeout(500); (500 milliseconds for example).

void loop()
{
  digitalWrite(SSerialTxControl, RS485Transmit);
  RS485Serial.write(request, sizeof(request));
  RS485Serial.flush();
  digitalWrite(SSerialTxControl, RS485Receive);
  int recvLen = RS485Serial.readBytes(buffer, sizeof(buffer));
  for (int i = 0; i < recvLen; i++) {
    Serial.println(buffer[i], HEX);
  }
}


Actuating a Hobbywing Skywalker 50A-UBEC ESC with Arduino CNC Shield

After a lot of research, I found out that the variable spindle speed output is a PWM signal, while the ESC needs a PPM signal to be controlled. Although that, it's a specific PPM signal that actually looks like PWM, so it can be used.

The problem is that, instead of being controlled by the duty cycle, what actually controls it is the amount of time that each pulse stays on high, which depends on the period, which is the inverse of the frequency. Long story short, the frequency is too high.

I managed to change the frequency used by grbl and found one that works. I don't know if this frequency allows the whole throttle range to be controlled but, for my application that doesn't require a very strict RPM, it was enough. Here are the steps (some steps are already explained elsewhere):

Import grbl's library in Arduino IDE.
Find out where the library got installed and edit grbl/spindle_control.c, lines 89 and 94.
Change 0x02 to 0x05. Save and close the file.
Compile and download the library to Arduino Uno.
Connect everything but leave the ESC unpowered.
Send M3 S0 (that's a zero).
Power the ESC.
You should hear a 123 tone (three beeps of different frequencies). It will then continue to beep once from time to time — I have no idea why... It should have stopped after a few.
Send S600. It should start spinning. If it doesn't, first send lower values from 0 to 600.
Send S500 to stop.