How to send float numbers from python3 with struct to arduino

There is no way around dealing with serial bytewise, since the communication over serial relies on bytes as a unit. You can write the received bytes directly to the float variable. That is faster, than save them to a char array first:

float f = Serial.read() << 24;
f = ((unsigned long) f) | (Serial.read() << 16);
f = ((unsigned long) f) | (Serial.read() << 8);
f = ((unsigned long) f) | Serial.read();

With this the bytes of the float value have to be send with the order from most significant to least significant. I don't know, how the data is formatted, if you send a struct over python. The casting to unsigned long is important here to do the bitwise OR (unsigned long and float have both 4 bytes). (I tried it and it works for me)

Also be aware, that you shouldn't read from Serial, when there is no received byte in the buffer. You can check this with Serial.available(). If there is no new byte in the buffer the Serial.read() function returns an integer with value -1

EDIT:
The code above works, if you transmit the data directly as byte. In your comment you wrote, that you want to write arduino.write(b"111.32") in python. Here you are transmitting an ASCII string representation of the float number 111.32. This is not as fast as transmitting byte data (since you may need way more bytes for one float than 4). In this case you can use either Serial.parseFloat() to get the float from the serial buffer (but ensure, that all bytes for this number have been received with Serial.available()) or you can save the bytes to a string and using String.toFloat() to get the float out of it.

Since you wanted to do it the fast way, you should transmit the numbers as byte data. To do this in python, have a look at the answer of this question. It explains the python code for it (be sure, that you get the ordering of the bytes the same in python and Arduino).


Creating a product with arduino bootloader

A quick google search found this info on the Arduino Forum which a user kindly shows the rules relating to this stuff.

