How can I connect more sensors when my lcd is blocking pin access?

What you need is a shield that can go between the Arduino and the LCD shield and break out whatever connections you like.

They are generally available as "screw terminal" shields, such as this one from iTead:

http://www.itead.cc/mega-proto-screw-shield.html


ESP8266EX along with Arduino Due rev3 to check wifi status

And where did you get that SoftwareSerial library? SoftwareSerial libraries are architecture dependent. You can't use AVR ore esp8266 SoftwareSerial library with ARM.

Due has no need for SoftwareSerial, it has 4 Serial ports configured.


There are two ways of doing this:

Using a Real Time Clock (RTC) chip, which you connect to your Arduino.
Using the millis() function of the Arduino.

Needless to say, they aren't completely the same in efficiency. An RTC is a dedicated chip for measuring time and is incredibly accurate. The millis() is not as accurate, but still pretty accurate.

So, it really depends on how accurate you want it to be. You can make millis() more accurate through code, which isn't something difficult. But an RTC always works fine and is always more accurate, if only by milliseconds. In general: need to time long durations, an RCT is probably better.

Regardless of the method you will use, you can convert the data into the desired format so it can be read easily when looking at the files on the SD card. So, for example: you can write code that simply checks how many hours fit in the saved time data, and after that you can check the minutes and even after that you can check for the last seconds. For this you're going to need modulo.

Here are some resources you might want to check out:

An Arduino tutorial for an RTC chip: http://playground.arduino.cc/Main/DS1302
Official documentation on millis(): https://www.arduino.cc/en/Reference/Millis


Analog reading with noise - Arduino Uno VS ESP12e

The ESP8266 is an incredibly (electrically) noisy environment.

Because you can't use anything except the internal voltage reference, which is in turn driven from the internal noisy power, you can't get anything even vaguely approaching stable readings.

It is recommended to disable the WiFI completely ("Modem Sleep") when doing ADC readings to reduce noise.

However, the ADC was never intended for this kind of work. Its primary role is for monitoring the battery voltage of your hardware - and as such it really doesn't care that much about noise, since you can average a number of samples for greater accuracy (something you can't really do with audio).


DC motor fan speed control with Temperature Sensor

I am assuming that whatever temperature you are measuring is not rising when the motor is on.
I see that you are sharing the power/ground between your temperature sensor IC and the motor.  Motors are extremely noisy from an electrical viewpoint and it's almost certainly causing your temperature sensor to malfunction.
It would be best to separate the temp sensor power/ground connections from the motor power/ground connections completely.  Power the motor from an external supply instead of sourcing it from the Arduino.
Another thing that might help is to add some bypass capacitors as close as possible to the motor and to the temperature IC across the Vcc and GND lines.  This will help to smooth out the power in spite of the noise that the motor itself generates.  Generally you want at least one of two types, an electrolytic capacitor and a ceramic capacitor.  These are both inexpensive if you don't already have some on hand.  I'll suggest a 10 uF electrolytic and a 0.1 uF ceramic capacitor near both the motor and the temp sensor.


Driving power MOSFET from 3.3v or lower Arduino Pro Mini

I don't think the mosfets will be an issue. Looking at the last one (BSS806NE); in figure 5 in the datasheet you see that for 1A and 1.4v (Vgs) you'd get a Vds of only .1v.

I think a bigger problem might be the voltage of the batteries dropping under load. You'd have to measure that with a multimeter while the motor is running. A simple cap might help with a little noise, but not with the voltage dropping while the motor is running. Not sure how much the AVR would mind having its supply voltage dropping all of a sudden.

Of the top of my head the minimal voltage of the Atmega328 @8mhz is 1.8v, while default fuse settings use 2.7v, so I'd probably change to fuses to make BOD at 1.8v. Other fuses don't need to change.

Backup option sound good, though you might have to go with 4 x 1.5v depending on the voltage drop under load. Another alternative might be to have two sets of 1.5v batteries in parallel, halving the current load on each battery.


Arduino Uno + USB Host Shield + Motor Shield

You need to check the I/O used by each shield to make sure there is no conflicts.


How to detect button presses with a 74HC595 shift register?

The 74HC595 is a deserializer while the 74HC165 is a serializer. This means the former consumes a serial datastream and provides all data bits in parallel on dedicated data lines. While the latter consumes parallel data and converts it to a serial datastream.

To scan buttons you want to have parallel input data, where each switch is attached to a single data line. Then you serialize the data to reduce the amount of required Arduino inputs. This method is well explained in the mentioned tutorial.

As the 74HC595 is a deserializer it is not really applicable here. Instead you could use it to drive multiple outputs through a serial interface (see https://www.arduino.cc/en/tutorial/ShiftOut as an example).


As @Juraj mentioned it was solved by changing the setting and I was able easily to play the sound when I matched the setting to this file:

So, I could not create one from scratch matches above setting but I was able to convert existing sound through this site
which allowed me to convert with desire setting and here finally the exiting sound has matched the setting:


Connecting Arduino Mega + SIM800L to a car battery

With this setup you are overstressing the onboard regulator, while wasting a lot of power (not suggested on a battery setup, even if the battery is quite big).

First of all, the power. You have a MEGA, which runs at 5V/few mA, and a SIM800L, which runs at 4V/2A. I suggest you to have two power supplies. On ebay you can find cheap XL4015 converters rated at 5A. You connect IN+ to the +12V, IN- to the ground, then set the first one to output 5V, while the other to 4V. If you want to have the most correct powering scheme connect the 5V to the USB port, otherwise connect it to the +5V pins (note that you will exclude the fuse).

Then there is another problem: the UART levels. As a first approximation you can hope that the arduino reads the correct levels, so you'll just have to lower the TX voltage from 5V to 3.3V. You can do this by using a voltage divider with a 4.7k resistor between arduino TX and SIM RX and a 10k resistor between SIM RX and ground (see, for instance, how they did it in this image).


How to use Infra Red (IR) to reset arduino board

Kind of, yes.  That doesn't actually reset the Arduino, it just sends the program to address 0.

There are two other ways of performing the reset that do a proper full reset:

Enable the watchdog timer and let it time out to reset the CPU.
Connect an IO pin to the RESET pin - keep it in INPUT most of the time but set it to OUTPUT and LOW when you want to reset.

By just jumping to address 0 you aren't resetting the internal peripherals and registers to their reset state, so things like timers and such will still be running when they shouldn't be, etc.  It's better by far to do a real reset instead of just jumping to 0 like that.


There is, as you may expect with C, many different ways of doing this.

The simplest is probably to use, instead of a const variable, a preprocessor macro.

In C you can concatenate string literals like this:

print("AT+BIND=" "abcd,ef,ghijkl");

Note the lack of anything but spaces between the strings - they are concatenated together. You can even do it on separate lines - it's a technique that is great for incredibly long strings.

Now you can, of course, replace one of those with a preprocessor macro:

#define BT_ADDRESS "abcd,ef,ghijkl"
print("AT+BIND=" BT_ADDRESS);
print("AT+LINK=" BT_ADDRESS);

The preprocessing replaces BT_ADDRESS with the string literal "abcd,ef,ghijkl" and all is well.

Other options, depending on what print does, is to expand it to take two const char * parameters and deal with them both separately.  For instance, you might have:

void print(const char *command, const char *data) {
    Serial.print(command);
    Serial.println(data);
}

print("AT+BIND=", BT_ADDRESS);

If you don't know how many parameters you may want to pass you could use variadic arguments:

#include <stdarg.h>

void print(int count, ...) {
    va_list args;
    va_start args, count);

    for (int i = 0; i < count; i++) {
        const char *arg = va_arg(args, const char *);
        Serial.print(arg);
    }
    va_end(args);
}

print(2, "AT+BIND=", BT_ADDRESS);

Yet another option is to pre-format the data into a single string using the various string operators.  For example:

int len = strlen("AT+BIND=") + strlen(BT_ADDRESS);
char temp[len + 1]; // Be sure to keep space for the terminating NULL.
strcpy(temp, "AT+BIND=");
strcat(BT_ADDRESS);
print(temp);

I could go on all night with different options...  The first one using the preprocessor is probably easiest though.


It looks like you're sending only one byte, but expecting to receive three.
In the TX sketch, char msg[1] = {distance}; declares an array of one char, assigns its zero-th element the value of distance. Then msg[0] = count; over-writes it with the value of count. vw_send((uint8_t *)msg, 3); tries to send three bytes but only the first one has been defined. The second and third bytes transmitted are outside of the 1-length array.

You need something more like:

vw_send(distance, sizeof(distance));

on the TX side, and:

long distance;
uint8_t count;

vw_get_message(distance, &count));
Serial.println(distance);

on the RX side. You must receive the count into a variable but can ignore it, on the RX side; you know you'll be receiving a long; though good defensive coding would check the value anyway.


Using Arduino libraries with ARM based microcontroller

Every time I work on a project I use arduino libraries and port them to my micro controller.
I used sublime text editor with multiple selection and editing(ctrl-d). Then I copy the arduino code to both sublime and my uC IDE then compile it in the IDE, scroll up to the first undefined function and add its definition to the code or modify it using sublime multiple editing and selecting (like digital read and write was in my opinion useless). After that update the file in your IDE and compile again.

You would do that till you have finished and it would take some time.


How do you configure ADC7 on the Arduino Pro Mini as a digital output?

This may be a little left field, but I use the ADC6 and ADC7 inputs to detect switches.  I just don't use the digitalRead() function, but instead use analogRead() function.  Using a resistor network and switches and some decoder software code in our sketch, we can use a single input pin to interface with many more switches.  The switches can only be on one at a time, but in many instances, this would be OK.


If you are reading from the analog pins then the values are 10 bits (not 8 as suggested above).  Are you looking at concatenating 2 10 bit numbers or 2 16 bit numbers or are you using a zero or duo in which case they could be 12 bit numbers.

In any case:

const int BITMASK = 0x3FF;  // 10 bits = 0x3FF, 12 = 0xFFF, 16 = 0xFFFF
const int BITWIDTH = 10;
long result = ((value1 & BITMASK) << BITWIDTH) | (value2 & BITMASK);

I suspect it won't give you the answer you want, but...


Adafruit Music Maker Shield - Retrieve song names from SD Card

The adafruit library was is similar to the prior SFEMP3shield library (disclosure I am the main author of that). That said either library can work on either Adafruit or SFE shield or breakout board. AdaFruit's library is cleaner re-write. But in doing so it is minimal in its functions. The SFE library demonstrates many more features of the VS1053 chip.

