Mac Arduino IDE Connection to Min Seg (Mega 2560). No tty

What you are seeing is normal.

In BSD (which is the OS that Mac OS is based on) a serial port has two distinct devices for two distinct roles.

The tty, or TeleTYpe interface is used for incoming connections, be that from a modem, serial terminal, whatever. You would normally run a process called getty on it to present a login prompt.

The cu, or Call Unix interface is used for making outgoing connections to other devices. Traditionally that was mainly other Unix servers through modems. Nowadays it includes many other devices such as an Arduino.

The theory is that when you try and initiate an outgoing connection through the cu interface it first checks that no-one is connected in through the tty interface and if the serial port is available it disables the tty interface so the listening getty process doesn't interfere with your call. Also the tty and cu interfaces deal with the modem control lines differently.

The Arduino IDE is merely honouring that system by only offering you the outgoing device in the port list. As far as the Arduino communication is concerned there should be no difference.


How to send SMS from an Ethernet shield via SMS Gateway?

First contact Clickatel's support and ask them how to use their API, make yourself familiar with it.

Then when you know that you connect your Arduino to your ethernet shield, I'm just gonna assume you got Arduino's original shield, because you want to support the arduino foundation.

http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the standalone board.
http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the shield board.


How to find the difference between two timestamps

Unix timestamps are just a count of seconds since a standard
origin (1970.0 UTC), thus a simple subtraction, followed by a
conversion from seconds to minutes:

float minutes_remaining = (timeEstimated - timeNow) / 60.0;


Programfault when dereferencing a 64bit int on due

I concur with Majenko's comment: it's probably a memory alignment
problem. I don't know the specifics of the Due, but when you access
memory in chunks of 32 bit data words on a 32 bit CPU, it can
happen that the architecture requires the data words to be aligned to
32 bit (i.e. 4 byte) boundaries. This means that the address
of an uint32_t or uint64_t should be a multiple of 4. Maybe
even 8 for a uint64_t, you will have to check.

The only solution to this issue is to fill the packet byte by byte:

void putData64(byte* packet, int pos, uint64_t data)
{
    union {
        uint64_t integer;
        byte bytes[8];
    } h = { .integer = data };
    for (int i = 0; i < 8; i++) {
        packet[pos+2+i] = h.bytes[i];
    }
}

Note that the AVR (in the Nano) is an 8 bit architecture with no
alignment constraints whatsoever.


Arduino IDE not compile .S program to board

There's four things I can see wrong (one of which is my fault, actually - I should have mentioned it in the previous question - nevermind).

Firstly you cannot include a .S file in a .INO file. A .S file is assembly, a .INO file is C++. You can't mix the two in one file (and including a file does just that - includes the file verbatim at that point). So remove that #include. Otherwise it would be like opening a book written in English only to find the preface is written in Klingon.

Secondly you need to give your function a name. It doesn't have one at the moment. Naming the file is not naming the function.

So you need to provide a label at the entry point:

  .section .text

blink:    ; << This is the name of the function
  ldi r18, 0x20   ; loading 0x20 = 00100000 into register r18
  out DDRB, r18   ; making pin 5 of port B an output

Third you need to export that name as a global symbol:

  .section .text
  .global blink ; << This exports the function name

blink:    ; << This is the name of the function
  ldi r18, 0x20   ; loading 0x20 = 00100000 into register r18
  out DDRB, r18   ; making pin 5 of port B an output

And finally you have the problem of linkage name munging.  You're linking a C++ file with (ostensibly) a C file - and C++ munges names. So you have to tell your C++ file that the function is not a C++ function, but a C function (which is what I should have mentioned previously):

extern "C" void blink(); // << Add the "C" to tell it not to munge the name

void setup() {
  // put your setup code here, to run once:
  blink();
}

void loop() {
  // put your main code here, to run repeatedly:
}


Digital Input with long cable - flickering values

That device (datasheet) puts out 3.3V on the OUT pin, not 5V:

  ◦ TTL output: 3.3V, 0V

The excess cable is most likely picking up EMI and creating spurious pulses on the input. There are two basic ways of combating this:

Increase the drive strength (especially the sink capacity) of the output
Implement a balanced line communication system

