You have to use a relay that can handle minimum 415 volts (and keep some reserve).

Also take the current/amperage into account (possibly use multiple relays).


The Arduino core configures Timer 0 for a period of 1,024 µs. Your
ISR will then be called at very regular intervals, and is a good place
to have timing-related code. You just have to keep in mind that the unit
of time is not one millisecond, but 1.024 ms.

If this “weird” unit bothers you, then you could do what the Arduino
timing ISR does: keep track of how late, relative to a 1 ms
period, you are getting. When you notice you are 1 ms late, count
one extra millisecond.


Some questions about a RGB LED Strip project that Im planning to do

You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLed library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".


How to prevent interference between dc motor and arduino?

There are two basic things you need to do:

Use proper pullup resistors on your I2C lines (2.2kΩ) instead of relying on the (terrible) internal pullups of the ATMega
Add capacitors to the motors.

For point 2 you need two or three small ceramic capacitors (10nF to 100nF) per motor.

Connect one from each terminal to the motor's body
Optionally connect a third between the two terminals of the motor

This will reduce the EMI produced by the motor, and the improved pullups should reject EMI easier.

(Even if this doesn't entirely fix your underlying issue, it's certainly something that you should do regardless.)


Had the wrong version. Correct version downloaded from the current master: github.com/JChristensen/Timer


Arduino - "expected primary-expression before '.' token" Error

Ultrasonic is a class name. Why are you trying to use it before a . in an expression?

Judging by the declaration, you need ultrasonic. That is your object name. ultrasonic, not Ultrasonic.


Error Compiling for board Arduino Nano while using Adafruit GFX

Currently, you defined a forward declaration for drawLine, however I assume you want to call the method (function) inside display.
So change
drawLine(20,60,5,50,256);

into
display.drawLine(20,60,5,50,256);

And you can remove the forward declaration, because this method is already defined in the library.
void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color);

Note, if you call drawLine without an instance (which is display), then the linker tries to find the drawLine function which it cannot find, so you get a linker error (see ld returned in your error, together with undefined reference).


Arduino changing output based on wire voltage

Maybe a wire coil wound around the wire could pick up the frequency. Though I won't write about this, since I don't know much about how you would measure this, and because I think, that you are looking the wrong way.
You want to switch one device with multiple switches (how these switches are operates is not important for now). You can look at how this is normally done in eletrical installations. Here the switches are all connected to your breaker box. And there is one component, that waits for trigger signals from the switches and will switch the target device (the light in this case) accordingly. So in the end there is only one place, where the light is switched: in the breaker box. The switches in the room are only triggers. The current for the light does not flow through them. Also they don't necessarily need to carry mains voltage (triggers could also be low voltage) (though it seems they are in fact just using mains voltage, for which I don't know the reason. Maybe to avoid additional voltage conversion).
So I propose the following solution: The mains wires (230V) are only connected to the light and a (suitable) relay board. The relay board is connected to the Arduino, which can act as a Smart Switch (switching via WiFi, time based or whatever). For manual switching you can connect a switch or button to the Arduino and program the Arduino to read it and control the relay accordingly.
This solution is way easier, than trying to sense the live voltage on the lines, and this will most likely make it more reliable . It comes down to controlling an relay board and reading a button/switch, both things with tons of tutorials on the web
Note: Since mains voltage is always really dangerous, you should be really really caution. Don't use mains voltage, when developing your device. A simple LED with current limiting resistir connected to the power line of the Arduino through the relay is sufficient to check the complete functionality. Only connect mains voltage, if you are really really sure, that you did everything correct


Almost all of those things you do which involve functions like print, println, and write all derive from the Print class.  You could have an array of Print objects and print to whichever you like.

Print* outs[] = {&Serial, &Serial1, &mySoftSerial};

//  Later somewhere in code:

outs[0]->println("This prints to Serial");
outs[1]->println("This prints to Serial1");
outs[2]->println("This prints to mySoftSerial");

for(int i = 0; i < 3; i++){
  outs[i]->println("This prints to all 3.  You could even make this bit a function");
}


You could put your switch/case inside an infinite loop, and return from
the Menu() function when the user presses '3'. E.g.:

void Menu() {
    Serial.println(menu_banner);
    for (;;) {
        switch (Serial.read()) {
            case '1': ldrConfig(); break;
            case '2': srvConfig(); break;
            case '3': return;
            default: continue;  // includes the case 'no input'
        }
    }
}


Step 2 solves this problem:

https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/arduino-bsp-setup

Also, read up about how to add something to Path Variable on Windows.


Arduino Uno vs Arduino MKR1000 analogRead discrepancies

The Adruino Uno is running off 5V, while the MKR1000 is 3.3V.  This means you need a bit more on-time to get the same power output.


How is the integration time set for a camera?

It is quite a difficult system to get your head around, as you have noticed.  I'll try and break it down more logically for you...

An important thing to note is that there are two capacitors in each pixel - the integrating capacitor and the sampling capacitor. It's these two capacitors that lead to a certain amount of confusion, and it's vital to understand the role of each one.

Under normal sampling operation light falling on the photodiode of a pixel generates charge through the internal amplifier which is stored in the integrating capacitor. Simultaneously that stored voltage level is mirrored in the sampling capacitor.

When you send the pulse on SI a signal called HOLD is generated internally. This signal is sent to all of the pixels and tells them to disconnect their sampling capacitors. They do that through the switch S2.  At the same time the integrating capacitor is emptied by S1 causing a short circuit across it. That is held there for 18 clock cycles to make sure that it's completely empty. All this time the sampled voltage is still there in the sampling capacitor.

Then as you continue clocking the pulse you sent in through the SI pin is walked down a 128 bit shift register. As it pops out of each output in turn it connects the sampling capacitor of that pixel to the output buffer so you can read the voltage. It's then flushed out and re-connected to the integrating circuit again to sample the pixel again.

So there is actually multiple things happening during your 129 clocks. Reading and integrating are both happening at the same time. But you're not reading this set of clock's integration, but the last set of clocks integration.

So you have:

SI pulse - HOLD generated, samples frozen
18 clocks of clearing the integrators and reading nothing much.
110 clocks of reading nothing much (nothing is sampled yet) and integrating.
1 clock to terminate
SI pulse - HOLD generated, samples frozen
10 clocks of clearing the integrators and reading the previously integrated samples 1-18
110 clocks of reading the previously integrated samples 19-128 and integrating new ones
1 clock to terminate
... etc ...

So clocks 130 to 258 are reading the light that was sampled during clocks 19 to 128.

The upshot of all this is that your integrating period is the total time taken for the 110 clocks that occur between the end of the 18 clocks that clear the integrators and the next SI pulse that creates a new HOLD signal.


Relay module and internal pull-up resistors

Connecting one side of a switch to ground and the other side to an input pin (with its pinmode set to INPUT_PULLUP) is a standard way of connecting control switches to an Arduino installation, and is not a problem.

Note, claims that built-in pull-ups are 20KΩ oversimplifies the situation.  See, for example, Table 28.2, DC Characteristics, in the ATmega48PA/88PA/168PA/328P specs, which shows a min value of 20KΩ for   I/O Pin Pull-up Resistors and a max value of 50KΩ.  I've measured resistances of about 40KΩ, IIRC, whenever I've measured the pull-up values.

Note, built-in pull-ups typically are of too much resistance to work as pull-ups for TWI/SPI/I2C communications.

Note, when you say in the question that you connected the relay-modules to input pins and they worked ok, I suppose that could be the case, but in general it is better to put i/o pins into output mode when you want to drive an output.  When you send LOW to an input pin, its built-in pull-up is turned off, the input impedance becomes high, and then the pin can float to any value between ground and Vcc. It might fail to turn off an attached device if that device also has high impedance.


ESP8266 - How to know if incoming connection is from AP or station network?

I don't think the default AT firmware allows to automatically reject packets because that would probably require a higher degree of control, but looking at the Expressif documentation about the AT command set I've discovered you can actually retrieve the remote address rather than the local one, just by using the same command you were using but with a different parameter

AT+CIPDINFO=1

Not sure though this actually might solve your problem.


Here:
alarm1Time = (t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);

you are repeatedly using the comma operator, which essentially means
“discard all the values but the last one”. If you want to invoke the
DateTime constructor that takes these arguments, you should call it
explicitly:
alarm1Time = DateTime(t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);

or, better yet, you can declare and initialize alarm1Time at the same
time:
DateTime alarm1Time(t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);


How important is the INT pin of the MPU6050 (GY-521)?

The INT is the interrupt signal, usually open-drain output and you can connect many of them to the single MCU interrupt line (but you have to check all devices which ones are ready). The LOW level from MPU device signalize that data are ready (conversion was finished). So you don't have to periodically read status register to find it out (no polling is necessary).

In short, using INT is optional.


Valid options for output port on Mega 2560

It would seem this library needs a single pin to communicate. So it
doesn't really matter whether the port you choose has only a few pins
available. Also, you do not care that some pins can have extra
functionality, like SPI, I2C, etc, unless you do plan to use that
functionality.
There is one think you should be aware of: the library uses the in and
out assembly instructions to access the port. These instructions can
only access the ports that are mapped in the regular I/O space of the
microcontroller, not those that are in the “extended I/O” space. In the
case of the ATmega2560, this means you can use any of the ports A
through G, but you cannot use H, J, K nor L.


Can't read PWM signal from 2-pin fan header

Your picture shows that you have only connected one line to the Arduino.  You do not have a common ground between the Arduino and the fan controller.  You need to connect the grounds together.
Voltage is like height, it requires two points to measure.  If I point at a hill and I say, "How high is that hill?" that seems like a pretty easy question to answer at first.  But it becomes ambiguous quickly.  Do we want to say how high it is compared to the ground around it?  Or how high from sea level?  Or how high from where we are standing?  You simply can't say how high a hill is unless you agree on where to measure from.
It's the same with voltage.  You can't measure a voltage unless you have a potential that you can consider the 0 point to measure from.  That 0 point is the ground wire.  And as you have drawn the circuit the two boards don't agree on where they will consider 0 volts.