The Optiboot bootloader is not actually an Arduino 'product'. Boards you design and software you write using Arduino IDE and libraries does not need to be disclosed to anybody, other than having the objects available (probably in a hidden part of your product's support website, in a "firmware" sub section) for some reason relating to being able to build the source against newer versions of Arduino.

I am currently making a product which I intend to use Arduino libraries and IDE and bootloader for fast development, but the board, schematics, and essentially the application code except for the libraries from Arduino will be mine. If you copy or build stuff specifically for/from Arduino hardware, you must(?) release certain source/schematics etc.


The default timeout is 1 minute for DHCP. There is also a response timeout, and in the library millis is used for timeouts. I don't know if there is a timeout for everything, but I suppose there is.

If it stops working when no ethernet cable is connected, that would be a bug. If something like that is in the library, then you have no way to bypass the Ethernet.begin when it took too long. How long did you wait ?

This is the source code for Ethernet.begin: Ethernet.cpp


Can I use custom ethernet shield with standard libraries?

The libraries don't care whether or not you're using a shield, only that you're using a device they support and that you've wired it up how they expect (or that you've modified the library to use the actual wiring you're using). So find a library that supports the ENC28J60 and knock yourself out.


multiple multiplexer (4051) - how to process the inputs?

I have no experience of this chip but I would guess that you would need to connect the child level multiplexer to the output of the parent and use the outputs to drive the address lines.

You could look at an MCP23008 or MCP23016, these are 8 and 16 bit GPIO expanders that you control via I2C.  You can have 8 of the MCP230008 (64 pins) before you need to look at I2C bus expanders (which you can get).  I think its the same for the 16 bit version, but you would need to double check.


How can I change the speed of a stepper motor?

Do you understand how a stepper works?  You send it pulses and it steps for each pulse you send it.  The faster you send the pulses the faster it will run.  The slower you send the pulses the slower it will run.  You have lines in your code like this:

void StepForwardDefault()
{
  Serial.println("Moving forward at default step mode.");
  digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
  for(x= 1; x<4000; x++)  //Loop the forward stepping enough times for motion to be visible
  {
    digitalWrite(stp,HIGH); //Trigger one step forward
    delay(1);
    digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
    delay(1);
  }
  Serial.println("Enter new option");
  Serial.println();
}

Can you see the part that is sending HIGH and LOW to your step pin?  See the delay that is determining how fast those pulses go out?  Can you imagine how you might change that delay so that the pulses go out faster or slower?  Here's a hint, delay works in milliseconds, but if you want to go faster than this then you'll need to work in microseconds.  Can you find the version of delay that works in microseconds in the Arduino reference?


Wrong Mouse.move() output in Arduino Leonardo

I struggled with this too until I realized this

  Parameters

  xVal: amount to move along the x-axis - signed char

  yVal: amount to move along the y-axis - signed char

  wheel: amount to move scroll wheel - signed char

Note it says signed char.

That means the value you pass to the Mouse.move is a signed 8-bit. (-128 to 127)

My work around is this below:

void moveMouse(int x, int y, int w){
  x = (int)x / 1.59; //Adjust these two values accordingly. I found out that 100, 100 does
  y = (int)y / 1.58; //not move 100, 100. It moves 159, 158 for me.

  while(x!=0 || y!=0 || w!=0){
    int moveX, moveY, moveW;
    if(x > 0){
      if(x >= 100){
        moveX = 100;
      }else{
        moveX = x;
      }
    }else if (x < 0){
      if(x <= -100){
        moveX = -100;
      }else{
        moveX = x;
      }
    }else{
      moveX = 0;
    }

    if(y > 0){
      if(y >= 100){
        moveY = 100;
      }else{
        moveY = y;
      }
    }else if (y < 0){
      if(y <= -100){
        moveY = -100;
      }else{
        moveY = y;
      }
    }else{
      moveY = 0;
    }

    if(w > 0){
      if(w >= 127){
        moveW = 127;
      }else{
        moveW = w;
      }
    }else if (w < 0){
      if(w <= -128){
        moveW = -128;
      }else{
        moveW = w;
      }
    }else{
      moveW = 0;
    }

    x = x - moveX;
    y = y - moveY;
    w = w - moveW;

    Mouse.move(moveX, moveY, moveW);
  }


exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'

It seems as if you are missing a parameter in the lcd() call. It seem to take six arguments, not five.

From the Blink example in the LiquidCrystal library:

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

Also, looking at the library definition, from LiquidCrystal.cpp:

class LiquidCrystal : public Print {
public:
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
...
}

The number of arguments accepted by the various overloaded constructors are (respectively):

10
11
7
6

So, your statement:

LiquidCrystal lcd(2,4,5,6,7);

is missing a parameter (or more) as it only has five.

This explains why the error that you are seeing has five ints listed in the parameter list:

'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'


Can I use a camera sensor from a not functioning smartphone in Arduino or Raspberry pi?

Is it possible to ... use the OmniVision_OV16860 camera sensor (on an)
  Arduino?

It is doubtful as bare image sensors usually require specialized software drivers to be of any use. Also, a common Arduino does not have the power to do image processing.  Only the few Arduino's built with unusually powerful processors could handle image processing.  But, at this level, expect little support as most do not do image processing on the Arduino platform.


Reliably measuring the energy consumption of arduino running sketch

programmatic way of measuring t

Not sure what you meant by that but typically you can use a high side current sense amplifier to get a measurement of the current. Then adv a known voltage to get vcc. That known voltage could be the internal reference, if available

In some cases a resistor on vcc can be used to measure current, together with two dividers.


Am I able to connect an anti static wrist strap to the ground pin on the Arduino uno?

I was about to write that I wouldn't do that, but in view of the post I linked to - I am changing my mind.

The point to the wrist strap it to have you, and the thing you are touching, at the same potential (whatever that is relative to the known Universe). Now if you connected the strap to the earth on your power point, that would not achieve anything unless your Arduino was also grounded (eg. via a USB cable).

So using the ground wire on the Arduino sounds sensible enough. Personally I don't usually do that, however if I have moved around (and might have shuffled over some carpet, etc.) I always touch some metal part to ground myself (for example, a metal switch on a lab power supply) and discharge any static that might have built up by moving around on the floor.


Quite often such situation occurs when the display does not reset properly (the reset from the IDE does not necessarily reset the display!).

So, once the sktech has been uploaded to the board, I would first try to do a reset on the Uno board (using the RESET button). If that doesn't do the trick, I would recommend to make the contrast adjustable (all my LDC displays showed "black boxes in the upper row" on delivery and I had to ajust the contrast).

If that also has not the desired effect, there is no alternative to debugging your code. Without the code itself, we cannot guess what might be wrong.


Without any sketch, I tried to send AT command from serial monitor, and nothing happened.

The problem is with your connections to the Uno. Although it seems wrong, the correct connection when you're using the Uno as a USB-serial adapter to communicate with the A7 AI Thinker module from Serial Monitor is:

Uno                A7
TX (pin 1)   ->    TX
RX (pin 0)   ->    RX

The RX and TX markings on the Uno refer to the pins on the ATmega328P microcontroller. But you're not using that microcontroller, you're communicating between the USB-serial chip on the Uno and the A7. The RX line of the USB-serial chip is connected to the TX pin of the ATmega328P and thus to pin 1, the TX pin of the USB-serial chip is connected to the RX pin of the ATmega328P and thus to pin 0. For this reason the connection between the Uno and A7 shown above are actually an RX-TX, TX-RX connection between the USB-serial chip and the A7.

If you were communicating between the ATmega328P on your Uno and the A7 then the connections you used would have been correct.


What makes this library work exclusively with Atmega328P boards?

That library relies mostly on Timer 1 and, as you already noticed,
the Timer 1 of the ATmega32U4 is very similar, if not identical, to
the one of the 328P. At least similar enough to expect the library to
work identically.

I took a look at both datasheets and the only difference I can see that
can possibly affect the library is the pinout. The pins relevant to the
library are:

       328P  32U4
ICP1 =  PB0   PD4
OC1A =  PB1   PB5

The pinout of the 328P is hardcoded into the library. CPPM.h contains
these lines:

#define CPPM_ICP1 8 // Input Capture Pin of Arduino UNO is pin 8 - ICP1 (Atmega328 PB0)
#define CPPM_OC1A 9 // Output Compare Pin of Arduino UNO is pin 9 - OC1A (Atmega328 PB1)

CPPM.cpp has two instances (here and here)
of this:

if ((PINB & _BV(PINB1))) // rising edge ?

If you change the code in these three places to match the pinout of the
32U4, I would expect the library to work for you.

You could also change that conditionally as

#ifdef __AVR_ATmega32U4__
    ...
#else // assume ATmega328P
    ...
#endif

in order to make the library compatible with both MCUs, and then submit
a pull request to the original author.


Edit: Chris Stratton rightfully points out that the question is
about a double, not a float:

a float is four bytes in every platform I know about, as per the
IEEE-754 standard
a double is eight bytes in almost all platforms, with the notable
exception of AVR: the AVR double is highly non-standard, four bytes
long, and essentially equivalent to float

Most, but not all Arduinos, are AVR-based.
In the following I assume you are talking about AVR doubles, i.e.
floats. If this is not the case, then just replace the array of 4 bytes
by an array of 8 bytes.

Original answer:
A float is four bytes, so it is somewhat equivalent to an array of
four unsigned chars, i.e. to unsigned char[4]. You can use this
equivalence with an union. For example, the following function will
send a float byte by byte:

void ble_write_float(float x)
{
    union {
        float f;
        unsigned char c[4];
    } data;

    data.f = x;
    ble_write(data.c[0]);
    ble_write(data.c[1]);
    ble_write(data.c[2]);
    ble_write(data.c[3]);
}

Notice that this will send the bytes in whatever is the natural order of
the sending processor. If it's an AVR (like most Arduinos), this will be
LSB (least significant byte) first. You have to make sure that this is
what the receiver expects.

Following Ignacio Vazquez-Abrams' suggestion, for sending a random float
you could just send four random bytes. However, it may be wiser to have
an idea of the random distribution you want for your float, and use
things like random() and map() to achieve that distribution. Using
four random bytes, you get a very wide distribution (all the possible
floats are equally likely) which includes weird things like denormals,
infinities and NaN (literally meaning “not a number”).


Trying to map a room with Arduino controlled bot

This is actually quite a complex thing to achieve. I'll give some suggestions, though this is not something I have attempted (yet).

The main thing to do is divide the room up into a grid. The resolution you choose (X and Y dimensions) depends on how small your robot is, how big the room is, and how much memory your have available (on an Uno that's not much at all).

The second thing you need to do is work out a way of determining exactly where in the room you are. That could be done by trying to get as close to the bottom-left corner as possible before starting to map.

Now you can work from square to square (you could do with some encoders to know how far you have driven, and a magnetometer so you know which direction you are facing) using whatever method you like to decide which way to go, and in each square you look to see which of the squares around you are accessible. From that you can work out which way you can go from that square.

As you go you maintain a map in memory of all the squares you have been to, and the squares that you cannot get to. Note that it may not be enough to say "You can't get to square 4,3" - instead you may to keep a more detailed list (depending on what your obstacles are). "You can't get to square 4,3 from square 4,2, nor 3,3, but you can get to it from square 5,3" for example (e.g., a thin obstacle that only blocks entry to that square from certain sides).

Since your sensors cover longer ranges than just one square (unless you have big squares) you can work out how far away an obstacle is, and mark the square it's in before you even get close to it. The square immediately preceding it on a path between it and you would be the "you can't get there from here" square.

Now you can work out paths and routes to get to the squares you need to so you can cover all the available floor.


How to transmit characters or just use xbee like serial monitor

XBee cannot send negative integers, as it is working in hexadecimal and it has range between 0-255


Trying to run Timer1 in ATmega2560 with assembly

Here:

ldi r20, 0b00000010 ; CTC mode, int clk;
sts TCCR1A, r20
ldi r20, 0b000000101 ; prescaler /1024
sts TCCR1B, r20

you are setting the bit WGM11 on TCCR1A. The timer then runs in mode 2 (PWM, Phase Correct, 9-bit) rather than mode 4 (CTC).


Turn off the second builtin Nodemcu 0.9 led

See this link which shows your second LED exactly (the image is for v1.0, I have v0.9 and the code below works just the same in this situation):

'Onboard LEDs? NodeMCU's got two!':

https://lowvoltage.github.io/2017/07/09/Onboard-LEDs-NodeMCU-Got-Two

Quote:

  ESP-12 LED Blink:

 void setup() {
        pinMode(2, OUTPUT);     //Initialize GPIO2 pin as an output
 }

 void loop() {
   digitalWrite(2, LOW);   // Turn the LED on by making the voltage LOW
   delay(1000);            // Wait for a second
   digitalWrite(2, HIGH);  // Turn the LED off by making the voltage HIGH
   delay(2000);            // Wait for two seconds
 }

Or write it like this (ie. using 'D4' rather than '2'):

  ESP-12 LED Blink:

 void setup() {
        pinMode(**D4**, OUTPUT);     //Initialize GPIO2 pin as an output
 }

 void loop() {
   digitalWrite(**D4**, LOW);   // Turn the LED on by making the voltage LOW
   delay(1000);            // Wait for a second
   digitalWrite(**D4**, HIGH);  // Turn the LED off by making the voltage HIGH
   delay(2000);            // Wait for two seconds
 }

Regards, Geoff


Switch 230V 50Hz using a digital out pin

The good advice to people asking how to drive a relay to control mains voltage is: don't.

Start with a complete solution such as those from PowerswitchTail.com and sold by many places:  Powerswitch Tail

You can get these already built or in kit form.  The 20 $ price is small price compared to damage to people or home you might incur with a home built solution.


Since it has two possible positions, and three pins, you have a connection between pin 1 and 2 when position 1 is selected, and between pin 1 and 3 when position 2 is selected.
As BSF comment below, the middle pin is common. This means it will be connected to the outside pins depending on where the switch is moved towards.

However, you always can verify this, in the following way:

To find out which is pin 1, pin 2 and pin 3, use a multimeter. Set it to continuity mode, or if you don't have that mode, to resistance mode, and put the red/black probes to two random pins. Check if the resistance is 0, in that case you know those two pins will be connected when position 1 is selected. If there is resistance, try other pins with the probes, until you know which are connected.

Than switch the position, and do it again.

Instead of a multimeter you also can 'hardwire'  it to e.g. 5V -> pin 1, pin 2 -> resistor of 220 ohm -> LED -> GND
And change pin 1 and pin 2 until you found which pins connect for which positions.

To use it for you Arduino, check for a normal simple switch example, but these are two in one, one for each position.


PUT request: PHP code to Arduino HTTPClient

I got clue from @esoterik answer and manage to send request successfully.
The problem were in adding header parameter:

 http.addHeader("Content-Length",  "20");

This duplicate the header( 2nd one added in PUT method). I just comment it and the code works.
Thanks for every one response


One thing that immediately jumps out at me is you are trying to power the servo from a digital pin.  That is very very wrong.

The servo must be powered from the +5V pin (or +3.3V pin if it's a 3.3V servo) and only the "pulse" pin is connected to an Arduino's PWM capable IO pin.

Also, I don't know how the "Threads" library works, but it looks to me like it's not real threads, but a "round robin" execution of function with time delays.  If one of your functions never returns (like your servo one) then the whole system will lock up.  You need to make your servo function non-blocking like your LED functions.  Give it a 15ms time setting and only move one step of the servo each time it gets called.

Ok, according to comments and research I can confirm that in fact the Thread library is really badly named.  It doesn't run threads, it just runs different functions at different times.  Those functions MUST be "single shot" - i.e., they MUST complete before anything else can happen.  There is absolutely no concurrency whatsoever.  It is entirely up to you to ensure that all your "threads" are fairly simple repetitive operations which are to be run at specific points in time.

Basically the operation is thus:

Add a function and its time to a list.
Work through the list to find a function whose time has expired
Call that function
Continue through the table
Go back to the beginning

If you have two functions both with the same time then one function will be called first and execute to completion, then the other function will be called afterwards, to execute to completion.  Only when a function returns is the system able to move on to the next entry in the function list.

You must not use delay() in your "thread" functions for anything more than maybe 1-2ms of delay in total.  You MUST return from your thread with enough time for your next timed event to execute, otherwise it will be delayed, or never run at all.

So your servo thread would look something like this:

Add my current "direction" to the servo value
If the servo value < 0 or > 180 then invert the direction and limit the value to 0-180.
Write the value to the servo

That is then triggered every 15ms by the thread library.

So as real code it may look like:

void runServo() {
    static int direction = 1; // 1 = up, -1 is down
    static int value = 0;

    value += direction;
    if ((value <= 0) || (value >= 180)) {
        direction = 0 - direction; // Change direction from + to - or - to +
    }

    value = max(min(180, value), 0); // Clamp it to between 0 and 180

    servo.write(value);
}


Measuring resistance conceptually and in code?

you cant control current output to a pin BUT you know a pin output 5V (if using a 5V a arduino, 3.3v in other case).

Then what you need is a know resistence resitor, so you can set up a voltage divider and then read the resulting voltage with an analogRead. That give you a 10bit precision value that you can easily translate to a voltage, and then use the formula on the linked page to find R1 or R2 (depends on how you wired up your know resistor)


How to read Ultrasonic sensor value to use and drive servo motors

First, I would make sure I have continuous servo motors that can rotate 360 degrees. Your servos will just rotate to the degree you entered if they are not continuous. Additionally, it would be more helpful if you named your pins. For example:

int echo = 7;
void setup(){
    pinMode(echo, INPUT);
}

This will help us read the code better.

I also see that you have "pulseIn" in your if statement. You must save the value to a variable with the data type of unsigned long.

//before the setup
unsigned long duration;

//keep your setup as it is

void loop(){
   digitalWrite(8, LOW);
   delayMicroseconds(2);
   digitalWrite(8, HIGH);
   delayMicroseconds(10);
   digitalWrite(8, LOW);

   duration=pulseIn(echo, HIGH);

   if(duration<=400){//check for the value
       // turn LED on:
        digitalWrite(13, HIGH);
        // turn the motors off for 2 seconds
        motor1.write(90);
        motor2.write(90);
        delay(2000);
        //turn motor 1 on for 2 seconds to make a turn
        motor1.write(180);
        delay(2000);
   }else{
        digitalWrite(13, LOW);
        //motors run when vehicle is not near objects
         motor1.write(0);
         motor2.write(180);
       }
   }

Overall: check your servos and save the value of pulseIn to a variable. You might also want to convert to centimeters by dividing duration by 58.2.


Arduino IDE Board Selection for 32u4 on custom PCB

There should not be any difference, However you would need to load the ItsyBitsy bootloader instead of the ProMicro Bootloader. Personally, I use the Pro Micro Bootloader on my 32u4 Boards.

The only difference would be in the size of each bootloader, one may be smaller and give you more actual codespace. Other than that there should be no performance difference because your code runs independently of the bootloader.


This is your circuit.

I think you can take it from here by looking at the diagram, but please note that e.g. 1 0 0 0 0 will light up 3 and 1, so be careful.

To show more than one, turn on multiple LEDs in rapid succession. It will give the effect that more than one are on. This is known as multiplexing.

Update:

After Googling around, I understood it better. I also wrote this code.

int IO1 = 50;
int IO2 = 48;
int IO3 = 46;
int IO4 = 44;
int IO5 = 41;
int del = 1000;

void setup() {

  pinMode(IO1, INPUT);
  pinMode(IO2, INPUT);
  pinMode(IO3, INPUT);
  pinMode(IO4, INPUT);
  pinMode(IO5, INPUT);
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
    displayLED(1);
    delay(del);
    displayLED(2);
    delay(del);
    displayLED(3);
    delay(del);
    displayLED(4);
    delay(del);
    displayLED(5);
    delay(del);
    displayLED(6);
    delay(del);
    displayLED(7);
    delay(del);
    displayLED(8);
    delay(del);
    displayLED(9);
    delay(del);
    displayLED(10);
    delay(del);
    displayLED(11);
    delay(del);
    displayLED(12);
    delay(del);
    displayLED(13);
    delay(del);
    displayLED(14);
    delay(del);
    displayLED(15);
    delay(del);
    displayLED(16);
    delay(del);// light up LEDS 1, 2 and 3.
}

void displayLED(int a){
    clear();
    if (a == 1){o(1); o(2); h(1); l(2); Serial.println('1');}
    if (a == 2){o(1); o(2); l(1); h(2); Serial.println('2');}
    if (a == 3){o(1); o(3); h(1); l(3); Serial.println('3');}
    if (a == 4){o(1); o(3); l(1); h(3); Serial.println('4');}
    if (a == 5){o(2); o(3); h(2); l(3); Serial.println('5');}
    if (a == 6){o(2); o(3); l(2); h(3); Serial.println('6');}
    if (a == 7){o(2); o(4); h(2); l(4); Serial.println('7');}
    if (a == 8){o(2); o(4); l(2); h(4); Serial.println('8');}
    if (a == 9){o(1); o(4); h(1); l(4); Serial.println('9');}
    if (a == 10){o(1); o(4); l(1); h(4); Serial.println(10);}
    if (a == 11){o(3); o(4); l(3); h(4); Serial.println(11);}
    if (a == 12){o(3); o(4); h(3); l(4); Serial.println(a);}
    if (a == 13){o(3); o(5); l(3); h(5); Serial.println(a);}
    if (a == 14){o(3); o(5); h(3); l(5); Serial.println(a);}
    if (a == 15){o(4); o(5); l(4); h(5); Serial.println(a);}
    if (a == 16){o(4); o(5); h(4); l(5); Serial.println(a);}

}

void clear(){pinMode(IO1, INPUT);
  pinMode(IO2, INPUT);
  pinMode(IO3, INPUT);
  pinMode(IO4, INPUT);
  pinMode(IO5, INPUT);}

void o(int o){
    if (o == 1){pinMode(IO1, OUTPUT);}
    if (o == 2){pinMode(IO2, OUTPUT);}
    if (o == 3){pinMode(IO3, OUTPUT);}
    if (o == 4){pinMode(IO4, OUTPUT);}
    if (o == 5){pinMode(IO5, OUTPUT);}
}

void h(int l){
    if (l == 1){digitalWrite(IO1, HIGH);}
    if (l == 2){digitalWrite(IO2, HIGH);}
    if (l == 3){digitalWrite(IO3, HIGH);}
    if (l == 4){digitalWrite(IO4, HIGH);}
    if (l == 5){digitalWrite(IO5, HIGH);}
}

void l(int h){
    if (h == 1){digitalWrite(IO1, LOW);}
    if (h == 2){digitalWrite(IO2, LOW);}
    if (h == 3){digitalWrite(IO3, LOW);}
    if (h == 4){digitalWrite(IO4, LOW);}
    if (h == 5){digitalWrite(IO5, LOW);}
}


programming STM32 with arduino IDE issues

others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.

As the pinout diagram you included in the question yourself shows, PA11 and PA12 provide the USB interface.

You can't use those pins for both USB and other GPIO roles at the same time.

Your Arduino core and add-on bootloader are presumably using the USB port for programming and communication with the host PC.  Custom projects which did not use the pins for USB would be possible, but you'd likely be largely on your own and unable to use those particular Arduino components (or at least not without heavily modifying them).

There are other pins which have key purposes, too, for example those which support external clock crystals, those which provide the SWD debug interface, those which could provide serial UART output, etc - some designs can use these as generic I/O's but only by forgoing the unique functionality which many designs need them to provide.


I just tried this with my ESP32Cam with no problems.  I would check that you are supplying enough power; I've definitely seen the 'Camera capture failed' when I had power issues.  Also, I would try a more recent tutorial on the ESP32Cam; the latest Expressif ESP32 Arduino libraries have AI Thinker ESP32Cam as a device choice.  I would try the CameraWebServer example in the ESP32 library and see if you still have the problem.


Splitting the power source between an arduino and a servo

If you have a 7V to 12V - 2A regulated supply, you can directly power your board using the 2.1mm connector. Do not go above 12V or you may destroy the voltage regulator on the board.

If you have a 5V to 6V - 2A regulated supply, you can supply your servo with this supply and rely on USB to supply the rest of the board (make sure you have a common ground for both the USB and the regulated supply).


Before using libraries, try to see whether you can manipulate the timer registers directly to achieve what you want.  You may find it is easier!

In the following example I assume you are using an ATmega328 chip.  The code may be slightly different for other microcontrollers.  In that case you can read the data sheets for both microcontrollers and work out what you need to change.

I also assume the data you want to transmit is stored in a byte array.  Initialize the data how you prefer.

e.g: byte my_data[10] = {0,0,0,0,0,0,0,0,0,0};

Next, you want to initialize timer1 in the main loop

TCCR1A=0;
TCCR1B=0;

To send data at 2000 bits per second, the following settings can be used

ICR1=124; // Timer counter resets to 0 after reaching 124
OCR1A=125;
OCR1B=125; // other counter match registers must be higher than ICR1
TCCR1A=B00000010; // waveform generation mode 14, fast PWM, ICR1=top
TCCR1B=B00011011; // clock scaler 64, 1 count = 4 us.  125*4 us = 500 us
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags

This will set the timer1 match register bit ICF1 every 500 us.  There are several ways of using the timer to send the data.  My preference would be to poll the match flag.  The timing precision is about as good as you can get - a couple of clock cycles:

loop_until_bit_is_set(TIFR1,ICF1); // wait until TCNT1=ICR1
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // clear match flags
// switch digital output high or low depending on data bit to be sent

One way is to run a state machine loop like this:

unsigned int state;

void setup(){
state=0;
}

void loop(){
switch (state){
case 0: // idle or receiving data to be sent
TCCR1A=0;
TCCR1B=0;
// insert other code here
// conditional function, when message data received, set state=1;
break;

case 1: // setup timer
ICR1=124; // Timer counter resets to 0 after reaching 124
OCR1A=125;
OCR1B=125; // other counter match registers must be higher than ICR1
TCCR1A=B00000010; // waveform generation mode 14, fast PWM, ICR1=top
TCCR1B=B00011011; // clock scaler 64, 1 count = 4 us.  125*4 us = 500 us
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
state=2;
break;

case 2:
loop_until_bit_is_set(TIFR1,ICF1); // wait until TCNT1==ICR1
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // clear match flags
// switch digital output high or low depending on data bit to be sent

// add conditional function so that when you are finished sending data, reset to state=0;
break;

}
}

As always, please upvote if you find this helpful.


ESP-12e - RX/TX pins flickering on boot when used as GPIO pins

According to this reference, GPIOs 1 and 3 have dedicated behaviour during boot (debug output or pulled high) which can not be disabled in your sketch.
You have to either choose different pins or implement an additional circuitry.


Some libraries I find good (opinion-based):

TaskManagerIO: https://github.com/davetcc/TaskManagerIO

does a good job at managing events / scheduling things for a certain (system) time, or even repetitively.
with that you could e.g. use a scheduleFixedRate() API to call a function every 60 minutes. Then starts the power up (I assume asynchronously, by setting a pin or something), and just primes the scheduler with the scheduleOnce() API to call another function in 15 seconds. That target function then starts the warmup and schedules the next function / step for 60 seconds into the future, et cetera. It would express the flow very naturally.

If accurate timekeeping is needed so that it's really every hour, you might want to  use an external RTC module. Also depends on the microcontroller you're using, many have a builtin one that you can feed with a 32.768 kHz crystal and thus you don't need an external chip

library for the DS3231 / DS3232 RTC lets you set an alarm in the RTC: https://github.com/JChristensen/DS3232RTC/blob/master/alarm-primer.md
with that you can e.g. set an alarm for every 60 minutes and then execute your task.


I wanted to post an update in April 2021 on the status of this question.
The SIM800L will work in the US, but T-Mobile is the only carrier that it can interface with. AT&T shut down its compatible towers in 2017. T-mobile will shut down its 2G network at the end of 2022.
So, the SIM800L is only good for another year and a half. Maybe you're better off finding a different module!


The code instantiates two instances of the SevSeg class.  This may or may not work.  Really depends on if the class uses any resources are not meant to be shared between multiple instances of that class.  For instance, it is unlikely that one hardware timer can be used for more than one purpose at a time.

But the code continues on to use the same (anode) pin resources for both instances of the class. This is likely not going to work.

Apologies for being vague using qualifier like "unlikely" instead of simply stating that it will not work.  Truth is, one might be able to write a class that can deal with multiple instances of its self.  But it would be very difficult and a far more complex programming task than to simply use one instance for all 8 digits.

In case there is a question as to the maximum number of digits supported for one instance of the SevSeg class, this line is in the one of the SevSeg header files:

#define MAXNUMDIGITS 8 // Can be increased, but the max number is 2^31


Basic if endif not working and I'm puzzled

You can't use commands like receivers++ outside of a function.  That is runtime executable code, and has to be run from inside a function. Global scope doesn't get executed in the same way as code in a function.


How to control Neopixel LEDs in parallel?

It will not be easy to “re-wire the LEDs [...] and still have everything
work without rewriting any code.” Those LEDs are not that smart, and the
only way to address them is by the order in which the color data is sent
through the data line.

What you can do, however, is write the code is such a way that rewiring
requires only a minimal change in the code. I would use an array to
map the LED indices to their labels. Something like this:

const uint16_t LED_COUNT = ...;

// Map LED indices along the strip to hex labels.
const uint8_t ledLabels[LED_COUNT] = {
    2, 2, 2, 2,  // LEDs 0 to 3 are labeled "2"
    8, 8, 8, 8,  // LEDs 4 to 7 are labeled "8"
    // etc...
};

Then, assuming your LED strip is declared as follows:

const uint8_t LED_STRIP_PIN = ...;
Adafruit_NeoPixel ledStrip(LED_COUNT, LED_STRIP_PIN);

the “function whose arguments are a label value and an RGB value, and
which turns all LEDs of that label value to the given RGB value” can be
quite easily written:

// Turn all the LEDs sharing that hex label to the given color.
void setHexColor(uint8_t label, uint32_t color)
{
    for (uint16_t n = 0; n < LED_COUNT; n++)
        if (ledLabels[n] == label)
            ledStrip.setPixelColor(n, color);
    ledStrip.show();
}

Now, if you rewire the strip, you just need to update the ledLabels
array and recompile. If you can manage to send that information to your
Arduino while it's running (a serial connection, an IR link, an SD card
inserted in an appropriate socket, whatever...), then you could even
have a procedure where the Arduino updates the array itself. Obviously
the const qualifier should then be removed. But you now have to devise
a way to “tell” the Arduino about your wiring.


I don't know what voltages inductive proximity sensors use, but in general it's inexpensive to use  3.3V–5V logic level converter modules.  These typically are bi-directional interfaces that use an N-FET and pullups to the two supply voltages to interface different-voltage logics.
See the "Bi-directional level shifters" section of the TAKING IT TO ANOTHER LEVEL: MAKING 3.3V SPEAK WITH 5V article at hackaday.com for a circuit explanation.  See gearbest.com and sparkfun.com and Adafruit for inexpensive modules.

Note, for finding small screws in carpet, a search coil as used in a metal detector might be a better choice than a proximity sensor.  The coil is part of a tuned LC circuit; metal near the loop detunes the circuit slightly, producing a tone by heterodyning.


"ptr2" != "prt2"

You have a typo there.


DC motor with slow speed to actuate mirrors

DC motors are made for spinning. Trying to spin it in sub full revolution steps is not really possible. But you can use a geared DC motor, where the rotor after the gear is slow enough for your purpose. Also this can give you enough torque for moving the knob (since small DC motors are often rather weak by their own). You can find geared DC motors with many different values (torque, voltage, speed, gear ratio, size...) at the typical online sellers. The small ones are rather cheap, so you might just buy some and test out, whats fitting for you. Otherwise you would need to set exact requirements for torque and speed (and maybe other parameters) and then search for a fitting one.
Also keep in mind, that you need something like a driver circuit for the motor. Since you will want to drive it in both directions, a H-bridge is needed. You can build those yourself with transistors, or buy a small chip, which incorporates the complete H-bridge (make sure to use one with MOSFETs in it, since they are more efficient). Also don't forget the flyback diode to avoid killing the electronics with the induction voltage from the motor.

I should use a coupler to interface the motor with the knob, basically some joint to connect the shaft to a 2mm Hex bar or something: could you suggest a way to do so?

Yes, you need some kind of coupler. But we cannot really suggest something here. It depends totally on your exact setup. This mechanical part will be something, that you have to design. There are different kinds of couplers available online, but I don't know, if they are good for your purpose.
Also maybe you should make sure to make the coupler flexible on the other axes than the rotation axis. That way the motor will not stall when a small disalignment happens, and the vibrations from the motor might not get transmitted to your mirror as much. I know this principle from my 3D printer, which uses a coupler like this one:


The first and most smart solution is to use a switch between the batteries and everything else. This way, you slide the switch in the off position and the whole circuit is completely detached from the batteries: power consumption: 0.

If you can't (because, for instance, you want it to automatically power off after a while) you can use a transistor (PMOS, for instance) instead of the switch. you have then to put a complementary transistor (NMOS) on its gate, then a button in parallel to it. Just another passve component is required: a resistor (value e.g. can be 100k). When you press the button, the circuits becomes momentarily powered on. You will have to pull the nmos gate to a logic 1 with the atmega to keep the circuit powered. When you want to turn everything off, pull the pin to a logic 0 and your circuit will immediately shut down.

If, third solution, you want to give the atmega complete control over the powering, it needs to be always on. You can then omit the complementary transistor and use a reverse logic on the pin (so 0 = on, 1 = off) and then you can do whatever you want with the power (turn on and off whenever you want).
edit: as a comment suggests, it can be better to put a resistor to set the appropriate voltage on the gate at power up. Even if the commenter told to put a pull-down, I suggest you to put a pull-up (pull-down = normally on, pull-up = normally off). edit 2 as Paul suggested, there could be cases in which you need to be able to turn on and off automatically the circuit, and then store it for longer times without consuming battery. In this case it could be a good idea to put something (a mechanical switch, a jumper, a detachable wire) to completely detach the battery even from the arduino (even if, in this case, you can just remove the batteries from the housing).

Here is a small paint-made sketch to show the solutions. If you have any questions just ask ;)

EDIT: If you want to let the atmega control the power, you'll have to give him a way to do so. Which means.. You should use a pin. If you want you can use safely the RX and TX pins, as long as you don't enable the serial interface. If you need more pins, you can try to optimize your pins usage (for instance using a 4:1 multiplexer for the buttons you will have 2 control pins and 1 input, for a total of 3 pins, instead of 4), even if I think that the best solution is to use a port expander. for instance in the past I used the MCP23017, which has a I2C interface, or the MCP23S17, with a SPI interface. You will have to use the serial interface you choose (I2C: 2 pins - SCL and SDA, SPI: 4 pins - MISO, MOSI, SCK, SS, but they are the same pins used for programming), and then you will have 16 more pins for your uC

EDIT BY foivaras:

The same result can be achieved utilizing an NMOS instead of a PMOS.This would have an advantage over PMOS solution if power line was >5v and arduino was powered by a dc to dc converter. On this scenario, PMOS solution would need one more transistor to work.
Notice that the NMOS has to be placed on the low side of the power line and it will cutoff the power to joystick and lcd with 0v  and enable the power with 5v on its gate.(See 4th image)

COMMENT BY fra87

This solution is not a valid alternative in my opinion. Usually interrupting ground is a bad idea, because usually the rest position of the I/O pins is ground: if you interrupt the ground for the LCD, for instance, you will have +5V on the VCC pin, and a floating ground, but you will have 0V on all the I/O pins, possibly damaging the internal circuits. Moreover having a floating ground is bad in terms of noise protection.

The only advantage COULD be in the particular case explained by the editor, which is a DC/DC converter powering the arduino but not the LCD and the Joystick. This is a strange setup, though, and the proposed solution is better at a first glance (requires one less transistor), but is wrong. For instance, let's suppose the joystick is powered at 12V. If you detach the ground, the joystick will "shut down", which means that all its pins will float up to 12V. This means that on the arduino pin you will see 12V: you can damage it.

So, in the end, I discourage this solution. The only case when you can need it is when you are in a hurry and do not have any feasable PMOS: even in this case, however, I suggest you to replace the NMOS with a PMOS as soon as possible.

Just one more note: edits to the posts, in my opinion, should be done to improve the quality of the answer, by better formatting the content, removing orthographic errors and so on. If someone needs to add some comments or other solutions, it's better to use the comments or add another answer to the thread


I2C connection freezes Master if Slave disconnects

There is code inside the standard library that loops waiting for certain interrupts to complete transmission. If the transmission fails in the middle it can hang.
See my page about I2C. On that page I mention that there is an alternative library. That is written a bit differently so it times out if the transmission doesn't complete in time. An alternative download to the library is here - I2C_Rev5.zip - 6.6 KB.

As hinted by KIIV in a comment, maybe you don't have pull-up resistors. Make sure that you have pull-up resistors from both SDA and SCL to the +5V line. A reasonable value would be 4.7k (each).

Example code

would like a few more examples to show a similar setup to replace my current requestFrom

Borrowed from my page about I2C I am using the same slave code as on that page.
Slave
#include <Wire.h>

const byte MY_ADDRESS = 42;

// various commands we might get

enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2,
    CMD_READ_D8 = 3
    };

char command;

void setup()
  {
  command = 0;

  pinMode (8, INPUT_PULLUP);
  pinMode (A0, INPUT);

  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

void loop()
  {
  // all done by interrupts
  }  // end of loop

void receiveEvent (int howMany)
  {
  command = Wire.read ();  // remember command for when we get request
  } // end of receiveEvent

void sendSensor (const byte which)
  {
  int val = analogRead (which);
  byte buf [2];

    buf [0] = val >> 8;
    buf [1] = val & 0xFF;
    Wire.write (buf, 2);
  }  // end of sendSensor

void requestEvent ()
  {
  switch (command)
     {
     case CMD_ID:      Wire.write (0x55); break;   // send our ID
     case CMD_READ_A0: sendSensor (A0); break;  // send A0 value
     case CMD_READ_D8: Wire.write (digitalRead (8)); break;   // send D8 value

     }  // end of switch

  }  // end of requestEvent

The above code responds to requests to send one of:

Its ID (0x55)
An analog reading (A0)
A digital reading (D8)

Master using Wire library
The master from my page was this:
#include <Wire.h>

const int SLAVE_ADDRESS = 42;

// various commands we might send
enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2,
    CMD_READ_D8 = 3
    };

void sendCommand (const byte cmd, const int responseSize)
  {
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (cmd);
  Wire.endTransmission ();

  Wire.requestFrom (SLAVE_ADDRESS, responseSize);
  }  // end of sendCommand

void setup ()
  {
  Wire.begin ();
  Serial.begin (115200);  // start serial for output

  sendCommand (CMD_ID, 1);

  if (Wire.available ())
    {
    Serial.print ("Slave is ID: ");
    Serial.println (Wire.read (), DEC);
    }
  else
    Serial.println ("No response to ID request");

  }  // end of setup

void loop()
  {
  int val;

  sendCommand (CMD_READ_A0, 2);
  val = Wire.read ();
  val <<= 8;
  val |= Wire.read ();
  Serial.print ("Value of A0: ");
  Serial.println (val, DEC);

  sendCommand (CMD_READ_D8, 1);
  val = Wire.read ();
  Serial.print ("Value of D8: ");
  Serial.println (val, DEC);

  delay (500);
  }  // end of loop

Master using I2C library
The beginTransmission() ... write() ... endTransmission() have been replaced by simply write() and the requestFrom() by read() like this:
#include <I2C.h>

const int SLAVE_ADDRESS = 42;

// various commands we might send
enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2,
    CMD_READ_D8 = 3
    };