You can combine both those quite easily, whilst at the same time boosting the output voltage to 5V using a 74HCT04 hex inverter chip (make sure it's the HCT variant).  Powered from 5V it will boost the logic level from 3.3V to 5V, and it will have a greater drive strength than the PIR chip alone.

Then the trick is to use multiple gates in the right way to make a crude balanced line system:

Basically you're double-inverting the signal so it remains the same logic level (high = high, low = low) but has higher drive strength, and you're also single-inverting the signal so it has inverted logic (high = low, low = high).  You then connect those to two different IO pins on the Arduino. Read both pins (instead of just one) and as long as the signal are opposite (Q = HIGH and !Q == LOW) then you have a valid signal. If both signals are HIGH then you have noise and you can ignore it.

You also need to ensure you select the right kind of cable. Ideally you need a cable with at least one twisted pair in it so that the Q and !Q signals are twined around each other. This ensures that if EMI is induced into the wire it's induced into both signals equally.  CAT5 Ethernet cable is often quite a good choice.


Adafruit Gemma unrecognised USB device on Windows 10

I think, you've pretty much done everything. If you could gain access to another board, and try that one you could figure out more. Otherwise your symptoms remind me of a something called an ESD (Electrostatic Discharge) caused malfunction. This basically means one of the system essential chips on the board have been fried. It is very easy to ESD a chip without protection, just walk on a carpet or put on a sweater, and than touch the chip. Chances are you were electrostaticly charged with thousands of volts. The chip does not stand a chance. To prevent this from happening, touch something made out of metal before touching the board.More on ESD: Electrostatic discharge


May arduino hang when current is changing over time?

There really isn't any such thing as "Current driftage". If you draw too much current from your battery it will cause the voltage to drop, and if it drops too much, the Arduino will stop working.

If you have high current devices like motors being switched on the same power supply as your Arduino you should add a reservoir capacitor as close to the input of your Arduino as possible. That will even out short term drops and spikes in supply voltage as your motors switch.

If you draw too much current continuously then your supply voltage will drop and stay dropped, and a reservoir capacitor won't help. In that case you need a higher current battery (or separate power supplies for your Arduino and motors.)

Edit: From your question it's pretty clear that you don't understand voltage and current and how they relate. I suggest you read up on the subject.

In short, the amount of current that flows through a component is determined by the voltage divided by the resistance: i = v/r. (Where i = current in amps, v = voltage, and r = resistance in ohms.)

The current that will flow will be limited by the max current that the power supply can provide.

For a non-regulated supply like a battery, the voltage from the supply will drop as you draw more and more current.

For a regulated supply, the supply keeps the voltage constant up to it's maximum current limit.


Can I automatically loop inside a library?

Generally speaking, no, you can not take control of the processor away from the main "thread" in a library. The normal solution is to provide an update method or something like that. you could do the calculations in a function that returns your boolean answer, then the loop code is basically the same with or without asynchronous updating.

If you can use interrupts to read your input, either as an external interrupt or on an internal timer interrupt, then what you want could be achieved because the interrupt would take control away from the main execution context and give it to you.

Interrupt routines need to be fast and simple though, and it makes the "cost" of using the library higher, since there is a limited number of interrupts/timers and other libraries may require the one you code yours to use.

Of course, the more powerful arduinos that actually run an os will have support for multiprocessing which you could leverage to get the behavior you want. This answer is intended for a standard AVR based arduino (uno, mega, etc.)


Trying to use Nano Every as a sort of USB logic analyzer, but can't isolate it from "device under observation"

@jsotola was correct and the software defined pin directions incorrectly. Looks like I fried one of the pins in the process (multimeter shows continuity between the pin and ground), but when I rewired to a new pin on Port D and ran the corrected software, everything seems to work as expected!


My default modems usually echo back whatever you send.  So if you send AT it will first respond with AT followed by the OK response:

>> AT
<< AT
<< OK

Echoing can be turned off with the command ATE0 and turned back on with ATE1:

>> ATE0
<< ATE0
<< OK
>> AT
<< OK
>> ATE1
<< OK
>> AT
<< AT
<< OK


Assuming you have a distance variable containing the distance measured from your sonar sensor in cm. You can use that value to adjust the delay times in between your steps.

EDIT Modified code to increase speed when distance increases

int time = 0;
int timeWait = 1000; //interval in milliseconds between each distance reading
int maxDelay = 1000;

void velocity(int speed){
   int trim = 10;
   digitalWrite(13,HIGH); // Output high
   delayMicroseconds(maxDelay - speed*trim); // Wait
   digitalWrite(13,LOW); // Output low
   delayMicroseconds(maxDelay - speed*trim); // Wait
}

int readDistance(){
 //code to read distance
 return distance;
}

void setup(){
time = millis();
}

void loop(){
   if(millis()-time > timeWait){ //only read distance if 1000ms has elapsed since the last reading
     time = millis();
     int distance = readDistance(); //your distance reading code;

   }
   velocity(distance);
}`

EDIT 2
You'll also need something to handle upper and lower limits for delays (i.e. you don't want delayMicroseconds(0) or any negative numbers and  you don't want to include extraneous distance readings)


Arduino Uno: how to increase distance of serial communication to PC

There are many options of varying complexities, pros, cons and prices.

The simplest method is to use powered USB hubs to extend the range. It's 5m per run of cable between powered hubs, so if you have access to power at 5m intervals (or can provide power at 5m intervals) you can chain hubs together to increase your distance. That rapidly becomes unwieldy and expensive though.

Assuming you want to keep the ability to directly program your Arduino from the PC without having to mess with swapping cables around, etc, other options include:

USB over CAT5 adapters (up to 100m length)
Bypass the USB altogether and use RS-232 (MAX-232 chips, about 15m length)

There are also some bluetooth adaptors that allow programming of the Arduino, but that gets a bit tricky.

If you're not too worried about programming there are far more options:

Radio options, such as using XBees, nRF24L01 modules, etc.
Networking - connect to an Ethernet or WiFi network
GSM modem
RS-485 / RS-422 - similar to RS-232 but longer distance, and without the signals needed for rebooting the Arduino for programming

The "distance" of the fully networked options is, literally, global. Once on a network you have the option of arranging access from anywhere on the globe with an internet connection

It all depends, really, on what you want to be able to do over the connection.

(I am sure there are many more options I have forgotten - feel free to suggest them in comments, or even go ahead and edit this answer to add them if you like.)


L293D to change the direction current and amplify it - Temperature-Stabilizer

I am interested on this as I have the same issue. What about using a FET or MOSFET to amplify the current that the LM293D provides?


Is it possible to use Maix_Speech_Recognition for speaker-dependent voice recognition on Arduino Uno compatible boards?

No. It's not.

What part of Maix_Speech_Recognition should I modify to make it work on Arduino Uno compatible boards?

Don't even think about it. The UNO cannot do anything even remotely like speech recognition of any form without adding extra specific speech recognition hardware.
Just get a K210 board - they're cheap enough.


How to test if PWM mode is working correcly?

There are my options:

The default way to do this is to use an oscilloscope. These can be quite expensive.
Use a logic analyzer if the voltage is logic/binary (0 and 3.3 or 5V). These are very cheap.
The easiest way to know if it works without the devices above, is to lower the speed drastically (using a divider in the software, like 1000 or more to get PWM widths of 100 ms to multiple seconds) and connect the PWM output with a resistor and a LED to GND. If the LED flashes faster, the PWM speed is high, otherwise low. By using a stopwatch you can roughly calculate the PWM speed (taking the divider into account) and after the test remove the divider.
If the PWM is controlled completely from your Arduino (probably not), you can use a software counter and print it out afterwards to see the speed.


delay(time); vs if(millis()-previous>time); and drift

There's one important thing that you need to remember when working with time on an Arudino of any form:

Every operation takes time.

Your foo() function will take an amount of time. What that time is, we cannot say.

The most reliable way of dealing with time is to only rely on the time for triggering, not for working out when the next triggering should be.

For instance, take the following:

if (millis() - last > interval) {
    doSomething();
    last = millis();
}

The variable last will be the time the routine triggered *plus the time doSomething took to run. So say interval is 100, and doSomething takes 10ms to run, you will get triggerings at 101ms, 212ms, 323ms, etc. Not the 100ms you were expecting.

So one thing you can do is to always use the same time regardless by remembering it at once specific point (as Juraj suggests):

uint32_t time = millis();

if (time - last > interval) {
    doSomething();
    last = time;
}

Now the time that doSomething() takes will have no effect on anything. So you will get triggerings at 101ms, 202ms, 303ms, etc. Still not quite the 100ms you wanted - because you're looking for more that 100ms having passed - and that means 101ms or more.  Instead you should use >=:

uint32_t time = millis();

if (time - last >= interval) {
    doSomething();
    last = time;
}

Now, assuming that nothing else happens in your loop you get triggerings at 100ms, 200ms, 300ms, etc.  But note that bit: "as long as nothing else happens in your loop"...

What happens if an operation that takes 5ms happens to occur at 99ms...? Your next triggering will be delayed until 104ms. That's a drift. But it's easy to combat. Instead of saying "The recorded time is now" you say "The recorded time is 100ms later than it was". That means that no matter what delays you get in your code your triggering will always be at 100ms intervals, or drift within a 100ms tick.

if (millis() - last >= interval) {
    doSomething();
    last += interval;
}

Now you will get triggerings at 100ms, 200ms, 300ms, etc. Or if there are delays in other bits of code you may get 100ms, 204ms, 300ms, 408ms, 503ms, 600ms, etc.  It always tries to run it as close to the interval as possible regardless of delays.  And if you have delays that are greater than the interval it will automatically run your routine enough times to catch up with the current time.

Before you had drift. Now you have jitter.


loop() does not need any time and repeats permanently.
lastButtonState is reading from previous loop run.
As long as the button bounces, lastDebounceTime is updated.
Only when the button has settled (either pressed or released), the condition
  ((millis() - lastDebounceTime) > debounceDelay)

becomes true and the code is executed -> if buttonState (the previous debounced state) and reading show a change to HIGH, the led state is toggled.
Not sure if this explanation makes anything clearer, as it is clear already as it stands, IMO.


Can you put Ardupilot on any flight controller?

There are pre-built binaries for many flight controllers.

http://firmware.ardupilot.org/ lists out the different ardupilot builds (arducopter, arduplane, etc.) and by clicking on them , you can see the different versions, then the different builds per version.

This document goes into more detail on the file structure they use for pre-built binaries.


Why my LCD does not work with this if statement?

On the Uno, pin 0 and 1 are used for Serial. You can't use pin 1 for Serial in addition to the LCD. In general, it's best to avoid using pins 0 and 1.

You need to change the LCD wiring to use a different pin and update the code accordingly. For example, if you moved the LCD's RS pin connection from pin 1 on your Arduino to pin 13, you would update this line from:

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

to:

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

After that, your LCD should work correctly.


Last question first: The ESP8266 is the main IC on the NodeMCU board.

This is similar to the idea that an ATMega328 is the IC on Arduino Uno.

A normal 'clean' Arduino IDE install can work with an Uno ('flash with an INO'), but not with an ESP8266 based board. For this, you will need the ESP8266 addon for the Arduino IDE, after which, the NodeMCU board is available as an option.

This page documents the ESP8266 addon:
https://github.com/esp8266/Arduino

Long story short, open preferences (File -> Preferences) , under Additional Board Manager URLs, add http://arduino.esp8266.com/stable/package_esp8266com_index.json

Click on Tools>Board>Board Manager (assuming you have Arduino IDE 1.6.4 or later) and search for ESP8266 and install the option that includes NodeMCU.


Why is the result of this product operation wrong?

Integer overflow. You're multiplying an int by an int then assigning it to a long.  Instead if you multiply a long by a long, or an int by a long, or a long by an int, it should work.

unsigned long res = 775L * 775;

The L suffix tells the compiler to treat it as a long, not an int.


AT command to put the A6 GSM/GPRS into sleep / power down

A6 module uses a hardware pin (INT/GPIO_1) or (EN) enable on some modules.
There is no AT command as in the SIM900.


Porting the FastNoise c++ library to Due

The FastNoise library compiles as it is for the Arduino MKR and Arduino Zero, but there is a "not cool" issue for the Due: https://github.com/arduino/ArduinoCore-samd/issues/308

A issue with assert can easily be solved, but the #include <algorithm> and #include <random> are somehow linked to a printf function.
I thought it was very hard, but then @Juraj wrote in his answer about the simple solution to comment out the #undef printf line.

In the file cstdio is a list of about fourty #undef lines. Only the printf requires to be commented out.

// #undef printf

The file is located in the hidden "Arduino15" folder in the build environment for the Due: Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio

Then it will also compile for the Arduino Due (even without removing the assert). There are many warnings.

I was able to run it on a SAMD21 processor and it produces random numbers. However, I am not sure that those numbers are correct. I don't know if the many compiler warnings can be ignored.

#include <FastNoise.h>

FastNoise myNoise; // Create a FastNoise object

float heightMap[32][32]; // 2D heightmap to create terrain

void setup() {
  SerialUSB.begin(9600);
  SerialUSB.println("FastNoise");
  delay(1000);

  myNoise.SetNoiseType(FastNoise::SimplexFractal); // Set the desired noise type

  for(int x=0; x<32; x++) {
    for(int y=0; y<32; y++) {
      heightMap[x][y] = myNoise.GetNoise(x,y);
      SerialUSB.println(heightMap[x][y]);
    }
  }
}

void loop() {
}

Do you know the XY Problem? You did not explain the reason for trying to make that library run on a Arduino Due. Perhaps there is an other way for what you want to achieve.

The Arduino Due was a major update for the Arduino boards, but nowadays some say to avoid the Arduino Due because it has issues (hardware and software).

I have updated my answer with help of the answer from @Juray.


I don't understand why you use 2 Serial.available condition.
I try to rewrote your program based on my imagination, so do not hate me if its wrong.
Why don't you try this and tell the results:

int pos = 0,x=0;
void loop()
{
  while (Serial.available() > 0) x = Serial.parseInt();

  pos+=x;
  if (pos>180) pos = 0;
  myservo.write(pos);
  Serial.println (pos);
  delay(100);
}


It's a common-cathode RGB LED module. The LED package itself has 3 independent LEDs, but the board ties the cathodes together.


How to have compiler know whether Arduino or ESP8266?

There are a number of macros defined to help you with this:

__AVR__ for any board with AVR architecture.
ARDUINO_AVR_PRO for the Arduino Pro or Pro Mini selection in the Tools > Board menu.
ESP8266 for any ESP8266 board.
ARDUINO_ESP8266_NODEMCU for the NodeMCU 0.9 (ESP-12 Module) or NodeMCU 1.0 (ESP-12E Module) selections in the Tools > Board menu.

This allows you to do things like this:

#if defined(__AVR__)
// AVR specific code here
#elif defined(ESP8266)
// ESP8266 specific code here
#endif


Arduino Switching Between Loops IR Remote

delay(0) apparently[*] acts like delay(2^32) or about 10^10 milliseconds. That may not be what you had in mind ... :)

Try reducing the delay to 1 or use delayMicroseconds() to get something shorter. That should at least get you some repeatable results.

(10^10 mSec is ~ 16.5 weeks, for those without a calculator handy).

[*]  I didn't read the code, nor wait for the call to expire. I tried it and saw that the Uno froze. I'm guessing a zero-argument to delay() isn't rejected but just gets decremented as usual, until it hits zero.


ESP-01 Deep Sleep not waking up properly

In the question the OP said:

  I have soldered a wire from GPIO16 to RST.

But, I'm going to post an answer for the people who find this question and need the ESP-01 modification instructions in order to wake an ESP-01 module up from deep-sleep:

The ESP8266 mounted on an ESP-01 board will not wake up from deep-sleep because the ESP8266 wake up signal is not connected to the reset pin of the ESP8266 on an ESP-01 board.  You need to add this connection which can be difficult for most people.  You can see the modification in this picture:

...which comes from this instructables posting.

If this is too difficult, consider using a different ESP8266 board which brings these ESP8266 pins to board edge connectors.


Can't connect to Arduino Uno + Wifi webpage

I've never seen this sort of board before.  Normally Arduinos communicate with ESP8266's using a serial connection and the AT command set.  I think that is what this board is doing, because it says you will need new firmware if you want to program the ESP.  So you need to find the AT command that gets the IP address.
(Sorry I don't know the command, never used the AT commands, never likely to)


I put this code into the IDE, and for n>=2, I got 99, 999, 9999 etc. The catch is that Arduino uses floating point arithmetic to implement the pow() function, and some of your values are being truncated as ints. If you change:

   int multiplier = pow(10,power);

to

   float multiplier = pow(10,power);

The results should be as expected.

(The brief reason why floats are used is related to the fact that it is very easy to calculate the pow() function using logs, and this makes it easy to pow() non-integers too. This also means that it may not be as exact as you would hope).


There are wide differences in power usage in AVR parts. Typically the "P" variants (for "picopower") are more optimized for low power usage, but there are also differences between different revs of the same part (for example the ATMEGA168PB uses slightly more power than the ATMEGA168PA during sleep) presumably becuase of different processes used to make the chips.

If you are looking for the lowest power possible, it will depend on how your application.  Do you spend most time running at full speed? Power down? Do you need a realtime-clock?

Don't forget about the ATXMEGA parts- they have some that have very low power when running a real-time clock from the internal "ultra-low power" oscillator.


Change the sequence of LEDs with button press

There are a few issues with your wiring.

As already stated in comments, you should not connect the battery to
the 5V input of the Arduino. Use the “Vin” input instead.
You should put a current-limiting resistor in series with each of your
LEDs. Any value in the range 330 Ω – 1 kΩ should be fine.
Your Arduino (and your LEDs) will last longer if you stop abusing it!
There is no point in using two digital IO pins to read a button. Just
connect the button between a digital input and GND. Alternatively, you
can wire it like in Holmez's answer, but that requires an extra wire
and a resistor.

And there are two main issues with your code:

You forgot to debounce the button. Mechanical button are bouncy.
The easiest way to debounce them is to use a ready-made library like,
e.g., Bounce2.
You are using delay(), which means you cannot respond to user input
while your Arduino is busy delaying. You should manage your timings
with milis() instead, as explained in the Blink Without Delay
Arduino tutorial.

Here is my take at your problem. This is based on the
finite state machine programming pattern, with a state defined by
two variables. There is a mode variable used to keep track of whether
we are in “digital” or in “analog” mode. And there is a “phase” variable
used to keep track of the phase along the blinking pattern. Phases 0
through 3 correspond to (LED1/LED2) in the states: (HIGH/HIGH),
(LOW/HIGH), (HIGH/HIGH), (HIGH/LOW). Note that, for simplicity, the LEDs
are controlled with analogWrite(), even in “digital” mode.

#include <Bounce2.h>

const uint8_t BUTTON_PIN = 4;
const uint8_t LED1 = 11;
const uint8_t LED2 = 10;

Bounce button;

void setup()
{
    button.attach(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    analogWrite(LED1, 255);
    analogWrite(LED2, 255);
}

/*
 * Vary the LED brightnesses along the following pattern:
 *
 *  phase:   0   1   2   3   0
 *          ___     ___________
 *  LED1:      \___/
 *          ___________     ___
 *  LED2:              \___/
 */
void loop()
{
    static enum { DIGITAL, ANALOG } mode = DIGITAL;
    static uint8_t phase = 0;
    static uint16_t phase_duration = 100;
    static uint8_t low_level = 0;
    static uint16_t last_change = 0;

    // Switch modes on button presses.
    button.update();
    if (button.fell()) {
        switch (mode) {
            case DIGITAL:
                mode = ANALOG;
                low_level = 150;
                phase_duration = 400;
                break;
            case ANALOG:
                mode = DIGITAL;
                low_level = 0;
                phase_duration = 100;
                break;
        }

        // Set initial phase.
        phase = 0;
        last_change = millis();
        analogWrite(LED1, 255);
        analogWrite(LED2, 255);
    }

    // Switch phase after phase_duration elapsed.
    if (millis() - last_change >= phase_duration) {
        last_change += phase_duration;
        phase = (phase + 1) % 4;
        switch (phase) {
            case 0:
                analogWrite(LED2, 255);
                break;
            case 1:
                analogWrite(LED1, low_level);
                break;
            case 2:
                analogWrite(LED1, 255);
                break;
            case 3:
                analogWrite(LED2, low_level);
                break;
        }
    }
}


Replace the non working code with this and it will compile:

long randNumber = RANDOM_REG32 % 10000;
Serial.println(randNumber);
size_t length = 4;
char randomstr[length];
itoa(randNumber, randomstr, 10);
serverClients[i].write(randomstr, length);


Using TMRpcm library, the audio does not play

This is now 5 months later - but I recently had the same problem.

Because the TMRpcm library plays through pulse width modulation, make sure your speakers are hooked up to a PWM capable pin.

That caused me no end of headaches trying to figure out.


clear Arduino as a global variable in Matlab

In the MatLab Help Center they had nice description of how to clear a variable from memory. Check it here: https://www.mathworks.com/help/matlab/ref/clearvars.html

In your case should be: clearvars -global a;


Do you know what int a; does?

For example you have a global variable a and then you have local a. Local one hides global one.

In all cases you're changing local variables. Then you're printing global a,b,c and local d.


Plotting data from Arduino and using the serial monitor in parallel

Is using the Serial Monitor a requirement, or are you just looking for a good way to get and plot the data?  If the latter, you may be interested in the open-source DaqPort sketch. https://www.daqarta.com/dw_rraa.htm  This was created to use the Arduino as a peripheral for data acquisition, as opposed to the more typical case of the Arduino being the central device.  With DaqPort you can program in any language you like on the host computer, and use it to plot data from the Arduino. The Daqarta software package that includes DaqPort has several examples that use Daqarta's macro language to implement a multi-channel chart recorder, high-speed multi-function oscilloscope, timers, signal generator, etc.  You can use these for free, forever, even after Daqarta's 30-day trial ends.  Since Daqarta already has plotting, you may find it simpler to use than rolling your own, perhaps by modifying one of the examples.


#include "Arduino.h"

const byte TONE_PIN = 4;
const int ALARM_BEEP_1 = 4186;
const int ALARM_BEEP_2 = 4699;

const int ALARM_TONE_LENGTH = 200;
const int ALARM_TONE_PAUSE = 800;
const int ALARM_TONE_REPEAT = 6;

boolean alarm = false;

void setup()
{
  alarm = true;
}

void loop()
{
  if (alarm) {
    alarmSound();
  }
}

void alarmSound() {
  static unsigned long next = millis();
  static byte count = 0;
  if (millis() > next) {
    next += ALARM_TONE_LENGTH;
    count++;
    if (count == ALARM_TONE_REPEAT) {
      next += ALARM_TONE_PAUSE;
      count = 0;
    }
    tone(TONE_PIN, (count % 2) ? ALARM_BEEP_1 : ALARM_BEEP_2, ALARM_TONE_LENGTH);
  }
}


print data after being plugged back into USB

You could have it write the final speed to EEPROM after the motor is shut-off, and output this value when the Arduino boots, see:
http://www.arduino.cc/en/Reference/EEPROM


LED Programme where it delays the amount written in the Serial Monitor

Here you have.

No error checking. Anything not digit produce zero as output.

void setup()
{
    Serial.begin(9600);
    Serial.println("Programming is starting");
    pinMode(13,OUTPUT);
}

void loop()
{
    static int value = 0;

    while(Serial.available() > 0) {
        int c = Serial.read();

        if(isDigit(c)) {
            value = value * 10 + (c - '0');
        } else {
            Serial.println(value);
            digitalWrite(13,HIGH);
            delay(value*1000);
            digitalWrite(13,LOW);
            value = 0;
        }
    }

It convert chars to values as they are being readed, one by one. There are no size limit for the input string, other that final value must fit in an int

You write a value in the Serial Monitor and end it with return, space bar or whatever non digit key you want.


Connect GPS module with GPS antenna SIM39EA to Arduino Uno

Your data comes back via the GPS's UART port.
Use the softserial library to create a second serial port on your Arduino (means you can still use the normal serial to read the console).

Then write a program that sucks data from the GPS and squirts it out of the Arduino serial port back to your PC using printf.

I only had a quick flick through and didn't see the default serial speed, so start with 9600 and experiment.

What should come out is probably a line of comma separated values which is in NEMA format.  Google for the specification and you will be able to find out the bits of interest.

Hope that helps.


Motors draw a LOT of current compared to CMOS circuits.
The 3.3V output on most Arduinos can only provide a very small amount of current. The Arduino Uno, for example, says it only provides a max of 50mA from its 3.3V regulator. Your motor driver probably needs >10X more than that.
The overload protection on the Arduino's voltage regulator will probably kick in and cause it to shut off. It might take a while to cool down before 3.3V output comes back. I've heard that the protection on Arduino knockoffs doesn't always work, so you could also fry the voltage regulator if you try to draw too much from it.
Bottom line: Don't do that.
Get a high current supply for your motor driver.


SD card example freezes at line SD.begin() what should I do?

I found another SD with 16GB capacity, and fortunately it worked. So the problem was because of the SD but I don't know what was the exact problem. I post the photo of this SD cards.


This is quite a huge topic to cover in one answer, but I will do my best.

The NodeMCU can be used in three distinctly different ways.  First is the AT mode, where you have installed the AT firmware.  In this mode the NodeMCU is purely a slave device to the Arduino.  Once you have got the Arduino to configure the NodeMCU in the right way to receive data on a socket it will send that data back to the Arduino verbatim through the serial port with special tags added (indicating what the data is, and which socket it arrived on, etc).  It is then up to you to receive that data, interpret it in whatever way you desire (as a HTTP GET request most likely) and craft the correct response (if any) and send it to the NodeMCU to send back (again using the AT commands).

What you send through the socket is entirely up to you.  By the sounds of things you will be making a simple GET request from a web browser to perform an operation, and maybe respond with some data to display in the web page.  That can be easy, or it can be hard - it's as hard as you want to make it.  The simplest way is to rely on an external web server to serve the main content and structure of the page, then use jQuery or Prototype to make an AJAX call to your NodeMCU and receive back any data there may be.  In this case everything will be on your external web server except the single (or few) URL(s) that perform operations and return data.  That includes the jQuery (which is just Javascript, it's loaded from your web server into the browser and executed), any code for buttons, images, HTML, everything (on the web server, that is).

The other two ways the NodeMCU can operate are both very different to that.  They differ mainly in the language that is used with them.  You can use the NodeMCU with its own LUA language to get it to do almost anything you want.  That includes receiving the HTTP GET request and serving the data for it, all without the help of the Arduino.  In fact, doing that, there is little need for the Arduino any more - the NodeMCU has an analog input and multiple digital IO lines - it also has SPI available for interfacing with external ADC chips if you want more than one analog input.  So you can have everything internal to the NodeMCU without needing the Arduino at all.  If you do want to keep the Arduino then you can interface to it through the serial port (as you would in AT mode) but using your own custom protocol in whatever way you see fit.

The third way is to program the NodeMCU as if it were itself an Arduino.  There is an ESP8266 core for the Arduino IDE (and for UECIDE Beta as well) which allows you to program the NodeMCU in the same language and with a similar API, as the Arduino.  This even more removes the need for the Arduino.  You can get the Arduino core from Github here: https://github.com/esp8266/Arduino

Incidentally, the Xtensa core in the ESP8266 is considerably more powerful than your typical Arduino, being 32-bit, having its own DSP, and with much more RAM and Flash memory.  It kind of makes the Arduino redundant.


Connect SD card to Arduino with or without a level shifter

You can't use SD card without level conversion from 5 V to 3.3 V. Clock and CS line are driven by the master, and the master must request over MOSI the data to read.


Is it possible to create an interface between Teensy 3.2 and a DSP?

I would use one of the serial interfaces and connect them together that way.  If Asyinc run as fast as reliable.


I don't know whether it's really the smallest you can find but... The
ATtiny84 has an ADC, more digital pins than you need, and is
available in 3 mm packages (UFBGA and VQFN). There is also an
Arduino-compatible core available for it.


avr-g++ (or avr-gcc) and LiquidCrystal library

I made a Makefile to compile the Blink program a little while back. It wasn't trivial.

#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

I basically did this by observing what the IDE does (as Ignacio Vazquez-Abrams suggested) and replicated it. Now to add libraries you have to add even more steps.


How to configure TinySine 3G module (SIM5320E) for HTTP GET request

CSTT works on GPRS modules like SIM900. I found a way to get SIM5320E working to download websites. Tested with TeraTerm and used <Ctrl M> and <Ctrl J> instead of '<CR> <LF> OR /r/n' characters.

Network setup

AT+CGDCONT=1,"IP","<your APN>","0.0.0.0"
AT+CGSOCKCONT=1,"IP","<your APN>"
AT+CSOCKSETPN=1

Start HTTP service
You can stop and start service if it's not responding properly.

AT+CHTTPSSTART
AT+CHTTPACT="www.iforce2d.net",80

HTTP GET request

GET /test.php HTTP/1.1  <-- don't hit enter, instead hit the below 2 keys
<Ctrl M>
<Ctrl J>
Host: www.iforce2d.net  <-- don't hit enter, instead hit the below 2 keys
<Ctrl M>
<Ctrl J>
Connection: close  <-- don't hit enter, instead hit the below 4 keys. This is useful when connecting to REST APIs to download the the respective result only.
<Ctrl M>
<Ctrl J>
<Ctrl M>
<Ctrl J>

To end the command and to receive results:

<Ctrl Z>

You will receive a lot of data here.

Stop HTTP service

AT+CHTTPSCLSE
AT+CHTTPSSTOP

You will get the contents of the website. Probably it should contain the data you need (I didn't test the content. May be you will need to tweek the result a bit.)


Modbus TCP together with MQTT over same ethernet

Does it work if I simply add a network switch and connect the sensor and an internet router to it, and use both protocols in parallel?

Kind of, yes. You just connect both the MODBUS device and the Arduino to the network provided by the router. The Arduino is just a normal network device - the IP address for it allocated by the router, as is the MODBUS device.
Any device can communicate with any other device in a network.


Receive whole string in serial sending data?

If you send "12" you send 4 characters/bytes: '1', '2' and a new line which is two characters:  ('\r', '\n').

On the receiver side you check for two characters (not the new line), so you should take it into account.

Actually, since you will eventually reach "100" you will receive 5 characters ('1', '0', '0', '\r', \'n').

So it is better to change the receiver side to store the bytes in line UNTIL a new line is received (than you can support values of any length).

Also remove the delay on the receiver side, or at least decrease it a lot, because it doesn't matter to check (too) often. if there is no byte available, it will check again. Now it can happen at time 1001 ms a byte would be received, but at time 1000 ms it is checked and it will not be checked again until time 2000 ms.


Counting to 1000 In Both cores execution time problem in esp32?

Your must use the semaphore to protect the read/write access to i
(Only one task is allowed to modify the variable at a time)
xSemaphoreTake(baton, portMAX_DELAY);
i = i + 1;
xSemaphoreGive(baton);

Additionally you should combine your if clauses. If both tasks increment iit could happen, that it will never has the value 1000for the second task.


INPUT_PULLUP not work for D8 in my NodeMCU v3

Pin D8 is esp8266 pin 15. This pin is one of the boot configuration pins and for use on a dev board, it must be pulled down at boot. So the NodeMcu has a pull down circuit on this pin and internal pullup is weaker then this external pulldown.


Problems in calculating and printing long unsigned integers

This is because the default numeric type is int, which on Arduino is just 16 bits (and signed).
So 48 * 70 * 144 is 0x76200 in hex, which truncated to 16 bits is 0x6200, or 25088. This calculation is done by the preprocessor, not the compiler, so doesn't know (or care) about the destination variable type.
You need to force the values to be calculated as unsigned long by appending UL to them:
bytes = 48UL * 70UL * 144UL;


How can I move these global variables to be

The problem you are having is you are trying to both define and declare a class member variable at the same time. You can't. Instead you need to split it:

protected:
    ros::Publisher chatter;

ROSController::ROSController() : chatter("chatter", &str_msg)
{
    this->_nh.initNode();
//  this->_nh.advertise(chatter);
}

That is, set up the variable as a protected member, then have the constructor call the constructor for you with the right parameters.

(I think that is the right syntax off the top of my head).


How to send Serial data from an Arduino Uno into the Serial of an ESP-01?

Writing Junk From Memory
Serial.write(analogRead(A0) + "\r\n");

This is advancing a pointer to "\r\n" by whatever number is being returned by analogRead.  In other words, you are not sending the measurement but junk from memory after (or sometimes at) "\r\n"'s memory location.
Serial.println(analogRead(A0)); appears to be what you were going for here.  println's line termination for the UNO serial connection is "\r\n".
Logic Levels
When it comes to attaching the serial connections together, there should be some level conversion going on.  Because an UNO's pins are 5V logic levels and the ESP-01 expects 3.3v levels.


Having read the NTPClientLib code, I would say that the first sync is not even attempted for 1 second after NTP.begin() is called anyway.

You could do this

void startNTP() {
    NTP.begin("pool.ntp.org", 2, true);
    delay(2000); // there seems to be a 1 second delay before first sync will be attempted, delay 2 seconds allows request to be made and received
    int counter = 2;
    while ( !NTP.getLastNtpSync() && counter <=2) {
        Serial.print("NTP CHECK: #");
        Serial.println(counter);
        counter +=1;
        delay(1000);
    };
    NTP.setInterval(clockUpdateInt); // in seconds
}

or, you could do this

void loop() {
    // code that doesn't rely on valid time
    //
    // lets say this bit of code requires sync'd time
    if (NTP.getLastNtpSync()) {
        // this will only run once NTP has been sync'd at least once
    }
    // more code that doesn't require sync'd time
}

Now, you may want to check how long time hasn't been sync'd for in your code and do something if it's been too long


How to get body temperature using MLX90614 DCI on Arduino

Skin temp tends to be lower (and less stable) than sublingual (under-the-tongue) temp, which tends to be lower than core temp.
I don't think there's going to be any meaningful way to use ambient temperature to adjust skin surface temperature.
You'd be better off putting the surface temperature probe under your armpit for a few minutes. That should be more stable than other parts of your skin.
If the probe is small enough you might also put it in the finger of a sterile glove and hold it under your tongue.


Arduino accepting only alternate characters

You wrote:

Serial.write(mySerial.read());
rc = mySerial.read();

Here you are calling mySerial.read() twice, and thus reading two
characters from the port's input buffer. You then forward the first
character through Serial, and process the second one. Note that you
should normally not read two characters unless you have tested that
mySerial.available() >= 2.

You probably want to forward and process one character at a time, thus
only call mySerial.read() once within this loop:

rc = mySerial.read();  // read from mySerial
Serial.write(rc);      // forward through Serial
// now process rc


ESP8266 not sending temperature data to text message

Not 100% sure what you are trying to do with the line:

const char TEXT_MESSAGE_BODY []  = "temperature", temperature;

This will not assign the value in temperature to TEXT_MESSAGE_BODY, it will create a variable of type char called temperature.

You will need to get your temperature value into a string (array of char) using sprintf() or similar to convert from the base type (float, double?).

Replace const TEXT_MESSAGE_BODY [] ... etc with :

strcat(data,"temperature");

char temperature_s[20];
sprintf(temperature_s, "%f", rawTemperature);
strcat(data,temperature_s);

Above assumes rawTemperature is a float holding the value read from the sensor, but the same idea applies for other data types..  There is no checking for buffer overflow etc, but you get the idea.


Graph plotting on Processing from Arduino sensor data

I have edited your serialEvent() method a little bit, so it could handle the data from the Arduino, when split by a tab.

void serialEvent (Serial myPort) {
   String inString = myPort.readStringUntil('\n');

   if (inString != null) {
     values=split(inString,"\t");  //Splitting the output of the arduino into a String Array
     for(int i=0;i<values.length;i++){
       values[i]=trim(values[i]); //deleting the whitespaces as before
       float_values[i]=float(values[i]); //cast the string to a float as before
     }
       x = map(float_values[0], 0, 1023, 0, height); //map the value as before
       y = map(float_values[1], 0, 1023, 0, height);//map the value as before
       z = map(float_values[2], 0, 1023, 0, height);//map the value as before
       newVal = true;
     }
}

so your sending on the Arduino has to look like this:

void loop()
{
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
    Serial.print("\n");
    Serial.print(x);
    Serial.print("\t");
    Serial.print(y);
    Serial.print("\t");
    Serial.print(z);
    delay(10);                                     //(make it readable)
}

You still have to make the drawing in the draw() method of processing, but I think that this is not the problem.

For the 3d draw you should have a look on the Processing reference or at this special topic, P3D by Daniel Shiffman.

I have not tested the code, but I think that it should work.

If you have questions, feel free to ask ;D


Problems with I2C connection on ESP8266 - 12F, which pins should I use?

Unlike most Arduinos, the ESP8266 doesn't have a hardware TWI, so I²C is bit-banged in software. This means that you can use any GPIO pins. By default, Wire.begin() initializes pins 4 (SDA) and 5 (SCL), but you can specify other pins using Wire.begin(int sda, int scl).

Documentation

(Note: the datasheet specifies GPIO2 as SDA and GPIO14 as SCL, but that doesn't matter, AFAIK, it's just a convention.)


Going from arduino & sketch to production

"Intel Hex" is pretty much an industry standard and I'm quite certain the .hex files produced by the GNU AVR tools is Intel Hex format. Your vendor is almost certainly prepared to load your sketch from the .hex file.


When you call dataFile.read(), the file pointer is advanced, so you always read different bytes in each read call. Imagine the file like a book with many lines: Each time you read, you advance the current line, so with multiple calls, you never get the same data. The solution is to currently store the last read byte:

while (dataFile.available()) {
  char readByte = dataFile.read();
  Serial.write(readByte);
  lcd.write(readByte);
  lcd.print(readByte);
}

You have two calls for displaying data in the LCD, but be careful that the second call (print) might interpret your data as a number, so just remove the lcd.print(readByte) call altogether to be sure it's printing the raw character.


The Arduino Uno is based on an ATmega382P microcontroller. This chip has
two 8-bit timers, driving two PWM channels each, and one 16-bit timer,
driving the last two channels.

You cannot increase the resolution of the 8-bit timers. You can,
however, put the 16-bit timer in 16-bit mode, instead of the 8-bit mode
used by the Arduino core library. This will give you two 16-bit PWM
channels, with a reduced frequency of 244 Hz (maximum). You will
probably have to configure the timer yourself, and will not benefit from
the easy to use analogWrite() function. For details, see the section
on Timer 1 in in the ATmega328P
datasheet.

Update: Here is an implementation of a 16-bit analogWrite(). It
only works on pins 9 and 10, as these are the only pins connected to the
16-bit timer.

/* Configure digital pins 9 and 10 as 16-bit PWM outputs. */
void setupPWM16() {
    DDRB |= _BV(PB1) | _BV(PB2);        /* set pins as outputs */
    TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                   /* mode 14: fast PWM, TOP=ICR1 */
    TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS10);                    /* no prescaling */
    ICR1 = 0xffff;                      /* TOP counter value */
}

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
    switch (pin) {
        case  9: OCR1A = val; break;
        case 10: OCR1B = val; break;
    }
}

You may notice that the top of the counter sequence is configured
explicitly. You can change this to a smaller value to make the PWM
faster, at the cost of decreased resolution.

And here is an example sketch illustrating its use:

void setup() {
    setupPWM16();
}

/* Test: send very slow sawtooth waves. */
void loop() {
    static uint16_t i;
    analogWrite16(9, i);
    analogWrite16(10, 0xffff - i);
    i++;
    delay(1);
}


Is there a Arduino UI library that provides dialog box and button functionality at a minimum?

Take a look at this library. Will this do all that you want?
https://github.com/AndreiDegtiarev/AWind
I have not tried it yet but I would like to.
Edit:
I just remembered this https://github.com/ImpulseAdventure/GUIslice
https://github.com/ImpulseAdventure/GUIslice/wiki
A lightweight GUI framework for embedded displays
The library supports creation of multiple pages of buttons, text, images, checkboxes, sliders and other graphics primitives. New UI / widget types can be created easily.
It works with many existing TFT libraries. There also is a drag & drop builder application.  https://github.com/ImpulseAdventure/GUIslice-Builder


Powering arduino sensors - what resistor should I use?

You should have NO resistor.

The datasheet states the current values the device will pull from the supply. Supplies DO NOT PUSH CURRENT.

Remove all resistors.

As long as the voltage is correct and the supply can provide at least as much current as all devices combined want to use then it will work.


According to the SIM800 AT Command Set you can terminate the sending of an SMS part way through by sending ESC (character 27).

So you can begin your sketch by first sending a number of ESC to ensure that any pre-existing text input for an earlier SMS is abandoned.

serialSIM800.write(27);
serialSIM800.write(27);
serialSIM800.write(27);

Only one should be needed, but it is best to repeat it a couple of times in case the first one isn't taken. You should then do a CR/LF to make sure it's ready for the next command.

serialSIM800.print("\r\n");

However, your method of controlling the modem is crude at best and not particularly reliable. The modem sends back responses from all the commands you send it. You should be reading in those responses and checking that the commands you sent actually worked. That way you can know if a command hasn't been accepted because it is in SMS reading mode (no response within 1 second, say), and you can force an escape.


Using millis() to time the start / stop of a DC motor

You can't reset the millis() function, but you can count the amount of milliseconds and stop when necessary: beware though, the positioning might not be as precise as you wish and you have to consider the error will accumulate on the long run.

Nonetheless here is the code:

uint16_t duration;
bool direction = true;
void loop() {
  if (duration != 0 and !buttonPressed()) {
    // running back and forth if setup and no "finish" button detect
    uint16_t start = millis(); // reset the timer
    startMotor(direction);
    while (millis() - start < duration && !buttonPressed()) {
      ; // keep going
    }
    direction = !direction; // reverse direction
  } else if (duration == 0) {
    // your motor positioning setup
    while (!buttonPressed()) {
      ; // wait for button to start positioning
    }
    uint16_t start = millis(); // ask for time
    startMotor(true); // run the motor cw
    while (!buttonPressed()) {
      ; wait for button to end positioning
    }
    duration = millis() - start; // store duration
    direction = false; // reverse motor direction
    // next time loop() is executed the motor will go back to home
  }
}
bool buttonPressed() {} // define this to determine if the button has been pressed, safer if you use an interrupt
void startMotor(bool cw) {} // define this to run your motor clockwise or counterclockwise


Understanding the relationship of Pulse and Stepper RPM

The real answer to this question requires understanding exactly what hardware you have. The formula, assuming one step per pulse, is that the delay should be:

wait = (MicroSecondsPerMinute)(1/RPM)(1/PulsesPerRevolution) - overhead

where overhead is the extra time it takes to run digitalWrite twice and loop. It is small, but if it were zero your code would not work because the amount of time your signal is LOW would be zero as well.

Your numbers suggest Pulses Per Revolution is around 1891. This will be the product of how many steps per revolution the motor is wired for and how many bits of microstepping the driver is doing. A 225 step motor with 3 bit microstepping (8 fractional steps per "true" step) would have PPR of 1800 for example. Your number does not precisely match any common setups, but is exactly in the range expected, with 1600 and 2000 being normal for small steppers.

Because of the "overhead" term, RPM as a function of wait should not be linear. Your constant value should be a function of RPM; in fact, when RPM gets much larger than the number of Microseconds per minute it should converge to being equal to RPM. In this case your RPM is so low that approximating it to 17 is probably valid and all error too small to notice. It could be causing some of the oddness of your PPR value though.


I have shorted my bords a few time and they always came back to "life" after a minute. Maybe you should be more concern about the voltage you supply to the board. Even if it can take up to 12 volt I never use more then 9 volt on the board. And if you run motors on them its always good to supply them with an external power source and use something like a H bridge to power your devices. I made mistakes and my board are still in mint conditions.


what actually happens with this code is when I put something near the sensor <= 5 , the led is on without i removed the thing , but I want the led on when I put then remove the thing

Here is my theory on what happens here. You can confirm it by using one of the solutions, that I will explain below.
Currently your code is measuring the distance as fast as it can. The measurement is what takes the longest time in one iteration of the loop() function. Thus you get many many measurements per second. But such distance measurements are always noisy, meaning that the values change randomly in a specific range. When you put the object in front of the sensor, you expect the values to just go down, but actually they are sometimes rising again for 1 or 2 values because of the noise. So the measured values might look something like this (only imagined for making the point; not real values):
5.4 --> 5.2 --> 4.99 --> 5.001 --> 4.89 --> 4.90 --> 4.5

Overall the values go down, but you are comparing always the current value with the fixed threshold of 5cm. When the noise just raises the value again, while you pass 5cm, you will get a false "put and removed again" outcome. At the probability  of the noise doing that is really high, since you measure that often and ultrasonic sensors are not accurate down to millimeters. You could even have the distance pass 5cm multiple times due to the noise.
There are some possibilities to reduce noise or to handle it.

Hysteresis: The first, that I would implement here is hysteresis. That means, that you set the "put" distance different than the "remove" distance. For example you could use 5cm as the distance to register, that the object is put in front of the sensor, but then you wait for the distance to go above 7cm to actually treat the object as "removed". You need to choose the difference between the distances larger than the noise (you can find that out via experimenting). This principle is also used directly with noisy digital signals on the Arduinos input pins. An Arduino Uno will treat voltages above about 2.6V as digital 1 (HIGH signal), and a value below 2.1V as digital 0 (LOW signal) (taken from the datasheet of the Atmega328P, which is the microcontroller on an Arduino Uno, while assuming the controller running on 5V like in an Arduino Uno). In electrical terms this is called a Schmitt-Trigger.
For implementing this, you can just change the threshold values in your if statements.

You can reduce the noise by always measuring multiple times in a row and then calculating the mean value from it. Since a part of the noise is random, you can smoothe out this part a bit through taking the mean. That also reduces your time resolution, but in such a simple use case that mostly doesn't matter that much.

If the reaction time doesn't matter that much, you could reduce the frequency of measurements, so that subsequent distance measurements are already to far away from each other for the noise to create false triggers. This is worse than the other solutions, since it also depends on how fast you put the object in front of the sensor, but it is really easy to implement (just a simple delay() call, or better using millis() like in the BlinkWithoutDelay example for non-blocking code)

I would first implement the hysteresis. Then, if the difference in distances, that you need for it to work good, is too big for you, you can take the mean of multiple value to reduce the noise.

And just for protocol, as it already was said in the comments: Your first if statement has an extra closing bracket } which should not be there.


Unable to upload the data on thingspeak using uno and esp8266

You have a malformed HTTP request. You only have half of the first line.

A valid HTTP request would look more like this:

GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60 HTTP/1.1
Host: api.thingspeak.com
Content-length: 0
Connection: close
<blank line>

Just sending "GET : ain't gonna work. For a start, the server won't know what protocol you're speaking (HTTP/1.1), nor what website it's supposed to direct the request to (Host: api.thingspeak.com). Also, the final extra blank line is required to finish the request.


The TCD1304's minimum OS-datarate is 200 kHz. Quite a lot more than what the arduino is capable of. You should look to faster processors or to a different sensor. The TSL1401 seems to be popular with the arduino-community.

If you /need/ the TCD1304, then an arduino due will probably be able to do it, but I'm guessing you'll have to drop the arduino-IDE to achieve the full speed of the ADC.

Here's how I've done it with a STM32F4 processor:
https://tcd1304.wordpress.com/


At what level does low dynamic memory effect performance?

The typical build memory statistics is:

Global variables use XXX bytes (X%) of dynamic memory,
leaving YYY bytes for local variables.
Maximum is ZZZ bytes.

What is all this about? First, the maximum number of bytes SRAM depends on the MCU. Arduino Uno is ATmega328 based and has 2K byte SRAM. Arduino Mega2560 has 8K byte. "Dynamic memory" in the print out is SRAM. It is not the heap (malloc/free). To avoid confusion I will use "data memory" below.

The compiler allocates memory for all global variable (objects, struct, etc). It also allocates memory for literal strings (character vectors). These are copied from program memory to data memory at startup. All static variables in functions are also allocated. The sum of all these allocations are the "Global variables".

To execute the sketch data memory is used for the stack. It contains the function parameters, local variables in called functions (that are not allocated to registers), saved registers such as return address to the caller, etc. The size of the frame is known by the compiler and may be found in the assembly listing of a sketch. The maximum stack size required is tricky to calculate as it is the call chain with the largest frame size sum. This is not necessarily the deepest call chain. Also the compiler does to a fair amount of inlining.

The heap (malloc/free) is used by classes such as String. The heap starts directly after the global variables in data memory and grows towards the stack. The heap is blocks of memory allocated and deallocated during the execution of the sketch. This behavior may give heap fragmentation.

Interrupt Service Routines (ISR) need to be able to execute "on top of" any function call. The ISRs are typically called on hardware events such as USART data received. The compiler has to generate code that stores the machine state on stack to execute the ISR. Depending on how many registers the ISR needs more or less of the machine state (registers) need to be stored. The worst case is all 32 registers.

The warning at 30% of SRAM is at approx. 600 bytes left (Arduino Uno, 2K byte). That has to cover the stack and possible heap usage together with ISRs. With a stack heap limit of 32-128 byte, ISR frame of 32-64 byte, that actually leaves worst case approx. 400 bytes for local variables in functions and possible usage of the heap (such as String).

Cheers!


Powering Moisture sensor via arduino pin

The entire circuit board, including the LM393, power light and it's resistor, uses 2.2 mA at 3.3 VDC (4.12 mA at 5 VDC). Once the comparator is "triggered", the "D0-LED" and it's associated resistor come in to play which bumps the current up to 3.6 mA at 3.3 VDC (7.82 mA at 5 VDC).

I think it would be OK to use digitalWrite(pin_number, HIGH) to power the circuit board, then use digitalWrite(pin_number, LOW) to turn the power off.


How can I have different routines fire off at different intervals

As said in the comments: you should read up on State Machines and have a close look at the Blink Without Delay example.
To get you started with an example closer to what you want to achieve, have a look at the code below; it will count seconds without blocking the loop.
unsigned long int secondsTimerMillis;
int seconds, minutes, hours = 0;
int secondsInterval = 1000; //ms

void setup() {
  Serial.begin(9600);
  // More setup() stuff goes here
  secondsTimerMillis = 0;
}

void loop() {
  if ((millis() - secondsTimerMillis) >= secondsInterval) {
    seconds++;
    secondsTimerMillis = millis();
    Serial.println(seconds);
    // More stuff you want to do every second goes here
  }
  // More loop() stuff goes here
}

This is just the basic mechanism, and it won't be very accurate without some way of adjusting the clock every now and again.
You will also have to add code for checking seconds == 60 and increase minutes / reset seconds when needed; the same goes for hours.
Having/handling other events at other intervals is just more of the same.
Note that using a Real Time Clock as the basis for your timing would make your life programming much easier, and your clock more accurate, but I am assuming you want to do this "by hand".


How to increase SD card write speed in arduino

OK. So, I tried the SDFat lib. This library is definitely better than the default SD library that comes with adruino.
But that is not how I solved my problem of low data-rate.

I followed the instruction of the author of SDFat library from this post.

According to fat16lib, to increase the data rate we need to use flush() wisely. We would want to write() the data in each cycle, but we only need to flush() once every 100 cycles or so depending on how much data is being written in each cycle. Also, be sure to keep the flag in SD.open() as 'O_WRITE | O_CREAT' instead of 'FILE_WRITE'.

This sure increased the speed by a great factor. But I needed more!

Storing the data in binary (check out this blog) improved the performance even more.

My current speed is approximately 100-120 KBps (that's kilo bytes) with a class 4 SD card!

Finally, I want to thank you guys for your help.


Strange values on Serial Monitor even with matched baud rate

You can't concatenate string and value inside Serial.println().

Print them using two different Serial.println().

int pin12;
int A12 = A12;

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

void loop() {
  // put your main code here, to run repeatedly:
  pin12 = analogRead(A11);

  Serial.print("pin 12 is ");
  Serial.println(pin12);

  delay(5000);
}


WS2812 - First are white and then they turn red/yellow/orange near the end

See Powering NeoPixels.

  Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue).

  ...

  To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps. Or use 60 (instead of 20) if you want to guarantee an absolute margin of safety for all situations. For example:

So you need at least 3 amps or even 9 amps for absolute safety.

  The LEDs are running off 3.3v directly from the ESP8266.

I doubt it is designed for that. The internal traces won't be designed to handle maybe 5 amps.

To avoid colour degradation through the strip you could use multiple power supplies (to avoid the voltage dropping due to the resistance over the strip). You would connect the grounds (and connect the data wires of course) but break the +5V line in the middle and insert another power supply.

However one (fairly powerful) supply directly connected to the NeoPixels might do the trick. That is, not through the ESP8266.

Also see NeoPixels Revealed: How to (not need to) generate precisely timed signals.

On that page:

  Q: In the video, when the entire strip is lit full white, it looks like the far end has a orange tint to it. Is this an artifact of the camera or something?

  A: Wow, you are very perceptive! Yes, the string did start to get orange at the end at full power. I actually didn’t just run out of apartment when making this long string – I also ran out of power supplies. I had 3 supplies, each 10amps. This is almost enough, but not when every single LED is full brightness white. When that happens, the voltage at the very end of the strip starts to get too low and the LEDs start looking pallid. Why orange? Because blue LEDs need the highest voltage drop to light so when the voltage sags they are the first to go followed by the greens – leaving yellows to oranges and ultimately red.

(He had 1000 pixels). So this guy used 3 separate 10 amp power supplies!


NodeMCU V2 ESP8266 - Use 5VIN as power for heater of a MQ-9 Sensor

The VIN pin is NOT directly connected to the USB's 5V supply as it is an VIN PIN for powering the MCU from an external source other than the USB - this means the pin cannot be used as a 5V supply output.

Never ever connect VIN to a power source AND connect the USB plug. That can destroy the USB port in your computer. There is zero back-powering protection on the MCU board.

According to the datasheet the sensor (heater) needs upto 350mW which IMHO makes powering via an extra power board (which can also power the MCU) a necessity.


Continue playing sound during interrupt routine

The sound is itself generated by an interrupt routine. Since only one interrupt routine can happen at a time, if your own interrupt routine takes too long, then you will get interruption in the sound.

There is nothing you can do about that other than making your interrupt routine short enough that it doesn't cause any interruption in the sound.


This is an image from a typical power jack:

The specific ones you bought may differ.  The vendor should be able to supply you with a manufacturer and P/N or an actual data sheet.
Image copied from: https://www.we-online.de/katalog/datasheet/6941xx301002.pdf


The SAM3X series MCUs, not being AVR MCUs, do not have AVR ISP connections. Like most ARM MCUs, they use JTAG for programming and debugging. On the Due the JTAG lines on the MCU are connected to the 10-pin microheader near the reset button.


I²C between ATTiny85 (8MHz) and Arduino Uno

I was able to compile your code "ATTiny85-Slave Code" without problems.

You can try to extract the contents of the ZIP archive (i.e. the library) directly to the directory where your sketch is stored. #include "TinyWireS.h" should then pick up that version.

You should also switch on verbose output for the compilation to have a look at the directory in which the code is compiled. Here you would find (at least in my older Arduino IDE version) copies of the included files. (/tmp/build... on Linux systems.) You can then make sure the proper version of the files is used.

You can also search your drives for other copies of TinyWireS.h.


The main difference between what you want and what that code does is that you want to fade both colours at once, but that code is aimed at only fading one colour at a time.

You want to fade R up whilst fading B down, and then fade R down whilst fading B up. The simplest way is with just two loops:

// Fade red up and blue down
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, i);
  analogWrite(BLUEPIN, 255 - i);
  delay(FADESPEED);
}

// Fade red down and blue up
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, 255 - i);
  analogWrite(BLUEPIN, i);
  delay(FADESPEED);
}

One fade value (i) per loop, and a little bit of maths to turn 0-255 into 255-0 for the value you are fading down.

For Red->Yellow->Red you just need to keep red on and fade green on and off.  You already have code to fade green on and off in your original program:

  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

Couple that with setting the red and blue to on and off respectively, and you have:

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);

  analogWrite(REDPIN, 255);
  analogWrite(BLUEPIN, 0);
}

void loop() {
  int g;

  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from yellow to red
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}


Why Smart Plugs don't require setting port forwarding on router and how to accomplish this with NodeMCU (ESP8266)

Port forwarding is required to allow a device outside your router to access a device inside a router that performs NAT (Network Address Translation).

When a NodeMCU is acting as a simple server to respond to requests, it is inside your network, and so the port-forwarding is required so that your phone or computer on the Outside can access it.

However, for the cloud-based "smart" devices, it is different. The smart device opens a connection from itself to a server (the cloud) outside your network. In this case, the router understands that a new two-way connection is created between the cloud server and your smart device.

The only communication to your smart device is from the cloud server to the smart device. If you have an app on your mobile device or computer, that app or website only accesses the cloud server, when then passes the instruction on to your smart device. Reverse direction for status info from the smart device to your app, etc.

These smart devices rely on the infrastructure of their creators to continue to work. There are no LAN-to-LAN connections from the client to the device. Everything goes through the Internet to the remote cloud server, and back.

Many home routers support a protocol called uPNP, that allows a device inside the network to request port forwarding to itself. Some routers require this to be explicitly enabled, because it's a security risk to allow any device to be able to open holes in your firewall/router.

To have your NodeMCU device do this, look for libraries for ESP8266 that implement uPNP. I did a quick search and found https://github.com/ofekp/TinyUPnP though I cannot vouch for it's effectiveness or safety.


Is it possible to read VGA with an arduino

Trying to capture analog video such as VGA and transmit it over Ethernet is going to be technically challenging, and of questionable wisdom (at least without compression).  A conventional ATmega-based Arduino is just about the worst contemporary platform you could choose for this job - even aside from the VGA issue, it is a poor choice for Ethernet requiring an expensive add-on.  But just for the sake of "can it be done" ....

If you can threshold your signal to a digital level (assuming a high contrast image) this probably can be done, crudely, but will be quite tricky.  The display is likely to be very blurred horizontally - really, it would only be worth doing for bragging points.

The first thing to realize is that the standard VGA 640x480x60 mode has a pixel clock of 25.175 MHz, and most others will be even faster.

One approach would be to try to write a program which samples a digital pin (directly, no Arduino abstractions) to memory as fast as possible.  This would not capture every pixel, but rather something like every 10th.  You would then have to send these over the network before you fill up your available memory.

The tricky part is that you then have to go back, and scan another frame of video with a slight offset, so that by getting every 10th pixel again, you effectively get the pixel adjacent to the first.   And then you do it again, and again, until you have collectively transmitted the entire screen, which hopefully hasn't changed much as you did it.

It's going to be tricky as you will have to work your delays from the sync signals, and you really want a delay which is a fraction of ATmega's clock - which won't happen without external circuitry (programmable delay buffer, etc)

The whole project would be a lot more feasible on an 80+ MHz ARM Cortex part, as you could then use a counter/timer to generate pixel-or-less-adjustable starting delays relative to the sync pulse.  An FPGA would likely be an even better choice.


Freeduino avrdude stk500_getsync() not in sync

There could be many reasons for the problem you have got.

1) Try to program your Board with any other device you have got. If you are trying to program it with PC try to do it using Laptop.

2) Plug your board to any other port. Then Right Click My Computer and Select Manage--> Device Manager and find the port where your Freeduino is connected. Then Select that port in  your Arduino IDE.

Solution 1 worked for me!


Without more detail about the system, I won't understand what printf() does; in non-embedded systems,  printf() writes to stdout by default, but Arduino systems typically don't use such a device.

That aside, %d is the proper format code for printing an integer value, and %f is proper for a float or double.  If you attempt to print an integer value like temperature_sensor_output under a %f format code, either the compiler will complain or the integer pattern of bits (plus perhaps two additional random bytes) will be interpreted as if it is a float or double pattern of bits.  No type cast occurs within printf().  If you want to use a %f format code, pair it up with a float-type variable.

If, as you say, ds18b20_temperature() returns a float, then the type cast  (float)ds18b20_temperature(&PORTD) will have no effect.  Generally, casts convert data from one form to another, or in some cases declare that data has a given form.  Going from float to float doesn't change anything.

In a C statement like a=b, if b has a type that's different from that of a, the b value will be cast to the type of a.  Thus, the float value on the right hand side of

int temperature_sensor_output =  (float)ds18b20_temperature(&PORTD);

will be converted to an integer value and stored into the integer variable temperature_sensor_output.


One complication you should be aware of is that in its default configuration, an Arduino Uno (and I assume that is what you’re talking about) will automatically reset whenever a serial connection is opened to it. This is easily bypassed with a capacitor between RESET and GND, but not taking it into account might make for hours of debugging fun.

The other complication is that just after a power up or RESET, an Arduino will delay for a second or two to listen for a programmer connection on the serial port, but that’s something you’ll have to take into account anyway.


nRF Connect is for Bluetooth LE devices, the nRF24L01+ is really not a Bluetooth Low Energy transceiver.
The best the nRF24L01+ can do is make a few Bluetooth LE advertisements but that's very finicky. Here's a long description how: https://dmitry.gr/index.php?r=05.Projects&proj=15&proj=11.%20Bluetooth%20LE%20fakery


Control 2 ESC with a potentiometer with arduino

If you want one potentiometer to handle BOTH ESCs' speed, you could use this code:

//Using servo library to control ESC
#include <Servo.h>

//Starting the servos
Servo esc1;
Servo esc2;

void setup() {
    esc1.attach(9); // Use a PWM pin to the Servo, in this case 9
    esc1.writeMicroseconds(1000); //initialize the signal to 1000
    esc2.attach(10); // Pick another PWM to the other, in this case 10
    esc2.writeMicroseconds(1000); //initialize the signal to 1000

    Serial.begin(9600);
}

void loop() {
    int val; //Creating a variable val
    val= analogRead(A0); //Read input from analog pin a0 and store in val
    val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(analogRead's goes from 0-1023 and analogWrite's goes from 0-255, check your servo's specs)
    esc1.writeMicroseconds(val); // write to the first ESC
    esc2.writeMicroseconds(val); // write to the second ESC
    delay(100); // We usually set a small delay to avoid excessive readings or over-heating, but thats optional...
}

If you need to use two potentiometers, one for each ESC, then you would have to start another variable to read the 2nd pot value and use it to write on the 2nd ESC, simple as that! :)


First, I think 40 mA to output from a GPIO is not a wise idea, because those are Arduino Pin Current Limitations.

What you can do is:

The VCC pin can handle 200 mA. So you can use this pin to power your KY-005 and use a transistor to switch it via a GPIO (much less than 40 mA is needed for that).
Or (high likely not needed): use an external power source and use a transistor in the same way.

For knowing all details about using a transistor this way, google for "transistor as switch".


How to return the value in Arduino function (that can be read by the connected device)?

You are using the USB interface, right? So you just use Serial to send data back. For example, this would send the distance every second:

unsigned long lastSent;
void loop() {
  distance = Dist.getDistanceCentimeter();
  if (millis () - lastSent >= 1000)  // every second
  {
    lastSent = millis ();
    Serial.println (distance);
  }

  if (distance <= 5 & distance > 1)
  {
    if (Serial.available()) {
      command = Serial.read();
      switch (command) {
        case 'a':
          forward();
          servoX.write(90);
          command = 0;
          break;
      }  // end of switch
    }
  }
}


My LED toggeling doesn't work the way I want

There are a few problems with your approach.

You seem to have the button backwards.  You should wire a button so that it is between the pin and ground.  This way it should read LOW when pressed, not HIGH.  It should also have pinMode(pin, INPUT_PULLUP) instead of INPUT.  With the button wired the way you have it to read HIGH then you will need an extra resistor for each button.  With it wired the right way where it reads LOW then it needs nothing extra.
If the first if statement is true and the button is pressed and it turns on the led, what do you think are the chances that you are fast enough to get your finger off the button in the 62.5 nanoseconds it takes to get to that next if statement?   It's not going to happen, so the button is still pressed there and now the led is on so this line turns it right back off.  Only in the rare case where you happen to get your finger off the button at just the right instant will the led stay lit.  To solve this, look at the "State Change Example" that comes with the IDE.  It shows how to keep track of the last state of the button in a variable so you can act only once when the button actually changes state.
Once you get that worked out you will notice that it seems like for every time you press your button it registers tens of presses.  This is switch bounce.  That's a term you should google.  The contacts are making and breaking contact really fast in the in-between pushed and not-pushed state.  But you need to get the first two issues solved before you worry about bounce.


This block of code can give you some idea...

% create an arduino object

a = arduino('com3', 'uno');

% start the loop to blink led for 10 seconds

for i = 1:10

    writeDigitalPin(a, 'D11', 1);

    pause(0.5);

    writeDigitalPin(a, 'D11', 0);

    pause(0.5);

end

% end communication with arduino

clear a

For more details on this code and working of it you can visit....
Here


Is I2C a good option for transmitting data over 200 meters by cable?

With I2C, you're unlikely to get reliable communication on a cable longer than 1m. For your reference, here's a table showing what you can achieve with regular RS-232:

Length (m)  Maximum Baud Rate
1600        600
800         1200
400         2400
200         4800
100         9600
50          19,200
25          38,400
16          57,600
8           115,200

So, if you don't really need 100 kHz data rate, you could use regular RS-232 (which is cheap). If RS-232 is not fast enough for you, consider more complex solutions. RS-485 is one possiblility. Another one is CAN, which supports topologies up to 500m at 100kHz. The key difference of CAN is that it's a bus, meaning that all devices will share the same pair of wires.


Yes, yes and yes.

  Will Nodemcu support 4AAA batteries which is 6v approx

Yes, it will. However there is no back-powering protection on the USB, so having that connected whilst the board is connected to your computer could potentially damage your computer's USB port. That's why VIN's label was changed to 5V on the newer boards.

  or should i go with 3AAA batteries which is 4.5V approx.

Yes, you should. Not only does that mean your USB port won't die, but you're not wasting as much power. The NodeMCU employs a linear "LDO" regulator to get 3.3V from the incoming power source. That means that the voltage difference between incoming power and 3.3V is thrown away as heat. The higher the incoming voltage the more heat is generated to discard that voltage.  Using a lower voltage, therefore, means that you don't waste as much. That fourth battery is doing absolutely nothing towards powering your project and is just being used to generate more heat.  One thing to note though is that 5V coming in from USB could try and charge your 3xAAA batteries. If they're not rechargeable then they could cause problems (overheat, leak, cause a fire, etc).  Adding a schottky diode in series with them would protect them from that.

  is it ok to use AA instead of AAA ?

Yes. Your project will last longer before you need to replace the batteries, since AA batteries have a higher mAh capacity than AAA.


How to add calibration to a humidity contoller using UNO and DHT22 sensor?

To get better calibration, you need more calibration points. In the example below, I use 8 measurement points.

Given 8 humidity calibration bags for 20, 30, 40, 50, 60, 70, 75 and 80%.

int calvalues[] = {20, 30, 40, 50, 60, 70, 75, 80};

You would take several samples with the DHT sensor and build a table using the averages:

int dhtvalues[] = {15, 28, 39, 51, 63, 75, 84, 89};

As you can see, the DHT is below the real values in the lower range and above the real values in the upper range. But it could also be the opposite way.

You can then write this function:

#define COMPENSATION_POINTS 8

int compensate(int sensor_value)
{
  for(int index=1; index<COMPENSATION_POINTS; index++)
  {
    if (dhtvalues[index]>sensor_value)
    {
      int dhtLow = dhtvalues[index-1];
      int dhtHigh = dhtvalues[index];
      int calLow = calvalues[index-1];
      int calHigh = calvalues[index];

      return map(sensor_value, dhtLow, dhtHigh, calLow, calHigh);
    }
  }
}

which does linear interpolation for all the values that fall somewhere in between.

Here's some test code, which goes through the values in the expected range.

void setup() {
  Serial.begin(9600);
  for(int hum=15; hum<=89; hum++)
  {
    Serial.print("DHT value: ");
    Serial.println(hum);
    Serial.print("Compensated to: ");
    Serial.println(compensate(hum));
  }
}

void loop() {
  delay(1000);
}

Output:

DHT value: 15
Compensated to: 20
DHT value: 16
Compensated to: 20
DHT value: 17
Compensated to: 21
DHT value: 18
Compensated to: 22
...
DHT value: 87
Compensated to: 78
DHT value: 88
Compensated to: 79
DHT value: 89
Compensated to: 79

Applied to your case:

[...]
  int chk = DHT.read22(DHT22_PIN);
  lastcheck = millis();

  lcd.setCursor(0, 0);
  lcd.print("Humidity: ");
  lcd.setCursor(13, 0);
  int compensated = compensate(DHT.humidity);   // <- new line
  lcd.print(compensated);                       // <- changed line
[...]


The authors of the library are not fans of the setBrightness() method and advise handling it yourself.

The following code should do what you want.

#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 60 // This should be the total number of LEDs in your strip

#define DATAPIN    4
#define CLOCKPIN   5
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BRG);

void setup()
{
  strip.begin();
  strip.show();
}

void loop()
{

  // loop through each pixel in the control array setting it to the colour mix you want.
  for (int i=0; i <= NUMPIXELS; i=i+1) {
    strip.setPixelColor(i, 25, 25, 25); // Even 25 on my strip gives reasonably bright flash
  }

  strip.show(); // Then push the control array to the strip
  delay(1000); // and leave it set for a while

// Then do it again for the 2nd brightness in your scheme

  // loop through each pixel in the control array setting it to off.
  for (int i=0; i <= NUMPIXELS; i=i+1) {
    strip.setPixelColor(i, 0, 0, 0);
  }

  strip.show(); // Then push the control array to the strip
  delay(1000); // and leave it set for a while

}


The part of the datasheet you need to understand is this bit:

That's the input logic levels, and as you can see they vary depending on the supply voltage.

At 10V you need to supply at least 7V to get a HIGH registered. At 15V you need 11V or more. So at 12V you can expect that level to be around 9V and upwards.

The Arduino outputs 5V. That's nowhere near 9V, so the chip completely ignores it.

These chips are not designed to be level translators. They are designed to work with other chips that also run at the same voltage. To use it at a higher voltage that the chip that's driving it you will need to employ some form of 5V to 12V level translation.


Unable to load programs onto Arduino Pro Mini Using FTDI?

Same problem faced. Try out many times with proper connection but no success. After that, I found one unique and simple solution. I use Arduino Uno instead of FTDI. Follow below step, your problem will definitely solve.

First, remove Arduino Uno's IC means ATMEGA 328P-PU.
Now, do connection as shown in below figure.

Connections are like:

Arduino Uno(Without Chip)     Arduino Mini Pro

          RX                         RX
          TX                         TX
          +5V                        Vcc
          GND                        GND
         RESET                  RST(RESET PIN)

Now, plug your Arduino Uno to your computer and open your Arduino IDE.
Now, an open sketch which one you want to upload. Now, go to Tools and select board in which you want to upload code. Below, show in the figure.

Now, upload your program. It will definitely work.

I hope it will help you.


I2C_graphical_LCD_display, fatal error: avr/pgmspace.h: No such file or directory

The authors of the ESP32 core didn't bother to create a proper set of compatability shims for the PROGMEM system - chiefly because it's not needed for ESP32 operation.

We did for chipKIT, though, and you can grab a copy of ours here and place it in with the core files for the ESP32 in your Arduino installation (you only need the pgmspace.h file, and place it in an avr folder inside the core source folder).

It's completely architecture agnostic and basically defines some pretty much empty macros, and maps _P variants of various functions to the non _P alternatives.


As @Majenko commented, the A0 input has a fixed voltage divider (see NodeMCU Schematics) that connects the A0 input to a 220kOhm resistor, then to the ADC pin of the ESP8266, then to ground via a 100kOhm resistor.

This effectively fixes the resistor values that can be used to scale the input of the NodeMCU. For a 0-5.0V input range (with sufficiently low impedance) you need to scale the ADC pin from 0-1.0V by adding a ~180kOhm resistor between the 5V output and the A0 input of the NodeMCU, creating a 400kOhm-> ADC -> 100kOhm divider like this:

simulate this circuit – Schematic created using CircuitLab


problem using #define to substitute functions

There is no way to suppress define substitution. You could use #undef and then #define again in required section.

Name the define MILLIS and use this name in code, except where you want the original millis() function.


Arduino Nano burns with ESP-01 in parallel

Use the 5v regulator to power both the ESP and the Nano. Those onboard regulators have minimal heat dissipation and if they burn out you lose the whole Nano. Check how hot your external regulator gets and mount it on a heat sink if it gets too hot to touch.
NB Connect the regulator output to the Nano 5v pin directly


It sounds like a dry joint; the fact that the LED matrix seems to work 'better' when you're fiddling with the microphone board makes me think that the problem lies entirely with that little board.

Try adding more solder; the more the merrier.


What is the correct way to create large project files?

Good to hear you are splitting large amount of code, it will benefit you a lot in the long run.

It's very hard to say what is best, it depends on the interaction of those patterns with other classes. Normally it is best to put them in the location where they BEST belong to, i.e. where the least association with other classes exist.

If it has a lot of interactions, maybe you should put the patterns itself in a different class.

Normally what I keep as guidelines:
- Not more than a few hundred lines in a class
- Not more than 7 (class) variables in a class
- Not more than 7 functions/methods in a class

Of course these are guide lines. If you have a lot of simple (constant) pattern definitions the file will become larger without getting more hard to understand.

Also try to think of a class to have only ONE responsibility. If you want to be serious about splitting classes or how to organize them, read about SOLID.


Why does a variable size struct not compile in the Arduino IDE?

Flexible array member is a C feature. It does not exist in C++. On top of that, the way you use it to declare and initialize a static struct of flexible size is non-standard even for C.

However, GNU-C language supports it as an extension. Also, newer versions of GCC (6 and higher) allow this in GNU-C++ code as an extension as well. But GCC 5.4.0 used by Arduino IDE doesn't support this non-standard feature in C++ code.

If you flip through different GCC versions on Godbolt (https://godbolt.org/z/Iul7hD) you'll see that support for this feature has always been present in C code, but for C++ code it first appeared in GCC 6.

This is why you were able to compile it with your standalone g++ compiler (which is apparently a much later version), but were unable to compile it in Arduino IDE.

It means that if you really want this non-standard code to compile in the current version of Arduino IDE, you have to place it into a .c file. Or just specify the array size explicitly.