I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do).

10Ksps and 12bit-resolution adcs are fairly common for onboard ADC. you should be able to find lots of mcus that have adc modules that can do that.

even for an external adc, that's not difficult at all. because of the speed, you are likely looking at a spi adc module.

precision is another matter.


In the latest version of Arduino Desktop IDE, are there all features of Arduino Web Editor?

You will always get the same API features in both, because the API is separate to both of them - it's a plugin that's developed separately.

Would you get the same GUI facilities? No idea. Maybe - maybe not. It depends how useful they would be. You may get features added to the GUI that don't appear on the web. Or you may get the other way around. If they are essential to the operation of the system, though, you will get them added to both.


Error compiling: expected unqualified id before token {

At line 82 you have the closing bracket of the loop function. Then after that you have:

  delay(1000);

}
}

Which is invalid.

If you format your code properly it's easy to see. Fix that and it will compile. Will it do what you want is an other question...

#include <LiquidCrystal.h>
#define trigPin 12        // the trig pin to digital pin 12
#define echoPin 13        // the Echo pin to digital pin 13
#define led 8
#include <Servo.h>
Servo servoMain; // Define our Servo

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

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
  lcd.begin(16, 2);
  servoMain.attach(11); // servo on digital pin 11

}
void loop()
{
  servoMain.write(5); // Turn Servo Left to 5 degrees
  delay(1000);     // Wait 1 second

  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  if (distance < 3) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
  }
  else {
    digitalWrite(led, LOW);
  }

  if (distance < 6) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
  }
  else {
    digitalWrite(led, LOW);
  }

  if (distance < 8) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
  }

  if (distance <= 16) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
  }

  if (distance > 16 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
}
delay(1000);

}
}


Need a simple accelerometer visualization example!

After some quick searching I found an Instructable which uses your same sensor and plots the data thanks to a Python script.

You'll need to install Python if you want to replicate this project, but any programming language with a drawing library will work.


Memory leakage caused by String Concatenation

If you size the buffer to be able to hold your final string, then yes, that method will avoid the fragmentation caused by the String concatenation function.

Note that String holds the string as a C-style char array internally; it is the concatenation procedure which dynamically allocates and deallocates memory, causing the fragmentation.


SH1106 - Transferring long buffer via SPI

You seem to have understood the following but just for clarification:

transfer16(uint16_t word), as the name implies, shifts 16bits/2bytes instead of just 8bits/1byte like transfer(uint8_t byte).

transfer(uint8_t* buffer, unsigned int size) on the other hand takes a pointer and the amount of bytes to shift.

Now to pointer arithmetic. Operations on pointer variables are dependent on their explicit data type(as well as processor architecture!). Therefore, in our case, a +1 on uint8_t* val will advance the pointer by 8bits.
+1 on uint32_t* val will do so by 4bytes/32bits.

Check buffer's data type

It should be any of char, unsigned char, uint8_t, int8_t


analogRead() output oscillates even though the pin is grounded

You have nothing in your setup loop. You need to set up all the inputs as inputs.

You setup() should look like this:

void setup()
 {
   Serial.begin(9600);
   for (int i = 0; i < 5; i++);
    {
      pinMode(input[i], INPUT);
    }
 }

The code cycles through your array "input", setting all the pins as inputs. Try that.


Assuming you are using windows, on the device manager you can access each device's properties (power management tab), where you can allow or not each device to wake your system up.


NodeMCU powered with battery and use WiFi

It seem to be a problem with onboard regulator such as AMS1117.
ESP are really sensitive to power instability.
For every of my project i need to put capacitor on alimentation to prevent bugs.
I think you dont have enougth voltage to work properly with your regulated input.
To correct this issue you should put two battery to get 7.5 volt on the regulated input.
Another solution is using 3.3v input to pass trought the regulator.


How to send data from Arduino Uno with SIM900 GPRS to Firebase

Like you said, Firebase only accepts HTTPS traffic, which the Arduino Uno cant generate. Your HTTP requests first need to be sent through a proxy server that supports SSL, before being sent on to your Firebase database using a PUT or POST request. This site explains how to do everything from setting up your own proxy server to writing the GPS data (in your case) to Firebase. You may want to look at alternatives if this is too tedious for your purposes.


stk500 getsync() attempt 10 of 10 atmega328pu

The first thing you should do is add a 0.1uF capacitor connected "in series" with the jumper wire from the DTR terminal of the FTDI programmer to pin 1 of the Atmega328P-PU chip. For most people, this will solve the problem.

I see you also have a "push button reset switch". If you can press/release this button at precisely the right moment, the sketch should upload without error. Using the Arduino IDE, if you click on the "Upload" button then press and release the "push button reset switch" just after the Arduino IDE's black console window shows you the line starting with:

  Sketch uses x bytes (y%) of program storage space...

there is a good chance it will work. You can try holding the "push button reset switch" down for 1 to 1.5 seconds.

Please add a capacitor to the DTR circuit or disconnect it from the Atmega328P-PU before you go any further. A DTR connection to the programmer is not needed for the "push button reset switch" method of uploading and a "direct, hard wired connection" could cause an issue.


You may use remove() method to remove last character.

String s = "1234567890";
while(s.length() > 0) {
    int lastIndex = s.length() - 1;
    s.remove(lastIndex);
    Serial.println(s);
}


Problem of fetching data from web page using Arduino Uno and ESP8266

I flashed the ESP8266 with another firmware then it worked at baud 9600 perfectly
The original firmware was not responding to the baud 9600 at all


A CPU or MCU uses very basic instructions which are executed.

If you write code in a program language (like in Arduino IDE), the sketch is converted into many instructions (by the compiler and linker).

The instruction set can be found here.

An example is:

ADC Rd, Rr: Adds two registers and the contents of the C flag and places the result in the destination register Rd.

A CPU/MCU uses registers, which can be seen as very fast 'variables', mostly there are quite few of them, and all operators (like +, -, *, /) are carried out using these registers.

If you are just starting Arduino, it's not so useful to dive into this, the compiler/linker will take care of these 'details'; just be glad you don't have to write in assembly (anymore).


Arduino and RF24 library: communication stops after short amount of time

Your question does not provide much information to go on.  Setting up as given in the tutorial is a good start, but does not guarantee that there will be no problems.  It can still either be a problem due to hardware or firmware.

Firmware problems:

The radio data may be getting corrupted after some time, which shows up as a failed radio transaction
You inadvertently change the register settings of the radio

Hardware problems:

There is noise interference on the radio channel you are using due to the urban environment (wifi, etc).  Does the system work any better on a different channel?
The radio drains too much power and browns out, then will revert to default settings on the IC rather than the ones set by your Arduino sketch.


Choosing rangefinder for obstacle-avoiding

Odds are pretty good they are real close. I've only used the sr04 with
  4 pins (too lazy to mod) and it was ok. cant say if the parallax is
  better or not. For 4 times the price you'd expect it to be, but so far
  in robotics, price seldom reflect performance in my experience. –
  Spiked3

I've also used the SR (with 4 pins) and it worked great. <2$ on eBay


Your answers :-)

yes, it's possible and should not be too complex
for a simple prototype, you do not need an embedded device, just a PC with a webcam
a webcam with few megapixels should be enough
try OpenCV

After your prototype is ready, you can use a small PC-like platform.
Examples: Minnowboard, Edison, BeagleBone, RaspBerry PI 2, Arduino Yun, Galileo 2

A word of warning: depending on the expectations you have, you will have to pick more powerful models. Computer Vision is computationally intensive.
The examples I gave are roughly sorted by performance and, unsurprisingly, cost. OpenCV is available for many architectures, but afaik, it is particularly optimized for x86, since it's mostly sponsored by Intel.

Disclosure: I work for Intel, so I am more informed on Intel products, but by no means I'm trying to do advertisement, this answer is simply given to the best of my knowledge.


What happens when I exceed amp limit on Arduino 5v pin?

If you exceed the amp limit, that can be drawn through (!) the Arduino, some components on the Arduino will be fried (As for most electronic devices. For the Arduino this is practically a short). There is no current limitation there. Which components are fried depends on how you provide the power. If you provide power through the power jack or VIN, the voltage regulator will burn out. If you provide power through USB a diode or the MOSFET will be fried (You can look this up in the Arduino UNOs schematic at this site).

The setup might output a current, that is a bit higher than 500mA, for a short time. But the mentioned components, that are in the currents path, will heat up very quickly and be destroyed. In this short time the LEDs will be very dim, since the Arduino cannot provide a current as big as 8A, not even for a short time.

All great loads have to be powered separately from the Arduino, so that their supply current will not flow through the Arduino. If you are using a powerful USB supply, you have to split the power lines, before giving the voltage to the Arduino. You can connect the USBs 5V pin to the 5V pin of the Arduino and to the LEDs. If you are using a power supply with a higher voltage than possible for your LEDs, you have to buy an extra regulator, that also capable of providing the needed current.

Important note: Since you didn't specify, how you are connecting the RGB LEDs, you also have to take care about the current limit of a single pin. It should not exceed 20mA, 40mA at the absolute maximum. So you cannot drive the LEDs directly. You will need a driver for then anyway. The simplest way is a MOSFET, that is capable of sourcing the corresponding current. It is then controlled by the Arduino, which needs very little current for it.


Passing variables for a PID in an interrupt

Short answer: Yes, it is possible to update global variables from interrupt routines, but it comes also with problems.

Long answer:

First you have to understand, how interrupts work. You are using a timer interrupt and an external (pin) interrupt. The compiled program lies in the flash of the chip. At the start there are some special addresses for the different interrupts. If the hardware then registers a condition for an interrupt, it will stop the execution of the main code (the code, that was executed, when the interrupt condition occured), saving the current state and jumping to the corresponding address, where it get's send to the ISR (interrupt service routine), that you defined (in your case the function docount()). After the execution of this program the microcontroller will return to the execution of the main code (by restoring the previously saved state and jumping there). An ISR can only have a return type of void (no return value), because when it returns, there is no special code to receive and use this value. The interrupt may occur at different times every time.

Instead it is common to write global variables in the ISR. For this you have to consider some points:

Global variables, that may be changed during an ISR, has to be declared (additionally to the type) as volatile. This means, that the compiler cannot optimize this variable (for example to a local variable) and has to consider, that it may change anytime, so that he cannot use a cached value.
The usage of the variable in the main code has to be atomic or secured against changing of the variable. If you use a variable in a calculation, it may take many cycles for it (especially if you have a big datatype or some expensive calculations as with float). If the interrupt occures in this time, the value might be changed in the middle of calculation, making the result a bunch of garbage. If the calculation only takes 1 statement cycle, is cannot be interrupted and is called atomic. Since this is rarely possible, you can enclose the corresponding code into securing code. For the Arduino platform, you can use the noInterrupts() and interrupts() functions, to turn off all interrupts, do the calculation and turning the interrupts on again. Be sure do turn the interrupts off only for a short time, so that you don't miss interrupts. Often this is only used to copy the variables value into a local variable (local working copy), which then can safely used for calculations, while the global variable may still change.

Besides that, you also have to think about, what code you write into an ISR. An ISR cannot be interrupted by another interrupt. So functions, that depend on interrupts to work, will not behave like intended. The delay() function for example will simply block all code execution, since the return of the millis() function will not change (it depends on the timer0 interrupt). In your Timer1 ISR, you use Serial.print(). This function can be used, but only until the Serial libraries buffer is filled. The actual communication will take place, after the ISR returns, because it also depends on interrupts. When you try to send more, than fits in the buffer (64 bytes), you will loose data. Currently you should be below that, but you should have this in mind, when coding.

I don't think, that you really need a timer interrupt for calculating and outputting the data every second. Here I would use a non-blocking coding style in the loop() function, like you can see in the BlinkWithoutDelay example, that comes with the Arduino IDE. This is better than using delay(), which is just busy waiting. You save a timestamp with the millis() function and check the time difference. That saves Timer1 for other purposes and also refactors your main code for being extendable and non-blocking, if you want to add more functions.

As I read from this example from the PID library, you need to call myPID.Compute() once in a while to do the PID calculations with the new values. Since these only change every second, you should call this function directly after the calculation of Input.

All in all you need something like this (I didn't include all the code, just the important part, so that you should be able to understand the principle):

unsigned long timestamp;
#define INTERVAL 1000

void loop(){
    if(millis() - timestamp >= INTERVAL){
        timestamp += INTERVAL;
        noInterrupts();
        int counter_copy = counter;
        interrupts();
        // Do the calculations with counter_copy and same the result to `Input`
        // You can put the code from your timerisr here (without the Timer1 code)
        myPID.Compute();
    }
}

Your pot code then should also be enclosed in such an if statement, to prevent, that the PWM get's restarted again and again very fast. If a reaction time of 1s is ok for you, you can put this code in the if statement above. If you want faster reaction times, you can add a second if statement like this to the loop() function (including it's own global timestamp variable and interval value).

The digitalWrite() calls for the direction can be put into the setup, since they don't ever change in your code.


No. You cannot directly drive any bare motor directly from an Arduino without any external components. To do so will damage the Arduino.

You need a motor driver (or at least some transistors and diodes etc) to control the motor.


So here is my official answer ;-)

Your sketch goes above the 30k flash available on the Arduino Uno.

Yes the Uno has 32k of flash, but 2k is used for the Arduino bootloader. if you convert 0x7800 in decimal that gives you 30720 which is exactly 30k. And your sketch is 30908 bytes so it's 188 bytes too long.

Try optimizing it.