void setup ()
  {
  I2c.begin ();
  I2c.timeOut(100);  // milliseconds
  Serial.begin (115200);  // start serial for output

  I2c.write (SLAVE_ADDRESS, CMD_ID);
  byte id;

  if (I2c.read (SLAVE_ADDRESS, sizeof id, &id) == 0)
    {
    Serial.print ("Slave is ID: ");
    Serial.println (id, DEC);
    }
  else
    Serial.println ("No response to ID request");

  }  // end of setup

void loop()
  {

  I2c.write (SLAVE_ADDRESS, CMD_READ_A0);

  byte buf [2];
  int val;
  if (I2c.read (SLAVE_ADDRESS, sizeof buf, buf) == 0)
    {
    val = buf [0] << 8 | buf [1];
    Serial.print ("Value of A0: ");
    Serial.println (val, DEC);
    }
  else
    Serial.println ("No response to CMD_READ_A0 request");

  I2c.write (SLAVE_ADDRESS, CMD_READ_D8);
  uint8_t digitalVal;
  if (I2c.read (SLAVE_ADDRESS, sizeof digitalVal, &digitalVal) == 0)
    {
    Serial.print ("Value of D8: ");
    Serial.println (digitalVal, DEC);
    }
  else
    Serial.println ("No response to CMD_READ_D8 request");

  delay (500);
  }  // end of loop