That said; the ./Example/fileplayer.ino does exactly what you are asking. The directory command lists out the files with an enumerating number. Entering 0[number] plays that file. This is how I broke away from "track###.mp3", without having to implement a command prompt parser. And it also allows other file formats.

The bulk of this feature is in the LOOP() and not in the constrained to the library. So one can cut and paste it into a sketch using the Adafruit library in place of the SFEMP3 or any sketch with an SdCard. That said it would actually be easier to replace the play file calls and include in the FilePlayer.ino example. Or just use it straight up.

The SFEmp3 library is bit overwhelming because it supports so many features of the VS1053. And uses a different SdCard library, which is more upto date than the IDE's SD". While the Adafruit library is a very nice re-write and cleans much hte confusing #define's making it much easier code to read, it is not as feature rich. But most feature beyond play and stop are not really needed.

Good luck.


Connecting to a WNR2000v4 Netgear Router via Serial Connection with an Arduino Uno and a sketch?

The WNR2000v4 serial port is at JP1: 115200 8N1 at 3.3V. Pads are, from left to right with the ethernet ports on right: [GND] [Rx] [Tx] [Vcc]

Source: https://wiki.openwrt.org/toh/netgear/wnr2000, PCB picture: https://wiki.openwrt.org/_detail/media/netgear/wnr2000/wnr2000v1_pcb_detail_small.jpg?id=toh%3Anetgear%3Awnr2000


How come my switch is triggering with out pushing the button?

I want the relay to trigger and stay open only while the button is
  pressed. However for some reason touching pin 2 triggers the relay and
  sound, even if I'm not connecting it to the ground.

Touching a pin is like connecting it to ground with a resistor (human body is conductive). It may or may not be stronger then the pull-up resistor.

  If i remove the tone (speaker, 100, 300); it only triggers when the
  button connecting pin 2 to ground is pressed, but obviously doesn't
  play the tone.

Activation of the neighbor pin influences the pull-up on pin 2. Try external pull-up on pin 2.


PT100 and MAX31865 readings showing wrong

I nearly have the same problem. I use five of the MAX31865-Boards with 2-Wire Termocouples on an Arduino Nano. Two of the five boards are working perfectly. The other 3 boards show exactly the same wrong behaviour you described. My temperature readings are exactly like yours (-242.02).

But I think I found the reason for the not working ones: The two working boards I bought on Amazon. The other three not working boards I bought on AliExpress. Maybe I (and maybe you too) got really bad fakes from China and they are simply dead :(

(BTW: If I remove one working board from the SPI bus and read out the temperature with the arduino, I get also the value of -242.02. This value seems to be an error value in the Adafruit MAX31865 library)

EDIT: Fixed it with a workaround!Like shown in the picture below, simply remove the wrong component (SMD Capacitor) and create a solder bridge . See comments for more informations!

Here is a picture of my modification of one chinese board as requested by the comments:

(It's not the best solution, but it works. For final using you should get the right filter ferrite and solder it on the board!)


Speed controller for Ceiling Fan 220V AC 100W

In theory, it should work to control the speed of fan. The manufactures description mentions "fan regulator". One of the pictures shows on the backside of the module that it is for 2 A (5 A peek). This should be good for 230 V / 100 W motor.

The module gives you a basic circuit to control AC. It reports zero-crossing and has an optocoupler switch to turn AC on and off. The dimming does your sketch, by cutting parts of the AC wave out in precise timing.

The example sketch is not good. It has delay in interrupt. With this implementation the sketch will not be able to do much else.

EDIT: I tested it and it works with fan too. The delay in interrupt is to create a short pulse to turn on the triac. The triac then turns self off on next zero-crossing. And Robotdyn changed the specs to 10 A.


Showing chronometer on PC controlling the begining and end of time by Arduino

It's perfectly possible to do, and the way I would probably do it is to use one of the ATMega32U4 based Arduinos (such as the Arduino Leonardo or the somewhat smaller Arduino Micro) to act like a keyboard. A keyboard with just one key - your chosen button.

Then you program the computer to respond to the keycode the Arduino sends to start and stop the chronometer. You could even use an off the shelf chronometer program that starts and stops with a specific keypress and tell the Arduino to send that keypress. It would probably take about 5 minutes to write the software - if that.


tty doesn't list ttyUSB0 so arduino doesn't list serial ports

Sorry, I was using the software center to get arduino IDE and that didn't work well. Downloading the official IDE from arduino.cc worked without hassle. Lesson learnt: Not all linux distros have package repos as up-to-date as Arch. :P


3.95 MCU Friend Arduino TFT LCD flickering

I think something is wrong with this LCD board. This is because in my case the display works sometimes perfectly with the ILI9481 driver but sometimes something hangs and the display starts to flicker. It looks like a chip charging problem. Anyway I solved the flickering problem by tuning the ILI9488 registers. Simply you have to change the initlcd.h for ILI9481 driver in UTFT library.

enter code here

case ILI9481:

LCD_Write_COM(0x11);
delay(70);

LCD_Write_COM(0x38);//Idle Mode OFF
LCD_Write_COM(0x13);//Normal mode

LCD_Write_COM(0x36); // Memory Access Control  crucial
LCD_Write_DATA(0x0A);

LCD_Write_COM(0x55);
LCD_Write_DATA(0x22);//High enhancment of CE ratio

LCD_Write_COM(0xB1);
LCD_Write_DATA(0x70);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB4);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB5);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x12);

LCD_Write_COM(0xB6);        // Display Function Control
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x21);       // 0x42 = Rotate display 180 deg.
LCD_Write_DATA(0x3B);

LCD_Write_COM(0xC0);
LCD_Write_DATA(0x1F);//0X1F
LCD_Write_DATA(0x01);//0X10

LCD_Write_COM(0xC1);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xC2);
LCD_Write_DATA(0x00);//0X44 lower better
LCD_Write_COM(0xC4);
LCD_Write_DATA(0x00);//0X10

LCD_Write_COM(0xC5);
LCD_Write_DATA(0x00);//0X10
LCD_Write_DATA(0x80);//optimum
LCD_Write_DATA(0x80);//0X10

LCD_Write_COM(0x3A);//Interface Pixel Format
LCD_Write_DATA(0x55);

LCD_Write_COM(0x2A);//Column Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0xDF);//320

LCD_Write_COM(0x2B);//Page Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0x3F);//480

delay(60);

LCD_Write_COM(0x29);//Display ON
delay(30);

LCD_Write_COM(0x2C);//Memory Write
delay(30);
break;


Using the MIDI library in my own library

void MIDI_CREATE_DEFAULT_INSTANCE();

This line should not be placed inside a function, because it is a forward function declaration.

However, I think there are more problems in your code.

My wild guess is to improve the following lines:

Uncomment line that doesn't work

Change

MIDI_CREATE_DEFAULT_INSTANCE();

to

MIDI_CREATE_DEFAULT_INSTANCE();

and place it outside a function.

Remove the word void  in the following lines

void midiSetup();
void pmbMIDI();

And also align the { and }

void MIDI.begin(MIDI_CHANNEL_OMNI);

So it's a function call.

Other improvements is to remove spaces or tabs  in

    void midiSetup();
    void pmbMIDI();

Also align { and } in

if (MIDI.getType() == 144){
    digitalWrite(13, 1);}

if (MIDI.getType() == 128){
    digitalWrite(13, 0);}


This: https://github.com/arendst/Sonoff-MQTT-OTA-Arduino is a Arduino based firmware with support for OTA. It's written for Sonoff, but that is just a ESP8266 with a relay attached, you can easily adapt it to any ESP8266.

It uses a 'hard coded' address of a web server where it downloads the firmware, and updates are triggered by MQTT messages, but all of that should not be too hard to change to something else.


What are the purposes of the different LED lights on a Arduino UNO board?

'L' shows the state of pin13 which is programmable by you for any purpose, whether to read or write to an external device, or just for turn the LED on and off as you have done.

'RX' and 'TX' show the states of the Receive and Transmit pins, respectively, and allow you see when serial communication is taking place.


As Mikael Patel pointed out in his answer, you have set up a voltage divider. Mikael has thoughtfully provided a schematic of the clone Uno, where the relevant part is here:

Equivalent circuit

If you jumper together pins D0 and D1 (Rx and Tx) on the Uno effectively you have made this circuit:

Testing

If I set up this with a function generator, I get this result:

You can see that for a square-wave input of 0 to 5V, we only get an output of 2.16 to 5V.

What is LOW?

Now looking at the datasheet for the DC characteristics we see:

For an input to register as LOW it has to be no higher than 0.3 * Vcc = 0.3 * 5. Thus the voltage cannot be higher than 1.5V. Since we are measuring 2.16V, that will not count as a LOW.

Now admittedly that is for the Atmega328P and not the CH340G, but it will probably have similar characteristics.

I found a datasheet for the CH340G, and that shows even stricter requirements for a LOW signal:

Official Uno

Comparing to the official Uno circuit:

You will note there that the indicator LEDs are on a different circuit, and thus do not form a voltage divider.

The Maths

The clone Uno circuit above can be re-arranged like this:

Given that the LEDs have a voltage drop of 1.86V (measured in practice, and about right for the red LEDs I am using) then effectively we have the resistors R1 and R2 connected to 3.14V.

Since they are in parallel they are effectively 500 ohms.

Now using the formula for voltage dividers:

1000 / (1000 + 500) * (5 - 1.86) = 2.09V

This is close enough to the observed result. I didn't check each resistor to make sure it was exactly in spec.

I don't think R4 affects the results because it is effectively "floating".


No.

What you have is two slave devices and you need a master in order to initiate the Bluetooth communication with the slave. So, either you need two HC-05 Or 1* HC-05 and 1* HC-06.


Arduino Resetting in Automotive Application

There is no power spike or loss to the PCB. The car is not actually
  running, I am just turning the key on and off.

And did you verify that with a digital scope? I doubt it.

I don't think you understand how ugly the electrical system in a car really is. If there is a coil or relay switched then there will be spikes. Do some research on electronics for use in an automobile.

Automotive relays can have a resistor in parallel with the coil to control the level of the back emf when the relay is turned off. You would think that a reversed diode should be used but a diode causes the coil current to discharge too slow and that causes the contact arcing to be extended. A resistor can be used to speed up the discharge but at the cost of a voltage spike on the electrical system.

An Arduino board is not appropriate. There needs to be a lot more protection.And one wire devices are basically an antenna looking for trouble.