Testing ID and Serial Communication (Update)

You are assigning a string to a single character here.

  char myID = 'tg123';

Instead you should make it a String variable. And compare it after all the characters are recieved.

  String myID = "tg123";

And Here is the modified code you should test with. In this case I have assumed you simply write the ID (string) in serial terminal and hit enter.

N.B. If you want to enter each character one by one, then it will not be able to catch the whole string. For this case you have to add some time-out to wait for next character to arrive.

String recvData = "";
void loop()
{
  while (!Serial.available());
  while (Serial.available())
  {
    char ch = Serial.read();
    recvData += ch;
  }
  if (myID == recvData)
  {
    digitalWrite(gLED, HIGH);
    digitalWrite(rLED, LOW);
    Serial.println("Hello! Your name is Trevor.");
    delay(5000);
  }
  else
  {
    digitalWrite(rLED, HIGH);
    digitalWrite(gLED, LOW);
    Serial.println("Invalid ID! Try again.");
    delay(2000);
  }
  recvData = "";
 }


WDT ISR not called when SPI ST7789 module initiated

You can't use the LED on pin 13 on Uno, Nano or Nano Every, if you use SPI . It is the clock pin of the SPI.
The init function of the display initializes SPI which dedicates the pin to SPI peripheral and disconnects it from pin IO peripheral.


Arduino Uno synthesizer - Line Level (audio) output to mixer/amplifier

In theory, the peak signal accepted from your amplifier should be 0.894V p2p if you want to rescpect the common -10dB signal strength/level. I don't know why you would want to have a 5V to 2.5V "voltage divider" in the first place, but in any case if you use that you already limit the current probably enough, it all depends on the resistor values used.

Using the LM386 amplifier is also simply not required at all, since the Arduino is already providing more than enough power. If you want to tune the volume at that stage, simply combine all functions (volume, low pass and current limit) by connecting the 5V PWM output thru a resistor (eg. 4k7) to a POT (eg. 1k) in parallel with the capacitor (eg.2n2) would give you approximately what you want. Then to remove de DC component, add a series capacitor (eg. 1uF) and you're all set. You may still hear a "click" when you connect it to the amplifier though, so keep the faders low when connecting.

Of course you can adapt the values quite liberally, but these values are both safe and should be close to what is needed (cutoff 15kHz, Vpp 0.88V max).


You can buy a camera module for the Arduino, and you can interface it fairly simply.  There are numerous modules around - ask Google, it knows more than me.

But I have yet to work out why people do it.  All you can do with an Uno is to pass the data through to something else like a PC to process the image - so why wouldn't you just use a simple webcam?

The Arduino UNO has 2KB of RAM.  A 24-bit 640x480 image (VGA) requires (640*480*3)/1024 = 900KB to store it in memory.  If you really wanted to process an image on an Uno then you would be limited to (say 8-bit grayscale) 48x32 pixels (1.5KB) which is pretty pointless really.

Even a Due would only allow (again grayscale) around 320x240 (which is better) but nothing colour unless you want to start messing with CLUTs which aren't fun when receiving a truecolour (24-bit) image from a camera.

For this kind of task you are better off with an embedded computer with plenty of RAM such as a Raspberry Pi or maybe a Galileo or something.


What can I do if I run out of Flash memory or SRAM?

Optimisation
Low-level programming for embedded systems is quite different from programming for general purpose devices, such as computers and cell phones. Efficiency (in terms of speed and space) is far more important because resources are at a premium. That means the very first thing to do if you run out of space is to look at what parts of your code you can optimise.

In terms of reducing program space (Flash) usage, the code size can be quite difficult to optimise if you're inexperienced, or if you're more used to programming for desktop computers which don't tend to need that skill. Unfortunately, there's no 'magic bullet' approach which will work for all situations, although it helps if you consider seriously what your sketch really needs to have. If a feature isn't needed, take it out.

Sometimes it's also helpful to identify where multiple parts of your code are the same (or very similar). You may be able to condense them into reusable functions which can be called from multiple places. However, be aware that sometimes trying to make code too reusable actually ends up making it more verbose. It's a tricky balance to strike that tends to come with practice. Spending some time looking at how code changes affect the compiler output can help.

Runtime data (SRAM) optimisation tends to be a bit easier when you're used to it. A very common pitfall for beginner programmers is using too much global data. Anything declared at global scope will exist for the entire lifetime of the sketch, and that isn't always necessary. If a variable is only used inside one function, and it doesn't need to persist between calls, then make it a local variable. If a value needs to be shared between functions, consider if you can pass it as a parameter instead of making it global. That way you'll only use SRAM for those variables when you actually need it.

Another killer for SRAM usage is text processing (e.g. using the String class). Generally speaking, you should avoid doing String operations if possible. They are massive memory hogs. For example, if you're outputting lots of text to serial, use multiple calls to Serial.print() instead of using string concatenation. Also try to reduce the number of string literals in your code if possible.

Avoid recursion if possible as well. Each time a recursive call is made, it takes the stack a level deeper. Refactor your recursive functions to be iterative instead.

Use EEPROM
EEPROM is used for long-term storage of things that only change occasionally. If you need to use large lists or look-up tables of fixed data, then consider storing it in EEPROM in advance, and only pulling out what you need when necessary.

Obviously EEPROM is quite limited in size and speed though, and has a limited number of write cycles. It's not a great solution to data limitations, but it might be enough to ease the burden on Flash or SRAM. It's also quite possible to interface with similar external storage, such as an SD card.

Expansion
If you've exhausted all other options, then expansion may be a possibility. Unfortunately, expanding Flash memory to increase program space isn't possible. However, it is possible to expand SRAM. This means you may be able to refactor your sketch to reduce code size at the expense of increasing data size.

Getting more SRAM is actually fairly straightforward. One option is to use one or more 23K256 chips. They are accessed via SPI, and there is the SpiRAM library to help you use them. Just beware that they operate at 3.3V not 5V!

If you're using the Mega, you could alternatively get SRAM expansion shields from Lagrangian Point or Rugged Circuits.


Is there some hardware that can be used to upload sketch source code via USB flash disk (Automatically By plugging it in)

There is a solution with SD card and SD bootloader. You put a bin file on SD card, insert it into the SD adapter and power up the Arduino. The bootloader loads the bin file to flash memory.

I use 'avr_boot' SD bootloader by Zevero. It reads a file named firmware.bin from SD card if present and loads it into flash.

To generate a bin file for Arduino AVR boards add to platform.txt

recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2hex.cmd}" -O binary {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin"

I use this with the ArduinoOTA library which uploads the bin file from IDE to the SD card over network and then resets the MCU for the bootloader to apply the bin.

btw: the ArduinoOTA library can use the upper half of the flash memory too to store the uploaded bin and then activate a modified Optiboot to copy the bin to run location and reset the MCU.


How to fix when i shorted 5v to gnd accidentally (Arduino Nano)

I would say that to repair an Arduino Nano clone yourself, if ICs/SMD parts are damaged, is not worth the effort, if you could do it at all (first having to find out which parts need to be replaced, carefully de-soldering the delicate SMD parts, then putting new parts in place, etc.).


I want to create 10 levels with one button but this code shows only level 1?

You forgot to ask a question. So I will assume the intended question is
“Why does this code always show level 1?” and I will try to answer that.
The variable level is defined here:
int level = 1;

Its initial value is 1. Then it is updated here:
if (level >= 10) {
  level++;
} else {
  level = 1;
}

The first time this section of code runs, level has its initial value,
namely 1. The condition in the if evaluates to false, then the
statement
level = 1;

is executed, which assigns the value 1 to level (which has no effect,
as that was already its value anyway).
The next time that section of code runs, level has still the vale 1,
and the effect is the same as the previous time.


Pointer to Hardware Differences Documentation For Arduino Boards?

You may find this helpful: PTD0001 Arduino Comparison Rev 0 - PDF - 245 KB.

Screenshot of above:

Credit: Payne Technologies Limited

That compares some models in a way you might find useful.

  I have found that the hardware PWM isn't always the same from one Arduino Board design to another

The PWM frequencies can be changed over quite a wide range. I have a page about timers which describes a lot of their features.

According to the Arduino reference page about analogWrite:

  The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.

By changing the hardware register you can change those frequencies. The frequency of 980 Hz is because of the compromise needed to get an approximate 1 ms interrupt for use by the millis() function:

16e6 / 64 / 256 = 976.5625 Hz

In other words the clock speed of 16 MHz is prescaled by 64 and then counted to 256, giving that frequency.

Note that this is almost 1 ms. The code behind millis() and micros() functions compensates for that so that you get a reasonably accurate result.

By changing the prescaler, and "count to" point you can get lots of other frequencies. However if you do that to Timer 0 on the Uno (and similar boards) then you will throw out the calculations for the millis() and micros() functions (you can compensate for that, of course).

This only partly answers your question, but hopefully will provide a nudge in a useful direction.


Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.

Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.

PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.

Edit: Use this code to connect to ESP8266:

#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  ESP8266.println("AT");
  delay(30);
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy.


An ESC is an Electronic Speed Controller. It's purpose is to control the speed and direction of a Brushless DC Motor.

A Bushless DC Motor ("BLDM") is not like other motors. You can't just provide it power and it will spin. Instead it is made up of three (or multiples of three) electromagnets along with a permanent magnet on the rotor. Energising these electromagnets in the right order at the right time (and the right amount, too) pulls the permanent magnet around in a circle, making the motor spin.

It's the ESC that has the job of controlling these electromagnets.

You provide a PWM signal as a digital speed indication. The ESC then interprets that as an indication of how fast you want the motor to turn, and excites the electromagnets in the right way to make that happen.

Oh, and no, you certainly never want to provide a PWM signal to a relay. A PWM signal switches hundreds, if not thousands, of times per second. A relay is capable of switching, at best, maybe 10 or 20 times per second.  Relays don't drive motors. Motor drivers (or at the bare minimum, MOSFETs) drive motors.