The only things you have at your disposal are what is in lsusb -v. Using those you can craft a udev rule to create a symlink to a unique device name. I do that with all my boards so that they all get a unique name.

Here is one of my rules:

ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0042",
  ATTRS{serial}=="95336333635351F091B1", KERNEL=="ttyACM*",
  MODE="0660", GROUP="plugdev", SYMLINK+="board/arduino/mega2560"

That links /dev/board/arduino/mega2560 to whatever /dev/ttyACM* node got created when it was plugged in.  That is in /etc/udev/rules.d/50-boards.rules

More on udev here: http://playground.arduino.cc/Linux/Udev

A useful command is udevadm info -a -n /dev/ttyACM0 which lists all the attributes for that device which you can then use in the udev rule.


Passive buzzer works with analogWrite(), but not with digitalWrite(). It also has constant static noise

To sound a passive buzzer, use Arduino tone() function. If you set the pin HIGH the piezo surfaces are pulled together (or pulled away). It is what makes one click but nothing more. To make a tone the input must oscillate at right frequency. PWM is one way how to do a beep. Use tone() function to generate tones of desired frequency.

Your analogWrite(255) is PWM at 1/4 of full on, because max analogWrite value on esp8266 is at default 1023. So it makes a nice beep with 255.

If you use a speaker or passive piezo with esp8266 you can expect noise generated by WiFi operations. I set the pin as INPUT after tone() to eliminate the noise.