https://www.st.com/content/ccc/resource/technical/document/application_note/1f/d7/fc/6d/2e/27/48/98/CD00181783.pdf/files/CD00181783.pdf/jcr:content/translations/en.CD00181783.pdf

https://electronics.stackexchange.com/a/40425/195251

https://en.wikipedia.org/wiki/Load_dump

https://electronics.stackexchange.com/a/163861/195251


Weird behaviour of rotary encoder values

Unfortunately, I couldn't find the issue.
BUT I used another approach which worked fine.

I used the ClickEncoder library.
This time, my rotary encoder triggered 4 events per notch.

After a little research I found out, that it's possible to set the steps per notch with this library.
I used this code to initiate the ClickEncoder:

encoder = new ClickEncoder(A15, A14, A13, 4);

The first three arguments define the pins the encoder is connected to. The last argument sets the steps per notch. Now it works like a charm!

Full code:

#include <ClickEncoder.h>
#include <TimerOne.h>

ClickEncoder *encoder;
int16_t last, value;

void timerIsr() {
  encoder->service();
}

void setup() {
  Serial.begin(9600);
  encoder = new ClickEncoder(A15, A14, A13, 4);

  Timer1.initialize(1000);
  Timer1.attachInterrupt(timerIsr);

  last = -1;
}

void loop() {
  value += encoder->getValue();

  if (value != last) {
    last = value;
    Serial.print("Encoder Value: ");
    Serial.println(value);
  }

  ClickEncoder::Button b = encoder->getButton();
  if (b != ClickEncoder::Open) {
    Serial.print("Button: ");
    #define VERBOSECASE(label) case label: Serial.println(#label); break;
    switch (b) {
      VERBOSECASE(ClickEncoder::Pressed);
      VERBOSECASE(ClickEncoder::Held)
      VERBOSECASE(ClickEncoder::Released)
      VERBOSECASE(ClickEncoder::Clicked)
      case ClickEncoder::DoubleClicked:
          Serial.println("ClickEncoder::DoubleClicked");
          encoder->setAccelerationEnabled(!encoder->getAccelerationEnabled());
          Serial.print("  Acceleration is ");
          Serial.println((encoder->getAccelerationEnabled()) ? "enabled" : "disabled");
        break;
    }
  }
}


Connecting high sampling rate DAC and ADC to arduino DUE, timer consideration

If I'm interpreting the datasheet correctly, you might be able to use the Static Memory Controller (SMC) capability of the Cortex M3 Sam3X to attach some 128K x 8 SRAM devices to your Due.  If your ADC and DAC support tri-state outputs then they could be attached the same way as memories (but ignoring address lines as irrelevant), allowing memory-to-memory DMA transfers.  Ie one could either input and store batches of ADC results at 42 MSPS, or could output batches of data to DAC at 42 MSPS, or could do simultaneous I/O at 21 MSPS.  I haven't read the DMA section closely enough to verify that this will work with the M3.

See Figure 25-2 in Section 25.6.2 of the datasheet regarding memory controllers, and Section 26, “Peripheral DMA Controller (PDC)”, regarding DMA.  Also see the eevblog.com page, “Looking for Cortex M3 or M4 with DMA to GPIO capability”.


Use input with pullup on pin 8 and a button to ground (GND). See below:

const int ledPin = 4;
const int buttonPin = 8;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
   digitalWrite(ledPin, digitalRead(buttonPin));
}

Using the pin as input and disconnecting is not the same as GND. The pin is floating. By using the internal pullup resistor the pin is HIGH when the button is not connected to GND.


How to chooce SDA/SCL pair on Arduino Due ?

Pins 20 and 21 are the default I2C pins. A lot of libraries assume you use these, and would require some extra work to get working with SDA1/SCL1.

They also have their pullup resistors already present on the board of the Due (see schematic).

So just use pins 20 and 21, unless you have a good reason to use the other.


Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using 'localhost:1.0' as the value of the DISPLAY variable

It is probably a non-existant or stale auth cookie in your .Xauthority file.  This sort of thing happens when you're running your X session with one user but trying to run your X application as different user.  Doing sudo or su root (or really any other user) is a common way to get in that situation.  Running the IDE as root usually mean something else has already gone sideways.  The typical reason for that is you're running as root instead of fixing your permissions to the Arduino serial device file.

That said, if you want to run headless builds and uploads of Arduino projects, what you're looking for is arduino-cli.
cd /path/to/directory/containing/sht30v1.ino
arduino-cli -b arduino:avr:nano compile
arduino-cli -b arduino:avr:nano upload --port /dev/ttyUSB0


Use of struct and sizeof in C for Arduino

Consider the following:

void printBook(const books &theBook)
{
    Serial.println("Name of the book is: ");
    Serial.println(theBook.name);
    Serial.println("author is: ");
    Serial.println(theBook.author);
    Serial.println("ID is: ");
    Serial.println(theBook.ID);
}

void loop()
{
    printBook(MyBook);
    printBook(YourBook);
}

You should appreciate this avoids the code duplication you have in your
example.

  Why I get 62 for the sizeof(Mybook)?

30 bytes for name[30] (each char is one byte)
30 bytes for author[30]
2 bytes for ID (the AVRs have 16-bit ints)

No padding between the members because this architecture has no
alignment constraints.


Arduino Uno - ESP 8266: sending AT commands via Code

Of course you cannot use the same pins for both hardware and software serial, but that part seems to have been solved in comments.

  Question now is: How do I store the string being returned from the esp8266. I thought my response string was suppose to store the "OK" but that did not happen.

 while (esp8266.available())     {
    char c = esp8266.read();
    response += c;
 }

This will only read as long as characters are available, but the ATmega is able to run this loop much more quickly than characters are received, so unless the entire message was previously transferred it will likely only get a character or two before the receive buffer is found (temporarily) empty and it terminates.

You should instead read until a terminating condition is found, such as a newline character.  For safety you might also put in a "give up and try again" timeout, but make it long.

Some would try to solve this problem by inserting short delays before trying to read, but that is unwise - depending on delays creates unreliability as the necessary delay can easily change due to conditions that may on the surface seem to have little relevance, for example the esp866 might respond more slowly if it is seeing a lot of broadcast traffic on a network, or if the firmware version changes.


"'serial' not declared in this scope" error

Serial must be UPPERCASE as this class is case sensitive

Therefore your code will be:

const float referenceVolts = 5.0;
const int batteryPin = 0;

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

void loop()  {
int val = analogRead(batteryPin);
float volts = (val / 1023.0) * referenceVolts;
Serial.println(volts);
}


Check if any of loop's insides returns 1 and hold it until the whole loop is 0 again

First, you should really not use a global variable to get the result of your comparison function. That is only confusion and unnecessary complicated code. For that we have return values. So instead of setting the compareVar variable inside the timeCompare() function, you should just return the corresponding value. In the timeCompare() function replace
compareVar = 1;

with
return 1;

and
compareVar = 0;

with
return 0;

Then in your main code: As I understood, you only need compareVar in the for loops, so you could delete the globally defined compareVar and declare it directly before the for loops:
int compareVar = 0;

Now we can do the magic trick. We want to go through our for loops and get a result of 1, if for any of the elements timeCompare() returns 1. For that we just doing an OR operation:
compareVar = compareVar || timeCompare(timeArray[i][j][k][0], timeArray[i][j][k][1], timeArray[i][j][k][2], timeArray[i][j][k][3], timeArray[i][j][k][4], timeArray[i][j][k][5], timeArray[i][j][k][6]);

This is a boolean OR ||. In C++ zero is treated as false, while any other number is treated as true. We are starting with compareVar begin zero. When timeCompare() for the element returns also zero, it stays zero. If it returns 1, compareVar will become 1. If it returns 1 again, it will stay one. If it returns zero, it will stay zero.
So now you can check for compareVar after the for loops. It will be 1, if any of the elements gave you 1.
Similarly you could check for all elements returning 1, if you replace the OR || by an AND && operation.

Lastly I want to strongly discourage you from using goto. It ignores some important principles and you can easily create really bad code with it. Refer to questions like this one to read more about it. I would say, that in every case you have better ways than goto. Here it seems, that you simply want to go out of both loops. I would pack these loops into a function, so that you could simply use a return statement to get out of them.


If I connect a battery to the vin pin on the arduino, will the 5V pin be activated?

Yes, that's what the Vin pin is for: unregulated voltage or a voltage higher than 5V. Then the 5V pin will be at 5V, regulated by the on board regulator. You would only connect a source to the 5V pin if the source is already a regulated 5V.


Arduino Uno + MSD-11-EM stepdriver + NEMA 17

In loop add flag to change after what you desired plus a statement to check the flag.
Code below (assuming what is in for() being enough to do 4 revolutions):

#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
bool flag = true;

void setup() {
 // set the speed at 60 rpm:
 myStepper.setSpeed(110);
 // initialize the serial port:
 Serial.begin(9600);
}

void loop {
 if (flag) {
   for(int i=0;i<25;i++) {
     Serial.println("Anti-clockwise");
     myStepper.step(stepsPerRevolution);
     delay(50);
   }
   flag = false;
 }
}

This solution gives you a flexibility to add a pushbutton to change flag and do another 4 revolutions.


Naked displays... search e.g. Ebay for "40x4 lcd" (maybe enable "worldwide" search)...

...naked... so not i2c ... but Arduino libs for these displays exist (e.g.: liquidcrystal440), so add an Arduino-Pro or such and you can have i2c... basically they are two 40x2 displays on the same spi bus selected by different chip select lines...


Why are there 3 crystals on the Mega2560 schematic?

One of the crystals is for the ATMega8U2 chip which is being used for USB-Serial conversion.

The other two crystals are both for the ATMega2560. Why two? Basically they only populate one of the two, but they have two different footprints. One is for a surface mount resonator, the other for a through-hole crystal.

Having two footprints gives the option during assembly to go for the cheapest package at the time. It also means that the hobbyist can replaces the low accuracy resonator with a high accuracy crystal if their project requires.

As a side note, if you look at Y1, you will notice it is not the symbol for a crystal, it is of a resonator.


Button to optocoupler to fire camera 4 times

First of all, the loop (if it worked well) would only fire twice. It should only fire when you turn it on/off in a cycle (unless it's a rising/falling edge circuit (i.e. a pull down button/a falling edge interrupt), but I won't get into that). In your code you toggle it twice. The third one? I suspect that your camera only fires when it's given a low signal. This means that, when you set it to low in setup(), it takes a photo. To fix this, switch all the HIGHs and the LOWs for the opto pin.