It is very simple, and you don't need any code to work it out.

SoftwareSerial is completely synchronous (i.e., blocking) when writing.  That means that the amount of time taken to peform the write is the time taken to send the data on the line plus a small function call overhead.

That means the time taken is:

1 / baud * 10 seconds

So at 9600 baud one bit is sent in 1/9600 of a second, and there are 10 bits (1 start, 8 data, and 1 stop bit), so it takes 1/960th of a second.

That's about 1ms per byte, plus a few extra clock cycles for calling the actual functions.

To put it in more detail, when you send a byte this happens:

Set the line level to the start bit level
Wait 1/9600th of a second
Set the line level to the first data bit level
Wait 1/9600th of a second
Repeat 3&4 for the rest of the data bits
Set the line level to the stop bit level
Wait 1/9600th of a second
Set the line level to the idle level

So you have 10 "wait 1/9600th of a second" in total, or a total time of 1/960th of a second.

The same can be said of receiving data. When the start bit arrives it triggers a pin change interrupt.  A synchronous blocking interrupt routine then executes that does the same as above but with reading instead of writing. So that takes about 1ms to execute at 9600 baud - plus some extra to insert the incoming byte into a circular buffer, which you then read from in your sketch.

So the round-trip time of a single byte from unit A to unit B then from unit B to unit A can be estimated as:

1/960 + 1/960 + overheads

That means the minimum time will be 1/480 seconds plus whatever time is spent at the remote unit processing the byte to send data back to you, and a little bit for the function call overheads.

Incidentally, it's that last operation in the interrupt, the "adding the byte to a circular buffer" that means you can't reliably receive at 115200 baud with SoftwareSerial. That takes more time to process than the typical gap between bytes (could be zero - just the width of the stop bit...) that the next byte could have already started to arrive at the GPIO pin before the Arduino is capable of triggering the ISR again, so it misses the start bit.


Splitting DOUBLE in byte for save on EEPROM

how suggest in the comments, and on Arduino reference DOUBLE website

only on arduino 2 float it's 8 byte.


Communication between two Bluetooth modules of two Arduinos

I'm not sure how many bluetooth devices can be connected to your smartphone. But if you use smartphone, the you can eliminate the master Arduino. But as I said, it still depends on the number of devices you'd like to control. This is supposed to go in the comment section.


Will writing to serial when no serial is available cause problems?

No, that will not cause any problem.

What might hurt you is the fact that if you want to leave your Arduino in low power mode, but keep the serial potr disconnected and the serial port is a wakeup source, it might pick up sporadic (but frequent enough to cause be noticeable) noise that will trigger wakeups and spam with meaningless data your RX.

This, however, is not specific to the serial port, but it can happen to any wake up source that is enabled and left dangling.


Simulink just supplies code for all the things you could be up to, triggered by a serial command of yours. This is very slow and I think it's obvious, that you would want a fast and slim realization of everything possible, if you attempt to do HIL.

If there is a special part you think is only easy for you with blocks, just ask right away, but it is really easy to do everything you can wish for in a few simple lines.
Also this is better for you, because you really know, what's going on.

I could provide some detail code, since I'm doing HIL myself atm, but you would need to specify a bit, what you are up to.

To really answer your question: I don't know of any other visual programming tool for arduino and as stated above, my best knowledge is, that simulink uses pretty messy things. And loads them onto the board right away, right?


Why does using ESP8266 in deep sleep mode still drain the battery quickly?

The example shows a Sparkfun Thing, which the article notes doesn't have extra peripherals. What you show is something different, like a NodeMCU dev board, which typically has a linear regulator, possibly a power LED (which the article notes can be removed).

I see you're using a DHT11 or DHT22, which has a pull-up resistor. The pull-up resistor is constantly using power. Instead of connecting the pull-up to the power rail, you can connect it to a GPIO pin and pull that pin LOW before you go into sleep, which effectively disables the sensor and stops it from drawing power just to keep the data line high.

Safe to say that somewhere there is something drawing power -- have you measured the actual current draw in deep-sleep, or are you only noting that your batteries run low sooner than expected?


3.3 V Arduino Pro Mini and nRF24L01 issues

voltage = 3.97 V 0 RSLT (1 = success) 0 Data Sent 3.00 0.00

nrf24l01 is a 3.3V device, Where'd that come from?


If your car is moving at the time, then relative to your car everything is moving.

Automotive companies have spent billions of dollars working on this problem.  There is no "sensor" that can differentiate one moving object from a background that is also moving.

All existing automotive systems that perform this task use cameras and computers, with software such as OpenCV.  This is not something that any Arduino could even come close to doing.

The closest you could get is "is there something in this area that is within a certain distance of me" which you may be able to do with an ultrasound "Ping" sensor.  It won't differentiate between a moving car or a bollard or a child or just the wall you are reversing towards.


Analog pins as output by using digitalWrite

My code was quite messy, it appears that some other functions prevented from using pins A4 or A5. It is working now.
    It was the DS1307Emulator library. After initialization I had to use DS1307Emulator.busDisconnect();
    Didn't know it uses I2C.


Broadcast data to radius of at least 500 meters

Maybe you can look into the LoPy Microcontroller, a MicroPython enabled controller, that has a 1km WiFi range. It uses the Espressif ESP32 chipset (with 802.1b/g/n 16mbps WiFi) and has Bluetooth (BLE & Classic) integrated into the board.