How to use a DC buck converter to regulate Uno R3 input voltage?

The barrel jack needs 9-12 V, the internal voltage regulator of the Arduino will reduce this to 5 V.

Since you only supply 5 V, there is a loss in the internal voltage regulator why you probably get only 3.5 V.

And after applying 7 V, probably some (sub) system gets less than the necessary voltage, or there are occasional 'downspikes' lower than 5 V.

The default adapter that you use for supplying voltage to the Uno, also is 9V-12V. Also, check the polarity.

See the following link for more info:

What adapter


Standard Practice for including custom library in examples folder

You can use either. There is no "standard".

When using a raw C compiler there is a difference between the two as regards the order in which directories are searched for files to include, but with the Arduino that is completely irrelevant, so either can be used.

Personally I use <...> for libraries and "..." for header files that form part of the sketch.  It makes for easier identification of which is which, and conforms to the C standard of <...> for system-installed headers, and "..." for local headers.


Does millis() conflict with the PWM pins associated with timer 0?

They do not conflict as millis() strictly reads the immediate value in TCNT0 whereas PWM via timer 0 uses the hardware's ability to compare the value of TCNT0 with the values in OCR0x without affecting the value of any of them.


It depends on what you want to do overall.

Using the HC-SR04 works roughly like this:

you generate a strobe on a pin for a minimum amount of time, and this strobe is understood by the sensor as "emit the ultrasound signal"
then you somehow (more on this later) measure how much time passed between your strobe and a change of level on another pin from the sensor - this is how the sensor notifies you that there was an echo and it has returned.
finally, you convert the time measured into distance, using a conversion algo (typically multiplying by a certain factor) that is specific to the sensor.

Mostly the problem revolves around point #2: how to measure the time elapsed between command (strobe) and answer (change of level).

You have various options, each with pros and cons:

busy looping: it's easy to implement, very straightforward and works right away. The problem is that your arduino will do just that.
polling: it's a less aggressive version of polling, where you check the values every now and then. It lets you do more, but the drawback is that in the worst case the line changes level right after you have checked it, so it will be noticed only at the following iteration. The period used for checking is the maximum error you will get.
GPIO interrupt driven: this is harder but lets your arduino do many other things, while not loosing precision (I'll detail it separately)
HW backed: the AVR on UNO has the ability to capture events: basically there is a timer running that will stop when it gets triggered by a certain event (ex: the change of pin level cause by the echo). It is very precise, but you are limited by the number of HW blocks available on the AVR (3 iirc).

Now about the sub-cases of the GPIO interrupt-driven solution:

EXT based: the ATMega328p present on the UNO has what are called external interrupt sources, which is a fancy way to say that if you configure correctly a pin, the processor will notice when the pin voltage level changes and do something about it (in your case, take a time measurement) - this is quite generic solution, but unfortunately it works only on 2 pins, so you are out of lack with your 3 sensors, unless you implement some scheme where you multiplex 2 or more sensors on only one pin.
Pin-change-interrupt based: on AVR most of the PINS are grouped in ports. Each port contains maximum 8 pins and is labelled with a letter (A, B, C, ..). The way this interrupt works is roughly like the EXT type, but with a catch: you will get an interrupt whenever any of the pins that you have enabled on a certain port will change. In your case you could allocate only one sensor on a certain port, so that it would be obvious that if you get an interrupt for that port, it will be because of that sensor.

So now you can see why I said "it depends". If all you want to do is to get the information about proximity, you can go with busy-looping/polling.

But if you decide later on to do more on the same arduino, be aware that you might have to come back to the implementation of the ultrasonic sensor.

Finally, there is a library for this, but its implementation will fall into one of the cases i mentioned before, so be aware that the same catch applies: at some point you might want to do something that conflicts with the library.

Other points worth mentioning, that you should consider in your design (at least experiment with them):

orientation of the sensors: will they interfere with each other?
timing: do you need/want to activate them all simultaneously or do you prefer to have them activated in sequence?


I may have a personal bias for the concept of finite state
machine. I find that some many problems become so easy when ween
approached from this perspective...
Let me rephrase your requirements, just to make sure I understood
correctly:

If the buzzer is OFF:

it should turn ON if the input rises (goes from LOW to HIGH)

If the buzzer is ON:

it should turn OFF if the input falls (goes from HIGH to LOW)
it should also turn OFF if the reset button is pressed

Or, as a state diagram:

Or, as code:
bool buzzer_is_on;  // state variable

void loop() {
    bool input_rises = ...:
    bool input_falls = ...;
    bool reset_pressed = ...;
    if (buzzer_is_on) {
        if (input_falls || reset_pressed) {
            digitalWrite(BUZZER_PIN, LOW);
            buzzer_is_on = false;
        }
    } else {  // buzzer is off
        if (input_rises) {
            digitalWrite(BUZZER_PIN, HIGH);
            buzzer_is_on = true;
        }
    }
}

Now, the trick (which I leave as an exercise), is to properly detect
when the input rises. This is not the same as the input being HIGH: if
the user presses reset, the buzzer should turn OFF, but it should also
stay OFF, even though the input remains HIGH. Hint: you not only have
to read the input, you also have to remember the state you saw the
previous time you read it. Or you can search “edge detection”.
Note that you do not need edge detection for the other transitions: you
can turn the buzzer OFF when the input goes LOW, but you can also turn
it OFF when the input is LOW. It should not make a difference.


Why? And how do I receive desired output? getBytes docs

The String member function getBytes() will null-terminate the string. You must add space for that.

  byte user1[17], user2[17], pass1[17], pass2[17];
  ...
  user1str.getBytes(user1, sizeof(user1));
  ...
  Serial.print((char*) user1);

That should do the trick.


Measure small capacitances with ATtiny85 (Digispark board)

The reason this doesn't work is that PB5 is pulled high (as it's used as -RESET pin on the board). The code can be rewritten to use only one ADC pin though.


I am running 1.6.5, but the folder says 1.6.3?

1.6.5 is the version of the Arduino IDE.

1.6.3 is the version of the Arduino SAM Boards package that you have installed.

  Does this mean there is a hidden 1.6.5 folder that I am not seeing?

Library/Arduino15 is where your preferences.txt file and Boards Manager index files are stored. Library/Arduino15/packages is where hardware packages installed via Tools > Board > Boards Manager are stored. The Arduino IDE will be located elsewhere on your hard drive. If you need to find it here is an easy way:

Tools > Examples > 01.Basics > BareMinimum
Sketch > Show Sketch Folder - this will open the Examples/01.Basics/BareMinimum subfolder of the Arduino IDE installation folder.

  BTW, this issue surfaced...

That's off the topic of your question and already answered in a comment on your question so I will refrain from answering it.


Can Arduino be used as an FDTI Programmer?

Yes. Tie the reset pin on the ISP connector low to keep the ATmega328P in reset, then you can connect pins 0 and 1 to the ESP module to communicate using the Uno's USB-UART bridge. Since the pins are labelled from the perspective of the '328P, connect TX to TX and RX to RX.


I guess that what you want is a descending sort algorithm, but in the case of Fibonacci numbers you can take advantage that they are already sorted at the beginning. Here are different strategies that you can try :

/*
  SORTING IN DESCENDING ORDER
*/

const int nbElem = 15; // 24 max
int fibonacci[ nbElem ] = { 0, 1 };

void createFibonacciArray( int inputArray[], int arraySize )
{
  fibonacci[ 0 ] = 0;
  fibonacci[ 1 ] = 1;
  for( int i=0; i<nbElem-2; i++ )
    fibonacci[ i+2 ] = fibonacci[ i ] + fibonacci[ i+1 ];
}

void displayArray( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize; i++ )
    Serial.println( inputArray[ i ] );
}

void displayArrayReverse( int inputArray[], int arraySize )
{
  for( int i=arraySize-1; i>=0; i-- )
    Serial.println( inputArray[ i ] );
}

void reverseArray( int inputArray[], int arraySize )
{
  for( int i=0; i<nbElem/2; i++ )
  {
    int fTemp = fibonacci[ i ];
    fibonacci[ i ] = fibonacci[ nbElem-i-1 ];
    fibonacci[ nbElem-i-1 ] = fTemp;
  }
}

void inverseBubbleSort( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize-1; i++ )
  {
    for( int j=0; j<arraySize-1-i; j++ )
    {
      if( inputArray[ j ] < inputArray[ j+1 ] )
      {
        int temp = inputArray[ j+1 ];
        inputArray[ j+1 ] = inputArray[ j ];
        inputArray[ j ] = temp;
      }
    }
  }
}