This is the code which I think should work for you:

// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int opto = 12;
int buttonInput = 2;     // the number of the pushbutton pin
int buttonState = 0;         // variable for reading the pushbutton status

// the setup routine runs once when you press reset:
void setup()
{
// initialize the digital pin as an output.m
pinMode(opto, OUTPUT);
pinMode(buttonInput, INPUT);
digitalWrite(buttonInput, HIGH);}

// the loop routine runs over and over again forever:
void loop()
{
  buttonState = digitalRead(buttonInput);
  if (buttonState == HIGH) {
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
  } else {

  }

}

Without much info about your camera, I'd imagine that the HIGH/LOW discrepancy is the issue. Another note: this code doesn't protect against bouncing. It's fine if as it is because the delays will cause the bounces to not be picked up. If you do a "blink without delay" type of sketch using millis() and a loop, you might need to fix this. Like I said, it'll work fine now, but it's kind a crude fix since it could cause problems later if mixed with other code.


How to understand the "power economy" of a voltage up-converter (boost converter)?

He is describing a boost converter which steps up voltage at the expense of current. To quote from the Wikipedia page on that subject:

  A boost converter (step-up converter) is a DC-to-DC power converter that steps up voltage (while stepping down current) from its input (supply) to its output (load). It is a class of switched-mode power supply (SMPS) containing at least two semiconductors (a diode and a transistor) and at least one energy storage element: a capacitor, inductor, or the two in combination.

As an example, an Arduino Uno consumes around 50 mA from the power jack (at 9V) running a "do nothing" sketch like this:

void setup () {}
void loop () {}

You could say that this is consuming 450 mW of power.

9V * 0.050A = 0.450W

To run from a lower voltage the boost converter (say, 3V) you still need to get 450 mW of power, so therefore it will consume a higher current:

0.450w / 3V = 0.150A

In other words, we now need 150 mA (3 times the current) since we have 1/3 of the voltage.

Also, these converters are not 100% efficient. Say a particular converter is 90% efficient, that means it requires even more current (150mA / 0.9 in this case, being 166 mA).

The efficiency is not linear anyway. It varies somewhat depending on the input voltage and the load. There is a question and answer on Electronics Stack Exchange (Boost Converter Efficiency goes down as Duty Cycle goes up?) which discusses this.

  Is my understanding correct (higher voltage = lower current)?

Yes - in the sense that the device consumes power. Thus a higher voltage requires a lower current to deliver the same power. Conversely, if you drop the voltage you need to increase the current to get the same power.

  If the current decreased then why was this still an adequate power source for Arduino? Does current not matter?

Yes it matters. You need a certain voltage, with the capability of providing enough current. In this particular case if your batteries can supply 166 mA then the Arduino can still run.

  What are the practical limits of this type of conversion?

You will eventually exceed the capacity of your battery to supply enough current. A more elaborate Arduino circuit may involve LEDs and motors. The higher current drain may exceed what the battery can supply, or possibly it will just be drained quickly.

Another factor is that batteries are less efficient when supplying higher current (the quoted mAh figure for a battery is usually for quite a low current). In other words, if you double the current drawn from a battery, the time the battery lasts is not half the time, it is less than half the time. One of the reasons for this is that batteries have an equivalent series resistance (ESR). At higher current drains there is a larger voltage drop over that resistance (some power gets turned into heat, in other words). Thus it isn't practical to try to get 10 amps from an AA battery. The battery will just get very hot.

  For instance, he has 4 AA batteries with 1.2V each. He says "that's not going to be enough for Arduino" so he then passes the power through a voltage up-converter and increases it to 9V.

This is actually quite inefficient in the first place. The Arduino nominally can run from 5V (if sent directly to the 5V pin on the board) and 4 * 1.2V is 4.8V which should be close enough for practical purposes.

His idea is to step up the 4.8V using a boost converter to 9V (which in itself has some inefficiency) and then use the voltage regulator on the Arduino to drop the 9V back to 5V which is also inefficient because some power is now being dissipated as heat.


Arduino stopped working: avrdude: ser_open(): can't set com-state

The thing to remember with the Leonardo and other ATMega32U4 based boards is that there is no actual serial connection.

What there is, is a USB connection which is controlled by the sketch (and independently by the bootloader) to provide a "CDC/ACM" connection over USB.  This emulates a serial connection, but it's not a real serial connection.

This actually has a huge number of benefits, because you can be other things besides a serial port, such as a keyboard or a mouse. However, it comes at a cost:  the serial port is at the mercy of the sketch that's running at the time.

If your sketch crashes for any reason then the serial port can no longer be used. That's bad. It can cripple your Arduino. Since it's the sketch that is providing the driving force for the CDC/ACM serial emulation, if that sketch dies, so does the control of the USB and thus the CDC/ACM.

So while the port may be created initially by the sketch, if it then subsequently crashes the port is still there, but unresponsive.  Or the port can vanish completely.

So how do you fix it?  Well, there's a couple of strategies:

Some people have had success by pressing the RESET button twice in quick succession. This depends on the version of the bootloader in use though, and it's not something I have ever tried.
Pressing RESET at just the right moment to get the bootloader to run just before avrdude runs and catch it at the right time to accept a new sketch, or
Using a hardware programmer (e.g., USBASP) or another Arduino to wipe the chip and reinstall the bootloader

My preferred method is 3, since it is certain to always work - however it requires either a hardware programmer or another Arduino. However you can pick up a USBASP on eBay / AliExpress / Amazon etc for next to nothing, and when you're working with AVR chips they're always good to have to get you out of tight spots like this.


Arduino Uno - MQTT message using PUBSUB on ESP8266

The maximum MQTT packet size in PubSubClient is 128 bytes. After all the MQTT header information that leaves only 99 bytes for a message.

You can change it by editing the PubSubClient.h file:

#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 128
#endif

As it says in the PubSubClient README.md:

  The maximum message size, including header, is 128 bytes by default. This is configurable via MQTT_MAX_PACKET_SIZE in PubSubClient.h.


You can make your own. Buy a protoshield and 4 fets (and a few resistors).

You can also use the shield you linked to, by not using the + terminals on the board. Just connect the + of the lights directly to the battery and only the - of the light to the shield.

The Uno can be powered by up-to 20V, so you can connect it directly to the battery.


exit status 1 'Time' does not name a type

You don't mention which library you are using (which library does #include <DS3231.h> refer to?)

The DS3231 library here https://github.com/NorthernWidget/DS3231 defines a DateTime object which appears to have similar elements to what you are trying to access in 't' (hour, min, sec etc).

I would try defining 't' as a DateTime object.


Yes, you will have to change the code to match the Mega pinout.

Because the program need to run quite fast, and the Arduino functions
digitalRead() and digitalWrite() are dead slow, the author of the
program used direct port access for performing the raw IO.
For example:

    //Wait for vsync it is on pin 3 (counting from 0) portD
    while(!(PIND&8));//wait for high
    while((PIND&8));//wait for low

This is testing pin PD3 (8 is 23), which on the Uno is
digital 3, but on the Mega is digital 18. The same code could
be written in a portable fashion:

    //Wait for vsync it is on pin 3 (counting from 0) portD
    while (digitalRead(3) == LOW);   //wait for high
    while (digitalRead(3) == HIGH);  //wait for low

but it would probably be too slow.

Note also that here:

    UDR0=(PINC&15)|(PIND&240);

the program takes advantage of the particular pin mapping of the Uno in
order to read 8 inputs with only two port reads (4 bits on
port C and 4 bits on port D). You could do even better on the Mega
if you use pins A8 through A15 for the data bus, and then read the whole
8-bit word as PINK.

There may be some other differences between the Uno and the Mega that
need to be taken into account, but the pin mapping is the only one that
is obvious to me just by quickly going through the code.


Problem on color mixing lamp on Proteus Arduino starter kit

just fixed by using TORCH LDR instead of normal LDR. FULLY WORKS.


If all you need is to play back lo-fi audio then any with PWM will do, which means that any Arduino will do. If you want hi-fi sound then you'll need a DAC, which means either choosing the Due or using a discrete DAC via SPI. If you need decoding of complex audio formats such as MP3 or Vorbis then you'll need either the Due for its power, or a separate audio playback shield that supports the formats you're interested in.


Why does current flow along a wire instead of a resistor right next to it?

So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

Simple: It does go through the pull down resistor. But  it also goes down the "input" wire.

For simplicity you can imagine that the input is simply a very large resistor. Say, 1MΩ.

The circuit can then be simplified as:

simulate this circuit – Schematic created using CircuitLab

Contrary to popular belief, current does not take the path of least resistance. It takes all possible paths. The quantity of current through each path is proportional to the resistance of the paths.

In this example we have two paths - one with 10kΩ and one with 1MΩ.  That's a ratio of 1:100, and the current will be split accordingly.

You can calculate the current that flows through each resistor simple using Ohm's Law because the wires and switch are (in an ideal world) just not there. The 5V is directly connected across each of the resistors.

So for the 10kΩ resistor the current through is is:

     V      5
I = --- = ----- = 0.0005 = 500µA
     R    10000

And for the 1MΩ it is of course 100x smaller (I'll let you do the maths for that if you want to check), so 5µA.

The full current that the circuit takes is 505µA, with it split between the two resistors.

With the Arduino instead of the 1MΩ resistor it's exactly the same (though the current values may vary somewhat).  500µA flows through the 10kΩ resistor, and "some tiny current" flows through the Arduino.

However, with all that said, the Arduino really doesn't care about the current. All it cares about is the voltage. With the button pressed both the input and the 10kΩ resistor are connected directly to the 5V supply - so the Arduino reads that as "HIGH". When you release the button the input is now connected to ground through the 10kΩ resistor, but there's no current to flow, so there's no voltage across the resistor (the voltage across a resistor is proportional to the current flowing through the resistor - Ohm's Law), so it's as if the input is connected directly to ground - and the Arduino reads that as "LOW".

To be more technically accurate the input of the Arduino is actually more akin to a tiny capacitor.  When you apply 5V to the input it charges that capacitor up. Once it reaches 60% of 5V the Arduino recognises it as a "HIGH" signal.

When you release the button that capacitor is then connected to ground through the resistor, and it discharges through that resistor. Once it drops to 30% of 5V the Arduino sees it as being "LOW".

If you don't have the pull-down resistor, when you remove the 5V from the input that capacitor is still charged. So the Arduino still sees it as a HIGH. The charge in the capacitor will slowly bleed away until it's low enough to be seen as low.

