When you connect your arduino directly to the PC using the ethernet cable, neither of them have any information about the network.

Most ethernet devices attach to switches, routers, and gateways, and one or more of these devices host network services such as DHCP, DNS, or provide a way to obtain those services.

Without DHCP, for instance, neither your PC nor the Arduino know what IP adress to use, what their netmask is, and whether there's a gateway to other IP addresses.

You have a few options:

Follow the Automatic Private IP Addressing specification, which windows computers default to when no DHCP server is present or available. Set the IP address of the Arduino to 169.254.x.y where x and y are randomly chosen numbers between 0 and 255, and set th netmask to 255.255.0.0.  The windows computer should have done the same if no static IP address was set - use ipconfig on the windows command prompt to find its IP address.  Your computer and arduino should be able to talk to each other.
Set up a router. It doesn't need to connect to the internet, it just needs to connect to both the PC and the Arduino.  It'll implement a DHCP server and make sure, at minimum, that the two devices can talk to each other and the router.
Set static IP addresses on both devices.  Set up the PC with something like 192.168.42.1 with a netmask of 255.255.0.0 and the Arduino with 192.168.42.2 and the same netmask.  Now they should be able to talk to each other.
Connect both to an existing network.  The network should already have a router with DHCP on it, so it'll take care of everything, and as a bonus you may be able to get internet access as well, which could help with testing since you can use the ethernet shield to communicate with google and other known working services, rather than trying to set up a server on the PC.


What is the best way to connect multiple Arduinos?

I think you should start with using Wifi modules and you use an esp-01 too instead of NodeMCU. Once you are familiar with esp-01's, you will find them as good as NodeMCU. Esp-01's only lack multiple pins when compared to NodeMCU.

And for communication between arduino and esp-01, use serial ports- 0 and 1.

Here is example code-
For Master Arduino

int temp;
int hum;

void setup(){
 Serial.begin(115200);
 delay(2000);
}
void loop() {

 temp = random(0,100);
 hum = random(100,200);
 Serial.print(temp);
 Serial.println('t');
 delay(2000);
 Serial.print(hum);
 Serial.println('h');
 delay(2000);
 Serial.flush();
}

For Slave Esp or any other slave arduino -

String inString = "";    // string to hold input

float temp = 0,hum = 0;

boolean newtemp=false, newhum=false;

void setup() {
  Serial.begin(115200);
  Serial.println("ESP 8266 - 01 Module is ready to receive codes from Master Arduino");
 }

void loop() {
  // Read serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {

      if (inChar == 't')
      newtemp = true;

      if (inChar == 'h')
      newhum = true;

      inString += (char)inChar;
    }
    else {
      Serial.print("Input string: ");
      Serial.println(inString);
      if ( newtemp == true ) {
      temp = inString.toFloat();
      Serial.print("Received Temperature:");
      Serial.println(temp);
      newtemp = false;
      }
      if ( newhum == true ) {
      hum = inString.toFloat();
      Serial.print("Received Humidity:");
      Serial.println(hum);
      newhum = false;
      }
      inString = "";
    }
  }
}

Pin connections -

Master Arduino TX -- Slave board RX


For the fix, just add the reference capture and it should compile fine:

   // Execute delayed instructions
  client.executeDelayed(5 * 1000, [&]() {   // [&] instead []
    client.publish("mytopic/test", "This is a message sent 5 seconds later");
  });

I could not test, but you will have to apply to other functions as well.

[] Capture nothing
[&] Capture any referenced variable by reference
[=] Capture any referenced variable by making a copy


The problem is that the delay routine is blocking. It stops operation and blocks other things from happening. Have a look at the Blink without delay example in the example tab. (also linked below)
https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

What you need to do is to not block. Call the time checker often and check if the time you want delayed has run out. The perform the action needed to be done at that time.

This is a more sophisticated way to deal with timed events. Also look at this
Demonstration code for several things at the same time.
https://forum.arduino.cc/index.php?topic=223286.0

Have fun learning. :)


Is it possible to supply Arduino nano with LED-stripe from 12V

I remember Answering similar question somewhere. Do not worry about Arduino sharing 12V supply with LEDs. Any supply with CE mark (I would have expected that to be standard in Russia and nearby countries) would be unlikely to spike above the means of arduinos voltage regulator.
There is a small chance that your supply may assume the consumption is too low and go to sleep, but that is rare.

I guess the question is a matter of controlling the LED strip. from the strong 40Amp I am guessing that LED strip would be longer then few CM, So transistor wont cut it
Its a question of MOSFET vs relay. MOSFETS are better if you keep switching LED's on and off a lot, few Milion times is no problem for them, however they are expensive especial if there is a high current (the 1K resistor is not necessary, just a habit to protect the output).

simulate this circuit – Schematic created using CircuitLab

Second option is a relay. its useful even on a higher load, but only gives several thousand, and in case of e-bay special like songle about a hundred switch of's(or ons). Note that many relays have two ratings in Amperes. The smaller number is for you here (DC).

simulate this circuit

Here 1K is required

Although when saying 40 ampere dont forget the rule of online shoping on power )supply, light emission etc:
50 Ebay Amperes = 60 BangGood Amperes= 80 Wish Amperes= Around 18 Real world amperes

So if your 40Amp supply is from ebay that would make it about 16Amp of long-term (more then half an hour-10 hours) running time


You need 2 typecasts. So

atan(-ax/sqrt((float)ay*ay+(float)az*az));

Otherwise it will use int16_t for the right side of the addition and overflow.

Though for speed you might want to typecast them as long (int32_t), as floats calculations on the arduino are really slow. The sqrt function will covert this double into a float for you.


Interactive menus are certainly not a "simple" task. That is why people use libraries.

Whatever you try you will end up with complex code - either long winded with lots of duplication, or somewhat cryptic with lots of pointers, arrays, and structures. Not an easy task for a beginner in C++.

How I would set about it would involve the following things:

A structure that defines a menu entry, including pointers to one of: sub-menu array, numeric variable (including max/min limits), option array, function to execute.
Arrays of the above structure to define each menu
Array or linked list of "breadcrumbs" through the menu to track where you are and go back up properly
Functions to display and navigate the menu arrays on an LCD.

All of that uses fairly advanced C coding techniques, especially when it comes to managing all the pointers, etc.

The "simpler", though more long winded way, would be to write individual functions for each menu and sub-menu, but that would make your program incredibly long and prone to have errors when duplicating (copy/paste) code.


Can I change the USB device name of Arduino?

You'll have to change the software on the Arduino USB chip itself, and you may need to modify the drivers for the Arduino USB interface on the computer side.  It's not trivial, and probably not worth it.

However, Windows attempts to use the same serial port for the same devices in the same USB positions, so if you figure out which is which (blinking the LED at different frequencies) then you can mark the USB port itself with the com number that Windows uses when you plug an arduino into it.

If you use a hub, and you move that hub to a different port, the com numbers will change, but if you keep it in the same port, then it too will try to have them match what they have been in the past.

It's an annoyance, but it's a design decision by arduino.cc.  The old FTDI chips kept their assigned com port numbers because they have individual serial numbers and windows would attempt to reassign the same com port to the same chip each time it was plugged in, regardless of its location.  When Arduino.cc moved to a programmed MCU for the USB interface, they chose not to provide USB serial numbers, and thus windows has little option but to try to keep things straight by determining the location in the USB hierarchy that the device is connected, and try to keep com port assignments the same using that method.


The information is available on SDK level. If you include #include "user_interface.h", you can use function wifi_station_get_connect_status(). It returns one of:

STATION_GOT_IP
STATION_NO_AP_FOUND
STATION_CONNECT_FAIL
STATION_WRONG_PASSWORD
STATION_IDLE

The WiFi.status() function uses function wifi_station_get_connect_status(),  but returns WL_CONNECT_FAILED for STATION_WRONG_PASSWORD.


Maybe you use the wrong baudrate with your hardware serial. Your tutorial states, that 38400 baud is the default, but I found other sources (HC-05), that say the default is 9600 baud (which is also true for my HC-06 modules). Try 9600 baud and if it still doesn't work try some other standard baudrates.


How to find integer inside a file with STRNCMP

Maybe make it as:

char id[] = "18";

This is if you want to find "18" in your file. That's what I understood from your question.

EDIT: I guess you want this http://playground.arduino.cc/Code/PrintingNumbers:

int num = 18;
char buffer[100]; // this will hold your number
itoa(num, buffer, 10);

Function description here. Also it's not to hard to make this your self for integers and it's a good exercise.


unsigned int t1=0;
unsigned int t2=0;

Integers on an 8 bit system can only store 16 bits of data. For unsigned that is 0 - 216-1, or 0 - 65535.

Make them unsigned long and they can store 0 - 232-1, or 0 - 4294967295.

Also, since they are unsigned, any negative value will wrap around to the maximum again. An unsigned can't store a negative value.


Is this the best approach ?

Not really, no.

  Is it efficient ?

No, far from it.

  are there any problems I should be aware of ? Precautions I need to take ?

You don't want a voltage divider to power an opto-isolator. An opto-isolator won't be powerful enough to cope with the motor current. You need flyback protection.

  Is the voltage divider a good approach to feed the input to the Optoisolator ?

No, definitely not.

Unless you require galvanic isolation all you need is a simple NPN transistor or N-channel MOSFET circuit:

simulate this circuit – Schematic created using CircuitLab


How can I pair a Bluetooth dongle on arduino Yun (openwrt-yun)?

It takes me some time to make it work :

1) update drivers

opkg update

opkg install kmod-bluetooth bluez-libs bluez-utils

2) add configuration files in directory /etc/bluetooth

root@Arduino:~# cat /etc/bluetooth/hcid.conf

options {
  autoinit yes;
  security auto;
  pairing multi;
  passkey "0000";
   }
device {
  name "OpenWrt";
  class 0x000100;
  lm accept,master;
  lp rswitch,hold,sniff,park;
  }

root@Arduino:~# cat /etc/bluetooth/rfcomm.conf

rfcomm0{
 bind yes;
 device 00:1B:C1:02:B0:F5;
 channel 1;
 comment "Holux M-1000";
 }

3) Reboot the card

4) test if all is OK

hciconfig

5) put the interface up

hciconfig hci0 up

6) Search for devices

hcitool scan

7) Look for Serial Port capability on the devices

sdptool search SP

8) bind the serial dev