(Reference: https://www.pycom.io/product/lopy/)


How can I drive this LCD TFT with an Arduino?

From what I'm seeing, the touch screen and card reader use SPI but the LCD uses a bunch of Digital I/O lines. The link in Gerben's comment includes a library for the LCD that might be what you're looking for. I hope you're using a ATMega board as it doesn't look like an Uno or similar board will have enough I/O for the LCD.


Solution to interrupt Arduino every n seconds

So, since you're coming from the application domain there are some things you might want to consider:

Make sure to always stay inside the super loop. With an Arduino or any other Microcontroller (not using a RTOS) you do not have anything defined that's going to happen after the superloop. Everything that happens after this loop is basically undefined (it typically is a reboot or jump to a default interrupt handler but may also be a lockup). Simply telling the processor to "exit" will .. well, exit - but you have no idea where it's going after that. To allow for interrupts and further execution of your main code, you need to have your processor in a defined state (and that basically is the super-loop). as a comparison with your PC, after you exit a thread, the operating system will take over. On your Arduino there is no such concept. The super-loop IS your OS (well, at least it's some minimum implementation of a non-preemptive scheduler).
If you want to have only interrupt actions active while the processor is using only little power, you will need to use the processors sleep modes. These are modes, where special functionality is disabled but which keeps the processor alive or in some idle mode where it's actually just waiting. Whilst the Arduino may have various sleep modes, none of them are what can be achieved with other architectures, such as the MSP430 platform or some SAMxL platform. Those are dedicated as low power processor and provide the necessary deep sleep modes.
When using a deep sleep mode, it depends on the actual sleep mode which interrupts can wake the processor. Typically for the deepest sleep modes, only few interrupt sources will actually wake the processor up as all other peripherals are inactive either because their clock was gated or power was turned off for that function block.
You will always have some power drain for the processor but keep in mind that it's not only the processor which will require power. At some point, you have leakage currents through your capacitors/resistors and other ICs on your board which require power as well. When you're talking about "years", you will also need to account for the battery discharge as well. No battery is perfect.
Jack Ganssle is probably well known for his insight into anything related embedded, but he explicitly wrote some articles for ultra-low-power systems. You must read those if you want to start somewhere. While having the software side covered using low power techniques you will also need to tackle the hardware side, yet as I said - the Arduino wasn't made for such tasks even if it provides some basic sleep modes.


L298 Motor Driver not showing Red light when connecting power supply

You need to do math on the power consumption as arduino uno takes takes 5 V 500 mA at least for it to work. That is why it can be powered by USB cables too.
Now if you try calculating power consumption on the motors you would understand that the power you are giving is nowhere enough for the arrangement to work or you could have been able to run the motors without the motor driver.
Try upgrading the power you are giving.


Yes, it is possible for the arduino handle communicating over serial and I2C in real time, I've done it frequently. The IR sensor should not pose a problem either.

The ultrasonic sensor might use a timed pulse to send its information that can take a relatively long time, and the basic ultrasound code will just wait for it to finish without doing anything else. The delay itself will not cause you problems but if a lot of data is being sent to the arduino very quickly over serial it might miss some. These delays can be worked around with interrupts/some clever coding but I doubt it will ever be a problem.


If value in serial begin is greater than that of delay in arduino, does delay time matters?

The parameter to Serial.begin(speed) is the BAUD rate, or the speed characters are read (and written) from (to) the serial line.  The parameter in delay(time) is the number is milliseconds that the system will wait for.

I think what you may have noticed is that by experimenting with the Baud and delay parameters you notice that you are receiving characters slower and faster.
The faster the serial line the more data you will receive, but the longer the delay the more the data will be slowed down, because the receive buffer will become full.

If the delay is very small (<50) then yes it will appear insignificant.
Try Serial.begin(9600) and delay(30000). This will show how significant the delay is :)


If the LEDs turn on when you apply 5V to ground then what you have identified as GND on the board is actually VCC.
There is no such thing as negative current: current is either sourced or sinked, depending if it’s exiting or entering into a node.

The diodes (LED) are one way valves, so you have a clear current direction: once that is established, identifying a button press can work either triggering when it gets LOW or when it gets HIGH, in other words that can be easily reversed.

If previously you where detecting a button press with digitalRead(BTN_PIN) == HIGH then just switch to digitalRead(BTN_PIN) == LOW and you have your solution.


Stepper motor shield compatibilty question

That is an SPI based device, and it doesn't use the (now considered standard) 6-pin ICSP header for SPI.

Therefore it will only directly work on boards that have the SPI pins available on pins 10-13 of the digital headers.

To use it with other boards you will need to manually route the SPI pins to the right places using wires.


How to determine what resistor value to use for LED strip

It seems like people generally just use a resistor around 300 - 500 ohms so I'll just use a 500 ohm resistor. Answer found on another thread. And here as well.


Is Gsm antenna effect on microcontroller working?

There are 3 possible causes that I can think of (it's difficult to say more without further details):

SW bug: this is hard to confirm without actually finding the bug, but it might cause a lock-up and trigger a watchdog reset (do you have a watchdog running?) or a pointer error cause a jump to some memory location along the boot path (not so likely, I suspect)
Too tight power envelope: when your system tries to transmit, it draws more power than the power supply/battery can provide. This cause a temporary voltage drop, to the point that the system kinda power cycles. You can try to use a power supply with higher maximum current.
Electromagnetic interference: somehow the transmission interferes with the AVR. You can try to direct the antenna further away from the AVR and to increase the distance in between.

But you should really add more information to your question.


Generate 2 PWM signals Vc and Vh from Arduino Uno

You can use the millis() function to see how much time has passed and use this to create your waveform while still being able to perform other tasks. You will check in which part of the wave you are in each iteration of loop() and adjust your outputs accordingly.

E.g:

long vhtime;
uint8_t vhpin = 9;   // the VH output pin
uint8_t vcpin = 10;  // the VC output pin

long period = 250;   // the period of your pwm signal in ms
long vhduty = 14;    // amount of ms vh should be high
long vcdelay = 2;    // amount of ms we wait for vc to go high after vh has gone high
long vcduty = 5;     // amount of ms vc should be high

long curtime;        // this will hold our current position in one period of the waveform

void setup() {
  pinMode(vhpin, OUT);
  pinMode(vcpin, OUT);
  digitalWrite(vcpin, LOW);
  digitalWrite(vhpin, HIGH);
  vhtime = millis();
}

void loop() {
  curtime = millis() - vhtime;
  if (curtime > vhduty)        // we are in the last 236ms of the wave, vh should be low
    digitalWrite(vhpin, LOW);
  else                         // we are in the first 14ms of the wave, vh should be high
    digitalWrite(vhpin, HIGH);
  if (curtime > vcdelay && curtime < vcduty + vcdelay) // vc should be high during this time
    digitalWrite(vcpin, HIGH);
  else
    digitalWrite(vcpin, LOW);
  if (curtime > period) {
    // we should start a new period
    digitalWrite(vhpin, HIGH);
    vhtime = millis();
  }
  // do your other calculations here
}


How do I repeat else if (cmd == '3') until I press another cmd?

I would suggest to rewrite your program as a Finite State Machine (FSM). It's a simple but powerful concept. You first model your program into multiple states, that are connected through state transitions. It is a good way to first draw this as a graph. You can see one example in my answer to this question.

For your case I would use your "modes" as states for the FSM plus an idle state, where simply nothing happens. You would start in the idle stat and then change to different states depending on the Serial input. In the states/modes 1 and 2, which are only one time actions, you would execute the action in the state and then directly change to the idle state again.

From the programming side a FSM can be implemented in multiple ways. I have seen FSMs using a variable and switch cases, but also FSMs, that use a function pointer. The last is elegant, but not as easy to understand for beginners. So I suggest you use the switch-case variant, as you can see in the answer linked above. Basically you use a variable (something like int or char) to represent the current state. In your loop() function you then build a switch-case statement for different values of your state variable. Often an enum is used as variable type to make the code more readable. In each case statement you write the code for the corresponding state. In your state/mode 3 you would check your sensors and close/open the window as needed, then leaving the case statement. When the next iteration of the loop() function happens, the FSM will still be in this state, checking again the sensors. In your states/modes 1 and 2 you would check, if the window already has the needed state and - if not - drive to motor to close/open the window. Then - still in the case statement - you would set the state variable to the idle state, then leave the case statement. So in the next interation of the loop() function the FSM will be in the idle state, doing nothing, making the states/modes 1 and 2 a one-shot everytime, that you activate them.

In contrast to the code in the linked answer, I would read the Serial data outside of the switch statement, since you will write directly to the state variable in there.

I strongly suggest, that you try to implement this. It is an important principle, that makes your more structural sound and easier to extent. A great learning experience.


ST7789 TFT display only shows a correct image while Arduino reset button is held down - Why?

I found the answer to this problem. After reading multiple web pages / YouTube videos from multiple authors on this device and ~all of them warning you must never connect the Vcc to 5v or it will destroy the display, I found one or two that suggested you could use 5v because in this particular module there is a built-in regulator. So, faced with the thing being useless anyway, I decided to take the plunge and connect the Vcc of the TFT to the 5v pin of the Arduino and - hey presto - it works perfectly (see picture below: note the clear full image without the reset button being held down and also notice the voltage pin of the TFT is now connected to Arduino 5v compared to the pictures in my question).

The picture below shows the back of my TFT display module and, from what I have read, it is the J3Y transistor that is key to the voltage regulation in this module.

I hypothesise that pressing the reset button must have allowed equalisation of the voltages somehow but it is beyond my knowledge to explain it. I tried measuring the 3.3v pin on the Arduino with a voltmeter while holding down the reset button but I could see no change (the TFT module was not in situ for this test so maybe there is some interaction between Arduino and the TFT circuitry during reset).
Please note: I suspect this is a peculiarity of the particular TFT display module I have. Please DON'T run your 3.3v devices at 5v unless you have good reason to believe that they can take it. I only tried this after reading a couple of pages (including the detailed specs on the TFT module seller's listing) that suggested it would be OK with my particular TFT module - your's may be different. But if you have the same problem you see in my question then maybe that is something to consider.
Thanks to those who have responded.


No.

Even if you don't use OTA, your program is stored in flash. If you have 1MB of flash, there's no way you can use all 1MB for SPIFFS; that would leave no space for your program.

Here's a page showing how flash is divided up in an Arduino environment.

Even if you eliminate space for OTA images and the EEPROM, the Arduino environment will still reserve space for the sketch itself and for its wifi config and possibly a little more data.

You can never use 100% of the flash storage for SPIFFS.


You add a transistor. Just like when you're controlling a relay, which needs more current that the Arduino can provide.


how to make an led turn on when something gets close to an ultrasonic sensor

Try with this and check that at least you can reproduce the desired effect:
http://www.arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor

Then you can refer to this for the part related to driving the LED:
http://www.arduino.cc/en/Tutorial/Blink?from=Tutorial.BlinkingLED

Since the ultra sound demo already calculates the distance, you can do the test on that to decide when to turn ON/OFF the LED.


Arduino Mega 2560 - TFT 3.5 Display is not working with libraries suggested

I have the same display. It has ILI9137 chip using 8-bit mode, so original Henning Karlsen UTF library doesn't work. You can find this library patched to support this display using Arduino MEGA at https://github.com/dgolda/UTFT

If display wouldn't work it is probably broken. I've received first piece broken - only backlight was working, but second and third was OK.


Sending AT commands to Reyax RYLR890 LoRa modules via additional serial port not working

In order to test AT commands for Reyax Rylr 896 module, you need to connect rxd of lora module with rx(D7) of nodemcu and txd of lora module with tx(D8) of nodemcu.


I can't control my DC motors speed with analogWrite()

I did find solutions for the problem. It turned out that the bridge does not work as it should be and the pins of en(A,B) is replaced with the in pins ..now I can control the speed but can't reverse the direction of the motors


I can't find the root cause of the problem - it's probably because the Due is possibly the worst board that Arduino ever made, and the compiler / linker / support libraries barely work at the best of times.

However, some things you need to look at in your code:

    double* h = new double[L];
    for(int n = 0; n <= L; n++){
        for(int k = 0; k <= n; k++){
            h[n] += pow(operador,-alpha-n+k)*pow(1.0-operador,n-k)*Binomial_E(alpha,k)*Binomial(-alpha,n-k);
        }
    }

There you allocate L (15) doubles in an array. But then you go on to access array slices 0-15. That's 16 entries in an array of size 15, so you're overflowing it and corrupting other memory.

Also you have no delete to balance the new, so you have a memory leak.  You would be better using:

double h[L+1];

instead of new.


In what situation would the Vin pin be attached to any of the I/O pins?

Vin is exactly the same as using the barrel jack (DC in) on the Arduino.  You can use it when you want to power your Arduino from an external source and you don't want to have the bulk of a big power plug.  It can also be used as a power output when you are using the barrel jack, for instance for powering relays or motors.  It just saves on having to splice wires into the cable of a wall wart, for example.

The voltage you feed in to the Vin pin should be of the same specification as the barrel jack - that is, between 7 and 12V.  From there, just like the barrel jack, it goes to the 5V regulator to provide the 5V for the board, and then on to the 3.3V regulator for low powered peripherals.

If, at any time, you power the board from the USB and have something connected to the Vin pin that consumes power you risk damaging the 5V regulator on the Arduino since power will flow backwards through it form 5V to Vin, which it really isn't meant to do.  In these situations it is good to connect a diode between 5V and Vin such that the anode is on 5V and the cathode on Vin - so that if the 5V is higher than the Vin voltage then the current will bypass the regulator safely.


This would be better answered on Stack Exchange Electrical Engineering.

Also see this question and answers. This is not quite the same and the answers there are OK but less than complete or correct, but it adds to the resource available.

You need a battery charging controller, a PV (solar) panel capable of producing somewhat more than maximum battery voltage and enough energy to operate your circuit and a battery with enough voltage to operate the device and enough capacity to store the energy.

Current drain will vary with total circuit. You can measure this will a milliammeter. I'll assume that 50 mA continuous will be enough. Less or much less may suffice. I have a pro mini clone operating at 20 mA on 5V at present and with due care you may be able to operate one with less or much less current depending on application and what your circuit needs are.

Looking at solar current needs at present, the average solar current needed is about Icircuit x 24/SSH mA where SSH = average sunshine hours per day. eg if you had 4 hours of sunshine per day but want to run the circuit for 24 hours a day the sun must provide (24 hours per day)/(4 hours of sun) = 6 x as much current as the circuit needs on average. So if your circuit needs 50 mA continuous the PV panel must provide 6 x 50 mA = 300 mA for 4 hours per day. You will see below that this is not a trivial amount.

Sunshine hours per day may be found for sites worldwide using the excellent www.gaisma.com The average sunshine hours per day for Iráklion may be found at that link and other locations in Greece can be found here but will probably be similar.
For Iráklion the SSH may be found in the 1st line of the 4th chart.
Average hours/day of equivalent full sunshine = kWh/m^2/day = a peak of 8.53 hours in June and a low of 2.08 hours in December.
Wow!
I think that is about as sunny a place in Summer as anywhere on earth not in the polar regions.  In Winter it gets about the same SSH as in my city. You can calculate PV sizing for peak summer - but if you want year round operation you should use the worst case winter month and add a bit for bad days.
For Iraklion us say 2 SSH per day so the panels needs to provide 24/2 = 12 x winter average load. So per 10 mA of load yo need 120 mA of panel and if the mean load is 50 mA you need 12 x 50 = 300 mA panel output.

Battery voltage needs to be > 5V at all times.
An easy cheap available starting solution is to use a 6B lead acid battery.
These are easyish to charge and provide a relatively stable operating voltage.
Vmax_charge is about 7V so an 8V or 9V PV panel is "about right". 9V is a common voltage for hobby applications. An alternative is to use a 12V panel. this is probably more suitable as they are widely available and cost per energy out is often lower. This wastes MOST of the panel output but still MAY be the cheapest option in many cases. (A 12V x 600 mA panel is rated at about 18V x 0.6A ~= 10 Watts. Actual Arduino load = 50 mA x 5V x 12:1 = 3 Watts)

At 50 mA load you need 24/2 x 50 mA = 600 mA PV output in full sun.
PV panel sizing is not as may be expected. It is easiest to get a panel that makes at least enough voltage and enough current. This is because panel RATED voltages are usually higher than the voltages they are used at. eg 12V system PV panels are usually rated at 18V max power voltage- so an 18W panel provide 18V at 1 A BUT if attached directly to a 12V battery the input to the battery = 12V x 1A = 12 Watts. There are ways around this but at first, just concentrate on panel mA.

So, you "need" a 600 mA panel for a 50 mA load.
Or a 60 mA panel for a 5 mA load.
Or a 6 mA panel for a 0.5 mA load.
Obviously, reducing load current is going to help panel sizing.
So knowing what your application really needs is essential.

Batery is easier.
If you use 6V lead acid then for one day you need.
Hours x load = mAh.
Here load=24 hours. mA = 50 in this example.
mAh = 24 x 50 mA =  1200 mAh = 1.2 Ah. This is the capacity of about the smallest LA battery commonly available. In practice you want to discharge your battery by only a small % of its actual capacity so use a 2.4 Ah or 3.5 Ah or larger. 7Ah is not vastly dearer and will last far longer and will have several days of reserve capacity for bad weather.

Charging can now be discussed - but I'll stop here and see what is said about the above. We can add charging and other detail if it seems useful to do so.

An easy battery to use is 2 x LiIon or LiPo cells in series.


Deviation of power consumption between datasheet and real world?

According to the datasheet:

  All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled.

That was the critical point. Trying this sketch:

int main ()
  {
  for (int i = 0; i < 20; i++)
    pinMode (i, INPUT_PULLUP);
  }  // end of setup

Note that timers are not running (your sketch would have timer 0 running):

With that sketch, even using the crystal and capacitors (I actually had a resonator) the consumption at 5 V at around 20 °C was 9.2 mA which is within spec.

Fuses:

Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDF
EFuse = 0xFF
Lock byte = 0xFF
Clock calibration = 0x96

If we turn pull-ups off:

int main ()
  {
  }  // end of setup

Now it consumes 14.4 mA, closer to what you measured.

And with your actual test sketch:

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

It consumes 15.5 mA, which is more, because Timer 0 is running (started in the init function). It is also close to what I had on my page about power - 15.15 mA.

So, working as expected. Those pull-ups are important, to stop the input drivers consuming current.

I did mention further down in my page the importance of configuring the pins:

  Testing in SLEEP_MODE_PWR_DOWN:

  All pins as outputs, and LOW: 0.35 µA (same as before).
  All pins as outputs, and HIGH: 1.86 µA.
  All pins as inputs, and LOW (in other words, internal pull-ups disabled): 0.35 µA (same as before).
  All pins as inputs, and HIGH (in other words, internal pull-ups enabled): 1.25 µA.

Notice the difference there of 0.9 µA when asleep. It would appear that there is an ever greater difference if the processor is awake.


I have a few years working with DMX, SPI (and other serial) & LEDs. I have worked with DMX and a video dance floor for 10+ years previously. I would offer that "some people" are correct. You will get a reliable system with differential pair signalling (such as DMX).
I have found from experience that over 5m of unbalanced serial starts chancing it. Over 10m and you are likely to come up with at least reliability issues, but more likely garbage.

I have used the TI SN75176B driver a fair bit and is cheap and works.

Depends on your audience. You can afford to chance it for your bedroom, but not paid business.


Arduino as voltage monitor shorts to ground

A voltmeter does not have a ground reference. An Arduino plugged into the USB port would have one. Conceivably a battery-powered Arduino might work, however a safer solution would be to use an opto-isolator to isolate the voltage being tested from the Arduino. Something like this:

In this case you connect the "data pin" to the thing you are sensing. If it is at 5V then the LED will conduct (taking around 7 mA) and the transistor in the isolator will drive the Arduino pin LOW. If the data pin goes to zero volts, the transistor will not conduct, and the 1k resistor will pull the Arduino pin HIGH. Thus you can detect if the pin has changed voltage.

The 560 ohm resistor is a current-limiting resistor for the LED in the isolator. A 1k resistor would probably also work, reducing the current draw on the data pin to around 3.8 mA.


The main difference is the bit before the -. That is, the 328 vs the 328P.  The "P" there denotes "Picopower" which allows the chip to run at very low power consumptions.

Basically the P version is a more modern version of the non-P chip.  There are probably other internal differences too but you will have to check the datasheets thoroughly for those.

Everything after the - is to do with the packaging and environmental grading of the chip.  For example PU is a -40C to +85C grade DIP chip. ANR is a -40C to +105C grade TQFP chip, etc.

If you see 328P-U then that's probably a fake chip. There's no such thing as single U suffix.


My Arduino keeps telling me the button is being pushed

When using a pull-up mode on an input pin, that means that when nothing is connected, the pin floats up to HIGH. The connected button should have one side connected to your input pin, and the other to GND, so that when you press the button, the input pin is pulled to GND (that is, LOW).

So your comparison to trigger on a button press should be if (buttonState == LOW)


Well, after playing with the code for some time, I just did it!!
pasting the updated code here, may be useful for someone else like me..

int ledPin = 13;                // choose the pin for the LED
int ledPinB = 12;               // choose the pin for the LED 2
int inputPin = 2;               // choose the input pin (for PIR sensor)
int inputPinB = 4;              // choose the input pin (for PIR sensor 2)
int pirState = LOW;             // we start, assuming no motion detected
int val1 = 0;                  // variable for reading the pin status
int val2 = 0;                  // variable for reading the pin status
int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(ledPinB, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(inputPinB, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  val1 = digitalRead(inputPin);  // read input value
  val2 = digitalRead(inputPinB);  // read input value
  if (val1 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  }
  else if (val2 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPinB, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  }

  else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      digitalWrite(ledPinB, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

Link to circuit and virtual demo


You forgot to put the parenthenses () after the name of the function changelights. They are there to declare variables you can use later in the code like that:
void function(int a){
  a+=1;
  return a;
}

To fix your error just change
void changelights{

to
void changelights(){

Keep in mind if you want to program C++ (which would be Off-Topic here, but you mentioned it in your question) you have to declare the function in the beginning or mention it.


In electronics, as usual in situations where a cricuit is misbehaving and we don't understand why, a solution that generally works is to add a decoupling cap between +5V and GND.

In your case, I would put at least 220uF; that would ensure two things:

the voltage used to control the servo never drops
the voltage brought to Arduino by the USB does not drop either (which would have very bad impact on the Arduino, probably resetting it)

Electrolytic caps are a must-have for every electronics hobbyist (and professional as well, of course).

You can read more about decoupling capacitors on Wikipedia.

Edit:

According to @gwideman comment, it seems that using a decoupling capacitance above 10uF in a USB 2.0 device would violate USB specs and may damage the USB host controller on the computer.

I was not aware of this limitation but I have already used decoupling capacitance up to 100uF in my circuits and never got any issue with my USB computer port.

It might be due to extra electronics on the Arduino board that would "isolate" USB power from Arduino +5V anf d GND pins, I don't know (that should probably be the topic of a specific question); or maybe I have just been lucky all this time...


Understanding how methods and pointers inside a function work

"There are no stupid questions, just stupid answers"

  Why there is a Method "Print" not a Data Type inside the Function Argument List?

There is no "Method" Print in the argument list.  There is a reference (not a pointer which would be a * not a &) to an object called printer that is of type Print.  The code you have provided doesn't define Print but its a could guess that it is probably something to do with printing.  By supplying the printer argument you can print this data to anything that inherits from the Print base class, Serial is a good possibility, but you could write a class that derived from Print and wrote the data to an LED matrix, etc.
I can tell its not a Method, because you are calling the print method of printer, so it has to be either a class or structure.

  The function will print some data on a Serial Monitor or SD Card

I can see why you thought that but you are being too specific, it prints to anything that derives from Print, Serial and dataFile derive from it, but they might not be the only things.

  I need to send one Method through the left value of a pointer and 7 integers. I can't understand why a method.

An example might help:

class CGPrinter : public Print
{
  // Some code....
  virtual void print (const char* input) {// do something}
}

void loop()
{
  CGPrinter cgp;
  printImuData (Serial, 1,2,3,4,5,6,7);
  printImuData (cgp, 1,2,3,4,5,6,7);
}

Serial is an object, a variable, a specific instance of type of class that can print data.

CGPrinter is my new super sexy printing class that will read the characters that you 'print'.  To print the 7 integers to CG's printer class is exactly the same call as the one to write it to the Serial Monitor, because both classes derive from Print.

  What data do I get back from it?

Yes, correct on both points.

Does it make more sense now?  If not, just say and I'll try and clarify it.


How to update multiple outputs simultaneously

Yes, the ports of an Uno are addressed in C/C++ as PORTB, PORTC, and PORTD respectively, each 8 bits wide. You can read them or assign to them. Other processors' ports have similar names. Of course the pins' port assignments and functions differ from one to the other, which is one reason for providing the single-pin pinMode() and digitalRead(), digitalWrite() functions. But where you need to deal directly with the hardware (and probably don't care about chip-to-chip portability), the registers are exposed with the above symbols.

Also note that most other CPU registers are exposed the same way - the ports' data-direction registers as DDRA, DDRB, DDRC. You may not care about setting them up simultaneously, but if you wanted to make all of your hardware accesses similarly (and save the flash space for the portable pin functions), you could.

Update:

  Is there a specific command I can use ? Such as Write PortD ?

Yes, you can use the PORTx names like any other C/C++ variable:
PORTD = 0xFF;
PORTD ^= 0x02;
if( (PORTD & 0x40) != 0 ){, for just a couple of examples - just like real C! :-)

PS: Pighixxx makes absolutely top-notch pinout diagrams for boards & processors. Here is his diagram for the 28-pin DIP-packaged AtMega328p for instance. They're extremely useful when you're working with a chip at the port or board level.


How To Make LCD Shield Button Code Work with Pot

I think what may be most helpful is an explanation of some tools which would serve you well on this.  In order to use the potentiometer to select different options, a simple solution would be along these lines:

Read the potentiometer value.
Check which range the value fits in.
Perform a corresponding action.

Here is one idea for accomplishing this:
Read the potentiometer value:

int reading = analogRead(A0);

Check which range the value fits in.

if(reading < 1023/4){
    //Action 1
}else if(reading < (1023/4)*2){
    //Action 2
}else if(reading < (1023/4)*3){
    //Action 3
}else{
    //Action 4
}

Perform a corresponding action.

//Do something cool.


Arduino server to read from multiple clients

Without knowing your exact implementation details...

You should be OK as long as you don't have multiple clients connected at the same time. You may think that there are multiple clients connected to your server, but the connection is closed after the resource is obtained by the client over a protocol.*

The standard flow of a server on Arduino:

A client connects to the Arduino.
The Arduino code realizes this connection and reads the data provided by the client.
The Arduino then sends some data back to the client.
The Arduino closes the connection and waits for another client to connect.

This happens relatively fast so multiple people can connect.

If you call a function like .close(); after you send data to your client, you should be okay. If you don't, redesign your code to have this element (avoid loops and blocking functions) and make sure to have your client reconnect every time it sends a command.

I wouldn't mess with this and Protothreads because I'm not sure that the Arduino hardware is designed to be able to handle multiple connections at the same time. [Citation needed]


A common anode RGB LED can be sketched in a schematic like this:

simulate this circuit – Schematic created using CircuitLab

The positive voltage has to be applied to the top, for all the LEDs together. To light the LEDs up, you have to sink the current on the other end, meaning providing ground level at the bottom of that schematic at the corresponding pins. The current will then flow from your 5V pin, through the LEDs into the Arduinos pin.

That means, that analogWrite(pin, 0) will turn the LED on that pin ON and analogWrite(pin, 255) will turn the LED OFF. The logic is inverted here, because the Arduinos output pin is on the other side of the LED.

So your circuit and code work perfectly, you just didn't expect the inverted logic.

Note: The pins of the Arduino can only source/draw a certain amount of current (20mA continuously, 40mA at maximum) without getting damaged. A single, not too strong RGB LED should be OK, but as soon, as you want to drive more LEDs, you should consider using a driver circuit (for example simple transistors). That way the output pins don't have to provide the LEDs current, but only the current to control the transistor.


Read from serial monitor and put it in a array of byte

If you want to print it only, I would suggest not to store it. But if you want to do some calculations, you might store it.

The problem you make is you always store the value in the 6th element of the array A, however A only has elements A[0] to A[5], so A[6] is beyond the storage space, and results in crashes (sometimes) or at least unexpected behavior.

To fix it you have to store the value in the correct element of A, and for that you need an index variable. Since you can only store 6 values, after the 6th, start with the 0 and process it.

Like:

byte arr[6];
index arrIndex;

void setup()
{
   arrIndex = 0;
}

void loop() {
  // Read serial.
  arr[arrIndex] = Serial.read();

  // Increase counter
  arrIndex++;

  // If the maximum is read, print values and reset it.
  if (arrIndex == 6) {
     // Print the elements.
     for (index = 0; index < 6; index++)
     {
        Serial.write(A[index]);
     }

     // Restart counter.
     arrIndex = 0;
  }
}

An improvement: instead of 6 everywhere, use a define:

#define MAX_ELEMENTS 6


You cannot get GPS data without getting GPS data. That's like wanting to get milk from a cow without using a cow.

Some GSM modem modules also include a GPS chip. If yours does you can use that. If not then the closest you can get is:

Country (or maybe city) the IP address is registered in
Cell ID and location of the tower you are communicating with

Both of those are only very rough "somewhere within this square few miles" or "somewhere in this country" kind of data. Any more than that and you need GPS.

Mobile phones augment the GPS / Cell data with WiFi data by matching BSSIDs with an online database (within Google etc) to get rough location information.


How to use d0 and d1 pins of arduino uno (Others) as a digital output when I don't want to use Serial

If you don't use the serial port, pins 0 and 1 are regular I/O pins.
It's just as simple as that.

If you want to use Serial communication, then you can't use them.

Correct.

You can't use it while your arduino is connected to PC.

Wrong. You can keep the USB cable connected as a power supply. You will
not be able to use it for communication though.

You Can't do this, as this may harm the device

What is “this”? The device can be harmed if you drive too much current
to/from an I/O pin, irrespective of whether it's a pin that could be
used for serial communication.

You must turn off serial connection first.

Only if you did turn it on before. If you never enable Serial, you
don't have to do anything more.


I am 90% sure it's a power issue. Not sure on what board/module you're using but the SIM800L/SIM900 needs a burst of current of 2 A during 577 µS (See the manual).

Try using 4700 µF and a 10 µF capacitor in parallel with the module. Powering it with a proper power source instead of the Arduino wouldn't hurt too.


error at compiling : 'class TwoWire' has no member named 'setClock'

Thanks for the reply. I tried again with the arduino on PC with RasPiDuino librarie and had no further problem. The resulting executable does work on a RPi3 with Buster OS. Apparently the arduino webeditor lacks some libraries to succesfully compile for raspberry . I continue this road. Item can be closed.


I've found the problem

It should be:

Serial1.println("2");

instead of:

Serial1.write("2");


String use in arduino IDE (this question for understanding)

String objects are simple to use. There is a trade-off for simplicity. Strings work by using dynamic memory allocation. Something like this for example:

String foo;
...
foo += 'a';

By adding one character to a string the class has to allocate new memory for the slightly longer string. If you keep doing this you get memory fragmentation.

You are probably better off deciding what your maximum size string is and making that a static array of characters.

So should I use the String objects?

For occasional use they are fine (for example, holding the name of something). They tend to fall down once you start with a small String and keep adding to it, because the code has to dynamically allocate memory, allocating (say) 5 bytes, then 6 bytes, then 7 bytes, and in the process freeing up the original 5 bytes, then 6 bytes and so on. This allocating/freeing process can leave holes in the "heap" causing a thing known as memory fragmentation.

Done to excess you can run out of memory. That is, you might need 100 bytes but have 10 lots of 10 bytes free, with stuff in-between that isn't free.

You don't have lots of memory to start with, so it is probably better, faster and more efficient to decide the largest amount you need for some string, and just make that a character array.


Any way I can avoid this?

I think the whole concept of reading "n" bytes is flawed. It will indeed hang if you don't get the number you expect.

Why not just do what normal serial comms does. Accept bytes as they arrive in an ISR, and put them in a buffer? Then use the line-terminator to know when you have enough to process.

  So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

The UART ISR won't be called if there is no data, so it won't be "always called".


Understanding Soil Moisture Sensor Values

I had this same problem when I began experimenting with soil moisture readings. I noticed that the readings from the sensor can vary widely when not hooked up correctly, or when other nearby objects are somehow interfering.

For instance when I put a SparkFun breakout similar to yours in dry soil and continuously take readings every 50ms, the signal oscillates from 0 to 50, and simply touching the soil with my finger can affect the signal due to the electricity in my body. If you have a metal pot on a metal table, that could be affecting your readings. There's a lot to consider!

However, once I water the soil and let it soak in, the reading generally becomes much more stable. Below I included a real-time plot using a plant I watered about 24 hours ago. Here's how I set up my soil moisture sensor, including code. The readings are taken every 60s and the plotter repeats the old reading until a new one is taken. There's very little deviation when all connections are secure and the soil moisture is evenly distributed.

In general, the specs for the sensor will inform you on what kind of signal to expect. Based on your sample data I suspect yours is a 10-bit signal from 0-1023, so 800 range means the soil is quite moist. If you just watered the plant, then the water content around the sensor will change as it seeps through the soil, leading to fluctuations when measuring. Give the soil a few hours to absorb the moisture and try measuring again.


Using signal strength feature of nRF24L01 module

To get the signal strength just send 100 packets with no retries and see how many times the packet arrives.
radio.begin();
radio.setRetries(0,0); // by default nrf tries 15 times. Change to no retries to measure strength

char buffer[32];
int counter = 0;

for(int i=0; i<100; i++)
{
   int status = radio.send(buffer,32); // send 32 bytes of data. It does not matter what it is
   if(status)
       counter++;

   delay(1); // try again in 1 millisecond
}

// if counter > 80 signal strength is great
{

}

// else if counter > 60 signal strength is good
{

}

// etc

radio.setRetries(5,15); change back to its default when done.

For this code to work the receiver must be listening for data. Just listen for data on the receiver there is no need to validate the data.


Can I load programs through the RS232 pins?

The stock bootloader will accept the load of new programs on PE0(RX input) and PE1(TX output) (of the ATmega2560) just after reset. Note PE0/1 on the Arduino correspond to pins D0 and D1. Not D2 and D3. You could change the Boot loader if desired.

There is a 1K series resistor between the 16U2 and 2560's PE0/1. So you can directly connect your external TTL serial port's TX(out) to PE0(D0), without harm. And correspondingly connect PE1(D1) to the TTL Serial port's RX(in).

Next you need to synchronize the bootloader. Either by manually synchronizing the Reset of the 2560 with the starting of the download (of AVRdude). Or by connecting the DTR(out) of the TTL Serial Port through a 100nF capacitor to the RESET pin of the Arduino.

I would also recommend putting the 16U2 into reset, to get it out of the way. Simply place a jumper between ICSP1's RESET2(pin5) and GND(pin6).


On your setup function

Serial.begin(115200);//<- 115200 is the baud rate, serial monitor must match this speed
while(!Serial);//<-- wait for Serial to be ready

see: https://electronics.stackexchange.com/questions/9264/what-standard-uart-rates-are-there for more baud rates


Error: "invalid use of non-static member function" while calling a function from my own class-method

The problem is that echo_check isn't void echo_check() but void echo_check(myclass *this) because it's a member function of a class.

You can make the whole thing static (along with run()) by:

class myclass {
    public:
        static void run();
        static void echo_check();
};

static void myclass::run() {
    ....
}

void myclass::echo_check() {
    ....
}

And then you call:

myclass::run();

instead of instantiating an object.


What you want is a P-channel MOSFET to control the power. Something with a nice low "logic level" gate threshold.

simulate this circuit – Schematic created using CircuitLab

R1 keeps it switched off.  Set the output to LOW to pull the gate down and enable the MOSFET.

Be sure to "stop" your Serial connection and set both TX and RX pins to INPUT to prevent damage to the ESP8266 (or ATTiny) while powered off.


DB:NO RESP Using inet.httpPOST on loop()

Like I told you before, you have 2 instances of SoftwareSerial active, but you're allowed to listen to only one at a time (implementation rules). So you have to alternate between calling listen() on each instance; any data arriving at any port while its not the active port will be discarded. inet.httpPOST() worked in setup() because you called the function before begin()ing serialGps. Calling serialGps.begin() immediately made serialGps the active port, severing communication with the modem.

Add this line to SIM900.h in the library, under the public methods:

void listen();

Add this method to SIM900.cpp:

void SIMCOM900::listen(){
   _cell.listen();
}

Save the files and add gsm.listen() right before gsm.SimpleWriteln("AT+CIFSR"); in loop().
Re-initialize GPRS, like you did in setup() with attachGprs(), right after gsm.listen() in loop().
Make serialGps.listen() the last  statement in loop() immediately after the inet.httpPOST() call. Use braces to enclose the body of the while loop.

Hopefully this should solve your problem.


scroll text through multiple i2c connected dot matrix displays

This is what I found behind the link @mikael-patel posted, and with a little configuration it does exactly what I want. Basically the scroll()-method handles anything neccessary.

#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

#define NUM_MATRICES 2
Adafruit_8x8matrix matrix[NUM_MATRICES];

void setup() {
  Serial.begin(9600);
  Serial.println("8x8 LED Matrix Test");

  for(uint8_t m=0; m<NUM_MATRICES; m++) {
    matrix[m].begin(0x70 + m);
    matrix[m].clear();
    matrix[m].setTextSize(1);
    matrix[m].setTextWrap(false);  // we dont want text to wrap so it scrolls nicely
    matrix[m].setTextColor(LED_GREEN);
  }
}

void loop() {
  scroll("Hello World!");
}

void scroll(char* text) {
  int scrollPositions = (strlen(text) * 8) + 32;

  for (int x=(8 * NUM_MATRICES); x>=-scrollPositions; x--) {
   for(uint8_t m=0; m<NUM_MATRICES; m++) {
    matrix[m].clear();
    matrix[m].setCursor((x - (m * 8)), 0);
    matrix[m].print(text);
    matrix[m].writeDisplay();
   }
   delay(80);
  }
}


Arduino Mega - Enabling CTC mode disables timer

I think your problem is that you are using the wrong "TOP" counter value register.

OCR3B =  CMP_FAST; // CMP_FAST = 40

should be:

OCR3A =  CMP_FAST; // CMP_FAST = 40

I am not too familiar with the workings of the AVR times, but according to the datasheet:

  In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence also its resolution.

(Note: it only mentions the register for timer 2, but the same holds true for all the timers in the same class, including timer 3).

Since OCR3A is zero it never triggers a match.  And since there is only one counter (TCNT3) which gets reset to 0 on a match, there can only be one register to compare to, and that is the "A" register. The "B" register appears to be redundant in CTC mode.

You may also need to switch to the COMPA vector (I am not sure on this one TBH)


Hall effect sensor direction detection using arduino

According to the data sheet (see below) the no-field PWM output is mid-range; north poles reduce it & south increase.

So if you had an arrangement whereby the float had north down & south up, ie a vertical bar-magnet, this would presumably give a rise-before-0 or fall-before-0 at the float vanishes, or a fall-to-minimum an rise-to-maximum as the float centres? The bit in the middle could be interesting!

From the datasheet:
"The presence of a south polarity magnetic field,
perpendicular to the branded surface of the package face,
increases the output duty cycle from its quiescent value toward
the maximum duty cycle limit. The amount of the output duty
cycle increase is proportional to the magnitude of the magnetic
field applied. Conversely, the application of a north polarity
field decreases the output duty cycle from its quiescent value."


Does anyone know where on the board are the RX and TX pins

The serial Rx and Tx signals from the ATmega2560, go to the nearby FT232RQ USB-to-serial adapter. You can look at the part numbers on the ICs and find those two devices on the PCB.

  no more info on the board in the internet and forums

It's good news that there does seem to be more information available :-) After a few minutes with Google (searching for GT2560 schematics) I found this download link for the schematics on this forum page.

Although it would be possible to reverse-engineer the PCB (or at least the relevant part of it) the schematics are still helpful, since the white coating makes the actual copper traces harder to follow visually.

The schematic shows that two 1k resistors, R3 and R13, are in series with serial signals:

R3 between ATmega Tx -> FT232 Rx
R13 between ATmega Rx <- FT232 Tx

You may want to confirm that the linked schematic still applies to your specific PCB (since PCB and schematic versions could have changed). With the power disconnected, you could check with a multimeter that there is continuity between the appropriate ATmega pin and one end of each resistor R3 & R13, and between the other end of each resistor and the appropriate FT232 pin, as shown on the schematic.

I have put a red ring around those 2 resistors on the GT2560 top view below, to help you to find them:

(original image source)

  best place to connect to them

If you are going to drive those serial signals from an ESP8266, you must first disconnect them from the on-board FT232, to avoid contention and so the ESP8266 replaces the FT232. Removing those two resistors would make each resistor's (now vacant) pads leading to the ATmega serial port, an ideal place to connect the ESP8266. (Of course you could attach wires directly to the pins of the ATmega or FT232, but I don't see any advantage to doing that.)

One issue which you need to consider, is the voltage compatibility of the serial port signals. The ATmega2560 uses 5V signal levels, whereas the ESP8266 is a 3.3V device. There have been discussions on various websites (example) that suggest the ESP8266 is 5V-tolerant on I/O pins. You will need to satisfy yourself whether to use voltage translation, or to rely on information discussed on web pages like that one.


How the output of a bicycle dynamo can be displayed using Arduino?

The first thing to look at before you connect the bicycle dynamo to an Arduino is what type of signal / voltage it generates. The link you've provided: http://www.lanzo.se/experiments/dynamo/dynamo.html gives you the answer. It's an AC signal which varies between +4V and -4V (It could be much higher if you spin it faster). On the Atmega328P data sheet under "Absolute Maximum Ratings" it says "Voltage on any Pin except RESET with respect to Ground -0.5V to VCC +0.5V". Obviously, -4V exceeds the -0.5V maximum so don't connect it directly to an Arduino.

The signal from the dynamo to Arduino must be limited to between 0V and 5V (for an Arduino operating at 5V). The answer on how to accomplish this is a general electronics question and should be asked on a different forum e.g. https://electronics.stackexchange.com/questions/132330/8v-ac-signal-into-3-3v-digital-input-pin

The "frequency meter" part of your question is easy to build with an Arduino. You could use an Uno or something smaller like a Pro Mini with a 16 x 2 LCD display and this library: https://github.com/k3ng/k3ng_antenna_tuner/tree/master/libraries/FreqCounter. An I2C backpack for the LCD is only a dollar more and makes the wiring much easier. To use the backpack you'll need this library: https://github.com/marcoschwartz/LiquidCrystal_I2C.


In a real world scenario, your robot would know its start point and end point but due the limited range of its sensors (radar/ sonar/ visual) and the inability to "see" around corners, it would never be able to plan a full route at the very start of its journey. It would need to start the journey, detect obstacles as it moved and then re-calculate its path as it proceeds to its destination.

There is a very simple weighted index algorithm called the 'Bubble Rebound Algorithm' to accomplish this type of maneouvering developed by IOAN SUSNEA, VIOREL MINZU and GRIGORE VASILIU.

Be aware however, that this is NOT a 'Maze Solving' algorithm. It is only meant for avoiding obstacles.

But first I suggest you take a look at my blog post about the python simulation I wrote using this algorithm. This will help you understand what is going on and give you a broad idea about how the problem is solved.

I also made two very important modifications (which I have described in the blog) to the algorithm that help the robot actually reach a destination.

On the blog post you will find a link to the source code hosted at codeskulptor and a YouTube video demonstrating the algorithm at work.


Is there any good working MODBUS TCP master library available for Arduino?

Check out the library Modbus-TCP on Github. It has the facility for all the function codes as asked. It has provision for Wiznet W5100 and ENC28J60 Ethernet IC. All tested with Arduino Mega. See the well documented example code for the Wiznet module in the library.

For detailed knowledge about the library, read the index.html inside the doc folder of the library.

Here is an example code explaining a few function codes for the Arduino Mega and a W5100 module.

/*
  This is Modbus test code to demonstrate all the Modbus functions with
  with Ethernet IC WIZNET W5100

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

  ModbusTCP is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with ModbusTCP.  If not, see <http://www.gnu.org/licenses/>.

  Adopted from ModbusMaster for RTU over RS-485 by Doc Walker
  Modified by Narendra Dehury for TCP.
  copyright @ phoenixrobotix.com

*/
#define WIZNET_W5100 1

unsigned int param_value_int[7];
#include <Ethernet.h>

IPAddress ModbusDeviceIP(10, 10, 108, 211);  // Put IP Address of PLC here
IPAddress moduleIPAddress(10, 10, 108, 23);  // Assign Anything other than the PLC IP Address

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xE1 };

#include <ModbusTCP.h>

ModbusTCP node(1);                            // Unit Identifier.

void setup()
{

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);                      // To disable slave select for SD card; depricated.

  Serial.begin(9600);
  delay(1000);
  Ethernet.begin(mac, moduleIPAddress);
  node.setServerIPAddress(ModbusDeviceIP);
  delay(6000);                                // To provide sufficient time to initialize.

}

void loop()
{
  uint8_t result;

  node.setTransactionID(random(100));           // Not necessary; but good to distinguish each frame individually.
  result = node.readHoldingRegisters(1, 12);    // Read Holding Registers

  Serial.println(result, HEX);
  if(result != 0)
  {
    Serial.println("TimeOut");

    delay(6000);
  }

  int len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));// See the length of data packet received.
  for (byte j = 0; j < len; j++)
  {
    Serial.print(node.getResponseBuffer(j));       // Inspect the data.
    Serial.print(" ");
  }
  Serial.println();
  node.clearResponseBuffer();
  delay(100);

  node.writeSingleRegister(5, 3);                  // Write single register
  Serial.println(result, HEX);
  delay(500);

  for (byte i = 0; i < 5; i++)
  {
    node.setTransmitBuffer(i, (i+100));
  }
  node.writeMultipleRegisters(2, 5);               // Write multiple register
  Serial.println(result, HEX);
  delay(500);

  node.writeSingleCoil(20, 1);                     // Write Single coil
  delay(500);

  node.setTransmitBuffer(0, 0b1010101001010101);

  node.writeMultipleCoils(20, 16);                 // Write multiple coils
  delay(500);
  result = node.readCoils(20, 18);
  len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));
  Serial.println(node.getResponseBuffer(0), BIN);

  node.clearResponseBuffer();
  delay(5000);
}


From the documentation:

  delay()

  Description

  Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)