But, (and it's a big but), the capacitor is very sensitive and can be charged up again by ambient energy around the place (radio waves, static electricity, etc). It can harvest enough energy from the environment to get back up to the 60% of 5V and be seen as "HIGH" again. This is known as "Floating", and is something you do not want in your circuit. The input "flaps around" between HIGH and LOW with no control.  Which is why the pull-down resistor is absolutely essential.


Is it possible to use LCD (the 16 pins) without potentiometer?

Sure. You can use two resistors in series to be a "fixed value" potentiometer.

The "wiper" of the potentiometer is the junction between the two resistors.

I can't tell you what values to use, so you'll have to experiment. You want them to add up to somewhere in the tens of kilo-ohms though, ideally, though the value isn't that critical - it's the ratio between the two values that is of interest, and it's that which gives you your contrast setting.


Immediately after making the request when reading client.available() will be 0 since no data was received yet so:

  while(client.available()!=0)
  {
    content = content + String(char (client.read()));
  }

Will never actually run. Try something like:

unsigned long last = millis();
String content = "";

while(client.connected()) {
  int len = client.available();
  if(len > 0) {
    last = millis();

    char buff[len];
    for(int i = 0; i < len; i++) {
      buff[i] = client.read();
    }
    content += String(buff);

  } else {
    if(millis() - last > 2000) {
      client.stop();
      return;
    }
    delay(1);
  }
}

Also note if you use Connection: close on the client then you must close the connection. This example doesn't do that until 2 seconds have passed. To do this properly you'd need to also add header parsing to your client and close the connection once the amount specified in Content-Length is received.


Writing to serial LCD seems to interfere with servos

You are using SoftwareSerial which turns interrupts off when sending/receiving in order to precisely time gaps between bits. The Servo library may use hardware timers, but to work on pins 12 and 13 would require interrupts to "copy" the pulses to those pins. Thus the copies will be distorted when writing to, or reading from, SoftwareSerial.

I suggest using hardware serial (pins 0 and 1) for talking to the LCDs, which does not turn interrupts off. Alternatively, implement the servo positioning using the hardware timers yourself, which (once set up) won't change the pulse widths if interrupts are turned off.


Arduino Text Scrolling on 16x02 I2c on NodeMcu (ESP8266-12)

Inspecting the library code, it is apparent that the method called only sets up a command bit field and it is actually the display that performs the operation.

So, you might check if your LCD is capable of performing the scrolling operation.

This web page contains a tutorial on how to use the scrolling feature.  In this code example from that page:

void loop() {
  // scroll 13 positions (string length) to the left
  // to move it offscreen left:
  for (int positionCounter = 0; positionCounter < 13; positionCounter++) {
    // scroll one position left:
    lcd.scrollDisplayLeft();
    // wait a bit:
    delay(150);
  }

...you can see that it is not automatic.  That you need to call the method each time you want to scroll (in this case) one position to the left.


You could also give my ThreadHandler library a try

https://bitbucket.org/adamb3_14/threadhandler/src/master/

It uses an interrupting scheduler to allow context switching without relaying on yield() or delay().

I created the library because I needed three threads and I needed two of them to run at a precise time no matter what the others were doing. The first thread handled serial communication. The second was running a Kalman filter using float matrix multiplication with the Eigen library. And the third was a fast current control loop thread which had to be able to interrupt the matrix calculations.

How it works

Each cyclic thread has a priority and a period. If a thread, with higher priority than the current executing thread, reaches its next execution time the scheduler will pause the current thread and switch to the higher priority one. Once the high priority thread completes its execution the scheduler switches back to the previous thread.

Scheduling rules

The scheduling scheme of the ThreadHandler library is as follows:

Highest priority first.
If the priority is the same then the thread with the earliest deadline is executed first.
If two threads have the same deadline then the first created thread will execute first.
A thread can only be interrupted by threads with higher priority.
Once a thread is executing it will block execution for all threads with lower priority until the run function returns.
The loop function has priority -128 compared to ThreadHandler threads.

How to use

Threads can be created via c++ inheritance

class MyThread : public Thread
{
public:
    MyThread() : Thread(priority, period, offset){}

    virtual ~MyThread(){}

    virtual void run()
    {
        //code to run
    }
};

MyThread* threadObj = new MyThread();

Or via createThread and a lambda function

Thread* myThread = createThread(priority, period, offset,
    []()
    {
        //code to run
    });

Thread objects automatically connect to the ThreadHandler when they are created.

To start execution of created thread objects call:

ThreadHandler::getInstance()->enableThreadExecution();


What line ending are you using in your IDE? Because if it is other than 'no line ending', you are also sending a new line, carriage return or both. Those control caracter get included in mystring.

Better to be safe and filter out control caracter. Try this:

String mystring = "";

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

void loop() {

  while (Serial.available()) {
    delay(10);
    char mychar = Serial.read();
    if (mychar == '\0')
      break;

    if (isAlpha(mychar)) {
      //  Doesn't include control caracters in mystring
      mystring += mychar;
    }
  }

  if (mystring != "") {
    Serial.print("***"); Serial.print(mystring); Serial.println("***");
    if (mystring == "F") {
      Serial.println("mystring is equal to 'F'");
    } else {
      Serial.println("mystring is not equal to 'F'");
    }
    mystring = "";
  }
}


limit length of the generated timestamp from ESP32 with DS3231 to 13

For getting millisecond resolution out of an RTC, I think the only
viable solution is to sync with the 1 Hz square wave output, as
suggested by Jot in a comment. Note that, since you are only counting
seconds and milliseconds, you probably don't care about hours, minutes,
days, months, etc. So you won't use the RTC for timekeeping: only for
providing the 1 Hz reference signal and, maybe, an initial
timestamp at program startup.

Connect the SQW pin of the DS3231 to an interrupt-capable input of your
MCU. Add the following to your setup():

pinMode(SQW_PIN, INPUT_PULLUP);
rtc.writeSqwPinMode(DS3231_SquareWave1Hz);
attachInterrupt(digitalPinToInterrupt(SQW_PIN), tick, FALLING);

Use the interrupt routine to both keep track of the total second count
(seconds elapsed since the Unix epoch) and record the micros() value
of the last tick:

volatile uint32_t seconds_since_epoch;
volatile uint32_t micros_on_tick;

void tick() {
    seconds_since_epoch++;
    micros_on_tick = micros();
}

Now you can combine these two values to get a millisecond-resolved
timestamp as follows:

uint64_t millis_since_epoch() {
    noInterrupts();
    uint32_t seconds = seconds_since_epoch;
    uint32_t microseconds = micros_on_tick;
    interrupts();
    uint32_t extra_micros = micros() - microseconds;
    uint16_t extra_millis = extra_micros / 1000;
    if (extra_millis > 999)
        extra_millis = 999;
    return (uint64_t) seconds * 1000 + extra_millis;
}

The value returned from this function is the 13-digit number you want,
provided seconds_since_epoch has been sensibly initialized.


Using serial.available to return number of bytes

This is because at the first execution only one byte was received. The Serial interface does not send the data in one big packet of 5 bytes, only because you typed five bytes and started the transmission of all with one press in enter. It is sending the bytes one by one, in other words serial (hence the name). The exact transmission time is dependend on many factors (especially, when other technologies are involved, like the USB interface, when you are transmitting over the Arduinos USB to serial converter).

In this case the first byte is sent, followed by a short break, then the other bytes. The Arduino is fast enough in checking the Serial interface to sense this at 9600 baud.


AnalogRead value constant for a varying voltage (for LED brightness variation)

As CrossRoads says, there really isn't any such thing as analog output on an Arduino. (Any Arduino unless it has a built-in DAC.) It uses pulse-width modulation to vary the "duty cycle" of the output from 100% on to 0% on, which simulates an analog voltage.

If you drive an LED with PWM (and the required current limiting resistor) your eyes will not see the flashes, and will average out the brightness based on the duty cycle of the PWM signal.

If you want an actual analog voltage from PWM you will need to add a filter capacitor to average out the voltage over time. With a simple single capacitor filter you'll still have flutter in the output but it will be closer. If you want a clean constant voltage you'll need a more complex filter.


If you just need to get more inputs you could use multiplexing. The multiplexing method is more robust than software serial will be. How to do this is explained here and datasheet for the commonly used cd4051 here

You don't specify what kind of sensors you will use. if the sensors are i2c or similar it is possible to daisychain (multiplex too) them.


Is there any reason not to solder power leads to the lugs for the power in socket on the reverse side of a mega 2560 rev 3 board?

Soldering to the underside of the connector is exactly the same as plugging something in to the connector.

Yes the regulator will be used.

No the polyfuse will not be used - that is in the USB power circuit not the barrel jack power circuit.


Library to send large amount of data over 433 MHz

Radio modules send packets of data (and for very good reasons) so, if the total size of the data you want to send is greater than the packet limit, you have to engineer a higher level system (called a protocol) that can split your bigger message up into chunks that can be handled by the .h file.

I'm not saying one isn't available and indeed you may find one but, if you don't find one, you are facing the design of a protocol to handle bigger messages. It's not too difficult - imagine splitting the data you wish to send into 64 byte chunks and appending a single byte at the start of the data that describes the packet payload: -

As being a full message
As being a start of message (message overruns 64 bytes)
As being a mid message
As being an end of message (i.e. the last few bytes of data in the message)

This is enough information for your receiver code to reconstruct the original message but make sure you do good error checking if there isn't sufficient in the .h code. And also make sure your receiver "acknowledges" each packet received as being error free.

You might also wish to embed an address that makes your transmission and reception more robust or even add a packet count to the mid message marker byte. You have a maximum of 77 bytes for the payload so you have a few bytes spare for improving integrity but, the minimum payload system is 1 byte header and 76 bytes of payload (which may include other checks like CRC).


Small, Power-Efficient wireless communication with ATTiny85

I've also had good results with using the Mchr3k - Arduino Manchester Encoding library with those 315mhz RF kits. It has support for ATTiny85 as well.


Suggest some highly sensitive temperature sensor

You can use the LM35, is a Precision Centigrade Temperature Sensors with TO-92 package or SO-8 SMD package.

Here is a tutorial of how to use.

Its very simple to use it.


Arduino MySQL Connector Issues with Select only

I have no access to a compiler, so there might be errors.

#include <WiFiEsp.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192,168,x,x);
char user[] = "francis";
char password[] = "xxxxxx";

char ssid[] = "PintoLoco";
char pass[] = "xxxxxxxx";

WiFiEspClient client;
MySQL_Connection conn( (Client *) &client );
MySQL_Cursor *cur_mem = null;

// PPK: some database systems are case sensitive
// so Peceras.Parameters is not the same as peceras.parameters
// check if the tables and fields are named correctly.
char query[] = "SELECT Value FROM Peceras.Parameters";

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

  Serial.println( "Connecting to WiFi" );
  WiFi.init( &Serial1 );
  int status = WiFi.begin( ssid, pass );
  while( status != WL_CONNECTED )
  {
    status = WiFi.begin(ssid, pass);
  }

  Serial.println( "Connected to network" );
  IPAddress ip = WiFi.localIP();
  Serial.print( "My IP address is: " );
  Serial.println( ip );

  Serial.println( "Connecting DB ..." );
  if ( conn.connect( server_addr, 3306, user, password ) )
  {
    Serial.println( "DB connected." );
    cur_mem = new MySQL_Cursor( &conn );
    row_values *row = NULL;
    long head_count = NULL;
    column_names *cols = cur_mem->get_columns();

    cur_mem->execute(query);

    do
    {
      row = cur_mem->get_next_row();
      if ( row != NULL )
      {
        for ( int f = 0; f < cols->num_fields; f++ )
        {
          head_count = atoi( row->values[f] );
          Serial.print( "Ingestelde Temperatuur:  ");
          Serial.println( head_count );
          if ( f < cols->num_fields - 1 )
          {
            Serial.println(',');
          }
        }
        Serial.println();
      }
    } while (row != NULL);

    // Deleting the cursor also frees up memory used
    // PPK: I'm not sure if this is a good idea, I don't know
    delete cur_mem;
  }
  else
  {
    Serial.println( "DB Connection failed." );
  }
}

void loop()
{
  // PPK: I would recommend to do the select in the setup section
  // It looks like you want to run it just once
}

Edit

Please note, that this code only works if you connect the software serial pins D2, D3 to the respective RX and TX pins on the Shield. You have to bend the pins (P0-P3) of the shield to disconnect them from the Arduino. Then you have to connect D2 and D3 to P0 and P1. This is described in step 1 of the instructables you linked to in the question. See the picture at the end of Step 1. https://www.instructables.com/id/ESP8266-ESP-12E-UART-Wireless-WIFI-Shield-TTL-Conv/


How many transistors can be connected to Arduino pins?

The TIP122 is a 100V, 5A, Hfe at least 1000, darlington NPN transistor. With the base resistor of 2k2, that is about 1 or 2 mA per pin. You don't have to worry about a few mA.

To answer your question: "How many transistor can be connected to arduino pins?", that will be about 100.

Why do you use TIP122 ? They have a voltage drop. Logic level mosfets have a very little voltage drop and thus they stay a lot cooler.
Mosfets leak at a higher voltage. If you need to operate near 100V, there are IGBT transistors for that.

Make sure that the high current through the TIP122 at the emitter does not disturb the GND of the ATmega chip. You have to design your circuit board to avoid such troubles.


How to exclude a ino/pde file from Arduino projects

One possible approach is to guard the body of that sketch with an #ifdef ... #endif pair, and use Visual Micro's  “Project Properties” to define (or not) a preprocessor symbol.  [If the .ino or .pde in question is used as a #include file, you would instead guard all the #include instances.]

Refer to the “Project Defines” page at visualmicro.com for how to define a preprocessor symbol and its value. [Via: Tools > Options > Visual Micro > Compiler > Show Build Properties]  Also see  How do I add additional compiler switches in Visual Studio.

If necessary, you can use other tests besides #ifdef to control compilation.  The first link above shows the following example.

#if USBPORT > 3
....your code here....
#endif


I don't know why this type of come in my program expected initializer before 'if'

Your if statements are also incorrect, in your code you're assigning values if(i=1){ rather than testing for them if(i==1){ see Arduino If reference


Question about browsing the web using arduino

You just have to install Chromium and call the desired page.

No, just kidding. I don't think you will ever fit a parsing and rendering engine on an arduino. Chromium for example takes about 150MiB of storage and depending on the opened page hundreds of MiB of RAM. Both of which is multiple orders of magnitude larger than the Arduino has to offer.

You might want to consider going to use a SBC like the Raspberry Pi for such usecase.

Alternatively you can query the data over network and write your own rendering code for the TFT display.


How does this code line detect if a serial interface is connected?

You're right -- it doesn't work in most cases, and will almost always return true. The one board where it's actually functional is the Leonardo. According to the official documentation:

  On the Leonardo, if (Serial) indicates wether or not the USB CDC serial connection is open. For all other instances, including if (Serial1) on the Leonardo, this will always returns true.

Basic serial connections (used by most Arduinos) usually don't care if anything is actually listening. It's not uncommon for embedded devices to send debug info by serial even when nothing is receiving it. This has the advantage that the code's timing and behaviour won't change when debugging, which could cause all sorts of problems if you're trying to diagnose a problem reported in the field.


How to get constant readings from hall effect sensor

Does the value change if there is nothing else connected?
Do you have a constant supply from your PSU?

I'm not great with electronics, but since its a real device not a theoretical device I suspect you are always going to get some fluctuation.  Could you look at adding extra components to smooth the flow to the device, possibly a capacitor?  Is it possible to supply the sensor from an independent supply that you smooth and then any devices added to the Arduino would cause an affect.

Is it possible you are not supplying enough power to the Arduino?

Could you look at taking an average with a sliding window say the last 10 values?


The usual Firebase library for esp8266 is https://github.com/FirebaseExtended/firebase-arduino.

And there is some new Firebase library in Library Manager in IDE. The "More info" link leads to https://github.com/mobizt/Firebase-ESP8266


I need 70 or more input pins for the Arduino -how to do this?

The best way I know to do it is by using the MCP23017, which gives you 16 extra GPIOs via I²C communication. They can be configured for both input and/or output. I've done it myself and it worked like a charm. It has 3 pins for dynamic addressing (3 bits), which allows you to use up to 8 (0..7) MCP23017 for a total of 128 extra GPIOs.
This is the chip datasheet:
(http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf)
There's a lot of examples about its use on the internet. Just google for "MCP23017 arduino" and you'll find them. For example:
http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/


Arduino esp8266 some times data will not be sent to thingspeak.com

َAbout first question I found after AT command AT+CWJAP="network","password" it takes a while to have  active and ready wifi connection  , so I used a 30 seconds delay after this command and then send sensor data toward thingspeak.com ,  now  problem is solved .


USB mouse/keyboard passthrough feasible?

To connect an external USB device to AVR you need USB Host supported on AVR side. Overhelming majority of AVR chips supports USB device only. There is e.g. AT90USB1287 chip exception. It even exists an AVR USB Key 2 device which can be used instead of normal Arduino unless you want make own PCBs.

Arduino UNO Mouse HID emulates USB mouse internally in Arduino. Implementing is easy when you have USB device AVR chip using LUFA library. But it's not case using external mouse. On the other side you can use legacy serial mouse or PS/2 keyboard as workaround.


In your program there is this line of code:

  return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);