rfcomm -i hci0 connect /dev/rfcomm0 00:1B:C1:02:B0:F5

9) see the information comming from the device (bluetooth GPS in my case)

cat /dev/rfcomm0


Why is Arduino resetting while driving motors?

The VIN pin goes to a 5V voltage regulator on the Arduino and needs at least about 7V minimum to work properly.  If you want to supply 5V to an Arduino do it either on the 5V pin or via the USB connector.  The VIN pin should receive 7V to 12V.


How can I tell the resistance of an internal pull-up resistor?

io 0 and io 15 are with io 2 boot configuration pins of the esp8266. esp8266 dev boards have external pull-up on io 0 and io 2 and pull-down on io 15.


Can Arduino Uno R3 board remove chip on the board

It depends, if the chip has not been soldered, but placed in an IC (DIP) socket, than you can remove the programmed chip, and use it in another circuit and place another (same) IC in the IC socket of the Uno to be reprogrammed.

You also could desolder it, but I would not advice that; also most of the Uno's having a soldered IC use SMD instead of DIP.

Also, to replace the IC, you need to install a bootloader on the IC to be placed in the new Arduino (thanks for the addition Roberto Lo Giacco).

Below is a version with DIP that easily can be replaced, hence the big IC and the socket:

Below is a version with SMD that cannot easily be replaced, hence the small IC without a socket:


Time Stamping data on an Arduino and reading it on a Java IDE

There's a number of fundamentally wrong things in your sketch.

static char buffer[1]; // a variable to hold both sensor data

No - that has room for 1 entry - hence the 1. 1 means 1, not 2.

buffer[1] = newByte;

No. There is no buffer[1]. You count slices from 0.  buffer[0] exists (the first one) but buffer[1] doesn't.

buffer[0] = millis;

You aren't calling the function, you are assigning the address of the function. And worse than that, buffer is an array of 8-bit values - neither the address of the function, nor the return value from the function (if you were to fix that) would fit in that space - since the return value is an unsigned long which is 4 bytes in size.

You need to have at least 5 bytes in your array - four for the time stamp and one for the value you read from serial. Then you place them in to the array in the order you see fit, and read them back in the same order in Java.


How to: soil moisture measurement with WaterMark?

You can google
"Arduino-based system for soil moisture measurement"
and the author about this paper is "Vuk Radman" .

Now, I am also try to find the method using Arduino to connect WaterMark 200ss Sensor. The paper I share to you is what I have found from GoogleScholar, but I haven't used this method yet. Nevertheless, I think the method mentioned in the paper is feasible. Hopefully, this information can help you.


Using software Serial for Adafruit Thermal library and more general cpp question

:'( it's a bitter sweet solution.

After @majenko's last comment:

  Ah. So is there something you have to do in that IDE to say "Include the files in lib in the compilation`?

I remembered that this issue has bitten me before. Specifically, the issue of including subfolders into a sketch.

Normally in programming languages (at least all of the ones I work in normally), you can use relative paths or namespaces to include files from subfolders, but for some reason with Arduino if you want to include files from subfolders you have to put the files in a directory named src.

And it specifically needs to be src. You can't use lib or libs or source or whatevernameyouwant, it needs to be src.

I can't find a spot in the arduino reference docs or the IDE's github repository that explains that you need to use src for the subfolder name, but you can find various mentions in the forums. E.g.

https://arduino.stackexchange.com/a/54655/35534

So yeah, the solution to my problem was three parts.

Adopting the Adafruit_Thermal library into my codebase so that I could edit the source code without worrying about those changes polluting the orginal.
Removing the &Serial reference pass in the constructor declaration of Adafruit_Thermal.h
using the src directory name to include things from a subfolder.

After doing this, the sketch passes verification.

But here's the bittersweet part. After getting past all of this and seeing the compiler get past the sketch verification the bombshell dropped; the sketch is too big for the attiny:

I guess it was not meant to be :'(

Well, at least I know what was causing the linker/compiler errors and I'll be able to sleep at night :P

Thanks for your help Majenko :bows:.


Read all relay output (high or low) from Bluetooth through Android app

It's rather undocumented, but you can actually use digitalRead(relay2); on a pin (ex relay2) that is set to OUTPUT. I discovered it accidentally, and it worked exactly as expected, so i looked it up and it's legit. This is very handy to check an output pin's hi/lo state from a non-connected part of the code.

There is a tiny performance dip compared to reading just a variable, but it usually won't be noticed. If you need top performance, wrap the digitalWrite() with your own function, and set a variable with the new state:

int myState[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

void digitalWrite2(int pin, int value){
   myState[pin] = value; // copy setting to a global array
   digitalWrite(pin, value); // apply the setting as intended
}

Now, you can instantly get all the relay states from the myState array, provided they've been set with digitalWrite2. The other advantage to an array is that you can easily persist it to SPIFFs or EEPROM as-needed and recover the relay states on the next boot.


Try with

unsigned int distance;

Instead of

int distance;

It could also be the motor shield that is using the same pins as your ultrasonic sensor.


Receiving serial data in groups instead of individually

readString() will keep reading until it times out. Instead try readStringUntil('\n') to read until you get a new line character.


UART Software Serial - Syncing two different sensors with start and stop bytes

Your code bit

SendCmd(0x00,0x5C);//Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
delay(70);//time for SRF02 to measure the range
SendCmd(0x02,0x57); //Get Fake Range at Address 0x02 - receiver

will send a sound burst, delay 70 ms, then start listening for the burst, which by then will have traveled around 24 meters and probably be no longer audible.

You should instead start the fake range listener immediately after sending the burst.  The general idea for one approach is as follows:

Record time (eg, t1=micros();)
Send burst (eg, SendCmd(0,0x5C);)
Record time (eg, t2=micros();)
Listen for burst (eg, SendCmd(2,0x58); // Get microseconds)
Wait 70 ms, then read microseconds result t3
Compute corrected total microseconds, tm=t3+t2-t1
Convert microseconds to cm

Note use of command 0x58 instead of 0x57 to get microseconds instead of cm.  If you used 0x57, instead of adding t2-t1 to t3, you would add t2-t1 microseconds-converted-to-cm to a cm reading.

The reason for the computation tm=t3+t2-t1 is that the second command is issued about t2-t1 microseconds later than the first command, as explained in the next paragraph.

There is an unknown delay d1 between when t1 is recorded and when the first SRF02 acts; and there is an unknown delay d2 between when t2 is recorded and when the second SRF02 begins listening.  The correct amount to add to t3 is t2+d2-(t1+d1), which is t2-t1 if d1 equals d2, a more-or-less plausible assumption.  If your experiments reveal a constant error, add a small constant offset to compensate.

I doubt you should have the delayMicroseconds(100); statements in SendCmd(), and would recommend getting the code to work ok, then see if it still works ok when you take them out.  The delay(10); is unnecessary if you rewrite your 2-character-wait correctly (ie as a while rather than an if), and the delay(70); is unnecessary if you start conversion with command 0x5A,  “Fake Ranging Mode - Result in centimeters, automatically Tx range back to controller as soon as ranging is complete” and then properly wait for two characters to arrive, instead of a blind wait followed by a test if they've arrrived.


What is the equivilent of PORTx for Teensy (4.0)?

All Teensies support digitalWriteFast out of the box. digitalWriteFast compiles to just setting the bit in the right port register. You can not do that faster by direct register manipulation.

However, if for some reason you do want to manipulate the registers directly here the pin/gpio relation for the T4. (Generated by the sketch described here: https://github.com/luni64/TeensyTimerTool/wiki/Avoid-PWM-timer-clashes")

Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
00  |  GPIO6_03  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
07  |  GPIO7_17  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
10  |  GPIO7_00  |  QUAD1
11  |  GPIO7_02  |  QUAD1
12  |  GPIO7_01  |  QUAD1
13  |  GPIO7_03  |  QUAD2
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
16  |  GPIO6_23  |  no pwm
17  |  GPIO6_22  |  no pwm
18  |  GPIO6_17  |  QUAD3
19  |  GPIO6_16  |  QUAD3
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
33  |  GPIO9_07  |  FLEX_PWM2
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1

#### Sorted by PWM timer
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
10  |  GPIO7_00  |  QUAD1
13  |  GPIO7_03  |  QUAD2
18  |  GPIO6_17  |  QUAD3
15  |  GPIO6_19  |  QUAD3
14  |  GPIO6_18  |  QUAD3
19  |  GPIO6_16  |  QUAD3
24  |  GPIO6_12  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
23  |  GPIO6_25  |  FLEX_PWM4
22  |  GPIO6_24  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
02  |  GPIO9_04  |  FLEX_PWM4
27  |  GPIO6_31  |  no pwm
17  |  GPIO6_22  |  no pwm
26  |  GPIO6_30  |  no pwm
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
21  |  GPIO6_27  |  no pwm
20  |  GPIO6_26  |  no pwm
16  |  GPIO6_23  |  no pwm

#### Sorted by GPIO register:
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
01  |  GPIO6_02  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
19  |  GPIO6_16  |  QUAD3
18  |  GPIO6_17  |  QUAD3
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
17  |  GPIO6_22  |  no pwm
16  |  GPIO6_23  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
10  |  GPIO7_00  |  QUAD1
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
13  |  GPIO7_03  |  QUAD2
06  |  GPIO7_10  |  FLEX_PWM2
09  |  GPIO7_11  |  FLEX_PWM2
32  |  GPIO7_12  |  no pwm
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
28  |  GPIO8_18  |  FLEX_PWM3
31  |  GPIO8_22  |  no pwm
30  |  GPIO8_23  |  no pwm
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
29  |  GPIO9_31  |  FLEX_PWM3


A Reset is necessary to activate the Bootloader and allow programming. Without the DTR signal the Reset button has to be pressed just before starting the upload from the Arduino IDE.


What is the purpose of this line: Morse(int pin);

It is the method that is called when you create an object of class Morse when only passing a single int:

Morse somemorse(1);

  If any, what is the name of this line?

It has multiple names, depending on what aspect you care about:

It is a constructor for the class Morse.
It is a forward declaration for the method Morse::Morse(int).


Control Android Camera using Arduino over Bluetooth

I am trying out Camera Pro. It allows shutter control on Android over Bluetooth. I just got an Uno R3 and and HC-05 so I have not wired it up to try it.

There are example sketch and detailed docs here.


Initialize a class (HX711) within a class with constructor and parameters

Unfortunatly HX711 has no default constructor. So the easiest way would be to add one in the header:

HX711() {} // default constructor, empty

Add member function to do the init job (done by original constructor), also in the header file

    void Init(byte dout, byte pd_sck, byte gain = 128) {
    PD_SCK  = pd_sck;
    DOUT    = dout;

    pinMode(PD_SCK, OUTPUT);
    pinMode(DOUT, INPUT);

    set_gain(gain);
}

Now your ScaleMeasure class will be like (header):

class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale;
};

and cpp

ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
{
    _clk_pin = Clk;
    _dout_pin = Dout;

    _scale.Init(_dout_pin, _clk_pin);

    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}


2G/3G vs 4G/LTE Cell Connectivity for Sensor Prototype?

2G GSM/GPRS are almost dead in the US. CDMA is still working and it would be supported atleast till 2020 becaasue it is used in M2M devices. 3G is still one of the most widely used networks and it has great coverage and it would not likely be phased out till 2024. 4G is widely deployed now and is the future.

Coming back to this from the perspective of developing hardware projects/products and availability of module for DIY use.

2G chip-sets are very cheap (~$10) and easily available with lots of documentation. Example 2g module here

3G modules have been in the market for a little while and there are a couple of modules at a good price-point with decent documentation. Example 3g module here

4g is still bleeding edge and there are not a lot of modules available for DIY users with great documentation and at a good price. I was able to find one with good documentation here.

There are a couple of other factors that come in play when you are working on a project. One is just the support and documentation around the hardware. These modems usually need a good library built around them which can handle most of the functionality and most of the time, the manufacturer gives just a datasheet specifying what all the functionality is and the user is supposed to build the libraries for them in the platform of their choice. Here is adafruit's library for the cellular module to show you the complexity. Also, when you are just using a few of these then the modules are just building blocks and it usually makes sense to use the modules with the best possible support around them.

Tl;dr, use a 3G module with good software support for your platform.


How to power Arduino pro mini and DFPlayer mini togather with 3.7 V LiPo battery?

Use a buck/boost voltage regulator. Those are high efficiency switching regulators, and can either increase or decrease the input voltage. Feed the output of the regulator directly into the Arudino's 5V (or 3.3V) line, bypassing the on-board voltage regulator.
What input voltages do the 2 devices need? Both 5V? If so, you can use a single voltage regulator to power both devices. If one needs 3.3V and the other needs 5V you may have to have 2 different voltage regulators.
By using a switching regulator you can bypass the fairly inefficient linear regulator in your Arduino supply 3.3V or 5V to it directly (depending on the type of board you have.)
Edit:
Ok, I looked it up and a DFPlayer Mini player appears to be a shield designed to plug directly into an Arduino. It looks like it can be powered from 3.2 to 5V, so you should be able to use it with either a 3.3V or 5V Arduino Pro Mini. Once you've decided if you're going to use a 3.3V or 5V Arduino, pick a buck/boost voltage regulator with the desired output voltage (or get an adjustable one and set it appropriately.)


Initialising timer interrupt crashes Mega 2560

You have enabled the timer and also its interrupts but you have no interrupt handler. The interrupt has to go somewhere and as it is it's going who-knows-where. Add an ISR and I believe that will resolve your issue.
Yes, the capitalization is important!


Although I still do not understand how to combine the data from the serial port with the analog input, I can show how to display a message for 5 seconds, using the Blink Without Delay example.

A boolean variable 'message' is used to prevent the normal code to use the display during the 5 seconds. The same boolean variable is used to check if 5 seconds have passed (using millis). Once the 5 seconds have passed, the boolean variable is set to 'false' and that releases the display so it can be used for normal things.

To start the 5 seconds, these two lines are required:

previousMillis = millis();
message = true;

When 'message' is set to true, the variable 'previousMillis' must be valid. Once 'message' is false, the value of 'previousMillis' is not used anymore.

The sketch can be like this:

unsigned long previousMillis;
const unsigned long interval = 5000;  // 5 seconds
bool message = false;     // true if message is displayed

void setup() {
  // the code for setup here
}

void loop() {
  if(!message) {          // message not displaying ?
    // show temperature, time, etc.
  }

  if(Serial.available() > 0) {
    int a = Serial.read();
    switch(a) {
      case 102:
        lcd.setCursor(0,0);
        lcd.print("Lamp ON ");
        previousMillis = millis(); // remember this moment
        message = true;    // set boolean variable
        break;
    }
  }

  if(message) {
    if(millis() - previousMillis >= interval) {
      // 5 seconds have passed ?
      message = false;    // release the display
    }
  }
}


How to use an external clock with the Due timer?

Everything you need to know is in the SAM3X datasheet:

http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf

However, as Atmel's datasheets are some of the most cryptic ones around, you'll need to spend quite some time deciphering it.

There's an entire section just on the timers.  It tells you all about how they work, however, relating that to which registers you need to set to get it to do that is not clear (as is normal for Atmel) since the registers are listed elsewhere in that section with no real relationship between them.


Components required to control the Speed of Wilo Para AC Synchronous Motor

You do not want a "0-10V PWM signal". There is no such thing.

There are generally 2 methods of controlling motors like these:

Through a variable analog voltage between 0V and 10V, where the voltage given is proportional to the speed, and
Using a digital PWM signal where the duty cycle is proportional to the speed.

You are getting confused and combining the two together (and to be honest that datasheet, which is really little more than a sales brochure, doesn't help matters).

Typically a PWM input on a motor uses a standard TTL signalling method.  This specific motor, as detailed in this document uses a slight modification on the standard. It requires a minimum of 3.6V for a HIGH, and the ESP32 gives 3.3V maximum.

Because of that you will need to amplify, or "boost" the signal to a slightly higher voltage.  The simplest way to do that is with an off-the-shelf logic level translator (3.3V to 5V). There are cheap MOSFET based ones on eBay etc that will do the job.

If you want to create your own the circuit is quite simple, and requires one N-channel MOSFET and two resistors. I use the BSS138:

simulate this circuit – Schematic created using CircuitLab


I have a couple of ideas for you but know these are only suggestions. No hate please.

Have you tought of IR following?

IR is a almost unique signal that only you have. You can either use multiple IR sensors to determine where the emitter is or you can use the servo motor to do it as a radar. Note that you have to isolate each sensor so it knows where you are and it doesn't captures the wave from a different angle by accident.

Extra safety?

You can also incorporate an untrasonic distance sensor so that the cart doesn't bump into you or any one. Like you can say, if the distance is smaller then 12 inchs / 30 cm, stop the cart. It is practically an extra safety feature.


In multidimensional arrays, can you use variable arrays or their names instead of the actual data?

Two-dimensional arrays come in two "flavours". Actually, multi-dimensional arrays are possible in any combination of these.

All elements in a rectangular grid, at least from the abstract view of the programming language;
A one-dimensional array of one-dimensional arrays.

If you declare:
byte array[n][m];

then you have reserved space for "n times m" bytes. From the programmer's view it is a rectangular grid, actually all bytes are in sequence in a one-dimensional array. This is because the memory of our computers are commonly organized as a big one-dimensional array of bytes. The compiler generates the correct calculation for the offset into this array, multiplying one index with the size of the width (or length, depending on your mental model) and adding the other index.
You can initialize such an array with the nested set of curly braces like this:
byte array[n][m] = {
    { /* ... */ },
    /* ... */
};

But you cannot initialize it as you show.
Otherwise, if you declare
byte* array[n];

then you have reseved space for "n" pointers to bytes, that is a one-dimensional array of pointers. Each of these pointers can point to a different or the same one-dimensional array of bytes, or to no array at all if it's nullptr.
Now you can set up the array as you like:
byte arrayX[m1] = { /* ... */ };
byte arrayY[m2] = { /* ... */ };

byte* array[n] = { arrayX, arrayY, /* ... */ };

The arrays arrayX and arrayY (and any further) don't need to have the same length. Each can have its own length. But beware, you need to trace the length somehow to avoid out-of-bounds accesses. And of course, you need to check or be sure that a pointer is not null before dereferencing it.
In both cases you can access a single element with:
byte element = array[i][j];
array[k][l] = 23;

This is because the syntax with the brackets is equivalent to the dereferencing operator:
x[y] == *(x + y)

Note 1: Since Arduinos are programmed in C++, there is another option. You can use references instead of pointers. Because it is really hard to create a null reference, some see it as a safety measure against null pointers.
Note 2: Again, since Arduinos are programmed in C++, you can implement an own class that provides the operator[]. With this option you can do any magical stuff, but it might break the user's expectation. Be careful if you go that route.


USB 1.1 Low Speed project for Arduino UNO/ATmega328P to learn USB protocol

Not exactly the answer to your question, but have you tried the typical way to emulate slave devices with Arduino UNO?

It uses the 2nd ATMega present onboard (this applies only to UNO, afaik) and lets you use the main ATMega for other tasks, delegating the USB protocol to the smaller ATMega16.

Do you have any specific reason why you would use the serial lines?


External ADC reading zero while input is zero

The behaviour you are seeing is what happens when you have high-impedance inputs.  Basically, if you don't drive them, you get random values.

Unfortunately in your case, where the sensor you are using has no output current to speak of, I don't think there's anything you can do about this electronically.

You'll have to solve the problem in some other way if you really need to be able to disconnect the sensor.  A mechanical solution would be a connector which shorts when disconnected.  Switched headphone connectors do this, for example - when you pull out the jack, they make a connection so that the speakers can be switched on.


How to set Inquire Access Code (IAC) via AT commands on HC-05?

You have to have \r\n in both the set and read command.

Example:

AT+IAC=12345f\r\n
OK

AT+IAC?\r\n
+IAC: 12345f
OK


Can I do speech to text converting with arduino?

There are many Arduino type boards.  Some, like the galileo from Intel, are very powerful.  And are more expensive than the basic Arduino Uno.  It may be possible to program such a board for speech to text conversion.  But it is arguable that using a modern laptop with built in features (microphone, keyboard, display, speaker, ect) would make the task easier.

Also, consider current industry standards.  Many text to speech applications are now centered around cloud computing.  Think of Siri, Alexa and Cortana.  But even if you do, consider that the Arduino Uno only contains enough RAM to record an "utterance" of speech. On the order of a second, maybe two.

Finally, consider COTS (Common Off The Shelf) parts (Arduino shields).  Searching "arduino speech to text" I found at least one device.


How to reset the count/data after HTTP.POST?

Try putting your total variable to 0, like this:
total = 0;
It should work like this.


Your code to calculate the length of your Strings does not make sense. The String type is an object type. The addresses of your String objects will not match the length of the charcters in those strings. You should use an array of C strings as suggested by Juraj, and then you should use strlen() to get the length of those strings (C strings have a null terminating byte, and strlen() uses that null to calculate the length. Note that C strings can't handle Unicode.)
The String type is best avoided on Arduino anyway, as String objects tend to fragment the extremely limited heap memory on Arduino devices and cause out-of-memory crashes.


EDIT due to misunderstanding the question.

If you want to be able to pass instructions into a function, you will have to have a function for each set of instructions (that is, you cannot pass arbitrary statements as a function parameter), and then you adjust your runfor() function to accept a pointer-to-a-function parameter.

typedef void (*callback_function)(void);  // defining the type here makes the code easier to read when used in other places.

void runfor(uint32_t duration, callback_function patternCode){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
    patternCode();
  }
}

void pattern1() {
  // Light pattern #1
}

void pattern2() {
  // Light pattern #2
}

void setup() {
  // Setup code
}

void loop() {
  runfor(1000, pattern1);
  runfor(2000, pattern2);
}

ORIGINAL ANSWER

Your starting pseudo-code is nearly there.

void runfor(uint32_t duration){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
  }
}

Changes I made:

change int to uint32_t to accommodate all possible values of millis().
change for keyword to while, which is the correct keyword for the loop type you want.
added semicolon after your timer assignment, per C syntax.


How to network multiple Arduinos so they react to the same signal

Rule 1 do not connect Arduino pins to long wires.

You can achieve your your goal in many ways, a serial interface looks good from here.  I am doing it with a RS485 interface, note it is an interface not a protocol. You can use CAN, Wi-fi and many others.  It sounds like all the units except 1 will be receiving data, the other is transmitting it to the other devices.  RS485 will work good and it needs only 5V.  It will work over several thousand feet and some reasonable speeds. You can use a UART either hardware or software to accomplish the task with a RS-485 driver at each node.  You need to remember you need to wire from point to point with the terminating resistors only on the end nodes.


Being from eBay, I would assume the seller "bricked" the chip beyond his/her capability to fix.  Fortunately, you know about stack exchange!

My immediate suggestion is to find, borrow or build a high-voltage programmer.  This is a special programmer that can un-brick the chip no matter what's been done to it. The concept is easy, but you need to protect the programmer's pins from the 12v reset signal.

Googling "avr high voltage programmer" gives several useful links.
I'll get the actual links when I get back to a real computer.

Ok, so life got in the way, sorry about that.
This is the one I built which worked perfectly:
MightyOhm

However hooking up the AVR to a "high voltage programmer" is well documented in the data sheets.  These should be very much similar circuits on Google.


HC-05 Bluetooth Module Blinking Red Light-Arduino Uno

There are several issues to consider:
• Program downloading
• HC-05 serial communication
• Bluetooth pairing

For the first issue:  The serial-over-USB connection between the development computer and the Uno ties up the Uno's hardware serial RX and TX pins.  There will be a conflict if the development computer transmits when the HC-05's TX is connected to the Uno's RX.  This can be resolved by disconnecting the HC-05 TX when downloading a program.

For the second issue:  The Uno schematic shows 1KΩ resistors between TX and RX on the ATmega328P and RX and TX on the USB chip (ie on an ATmega16U2, or a CH340, etc).  If the HC-05's TX drive is strong enough, it will overcome the drive from the USB chip and work ok.  Note, I would leave out the voltage divider (on the HC-05 RX line) that the video shows.

For the third issue:  The HC-05 in the video mentioned in the question has a blue LED that blinks steadily when the HC-05 isn't paired, and blinks at a long interval when it is paired.  Many HC-05's have red LEDs instead of blue; the LED color is not an issue.  Some HC-05's don't blink at all when paired; that's not an issue either.  What is an issue is that (according to description in question) your HC-05 keeps on blinking, so apparently isn't paired up.

Whether the HC-05 pairs with an Android app is more or less independent of whether you have the HC-05 connected to an Arduino; you should be able to pair your phone with the HC-05 when just Vcc and ground are connected to the HC-05.  If you are having trouble with pairing, try another app; try powering the HC-05 down and up; and try a different HC-05.  I mention trying another app because one serial-terminal app I installed on my Android phone needed the app or the HC-05 to be restarted to pair up after loss of pairing, and the serial-terminal app I replaced it with did not need those actions.  Note, pairing takes a few steps on my phone:  in Settings / Wireless, search for Bluetooth devices; select device; enter its passcode; run an app and tell the app which Bluetooth device to use.


What is ECC608 crypto chip accelerator used for in Arduino Uno Wifi rev2?

The library for the chip is ArduinoECCX08. It is used by the ArduinoBearSSL library. The ArduinoBearSSL is used by the ArduinoIoTCloud
 library and Arduino_OAuth library.
.


Can the EWRF 3022 module be directly connected to the pc totransmit data from the pc wirelessly?

If you use a USB to TTL UART adapter, such as an FT232 dongle, then yes you can communicate to it from a PC.

It will not directly connect to a PC though without you getting that extra hardware.


Receiver xbee receiving data while the Transmitter is powered off?

As @Garben mentioned, we do not know what is your question, problem or whatever...
Provide some more information about wiring. I looked at your question 5 mins and still can't get what is wrong...

What are you doing here??? Sending from Arduino+XBEE to another Arduino+XBEE???

void loop() {
    Serial.println("Hello");
    delay(1000);
}

Here you are resending what you got

void loop() {
     if(Serial.available()>0){
         Serial.print((char)Serial.read());
     }
}

So what is your problem? Or is this all your code???
Arduino has to have

void setup(){
//Set up your Arduino here
}
void loop(){
//Code here will run over and over and over...
}


Using a transistor to get 100mA on a IR led

Increasing the power to the LED isn't the best way of increasing the distance. In fact it's the worst way.

The 100mA is only for a small duty cycle. You can power it with 100mA but only for a fraction of the time. The overall average light output won't be any more than at 30mA.

The problem you are actually suffering from is the fact that your receiver can't distinguish the LED's light from the background light. That is simple to overcome though. You just need to modulate your LED with a high frequency (typically 30kHz or higher) and perform a high pass filter and amplification on the receiver.

Exactly the same way that remote controls do it.

That way you can distinguish the LED (flashing at a given frequency) from the background light (static brightness or relatively very slowly changing).


Arduino with using Adafruit NeoPixel library set one color, fade random pixels in strip on and off

You simply have to treat each pixel individually.

Pick a pixel
Add it to a fade list
Fade all the pixels in the list by a step
Remove pixels which are below some threshold
Repeat

How you do those things like picking the pixel is up to you. You'll probably want to brighten some as well, using a similar algorithm.


When is it necessary to use "float" instead of "int"?

An integer is a whole or natural number.  Computers use integers for counting and comparisons.  Computers can count precisely using integers and comparisons of two integers can be absolutely true or false.

To make a float or floating-point number, a computer uses two integer numbers.  It uses one integer as the mantissa and the other as the exponent.  Computers use floats for calculations involving very large, very small or fractional values.  In other words the set of real numbers.  Computers can not count very well using floats.  Computer can not even compare two floats very well. That is to say, you may get different results from different computers when testing if two different floats are the same or not. This is due to rounding error.

Consider that the set of real numbers between 0 and 1 to be infinite.  However, intuitively, we know computers can not keep track of an infinite number of unique values between 0 and 1.  After all, computers use a float to do this and a float has a finite number of bits in it's mantissa and exponent.  The difference, if any, between the actual real number from, say, a calculation and the next possible float value is commonly referred to as the roundoff error.  In a program, a difference, for example, in the order of operation is enough to cause different roundoff errors to occur resulting in two slightly different float value results.

Rounding errors are what we end up with for allowing float values to grow very large or very small or to contain factional amounts.  Fortunately, floats are exactly what we need when computers are asked to calculate very large, very small or fractional numbers.

In embedded programming we rarely use floats.  They take up more of our limited RAM space than integers.  And it is rare that we need to calculate very large or very small numbers.  Usually, in embedded programming, we are counting events or measuring sensors.  Usually integers are preferred or are sufficient for our purposes.

Addressing your specific application (pedometer):

It is anticipated you would prefer to track distances in miles.  And it is practical to assume a good pedometer displays factional miles.  You can use floats to calculate this value.  A rigorous programmer would cast their integers as floats when mixing them in equations to make it clear to the compiler what is desired.


If statement comparing array to value list throws error

You cannot compare like that... you have to do it one by one (and check the length of the array).

if ((sizeof(invest) / sizeof(bool) == 4) &&
    (invest[0] == 0) &&
    (invest[1] == 1) &&
    (invest[2] == 0) &&
    (invest[3] == 0))
{
     ...
}

If you need to do such a compare often (with possibly different values), you of course can always write a dedicated function passing the array, and the array to check against and check the length and use a loop for checking all values.

Note that if invest is a boolean array, it's best to use false and true instead 0 and 1.


DC motor does not work using PWN or Digital pins

The Tutorial.pdf document that describes the components in the kit does not tell you what the current draw of the motor is. Chapter 10 has 2 tutorials on how to use the motor with a relay or L293D IC. This suggests to me that the motor draws a lot more current than a digital output can provide.

The tutorial using the L293D gives you the ability to vary the speed of the motor using PWM, so it would be a good place to start.

Hopefully pin 3 was not damaged by the excess current flow when the motor was attempted to be powered from it.


The registers aren't for just turning the LEDs on or off.  They are for setting the ON and OFF times of the PWM. Bit 12 of each combined value is used as a "full" setting, so:

To set the LEDs on to full brightness you need to set:

PCA9685_ALL_LED_OFF_L to 0x00
PCA9685_ALL_LED_OFF_H to 0x00
PCA9685_ALL_LED_ON_L to 0x00
PCA9685_ALL_LED_ON_H to 0x10

This sets the off time to 0 counts and the on to be "full on".

It doesn't really matter what value you set the OFF to as long as you set ON to "full on" and off isn't set to "full off".

For off you should set the ON to 0 and the OFF to "full off" (reverse the above settings).

Section 7.3.3 of the datasheet says:

  The turn-on time of each LED driver output and the duty cycle of PWM can be controlled independently using the LEDn_ON and LEDn_OFF registers.

  There will be two 12-bit registers per LED output. These registers will be programmed by the user. Both registers will hold a value from 0 to 4095. One 12-bit register will hold a
  value for the ON time and the other 12-bit register will hold the value for the OFF time. The ON and OFF times are compared with the value of a 12-bit counter that will be running
  continuously from 0000h to 0FFFh (0 to 4095 decimal).

  Update on ACK requires all 4 PWM channel registers to be loaded before outputs will change on the last ACK.

  The ON time, which is programmable, will be the time the LED output will be asserted and the OFF time, which is also programmable, will be the time when the LED output will be
  negated. In this way, the phase shift becomes completely programmable. The resolution for the phase shift is 1⁄
  4096 of the target frequency.

So you have to set all 4 registers together for anything to happen.

There are also some examples shown in the datasheet as well which explain it better.

In simple terms:

There is a free-running counter that counts from 0 to 4095
When the ON time matches the counter the LED turns on.
When the OFF time matches the counter the LED turns off.
If a channel is "FULL OFF" it will be off regardless.
If a channel is "FULL ON" and not "FULL OFF" it will be on regardless.
"FULL OFF" always takes priority over everything else - even "FULL ON".

Some simple examples:

All off: ON=0x0000 OFF=0x1000
All on full: ON=0x1000 OFF=0x0000
50% duty: ON=0x0000 OFF=0x0800
25% duty: ON=0x0000 OFF=0x0400
25% duty with phase shift: ON=0x0100 OFF=0x0500


32u4 using internal clock on custom PCB - loading sketch

Yes you can reprogram your 32U4 chips via the ISP, they do not have to be fresh chip. If you set your Fuses to -U lfuse:w:0xE2:m -U hfuse:w:0xD8:m -U efuse:w:0xCB:m using AVRDUDE you will have an 8mhz internal RC oscillator set and you do not have to have the external crystal.

You can play with these settings at http://www.engbedded.com/fusecalc/.

I recommend learning the command line AVRDUDE commands this way you have more control over what you are doing to your chip.

I use this all the time, and if you need to do more than one quickly I typically make a batch file that does the Fuse Burn and hex at the same time.

this is for a attiny167 but you get the idea:
.\avrdude\avrdude -C".\avrdude\avrdude.conf" -v -pattiny167 -cstk500v2 -PCOM3 -Ulfuse:w:0xE2:m -Uhfuse:w:0xDF:m -Uefuse:w:0xFF:m  -Uflash:w:1060X01-001.hex:i


If your sketch has

  ...
void setup() {
  Serial.begin(115200);
  // ... other stuff here;
}
  ...

And you run the IDE serial monitor at 9600, you will get gibberish. The same happens the other way round. You need to match the monitor to the baud rate you've defined on the Serial.begin(); call.


Controlling JX PDI-6221MG Digital Servo with Arduino

I managed to get servos running with 6 V and 3 A powered from lab power supply (GOPHERT CPS-1620 0-16V 0-20A). I guess, at the end, it was power supply which was crucial.


Sketch is not being received by Arduino even though Arduino Editor acts like it is finished?

Thank you to all who have suggested corrective action for my posted communication problem. After trying all of the suggestions, I threw up my hands and deleted all evidence of Arduino Create Editor. Next I installed the Arduino Create Editor as a fresh/new install. Magically, all of my communication issues with the Arduino Uno have been corrected. Apparently, something in the communication code was corrupted during my first attempt install on my desktop PC.


Why does my Arduino Nano send the wrong voltage on a digital output PIN?

The microcontoller in an Arduino operates on 5 Volts (or perhaps 3.3 Volts).  An on-board voltage regulator reduces the 12 Volt input to 5 volts for the ICs on the board.

Connecting the pull-up resistor (R1 in your drawing) to 12 Volts may damage the microcontroller (especially if it is really 100 Ohms as your drawing shows).  The pullup resistor must be connected to the 5 Volt pin on the Arduino board.

The output voltage of an Arduino pin should be near 5 Volts, but may be less if you place a heavy (high-current) load on it.


Can you power the ESP8266E-12 with any of the 3.3V pins?

On the nodeMCU board all the 3.3v pins have continuity. That means they all do the same thing. And yes, you can apply ~3.3v to them. I have trouble with voltages under ~2.8 though, 2.5v is likely not going to work.
Use a buck+boost to keep it 3.3v if needed. For cheap dc/dc converters, I strongly prefer ones with XL semi chips; clean enough to please the ESPs.


Since you talk about the watchdog I presume you want timer interrupts. (There are also I/O interrupts, for instance when the level of a pin changes state.)
Like Russell McMahon says the watchdog is not a good source. The ATmega has several timers (8-bit and 16-bit) which serve your exact purpose. Let's view some example code:

// timer interrupts
// adapted from code by Amanda Ghassaei
// June 2012
// http://www.instructables.com/id/Arduino-Timer-Interrupts/

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
*/

// timer setup for timer0, timer1, and timer2.
// For arduino uno or any board with ATMEL 328/168.. diecimila,
// duemilanove, lilypad, nano, mini...

// this code will enable all three arduino timer interrupts.
// timer0 will interrupt at 2kHz
// timer1 will interrupt at 1Hz
// timer2 will interrupt at 10kHz

// storage variables
boolean toggle0 = 0;
boolean toggle1 = 0;
boolean toggle2 = 0;

void setup() {

  // set pins as outputs
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);

  cli(); // stop interrupts

  // set timer0 interrupt at 2kHz
  TCCR0A = 0; // set entire TCCR2A register to 0
  TCCR0B = 0; // same for TCCR2B
  TCNT0  = 0; // initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124; // = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

  // set timer1 interrupt at 1Hz
  TCCR1A = 0; // set entire TCCR1A register to 0
  TCCR1B = 0; // same for TCCR1B
  TCNT1  = 0; // initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624; // = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  // set timer2 interrupt at 10kHz
  TCCR2A = 0; // set entire TCCR2A register to 0
  TCCR2B = 0; // same for TCCR2B
  TCNT2  = 0; // initialize counter value to 0
  // set compare match register for 8khz increments
  OCR2A = 199;// = (16*10^6) / (10000*8) - 1 (must be <256)
  // turn on CTC mode
  TCCR2A |= (1 << WGM21);
  // Set CS21 bit for 8 prescaler
  TCCR2B |= (1 << CS21);
  // enable timer compare interrupt
  TIMSK2 |= (1 << OCIE2A);

  sei(); // enable interrupts

} // end setup

ISR(TIMER0_COMPA_vect){ // timer0 interrupt 2kHz toggles pin 8
  // generates pulse wave of frequency 2kHz/2 = 1kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle0 = HIGH - toggle0;
  digitalWrite(8, toggle0);
}

ISR(TIMER1_COMPA_vect) { // timer1 interrupt 1Hz toggles pin 13 (LED)
  // generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle1 = HIGH - toggle1;
  digitalWrite(13, toggle1);
}

ISR(TIMER2_COMPA_vect) { // timer1 interrupt 10kHz toggles pin 9
  // generates pulse wave of frequency 10kHz/2 = 5kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle2 = HIGH - toggle2;
  digitalWrite(9, toggle2);
}

void loop() {
  // do other things here
}

This sets up 3 different timers: one at 500 µs, one at 1 s, one at 100 µs. For the details about each timer, look up the registers in the datasheet.
With each timer goes a timer interrupt service routine (ISR). These perform the action required when an interrupt occurs. It's a good practice to exit an ISR as quickly as possible. Only do the things which are really time-critical, but for the rest set a flag to indicate that the interrupt occurred. Then in the main loop you continuously check that flag, and when it is set, perform the necessary actions. Don't forget to clear the flag when you're done.


Its because the resolution of the analog read is 10 bits or 1024 discrete values.

In your code the density is basically calculated as:

density = (((5000 / 1024.0) * analog_value * 11) - 400) * 0.2

You can calculate the resolution as:

(5000 / 1024.0) * 11 * 0.2

and you get 10.7421875, which matches your observation.

If your filtering (calculating the average over last 10 values), would calculate and return a float, you would get smoother values.


Unable to send UDP packets while performing OTA update on the esp8266

esp8266 ArduinoOTA library has
  WiFiUDP::stopAll();
  WiFiClient::stopAll();

to ensure undisturbed OTA upload


How to randomize the delay in Arduino Stepper code?

In setup(), add

randomSeed(analogRead(0));

This reads the value of an analog input pin, which if not connected, will float to relatively random values between 0 and 1023. This "seeds" the random number generator so the pattern of random numbers you will get later doesn't always give the same results each time you start the sketch.

In your delay() call, just replace the fixed value with a call to the random(min, max) function, as:

delay(random(10000, 20000));


Set array to array passed as parameter in constructor

_MIDICommnads is declared like this: MIDICommand* _MIDICommands[];.

This is the major error. That is an incomplete array type. The number of elements (and storage) is unknown.

To solve this you have decide on how the elements should be stored. Should the class allocate storage and copy the values given to the constructor or should a pointer to the vector be used.

One alternative is to use a template class and provide the max element size as a template class parameter.

Cheers!


Yes, Chris Stratton is right. A toroidal inductor keeps flux within the core, reduces the external flux to near zero and have near zero ability to grasp/convert external flux/magnetic field into electrical signal. Apparently, the word 'toroidal' was used in loose sense referring to a circularly shaped coil.

In an real-life commercial product, a 125 kHz coil typically has many turns on a very thin wire on an open-air core (no core).

An example profession factory made a 125 kHz RFID with a GitHub Arduino library and photos of an antenna coil:

125 kHz RFID module - UART
Seeed-Studio/RFID_Library
125Khz RFID module - UART (wiki)

Also, see Building RFID Card Reader using PIC Microcontroller.

Note, for higher frequency RFID, not shown in above examples, coils have fewer turns than for 125 kHz.


Pro Mini not communicating with computer

You did set the Serial Port and then tell the Arduino IDE that it's talking to a Pro Mini right?

This gets me every time I switch between my Nano & Uno.

On the main menu
[Tools]->[Board]=>"Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega 328"

I've also had this problem trying to use a longer USB cable, it just wouldn't work.  The stock cable (shorter) worked fine.


ERROR: Timed out waiting for Arduino 101 - anything I can do?

Press the reset button next to the USB port. (either one, the master reset is between the DC jack and USB ).

This will cause the Arduino 101 to reboot and enter DFU mode for 5 seconds if it is connected on USB. The download will proceed when the Curie enters DFU.

The IDE uses a baud-rate signal over USB. It is a virtual serial port, so baud rate doesn't matter. But when the host side (Arduino IDE) switches the baud rate to 1200, the board will reboot and enter DFU mode for download. If it gets stuck for some reason and misses the message to reboot, you can just hit the reset button and accomplish the same thing.


Integrating an analog signal using Arduino Mega 2560

V1=analogRead(A0)*2/1023.0-1.0;

This will give you the voltage across R1 in units of 2.5 V. I do
not know whether you care or not about the units but, if you want the
voltage in volts, then:

the voltage at the Arduino input is analogRead(A0) * (5.0/1024)
to get the voltage across R1, you have to subtract 2.5 V
to get the voltage at the output of the transformer, you have to
multiply by 11.

This could be written as

float V = (analogRead(A0) * (5.0/1024) - 2.5) * 11;

but, in order to minimize the number of floating point operations, you
can simplify it to

float V = analogRead(A0) * (55.0/1024) - 27.5;

You could then integrate the voltage by running it through a function
like this:

static float integral(float x)
{
    static float y;                         // last filter output
    static uint32_t last_sample;            // last time sampled
    uint32_t now = micros();
    float dt = (now - last_sample) * 1e-6;  // step time in seconds
    last_sample = now;
    y += x * dt;
    return y;
}

Now, there is an issue with this approach: the average voltage at the
input of the Arduino is not going to be exactly 2.5 V, because
your resistors R3 and R4 will not have identical resistance. Then the
output of the integral will slowly drift and eventually become
unreasonably large.

One way to mitigate this drift problem is to measure this average using
the same Arduino running the same program: disconnect the mains, see how
the output of the program drifts, and measure the drift rate. Then you
subtract the drift rate from the 27.5 in the code, and fine tune until
there is no drift at all. There is, however, the risk that some time
later it will drift again, due to components changing behavior as the
temperature changes.

A better option would probably be to not integrate, but instead use a
first-order low-pass filter. Such a filter behaves like an integrator
for any signal faster than its cutoff frequency but, unlike a simple
integrator, it has a finite gain at zero frequency. You can turn the
integrator into a low-pass filter simply by changing the line
y += x * dt; into

y += (x - y/tau) * dt;

where tau is the time constant of the filter.


I have found why !!!

1st: buf[8] instead buf[7] in declaration
2nd: reinit byte buf[8] before EC request part.

So the code who works fine is:

byte buf[8];
void loop(){

      Serial.print("pH: ");
      digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
      digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
      byte  pHrequest[] = {0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x85, 0xDB};
      RS485Serial.write(pHrequest, sizeof(pHrequest));
      RS485Serial.flush();
      digitalWrite(modbusModuleRE, RS485Receive);
      digitalWrite(modbusModuleDE, RS485Receive);
      RS485Serial.readBytes(buf, 8);
     Serial.print(buf[3], HEX);Serial.println(buf[4], HEX);

byte buf[8];

      Serial.print("EC: ");
      digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
      digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
      byte  ECrequest[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
      RS485Serial.write(ECrequest, sizeof(ECrequest));
      RS485Serial.flush();
      digitalWrite(modbusModuleRE, RS485Receive);
      digitalWrite(modbusModuleDE, RS485Receive);
      RS485Serial.readBytes(buf, 8);
      Serial.print(buf[3], HEX);Serial.print(buf[4], HEX);Serial.print(buf[5], HEX);Serial.println(buf[6], HEX);

Serial.println();

}


Your HDMI switcher, and your USB to RS-232 converter speak RS-232.  The Arduino speaks TTL UART.

While the concept behind them, and the overall format of the data, is the same there are major differences:

RS-232 uses a ±10V NRZ signalling method, TTL UART uses a 0-5V signalling method
RS-232 uses inverse logic compared to TTL UART

That means that you need to convert the Arduino's TTL UART to ±10V NRZ with inverse logic in order to communicate with the IOGear.

Fortunately that's a simple enough task using a special interface chip. These are readily available and can be bought for tiny amounts as a breakout board or even a full shield if you like (such as this one from Sparkfun).  The chip is known as a MAX232 in its most common form, though other manufacturers may use different letters.

If you pop on eBay (or your favourite budget seller site) and search for "Arduino MAX232 DB9" (the DB9 is the type of plug on the board - the 9-pin D connector) you will get lots of hits to choose from.


You may well have killed the ESP by supplying it 5v, you have to have a logic level shifter, as Juraj says.

Assuming it's not dead then your next problem is there have been posts about that hardware setup and SoftwareSerial doesn't work at high speed. I can't tell you what it is that doesn't work because turning the speed of the link cures the problem, try 9600 maximum.

[Edited to be less accusational, which was not the original intent]

[Update]

Please see the datasheet here:
https://www.mikrocontroller.net/attachment/231858/0A-ESP8266_Specifications_v4.pdf

The table in section 8.4.4 says that the maximum input voltage is 3.6V
Just after that it says all digital pins are "protected from over-voltage with a snap-back circuit". This snap back voltage is typically 6V.  So does that mean the GPIO are safe up to 6V?

(It might be that this datasheet has been superseded, I am unable to access the EspressIF site at the moment).


error using String class to convert a double to a string

I had installed arduino using apt-get and I didnt notice that I had an old version. I upgraded my arduino and it worked fine.


Good quality sound using a microcontroller

One would think that single channel for voice would be enough.  Remember the old Sprint commercials? "So quiet you can hear a pin drop", that was only single channel.  12 bits at 16 MHz for max 8 KHz bandwidth would be good.  Per Wikipedia "In telephony, the usable voice frequency band ranges from approximately 300 Hz to 3400 Hz. It is for this reason that the ultra low frequency band of the electromagnetic spectrum between 300 and 3000 Hz is also referred to as voice frequency, being the electromagnetic energy that represents acoustic energy at baseband. The bandwidth allocated for a single voice-frequency transmission channel is usually 4 kHz, including guard bands, allowing a sampling rate of 8 kHz to be used as the basis of the pulse code modulation system used for the digital PSTN. "

I think several folks, such as Adafruit.com, DFRobot.com, and others make cards with DAC outputs.  Or you could get a DAC only card from Gravitech.us

I started a project at Arduino.cc to sample 16 bits at 44.1KHz, store to SD card, then play it back later. I used external SPI ADC and DAC, and member fatlib16 there helped me to code it.  You can find it by searching "sample, record, playback later" and it should pull it up.


What is the difference betwen “ESP8266Wifi.h” and “WiFiEsp.h” libraries?

It's quite simple:

ESP8266WiFi.h - Runs on the ESP8266 to control the WiFi.
WiFiEsp.h - Runs on an Arduino to communicate with an ESP8266 module with AT commands
WiFi.h - Runs on an Arduino to work with the Arduino WiFi shield.

So the one you want, which is part of the ESP8266 core, is ESP8266WiFi.h.


I would highly recommend using a digital multimeter in this case. They are not too expensive and a must for electrical projects. Most have functions such as checking for shorts. In addition, you can check to see if the pin in question changes voltage when activated. The thing to remember is that heat kills electrical components, and high current causes heat (high power, really, but watch your current and you will be fine) get familiar with the formula v=I/R and don't put too much current through your buzzer or LED. LEDs have very little resistance.


The datasheet says:

  The first ADC conversion result after switching reference voltage
  source may be inaccurate, and the user is advised to discard this
  result.

Then you could try to take each reading twice, looping over four ADC
readings:

Read bandgap with Vcc as reference, discard the value.
Re-take the same, keep the value.
Read A1 with 1.1V bandgap as reference, discard the value.
Re-take the same, keep the value.


That type of LCD has two main modes of operation: 4-bit mode which uses 4 data pins (d4-d7), and 8-bit mode which uses all 8 data pins (d0-d7).

4-bit mode has the advantage of requiring fewer output pins on your Arduino. However, it means your sketch needs to send each command/character as two separate batches of 4-bits (one after the other). This is handled for you automatically by the LiquidCrystal library, so you won't need any extra complexity in your code. However, it does mean that your sketch requires roughly double the number of processor cycles to send anything to the LCD.

In contrast, 8-bit mode sends each command/character as a single batch of 8-bits. That simply means it technically runs a little faster.

With that said, a person looking at the display probably won't see a significant speed difference most of the time, as it still goes very quickly. The main impact will be on the microcontroller (the Arduino in this case). If it can use the faster 8-bit mode then it can devote a little more processing time to other things. That can be particularly helpful for timing-critical applications.


Is there a way to play .mp3 files from an SD card on Arduino?

If you're not specifically trying to make the arduino itself do the decoding and playback, you can get something like the Mini DFPlayer which would let you do essentially what you're asking for and offloads the decoding and playback so your arduino can do something else while the audio is playing.


Noise when running Arduino close to analogue audio circuit

Arduino PWM signal is about 500Hz, so it will be audible (read: noise) by itself. You could implement a low-pass filter between the PWM pin and your J-FET. A simple RC filter tuned to 5Hz would attenuate a 500Hz signal to -40dB, which probably won't be enough for high quality audio. There are filters with better rejection properties which usually require active components to build. One of the simplest of such filters is the Sallen-Key topology, which can practically double the rejection ratio using a signle active component (opamp).

Another option is to use a simple RC filter, but increase the the PWM frequency (as described here) to achieve high rejection ratio. Eventually, increasing the frequency past the audible range (about 16kHz) will ultimately resolve the noise problem, though I would still use an RC filter to keep the J-FET in linear mode. Apparently, the highest frequency you can achieve at full resolution is 62.5KHz, which is more than enough.


Opening a program in administrator with Arduino (DigiSpark/DigiSparkKeyboard)

Looking at the code, the first argument should be the key, and the second the modifiers. So DigiKeyboard.sendKeyStroke(MOD_CONTROL_LEFT + MOD_SHIFT_LEFT + KEY_ENTER); should become:

DigiKeyboard.sendKeyStroke(KEY_ENTER, MOD_CONTROL_LEFT + MOD_SHIFT_LEFT);`


Problems powering standalone arduino with USB powerbank

According to the datasheet, the LM317 needs an input voltage 3v higher than the output. Since 6.3<5, there's not enough margin for the LM317.

You can use an AMS117 LDO @3.3, which only needs an input of 3.9v to operate. I find these modules very handy. If the MCU has some tolerances, you can likely get away with using a diode or two in series with the 5v rail to drop it down; the actual forward voltage fluctuates slightly on load, but it will likely stay in the acceptable range for your MCU.

you can also use a switch-mode regulator, commonly sold as "buck converters" on ebay, to more efficiently reduce the voltage. This is the way to go over linear regulator like the 317 if you power your project from batteries or have concerns about heat. I go through a lot of these style converters, and they seem to work very well.


If you set "Show verbose output during compilation" in your IDE preferences, you'll see a message like the following in the IDE window's lower pane. The part I bolded is the amount of SRAM assigned:

  Sketch uses 2,148 bytes (6%) of program storage space. Maximum is 32,256 bytes.
  Global variables use 204 bytes (9%) of dynamic memory, leaving 1,844 bytes for local variables. Maximum is 2,048 bytes.

You can also include this function and print its result to get the same information on the terminal during run-time:

int freeRAM () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}


Arduino Uno and ESP01: can't issue AT commands [Solved]

Just to have an answer instead of just an edit/addition to the question:

  EDIT: PROBLEM RESOLVED:

  My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.

Ok... sure... your Uno's Atmega384 was talking with pins 0 and 1 to the USB adaper chip (Atmega16u2 on Uno R3) and at the same time to the ESP-01.

Read the fine schematic: Arduino Uno R3


Temperature Sensor not giving proper values

The -127 for your temperature reading is actually the error code for DEVICE_DISCONNECTED_C.
In the library's example code, they put an if that checks for this error code before printing the temperature:
if(tempC != DEVICE_DISCONNECTED_C)
{
  Serial.print("Temperature for the device 1 (index 0) is: ");
  Serial.println(tempC);
}

Since your sensor has only 2 wires, according to Wikipedia, you need a capacitor to power the sensor:

One distinctive feature of the bus is the possibility of using only two wires — data and ground. To accomplish this, 1-Wire devices include an 800 pF capacitor to store charge and power the device during periods when the data line is active.

This should hopefully resolve your issues.


How much current does an Arduino Mega draw from a LiPo battery (5,000 mAh)?

The important thing to realize here is that the capacity of the battery does not affect the amount of current drawn. Your Mega will draw the same whether it is connected to a 1000 mAh battery or a 5000 mAh battery. The larger battery will just last longer.

Tests on my Mega2560 Arduino show that (with no peripherals connected) it draws about 70 mA from a 7V supply, and slightly more (72 mA) from a 12V supply (the voltage regulator has to throw away some of the extra voltage as heat). (However, see below)

The exact amount it would draw in practice would be strongly correlated to what things you have connected. For example, LEDs, motors, shields, other devices.

I have a page about power saving that you might find useful if your objective is to minimize power usage.

Edited to add more about power consumption

It appears that my initial claim that the current consumption goes up with an increase in voltage was wrong. With Majenko's help I made up a detailed set of automated tests, increasing the Mega2560 power input by increments of 200 mV, taking a reading from both the power supply and my multimeter, averaging each one over ten readings, and plotting the results. This is what I got:

The two measurements seem to be consistently different by 0.2 mA. What this shows is that at 7V, the current consumption is 65.3 mA, and at 12 it is 64.1 mA, about a milliamp less.

I do, however, stick by my original assertion that the capacity of the battery will not affect consumption, and a larger battery will just last longer.


What is the difference between file.print() and file.write()

The File class inherits from the Stream class, which in turn inherits from the Print class.

The Serial class inherits from the Stream class, which in turn inherits from the Print class.

print() and write() are defined by the Print class.

So yes, File.print() and Serial.print() are the same, as are File.write() and Serial.Write().


Altering SoftwareSerial to transmit more than 1 byte at a time

So far you have asked a lot of questions about your project which uses SoftwareSerial to send a lot of bits:

How to transmit more than 1 byte continually?
Basic Serial Transmission Protocol
Synchronization and Implementing hamming code on Software Serial
Encoding clock signal into linear block codes
How to fix baud rate when hardware capacity has a low limit?
Unable to tell if error is from receiving or transmitting end
Read function in Software Serial

And now we have another one (this question).

I think you are flogging a dead horse with this. For one thing, what are you trying to achieve, that can't be achieved by just sending the bytes "normally" as 8-bit bytes? The only thing I can think of is a slight speed increase. By trying to make a 1024-bit packet, you are saving some start and stop bits in the middle, that's all.

In some of your other questions you mention 9600 baud, so let's run with that. At 9600 baud one bit is 1/9600 of a second, that is 104.17 µs.

To transmit 1024 bits "normally" you would need 128 bytes, each of which needs a start and stop bit, so the total is 128 * 10 * 104.17 µs = 133.338 ms.

To use your system you need 1024 bits plus one start and stop bit, so that is 1026 * 104.17 µs = 106.878 ms.

So far you have only saved 26.46 ms.

You could save a lot more by simply doubling the baud rate. Or quadrupling it. However SoftwareSerial is less reliable at higher baud rates. Why not use HardwareSerial?

Your next problem is that SoftwareSerial turns interrupts off during reception of one byte, so that it gets the timing right. For an 8-bit byte this means they are off for 10 * 104.17 µs = 1.0417 ms. That's about the limit for turning interrupts off if you want the internal timer to work, the one which gives you millis and micros. If you turn them off for 128 times as long, you can say "goodbye" to knowing how much time has elapsed.

As I mentioned in a comment, too, since serial comms relies on external clocks (that is, both ends have to get the clocking right) you can only afford around a ±2% error in the receiving clock to ensure that we are sampling at the correct place (see the datasheet) for an 8-bit byte. The error tolerance will drop to 1/128th of that if you try to send 128 bytes in a single stream. The crystal/resonator in the Arduino just won't be that good.

Finally, to avoid false detection of the start bit (which you have asked about elsewhere) you need a much longer gap between packets, to ensure that we get the correct start bit. Effectively you need a one-byte length (ie. the incoming data is continually HIGH) for 8-bit bytes. For 1024-bit packets you will need to introduce a gap of 1024 * 104.17 µs = 106.670 ms between packets. This required gap totally wipes out any saving by not sending those extra start and stop bits.


Error "cstddef: No such file or directory" on use AzureIoTHub

Azure IoT is only supported on ESP8266 and ESP32. As stated in the README for the library:

Currently supported hardware:

ESP8266 based boards with esp8266/arduino

SparkFun Thing

Adafruit Feather Huzzah

ESP32 based boards with espressif/arduino-esp32

Adafruit HUZZAH32


Servos not working properly with joystick

The problem, as jsotola pointed out, is that your code writes totally different values to the servos very fast. You don't combine the two values from the joystick, but just overwrite the previous servo value. So this cannot work.

As I interpret your description, you want the x axis to move both servos the same amount in the same direction (in unity), while the y axis determines the difference of position between them. If you move the y axis to one side, the first servo will go a bit clockwise, while the other goes a bit counter-clockwise. When you then move the x axis, both servos will move to the corresponding direction, while maintaining their position difference.

It is better to first write a formula, how you will calculate each servo position from the given joystick values. The above behavior can be described with these formulas:

servo_1_value = mapped_x + mapped_y;
servo_2_value = mapped_x - mapped_y;

Now you have to map the joystick values correspondingly:

mapped_x = map(x, 0, 1023, 0, 180);
mapped_y = map(y, 0, 1023, -90, 90);

Note, that you should change the parameters for mapping y to the values you need. In the above code they are set to the maximum (meaning that moving the y axis to either end will effectively disable the x axis, since the servo cannot move past 0 or 180 degrees).

You don't really need to check, if the value changed. But if you really want to, you should check the calculated values for each servo separately. Something like this:

if(servo_1_value != old_servo_1_value){
    servo1.write(servo_1_value);
}
if(servo_2_value != old_servo_2_value){
    servo2.write(servo_2_value);
}

But you don't really need to check for a change here.


Help - Atmega328p, converting a PWM servo code from pin9 to pin6

PORTB bit 6 is controlled with TIMER0 while PORTB bit 1 is controlled with TIMER1.  Therefore you need to change the timer variables appropriately.  One mistake in your code is that you leave ICR1.  It should be OCRA if you want to use TIMER0.


It appears you are using Linux. In order to communicate you must establish yourself as being allowed to use it, that is the dial out function. "sudo usermod -a -G dialout " should work but you need to log out then back in before it takes effect. After that you are all set.


How do i properly read an analog pin on attiny85?

The improper bush-button event handling is likely to cause the problem. One way to properly react to the external environment signals could be constant polling or using interrupts. With constant polling, all the time is spent on the checking the status of the button. With interrupts, the program is executed as it should, and only if interrupt happens - the execution jumps to the interrupt subroutine, executes it, and goes back to the main code where it left off.

In your case, you can use pin 7, for example, for push button signal. It can have a function of INT0. Read Section 9. Interrupts of the datasheet - it is straight forward.

I do not completely understand what your program should do, but I will try to convey the general approach of using subroutines:

volatile bool pressed = false;
int main(void)
   {
   MCUCR |= (1<<ISC01 |1<<ISC00);       // set INT0 to interrupt on rising edge of pin7
   sei();                               // enable global interrupts

   while(1){
      if (pressed) then do something; //You can disable interrupts here so your code is not interrupted by cli();
      pressed = false; // reset the state
      else do something else;
   // you can re-enable your interrupts here by sei();
   }
}

// only happens when the change on pin 7 is from LOW to HI
ISR(INT0_vect){
pressed = true; // update the pressed status
}

If you want to use pin6 for push button, you should enable the PCINT1 instead of INT0 and change the ISR to handle the PCINT1 interrupt. In this case, pin 6 will react on voltage toggle (from HI to LOW, or the other way) and you can not discriminate rizing/falling edges. In that way, you must read pin6 within the instruction subroutine to know if it is hi or low.

EDIT:

I would suggest to stop the calculations in the Temp() function after the

  average = SERIESRESISTOR / average;

line due to the fact that you have only three operating modes for the LED. Thus you can, back calculate the average value that makes your steinhart value to be, for example >30. This way, all other values greather/smaller than that value will also fall under the same condition depending on whether average/steinhart are directly/inversely proportional.

When you determine the three ranges of raw average values you can use them directly in the Mode() function. Eventually, you can optimize you code even further, by performing monotonic read instead of burst reads. If you keep a buffer, you do only one addition of the most recent sample and subtracting the oldest sample. For this you will need two pointers and one memory for to store sum, but you will not need to do nSamples additions:

read (newSample);
sum += newSample;
sum -= oldestSample;
average = sum/numSamples;
update pointers to the memory for oldest sample and for the feature sample;


Arduino board to control microwave oven?

It's pretty much all proprietary. It can be done, but you'd have to replace all the circuitry with the Arduino, interfacing with the existing magnetic and mechanical devices and doing everything in your own code.

Power level is controlled by PWM, but it's extremely low frequency PWM, on the order of 0.05Hz (20s period). That's why there are two different sounds that come from the microwave when it's not at full power; one when the magnetron is active, and one when it is off.


Getting issues while using SoftwareSerial

SoftwareSerial only works on a few select GPIO pins on the Mega. Specifically those pins that have PCINT on them.

But that is irrelevant. There is no reason to use SoftwareSerial on a Mega except in exceptional circumstances.  You have four hardware UARTs on the Mega, so there is no call to use SoftwareSerial.  Use the real UART pins and objects:

Serial -> RX(0) / TX(1)
Serial1 -> RX1(19) / TX1(18)
Serial2 -> RX2(17) / TX2(16)
Serial3 -> RX3(15) / TX3(14)

Just replace all references in your code to the SoftwareSerial instance with Serial1 (delete the #include and the object instance constructor) and use TX1 and RX1 to connect your module:

String data="true";

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    Serial1.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    if(Serial1.available()){
        data=Serial1.readString();
    }
    Serial.println(data);
    //Serial.write(data);
    delay(2000);
}


How do I specify a particular pin to use as output for the Print class?

You need to do far more than just "specify a pin". You need to write the software that transmits data through that pin in your chosen format.

You cannot send data through a pin. You can only set a pin HIGH or set a pin LOW. It is the sequence (and most importantly the timing) of setting a pin HIGH and LOW that constitutes sending data.

So you have to write the software that sets the pin HIGH and LOW in the right way and at the right time.

Fortunately sending is far simpler than receiving, as you can see if you look at the source code to SoftwareSerial.

Specifying the pin itself though is simple:

class MyClass : public Print {
    private:
        uint8_t _pin;

    public:
        MyClass(uint8_t pin);
        size_t write(uint8_t data);
};

MyClass::MyClass(uint8_t pin) {
    _pin = pin;
}

size_t MyClass::write(uint8_t data) {
    // In here you do whatever you have to in order
    // to manipulate _pin in the right way to send your data.

    // Don't forget to return the number of bytes written (there
    // is only one, so either 1 for "it got sent" or 0 for "it
    // didn't get sent".
    return 1;
}

It can be quite useful to have a begin() function for setting things up, such as configuring the right pinMode() for _pin, and maybe setting a baud rate like Serial does (although for simplicity you may choose to just have a single fixed baud rate, which means you can pre-calculate delay loops etc).


Your logic is flawed. Translating your loop in pseudocode gives
something like this:

if (PIR does not detect OR ANY sonar is out of range) {  // cond. 1
    stop
} else if (PIR does detect AND right sonar is in range) {  // cond. 2
    turn right
} else if (PIR does detect AND left sonar is in range) {  // cond. 3
    turn left
} else if (PIR does detect AND center sonar is in range) {  // cond. 4
    go straight
}

Notice that, if condition 1 is false, then that means that the PIR does
detect AND ALL of the sonars are in range. Which implies that condition
2 is necessarily true. Which implies that the following elses have no
effect. Your code can then be optimized (and the compiler probably did
optimize it) into

if (ANY sonar is out of range OR PIR does not detect) {  // cond. 1
    stop
} else {  // cond. 2 is true if cond 1. is false
    turn right
}

You should rethink your problem asking yourself the following questions:

under what conditions should the robot turn right?
under what conditions should the robot turn left?
under what conditions should the robot go straight?
under what conditions should the robot stop?

Make sure that in any circumstance EXACTLY one of the above conditions
holds true. In other words, the conditions should be mutually exclusive
and cover every possibility. One you have the answers, the coding should
be straightforward.

Edit: Your updated code still contains logic flaws. For example, if
the PIR senses the person and BOTH the left and right sonars are in
range, then you are asking the robot to BOTH turn left and turn right.
Unless it's a quantum robot evolving in an Everett's multiverse, it
won't be able to comply. To the risk of repeating myself, you must
decide on one and only one action for every possible situation.

If you are struggling with that concept, I suggest you start by filling
the truth table below. On each of the 16 lines of the table you should
fill the last column with one (and only one) action among: allStop,
turnRight, turnLeft and straight. Yes, I know it's tedious to
consider all the possible situations one by one, but you must do that
before starting to write the code. Otherwise you end up with completely
broken logic.

+--------+----------+----------+----------+-----------+
| PIR    | sonar 0  | sonar 1  | sonar 2  |  robot    |
| senses | in range | in range | in range |  action   |
+--------+----------+----------+----------+-----------+
|  no    |   no     |   no     |   no     |           |
|  no    |   no     |   no     |   yes    |           |
|  no    |   no     |   yes    |   no     |           |
|  no    |   no     |   yes    |   yes    |           |
|  no    |   yes    |   no     |   no     |           |
|  no    |   yes    |   no     |   yes    |           |
|  no    |   yes    |   yes    |   no     |           |
|  no    |   yes    |   yes    |   yes    |           |
|  yes   |   no     |   no     |   no     |           |
|  yes   |   no     |   no     |   yes    |           |
|  yes   |   no     |   yes    |   no     |           |
|  yes   |   no     |   yes    |   yes    |           |
|  yes   |   yes    |   no     |   no     |           |
|  yes   |   yes    |   no     |   yes    |           |
|  yes   |   yes    |   yes    |   no     |           |
|  yes   |   yes    |   yes    |   yes    |           |
+--------+----------+----------+----------+-----------+


Algorithm to detect motion using ultrasonic sensor

The main blocking part of your code is this bit:

while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
  if((micros() - time) >= 100000) {
    continue;
  }
}

That is saying "While the echo pin is low, check the time.  If too much time has passed then carry on with the loop".

So basically that will loop until the echo pin goes high, regardless of the time.

The continue command means to jump back to the beginning of the loop that it's in, be that a while, for, or do loop.  In this case it jumps back to the beginning of the while loop it's in.

Instead you should consider using break, which means "Terminate this loop and carry on with what comes next".

Ultrasound sensing with pulseIn(), while simple to perform is rarely particularly accurate.  Any interrupts that occur during the sensing will affect the outcome, and it's only as accurate as the micros() function allows it to be.

If you need a more precise and reliable measurement you should consider using one of the Input Capture modules in the ATMega.  I don't know if there is a library to do it off hand, but programming it through the registers shouldn't be that difficult - just read the datasheet to find out how it all works.

Briefly the operation of IC is:

Send trigger pulse
Start IC timer counting
Pulse arrives
IC stops counting automatically and interrupt is triggered
Read counter value and convert to microseconds.
Set flag to indicate a result is available

The timing source is the main system clock and counting happens in the background completely parallel to the operation of the CPU, so nothing can interrupt it or delay it. Even if the execution of the IC interrupt routine is delayed by another interrupt running the counter value will have already stopped incrementing, so it will have been "captured" and give the correct result every time.


Difference between these two relays (D1 Mini Relay Shield and Single 5V Relay)

Ok, so:

I've bought a logic level converter.
Bought another relay.

Now to the results:

With the first relay, no joy with 5v or 3v in any combination (3v on VCC / 3v on IN; 5v VCC / 5V IN; 3V VCC / 5V IN; 5v VCC / 3V IN)
With the second relay (the new one), funny enough.. Didn't work with 5V on VCC and 5V on input. But it did work with 3v on both of them.

I measured every output voltage to make sure everything was working fine and it wasn't a problem with power supply.

I guess it should work with 5v...? Right?

Anyway, it was indeed a faulty relay. And 3V on VCC and Input is what worked for me, even though it is a 5V relay. Thank you all for the assistance.


How does electricity flow in an arduino?

To expand on JRobert's answer, think of the energy as coming from the +5 pin (assuming an UNO, etc), which is like a water tower as source of pressure.  If you open a valve from the water tower, the water will flow under pressure and fall to the ground.  If you put a water wheel (electrical component) in the path, the flowing water will make it turn.  A good example component for your Arduino experiment is an LED with a resistor connected to one lead (the longer one).  A 1000 ohm resistor is a good choice.  Now connect the other lead of the LED to ground and the other end of the resistor to +5.  If the LED fails to light, reverse the LED connections.
That example didn't include a "valve" (switch) to control the flow, which is what the Arduino does. Instead of connecting to +5, connect the resistor to a digital I/O pin.  Now you can program the Arduino to make that pin an output, and to make it high (digital one, which is +5V) or low (digital zero or 0V) to turn the LED on or off.  Carry on from there!


automated parking system (sir sensor+ stepper motor)

When you use delay(), your code stops and dont check anything at all until the delay is over, if you want to check for sensors during a timer, you have to use millis()

There is a lot of documentation and tutorials you can find to replace delay with millis when you know what you are searching for


analogRead Function AC Voltage Reading Capabilities

I guess that you are showing the voltages there directly calculated from analogRead() and that you connected the AC voltage directly to the analog input (and it's ground with the Arduino's ground).

The reference for every communication/voltage measurement/digital input is ground. Naturally the Arduino can only measure voltages inside of it's own supplied voltage range, meaning 0 to 5V for the Uno. If you apply a negative voltage (relative to ground), you will measure a voltage of 0V. You can even damage the microcontroller, if the negative voltage is too high.

If you have negative and positive voltages, you should offset the signal at the analog input pin, so that the resulting signal stays in the range from 0 to 5V. You can do this with a simple voltage divider. Use two resistors with the same value (for example 5kOhm), so that you will get a new zero point at 2.5V. The AC signal will then variate around that value.

For what is happening inside the microcontroller:

The ADC is responsible for measuring the voltage. For this the voltage on the analog input pin will first be sampled (loaded onto an internal condensator) and then step by step compared to the voltages, that the ADC generates by dividing the supply voltage range into 1024 distinct values (10 bit). Again the reference, to which the voltage is measured/compared, is ground. It cannot generate negative voltages, thus cannot compare them.