So... milliseconds vs. microseconds.


No, this is not a bug. You are using a compile time constant expression which is signed int unless told otherwise. Therefore you can only represent numbers between -32768 and 32767. Your computation of 255 * 255 = 65025 exceeds the range. Thus you see an overflow. In the C/C++ standard the overflow of signed types is actually undefined behavior. That means that the compiler is allowed to do anything from showing the correct answer to halt and catch fire. Only unsigned types with a known size like uint16_t have a well-defined overflow behaviour. You should promote your right hand side computation to unsigned type like this:

z = 255U * 255U;

This way you tell the compiler your intention and don't land in "Undefined-Behaviour-Land".


Need help with nRF24L01 and Arduino decoding and receiving

On the nRF24L01 the communication is performed through "pipes", each with an address. That is unique to those chips and you cannot assume that some other random chip will do the same thing. As a general rule the nRF24L01 chips will only communicate with other nRF24L01 chips. You will need a SDR and an in-depth understanding of the workings of your current transmitter and it's communication scheme to even begin to think about doing what you want.

So... Go plan B.


Not getting proper readings on Arduino from MAP Sensor


Do I need 3 full-size arduinos to control this LED setup?

Maybe look at NeoPixels Revealed: How to (not need to) generate precisely timed signals. The author there controlled 1000 Neopixels with a Duemilanove with fairly simple code. These were WS2812 not WS2811 but perhaps the code could be adapted to suit. Judging by the datasheets they are fairly similar.