Which appears to return a 1 if A is greater then B other wise it will return a 0.  This code can not tell the difference between A < B and A == B.  Consider altering this line of code to allow returning 1 for A > B, 0 for A == B and -1 for A < B:

  return redA->rssi > redB->rssi ? 1 : (redA->rssi < redB->rssi ? -1 : 0);


How to keep a specific bit set all the time for bit masking I2C operations?

'static' just avoids reinitialization and is used for local vars in timed interrupts for example.

volatile is another keyword you should not be using without thinking about it and does not appear to be useful for your case. See https://stackoverflow.com/questions/4592762/difference-between-const-const-volatile for more information

The appropiate keyword would be const, which tells the compiler this var mustn't be changed.

But I suspect there is another problem with your code, which will make the compiler throw an error as soon as you use const in the declaration.
I assume you are not using the variable correctly. You are meant to use a bitwise OR | in order to set the required bit along your actual data.

So do it like this:

data_byte |= bitmasking;
write8(data_byte);


My guess is your drawing too much current from the Arduino 5v rail.

Try connecting the servo to it's own 5v source with of course a common ground with the Arduino.


Dimmer on Due: digitalWrite on one pin affects digital value of another

There are a few issues with your circuit.

First, you need to add a diode to your 4N25 circuit.  See EDIT below.     You should still put a diode across your 4N25 LED.  Right now, your 4N25 diode (LED) gets a high voltage across it 1/2 of the time.  Because you have 60K (30K+30K) in the circuit, the LED is likely not damaged, however the LED isn't really designed to handle reverse voltage more than 6 volts. Depending upon the reverse characteristics of the Bridge diodes (leakage current), your 4N25 LED could be experiencing greater than 6 volts.  Using devices beyond their "maximum specification" can produce unusual side effects.

Place the new diode (1N4007 is good, almost any diode will work) across the LED on your 4N25. Wire the new diode with new diode anode to the LEd cathode. Now, the LED will turn on during 1/2 cycle of the AC,  and be protected against overvoltage during the other half of the cycle.

Second,  rearrange your circuit for the Triac.  The data sheet for your MOC3043 triac driver shows a typical schematic.

Notice the 39 ohm resistor and the 0.01 uf capacitor in the circuit.  This is called a snubber and will reduce interference and voltage spikes. This type of interference is famous for disrupting low voltage circuits such as micro-controllers.

Without seeing your code, I can't say much on that.  However, I presume that you are trying to detect the zero cross, and then waiting a certain amount of time AFTER the zero cross to turn on the Triac.

  I measured current on the controlPin, it's only 3.2mA

Your 3.2mA may not be enough to drive the LED in your dimmer circuit. You will likely need 10mA to assure proper operation.  You can reduce the resistor to achieve higher current to the MOC3043.

EDIT  :  I just realized that your bridge rectifier protects the LED (4N25) from reverse voltage.


Yes, losses in wires are proportional to the length, so an excessively long wire may not be able to deliver enough power. Many factors come into play here:

higher current consumed by the relay increases the losses
smaller wire diameter increses the losses
the voltage required by your relay defines how much you can afford to lose

For example, a pair of AWG23 wires 30m long will have a total resistance of 4 Ohm. If your relay consumes 100 mA, you will lose 0.4V in the wires. If Arduino delivers 5V, and the relay requires a mininum of 4.5V to work, you're just good enough: you're delivering 4.6V to the relay after the losses.


I want to bypass the PGA to change the input signal range from +/-2.5 to 0/5 V range.