void bubbleSort( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize-1; i++ )
  {
    for( int j=0; j<arraySize-1-i; j++ )
    {
      if( inputArray[ j ] > inputArray[ j+1 ] )
      {
        int temp = inputArray[ j+1 ];
        inputArray[ j+1 ] = inputArray[ j ];
        inputArray[ j ] = temp;
      }
    }
  }
}

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

  // Create and display Fibonacci array
  createFibonacciArray( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI ARRAY\n" );
  Serial.print( "===============\n" );
  displayArray( fibonacci, nbElem );

  // Solution 1: Display array starting from the end
  Serial.print( "\n\nFIBONACCI ARRAY STARTING FROM THE END\n" );
  Serial.print( "=====================================\n" );
  displayArrayReverse( fibonacci, nbElem );

  // Solution 2: Reverse array
  reverseArray( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI REVERSED ARRAY\n" );
  Serial.print( "========================\n" );
  displayArray( fibonacci, nbElem );

  // Solution 3: Inverse bubble sort array
  createFibonacciArray( fibonacci, nbElem );
  inverseBubbleSort( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI SORTED IN DESCENDED ORDER WITH BUBBLE SORT\n" );
  Serial.print( "====================================================\n" );
  displayArray( fibonacci, nbElem );

  // Ascending order sort array
  bubbleSort( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI SORTED WITH BUBBLE SORT\n" );
  Serial.print( "=================================\n" );
  displayArray( fibonacci, nbElem );
}

void loop()
{}


Arduino Uno (master) and ATTiny85 (slave) I2C connection not working

I modified your Uno sketch slightly to add a delay:

#include <Wire.h>

#define SLAVE_ADDR 0x50

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

void loop()
{
  Wire.requestFrom(SLAVE_ADDR, 1);

  if (Wire.available())
  {
    byte byteReceived = Wire.read();
    Serial.println(byteReceived, DEC);
  }

 delay (1000);
}

Upon testing, it worked perfectly!

23
23
23
23
23
23
23
23
23
23
23
23

I suggest a wiring error. Check you have:

Uno    ATtiny85
--------------------
A4      pin 5  (SDA)
A5      pin 7  (SCL)
+5V     pin 8
Gnd     pin 4


Arduino stops working when servo makes a few rotations

Ground loops can be bad.  Do follow up as suggested in the comments regarding ensuring the power supply grounds are the same. To be specific, connecting the power supply grounds through the Arduino is a bad idea! The trace size should not be assumed adequate for the unknown amount of current passing between the ground outputs of the power supplies.  And a voltage potential can develop causing the processor to behave unexpectedly or worse burn out components.
Also, consider that some Arduino platforms regulate power to 5 volts on the board and that many servos run fine at 5 volts. If this is true here, you could greatly simplify and possibly solve the describe problem by using a single 5 volt power supply.
Lastly, ensure there is a pull up on the 2 inputs connected to the (assumed) normally-open-momentary-contact switches.  There are none in the diagram.  So it is assumed pull ups have been activated in the code such as explained here.


Need Help to implement MODBUS TCP Master over Atmega32 MCU

So if you want to the atmega as client this means it will start the conection and made the request for values, so translating into modbus words your atmega will be a modbus master and the solar will be a modbus slave.

first you need a way to interface the micocontroller to the tcp/ip stack. you can use an ic or arduino shield which has this ic like a w5100 or enc28j60.

then you can write a library over tcp sockets to start the comunication or change some from the arduino.

https://www.google.com.br/url?sa=t&source=web&rct=j&url=http://myarduinoprojects.com/modbus.html&ved=0ahUKEwj9zMvjiYDTAhXJkpAKHfsNBz0QFggpMAE&usg=AFQjCNEfRhDgPGJNK-IUqrUw1FXEnBcxwQ&sig2=Xs0JNEWi_F_XiPgkTQdy-w


Does a moisture sensor need warm-up time?

Photograph of the YL-69 Sensor  :

Most of this content was generated by :  Conner Wolf

Basically, that sensor works by measuring the resistance between the two "pins" of the PCB stake. It does this by applying a voltage across the pins, and measuring the current flow. So, the intention is that more water means less resistance, means less voltage, and a fall in the voltage sent to the ADC of the processor.

However, this is also going to lead to the metal from one of the pins being eaten away by galvanic action (electrolysis).

The other pin is likely to have accumulation of materials rather than being eaten away.

This electrolysis and coating of the pins results in a change in surface area of the pins and causes resistance measured to change (for the same given moisture content).

If you want to squeeze as much life out of the thing as possible, there are a few things you can do.

DO NOT leave the sensor powered. When you want to take a reading, power the sensor for maybe a few seconds, and take your readings. Then power it off again. Don't take readings too often.
Periodically reverse the pins of the electrical connection between the readout board and the "stake" board. Since only one terminal will be eaten away at a time, this should spread the decay out a bit.
Be aware that ANY mechanical disturbance of the "stake" board will probably cause a large shift in readout value. Your "jiggling the wires" causing a shift in values probably came from the mechanical force transmitted to the PCB through the wiring.

An improved version for this sort of thing use a AC bias on the sensor, which minimizes galvanic corrosion. AC bias reverses the voltage applied to the sensor, attempting to eliminate electrolysis on the sensor.

Higher Quality soil moisture sensors use capacitive sensor, and therefore make the sensor immune to the corrosion issue, but are much more complex and expensive.


Thin battery to power arduino micro with nRF8001?

I think you should use a 3.7v mini battery that are around 200-300mAh capacity. These batteries are variable on online stores and are very thin. Now as you require 5v there are mini DC-DC boost converters available what you can use with them.


Since no other code is posted, I am going to guess that you're performing a loop on months[], which has 13 elements (last one is NULL).

You are likely also trying to walk the days[] array (or some other array), which only has 12 elements.

Since days[] or the other (not pasted) array doesn't have 13 elements, you're probably overriding a critical bootloader memory which causes a crash.


How can Arduino know that the number in a variable is a pin number and not something else?

Yes, a variable is just somewhere to store some data.

It's what you do with the variable that is important.

For instance:

int ledpin = 13;
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);

That will set the variable ledpin to 13, then the next line will query the ledpin variable to find out what number it is, then pass that number to the pinMode function to set the mode of the pin to OUTPUT. The line after then does the same thing but passes the number 13 that it read from ledpin to the digitalWrite function to turn the LED on.

However, if you do this:

int ledpin = 13;
pinMode(ledpin, OUTPUT);
ledpin = 10
digitalWrite(ledpin, HIGH);

then it will act just the same at first, but the digitalWrite function will get the number 10 not the number 13 since the value in ledpin has been changed to 10 in the third line.

Remember: an integer is just a number - it's only when you do something with that number that it has any meaning.


Value keeps incrementing even though loop has terminated, why?

Here:
void awakeLoop(){
  double delta;
  // The rest of the function body...
  delta = 0;
}

delta is being defined as a variable local to the function awakeLoop()
and with automatic storage. This means the variable is created whenever
the program enters the function, is not implicitly initialized, and is
destroyed when the function returns.
The last statement delta = 0; has no effect, as it is setting a
variable that is going to be destroyed right away. The compiler most
likely got rid of it.
You most likely want the variable to retain its value across invocations
of the function. For this to be the case, it has to be either global
(defined outside the function) or local with the static qualifier. In
both cases, it will have static storage, i.e. its lifetime will be the
whole program run. Also, if you fail to explicitly initialize it, the
compiler will implicitly initialize it to zero.


Writing new functions into progmem after main program is burned

First, I keep hearing that you can't write to progmem at runtime. But
  isn't that what a bootloader does?

Indeed. My understanding is that non-bootloader code cannot write to
the Flash, except on the smallest AVRs. You may need to check the
datasheet of your target MCU.

  Second, once a user program ends, I should return to the OS.

You could require for the user programs to be linked against a library
you provide. Just implement void exit(int status) in that library and
it will automatically override the version from avr-libc.


RC servo misbehave using arduino and MPU6050

At the end two pull-up resistors and one capacitor solved the problem.

I followed instruction here:

http://www.instructables.com/id/Brushless-Gimbal-with-Arduino/step3/Using-the-Accelerometer-and-Gyro/

Now it works well.. Thank you all.


Arduino have the Wire Library that communicate with I2C.

  This library allows you to communicate with I2C / TWI devices. On the
  Arduino boards with the R3 layout (1.0 pinout), the SDA (data line)
  and SCL (clock line) are on the pin headers close to the AREF pin. The
  Arduino Due has two I2C / TWI interfaces SDA1 and SCL1 are near to the
  AREF pin and the additional one is on pins 20 and 21. As a reference
  the table below shows where TWI pins are located on various Arduino
  boards.

Board   I2C / TWI pins

Uno, Ethernet    A4 (SDA), A5 (SCL)
Mega2560 20 (SDA), 21 (SCL)
Leonardo 2 (SDA), 3 (SCL)
Due  20 (SDA), 21 (SCL), SDA1, SCL1

You can take a look at , this examples.

Like @TheDoctor said:

  The I2C data lines both need resistors to 3.3V. This keeps them from
  drifting if they are disabled. Andy resistor value should work, but it
  is recommended to use one between 10k ohm and 47k ohm.


Issues with Arduino UNO printing repeated "double" on serial monitor

As Majenko and DataFiddler already stated in the comments, you are reading the Serial interface in the wrong way, because you seem to misunderstand a specific point involving the interface.
The Serial (UART) interface knows only of individual bytes, which are send asynchronously over the lines. It does not have any context of a full packet or message. When you type in some data into the Serial Monitor and then press "Send", the data will be send, but not as one big bunch of data. The individual bytes are delayed.
The first delay comes with the nature of the interface itself, as you send with a limited baudrate. With a baudrate of 9600 the Arduino is way faster, than the bytes can arrive. So when you first get a result higher than zero from Serial.available(), the rest of the message is not yet received. Thus with your current code you would only process only the first part of the message.
The second delay comes with the fact, that you and the Serial program on your PC cannot control, when exactly each byte is send. Thats done by the driver. So it might happen, that there is a small gap between 2 bytes somewhere in your message. You cannot mitigate this without writing your own driver and you cannot predict this.
So, what to do now? You should read data, when it is available, and put it into a buffer. And only, when a full message was received, you should process the data. Now you need to know, where the end of a message is. Mostly a delimiting character (like the newline character \n) at the end of the message is used. So you read, if available, and only process the message, when you have read the delimiting character. Something like this:
unsigned int buffer_pos = 0;
char buffer[50]="";

void loop(){
    if(Serial.available()){
        char c = Serial.read();
        if(c == '\n'){
            buffer[buffer_pos] = '\0'; // End the message as C string with a null character
            // process the message here
            buffer_pos = 0;
        } else {
            buffer[buffer_pos] = c;
            buffer_pos++;
        }
    }
}

buffer holds the message. buffer_pos is the current position in the buffer. We terminate the message with the null character, to get a valid C string in the buffer. After processing the message, we set the position back to zero, to receive the next message. When you send data from your PC, you need to make sure, that the message is ended with the newline character.
Now you are independent on when exactly the data is send.

DataFiddler stated in the comments, that without a delimiting character you can simply delay for enough time, so that the data has enough time to arrive. He also stated, that it is ugly. It is a bad coding style. A long delay will impact the responsiveness of your program, while a short delay may give you problems with longer messages. So I suggest, that you directly use the correct way to read the Serial interface. Then you don't have such pitfalls.


I have been playing with an ESP8266 over the last couple of days with similar results. My conclusion was that it is very timing dependent.

If you build in (fairly large) delays into your code then you will find it works better. The delays are effectively what you are doing as you type in each new command.

I found, for example, that the AT+CWJAP (join access point) command takes quite a while, like 10 seconds or so.

Preferably don't use "actual" delays because they are blocking (unless you don't care about that). You could have a list of commands you want to send, and a system that pulls the next one out of the list when a certain time has elapsed.

If you use something like 5 to 10 second delays between commands you should get better results. At the very least, after sending one command, look for a confirmation string from the device (eg. OK, ERROR etc.).


Phase and frequency correct PWM mode Arduino Mega 2560

You wrote:

  TIMSK4 |= (1<<OCIE4A);

and then never defined ISR(TIMER4_COMPA_vect). As soon as you get a
compare match, you get a bad interrupt, which defaults to resetting your
program and restarting again from reset vector.


Which sources of randomness are available?

Whether you need a source of random noise depends on whether your project needs to not run repeatably. Most experiments - Monte-Carlo simulations, for example, benefit by being able to be re-run. In those cases, you need to be able to re-use the seed, and having an non-reproducible seed (and thus, experiment) is a disadvantage.

If you really need something that runs differently each time you run it, then a seed derived from user reaction time, or from some kind of electrical noise, even reading analog values from a floating input pin, should give you plenty of non-reproducibility.


Relay switching problem with ATmega328P + 10 relays

I can see lot of problems.

No decoupling capacitors on ATMega.
Capacitors on both sides voltage regulators are usualy essential for regulator stability.
Big voltage drop on regulator - if it's overheating, thermal shutdown might happen. For example 7V drop @ 350mA (about four relays) results into 2.45 Watts turned into heat.
Bare HC06 doesn't like 5 Volts on its 3.3V logic level input
Xtal oscilator usualy requies two capacitors (22pF) for better stability.


attiny85 reset itself instead of wakeup procedure

I found this, I can confirm it is working. on digispark attiny85.

void sleepTillChg() {  // 0.02ma drain while sleeping here
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT0);                   // Use PB0 (was PB3) as interrupt pin
    // Turn off unnecessary peripherals
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    ACSR |= _BV(ACD); // Disable analog comparator

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep ... Zzzz

    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT0);                  // Turn off PB0 (was PB3) as interrupt pin
    sleep_disable();                        // Clear SE bit
    sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
    // This is called when the interrupt occurs, but we don't need to do anything in it
}