A second alternative would be to use the Optiboot bootloader replacement (https://github.com/Optiboot/optiboot) which only uses 512 bytes.


Confusion over Transistors for a switching circuit with an Arduino Mega 2560

A transistor amplifies current, not voltage.

The first thing to check is the current of your LEDs. In your current configuration, it is between 25 and 30 mA. This is too high for most LEDs. Check the datasheet of your LEDs for the actual forward voltage, and current rating.
To calculate the value for the resistor in your circuit, use Kirchhoff's and Ohm's laws. According to Kirchhoff: VResistor + 3 VLED = 12 V. Let's assume that the LED's forward voltage drop VLED = 1.8 V. This means that VResistor = 12 V - 3 VLED = 6.6 V. Ohm's law will then tell you the relationship between the voltage across the resistor and the current through it: R = VResistor / I. The current through the resistor is the same as the current through the LEDs. Let's assume that this is 20 mA. Therefore: R = VResistor / I = 6.6 V / 0.020 A = 330 Ω.

The next thing to calculate is the resistor between the Arduino and the base of the transistor. As mentioned before: the voltage on the base does not matter, the current does. You want to use the transistor as a switch, so you have to drive it into saturation. As a general rule of thumb, you want the base current to be a tenth of the collector current in that case: IBase = ICollector / 10. The current through the collector is the same as the current through the LEDs, so IBase = 20 mA / 10 = 2 mA.

In a similar way as before, we can calculate the base resistor: VResistor + VBase-Emitter = VArduino. The voltage of the Arduino pin is most likely 5 V, and the Base-Emitter voltage of a silicon transistor is around 700 mV (look it up in the datasheet): VResistor = 5 V - 0.7 V = 4.3 V. Then use Ohm's law again to calculate the resistor value: RBase = VResistor / IBase = 4.3 V / 0.002 A = 2150 Ω ≈ 2.2 kΩ.

The current has to flow through the base to the emitter. For current to flow, you need at least two connections: current flows from the Arduino pin, through the transistor, to ground. You have to connect the emitter of the transistor to the Arduino's ground.

You can use pretty much any normal transistor that has a maximum collector current that is larger than the LED current, and a maximum collector-emitter voltage greater than your power supply.


Connect multiple modules to arduino micro

You can design/build/deploy a power supply that provides to each board (arduino included) the voltage it needs (but it's advisable to have modules working at the same voltage level) and that should be sufficient.
As long as you have a shared Vcc-to-GND reference, it's enough.

To verify that the power supply you choose is ok, do the following:

check that the modules are compatible with its voltage (ex: all at 5V)
check that the combined power consumption of each module (you get that from the datasheet) is lower than the total power output of the power supply.

Additional checks:

check that the maximum voltage ripple provided by the power supply is lower than what the modules can tolerate
check that the peak current the power supply can provide is larger than the combined peak current of all the other devices.


What are the Ramps pins on my Arduino mega?

You are right, your have all the information in your question.

Pin 54 Refers to the Arduino PIN Number, nothing to do with RAMPS.
0-53 are the digital pins and the 54 is A0, etc.
So the pin numbers should go higher than 69, which is A15.


Generally the Tools > Programmer selection is only used for Tools > Burn Bootloader and Sketch > Upload Using Programmer and is not used for standard uploads. So for standard uploads you can set it to anything you like because it will have no effect.

The most notable exception is the Adafruit Trinket, which does require you to select Tools > Programmer > USBTinyISP even though you are uploading through the USB socket on the Trinket board without a separate ISP programmer.

You will also find some 3rd party hardware packages that are not written for boards with an Arduino style serial bootloader and so treat a standard upload as an "Upload Using Programmer" for the sake of convenience. Examples are MicroCore and the "Barebones ATmega Chips (no bootloader)" hardware package. In this case the correct Programmer menu selection is dependent on which model of ISP programmer you are using.

So regarding the question "How can I tell what programmer to use?": If you're doing a standard upload, start by assuming it doesn't matter. If that doesn't work, read the documentation!

If you're doing a Tools > Burn Bootloader or Sketch > Upload Using Programmer (or holding shift while pressing the "Upload" button) then you should select the model of the ISP programmer you're using.


Does the compiler generate intermediate assembler?

My source files are *.ino, but after compilation there aren't any other files placed in the folder.

Correct. The Arduino IDE performs compilation in a separate temporary directory, whose location you can see if you enable verbose compilation in the IDE options.

  Does the compiler generate intermediate assembler, and if so, where does it leave them?

By default GCC (which the Arduino IDE uses) does not leave intermediate assembly language files on disk. You must pass the --save-temps argument to have it leave them in the current directory, or --save-temps=obj to save them in the output directory.

  Or is the machine code available somewhere?

The machine code is available in the .elf and .hex files generated in the temprary directory.


You are not sending a speed command to the motor, you are sending it an analog voltage with the analogWrite. If that voltage is too low, the motor will stall. A higher value should make it spin faster. If you want the speed to be more tightly controlled, you will need encoders on the motors to sense how fast they are spinning, or use stepper motors.


How to get air speed, which sensor to use?

Typically you want to use Pitot tube sensor


Manual TCP connection using WiFi ESP8266 module mistyped command

You need to escape your quotes:

Serial1.println("AT+CIPSTART=\"TCP\",\"192.168.1.5\",1647");


Using usb port to communicate with standalone atmega328p circuit

The ATmega328 does not have any native USB capability, so there is nowhere appropriate to connect D+/D- to the ATmega328.

Assuming you are emulating an Arduino Uno, then something like this:

https://www.jaycar.com.au/arduino-compatible-usb-to-serial-adaptor-module/p/XC4464

is what will come closest to mimicking the USB function on an Uno (ie a serial connection).

This shows how such a device would be connected:

https://www.jaycar.com.au/usb-serial-converter


simultaneously read 16 hall sensor and maximum current allowed by Arduino

Since this sensor doesn't need to be driven directly from a pin, the maximum current for one pin is not important here. The hall sensor uses two of it's pins as supply voltage. The output pin is an Open-Collector pin. So it will be connected to GND trough a transistor depending on the magnetic field. If you use an external pullup resistor (as connection between OUTPUT and positive supply voltage), you get somewhat like a voltage divider. Since the hall sensor seems to behave as a switch, there will only be two possible states. When the magnetic field is low, the transistor doesn't let the current flow. The pullup resistor can pull the pin to the positive supply voltage (5V -> 1 as digital value). If the magnetic field is high enough, the transistor will open the connection to GND. Now a maximum of 25mA of current can flow throw it to GND. The voltage of the pin is now determined by the voltage divider the transistor and the pullup resistor build. You can calculate the virtual "resistance" of the transistor in this state with Ohm's law

  R = U/I

(R is resistance, U is voltage and I is current) With 5V supply voltage and 25mA current you get a resistance of 200 Ohm. Since you just want to use the sensor as a switch, you only have to ensure, that the pin cannot be pulled to a significantly greater value than 0V. So grab a resistor, that is significantly higher than 200 Ohm and use it as pullup resistor. Keep in mind, that you always must use the pullup resistor with the supply voltage, that runs the Arduino. A higher voltage can fry the Arduinos components.

Then you connect this pin to a digital pin of the Arduino, which you configure as INPUT. In this state the pin has a high impedance, so that the current, that flows into it, is really small (it CAN source 25mA, but it does not have to. The current depends on your external circuit). So this isn't something you have to bother about.

This leaves us with the supply current, that the sensor needs to work. In the datasheet it says, that at a supply voltage of 8V the supply current is at maximum 9mA. For 16 sensors this gives us a total of 144mA, which is still comfortable inside the 200mA the Arduino can provide. So you should be able to drive all of them safely.

That said, if you want to add more components, that draw current, it might be better so source the current you need not over the Arduino but directly from your power source (if this is possible for you). Depending on the current you may need, it can also be good, to get an external voltage regulator (if your supply doesn't directly give you 5V), that can provide enough current.


Serial.write and Serial.println return different values? Cannot use correct ones

The text file contains the sequential ascii values that spell out the data, not binary data. println in printing the numerical value of each byte. For example, the 10's println prints are '\n' characters. write is printing the ascii character associated with the binary value (the new line). You need to parse the ascii characters into numbers.

Luckily for you the SD library inherits from the Stream class, so it will have the same parseInt function most often used to parse ints from the serial monitor.

You probably want to set myFile.setTimeout(0) first because the file isn't slowly getting characters from the serial bus, so the timeout would just slow you down.

Then you should be able to parse and print out the ascii integers with something like this:

int val = myFile.parseInt();
Serial.println(val);


Finding Relatively Accurate Velocity Using an IMU

Integration of acceleration to derive velocity is a difficult task.  This is the first step in dead reckoning.  Consider some of the following options to improve accuracy:

Some IMUs can be adjusted to increase sample speed. If the
acceleration is sudden, more samples my improve the accuracy of the
calculated velocity.
Try aligning just 1 of the axes of the IMU chip in the direction of
acceleration. Do this to simplify the problem.  Depending on the
Arduino you are using, the processor may not have the power to
perform the trig functions necessary for anything except
acceleration only along 1 of the IMU's axes.
Take care of loosing significant digits.  If using integers, try
multiplying everything up.  For example instead of 1 equaling 1
meter multiply the value up such that 1000 equals 1.000 meters.  Now
integer math can be used to calculate down to the mm.


The solution was to move the enum declarations to a header file, due to the fact this was a VM add-in issue which will be resolved once they've implemented arduino version 1.6.8.

Adding this code to a header file and removing it from the main file resolved the issues and the code builds and runs.

// ModelRRCrossing.h

#ifndef _MODELRRCROSSING_h
#define _MODELRRCROSSING_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif
#pragma once
// Arduino Digital I/O pin numbers for MEGA
//note: digital pins 30-45
//MEGA is a MUST for this project
enum {
    Relay1 = 30, Relay2 = 31, Relay3 = 32, Relay4 = 33, Relay5 = 34, Relay6 = 35,
    Relay7 = 36, Relay8 = 37, Relay9 = 38, Relay10 = 39, Relay11 = 40,
    Relay12 = 41, Relay13 = 42, Relay14 = 43, Relay15 = 44, Relay16 = 45
};

enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum class CrossingZoneState : uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

#endif


As suggested by Jot in a comment, one way would be to simply do what you want (which takes roughly two seconds per iteration) in a loop, like this:

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(5);

  for (int i = 0; i < 30; i++)
    {
    myservo.write(45);
    delay(1000);
    myservo.write(125);
    delay(1000);
    }
}

void loop()
{
}

The problem with that is it relies upon knowing how long your delays are, and assumes that the myservo.write() functions take no time. A better method is:

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(5);

  unsigned long start = millis ();

  while (millis () - start <= 60000)  // for 60 seconds
    {
    myservo.write(45);
    delay(1000);
    myservo.write(125);
    delay(1000);
    }
}

void loop()
{
}

This uses the millis() function call to find out how much time has elapsed, and wait for 60000 milliseconds (60 seconds).

I've put the code into setup because that is where you put things you want done once.


Need Help to Select Microcontroller ?? Help

We cannot say, what single board you need to use. There are many boards, that are fitting to your requirements. You yourself have to choose.

Most of your listed boards use the same microcontroller (as Juraj wrote in his comment):
The Arduino Uno (doesn't matter where you buy it, it's the same) and all the boards with a 328 at the end use the Atmega238P. The Sparkfun Arduino Fio uses an Atmega32U4, which is different from the 328P, but not a very big jump (though it implements native USB support). These are all AVR based microcontrollers. The Particle Photon is not an Arduino. It uses an ARM processor and has wifi.

To choose from the big amount of boards on the market, you should look into your requirements:
- How many outputs do I need? Only simple digital outputs or also PWM? If the latter, how many individual PWM pins do I need?
- How many inputs do I need? Only digital or also analog?
- What extra devices do I need? Relays for motors/high loads? Special boards? And how do they need to be connected (what interfaces they use)?
- What interfaces do I need to the outside world? LCD Display + Buttons? Bluetooth? Wifi? Or nothing?
- How computationtime- and memory-consuming are the calculation tasks, that I need to perform (resources)?
- What environment will the project be in?

Based on the answers, you can choose a board, that fit's all the requirements and still leaves a bit headroom for further development. To help you I will write some examples for your project, that might be fitting for you.

Outputs: I guess your pumps are using mains power or similar (Be VERY carefully with mains power. It can easily kill you!). You need a relay to control these. It would be easiest to use a complete relay board, that includes all the needed extra circuitry. Then you just need to use one digital output pin per controlled pump, which results in 5 pins needed.
Inputs: This depends on what level sensors you have. If they have a digital signal (like a simple switch, that triggers, when it is covered by water), you just need to tie one digital input pin to each level sensor. With 2 level sensors per tank and 2 tanks we need 4 digital input pins for level sensing.

If the level sensors work with an analog voltage, you need to use 4 analog input pins. Their usage is a bit different, since their voltage has to be converted to a number value by the ADC (Analog Digital Converter) inside the microcontroller.
Interfaces: This is mostly up to you, since you didn't specify anything. You can just build the device with any outside interfaces, if you don't need them. Then you also can use a board without wifi. If you think, that adding wifi in the future would be a great idea, you can use a wifi capable board and just disabling wifi, until you need it. (Thinking a bit in the future, what future development might get interesting for this project)
Resources: Controlling motors (pumps are only motors for the microcontroller) based on some simple inputs is somewhat the standard task for a simple microcontroller. It doesn't need much computation power, neither much memory.
Environment: The temperature is not a problem for you. Basically all microcontrollers can operate in temperatures up to 80°C und down to -35°C (the exact values can be found in the datasheet of the corresponding microcontroller). The humidity is more of a problem. You need to build a water resistant casing for the electronics of your project, so that no water can get on the electronic parts. Also - to be sure - you should put one or two of these little silica bags into the casing, which sometimes come with electronic devices or such. The silica bags will bind the water in the air inside the casing and will keep the electronics even more dry.

So you need a simple microcontroller with 5 digital outputs and 4 inputs (digital or analog depending on your sensors), so in total 9 free fitting pins. An Uno or some of it's variants are fitting for this. If you want it smaller, that the Uno, you might want to use the Nano, which is the same as the Uno, just smaller. If you want wifi capabilities, you can go with an ESP variant like the NodeMCU.

This is just an example. There are many ways to build such a project, so there is no definitive answer. Any microcontroller, that fit's your requirements, is ok for the job.


The Arduino boards with the NINA module: MKR 1010 WiFi, MKR 4000 vidor, Uno WiFi and Nano 33 IoT use the NINA module for WiFi networking with the WiFiNINA library and for BLE with the ArdunioBLE library. Additionally the flash memory of the NINA module will be available as storage.

The NINA module runs a firmware made by Arduino with ESP32 IDF framework.

I wired MKR ZERO with an ESP32 dev board for the WiFiNINA firmware and library according to MKR 1010 WiFi schematics, which is very similar to Nano 33 IoT. The MCUs are connected on SPI pins and UART for communication. The firmware uses one additional pin to signal to SPI master as 'ready' pin. Also io 0 and enable pin of NINA module are wired to put the ESP32 into flashing mode for firmware upgrade over UART.

On MKR 1010 and Nano33 IoT I2C is connected too. Boot MCU have access to on-board I2C sensors and could in theory communicate over I2C. This is currently not used.

The WiFiNINA library uses SPI communication. SAMD is master, NINA is slave.

The ArduinoBLE library communicates over UART. 'Ready' pin is used to switch to BLE mode in firmware at NINA reset.

The firmware uses io 0 as 'heartbeat' signal for the library.

My wiring:

the orange wire from MKR pin 5 is connected as reset to EN (with a wire under the ESP32 board)
io 0 of ESP32 is the yellow wire to MKR pin 4
VSPI pins 5, 18, 19, 23 (I changed 12 to 19 in firmware). white wire on MKR pin 7 and ESP32 pin 19 is CS
I used 22 as readyPin (originally 33). white wire on MKR pin 6
I didn't wire I2C and Serial here


How well will the Arduino Uno survive in a vacuum?

Interesting question. You're right- heat is your enemy. Given the power dissipated by a Pi even when idle I'm not surprised it died. Most chips depend on convection to get rid of heat. A loaded Pi might require a (convective) heat sink and/or fan to keep it's core temperature down to an acceptable level, and that's at normal pressure and temperature. An Arduino -might- be able to work in a vacuum- it can lose some of it's heat through lead conduction- it'll only draw ~.25 watts normally vs 2.5 watts plus for a loaded Pi.

Ultimately it will depend on your application. If you have idle time when you can put the Arduino to sleep that will help keep it cool. If you have a conductive heat sink you can use then that would certainly help.


Connecting two pressure sensors with one uno

You can try my BMP080/BMP180 Arduino library
My library doesn't require use of floats of math library, making your sketch very small and fast.


Why does this code not respond promptly to changes in the LDR reading?

I'm going to lever off gre_gor's comment on the question.

The code you are calling (for example, rainbow) has delays in it:

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

So we can see straight away that calling rainbow(20); is going to take at least 20 x 256 ms (256 iterations of the loop with a 20 ms delay) plus more because of whatever else it does. That is over 5 seconds already!

Then you call rainbowCycle(20); and then theaterChaseRainbow(50); so you won't get back to the main loop for a while.

How to fix? Well, it isn't just a case of adding a line or two. One solution is to rewrite without delays, but instead have a state machine.

An alternative would be to test the sensor in each loop. Let's guess your objective is to stop the display if the LDR gives a higher reading. You could copy/paste the functions in question, but test the LDR inside them, eg.

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {

    int LDRValue = analogRead(LDRSensor);   // <--- add these 3 lines
    if (LDRValue >= 100)
       return;

    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

Suggested improvement to example

The code below uses a technique of supplying a "callback function" to the functions that do the pixel displays. I modified the Adafruit example to show the idea:

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

#define PIN 6

typedef bool (*AbortFunction) ();

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, PIN, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code

  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

// function prototypes
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void rainbow(uint8_t wait, AbortFunction fAbort = NULL);
void rainbowCycle(uint8_t wait, AbortFunction fAbort = NULL);
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort = NULL);

const byte LDRSensor = 0;

bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

void loop() {
  // start with black
  colorWipe(strip.Color(0, 0, 0), 0); // Black

  // Some example procedures showing how to display to the pixels:
  colorWipe(strip.Color(255, 0, 0), 50, checkLDR); // Red
  colorWipe(strip.Color(0, 255, 0), 50, checkLDR); // Green
  colorWipe(strip.Color(0, 0, 255), 50, checkLDR); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
  // Send a theater pixel chase in...
  theaterChase(strip.Color(127, 127, 127), 50, checkLDR); // White
  theaterChase(strip.Color(127, 0, 0), 50, checkLDR); // Red
  theaterChase(strip.Color(0, 0, 127), 50, checkLDR); // Blue

  rainbow(20, checkLDR);
  rainbowCycle(20, checkLDR);
  theaterChaseRainbow(50, checkLDR);
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    if (fAbort && fAbort ())
      return;
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      if (fAbort && fAbort ())
        return;
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    if (fAbort && fAbort ())
      return;
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.AbortFunction fAbort
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

The important addition is to add another optional argument AbortFunction fAbort to each function call. The default is NULL, in which case the function behaves the same as before. However, if supplied, the function is called. If it returns true then the display function exits (thus avoiding the delays), like this:

if (fAbort && fAbort ())
  return;

The first test is "does the function exist?" and if so, the second test calls the function and checks to see if it returns true or false.

The modified example shows the scrolling patterns on the NeoPixels, provided A0 returns 100 or less. The function that does this is here:

bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

That function is passed as an argument to the other functions, eg.

rainbow(20, checkLDR);

I have a page about writing callback functions.


Doesn't work radio transmission from Arduino Uno to Arduino Pro Micro

Thanks for your answers. I solved this problem, my Chinese copy has problems with power.


Ardiuno DUE board. Sketch uploading Error

The problem is solved. The cable came with my Arduino was charge only , I tried data transfer cable and it worked. This is so dumb. sorry for wasting your time.


Can I power the arduino UNO through the 5V pin while I use USB cable to collect data?

If u use the VIN pin of arduino, You shouldn't have a problem , as arduino selects it required voltage automatically, it's voltage regulator senses the voltage from USB and External source, if the power of the external source is higher than usb, the the power is bypassed to the External power. But don't know if you are using the 5 volt pin to turn on the arduino.
Well everything I said is applicable for UNO boards don't know other ones.
Thanks...


I think line 84 that keeps the leds green instead of going black. I think line 81 is there to create some kind of shimmer effect on some of the green leds and to skew the color to a bit more green. So I removed those. To prevent the leds from going to black instead of green, I added an if statement that stops any further fading out, if the total "brightness" is 16 or lower. I have no idea how this will look. You might have to tweak this 16-value a bit.
That's the best I could do without a full rewrite of the code.
void SingleDrift() {
  int mini = 5;
  int maxi = 255;
  FastLED.setBrightness(maxi);
  for (int i = 0; i < NUM_LEDS; i++)
  {
    if (leds[i].r > 64) leds[i].r = leds[i].r - 8;
    if (leds[i].g > 64) leds[i].g = leds[i].g - 8;
    if (leds[i].b > 64) leds[i].b = leds[i].b - 8;

    if ( (leds[i].r + leds[i].g + leds[i].b) > 16) // prevent fading to black
    {
      int rnd = random(10);
      if (rnd == 1 && leds[i].r >= 2) leds[i].r = leds[i].r - 1;
      if (rnd == 2 && leds[i].g >= 2) leds[i].g = leds[i].g - 1;
      if (rnd == 3 && leds[i].b >= 2) leds[i].b = leds[i].b - 1;
      if (rnd == 4) leds[i].fadeToBlackBy(2);
      //if (rnd == 5) leds[i].g++;
      //if (rnd == 6 && leds[i].g < 240) leds[i].g = leds[i].g + 1;
      //if (rnd == 7 && leds[i].b < 240) leds[i].b = leds[i].b + 1;
      //if (leds[i].g < 2) leds[i].g = 2; // I think this line kept the leds green
    }
  }
  ...


Yes, based on basic electrical theory, you have the ground connected correctly.


Store value in EEPROM to perform different actions on reset?

While it looks interesting as idea, IHMO you have keep in mind:

Include some code for button denouncing logic. Actually you will receive couple of “resets” during ~20ms during button press. Without denouncing you may end up with reset signal right at the moment you write to the EPROM. While EPROMs are pretty “solid” nowadays, it many not be good practice. One of potential solutions IMHO is to delay update EPROM with state switch for 20ms after boot, so it be done in stable state.
You may also consider to include electronic circuit to hold reset long enough to reboot the controller (it may also reduce bouncing).
EPROM has finite lifespan in terms of rewrite cycles, if your device turned on and off ~100 timers per day, it may die in a ~year.
Writing the EPROM usually consumes significant amount of energy, so it may reduce battery lifespan (if you use battery).

Probably more classic approach with sleep / wake up by button looks more reasonable, unless you have shortage of pins ;)


The Arduino UNO always consumes current mainly because:

it has 2 MCU, the ATmega328 which you can power down, and an ATmega16u2 for USB communication which is never powered down.
in addition, the voltage regulator is permanently leaking some current

To be honest, I am surprised your UNO consumes only 15mA, on my boards, it is rather near 40-50mA.

Also, a 9V battery is probably the battery with the smallest charge capacity.

I would suggest you:

work on a breadboard with just the ATmega328,
power it with two 1.5V batteries (AA or AAA)
and run @8MHz

That should already reduce current consumption.

You may even try smaller MCU (e.g. ATtiny84A) which consumes less current than the ATmega328 in the same conditions.

Finally, I highly recommend Nick Gammon's blog on that topic. It includes many good tricks to help you with current consumption.


How do I erase internal EEPROM on a Arduino Pro Mini

You are clearing 28 decimal bytes, but your address range is 28 hex bytes, or 40 bytes of data.  Hence, the last 12 characters are untouched.


Why my Arduino output active on reset using relay module?

The relays may be low-level triggered relays so to turn them on you need to set the pin connected to the relay to digital LOW and to turn them off you need to set the pin to digital HIGH; Please verify this first whenever you get a new relay and there is no mention on it if its a low-level triggered relay;


Diffrence between running once and infinite

Serial.read() -'0'

Such code is often used to convert a character to a digit (e.g. int).

Like if the character is '2', than '2' - '0' = ascii 50 - ascii 48 = 2

However, if you use

Serial.read()

the value will be 50 instead of 2.... maybe looping 50 times (or 48 to 58, for values 0 to 9) will give you the impression it runs infinite?


The implied question is how to turn off the Tx LED, which has already been answered and is probably the answer you're looking for. But the question you asked is how to end the loop() function. Not to be pedantic but to clarify the use of loop, the simple answer is, "you can't". loop() is called from a forever loop in the C/C++ main program, function main(), so returning from it, either with a return statement or by reaching the final close } causes loop() to be called again. This is intentional as the main() function in an embedded system is never supposed to return, thus it must keep re-running the application program.

Update (since this question just reappeared on the front page, I'll add the following to my answer):

loop() reads and prints continuously. If you had wanted that code to be executed only once, you could put in setup() and leave loop() empty. Then the sketch would initialize the serial output, read an analog value, print it - once - followed by entering the empty loop() and remaining there until power-down.

A way to execute the loop function once is to write an infinite loop at the end of it, so loop() would never return and thus never be re-executed:

void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);

  while(1)
     ;
}


Why do I need to use latin-1 instead of utf-8 when using python with arduino?

but is there something about arduino that requires using latin-1?

No, not really.
What it comes down to is that Serial.read() reads bytes, irrespective of whatever encoding they may be being used with.  ISO-8859 only encodes character code points in the 0-255 range, so when you choose a 0-255 code point and send it as ISO-8859, it gets sent as 1 byte, which is how you're code has been written to receive it.
A 255 code point as utf-8 would require multiple bytes to encode and so would result in multiple Serial.read() calls for a given value.
If you open a python3 REPL and put chr(255).encode() or more explicitly chr(255).encode('utf-8') you will see it results in b'\xc3\xbf'.  So on the Arduino side you will see this as two separate Serial.read() results, 0xC3 and 0xBF.
When you're just taking in strings and UTF-8 and splatting them out via Serial.println(), the Arduino is blissfully unaware of that they're UTF-8 and not ISO-8859.  Really you could use any encoding you wanted, the the caveat being that if you're using c-strings to store them, the encoding would need to be one that doens't allow for a single null byte to be in the middle of the string.

You may want to look into using struct.pack rather than cobbling together python bytestrings with sequences of chr() and .encode(whatever). struct.pack will also result in a bytestring, but it's more purpose built for doing this.
You can import struct and then struct.pack('B', 255) will result in b'\xff same as chr(255).encode('iso8859-1'), but at least expresses intent.  'B' here signifies an unsigned char range, you'll find the format specifiers in the documentation. You'll get a greater benefit when you begin using multiple fields where struct.pack will be a lot less unwieldy than the chr and encode and string concatenation.


How many sensors can be supported by a single Arduino unit?

An Uno has more than enough pins for the devices you described.

A DHT22 Relative Humidity and Temperature sensor needs only one digital pin for both variables.
An MQ-7 Carbon Monoxide sensor needs one analog pin.
An MG-811 Carbon Dioxide sensor needs one analog pin (and an amplifier).
A Piezo buzzer needs one PWM pin.
The LCD with a Hitachi interface needs four digital pins.
The ESP module needs two digital pins.

That's 7 digital pins, one of which needs to be a PWM pin, and 2 analog pins. I did not make any choices about best or cheapest devices, just ones I either knew about or could find quickly by searching. But with this pin requirement doesn't come close to exhausting the available pins on an Uno so there's plenty of capacity left unassigned for you to make other choices that might require different interfaces or more pins.


ATtiny85 soft-latching, and sensor-waking: Are multiple switches differentiable by pin change interrupt?

If you have one dedicated interrupt signal, and enable the shared pin change interupt for only one pin, then you have no ambiguity - the hardware ISR is caused by the dedicated pin, and the shared pin change ISR is caused by the only enabled pin change pin.

Where things get more complicated is if you enable more than one pin to trigger the pin-change interrupt.  In this case, either the ISR or whatever follows in cause from it will need to figure out which pin caused the interrupt.

Unless I'm overlooking it in the data sheet, the ATtiny pin change interrupts don't have a register which latches the causing condition, so you may have to look at the actual pin input register.   The catch is that things like contact bounce might make the causing signal no longer present at the exact instant you check it.  However, contact bounce is typically a more serious problem when releasing a contact than closing it.

Some things you can do:

In the ISR, don't actually do anything, but set an "interrupt happened" flag.  Then in the main program, poll the inputs for a while until you see one actually asserted, and act on that.  You should only need to stay awake for a small fraction of a second before you catch the responsible contacts closed when you are looking.
You could try to use a small capacitor to slow the rate at which the pullup resistor responds to the switch bouncing back open, in the hopes of  making sure that the causing condition is seen when the ISR itself looks.

In either case you will probably want to stay awake and keep the pin change interrupt disabled until the switch has been released, and for maybe a hundred milliseconds thereafter to let release bounces die out.  Then you can re-enable the interrupt and go back to sleep.

Do keep in mind that regardless if the MCU is awake or not, if someone wedges the product into packing material or something which holds the switch closed in opposition to the pullup resistor, then that pullup resistor itself may drain your battery over a few weeks/months.


Use lowpower-libary and still use serial connection and other things

Yes, activating low power does disable the UART - but only while it's sleeping.

To use serial you just need to ensure that you only use it while it's not sleeping - and due to the interrupt and buffered nature of the Serial driver it's not as easy as just printing.

However, it's simple to achieve: just flush the serial before sleeping. This ensures that any pending serial data is sent out through the serial port before you go to sleep:

void loop() {
  Serial.println("Turning LED on");
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.flush();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                      // wait for a second
  Serial.println("Turning LED off");
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  Serial.flush();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                  // wait for a second
}

If that doesn't help you may need to turn serial off and on yourself either side of your powerdown:

void loop() {
  Serial.begin(115200);
  Serial.println("Turning LED on");
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.flush();
  Serial.end();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                      // wait for a second
  Serial.begin(115200);
  Serial.println("Turning LED off");
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  Serial.flush();
  Serial.end();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                  // wait for a second
}

Update:

I just noticed you're using the Micro. That makes a big difference. The Micro and the Leonardo's Serial object is actually a USB CDC/ACM serial emulation, not UART.  You cannot sustain a USB connection while sleeping. So it will be killed.

To use communication while sleeping you will have to switch to a proper UART connection with a USB to TTL UART (e.g., FT232RL) adaptor to connect to the TX/RX pins and use Serial1 instead.


The IR receiver does some filtering on the signal. It doesn't signal a LOW immediately if it lost a single pulse of light. A speck of dust, hanging in the air, might just be blocking the IR phototransitor. Or some brief flash of light, making two pulses seem like one or more.

These IR receivers a specifically build to filter out the 'noise' coming from other light sources and light obstructions.

Identically, you would want this receiver to give you a HIGH if it detect only 2 pulses of light 13uS apart. I could just be some sunlight reflected from a puddle, accidentally matching 38kHz.


Interrupt volatile variable doesn't work as expected

Turns out, the 64 button shield calls the interrupt TWICE. Once when the button is pressed and once when it is released.

Thank you for everyone's help!


It seems you have to increase the gain, see inside the document

Sound dectector hookup guide

The following fragment:

Also take into account it needs between 3.5 and 5.5 V, while 5 V is ideal (see Quick start at the beginning of the same document.


Use command line to upload program through hex file to Teensy-LC

Paul Stoffregen (Teensy creator) has released a command line version of the Teensy Loader which can be found on his website. However, this program appears to be Linux only, so unless your client has Linux, that may be a non-starter. The source code for the program is available, so you might be able to work out the logic and port it over to whatever platform you are wanting this to work on (just make sure you comply with the source code license).

All that being said, pressing the reset button is not necessary for programming. The Teensy loader should be able to trigger a reset over USB all on its own. So unless the current program on the device disables interrupts that are necessary for the USB port to function, or it was programmed with the USB port disabled (by selecting "No USB" in the USB Type menu), physically pressing the reset button isn't necessary for programming. For more details you can see this forum post.

Loading Firmware Without Pressing the Button

When programming via Arduino, it does a lot of things for you automatically. To replicate that manually, follow these steps:

Connect the Teensy to the computer via USB.
Run teensy.exe (found in C:\Program Files (x86)\Arduino\hardware\tools)
Click the button on the left to select the hex file to load.
Go ahead and leave Auto enabled (this actually doesn't matter).
Run teensy_reboot.exe (also found in C:\Program Files (x86)\Arduino\hardware\tools, this will restart the Teensy, as if you had pressed the button, and automatically start the programming process.)


Arduino IDE monitor multiple USB ports simultaneously

If you are only interested in monitoring the output, a simply python script can be run to monitor the port. This sample takes an input of the port number(assuming they get named ttyUSB1, ttyUSB2, ect...  Or you can modify it to be a hard coded port.  Also make sure the baud rate matches with what your arduino is running (115200 in the example)

You can then run this script in two separate terminals, one for each port

#!/usr/bin/env python3

import serial
import sys

if len(sys.argv)<2:
    print("Please give serial port number")
    exit()
port=sys.argv[1]
ser= serial.Serial('/dev/ttyUSB'+port,115200,timeout=5)

while True:
    try:
        print(str(ser.readline().strip()))
    except:
        print(sys.exc_info())
        ser.close()
        exit()

Start the program like so

python3 ./programName.py 1 (or ./programName.py 0, etc)

The number dictates which of the ttyUSBx devices you are trying to watch (will match with what you see in the arduino IDE).


This is to be expected.

The other pins have nothing connected to it, so their voltage is floating.

The Arduino MCU only has a single ADC. To read the different analog pins, it uses a multiplexer to connect the pin you want to read to the single ADC. The ADC inside the MCU have a "sample and hold" capacitor inside it.

To read the voltage at the pin, it will connect the pin, to charge the sample and hold capacitor. It will then disconnect and measure the voltage of the sample and hold capacitor, one bit at a time.

So in your case, by reading the voltage at the connected pin, it will charge the capacitor. It will then read the unconnected pins. But because nothing is connected the sample and hold capacitor will stay at about the same voltage, because the unconnected pin will neither charge, nor discharge it.

Measuring the voltage on the sample and hold capacitor will slightly lower this voltage, so that's why in the graph the lines will be lower than the previous measurement.

PS Also, because all the pins are placed in a breadboard, you'll have some capacitive coupling between the adjacent pins.


LEDs: difference between common anode and common cathode?

A 7-segment is a packaged set of 8 LEDs (7 number-segments & 1 decimal point). Common anode means that the anode (positive) side of all of the LEDs are electrically connected at one pin, and each LED cathode has its own pin. So turning on any particular segment will involve running a current from this common anode (positive) pin to the particular cathode (negative) pin for the desired segment.

Common cathode means that the cathodes of all of the LEDs are common and connected to a single pin. The anode for each LED has its own pin. So driving one of these means running a current from the particular anode (positive) pin for the desired segment to the common cathode pin.

The way that you are diving the 7-segment involves using a separate pin to drive each segment, so you use 8 pins of the Arduino to drive the display. You will run out of digital pins if you try to add a second 7-segment. There are a couple of ways to address this. One is to add a 7-segment driver, like the CD4511. This limits you to being able to display only numerical digits, but uses only 4 pins of the Arduino per 7-segment.

Another, more versatile way is to add a serial-in to parallel out chip (74HC595, for example) to drive the 7-segment. This requires only two pins from the Arduino (data & clock), and they can be chained to have multiple 7-segments driven from those same 2 pins.


There is no simple way to have a formula from the RGB values to intensity.
Also, there is intensity that can be measured with an intensity meter/sensor, but what people (humans, or each individual) consider more intensity (perceived intensity) is not fully related.
However, some things I found when I had a similar problem:

Typically a LED value of 0 is OFF, 1 is shining a little and 255 a lot. However, the difference in (perceived) intensity between value 1 and 10 is much higher than between e.g. 100 and 255.
Also, each LED color has a different intensity, e.g. red seems more bright than blue or green, with the same R, G or B value for the DMX lights I have, as can be read from the remarks from Duncan C and Majenko below, red is less bright than others.
Also, it depends on the physical device probably (it could have an internal algorithm to convert an RGB value to some power driven to the LED(s)).

What you can do is measure for each value and color the intensity with an intensity meter or sensor.
Or, in case you are more interested in the perceived intensity, manually check two LEDs with values to and create your own intensity algorithm.
I ended up having 3 arrays (for R, G, B), having for each value from 0-255 an 'intensity' value. I did it partly by measuring, partly by manually checking.


Powering LED Strip at both ends shorts my psu?

Put a diode to every psu cable or just take only one psu but make a connection between the input and the far end eith a cable of more than 0,5 mm^2... Spesker csble or so.

Problem with two psu is: one gives 5,00 Volt,  the other 5,05... And there is s power of 0,05 Volt / 8 Ampere running.

Second problem can be the influrnce of different PSU switching frequencies.
Regards,  Michael


In the product description it says "DC 12V 8-Channel Relay interface board, and each one needs 15-20mA Driver Current." So 8 times 0.020A is 0.160A per board. I think your 2 amp power supply should work just fine.


It's pretty hard to see the wiring for sure in the photo, but you have an extra red wire looped from one side to the other, what is that for? It's not in the tutorial. Other than that, your wiring looks ok to me, as far as I can see from the photo. So probably it's broken, I hope you can return it.


To what extent is Javascript used in robots?

It wouldn't be my first choice for programming of robotics, but it's certainly doable.

Thanks to NodeJS, JavaScript (or ECMAScript as it is properly known) has broken free of the browser and is now a general programming language.

Thanks to the BeagleBone Black (and others), which runs most of its systems by default through NodeJS, including its web-based IDE, you can program the whole board with ECMAScript.

So yes, you can do robotics with ECMAScript, and there are platforms which do allow you to do robotics with ECMAScript.

Would you want to do it in a real industrial environment?

As I said - it wouldn't be my first choice.


I'm sorry to tell you but i think you damaged your board severely that's because you took more energy from the pins than an arduino can handle.

150 LEDs takes way too much power for the arduino to handle as you can see here.

So you likely burnt something on your board and might have to replace it :/
make sure which board is damaged(the arduino itself or the shield) before replacing it.

If the ATmega328P(The chip on the arduino) is damaged then this should be an easy fix.

Instead of what you did, you shoud have powered the LED strip from another power supply(not from the arduino pins) and used the arduino to turn "this power supply" on and off(probably using transistors).


What are the problems with using an Arduino in a production environment?

I want to know if there is anyone that has used Arduino boards in a real project?

I have seen it being done, quite a few times.

  What are the problems that you have faced?

Pros:

quick to market;
low cost accessories;
large code base to drop from;
...

Cons:

only workable for certain applications -> high cost per mcu (vs. bare chips), no possibility of passing certification of any rigor, no respect from others / clients, ...
quite inflexible an eco-system: porting code to / from others can be problematic.
poor project management capabilities.
...

Each of those pros / cons can be addressed and may not be relevant for your particular application.


What I do in situations like that is get some of those breadboard hookup wires, like you have in your second photo, cut them in the middle (giving yourself two wires, each with a bare end, and a end with a plug on them).

Strip the bare end, and then solder it to the servo motor wires. Before commencing soldering, slip some heat-shrink tubing onto the wire. Once the wires are soldered together, move the heat-shrink tubing over the join and shrink it (with a hair-dryer, or heat gun).

You now have a plug for your breadboard which is designed to be mechanically strong, and the heat-shrink tubing over the join protects it from being flexed too much.

You could put some thicker heat-shrink over all three wires, to give additional stability.


Pro Micro board not responding to anything

It turns out I had to use the port ttyACM0 (and not ttyS0) which wasn't found at the time. The port was there the next day and I have no idea why it wasn't there before.
Also, I thought I had to press and hold RST for a couple of seconds to reset the Pro Micro, but I actually have to press it twice in a row.
I've managed to flash the firmware for my keyboard by double-pressing RST.


Android phone can't get ESP8266WebServer page if Content-Length > 1460

The solution is to add the following line to platformio.ini:

build_flags = -D PIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY

I noticed that the same sketch works without a problem when building with the Arduino IDE, so I checked the differences in building with platformio and the Arduino IDE.

Turns out the relevant difference is that the Arduino IDE uses lwIP 2 by default, while platformio uses 1.4, which seems to have this bug (the same bug appears when using the Arduino IDE with lwIP 1.4).

The build flag above tells platformio to use lwIP v2.


Programming bluetooth module JY-MCU v1.06

OK, I figured it out. It looks like CoolTerm was sending wrong line endings. Thus the only command that worked was name change as it interpreted the extra symbols as part of the name specification. Now I am using in built Arduino serial communication and it works like a charm!


Eclipse Arduino Leonardo Pro Micro ATMega32U4 Programming Issue

I assume you use Eclipse Sloeber plugin for Arduino. For serial upload over USB using bootloader choose programmer Default. All other programmers are for flashing over ICSP.


for an arduino, 16Mhz / 62.5Khz = 256 -> prescaler = 1 and single sloped pwm, with its top at 255.

the number of timer modes meeting those conditions are limited.

if you move outside of arduino, a lot more of choices.


MCore(Arduino) - Python bluetooth communication

Probably because you never called bluetooth.open().

What would be much easier to do is use pySerialTransfer and SerialTransfer.h to guarantee reliable and robust serial communication between Python and your Arduino.

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs and come with examples.


Now at IDE 1.0.5, should I upgrade to 1.0.6 or 1.5.7 Beta for Pro mini and ATMega2560 use?

I have had trouble with 1.5.7 (Beta), so I would stick with 1.0.6. As for code space, you might want to look into Atmel Studio (Free), which uses a Visual Studio shell as the IDE. It blows the Arduino IDE out-of-water. Atmel is the maker of all the AT chips, so the Atmel Studio IDE is a great IDE for writing AVR code. Lots of tutorials online and there is a Arduino plug in called Visual Micro (Free also).


Why do we use bitwise operators to assign PORTx, DDRx and Pinx?

My question is why do we need to use bitwise operations to make assignements?

Because you're not assigning, you're modifying.
If you want to turn on just pin 3 (for example) you need to only control bit 3 of PORTB and leave the others alone.
That means you need to "or" the value of just bit 3 being on with the existing PORTB to turn the bit on, or AND it with the inverse (all pins on except bit 3) to turn it off.
To get the value of bit 3 you can remember that it's 4, or you can just use 1<<3 to say "Bit 3" - or use the macro PORTB3 to make it more readable instead of just the number 3.
The operation is commonly known as "Read Modify Write" and in some low-end microcontrollers you have to take special care when doing it.
For example, if you want to control the output pin 3 and currently you have pins 2, 5 and 6 on and the rest of pins 0-7 off (those are the ones on port B on the Uno) the sequence may be like:
Turn on:

Calculate bit value 1<<3    => 0b00001000
Read PORTB                  => 0b01100100
OR the two values together  => 0b01101100
Write to PORTB              <= 0b01101100

Turn off:

Calculate bit value 1<<3    => 0b00001000
Invert it                   => 0b11110111
Read PORTB                  => 0b01101100
AND the two values together => 0b01100100
Write to PORTB              <= 0b01100100


Controlling a sliding tray - beginners project

Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino?

Not at all. For example see Reprap - a 3D printer using an Atmega1280 as the controller. As it says here:

  Arduino is an open source project that has created an easy and powerful microcontroller board based on the Atmel ATmega168. It is the brain of the RepRap electronics.

If you can make a 3D printer with an Arduino, then you can make your sliding platform gadget, which sounds simpler if anything.

  Are there existing projects that basically do what I'm hoping to achieve?

Reprap, for one.

  Are there books that are considered the "bible" of Arduino development?

This is a broad question, and your original question already has a couple of "flags" that it is too broad. I suggest you narrow it down a bit.

There are a number of books about learning Arduino. My advice is to start doing some simple projects (simpler than the platform initially) to get the hang of compiling, uploading, and generally working with microcontrollers.

Also try Google and YouTube. There are a lot of Arduino projects out there.


Rc receiver giving wrong values when controlling servo

I found the problem. The problem was with the interrupts when the program was running and doing calculations at that moment the Arduino would be interrupted and stop in the middle of it, and change the value it was doing calculations with. This somehow caused the Arduino to sent interference over the signal wires. Reading the signals with a reading guard fixed the problem.

void read_inputs()
{
  noInterrupts();

  byte identifyer = 0;
  rc_shared[identifyer] = rc_raw[identifyer];

  ...

  interrupts();
}


Can we control other servos with common servo code Arduino

They work with same control signal, so the same code should work for both of them
You need make sure the ground of servo is both connected with the Arduino ground and the power supply ground (power supply ground for power supply positive, Arduino ground for the signal line)
I think SG90 worked even not connecting the Arduino ground is because the difference in design.
But you should always connect Servo ground to the Arduino ground.


ESP8266 Timing question / Do something in 2 seconds even

You can, but I think you are probably not looking at the best solution.  This link has details of how to program the "OS" timer http://www.switchdoc.com/2015/10/iot-esp8266-timer-tutorial-arduino-ide/ I haven't tried it, I'm not even sure it will work, but...

The fact that setting the timer interval to 2uS causes issues with the WIFI implies that it might not be accurate enough for your purposes.  It might be better to use "something" to trigger a HW interrupt.  From the moment the interrupt triggers to the moment the signal is sent out on the pin is a calculable finite time, so rather than 2,000,000 uS you want the event to trigger after 1,999,524uS (that's a made up number).

Of course if you are using a device that can trigger a pin on the ESP8266 there is no reason it can't trigger the 'output' pin, without involving the ESP at all.

You could use an RTC DS3221(?), the ESP sets the time on the RTC and then sets the alarm.  The alarm interrupt pin is connected to the ESP and it relays the signal to the output, or the alarm interrupt pin is directly connected to the output pin.  The limiting factor here is the accuracy you require.


Should be possible, but only if you setup the Bluetooth module of Arduino 2 as the master. You see, Bluetooth requires to connect to a master. A master can connect to 8 slaves in total. Because Arduino 2 connects to multiple devices (Arduino 1 and your Android device) it should be the master. This also means your Android device cannot connect to any other devices.

Hope this gives you a place to start exploring.


I would go for option 2.

You can wake up the controller immediately, but only the processor.

Then just start waiting for the "long enough" time that you defined, regulary checking the button state. If the button is still pushed, then initiate full wake up. If it is released, go back to sleep.

This is the easy option, requiring no extra hardware, and only a dozen of so of lines of code.

Another option, that exist and have a somewhat similar behaviour, is to have your processor wake up regulary on timer, and checking the state of the input. This is what is done for "radio controled" devices, for example (Where the "button" is a radio circuit that need to be switch on and off).
Given a sufficiently long sleep between check, on average you will get the "long enough" delay.

This option is useful when you don't have available interrupt pins, or you need something more complex that a button as the input.


you will need to implement a edge sensor. Add a previousTouchsensorState to the globals and replace the if where you check the sensor state with:

if(previousTouchsensorState == LOW && touchsensorState == HIGH) {
     // check if the touch sensor is pressed and wasn't the last time though the loop.
     // If it is, the touchsensorState is HIGH and previousTouchsensorState is LOW:
     digitalWrite(buzzer, HIGH); // buzzer will emit sound:
     timestamp = millis();       // Timing button press
}
previousTouchsensorState  = touchsensorState;


No you cannot. Arduino communicates to pc via UART so there must be a host which can send or receive the data. You have to install software on the host computer which can send and receive data to the com port to which arduino is connected to.


Uno to NodeMCU Serial Connection Problem

Arduino UNO is using pin 0 and pin 1 to have serial with USB serial Communication. You can not use them to softserial. Change softserial to other pins.  /Mikael


Can you access the EEPROM of an ATtiny with Arduino Code?

The Arduino EEPROM library is compatible with the ATTiny range of AVR microcontrollers as the library itself is built on the standard Atmel AVR avr/eeprom.h 'library' so it is compatible with all the AVR microcontrollers.

The EEPROM also doesn't take to being written or read to often as EEPROM can wear very quickly. Reading though does not cause much damage though.

Also note that using exit(0); will stop the ATTiny from doing anything else after it is called so I hope your intention is to only run the loop once, if not this would account for either not seeing anything or it only ever running the blinking cycle once.

To answer your follow up question. Yes you can run one sketch to set you values in EEPROM and then use another sketch to read those. That us usually the point of EEPROM it is a memory type that "keeps its value while there is no power".

Also you need to make sure the ATTiny is set to preserve EEPROM during upload with the ISP, this is done with the fuse settings. You need to look for a tutorial on fuse calculators for the AVRs. To set the EESAVE you need to set the High fuse to 0xD7, you can change this in the boards.txt file. Here is a fuse calculator.

If the code that is on your question at the moment is being used you won't be seeing anything as it needs the pins to be set with pinMode. That's a note for others that see this.

Next what you can do is run a basic test code which blinks the LED without anything else going on.

Basically:

void setup(){

 pinMode(0, OUTPUT);

}

void loop(){

 digitalWrite(0, HIGH);
 delay(1000);
 digitalWrite(0, LOW);
 delay(1000);

}

Below is the code you have written, it works I have it running in front of me.
I have commented it and changed a few things to make it work as intended, although the intention is not clear.

#include <EEPROM.h>

byte CLK = 0; //This is a global variable with an initial value

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

  EEPROM.write(0, 1); //set the pin to D1
  delay(5);

  //read from EEPROM address 0
  //this sets the value of the global variable CLK
  CLK = EEPROM.read(0); //place this inside a function

  //just to give an example...
  byte PIN = CLK;   //PIN variable is a local variable

  pinMode(PIN ,OUTPUT); //using that local variable

}

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

  // Note: the below if() will always be true as the value
  // of CLK is never change and shouldn't be changed as
  // it will change the pin number of the output

  if (CLK == 1) {
    for (int a = 0; a < 3; a++) {
      digitalWrite(CLK, HIGH);  //this uses the global variable
      delay(1000);
      digitalWrite(CLK, LOW);
      delay(1000);
    }
    //putting exit(0); will actually stop the program
    //remove it
//    exit(0);
  }
  else {
    for (int a = 0; a < 100; a++) {
      digitalWrite(0, HIGH);  //this has a predefined pin no.
      delay(500);
      digitalWrite(0, LOW);   //this has a predefined pin no.
      delay(500);
    }
    //putting exit(0); will actually stop the program
    //remove it
//    exit(0);
  }
}


controlling 2 sensor and 3 pump using millis

This is meant as a complement to Michel Keijzers' answer. I fully agree
with his assessment: code duplication is something to be avoided, as it
greatly hurts maintainability. And I sympathise with him feeling the
urge to implement this as a proper class. ;-)
I would argue, however, that between the simplistic version of the OP's
code, and the fully object-oriented one of that answer, there is an
intermediate step that is worth targeting as the next thing to learn. I
mean: arrays and loops.
Many cases of code duplication follow a pattern roughly like this:
// At the top of the sketch:
some_type data0 = some_value;
some_type data1 = some_other_value;
// etc.

// Within a function:
do_lots_of_stuff(data0);
do_lots_of_stuff(data1);
// etc.

where do_lots_of_stuff() may be a lot of code, rather than a single
function call (and it would indeed not be that bad if it was just a
function call).
The simple solution to this kind of code duplication is to put the
variables in an array, and process them by looping through the array:
// At the top of the sketch:
const int data_count = ...;
some_type[data_count] = {some_value, some_other_value, ...};

// Within a function:
for (int i = 0; i < data_count; i++)
    do_lots_of_stuff(data[i]);

Here is my attempt at applying this technique to the OP's code. Note
that, since there are multiple variables for each pump, we need multiple
arrays:
const int pump_count = 3;
const uint8_t pump_pins[pump_count] = {5, 6, 7};
const uint32_t pump_half_periods[pump_count] = {1000, 2500, 3200};

uint8_t pump_states[pump_count];  // LOW or HIGH
uint32_t pump_last_actuations[pump_count];  // time in ms

void setup() {
    for (int i = 0; i < pump_count; i++) {
        pinMode(pump_pins[i], OUTPUT);
    }
}

void loop() {
    unsigned long now = millis();
    for (int i = 0; i < pump_count; i++) {
        if (now - pump_last_actuations[i] >= pump_half_periods[i]) {
            pump_states[i] = (pump_states[i] == HIGH) ? LOW : HIGH;
            digitalWrite(pump_pins[i], pump_states[i]);
            pump_last_actuations[i] = now;
        }
    }
}

This removes all the duplication, and should be easier to maintain and
debug.
Once one is comfortable with this concept, I would argue the next step
in terms of building abstractions would be to bundle together all the
data relative to one pump into a struct. Then we would have a single
array (the elements of which are structs) instead of a collection of
arrays:
// Data structure describing a pump.
struct Pump {
    const uint8_t pin;
    const uint32_t half_period;  // half period in ms
    uint8_t state;               // LOW or HIGH
    uint32_t last_actuation;     // time in ms
};

const int pump_count = 3;

Pump pumps[pump_count] = {
// pin, half-T, state, last_actuation
    {5, 1000, LOW, 0},
    {6, 2500, LOW, 0},
    {7, 3200, LOW, 0}
};

The body of setup() and loop() would be very similar to the previous
version, but with pump_pins[i] replaced by pumps[i].pin and so on.
The third step in the abstraction ladder would be to embed the code that
handles the data structure with the data itself in a class, as shown
in Michel Keijzers' answer. With the proper methods defined, the main
sketch could be reduced to something like this:
#include "Pump.h"

Pump pumps[] = {
    Pump(5, 1000),
    Pump(6, 2500),
    Pump(7, 3200)
};

void setup() {
    for (Pump &pump : pumps)
        pump.begin();
}

void loop() {
    for (Pump &pump : pumps)
        pump.process();
}

I tried all these methods, and it turns out the first one (with a
collection of arrays) is the one that uses the least lines of code, and
the last one (with a class) uses the most. One could wonder then why use
more advanced abstractions, if they increase the amount of code one has
to type. The reason is, these abstractions become useful when the
program grows in complexity. On can put together all the code that deals
with the pumps in one place (maybe in a separate file), all the code
that deals with sensors in another place... and the main sketch that
puts all the pieces together remains simple.


The ModbusIP library expects from you that you supply the value of the register. The AirSensor library gives you that value.

Set the register value to Hreg:

mb.Hreg(SENSOR_ISTS, airSensor.getTemperature());

I tested your sketch without the sensor library and it is working. Client was my java test client I use to test access to Modbus TCP registers of my photovoltaic system.

Make sure that the client calls "0x03 - Read Holding Registers" and test address 100 and 101 because some modbus clients offsets are 1-based.


How to int variables with similar names without tons of code?

The word you are looking for is array.

An array is like a list of values all of the same type.  For instance, your LED pins could be specified as:

int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

You can then access the LEDs by number.  Note that arrays start counting from zero not from one, so you would have:

leds[0]
leds[1]
leds[2]
... etc to ...
leds[12]
leds[13]

It's great for using them in an array:

for (int i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

If the values are never going to change, as in this case since they are pin numbers, the array should be declared const so it doesn't take up any of your precious RAM:

const int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

Also you should get into the habit of tailoring the data types to the expected values.  If the values are never going to exceed 255 then you should use "byte" not "int", or better still the C standard "uint8_t".

const uint8_t leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

for (uint8_t i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

An int takes two bytes, so using int when you can get away with uint8_t means you're wasting half the memory.


Question on pin management using PCA9534PW IO Extender

You set the pin mode by setting the configuration register.

Wire.beginTransmission(0x20);
Wire.write(0x03);                   // Configuration Register
Wire.write(0xfe);                   // IO7-IO1 Input, IO0 Output
Wire.endTransmission();

Then write the output port register with HIGH and LOW.

Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x01);                   // IO0 HIGH
Wire.endTransmission();
delay(500);
Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x00);                   // IO0 LOW
Wire.endTransmission();

But using a library is much easier. See, for instance, https://github.com/alotaiba/PCA9534.


Controlling an MCP41HV31 Digital Potentiometer

I realize that this thread is old. I am providing an answer for anyone else who may end up here like I did a while back looking to solve this.
I have created an Arduino library on Github (https://github.com/gregsrabian/MCP41HVX1) which allows for control of this family of chips. The README.md within the github project documents all of the APIs and also provides the wiring diagram. There are also example sketches included.
I have created an article on Instructables (https://www.instructables.com/id/MCP41HVX1-Digital-Potentiometer-for-Arduino/) that provides a step by step on how to control this family of chips. There is also an explanation on how to solder the TSSOP chip.


Looks like same problem as described in https://forum.arduino.cc/index.php?topic=483636.0
Solution described in that thread:
Add

LowPower.attachInterruptWakeup(RTC_ALARM_WAKEUP, alarmEvent0, CHANGE);

to setup() and create a dummy function

void alarmEvent0() {
}


How to show the distance in decimal use sensor TF-Luna Lidar or more specific value

so if i inputting the duration of the light travel from trigger to echo, i can find the distance?. will it work?

That's the basic working principle, but you cannot do that with an Arduino. Light is too fast, resulting in incredibly small travel times. You need specialized hardware for that. And thats, what a Lidar sensor (or other Time Of Flight sensor) are.

The TF-Lunar Lidar sensor supports different output formats. The distance in cm is just the default. There is also the format, that you showed in your question (9 byte mm), which gives you the distance in mm. The manual of the TF-Lunar also explains how to change the used output format (look at page 22: "5.Output format setting ID_OUTPUT_FORMAT=0x05"). How exactly this is done depends on your actual code and the used communication interface (Serial or I2C).


Arduino UNO + CC3000 Wifi Shield, Reading webpage data

Webpages usually return data in text format with new line characters at the end.
In case of 55 you would get "55\r\n" or [53, 53, 13, 10] in bytes.
You need to parse the characters, like Serial.parseInt() does.

You are also only sending every second byte back to the serial monitor and only saving the last byte from the other every second byte.
After you read a byte with Serial.read() you can't read the same byte again, you get the next one.
In case of 55 you would send back "5\r" to the serial monitor and only store "\n" or 10 into dollars.
In case of 0 you would send back "0\n" to the serial monitor and store some unknown value into dollars, because you read more bytes that was sent.


Error: "invalid use of incomplete type" and "forward declaration"

Try to change

class TFT;

to

#include <TFT.h>

Then you can remove the #include <TFT.h> from the main arduino sketch.

Moreover you should at least write a piece of code to make the compiler include your library just once; this is the usual way to do it:

#ifndef _MESMENU_H_
#define _MESMENU_H_

#include <SPI.h>

...
the rest of your library
...

  TFT* _TFTscreen;
}

#endif

_MESMENU_H_ is any unique string (usually the filename is used, remembering that you can't put spaces or other punctuation marks except the underscore). And you should put it only in the header file (*.h or .hpp), not in the source (.c or *.cpp or *.ino)

EDIT:

The additional info lead me to analyze the library and.. there are problems with the library. Particularly the file TFT/src/utility/Adafruit_GFX.h has a big problem: it has the code for the functions.

To fix it, you have to modify the library.

Go into the folder TFT/src/utility/ and make a copy of Adafruit_GFX.h, calling it PImage.cpp.

Open Adafruit_GFX.h and delete everything between line 227 and line 370. This means that from

bool useFill;
};

#if defined(__SD_H__)  // Arduino SD library

#define BUFFPIXEL 20

void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) {

...

  return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
}

#endif

#endif // _ADAFRUIT_GFX_H

it should become

bool useFill;
};

#endif // _ADAFRUIT_GFX_H

Having done this, open PImage.cpp and delete everything above line 227, then delete the function Adafruit_GFX::image and the last endif and add, at the beginning, #include Adafruit_GFX.h. This means that the file should look like

#include "Adafruit_GFX.h"

#if defined(__SD_H__)  // Arduino SD library

#define BUFFPIXEL 20

// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.

uint16_t PImage::read16(File f) {

...

  return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
}

#endif

Then try to compile again the program

BTW: the source I looked at is at this page.


How to receive commands to a running arduino program from a raspberry pi?

What you are asking for is not completely trivial, and may be ill-suited
for a beginner's project. You will have to create a protocol for the
communication between the Raspberry Pi and the Arduino (your own
“command language” of sorts), and then implement on the Arduino a
command interpreter that understands this protocol and acts accordingly.
I highly recommend you use a text-based protocol, as this will be way
easier to debug than a binary protocol.
For the Arduino side of the project, you first have to learn how to
read the serial port from the Arduino. Then, you can take a
look at this very basic command line interpreter for
inspiration. Or you can search for Arduino libraries that provide
similar interpreters.
On the Python side, you have to open the serial port (/dev/ttyACM0)
and send your commands through it. The details on how to do that
would be a Python question, which is are out of scope here.


USB Communication like serial RS232 with an Attiny

Generally there are (or could be many) USB Devices and (only one controlling) USB Host.  The differences are discussed in this stackexchange.com question. Briefly, USB Hosts are usually very complex hardware and software devices that may know about many many different types of peripherals.  They are usually only found on computers.  USB Devices are usually dedicated peripherals.  They only need to know about them selves.  Many people do not realize that there are many protocols built into USB.  These are normally called Device Classes.  The USB Serial Protocol (or CDC) is one of dozens of Device Classes.

So, assuming you want a build a Serial Port USD Device, you would first need a processor with built in USB Device hardware.  (There are likely some project out in the wild that have implemented this feature using software. It might be a good experience.  But for practical purposes it is usually better to use hardware for this.)  The next feature you need to implement is a software USB Device driver.  This is not trivial.  But is much simpler than the USB Host software.  The next feature you need to implement the serial protocol inside the USB protocol.

In the real world, the USB code, even for a USB Device, is complex enough that most developers use the USB code provided by the processor manufacturer.  This is very common as most manufacturers want you to use their hardware and provide the USB code for free. Here is Atmel's support page for CDC USB (serial port) support. (Of course, Atmel makes the processor found in most Arduino boards.)

Thus far this answer has been general and is likely difficult to implement in a practical sense.  A more turn key solution is to use an existing platform which contains a USB CDC Device. The Arduino Uno comes in several versions.  One has a USB CDC chip made by FTDI.  Another has a 2nd processor programmed specifically to handle USB CDC type communications. Either version provides a USB CDC interface used for programming.  I believe this web page explains how you can also use this port to communicate with your sketch.


PWM fans causing temp sensor erroneus values (interference?)

In case anyone has the same problem, I solved it. Turns out is was a bad PSU. Buying a new, higher quality one made everything work. So the issue was high ripple I suspect, or at least high enough when applying some load (which is why I noticed that things got worse after the fans started spinning at greater than 20% duty cycle) for the temperature sensor to flip out.