Look at the register map. it should allow you to by pass the pga.

  In the example, I have put #define VREF 5 but it shows the double the input voltage in serial window and when I put VREF 2.5, it shows regular input voltage.

Simple solution: divide the library's output by 2.

Right solution: the library likely doesn't support bipolar output. So re-write  your own.


You can just solder everything you need to the Arduino (I would recommend using an Arduino Mini since it has no communication port) and coat it with Silicon Conformal Coating. It creates a silicon layer on top of the PCB that would not let any moisture through. Or you can just put it in a case and cover it with epoxy, that will be even more protection, but there will be no more access to the board unless you foresee it.


Can I make so when I press a button on my Arduino Uno board, it will press a key on my computer?

Not without extra software on your computer side.

However if you use Arduino Micro, you can emulate keyboard and/or mouse directly.


Using an Arduino to drive a digital RGB LED strip

I can not find detailed information regarding the 5M LED strips you bought.

I have used Adafruit addressable LED strips.  What Adafruit publishes on their web site helped a great deal when I cut my strips into smaller sizes.

Here is an Adafruit image which may help you:

I would think the order does not matter.  But you do need to connect the data such that "outs" go to "ins".  And you need to connect them in a row.  That is you need to connect them in one loop.

Added later...

Assuming we are using the WS2812:

We know from the specifications that the RGB data is encoded as 3 8 bit NZR (Non Zero Return) pulses.  8 bits for each color: red, green & blue.  That there is 1 such "word" of 24 bits for each pixel.  That the beginning of a set of "words" is marked by a 50us or grater interval where DI is zero.  And that each pixel strips off the first 24 bit "word" before passing the balance of the data on.

In other words, it doesn't matter what order WS2812 are assembled in.  Also that WS2812 have no idea where they are in the sequence.  All that matters is that each succeeding WS2812 gets its data from the previous WS2812.

One last note. The necessary timing is really fast and really tight. Can't be more than 150 billionths of a second off. No way can a multitasking platform like a PC, Mac or RaspberryPi pull this off.  When sending off a set of "words" to a string of pixels, the embedded processor will likely not be doing anything else!


The first thing that about Load Cells that always comes to my mind is the circuit which amplifies the load cell's signal, Usually the load cell signal changes in a low mv range, so you have to put a high gain circuit in the way of the signal, which amplifies signal and NOISE. You have to use an instrumentation amplifier for this purpose, otherwise, your signal would become so noisy.

And try to implement a low pass digital filter too, it should compensate the fluctuations and would give you smoother signal.


How do I download a sketch to an Arduino semi-permanently?

Download the Arduino software (IDE, or Integrated Development Environment).

In our case, we only need to download and run Windows Installer and follow the pop up instructions.  When asked if you want to install the Arduino driver, just press Yes.

Connect your Arduino Nano board to your computer.

In this step, Windows should automatically find the proper Arduino driver and install it, and your Nano board should be ready to use.  If not, please refer to the above mentioned instruction for details on installing the drivers.  Some compatible Nano boards such as DCCduino manufactured by a Chinese company use different USB-to-Serial chips so they require to install different drivers, but the installation should be quite straight forward once you have downloaded the proper drivers from internet.

Launch the Arduino application.
Open the blink example.

Open the LED blink example sketch: File > Examples > 01.Basics > Blink.

For those who are not familiar with Arduino sketch, a sketch is simply a program with various instructions telling Arduino board what to do.

Select your board.

You’ll need to select what type of Arduino board you are using.  In our case, simply select Tools > Board > Arduino Nano w/Atmega328.

Select your serial port

You also need to select the serial device of the Arduino board: Tools > Serial Port.  Usually the port number will be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect your Arduino board and re-open the menu; the entry that disappears should be the Arduino board. Reconnect the board and select that serial port.

Upload the program to Nano board

Now, simply click the “Upload” button in the environment. Wait a few seconds – you should see the RX and TX leds on the board flashing. If the upload is successful, the message “Done uploading.” will appear in the status bar.

A few seconds after the upload finishes, you should see the pin 13 (L) LED on the board start to blink (in orange). If it does, congratulations! You’ve gotten Arduino up-and-running.

Disconnect from your computer and connect to a power supply to see the blinking light.


Where are the chip configurations stored in IDE 1.6.x? How to modify them?

You are importing a json file provided by someone for free.
The best thing you can do is contribute by adding ATTiny13 to this repository.
To do so:
So go to github (create a account if you do not have one);
create a fork of the repository.
Add your ATTiny13 board to the boards.txt file.
mod the json file to contain a new version and the attiny13.
Test and if everything works fine
Create a pull request


Connecting Web Server in GoDaddy Hosting

I have a domain.

Congratulations.

It is hosted by GoDaddy.

You have my deepest sympathies.

I need to connect that server and receive some data by executing PHP files.
I am not sure about the components.
Tutorials on internet describes how to control esp8266 from web server which is i do not want.

"Controlling" an ESP8266 from a web server is nothing more than making a request to a web server and responding to something the web server sends back.
If you don't want to respond to what is sent back you don't have to. You just have to make the request. That request can contain whatever you want in the way of data and sensor values.

Also i found arduino uno wifi board/wifi shield but in arduino store, it says: this product is 'retired'.

Yes. It's been replaced with the Arduino WiFi Rev 2, which is a more modern AVR MCU coupled with an ESP32 based WiFi interface.
It's pretty wasteful really, since the WiFi interface is considerably more powerful than the AVR that it's connected to.

So do you recommend any component for this task or should i go with arduino uno wifi?

I'd recommend an ESP32 based board. They're cheap, have direct connection to WiFi, very very powerful, plenty of inbuilt peripherals (unlike the ESP8266), and above all have great software support, examples and tutorials.


Low Power library messing up serial text

The problem is most likely that the system is going to sleep while it's still sending the serial data.

Forcing all the serial data to be sent before you go to sleep should fix the problem (serial data is sent in the background using an interrupt so as to keep sketch slowdown to a minimum):

Serial.flush();
LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);


This should not be the solution to your problem which is btw. not exactly clear. Do you want to prevent people outside of this range to connect, or do you have some sort of interference problem (in this case it might be legitimate)?

Unauthorized access should not be controlled by range because it depends not only on your sender antenna but also on the gain of the receiving device. Anyways, in the frequency bands and energy levels of a Bluetooth antenna a potentiometer will not work.

Implement access control beyond the pairing in your application.

There should be some fancy Bluetooth devices that allow for energy control. Especially, low-energy devices.


Converting each digit in an integer to its respective ASCII characters

To convert a whole number to a char array in one go use the itoa function. That sounds like what you actually need.

To convert one digit from decimal to ascii just add '0', the ascii value for a 0. If you just want to try to understand what's going on, it's something like this.

char result[4] = {0};
int num = 345;

int digit = num % 10;  // get the 5 off the end
result[2] = digit + '0';  // convert to ascii and store
num /= 10;   // get rid of the 5
digit = num % 10;   // get the 4 off the end
result[1] = digit + '0';  // convert to ascii and store
num /= 10;   // get rid of the 4
digit = num % 10;   // get the 3 off the end
result[0] = digit + '0';  // convert to ascii and store

Serial.print(result);  // prints "345"


Recommendations For High Capacity Microcontrollers

In a comment, Juraj wrote:

the ATmega MCUs are similar so a port to Arduino Mega should be
possible

This seems indeed to be very much the case.
Looking at the source code of the library, it appears it uses
timer 2 for generating the PWM signal and timer 1 for
scheduling the samples. These timers are almost identical between the
ATmega328P of the Uno and the ATmega2560 used in the Arduino
Mega 2560. The only relevant difference between these boards, as
far as the library is concerned, is the output pin, which is the “OC2B”
pin of the microcontroller:

on the Uno, OC2B is digital pin 3
on the Mega, OC2B is digital pin 9