credits should go
https://www.instructables.com/id/3-Minute-Game-Timer/


Arduino: Error: 'PubNub' was not declared in this scope

It turns out my Arduino IDE could not find PubNub.* files until I manually added them as a Library.


How to get the signal strength of the network connected with the ESP8266

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

  AT+CWLAP     // list available access points

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

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

where "APs are sorted by channel and values are: (security, "name", signal strength, MAC, channel) where for security: 0 = open, 1 = WEP, 3 = WPA, 4 = WPA2".

Thus you can use AT+CWJAP? to obtain the name of the network you're connected to and get the signal strength from the respective item in the list provided by AT+CWLAP.

See http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module for a reference of commands.


How to make a dynamic menu with a sub-menu ( Arduino mega or Arduino Uno)

I will skip the RFID part, that is unrelated to the menu.

What you can do is creating two variables:

int menuLevel1 = 0;
int menuLevel2 = 0;

Assuming you have 2 levels, if you have more levels consider an array.

Now you can print the screen based on the values of these two variables (use a switch statement for menuLevel1 which calls new functions, each with their own switch statement for menuLevel2.

Note there are more solutions, but this is a rather simple solution.

The RFID scanner just changes the values, so going to a different menu screen.

A slightly different solution is to not use numbers, but an enumeration (or one for the main level, and x for the second level etc). This can add up, so you can also use a single enum value (with one entry per possible menu page).

The last example looks like:

enum EMenuPage
{
   StartPage,
   MainMenu,
   FirstMenu,
   DisplayX,
   SetY,
   …
}

enum EMenuPage _menuPage;

Displaying like:

switch (_menuPage)
{
case StartPage:
   // Fill LCD with start page
   break;

case …

And when an RFID messages comes in:

if (RFID... == Back)
{
  _menuPage = MainMenu;
}
else …


How to / is it possible to change Vendor Name in ESP8266-12E?

No. The Vendor Name is associated with the OUI.  The OUI is the first three parts of the MAC address.

The OUI's are all registered with IEEE here and Espressif's entries are:

18-FE-34   (hex)        Espressif Inc.
24-0A-C4   (hex)        Espressif Inc.
24-B2-DE   (hex)        Espressif Inc.
2C-3A-E8   (hex)        Espressif Inc.
30-AE-A4   (hex)        Espressif Inc.
3C-71-BF   (hex)        Espressif Inc.
54-5A-A6   (hex)        Espressif Inc.
5C-CF-7F   (hex)        Espressif Inc.
60-01-94   (hex)        Espressif Inc.
68-C6-3A   (hex)        Espressif Inc.
80-7D-3A   (hex)        Espressif Inc.
84-0D-8E   (hex)        Espressif Inc.
84-F3-EB   (hex)        Espressif Inc.
90-97-D5   (hex)        Espressif Inc.
A0-20-A6   (hex)        Espressif Inc.
A4-7B-9D   (hex)        Espressif Inc.
AC-D0-74   (hex)        Espressif Inc.
B4-E6-2D   (hex)        Espressif Inc.
BC-DD-C2   (hex)        Espressif Inc.
C4-4F-33   (hex)        Espressif Inc.
CC-50-E3   (hex)        Espressif Inc.
D8-A0-1D   (hex)        Espressif Inc.
DC-4F-22   (hex)        Espressif Inc.
EC-FA-BC   (hex)        Espressif Inc.

The ESP8266 does not advertise the vendor. The router / other device maintains a list of OUI to Name mappings (on Linux it's stored in /usr/share/ieee-data) and uses them to create a pretty display.

You would need to

Change the ESP8266's MAC address somehow
Subscribe to IEEE and pay the relevant fees
Be allocated an OUI
Hope that every device in the world that would ever talk to your hardware updates its OUI mappings (which they seldom do).


Look for Master and Slave code with error for a Arduino Mege

I am not sure that I understand what you are planning to build. From the Internet I see that a "10c Sim" is a flight simulation program. Therefore I assume you plan to build some hardware, like flight stick and throttle, to provide the necessary input to the PC on which this sim program runs.

The number of digital i/o and analog inputs you mention is not true for "each Arduino" but only for an Arduino Mega.

To expand the number of i/o pins you could add another Arduino, but this makes the programming (much) more complicated. You could set them up as master and slave, where the master tells the slave which output to perform and the slave tells the master which input came in. Or you can split-up the total system into two subsystems where each Arduino has his own responsibilities to handle it's part of the system. In order not to lose many i/o pins to the connection between both Arduino's, the connection between the two Arduino's has to be serial.

But there are better possibilities to extend the number of i/o-pins. IC's (chips) exist wit a serial input and a number of (parallel) i/o pins. A special case of this are the IC's working with I2C as the serial connection. Look at Google for "i2c port expander".


Set interrupts that are not GPIO or Timer in ESP32

There is no such thing as an "interrupt on a value changing" since that is something that only exists in software, and interrupts are things triggered by hardware.
All you can do is check the value in loop() and send the data if the value is above your threshold. If you want to wake from sleep then you will have to do that periodically through other means.


How can one use the SPI hardware on the Arduino Nano?

Yes, the Nano supports SPI when used with a modern Arduino version, and no, you do not have to do anything special to utilize it on this board.

The information you found that seems to suggest something to the contrary is simply a result of the fact that that the web page for the Nano is sadly out of date date and does not reflect the current state of the Arduino libraries which support SPI on this processor and hence board.

In terms of components, the Nano it is very nearly just a form-factor shrink of the discontinued Duemilanove, and in the current version updated to an an ATmega328p it has capabilities essentially comparable to an Uno, differing primarily the in the USB interface which has nothing to do with SPI.

In terms of what is wrong with the web page, if we examine archive.org's records for the page of the comparable Duemilanvoe, on September 15th, 2010 it said:

  SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication, which, although provided by the underlying hardware, is not currently included in the Arduino language.

But a few days later on September 26th, 2010 it had been changed to say:

  SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication using the SPI library.

Although the page for that once-flagship product was updated to reflect SPI support nearly six years ago, they've not yet made a corresponding correction to the Nano page.  But as the difference is in the software and the same software is used in either case, the addition of SPI support to the Duemilanove was also automatically an addition of that support to the Nano.


Your source has several flaws, and one error that generates the output you see. This is the analysis of the error.
In loop() you start by waiting for the button pin to get HIGH, following by another read of the pin's state that will most probably return the same, HIGH. Note: Only if your button bounces with just the right timing, this last read will return LOW.
while (digitalRead(button1Pin) == LOW) {}
button1State = digitalRead(button1Pin);

Next you check the pin's state, and let's assume that it is HIGH. Only the else part is executed, and it calculates the holdtime as the difference of endPressed and startPressed. The former has the current value of millis(), but the latter is 0 as you initialized it.
That's why you're getting always growing values.
How to solve?
Think about the while loops, do you need them? Remember that loop() is already called repeatedly.
You may need a state variable that stores the last pin's state, so you can detect changes.


Library and schematics are at https://github.com/maxgerhardt/rotary-encoder-over-mcp23017.

To read a rotary encoder (i.e., detect state changes of the knob), there are two possible implementations:

poll the state of the two output pins and check for changes
set up an interrupt which will be called when an output pin changes, then check for changes

Using interrupts is more efficient than always polling the pins, because an action is only executed when an actual change occurs.

Per rotary encoder you would need two pins on your microcontroller. However, we can use GPIO expanders over e.g. I2C or SPI, such as

Microchip MCP23017 (16-bit, I2C)
Texas Instruments PCF8575 (16-bit, I2C), PCF8574 (8-bit, I2C)

Using a port expander over I2C has the advantage being a bus that only uses 2 pins. This means that there can be multiple (up to 127) devices on the I2C bus, and each I2C device can then e.g. provide 16 GPIO pins.

Using an ATTiny85 per encoder and possibly joining them via an I2C bus is also possible, however more expensive and more work.

I've chosen a MCP23017 here because it is interrupt-capable, has 16-bit and I had it lying around. A PCF8574 would have also worked just fine, since it has the same capabilites.

Tests were made using an MCP23017 and a KY-040.

The written library uses a modified Adafruit MCP23017 library and the Rotary library. The Rotary library also handles debouncing by using a state-machine based approach for decoding. The library is a simple header file which defines a RotaryEncOverMCP C++ object, with which a rotary encoder connected to an MCP23017 device can be easily described and managed. It has an example for the polling method and the interrupt method.

For 1 encoder, one can write down schematic like: (interrupt based)

Since one MCP23017 has 16 ports, we can connect up to 8 rotary encoders to one such device.

However the MCP23017 also has three address pins with which its I2C address can be selected. This means we can have 2^3 = 8 such device on the same I2C bus (i.e., connected to the same SDA and SCL lines).

Thus, with one I2C bus, which uses 2 pins, we can have a maximum of 8xMCP23017 and 64 rotary encoders (assuming no interrupts are used, which would need 1 pin for any number of rotary encoders). At the cost of 2 more pins on the microcontroller, we can create another software bit-banged I2C bus, each of which adds again a maximum of 64 rotary encoders.

Assuming D2 to D13 and A0 to A5 are free, on these 18 pins we can have 9 I2C buses with a total of 72 MCP23017 devices hosting a grand total of 576 rotary encoders. Whatever one might need that for.

I've tested this library with one rotary encoder and a MCP23017, but the code is structured in a way that adding more encoders is just adding an entry in an array.


How to identify connection lost on HC-06?

My first one or couple of HC-06es brought its LED signal out to a pin on the base board, labeled "STATE" on mine. I tested the LED state on every loop and if it was changing regularly, took that to indicate whether it was waiting for a connection.

Later modules no longer bring out the LED signal but it is available on module's edge-pin 24, according to a (now 6yo) datasheet.

By cutting the plastic sleeve and bringing out the signal to the baseboard again, you use it to monitor the connection.


Here is a "stripped down version" of a sketch I used to replicate the Clap On, Clap Off lamp switch we had in the 1980's.  It works with the KY-038 sound sensor module you currently have. You will need to install the VirtualDelay Library.
The sound sensor module is very sensitive. A quarter turn of the potentiometer around the "sweet spot" makes a huge difference. Too sensitive, and the digital output is constantly high. If it's not sensitive enough, then you have to physically "tap" the microphone to get a high/low transition out of it.
Please note: This sketch uses delay() which is "blocking code" and it's use is usually not recommended.
#include "avdweb_VirtualDelay.h"
byte clapCounter = 0;
const byte soundSensorPin = 2;
const unsigned long loopDelay = 1;
const unsigned long clapCounterDelay = 400;
unsigned long clapCounterTimerDuration = 1000;
unsigned long previousMillis = 0;

void setup(){
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop(){

  // Timer object.
  static VirtualDelay clapCounterTimer;

  // Get the current time.
  unsigned long currentMillis = millis();

  // Check for a clapping sound (1 ms works good). If too much time
  // elapses here, you could miss the "beginning" of the clap.
  if(myTimer1(loopDelay, currentMillis) == 1){

    // Clap detected.
    if(digitalRead(soundSensorPin) == 1){

      clapCounter += 1;

      // When the first the clap is detected, start a timer
      // to reset the clap counter to 0 after 1 second.
      if(clapCounter == 1){
        clapCounterTimer.start(clapCounterTimerDuration);
      }

      // Delay execution of the loop. 400 ms works good.
      delay(clapCounterDelay);

      // If a second clap is detected, toggle the LED ON/OFF.
      if(clapCounter > 1){
        digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
      }

    }
  }

  // Reset the clap counter to 0 after 1 second. If
  // you don't do this, you could clap once, wait a
  // minute, then clap again and the LED will change state.
  if(clapCounterTimer.elapsed()){
    clapCounter = 0;
  }

}

// Clap loop timer.
byte myTimer1(unsigned long loopDelay, unsigned long currentMillis){
  if(currentMillis - previousMillis >= loopDelay){previousMillis += loopDelay;return 1;}
  else{return 0;}
}

EDIT: To answer your question regarding the multiple High to Low transitions from the module's digital output, you can use a DSO to look at the relationship between the analog and digital signals it produces.
In the following image, the digital signal (yellow trace) and the analog signal (blue trace) are superimposed over each other. The white dashed line (E), is set to 2.8 VDC which is approximately the analog output pin's voltage with ambient room noise. Once you clap in front of the microphone, this wave form is generated.

The entire clap lasts about 5.6 ms and the module gives you 18 High to Low transitions on it's digital output pin. When the analog voltage drops below a certain voltage, the digital output goes High. When the analog voltage goes above that voltage, the digital output goes Low.
The problem is, the sound of a person clapping generates a noisy signal and the sound sensor module does not know the difference between noise and the sound you want to trigger it.
Instead of using delay() like I did, you could increment a "clap counter"  to equal "1" on the first Low to High transition of the digital output pin. Next, start a non-blocking millis() timer that waits before you read the digital output pin again. If digital out is High after 400 ms, it's your second clap so change the LED state. A second millis() timer could reset the "clap counter" to 0 after 1 second.


You probably want to do something like this:

typedef enum { FEATURE1, FEATURE2, FEATURE3 } Feature;

//implement these
Feature getFeatureFromUser(){}
void setup1(){}
void setup2(){}
void setup3(){}
void loop1(){}
void loop2(){}
void loop3(){}

void setup() {
  Feature f = getFeatureFromUser();

  switch (f) {
    case FEATURE1:
      setup1();
      while (true) {
        loop1();
        if (serialEventRun) serialEventRun();
      }
    case FEATURE2:
      setup2();
      while (true) {
        loop2();
        if (serialEventRun) serialEventRun();
      }
    case FEATURE3:
      setup3();
      while (true) {
        loop3();
        if (serialEventRun) serialEventRun();
      }
  }
}

//never reached
void loop() {}

It's good to know that there's no hard rules about how the Arduino functions should be used. Examples like this demonstrate how Arduino's standard requirements of void setup() and void loop() don't quite match every use case.

EDIT: The serialEventRun lines are normally called behind the scenes after each execution of Arduino's normal loop(), so adding them here will result in the standard behavior of serial events


Uploading bootloader on ATmega328P SMT package using Arduino Uno

I've had success with bootloader of the Arduino IDE.
I used to have some trouble uploading sketches, but I solved them by doing this:

If the atmega is already soldered in a pcb and you have a pull up resistor, or something else connected to the reset pin, disconnect it. reset pin must be free.
Connect the tx, rx and rst pins of your atmega to your arduino.
Press the Upload button in the Arduino IDE and see the leds tx,rx in your arduino, just after the first blink, press the reset button, after that both of the leds should start blinking and in the end your code should be uploaded.


Reading two sensors at different frequencies... multiple Timer3?

The rule is:

One Timer, One Interrupt.

When the timer overflows it triggers its interrupt. It only has one. That interrupt then runs your ISR.

If you are using a library to provide abstraction from the timer registers then it is down to that library how it calls your ISR. It is possible for one to provide a mechanism whereby you can "attach" multiple routines to the same interrupt, but that is quite a lot of work and overhead for a simple timer library to provide, so it is highly unlikely anyone would ever bother.

So how do you do multiple sensor measurements from one timer? Simple: just do multiple sensor measurements. You don't have to restrict yourself to just reading one sensor within your interrupt - you can read as many as you like. There is just a couple of caveats though:

The whole ISR must take less that 10ms to run or it will overrun the timer overflow period.
You cannot do serial from inside an interrupt*

So in your interrupt you read the sensors and add their values to a buffer. Then in your main loop you read that buffer to send the data out through serial. You may want to set a flag in your interrupt routine to alert the main loop that there is data available, or implement a circular buffer which has an equivalent of a .available() function to see if there is any data to read from it.

*You can place data in the serial TX buffer but it will not be transmitted out of the TX buffer until after the interrupt routine has finished. If you put too much data in that TX buffer it will block indefinitely waiting for it to empty.


Which interrupts are enabled when programming an ATTiny85 with Arduino IDE?

The only interrupt that is always running is the one which generates the count for millis() and micros(). Disabling interrupts disables your ability to keep track of time and use delay().

Timer interrupts are also used by the tone() function and for sending / receiving serial data if the chip has a UART.

Disabling interrupts would also affect the use of external interrupts and pin change interrupts should you be using them.

It sounds, from your brief description, that you would only be effecting the use of millis() and delay() since you aren't using the other systems that use interrupts at all.


Can wifi shield connect to local network without internet?

If you have created your own local network, you may need a DHCP server to give it an IP address, or you will have to configure your Arduino with a static ip. I can't think of a reason why it would need internet access, but it is not uncommon for devices to refer (incorrectly) to connectivity issues on the local network as "internet" issues.


If you did manage to switch the transistor on, It would only output 4.3V, the rest would be dissipated in the transistor. If you managed to switch 4A this would dissipate 96W - and the transistor would melt.

A MOSFET would be a better option and could be easily switched by the Arduino. (I regularly switch 10A using a MOSFET and Arduino.)

This assumes you can put the MOSFET in the negative lead. If not you should use a P-Channel MOSFET, but you need a more complex circuit to drive it.

Have you considered using a relay module?


Depending on how you are powering your board different things will happen.

If you are powering through USB from a PC the PC should, according to the USB standard, detect an over-current situation and disconnect the power from the port. However some don't, in which case see point 2.
If you are powering through USB from a USB power supply (phone charger, etc) the charger's output voltage will drop to near zero and the current will hit maximum for the supply. This may or may not damage the supply, but either way it's not a nice thing to do.
If you are powering from a small external battery (say a 9V PP3 battery) things will start to get hot. The voltage regulator will most likely overheat, the battery may overheat, but not much damage should occur - a small PP3 battery can't provide much current.
If you are powering from a large external battery (e.g., Li-Ion cells) or an external power supply, things will get more nasty. The on-board regulator will overheat. If it isn't thermally protected (genuine Arduinos should be, but cheap Chinese clones may not be) then it will fail and you will find smoke coming out of the regulator. At this point the regulator is dead. If the board contains a polarity protection diode that may fail in the same way (I have seen these blow clean off the board before). Physical damage (blackening and blistering) may occur to the PCB as well.

So all in all shorting +5V to GND is never a good idea.