Since he got 30 fps with 1000 pixels, your requirement of around 100 pixels would seem fairly straightforward.


How to calculate air velocity from wire resistance?

Its very simple really, all you need to do is code the equations on this page and then supply some heat and you will be able to do it.  Just remember integer division rounds down :)

http://www-g.eng.cam.ac.uk/whittle/current-research/hph/hot-wire/hot-wire.html


[SOLVED]how to send command to Gsm module from Arduino via serial port

I solved my problem, On my circuit GSM module use an external source and my Arduino Uno use serial port source, So it cant communicate via pin because both ground of them did not connect to each other then the answer is connected GSM module GND to Arduino Uno GND.


How can I setup a LED state change with push buttons?

This is an excellent tutorial for exactly that:
http://www.instructables.com/id/How-to-use-a-Push-Button-Arduino-Tutorial/

Its a bit hard to give you a specific answer without seeing you circuit.
but as a start, i would set the ledPin to LOW in the setup routine.

void setup()
{
  pinMode(ledpin,OUTPUT);
  pinMode(pushbutton1,INPUT);
  pinMode(pushbutton2,INPUT);

  //initialize the pin to low
  digitalWrite(ledpin,LOW);

}


How does Yun identify itself to Windows?

It is written in what is called the USB String Descriptor.  I don't have my Yun to hand right now (it's acting as a wireless bridge temporarily), but all USB devices have these USB String Descriptors.  Here's an example for the Leonardo (which you can easily inspect on Linux):