So my guess is that the library should work on the Mega with just this
tiny change:
--- a/Talkie/talkie.cpp
+++ b/Talkie/talkie.cpp
@@ -71,7 +71,7 @@ void Talkie::say(uint8_t* addr) {
        //
        // Enable the speech system whenever say() is called.

-       pinMode(3,OUTPUT);
+       pinMode(9,OUTPUT);
        // Timer 2 set up as a 62500Hz PWM.
        //
        // The PWM 'buzz' is well above human hearing range and is

Also, make sure you plug your headphones on pin 9 rather than
pin 3.
If you try this and it works, please report that either here or directly
to the author of the library. It should then be easy to modify the
library to support both boards out of the box.

Edit: If you download Talkie through the Arduino library manager,
you will get this version, which does supports the Arduino
Mega 2560.


Posting TinyGPS++ co-ordinates as paramaters with GPRS

One solution may be to split the commands:

gsm.print("latitude=");
gsm.println(latitude);

I'm not sure how you should pass multiple parameters; if it is the usual syntax you can write something like

gsm.print("latitude=");
gsm.print(latitude);
gsm.print("&longitude=");
gsm.println("longitude);

If I have the time I'll research into this a bit.

To check what is the problem, you may try to send "static" messages, like

gsm.println("latitude=12.345");

To check if this format is the correct one

EDIT: after a very quick research

It looks like the AT commands are a bit more complicated. In order to send the parameters, at least on a SIM800L, you should:

send the HTTPDATA command (the first parameter is the length of the payload)
wait for the board to send you the command DOWNLOAD
Send the body of the request, which is formatted as a JSON object. This means you have to send something like { "latitude" : 12.345, "longitude": 98.765 }

After all, it is much faster to use a library already developed for this, for instance ArduinoSIM800L (check a library available for your GPRS modem, or modify this one)


You don't specify the sensor you're trying to emulate, so we can't tell you exactly how to do it.

The obvious hardware approach would be a potentiometer.

You could also do it in software by writing a function to get the value, and temporarily replacing its implementation with one which generates random values, or reads values from a serial port, or reads them in order from a hard-coded array, or calculates them according to the time, or whatever you want.


No. Not directly. You can use voltage divider and measure the result with using internal reference. But it's another current consumption and you can't reduce it by (for example) entering one of the sleep modes.

And if you have 5V Arduino Mini variant, you can power it directly through 5V power pin. Otherwise you are losing about 1.5V on voltage regulator. On 3.3V variant it might be better, but it also depends on used regulator voltage drop and would be better to power it directly (if you don't have connected anything strictly with 3.3V power, and for AVR based Arduinos it's not a problem)

Anyway, if you power it directly, you can measure the power source voltage by measuring internal bandgap voltage reference against power as reference. But, as far as I know, it can't be done by analogRead, as it doesn't support other sources than analog pins.


The ESP8266 is power hungry, the Arduino may not have enough output current to power it.  Also, which voltage regulator you're using matters, as some have higher dropout than others.


Arduino Nano + (2* tlc5940) + 34 LEDs = Power Questions

As Ignacio has mentioned the TLC5940 is a constant current driver. The 2kΩ resistor sets the current for the LEDs regardless of the forward voltage (or colour) or the supply voltage.

Also as Gerben says, move the 0.1µF (100nF) capacitor close to the TLC5940 as you can. There should be one for each TLC5940 since they are decoupling capacitors.

You might like to increase the capacitance of the electrolytic too. The purpose of that capacitor is to provide a low impedance energy source to supply the circuit (batteries are actually quite high impedance by comparison). Since you have lots of LEDs being controlled by PWM the current draw will be fluctuating wildly all the time, and lots of energy over brief periods will be wanted.

Another thing to watch, mentioned again by Ignacio, is the supply voltage for the TLC5940 is 5.5V absolute maximum. I wouldn't go much above 5V. Depending on what your batteries actually are you may be better running from 3 of them (4.5V alkaline AA - Ni-MH would be ~3.6V, so 4 of them, giving 4.8V, would be better in that situation).

I would also question your use of the TLC5940. They are not the easiest chips to drive requiring quite a strange protocol. Personally I prefer the TLC59116 which is the I2C variant of the same chip. Much easier to control from an Arduino, and requiring just 2 pins. Not so easy for bread-boarding though as they're SMD only.


Arduino DS3231 error: no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&)'

Alright I found the problem.
https://www.youtube.com/watch?v=BM3A7w3bhqM&ab_channel=MERTKILIC
In this video at 5:00 you can see the following:
First you have to download the library, unzip it and copy the files inside.
You will have to paste it to your Arduino/Libraries/DS3231 folder.

On the left is the current DS3231 Library which I added through the arduino library manager. Its not the same as the one the right, it should be, but its not, copy the files from the unzipped DS32321 library into the Arduino/library/DS3231.
Works fine now !


I recommend you get a MicroSD card breakout board from that link, or something similar. That's around $US 15.

That includes the logic level converters. That particular board is for the **micro* SD card, but similar converters could no doubt be found for an SD card. Or use that one with a micro-SD card and just get an SD converter for when you plug it into the Mac.

I personally have used the SDfat library without any problems. However since he started rewriting it, I did have some issues. I have a backup of an earlier version which might be useful if the live library doesn't work for you.

You might be best off not formatting the card, but leave it as factory formatted. That will probably be compatible with the Mac, and also the SDfat library.


Arduino - Raspberry Pi serial communication

You CAN NOT reliably power any model Pi from the Arduino 5V output.
You can interconnect the Arduino serial to the Pi using a voltage divider or (preferably) a level converter, as suggested in the linked article. (I might add that the linked article contains a number of errors which will not work on recent Pi models).

Better still you can use a USB connection, to provide serial communication to the Arduino, AND you can power the Arduino from the Pi (I often do this).


Yes, you could make a global String for getData and reserve space and reuse it every time the function is called. But what with String(getData.length())?

And the parameters? You create a new String for every parameter. And the function senddata doesn't take a reference to the String (String&), but it makes a new copy of each String parameter. So you create 12 small Strings with every call to this function. This is the evil of String. It does everything no matter at what cost.

And your sendCommand takes String too. That is why you can do "AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT and "AT+CIPSEND=0," + String(getData.length() + 4) as parameter to it. So every call to sendCommand creates two small Strings. That is 8. And every + on String can trigger a reallocation on heap.

Use C strings

void senddata(int temp1, int hum1, int dis1, int flood1, int heater1, int humid1) {
  char getData[256];
  snprintf(getData, sizeof(getData), "GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d",
      API, temp1, hum1, dis1, flood1, heater1, humid1);
  sendCommand("AT+CIPMUX=1", 5, "OK");
  char buff[32];
  snprintf(buff, sizeof(buff), "AT+CIPSTART=0,\"TCP\",\"%s\",%d" , HOST, PORT);
  sendCommand(buff, 15, "OK");
  snprintf(buff, sizeof(buff), "AT+CIPSEND=0,%d" , strlen(getData) + 4);
  sendCommand(buff, 4, ">");
}

void sendCommand(const char* command, const int timeout, const char* find) {

F macro optimizes memory use, by using data stored in flash memory. The snprintf_P function is a version of snprintf for format string from flash.

snprintf_P(getData, sizeof(getData), (const char*) F("GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d"),
  API, temp1, hum1, dis1, flood1, heater1, humid1);

One of the classes of my StreamLib is CStringBuilder. With it the code could be:

char getData[256];
CStringBuilder sb(getData, sizeof(getData));
sb.printf(F("GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d"),
    API, temp1, hum1, dis1, flood1, heater1, humid1);
sendCommand("AT+CIPMUX=1", 5, "OK");
char buff[32];
CStringBuilder sb2(buff, sizeof(buff));
sb2.printf(F("AT+CIPSTART=0,\"TCP\",\"%s\",%d") , HOST, PORT);
sendCommand(buff, 15, "OK");
sb2.reset();
sb2.print(F("AT+CIPSEND=0,"));
sb2.print(sb.length() + 4);
sendCommand(buff, 4, ">");


How to add indicator lights to button sketch

I'd suggest creating an array of MIDI button structs. For each entry you'd have a button object, an LED pin, and a BOOL to track the state of thate button.

Write a function that loops through the array of structs, checks the state of each one, and does the work to play/stop the notes and toggle the LED states based on the state of each button.


Previous and updated releases of Arduino IDE are not be able to start on Win 8.1 x64

I had the same problem with various IDE versions. Deleting the preferences.txt solved the problem for me.


Use an eInk/ePaper style display, which uses no power while the display is not changing.  These come in monochrome greyscale, and have excellent readability.

This solves only part of your problem as you still need to power the CPU.


Sending multiple byte data from Arduino as Slave on SPI

With SPI there is no such thing as "sending" and "receiving".  It is a full duplex operation every time. Whenever the master runs the clock the slave both receives bits from the master and simultaneously sends bits to the master.

These operations are inseparable.

Whatever mechanism you are using to recognise "A byte has arrived from the master" is the same mechanism that you use for filling the SPDR register. The bytes where you "send" data to the master are actually bytes where the master is sending you data, but you don't care about what that data is. Just like when the master is sending you "commands" you are sending the master data (which you haven't specified) and the master "doesn't care" what that data is.

It's up to you to keep track of how many bytes the master has clocked in and out, and to say "For bytes 19-23 the master is expecting valid data, so I need to make sure that I put data into the SPDR for those bytes".


Here you will find a lib for all M24SR NFC tags
In this test sketch you find details how to connect and test the tag with Arduino. If it helps mark as accepted to help others.


How to work with non-traditional UART baud rates

The Arduino Nano cannot do 800 kb/s. As you can see in the source
code, the bit duration is rounded to the nearest multiple of
8 CPU cycles. In your case, it is rounded to
3 × 8 CPU cycles, which yields a baud rate of
666.666 kb/s. That is 16% too slow, an error too large for any
communication to be possible.

At 400 kb/s there is no rounding error, so everything works fine.

Edit: Note that if you build your own barebones
Arduino, then either a 12.8 MHz or a 19.2 MHz
crystal should allow you to get that exact baud rate. But then
millis(), delay() and co. would all be off.


Why is my liquid crystal display not showing any output?

Your breadboard is one of those which have the power/GND lines interrupted between columns 31 and 33. I also once fell into this trap. If you look closely, you see that the blue and red lines are interrupted in the middle of the board. Just put wires between these pins to bridge the gap.


Error on sending AT+CWJAP_DEF commands to ESP8266

Based on the gibberish echo, the possible causes are:

Insufficient power. You need a source that can supply up to 300mA which is about the max consumption for the module. A good-sized capacitor across the ESP power rails (10uF maybe) wouldn't hurt.
Baud rate is too high. If you're using an Arduino as 'middle-man' and talking to the ESP8266 through a SoftwareSerial port, you're likely to face this sort of issue if the baud rate is as high as 115200; SoftwareSerial is unreliable at such rates.


Millis is driven by an interrupt. The reason it doesn't "work" from inside an interrupt is that you can't have two interrupts running at the same time. So when your interrupt is running the interrupt that makes millis count can't run.

Millis does work in an interrupt as long as all you want is to record a single point in time. If you do anything that relies on millis changing within the lifetime of the interrupt it will break. That is why delay is bad in interrupts.

So from that you can see that it's only when in an interrupt that things can go awry. Everywhere else, as long as interrupts are enabled, both millis and delay work fine.

After all, loop is just a function called by main, and main is just a function called by _startup... Etc...


Can I drive this relay shield with an Arduino Due?

You'd have to remove the yellow jumper. Connect 3.3v to the VCC and 5v to the JDVCC. But please double check that JDVCC is connected to one side of all the relays.

This way the opto-couplers are activated by 3.3v signals, which in turn activate the transistor (5v) used to engage the relay.


Can I control analog IO pins using Yun Linux

There are several libraries which will do this for you. Basically, you should upload a special sketch onto the Arduino, which listens to the serial port, and performs the I/O that the Linux chip requests. Libraries which can do this are

Firmata
Autobahn
LininoIO


How much voltage/current do I need for multiple chips?

You need a voltage regulator for the esp. Preferably a dc-dc step down, which will neither waste power nor heat up. Other, passive solutions are possible but not desirable. The regulator can be found on ebay amazon etc.

EDIT:

One more thing about the LEDs: depending on the model you have, they might or might not work with 3.3V input (I'm assuming you want to drive the LEDs from the esp).

In case they take only 12V input, you will need some interface solution, like this one, for example.


How many WS2811 LED strips can I control with Arduino?

There are three factors to consider when driving strings of these LEDs from an Arduino:

How much memory the Arduino has - each LED takes at least 3 bytes of RAM (possibly more depending on the library implementation). (An Uno could probably just manage 500 at most)
How long it takes to send the data over the wire - the more LEDs you have in a chain the longer each update takes and the slower your animations run.
How you power such a huge number of LEDs efficiently. You won't just plug them into the 5V pin of the Arduino that's for sure.

Note that the arrangement you link to most likely isn't a single small microcontroller controlling the whole lot. Instead it is much more likely each individual strip has a single controller and those controllers are all networked together (probably through RS-485 or CAN) to a master controller (probably a PC) to send instructions to them all.