$ sudo lsusb -v -d 2341:0036

Bus 001 Device 015: ID 2341:0036 Arduino SA
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               1.10
  bDeviceClass            2 Communications
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0         8
  idVendor           0x2341 Arduino SA
  idProduct          0x0036
  bcdDevice            0.01
  iManufacturer           2 Arduino LLC      <<== String descriptor ID 2
  iProduct                1 Arduino Leonardo <<== String descriptor ID 1
  iSerial                 0
  ... etc ...

Internally the strings are stored as an indexed table - there's two there, ID 1 and ID 2.  The Device Descriptor then has a couple of bytes in it that says "The manufacturer is string ID 2, and the product name is string ID 1".  The operating system then requests those string descriptors so it can display the friendly message for you.

If you want to change that name you basically have to both re-program the bootloader (which has the USB descriptors when in program upload mode) and the Arduino core (that has the string descriptors programmed into it).


How can I store the received data from nRF24l01+ module in an array (code in description)?

I would suggest to send 2 bytes to this module
the first byte is the pipe number (0xE1,0xE2,0xE3,0xE4)
and in the second byte Data

void loop()
{
  if (radio.available())
 {
  radio.read(&text, sizeof(text));
  for (int i=0; i < 4 ; i ++)
   {
     if( text[0] == ((unsigned char *)(&pipes[i]))[0]
        recArray[i] = text[1];
   }
  Serial.println(text[1]);
 }
}


Where can I find out how to make a hex file for arduino firmware?

The HEX file is simply a translated version of the AVR executable, which is in turn a translated version of AVR source code.

There are many tools available for turning (compiling) AVR source code into an AVR executable, including but not limited to the Arduino IDE, Ino, AVR-GCC, and Atmel Studio. Note that all four tools will compile the code the same way, since AVR-GCC is used under the hood by the other three.

avr-g++ -mmcu=atmega328 source.cc -o executable

Once you've compiled the code, you can use avr-objcopy to extract the appropriate sections from the executable into HEX files for programming into the flash and EEPROM.

avr-objcopy -j .text -j .data -O ihex executable executable.hex

You can then use AVRDUDE to upload the various HEX files to the target device.

avrdude -c arduino -P /dev/ttyUSB0 -b 19200 -p m328 -U flash:w:executable.hex:i

Note that the USB libraries in Arduino/Ino and AVR LibC are limited; you will need to use Atmel Studio if you want full USB capabilities.


How to drive motors and use an ultrasonic sensor simultaneously?

For the first question, you could simply implement an interrupt routine to regularly check the status of your sensor and when it achieves the desired threshold it triggers the action to stop the motor.

You can achieve this by setting timer1. There is a library here for example, where you set the period to execute a desired function, when some distance is detected you just stop the motors.

The second question could be done exactly like you said. Say you have some paths saved in memory, you can just create some options for them and execute whenever you want using switch/case command.

http://playground.arduino.cc/code/timer1


The limitations of accuracy of the library depend on accuracy of the crystal. When they make, or cook, the crystal they can only make it to a certain degree accurate, also the environment of the crystal (temperature, humidity, etc.) play a role in the accuracy of it. Let's say you have a crystal that is off by .5 second every hour, great for short term, but if you expand that over a year it is over 1 hour off by that time. If you want something to keep an accurate time over a long period I suggest a real time clock (they still have inaccuracies), a GPS module, or an internet connect to sync with.

For further information look at the wikipedia article on quartz crystals

The use of a 84MHz crystal versus a 16MHz crystal will not necessarily improve the accuracy of the Arduino clock since the frequency of the crystal is more an indicator of processor speed than accuracy. The accuracy of the Arduino clock is primarily dependent on the accuracy of the crystal oscillator.

EDIT: I am no expert on crystal oscillators so if you see anything wrong here please let me know