You wrote:

void runServoLight(
        int pos, int light1, int light2, Servo servo, int state)

Here you are giving the list of parameters used by the function. In C++,
parameters are by default passed by value. This means that, when the
function is called, the arguments passed in the call are copied into
the parameters listed here, which are local variables of the function.
Changes to those parameters will not propagate to the arguments provided
by the caller.
This can be an issue for the Servo object. This object keeps some
internal state, which has the memory of the current configuration of the
timers. Since you are working on a copy of the provided object, the
original object is not updated when you act on the copy. I do not know
whether this is making your program misbehave, but it would be safer to
pass the Servo object by reference:
void runServoLight(
        int pos, int light1, int light2, Servo &servo, int state)

This way the object will not be copied: the function will instead work
on the original object provided by the caller.
The same may apply to the pos parameter. The very first thing the
function does with this parameter is to overwrite it. Then there is no
point in receiving that value from the caller. You can instead remove
the parameter and create a local variable with the same name:
void runServoLight(int light1, int light2, Servo &servo, int state) {
    int pos;  // local variable
    ...
}

If you want the caller's version of this variable to be updated, you
could pass it by reference, just like the Servo object. It is,
however, more efficient to keep the variable local and have the function
return the final position. The call would then look like:
pos1 = runServoLight(lightON, lightOFF, servo1, 1);

One final point that is not visible in the snippets you showed: are you
doing edge detection on the buttons? Edge detection means that you act
on the changes of state of the buttons, not on the states themselves.
For example, you move from lightOFF  to lightON not when the button
state is HIGH but rather when it turns HIGH.


arduino flexbot drone connected in a wrong way

The motors turning on is expected because or the reverse diode in the mosfets driving the motor.

Looking at the schematic, it seems like the problem is on the 5v rail. If 5v isn't supplied by the USB port, it is provided by the LTC3200 (DC/DC converter)(U3 on the pcb). I think that's where the problem is, as that would explain why it only work when USB is connected.

To confirm this you'd have to measure the output voltage (pin1 (pin nearest to the ATMega) of U3, and see if it's 5 volt.

To fix it you should ideally replace this part. But it might also work without, if you simply connect the battery voltage directly to the 5v (i.e. jumper pins 1 and 5).


How to control 6 stepper motors with Arduino?

Yes it is possible, of course everything is possible!

These drivers need two IO lines at very minimum: DIR and STEP. Pulsing STEP makes one step movement forward or backwards (depending on DIR).

For 6 steppers you need therefore 12 outputs from Arduino. (Which Arduino please? pick one which has enough IO, or otherwise use an I2C output extender).

M0 and M1 controls microstepping mode - configure at your wish. CFG is high on this Pololu board, allowing the board to use as a stepper driver out of the box.

Steppers (if you want to get them working at full torque) require a constant-current drive. (Inexpensive solutions use a constant voltage drive, such as using an ULN2803 - however those can not get too much torque). Happily this driver can do this well, the potentiometer sets the maximum current.

Steppers need considerable current when starting movement to a next step. However, unlike DC motors, even a still position will consume current, which eventually makes the motor hot. Therefore you are supposed to limit the current when the motor is not moving. This is usually done from software (the driver does not known when it is time for a long period at stop).

The way for limiting motor current at stop can be either an analog limiter, or a PWM. This driver has no dedicated input for this purpose. You can do two things:

use smaller drive current (use the potentiometer) - this can work well if you're satisfied with the torque
use the sleep mode of the driver with a PWM from the Arduino side.

This latter solution needs you to:

connect all EN pins of all 6 drivers, and connect it to one Arduino pin which has PWM (i.e. analogWrite())
drive this to 0, then start movements
once movements are finished, use analogWrite() and set to say, 128 (usually half of the move current is a good guess for holding current)

This way when the motors are stopped, the holding current will be less, hence the motors don't get hot.


Can I mix 22awg and 26awg hookup wire in the same circuit?

Assuming you won't ever put more current through it than the 26AWG wire can handle, you'll be safe.


How to use the pushbutton without using if, else

As the required operation is finite and short, you can just hard code the sequence.


How can I generate a sinewave with Arduino Uno?

As far as I know, there is no library for Uno to generate such a
  signal (correct me if I'm wrong)

You are wrong, there is Mozzi, the sound synthesis library for
Arduino. It works essentially along the lines sketched by uint128_t.
Take a look at the Sinewave.ino for an example on how to make a
(lookup table-based) sine wave. It can also do much more.

In its default mode, Mozzi works with a 16,384 Hz sample rate and a
32,768 Hz (not audible) PWM frequency.


Is there a Serial write buffer limit and does the Arduino reset if it is hit?

It turns out this problem had a very different cause, once I was able to eliminate the other variables. Having disconnected literally every component from the board and uploaded an empty sketch:

void setup() {}

void loop() {}

the board would still periodically reset itself.

I eliminated:

flushing the receive buffers,
eliminating all receives by disconnecting pins,
speeding up/slowing down the serial port/s,
speeding up/slowing down the GPS reporting rate,
auxiliary hardware,
code,
includes,
defines,
laptop power supply noise,
board revision in Arduino IDE,
Arduino IDE version,
USB port on laptop,
trying this hack to prevent the RESET pin from going low,
another Mega 2560 and a Due

None of the above influenced the issue.

The thing I did not think to check was whether the board would work with another power supply alone. This was a result of hunting for another power fault in service and with the laptop plugged in, finding a periodic, random reset.

Ultimately, I plugged the board into a monitor USB output, then a car charger power supply and finally found the issue was eliminated. Even plugging into another computer solved the issue. It appears that either the Arduino driver in Windows or the Arduino IDE software itself, would periodically poll the port, causing the board to reset. While the serial monitor was running, I assume the driver or IDE felt no need to poll the port, thereby leaving the board un-reset.


Arduino Mega read of serial encoder read at 1,024,000 baudrate?

I think the problem is that there is more to serial I/O than just bits coming in. Otherwise, if nothing was sending, you would always read 0 from the serial port. Serial has a start and stop bit, for example. I doubt you could use the hardware serial to read in random bits.

If you are going to do this in software, you will have less than 16 clock cycles per bit - enough time to run about 15 instructions. It is not impossible, but very difficult.

There are two ways to read the data in code.

Option 1: Disable interrupts, and hand-write assembler that takes exactly the right amount of time. If you branch, make sure all branches take the same amount of time. I think all assembler instructions on Atmel take 1 cycle. You will need to pad out your loop to a predictable size. At 1.024mhz, the clock will drift by 2.4%, which means you'll either have to supersample (e.g. take one sample every 12 instructions, then throw away the samples closest to the clock interval) or you'll have to make some loops longer than others. If you store 8 bits per byte (as opposed to having an array of 77 bytes, storing 1 bit in each, which would be quicker), then you might get away with making "move to next byte" a different length.  Try to measure each sample in the MIDDLE of the allowed period, or as close to it as you can. You may have to unroll your loops (i.e. instead of "repeat this 77 times", do "do it, do it again, do it again....).

Or you might be able to write an ISR - Your ISR would have to be very short, basically "write the current time to a pre-defined array". Now you have 15 instructions to get the data out, but padding it OUT isn't so critical. With this method, you will get one datapoint per CHANGE (rising or falling signal). I don't know if micros() would be quick enough. Then, once the read is complete, you can post-process the data at your leisure. The ISR will be called at the start of the clock cycle following the change in signal, so this is likely to be easier.

UPDATE:

Micros only has a resolution of 4 microseconds, so you will have to make your own "clock". The easiest way to do this, is to set a counter with about how long you think it will take (, then hand-code a loop to decrement this, until zero. As far as I can make out, the decrement loop should take 2 cycle (decrement the counter, if-not-zero jump back to decrement). So if you start it at 800, it should take 100ms to reach zero. Remember that the ISR will stop the counter for the duration, you will need to compensate. Make sure that this loop isn't optimized out! Your ISR will be: copy the (above) counter into an array, increment your array pointer by 1 (so next time you put it in a different slot in your array). After the counter reaches zero, disable your ISR, and find the difference between each number and the next; add a constant (worked out by trial and error), round to the nearest 8 (which should be pretty close). Divide by 8. The first result should be the delay to the start of the data (first 1); the second will be the number of consecutive 1's, then the number of consecutive 0's, etc.


Neopixel led strip stops responding after change in brightness

It is almost certainly a power issue. The Adafruit page about one of those types of Neopixels says:

  Don't forget, with 256 LEDs, you could use over 15A of current if you turn on all the LEDs on to white (which we really do not recommend because we don't think the flex PCB can handle that much current). Try to keep the current draw at under 5A ...

Increasing the brightness increases the current drawn. Do you have a heavy-duty power supply? Are the connecting leads sufficient for (say) 8 amps of current?

New information based on comments made

Based on comments by Lorenz I now think it is more likely to be that they are overheating.

  I have the strip embedded in a picture frame with epoxy resin over it.

That makes it difficult for the ICs to cool down, and LEDs generate heat. If you search for "neopixels heat" you find quite a few matches. Some suggestions made are to use a heat sink or a fan. If this isn't practical for you, then running at a lower PWM rate (ie. not as bright) and not as saturated colour, could help keep the heat down.

You don't want to "cook" one of the early pixels, because each one has to pass the data on to the next one in sequence, so if you lose an early one, you lose everything after it, particularly if you can't get at it to replace one.

Postscript regarding heat

I have been testing a NeoPixel with a temperature sensor. Displaying full white (255/255/255) it has reached about 44°C. So clearly it warms up. However this is in the open air with just some sticky-tape holding the sensor onto the LED. According to the spec the chip can operate at up to 80°C, so this is within range.

However if the whole thing was sealed in epoxy, then the heat being generated would have much less chance of escaping into the ambient air, and thus would be likely to get a lot hotter.


My code is not uploading to Arduino Uno, Please help!

First of all find out on which port the Arduino is connected by running the command : dmesg | grep tty. You should get [82893.921017] usb 1-1: cp210x converter now attached to ttyXXX with the ttyXXX COM port.
Then check if the port is visible Tools->Port. If the port is not visible then you have a permission issue.


Can I monitor data of variables while simulating Arduino on Proteus?

It is possible. By using several tools on "Virtual Instruments Mode" such as SPI-Debugger, I2C-Debugger, Virtual Terminal, or Logic Analyser.

  I would like to know how the code is running step by step so that I can find logical errors.

For example, you can use Virtual Terminal and print the value of variables you want to examine


Temperature sensor reading is higher than the actual temperature

Any chance you're printing Vin, and not TC?

500*(50.25/1024) = ~24.5

If not, please post as much of your program as possible


No, it's not possible, nor desirable. It's complicated and unnecessary.

What you have to do is:

Declare a volatile global variable (a switch).
Inside ISR, change that switch to signal that a break is needed.
Inside your loop (for, while, ...) test for that global variable and proceed.

This example print "This is the end" each time a button connected to pin 2 is pressed.

volatile bool fin = false; // The switch for ISR-loop communication.

void setup()
{
    Serial.begin(9600);
    pinMode(2, INPUT);  // Read a button or other signal.
    attachInterrupt(0, buttonISR, RISING);
}

void loop()
{
    if(fin) {
        Serial.println("This is the end");
        fin = false; // Reset the switch.
    }
}

void buttonISR()
{
    fin = true;  // Just raise the signal for the main loop.
}

This method keeps ISR ultra-short and there is no mixing between ISR's instructions and loop's instructions. All of your logic reside in the main loop.


That should be working fine.

I just logged into my Yún and changed its name by editing that file.  I then restarted avahi-daemon since that is what broadcasts its name (faster to restart the daemon that reboot the whole Yún).

Browsing to the new name worked fine.

matt@dell:~$ ssh root@arduino.local
root@Arduino:~# vi /etc/config/system
(edit the config file)
root@Arduino:~# hostname skybridge
(manually changing the hostname so I don't have to reboot)
root@skybridge:~# /etc/init.d/avahi-daemon restart
(restart the avahi daemon)

Browsing to skybridge.local now shows me the Arduino login as it should.

As a further test I have just rebooted my Yún so it runs everything from scratch and it still works fine.

There are a number of caches involved in the system, any of which may be getting in the way.  It could be that the browser has cached incorrect or out of date information about the FQDN (fully qualified domain name) for the name you have given your Yún, in which case just closing and re-opening your browser may help.  It may be that the mDNS lookup system on your computer (you haven't mentioned which operating system you are using, which is a big factor) has cached old or out-dated information for the FQDN, in which case flushing that cache may help (how you do that depends on your OS), or just rebooting your computer.

Incidentally, if you are on Linux (Windows lacks these basic networking facilities along with many other basic tools), you can query the network for your Arduino Yún with the avahi-browse and avahi-resolve commands.  OS X has similar tools, but I don't know off hand what the commands are:

matt@dell:~$ avahi-browse _arduino._tcp
+  wlan0 IPv4 skybridge                                     _arduino._tcp        local
^CGot SIGINT, quitting.
matt@dell:~$ avahi-resolve -n skybridge.local
skybridge.local 192.168.0.252


What type of box?
Howmany times/how easily do you want to remove the Arduino Mini?

Hot glue

Hot glue is the way to go in many occasions.

It does not conduct electricity, so is pretty safe. (Please check your specific hot glue first)
It sticks quite well, for quite a time. You should also check if it's water resistant or fit for your target environment though.

But, it may have some side-effects:

It can get quite messy (which does not look really professional)
It's not that easily removable and has to be "re-glued" when you want to stick it back.
It might be too sticky (in a carboard box, you won't be able to just rip out the Arduino, withouth damaging the box).

You could use double sided tape, which might actually work fine. Or atleast better/neater as the hot glue.

Sticky velcro

A neat solution would be sticky velcro. You can easily attach, detach and re-attach the arduino to the velcro. It looks quite fancy and should hold well.

Again, you should check the specific velcro, it might not last 1000+ times of re-attaching (become loose or smh). But will be a good option overall.

Extra

You can use mint-boxes as an enclosure. But they're usually made of tin or another conductive material. Please take care and cover the back of your arduino (or box) with electrical tape, to avoid shorts.

Extra-extra, you should (for "replacability") add connectors or headers to your Arduino. Since soldering the leads directly will still give the need to un-solder or resolder your Arduino when replacing.

Note on making your Arduino project a consumer item

You might save yourself quite some money by using a barebones arduino. Or actually, an ATmega 328P chip. Which is around 3€.
These will be a little more difficult to program, but might also look more professional.

You can also enable "program protection" fuse bits, so that others can't download the code from your arduino/microcontroller.


LDC paired with Arduino locks up and freezes. Out of SPRAM?

I found the problem! it was specific to my code and didn't turn out to have anything to do with ram or power. The problem was I hadn't detached the interrupt from the rtc when I woke it up with a button. It would freeze seemingly randomly because the rtc would fire an interrupt signal when the next minute ticked, while the arduino was awake. I guess it causes problems when you try to interrupt arduino's sleep and it's not actually sleeping. All I had to do was detach both interrupts when the button is clicked. Thank you all for your help :)


getHostByName always failing to find a valid ip

My CC3000 wifi shield was not working correctly. So I replaced wifi shield with a new one and solved the problem. It is very hard to identify a hardware fault when it is partially working. It seems that CC3000 connecting to the WIFI network. That confuses me. But when I read about the problem and tried replacing with a new board which was successful. By the way I learnt that this same problem can be occur when you are using a public wifi connection (example- University Wifi Connection). This question is a good source that answers the 2nd kind of problem.


Options for measuring position of garage door

A couple of possibilities occur to me. One would be to mount a rotary encoder on a rotating part of the door. Another would be to attach a reed switch to the track and a series of magnets to the door. I suppose you could do something with a proximity sensor as well.

How much precision do you need in the position of the door? What do you know that is deterministic? For example is the door transit time predictable? Is it a positive drive? Do you get to know when the door starts moving? That might be enough right there.

If you can say more about what you're trying to do it would make it easier to provide suggestions and insight.


Servo going up to the limit as soon as attached

https://www.arduino.cc/en/Reference/ServoAttach - This should answer it. The library you are using supports only 2 specific pins


What is the proper way to make library pin mappings configurable?

The method I use is to provide the pins as parameters to the constructor. Those pin numbers are stored in variables to use later in the .begin() function and elsewhere.

Most of the time I use initialization lists to keep things simple. For example:

class Something {
    uint8_t _cs;
    uint8_t _dc;

    Something(uint8_t cs, uint8_t dc) : _cs(cs), _dc(dc) {}
    void begin();
};

void Something::begin() {
    pinMode(_cs, OUTPUT);
    pinMode(_dc, OUTPUT);
}

Something mySomething(10, 8);


How does this eBay relay board connect to the Arduino

Your module consists of both an optocoupler (large black rectangular device) and a P-channel MOSFET driver circuit for the relay.

VCC and GND are used to power the MOSFET and relay, and so should be connected to a power source suitable for driving the relay (if it's a 5V relay then the +5V and GND pins of the Arduino - if it's a 12V relay then a 12V power supply).

The interface to the Arduino is through the optocoupler. The Arduino sees that as just an LED, so you can wire it up just like any other LED.  The circuit contains a current limiting resistor already, so you don't need to worry about that at all.  So you connect the - of the input to GND and the + to an IO pin, or connect the + to +5V and the - to the IO pin, depending on which polarity of drive you want to have.

The jumper is optional to allow you to create one of those two links on the board - say connecting - to GND or connecting + to VCC so you don't need the extra wire.


static means that the global will only be accessible inside the current translation unit.

volatile means that while(!wifi_connected){/*...*/} cannot be optimized to if(!wifi_connected)while(true){/*...*/}

These things are orthogonal. So you would use static volatile when you need both properties.


Can I use arduino and mobile phone screen to make a touch board?

First, find a suitable phone screen! Good luck. Most of the touch screens that I have found are resistive, and will never feel like an iPhone. Try googling "Arduino touch screen". Adafruit have a promising one.

Once you find your screen, you will need to interface to it. With luck it will come with a pre-built library. Otherwise you will be up for quite a lot of coding.


What's the fastest way to periodically communicate via serial?

Lowest possible latency in both ways. High latency would cause instability of controlled systems.

the fact that you are using a not-real-time OS introduce a lot of unpredictable latency, the use of a visrtual machine over that os then add a bit more.
Fast communication can be obtained increasing the baudrate, that will decrease the latency between the sample and the elaboration.
Also sending RAW data instead of string will be faster (no convertion AND less byte send), and finally decreasing the overhead caused by the protocol.

For example Firmata by default use a low baudrate AND will add a lot of overhead to send WHAT kind of operation is doing. Writing your own communication protocol is better.

For example: analogRead use 10bit, so you may send a raw int, 2 byte, 16bit, so 6 bit are lost.. or you can "compress" with a bit of bitwise operation 4 read (40 bit) into 5 byte (40bit, no bit loss) instead of 8(int size * 4)!

AnalogRead is a really slow operation by default on arduino (~200us), but can be faster if you set up a lower prescaler (attention, lower prescaler means less ADC precision. at prescaler 16 guaranteed precision is 8bit, if my memory is good)

  Extremely constant, possibly user-defined update period. Varying sample rate would cause inaccuracies in the control.

On the PC side, if you need micro/nano second precision you need a real time os, newest linux kernel add a new special schedule but i think is still hard to find documentation. If less precision is ok, just use a timer.

On the arduino side, using a hardware timer is the best way, see LeOS for a nice scheduler on arduino

Please note HardwareSerial on the arduino side use interrupt to send data, so using it inside an ISR (like you are doing now or with LeOS) is really usafe and deadlock prone.
Also ISR will "slow down" each others, as they cannnot be executed parallel; and analogRead is a realtivly slow operation..
I would use timer to set up a flag, and in the loop if i see the flag, start the analogread, Serial.write and finally Serial.flush (to be sure to not fill Serial buffer, causing a lot of trouble on the arduino reprogrammation reset)


Extracting a specific sequence of characters from an array

You can simply chop it up in place without requiring more than a few extra bytes of RAM using strtok():

char storebuffer[] = "ssid=abcdef&pswd=ghijk";

// Slice it into two parts around the &:
char *lefthalf = strtok(storebuffer, "&");
if (lefthalf != NULL) { // We found a & and split the string OK
    char *righthalf = strtok(NULL, "&");

    // Now you can slice each half around the =
    char *ssidtag = strtok(lefthalf, "=");
    char *ssid = strtok(NULL, "=");
    char *pswdtag = strtok(righthalf, "=");
    char *pswdtag = strtok(NULL, "=");

    Serial.print("SSID: ");
    Serial.println(ssid);
    Serial.print("Password: ");
    Serial.println(pswd);
}

The existing string gets chopped up and the pointers point to different places:

ssid\0abcdef\0pswd\0ghijk
^     ^       ^     ^
1     2       3     4

1: ssidtag
2: ssid
3: pswdtag
4: pswd


Arduino Uno Sensor DHT11 Failed to read from DHT sensor

There are several versions of the DHT11 library for Arduino out there. This is the one that worked for me: https://github.com/adidax/dht11. Here is a simple sketch to test the sensor with the output going to the serial monitor.

// 5k ohm pull up resistor is used on the data line.
// Sensor operates at 5VDC.
// Data line connects to Arduino Uno pin 3.

#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 3

// Sensor calibration. Start with 0 for each.
const int HumidityCorrection = -10;          // -10 worked with my sensor.
const int CelsiusTemperatureCorrection = 2;  // 2 worked with my sensor.

const float FahrenheitTemperatureCorrection = CelsiusTemperatureCorrection * 1.8;

// Update the serial display every 60 seconds.
const float UpdateSerialDisplay = 60000;

// Celsius to Fahrenheit conversion.
double Fahrenheit(double celsius){
  return 1.8 * celsius + 32;
}

void setup(){
  Serial.begin(9600);
  // Minimum wait for good data recommended is 1 second.
  delay(2000);
  Serial.println("DHT11 TEST PROGRAM ");
  Serial.print("LIBRARY VERSION: ");
  Serial.println(DHT11LIB_VERSION);
}

void loop(){
  Serial.println("");
  int chk = DHT11.read(DHT11PIN);
  switch(chk){
    case DHTLIB_OK:
      //Serial.println("OK");
      break;
    case DHTLIB_ERROR_CHECKSUM:
      Serial.println("Read sensor: Checksum error");
      break;
    case DHTLIB_ERROR_TIMEOUT:
      Serial.println("Read sensor: Time out error");
      break;
    default:
      Serial.println("Read sensor: Unknown error");
      break;
  }

  Serial.print("Humidity: ");
  Serial.print("\t");
  Serial.print(DHT11.humidity + HumidityCorrection);
  Serial.println(" %");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(DHT11.temperature + CelsiusTemperatureCorrection);
  Serial.println(" C");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(round(Fahrenheit(DHT11.temperature) + FahrenheitTemperatureCorrection));
  Serial.println(" F");

  delay(UpdateSerialDisplay);
}

Once you get this working you can add the LCD code to it. Here is a link to the DHT 11 Humidity & Temperature Sensor manual / data sheet: http://www.micropik.com/PDF/dht11.pdf


Accessing one code using another code on RobotDyn Uno+WiFi board

You can't 'access code'. You can write sketches to communicate for example over Serial or SoftwareSerial. You connect the pins of Serial interfaces RX to TX and let sketch in one MCU read or parse what the sketch in other MCU sent over Serial with print or write.
The onboard connection on Uno+WiFi board is over Serial. So you can't use USB and connection to esp8266 at the same time. But you could use SoftwareSerial like other use it with esp8266, if you connect some pins (for example 6 and 7) of Uno headers to Serial of esp8266 which is accessible on the esp8266 header on the board.


Sending minimal data between two Arduinos far away from each other

RS-485 is best (you can buy some modules for this from Adafruit, Amazon, eBay, etc), but you can use the built-in hardware RS-232 serial UARTs from each on pins 0 and 1 so long as the baud rate is really really low. The lower the baud rate, the longer the range can be because lower baud rates reject noise better (and the longer the cable, the worse the noise, since the longer the cable the more it acts like an antenna and an inductor and a capacitor). Here are some rough estimates of how far you can transfer regular-logic-level unbalanced RS-232 signals:

Source:
https://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/serial-distance.html
If this trend continues, you should be able to get like 120m at 1200 bps (baud), 240m at 600 bps, 480m at 300 bps, etc. maybe even up to > 1000m at 50 bps. I don't think the trend will continue like that, and we are using 5V TTL logic (signal voltage) levels here instead of RS-232's +/- 12V or so, so our logic levels are much worse and will have less range, so just use 50 baud and give it a shot:
// do on each Arduino
Serial.begin(50); // 50 baud = 10 bytes/sec throughput rate; see below

Note that for 8-N-1 serial communication baud rate, which is the default on Arduino, there are 10 bits per byte sent over the wire. This is because there is "one start bit, the eight data bits, and the one stop bit" for every 8-bit byte sent. That's an effective throughput data rate of 80%. This means a baud rate of 50 bps (bits per second) only can transmit 50/10 = 5 bytes per second. That's it! That's suuuuuper slow, but if it's fast enough for your application, it's fast enough!
I hypothesize 5V TTL twisted quad RS-232 communication between two Arduinos would have a maximum range at 50 baud of about 1000m/(24V span for regular RS-232 / 5V span for 5V TTL logic RS-232) = 208m. Just a crude guestimate. Please report back any findings you get from your experiments. I'd like to hear about it.
Assuming that this all does work, it would also be useful to start increasing the baud rate on each device until the data starts getting corrupted. Back off on the baud rate a little, and that's your maximum baud rate. Take that maximum baud rate and divide by 2 or 3, and that's your maximum "safe" baud rate perhaps. If you need throughput that is as high as possible, then that's what I'd do. Ex: maybe in your case 50 baud works just fine, so you increase it. At 1000 baud you start seeing corrupted data, so you back off to 800. At that point you no longer see corrupted data. So, divide that by 2 or 3 and you get a maximum "safe" baud for your setup of perhaps 800/3 = 267 to 800/2 = 400.
Try using a twisted quad cable (wires are twisted together in groups of 4) to reduce noise and increase range, and set the baud rates on each Arduino to like 50. You will need 3 wires connected between the Arduinos:

GND to GND
Tx to Rx
Rx to Tx

Power them each separately with ungrounded power supplies.
Communicate via Serial.write() and Serial.read() (so long as Serial.available() shows some data is available in the read buffer).
More on balanced vs unbalanced lines, and why I recommend "twisted quad" wire:
Normally, RS-232 is considered to be an unbalanced line transimission system. This means the impedance in the transmission wire is not equal to the impedance in the return wire, which would be a common ground between the sender and receiver, in conjunction with (in parallel with) an Earth ground through the building wiring and/or actually through the Earth...literally, the dirt you walk on. By powering each Arduino with an ungrounded power supply, such as a 2-prong power supply, however, which is common, there is no Earth ground connected to the Arduino. Furthermore, by only having a single transmission line active at any moment between two Arduinos, you have just balanced the transmission between them. Now, the out path is a single Tx signal from one Arduino to the other, and the return path has matching impedance, as it is your single, common GND wire between the two Arduinos. You now have balanced line RS-232 TTL logic level transmission between the two Arduinos. Balanced line transmission can have improved noise rejection and range by using a twisted pair between the two lines. In this case, however, there are 3 lines: Tx --> Rx, Rx --> Tx, and Gnd --> Gnd. So, you should use twisted quad wire, which means 4 wires at once are twisted together. Connect all 3 lines to the same twisted quad bundle. Again, remember, this assumes only one Arduino is transmitting at a time on one single wire in one single direction at a time (so as to not negate your return current through the GND line when transmitting on two lines, one in each direction, or double your return current through the GND line when transmitting on two lines each in the same direction [assuming you had multiple UARTS on each device]), thereby this usage creates a balanced line system since they also aren't truly grounded through a 3-prong grounded power supply. If these 2 requirements are met (1 Arduino transmits at a time, and at least one of them is not grounded to the building wiring), use twisted quad wire, as the system is balanced line communication. If it is not the case, because you are transmitting from each Arduino to the other at exactly the same time, or because both (not one) Arduinos are grounded to the building, thereby offering an alternative return path through the building ground wiring, then twisted quad cable will not benefit you, and you should use regular untwisted wiring.
Having said all that, experimentation is the real boss here. Try it out. if I didn't have twisted quad wire I'd try twisted pair, and if I didn't have twisted pair, I'd try untwisted wire.
Regarding your approach about using PWM to produce an analog output to be read by the receiving end:
Using PWM to produce an analog voltage to be read by the receiving end is an interesting approach. Without filtering, I think what you'd be doing is producing tremendous noise, however, literally producing electromagnetic radiation (think like low frequency radio or TV waves or something), where this huge 60m wire is your broadcasting antenna. If you put a 20k~50k resistor right at the sending end, however, and a 1uF capacitor right at the receiving end, however, to filter this PWM into an analog output immediately at the sending end, I think it would then eliminate your antenna effect where you are broadcasting something, and work much better, but still be highly susceptible to external noise influencing it. Give it a shot, but I suspect a simple set of digital pins to set HIGH or LOW on different pins to match different states would be much much much better than any analog signal at those lengths, with a 50 baud serial signal being the next best for signal-to-noise thereafter.
So, in order of best to worst signal-to-noise ratio (SNR):

differential pair (referenced to each other) digital HIGH/LOW values to represent states, which you update very slowly
RS-485 differential pair serial transmission
Note: for all of the following really low-speed digital signal sending scenarios, you might try it with the low-pass filter shown in the schematic below too, as it may help reject noise.
single-ended (referenced to GND) digital HIGH/LOW values to represent states, which you update very slowly
super low-speed SPI (including bit-banging it); ie: declare any digital pin a CLOCK_PIN, and any other digital pin a DATA_PIN. Set a clock pin LOW, set a data pin HIGH, set the clock pin HIGH. The clock transition tells the receiver (you have to code this up) to read the data pin, so you just read a 1 bit. Set the data pin LOW, set the clock pin LOW. The clock transition tells the receiver to read the data pin, so you just read a 0 bit. Leave the data pin low, set the clock pin HIGH again. You just sent another 0 bit, etc etc. Send data like this really slowly. It will work at great lengths--even better than asynchronous serial since it's synchronous.
asynchronous serial (+/- 12V true RS-232) at 100 baud
asynchronous serial (+/- 12V true RS-232) at 50 baud
asynchronous serial (5V TTL RS-232) at 50 baud
asynchronous serial (3V TTL RS-232) at 50 baud
analog value filtered with resistor and capacitor low-pass RC filter; update: I'd try this filtering layout for sending analog values via PWM (see schematic below, but use the higher resistor value I describe in my bullets underneath the schematic, rather than the lower value I show in the schematic); the filter may also be beneficial to help filter noise when doing low-speed digital communication too, so give it a shot in your 50-baud rate serial setup above too:

Send with analogWrite() (PWM); receive with analogRead().
Report back on this too please. I'm very curious if it would work.

unfiltered PWM---square wave antenna broadcasting who knows what--could result in an interesting broadcasting system for you. Add a transistor and you could really amp up the power and broadcast some interesting signals out! Get some good high power going here (1W~10W+) and maybe even get the government to find out who's jamming GPS and cellular? I don't know: could be interesting!

Schematic of low-pass RC filter to reduce noise between the two Arduinos when sending really low-speed digital signals (better), or slowly-changing analog signals (worse) between the two sides:

simulate this circuit – Schematic created using CircuitLab

For filtering the digital signals (ex: 5V TTL pseudo-RS232 serial at 50 to 100 baud):

Use 470 Ohms for each resistor, as shown above.
This results in a cutoff freq of 847 Hz, so stay below ~169 baud (cutoff_freq/5 = 847Hz/5 = 169 or so) for digital signal sending through this filter.

For filtering analog signals sent via analogWrite():

Since most Arduino pins have a PWM Frequency of 490 Hz, we need a cutoff frequency of ~490Hz/10 = 49Hz or lower to cleanly filter out the PWM frequency and result in a true analog output.
Using the calculator linked-to below, that means you should use R values of at least 10k each, which results in a cutoff freq. of 40 Hz. You can use 20k resistors each too, for a cutoff freq. of about 20 Hz.

To increase cutoff frequency to allow higher baud rates, decrease either R or C or both.
For a cutoff frequency calculator, see: https://electronicbase.net/low-pass-filter-calculator/#rc-low-pass-calculator --> "RC Low Pass Filter Calculator" --> enter, for example, 940 Ohms (470 x 2) as the resistor value and 0.2uF (0.1uF x 2) as the capacitor value to see that the resulting cutoff frequency for this low-pass filter is 846.57 Hz.

I'm no filter expert, but this is what I'd try. If someone sees some glaring errors in this filter or ways to improve it, please comment below the answer.
Extras:
Here's the Bode plot for the above series filter I show except with a 1k resistor and 0.1uF (100nF) capacitor followed by the same thing again. The purple line is the voltage we care about. Source: godfreyl, here.

The cutoff frequency here is 398Hz, which is where the -3db drop occurs, which corresponds to the half power and 70.7% voltage attenuation point. (sqrt(0.50) = 0.707, so 0.707^2 = 0.5)). You can read more about cutoff frequency here.

Additional reading:

https://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/serial-distance.html
Google search for "is rs232 balanced?"
https://www.idc-online.com/technical_references/pdfs/data_communications/tutorial_2.pdf
http://www.iec-usa.com/Browse05/DTBALUN.html
https://en.wikipedia.org/wiki/Signal-to-noise_ratio


Almost.

First it's char not unsigned char:

char ErrorMsg[5];`

Second you don't specify a size with strcpy:

strcpy(ErrorMsg, "OK");

There is a variant of strcpy called strncpy which copies at most n characters:

strncpy(ErrorMsg, "OK", 5);

That is used to prevent buffer overruns. But when working with string literals like that it's pretty pointless.


how to make GPRS/GSM SIM900 shield work with gps neo-6M module using Arduino UNO board

I think you are searching for a solution like this Interfacing GSM and GPS Module using Arduino where GPS and GSM modules can run together and receive data at the same time.

I tried bringing up both inside setup() and it blocked the other device. Here is some extract of the code (Note that rx,tx and baud rates may differ according to the modules).

SoftwareSerial gsm(7,8);
SoftwareSerial gps(3,4);

void setup() {
    Serial.begin(9600);
    gps.begin(9600);
    gsm.begin(4800); <--- This stopped receiving GPS updates
}

If you look for an advanced way of handling this situation, you may need to implement some light-weight threads (e.g Protothreads) and assign GPS and GSM modules to run in separate threads, so one device may not block send/receive of the other device. These Arduino forum answers may help for such approach.


How to get current time and date in arduino without external source?

An accurate enough way is to use the millis() function. It  will return the value in milliseconds since the start of the Arduino. If you start the Arduino at a specific time, you will be able to calculate the exact date and time.

Why not an external module?? An RTC such as the DS3231 in merely 5$ and it includes a temperature sensor for you!


Try using println instead of printin.  It stands for print line.


multiple definition of local variable in linking

The common practice is to write Arduino libraries using C++ classes:

  The core of the header file consists of a line for each function in
  the library, wrapped up in a class along with any variables you need.

class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

In this way you can specify what is private (variables and methods only seen within the class) and what is public (variables and methods that can be seen outside the class).  In the given example, the variable called "_pin" is private to the class Morse.

In your case, you would want to make a private class variable called "value".  Because it is private, you are free to re-use the name when not inside the class.


Getting two Arduinos to talk to each other via an optocoupler

In order to synchronize two deices transmitting any information you need a CLK signal. CLK stands for clock so basically you send a 1 each time you want to send a bit of data. But in order to do so you need one more wire and a CLK generator (usually the transmitter).
It is described very well in the video of Ben Eater about Reliable data transmission. So I recommend you watching the video since Ben covers a lot of important topics on data transmission and shows a arduino example of how to transmit and receive data properly.


First of all you should read the tech specs for Arduino Uno here:
https://www.arduino.cc/en/Main/ArduinoBoardUno

You will find this important information about power supply:

Operating Voltage   5V
Input Voltage (recommended) 7-12V
Input Voltage (limit)   6-20V

From documentation also:

Vin. The input voltage to the Arduino/Genuino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

5V pin.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

So answering you question: yes you should have supplied 12v on Vin. Not on 5v.

  Why does an adapter with 12V input not make the same blown up for arduino like in the previous case?

Because you are pluging 12v in the correct input, the 7-12v jack.

Another important link to read:
http://playground.arduino.cc/Learning/WhatAdapter


Send String to a function inside a class

Try with the new version, U8g2lib.

With that version, you can write code like this:

String t1 = "Grow";
String t2 = "Room";
u8g2.firstPage();
do {
  u8g2.setFont(u8g2_font_logisoso24_tf);
  u8g2.drawStr(32, 24, t1.c_str());
  u8g2.drawStr(32, 60, t2.c_str());
} while(u8g2.nextPage());


Bizarre compilation problem -- only compiles with the addition of a single Serial.println() line?

Update: This seems to be a linker bug. Quick fix: upgrade your
Arduino installation. See the end of this answer for details. What
follows is the first version of this answer, with a detailed explanation
of the error message.

You have a problem linking the interrupt vector table with your program.
I quite understand what the error message means, but I do not understand
how in the world you can possibly have this error. This should not
happen. I will try to explain the error anyway.

The Arduino Mega is based on an AVR chip. The AVR instruction set has
“jump” and “call” instruction that come in two flavors:

“absolute” jumps and calls (opcodes: jmp and call) can address the
whole flash memory, which means you can branch from any part of the
program to any other part, without restrictions.
“relative” (a.k.a. “PC-relative”) jumps and calls (opcodes: rjmp and
rcall) have limited range: they can only bring you to nearby places,
no more than 4 K from your starting point.

The relative flavors take less space and execute faster, they are thus
better if the destination is close enough. On the smaller AVR chips
(up to 8 K of flash), they can access the whole flash, then these
chips lack the absolute flavors.

How the vector table is normally linked

Every program you build for an AVR starts with an “interrupt vector
table”. This is a series of jump instructions that are automatically
executed whenever an interrupt triggers: if the n-th supported
interrupt triggers, then the hardware automatically loads and executes
the n-th jump instruction, which will jump the execution of the
program to the corresponding ISR (interrupt service routine). The
table is chip-specific: on the smaller AVRs (up to 8 K), it's a
table of rjmp, whereas on the bigger ones it's a table of jmp. This
table is part of the CRT (C run time) provided by the avr-libc library
in a file named crtXXX.o, where XXX is a code identifying the chip. The
Arduino Mega being based on the ATmega2560 chip, it's CRT is crtm2560.o.

I disassembled my own copy of crtm2560.o and found this vector table:

00000000 <__vectors>:
   0:   0c 94 00 00     jmp 0
   4:   0c 94 00 00     jmp 0
   8:   0c 94 00 00     jmp 0
   ...
  e0:   0c 94 00 00     jmp 0

You can see these are all jmp instructions (absolute flavor), as
expected for any AVR with more than 8 K of flash. The address of
the jump, however, is always 0, which is obviously wrong. This is
because the proper addresses cannot be known until the program is fully
built. When you build your program, the linker will put all the pieces
together. It will then know where the ISRs are, and it will patch the
vector table to make it correct. This kind of patching is known as
“relocation”, and the linker performs this based on some “relocation
records” included in the CRT. Here are the relevant records from my copy
of crtm2560.o:

RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_CALL        __init
00000004 R_AVR_CALL        __vector_1
00000008 R_AVR_CALL        __vector_2
...
00000090 R_AVR_CALL        __vector_36  [*]
...
000000e0 R_AVR_CALL        __vector_56

The record I marked with [*] means: “at offset 0x90 into the vector
table there is an absolute jump or call instruction, and the instruction
should be modified to point to __vector_36”. This tells the linker
how to fix the table when building the program.

If I instead disassemble a CRT for a smaller chip, I get a smaller table
made of rjmp (instead of jmp) instructions, and the relocation
records look like this:

RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_13_PCREL    __init
00000002 R_AVR_13_PCREL    __vector_1
00000004 R_AVR_13_PCREL    __vector_2
...
00000032 R_AVR_13_PCREL    __vector_25

These records mean “at offset XXX into the vector table there is a
PC-relative jump or call instruction, and the instruction should be
modified to point to __vector_XXX”.

Your error message

Your error message provides the following information:

“crtm2560.o”: this is your CRT, where the vector table and the
relocation records live.
“.vectors+0x90”: this means the problem is at offset 0x90 into the
vector table.
“R_AVR_13_PCREL against symbol `__vector_36'”: this means there
is a relocation record of type R_AVR_13_PCREL (PC-relative jump or
call) referencing __vector_36. Here seems to be the problem.
“defined in [...] core.a(HardwareSerial.cpp.o)”: this __vector_36
is part of the serial port code from the Arduino core library.
“relocation truncated to fit”: __vector_36 is too far to be reached
by a PC-relative jump, thus the linker could not relocate properly.

The problem seems to be that the relocation record is of type
R_AVR_13_PCREL, which is what you expect on smaller chips but not on
your ATmega2560. You normally expect R_AVR_CALL.

Now, about the strange behavior: the exact point where the ISR lands
when the program is built is difficult to predict. Add or remove a few
lines in your code and the linker may bring the pieces together in a
different order. Then, the infamous __vector_36 may end up being in
range or out of range of a relative jump. Given the nature of the error,
the behavior you find “strange” is actually quite normal.

Further debugging

The root of the problem seems to be an incorrect relocation record in
your CRT. You can try to disassemble the CRT to see what is wrong:
search your computer for a file named crtm2560.o, probably in
/Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/avr/lib/avr6
or a similar place. The tool needed for disassembling is called
“avr-objdump” and should be hidden somewhere in your Arduino
installation folder. Once you find the files, start a terminal and type

/path/to/avr-objdump -d /path/to/crtm2560.o

with “/path/to” replaced by the actual paths. You should see something
very much like the first listing of my answer, with lots of jmp
instructions. If you have rjmp instructions instead, then something is
already wrong at this level.

To see the relocation records, type:

/path/to/avr-objdump -r /path/to/crtm2560.o

The output should look like my second listing, with lots of R_AVR_CALL
records. If you have R_AVR_13_PCREL instead, the records are wrong.

If this is the problem, then the obvious fix would be to replace the
broken CRT with a sane one. You may try to reinstall the whole Arduino
package. If you still have a corrupted CRT, you should report the error
to the Arduino folks. Then you may try to fetch a fresh copy of the
avr-libc and replace the relevant
parts of your Arduino installation. Replacing just the CRT may or may
not work: I don't know whether the last version of the CRT has
incompatibilities with older versions of the rest of the libc.

Update: this is a linker bug

I did some research, and I now believe you have hit a linker bug. There
is a gcc option called -mrelax that allows some link-time
optimizations. One if them is to have the linker replace some absolute
jumps and calls by the smaller and faster relative ones. Obviously, this
is only possible if the target address is within reach of the relative
jumps or calls. There was a bug in old versions of the GNU linker (up to
2.22) where, under some obscure circumstances, it would erroneously
believe the target was reachable, only to find out later that it was
not. This bug mainly affected the interrupt vector table, producing the
kind of error message you are seeing now.

Here is a partial timeline of this bug and its fix:

November 2011: this is filed as
bug 13410
on the bug tracker for the GNU binutils package.
January 2012: Vidya Praveen, from Atmel, publishes a fix.
February 2012: the fix is committed to the development version of
binutils.
October 2012: GNU binutils 2.23 is released, including the fix.
The same month, the bug is reported again as
issue 1071
on the Arduino issue tracker.
June 2013: Paul Stoffregen links this new issue to the old bug.
June 2014: Arduino gets an updated
toolchain
including binutils 2.23.2, which fixes the bug in the development
version of Arduino.
July 2014: Arduino 1.5.7 beta is
released including the
updated toolchain.
September 2014: Arduino 1.0.6 is released with the old toolchain.

A workaround for the bug has been
published by Mark Anderson on stackoverflow. The real fix, however,
would be to upgrade to the latest Arduino package (1.6.1 as of this
writing).


Unable to connect to Linux Environment (Linino AR9331 Interface) in Arduino Yun

Try uploading YunSerialTerminal example, opening the serial monitor and pressing the YUN RST button. You should see the linux side starting.

If it starts but it looks somehow bricked, you could try following the http://arduino.cc/en/Tutorial/YunUBootReflash tutorial.


Accelstepper.runToPosition() is working fine. Accelstepper.run() does nothing

You didn't include any code for us to see what the actual issue is, but I'm willing to guess that you didn't take into account that the run command requires repeated firing.

If your program comes to a point where there's an instance of runToPosition, the blocking function stops the program until the stepper reaches the position specified.

When your program comes to an instance of run(), it fires off a pulse and carries on reading. So you have to use a loop.

stepperMotor.moveTo(3000);
stepperMotor.runToPosition();
// reaches destination

stepperMotor.moveTo(3000);
stepperMotor.run();
// moves a single step

stepperMotor.moveTo(3000);
while (stepperMotor.distanceToGo > 0) {
stepperMotor.run();
}
// reaches destination

The reason you'd use run over runToPosition is to allow for continuous operations / parameters to be executed. For example, two stepper motors running simultaneously:

stepperMotor1.moveTo(5000);
stepperMotor2.moveTo(3000);
while ((stepperMotor1.distanceToGo > 0) && (stepperMotor2.distanceToGo > 0)) {
stepperMotor1.run();
stepperMotor2.run();
}
// Both motors will run, but will both stop when either of them reaches their destination.

Depending on the speed of your microprocessor, you can create some sophisticated instruction sets for your motor(s).


Matlab too many input arguments using csvread

You should improve your question and it seems not being related with arduino at all. However, what I think you are trying to do is to auto generate the name of the file you use in cvsread accordingly to the value of y. This can be done using sprintf, in your case for the first expression csvread(sprintf('t%d_25.csv',y),1,1).
Although, the structure of your code seems really messy take a look at your end instructions.


How to keep accurate millis() while using ADC_sleep mode?

Rather than trying to update TCNT0, it might be better to track the number of cycles lost to ADC conversions, and in an intermediate routine – eg, omillis() – compensate for those cycles. [Edit:  See better alternative, below]

In more detail:

• At each conversion, add about 128·13 cycles (or perhaps 128·13.5, to account for average prescaler delay) to a cycle counter:
 long lostcycles; ...; lostcycles += ADCcycles;

• Within each omillis() call, say return millis()+lostcycles/16000

• Or perhaps say return millis()+lostcycles>>14 to avoid wasting time on a division.  This would be off by 2% on the correction, but I presume the correction is small, say 5% of total time, leading to about 0.1% error because of using a shift instead of a divide.

  Re: “I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230”

That's incorrect [if using suggested approach].  Even if the timer 0 overflow is handled a hundred microseconds late, it will be handled ok. [As noted in Edgar Bonet's comment, a method that just adds to TCNT0 without checking arithmetic overflow, as in original approach, could miss a timer tick.]

Note, the example code using SLEEP_MODE_ADC in the “Sleep during reading” section of ADC conversion on the Arduino on Gammon Forum suggests that one should check for the case where a timer or other interrupt occurs during an ADC conversion.  While SLEEP_MODE_ADC stops clkI/O, clkCPU, and clkFLASH, it leaves Timer 2, WDT, and some other potential interrupt sources active.

A better alternative:

As Gerben points out, it's slightly cleaner to update the count variable maintained by millis(), rather than using an intermediate routine.  For background, refer to his answer to an earlier question.  Here is an adaptation [untested] of the idea to the current case:

unsigned int lostcycles=0;
...;
void accountForADC() {
  enum { ADCcycles = 13*128 + 64;  ms_cycles=16000 }; // adjust appropriately
  extern volatile unsigned long timer0_millis;
  lostcycles += ADCcycles;
  while (lostcycles >= ms_cycles) { // This loop usually runs one pass only
    byte statusReg = SREG; // Save interrupt status
    cli();                 // Turn off interrupts
    ++timer0_millis;       // Need interrupts off for atomicity
    SREG = statusReg;      // Restore old status
    lostcycles -= ms_cycles;
  }
}

After startup, on the tenth call to accountForADC() this code would add 1 to timer0_millis to account for a millisecond lost to ADC conversions. lostcycles -= ms_cycles would set lostcycles to 1280.  After another 9 calls we again add 1 to timer0_millis and reduce lostcycles; and so forth.


Okay, I figured out... this two prints the right number:

sprintf(dt,"%llu", t);
snprintf(dt, 18, "%llu", t);


Wemos D1 mini and JSN-SR04T-2.0: Type of power supply affects the sensor readings

Try a different supply or computer, it sounds like that one has a lot of ripple and or noise on it.  Not all USB power supplies are clean and some do not have much filtering.


As this image from Okdo Page on LED Driving shows, there are two ways to drive an LED from a GPIO output pin:

In the Active HIGH case, a HIGH output on the GPIO will turn the LED on since that will source current out of the pin and through the LED into ground.
In the Active LOW case, a LOW output on the GPIO will sink current from the +V supply into the pin.
In your case the LED is hooked up in the Active LOW configuration and so to turn it ON you must set the pin to LOW.
I'll add that these ESP32 boards are made by many different manufacturers and they are not all identical.


connecting a small motor to arduino using a transistor

I like your thought process (even though it might not be completely correct), I've seen how little thought were put in for such simple circuit design in the Arduino community, including from some Youtuber celebrities who teaching Arduino and claims to have an EE degree.
BF547 is an RF amplifier transistor, not for switching application, it would be better to use an NPN transistor such as 2N3904 which is designed for switching application and has a Ice of 200mA.
Your resistor value is too high. If your motor is designed to operate at 100mA 3.3v condition, you would want your driver to provide AT LEAST that current. Assuming your are driving the transistor with 5V out from an Arduino, a 1k bias resistor would limited the Ibe to (5 - 0.7Vbe)/1000=4.3mA, take a very conservative DC current gain of 30 (it typically in the range of 30 - 80 for switching transistor, and hfe could be in the range of 100 - 300 when frequency go up, but this will not be the case for Arduino even you drive the motor using PWM), which will capable to deliver Ice of 4.3 x 30 = 129mA. This should meet your Motor requirements.
You would need a protection diode connected between 3.3V and collector with its cathode connect to 3.3V and its anode connect to the collector of the transistor. An 1N4148 (max If=200mA) would be okay for this specific motor, or even better, use any Schottky diode with current and voltage limit higher than your application).


Get the distance to non perpendicular surface

You mean to say that you get proper reading when the surfaces are FLAT?
Ultrasonic sensors have this property that the waves emitted from then are only 15 degree from the line of sight, but this means that you can surely calculate distance of objects having a curved shape. The only condition is the object should be directly in a straight line


replacing #define with typedefs for bracket scope

It is possible to use "namespace { ... }" to create local defines for a *.cpp file.
In the Arduino IDE all *.ino files are combined in a single *.cpp file, therefor the "namespace" is not very useful.

When you create new tabs in the Arduino IDE and name them *.cpp, then you have different *.cpp files. Then you can use the "namespace" to create defines that are only valid for that *.cpp file.

More info: Hackaday: Using Modern C++ Techniques with Arduino


There is no one sensor that is perfect, but some are more reliable than others.

Yes, the temperature and humidity can play an important role in your sensing, and has to be taken into account. That's not to say that things like Ultrasound don't have a place in the scheme of things.

There's one word you need to think about here: Correlation.

If one single sensor isn't completely reliable then add a second that works in a different way. If both of them agree that there is someone in the shower (i.e., the sensors correlate) then the probability that there is actually someone in the shower is considerably higher.

The great thing about a shower is you are working in a defined enclosed space. That makes it much easier and there are plenty of sensors which, when combined with others, would be quite good at reliably sensing the presence of someone in that enclosed space.

Some ideas:

Ultrasound above the person's head

Pros:

Simple to arrange.
Safe.

Cons:

Can be fooled by the water from the shower head.
Steam isn't good for them.

Infra-red distance

Pros:

Accurate
Can be sealed

Cons:

Expensive
Harder to work with
Can be blocked by steam

Horizontal infra-red beam

Pros:

Can be positioned outside the shower glass with a reflector inside
Safe

Cons:

Small sensing area
Can be blocked by steam

Pressure sensor

Pros:

People weigh more than water so is very reliable
Simple to interface

Cons:

Hard to install safely
Needs to be completely waterproof and sealed.
Could be a shock hazard if not waterproof

You notice I haven't mentioned PIR. I'm not a fan of PIR for sensing the presence of humans. They work by detecting moving heat sources. If the person is moving (entering an area, walking round a room, etc) then they get detected. If the person stands still (as is often the case in a shower) it "forgets" they are there.

Of the choices above (and I am sure someone would come up with others) I would probably opt for the infra-red beam. Maybe split it into a V shape to cover more area - that is, the beam enters the side of the shower at an angle, strikes a reflector on the shower wall, and is reflected back at another angle. The detector is then placed away from the emitter. You could also have a second set to give better coverage.

Infra-red distance measuring in/on the ceiling could be used to improve correlation and thus the probability that there is actually someone there.

I'd stay away from pressure sensing unless you can get hold of a proper waterproof pressure sensing mat designed for in-shower use. Don't try and make one yourself, waterproofing isn't an easy task, especially when people stand on it all the time.


Circuit diagram for ACS712 and ZMPT101B with ESP8266 using ADS1115

Step one is to get the ADC working.  Once that is done everything else will fall pretty much into place.

The ADC you have chosen is an I2C device.  The ESP8266 doesn't have I2C as such, but it does provide a software-emulated I2C implementation.  This can be used on any pair of pins, but the default ones are GPIO4 for the data (SDA) and GPIO5 for the clock (SCL) (this corresponds to the Arduino Uno using pins A4 and A5 for I2C, so it should be easy to remember).

Once you have that working the wiring for the rest is the same as for any other system. The only thing that differs is that your analogue inputs are on the ADC chip, not the main module.

Here's a block diagram to get you started:

simulate this circuit – Schematic created using CircuitLab

This is assuming:

Single voltage output from each of your sensor modules
I2C pullup resistors provided by either ESP8266 or ADS1115 (add your own if not)
All modules providing the required support components for the chip


power nodemcu with battery and LDO, what if battery is empty?

As with any electronics, once you get outside of normal operating parameters, behaviour becomes undefined. It's up to you to avoid that.

The smartest thing to do is to employ a battery protection circuit or some means to shut down the system (or prevent it from waking up from deep sleep) before the voltage drops too low. This will also prevent your battery from damage by overdischarging it.

The ESP's minimum operating voltage according to its datasheet is 3.0V. Below that, behaviour is undefined but you can expect unreliable operation, crashes or even permanent damage. If you're writing to Flash memory when below the minimum voltage, the Flash might become corrupted (including the program the ESP is running).


How to emulate an analog potentiometer with PWM

Adding to Ricardo's answer:

PWM can do the job, sort of. You need a low pass filter (LPF) to convert the PWM to an analog voltage and an amplifier to take it from 0-5 to 0-10V. Or you can get a dedicated digital-to-analog (DAC) chip but that will obviously be more expensive than a resistor and capacitor for the LPF.

Here's some tutorials on converting your PWM to an analog voltage:

Analog-Output: How-To
Arduino’s AnalogWrite – Converting PWM to a Voltage

Then you need to basically double the voltage. You do that with an operational amplifier. The resistors you pick for the op amp set its "gain", in this case you want it to be 2 so you can go from ~5v (max output) to 10v.

Here's an example of that: My First OP-AMP Circuit


Upload with esptool fails with "espcomm_send_command: can't receive slip payload data"

This is a known issue with the included esptool, and for the Arduino IDE there are quite a few blog posts to be found on this problem. But most are outdated, and are not applicable when using PlatformIO with some other IDE. So, February 2016:

Install esptool.py

git clone https://github.com/themadinventor/esptool/ (or download the ZIP file)
cd esptool
sudo python setup.py install

When using Arduino IDE

Open ~/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/platform.txt.
Find the line tools.esptool.upload.pattern and disable that by prefixing with a hash. Check that your version only mentions -ca 0x00000, not -ca 0x10000 as well (like in most outdated blog posts):

# tools.esptool.upload.pattern="{path}/{cmd}" {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp "{serial.port}" -ca 0x00000 -cf "{build.path}/{build.project_name}.bin"

Add the following, referring to the esptool.py you installed above and also using different command line parameters:

# Fix for espcomm_send_command: cant receive slip payload data
tools.esptool.upload.pattern="/path/to/new/esptool.py" --port "{serial.port}" --baud {upload.speed} write_flash 0x00000 "{build.path}/{build.project_name}.bin"

Restart the IDE.

(One might be tempted to just change tools.esptool.path and tools.esptool.cmd instead, but beware that the command line parameters need changing as well.)

When using PlatformIO

You will find the same platform.txt file somewhere in ~/.platformio/packages/framework-arduinoespressif/platform.txt, but that file is not used for the upload. Instead:

In platformio.ini add:

# ...or whatever your port is named
upload_port = /dev/cu.usbserial
extra_script = /path/to/platformio_extra_script.py

Create a new file /path/to/platformio_extra_script.py:

# Custom settings, as referred to as "extra_script" in platformio.ini
#
# See http://docs.platformio.org/en/latest/projectconf.html#extra-script
# See https://github.com/platformio/platformio/issues/426

from SCons.Script import DefaultEnvironment

env = DefaultEnvironment()

# Must be full path, or use
# https://docs.python.org/2/library/os.path.html#os.path.expanduser

env.Replace(
    LOCAL_UPLOADER="/Users/arjan/path/to/new/esptool.py",
    LOCAL_UPLOADERFLAGS=[
        "--port", "$UPLOAD_PORT",
        "--baud", "$UPLOAD_SPEED",
        "write_flash", "0x00000",
    ],
    UPLOADCMD='$LOCAL_UPLOADER $LOCAL_UPLOADERFLAGS $SOURCE'
)


Having really weird experience with string concat

+ on const char * increments the pointer. only String has + overloaded as concatenation of the right operand (not left). so "abc" + str + "efg" will not work even if str is String. What will work is String("abc") + str + "efg", but small Strings will fragment the heap memory of the MCU very fast and the sketch will crash.

Print the parts directly to serialSIM800 or use snprintf to build the strings or try CStringBuilder from my StreamLib


Soldering Arduino Pro Mini's disaligned pins

That's indeed quite an problem.

If you don't mind losing 2 analog pin, you could solder some jumper-wires between A4 and A2; and between A5 and A3. Then you could connect your I2C lines to pins A2 and A3.

But you have to be careful to never set pins A2 and A3 to OUTPUT in your software. If you want to be super-duper safe, you could cut the trace from the header pins going to the TQFP-chip. See the image below.


Stream video from camera to mobile and send control signal back from mobile to Arduino via WiFi

You need good MPU with enough buffer size and nand size for such an intense process

Search esp modules

Thanks.


How to compile, upload and monitor via the Linux command line?

I use the command-line interface to the arduino command.

I run it like this:

arduino --upload sketch/sketch.ino --port /dev/ttyUSB*

There is a page which describes other command-line tools, like inotool. That page also has an example Makefile. These alternatives seem enticing, but apparently, as of this writing, none of them work. I'm assuming this is due to some recent changes in Arduino IDE distribution files which they depend on.

Running arduino as above is a bit slow, because it has to load Java I guess, but at least it works. There is also an arduino-builder command that comes with the Arduino IDE distribution. As of this writing, it was not sufficiently well-documented for me to be able to figure out how to use it. For instance there are no example command lines in the README or in any of the tutorials I came across, and I couldn't figure out how to use it to upload code to the board. However, presumably it is able to give us a faster compile than arduino. The README also mentions being able to reuse object files from a previous compile, so there is some make-like functionality.

To view serial output I use something like

stty -F /dev/ttyUSB* 1000000 raw -clocal -echo
cat /dev/ttyUSB*

The number 1000000 should match the number you pass to Serial.begin() in your board code. You can also use screen if you have a board program which is appropriately interactive, or you can use whatever utility to write directly to the device. By the way, my Due shows up as /dev/ttyACM0 (rather than /dev/ttyUSB0 for the Uno).


Use website to communicate with Arduino WirelessProtoShield

Arduino wifi web server: http://arduino.cc/en/Tutorial/WiFiWebServer just modify the webserver to show a "open" button and to receive a post request and open the door.


Arduino unable to read from XBee Series 2

As I mentioned in my comments to your question, if you are using this library
then it doesn't actually support AT mode. In fact, AT mode (otherwise known as Transparent Mode) is simply attached to the Serial port and accessed directly through the Serial object.

Example: put this into your Arduino attached to the AT Router.

#define LED 13

void setup() {
    pinMode(LED, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(previous != millis()/1000){
    previous = millis()/1000;
    char buffer[5];
    sprintf(buffer,"%04i",previous);
    Serial.println(buffer);
   digitalWrite(LED, !digitalRead(LED));
  }
}

Then open the console on the XCTU software on the API Coordinator watch the packets.

You will see above the received packets from the router. Because the coordinator is in API mode, you see it like this. (In AT mode, you will see the raw packets.

Ichose numbers to send because they are easy to read in this form. Packet 0102 appears in the packets data as 30 31 30 32 0D 0A

In AT mode there is no packet confirmation, validations, status or anything. They are all handled "transparently".

As a side note, I've seen many references that both XBees need to be in the same mode. That is, in fact, incorrect. If we modify our source to include Serial.read you would see data the other way as well.

edit: I thought I would add communications between AT Router and API Coordinator. I have modified the code in the Router to receive a constructed packet from the Coordinator via the XCTU software.

#define LED 13

boolean serialComplete = false;
char bufferIn[64];
char bufferOut[5];
int count=0;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(serialComplete) {
    Serial.println(bufferIn);
    serialComplete=false;
    count = 0;
    memset(bufferIn,0,sizeof(bufferIn));
    digitalWrite(LED,!digitalRead(LED));
  }
  if(previous != millis()/1000){
    previous = millis()/1000;
    sprintf(bufferOut,"%04u",(uint16_t)previous);
    Serial.println(bufferOut);
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n' || inChar == '\0') {
      bufferIn[count++]=0;
      serialComplete = true;
    } else {
      bufferIn[count++] = inChar;
    }
  }
}

Then in XCTU construct a packet for the Coordinator. I'm using version 6.1.0.

and click "the create frame using form generator tool"

here is the packet being received by the router. I am only sending 9999 nul terminated.

Then once the pair are running, you can send the constructed packet from the XCTU software and it will be received by the router.


I managed to verify code from terminal by invoking /Applications/Arduino.app/Contents/MacOS/Arduino --verify lab.ino BUT this command automatically starts the IDE and exits it afterwards. Even with an IDE instance open it will start a new one. This is annoying since it will switch the active workspace away, but it kinda works. See arduino manpage.


Establishing wireless comm. between PC and arduino pro micro to exchange speech and gyro data

The wireless medium you choose is largely irrelevant.  The important thing to realise is that it's not (in most cases) the wireless medium that is communicating with the computer.

Most wireless mice use the nRF24L01+ (or rather the integrated SoC equivalent) to communicate. They use a USB dongle plugged into the computer for that communication. The computer has no clue what an nRF24L01+ is, but it does know what a USB mouse is. So there is a microcontroller in the dongle which receives data from the nRF24L01+ and interprets it, and sends the right instructions over USB to make the computer think it's a USB mouse.

What the data is that's sent over the wireless, and exactly what form that wireless connection takes, is completely irrelevant as far as the computer is concerned.  In general one if the SoC equivalent to the nRF24L01+ (such as the nRF52810) is chosen because it's a single chip solution with a simple to use wireless protocol, which makes for cheap and easy development and implementation.

The only exception to this general rule (and there is always an exception to every rule) is Bluetooth. This is because there is the concept (as far as the computer is concerned) of a Bluetooth mouse. So it is possible, using the right Bluetooth adaptor on your Arduino, for the computer itself to see the Arduino as a Bluetooth mouse. This can be harder to implement using small microcontrollers, but results in a potentially lower cost solution with fewer components.

The simplest solution for you, though, is probably:

One Arduino that has a native USB connection (Pro Micro, Leonardo, etc - anything ATMega32U4 based)

This will be connected directly to the computer and programmed to emulate a USB mouse

One Arduino that best suits your sensors (probably doesn't really matter what for this. Mini? Micro? Nano? Uno? They would probably all do fine).

To this you attach your sensors, your voice recognition, etc.

A pair of wireless connectivity modules of some form

I'd recommend the nRF24L01+ - simple to use, has a very convenient packet-based protocol, cheap, and there's plenty of examples and libraries out there.  These are connected to both Arduinos and are used to communicate between them.

Then it's up to you to decide what information gets sent between the Arduinos to make the one connected directly to the PC send the right mouse movements.


Arduino Uno R3 ISR does not work on pin 2?

never use Serial inside an interrupt handler, increment a (volatile) variable and print it in the loop().


Is there any way I can stop the Arduino Mega 2560 from resetting all variables after losing and reconnecting power?


How to connect mini jack output to arduino mini pro and send sound to it?

The Arduino Uno / Mini Pro is not really the right tool for the job. It has no native audio output such as a 3.5mm jack.

Having said that I am sure it can be done - but it won't be the best quality sound. I have no doubt that it can be achieved with one of the following methods:

using the tone() function.
by using a R-2R resistor ladder network and some sort of amplification circuit.

The Arduino Due and the Arduino M0 / M0 Pro both have inbuilt DAC's, meaning that they can output analog signals which can be used to drive a speaker circuit.

Another option is to use a Raspberry Pi which has a native 3.5mm audio jack.


Arduino Ethernet Client crashes after obtaining values from string

Using String, which uses dynamic allocation/deallocation on the heap is not advised in embedded platforms, as this can quickly lead to heap fragmentation, eventually leading to memory exhaustion, heap/stack collision...

First off, you should try to replace all String usage, everywhere in your program, with C-tyle strings, i.e. char* or char xxx[...] along with dedicated C functions to deal with them: strchr, strstr, strcpy, strcat, strtok, atoi...

Second, you can avoid using global variables and use the stack for many of them.

void loop() {
    ...
    if (client) {
        char readString[101];
        const int READ_STRING_SIZE = sizeof(readString) - 1;
        int readIndex = 0;
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();
                if (readIndex < READ_STRING_SIZE) {
                    readString[readIndex++] = c;
                }

                if (c == '\n') {
                    // Terminate the read string
                    readString[readIndex] = 0;
                    Serial.println(readString);

                    // Prepare for next reeading
                    readIndex = 0;

                    client.println("HTTP/1.1 200 OK");
                    ...
                    client.stop();

                    // convert readString to all uppercase
                    for (i = 0; i < strlen(readString); i++)
                        readString[i] = toupper(readString[i]);

                    bool b = false;
                    bool r = false;
                    bool g = false;
                    int blue, red, green;

                    // Look for 'B' value
                    char* bb = strchr(readString, 'B');
                    if (bb != 0 && isdigit(bb[1]) {
                        blue = atoi(&bb[1]);
                        analogWrite(11, blue);
                        delay(500);
                        b = true;
                    }
                    // Same for 'G' and 'R' value
                    ...
                    if (b && r && g) {
                        Serial.print("CHANGING RED TO: ");
                        Serial.println(red);
                        Serial.print("CHANGING GREEN TO: ");
                        Serial.println(green);
                        Serial.print("CHANGING BLUE TO: ");
                        Serial.println(blue);
                    }
                }

                if (strstr(readString, "PIN6") != 0) {
                    digitalWrite(6, !digitalRead(6));
                    ...
                }
            }
        }
    }
}

In this sample code, we have completely removed dynamic memory allocation.


I made this video and github just for this about a year ago.

And here is the code:

/*
2-axis joystick connected to an Arduino Micro
to output 4 pins, up, down, left & right

If you are using pull down resistors, change all the HIGHs to LOWs and LOWs to HIGH.
This skectch is using pull up resistors.

*/

int UD = 0;
int LR = 0;
/* Arduino Micro output pins*/
int DWN = 13;
int UP = 12;
int LEFT = 11;
int RT = 10;
/* Arduino Micro Input Pins */
int IUP=A0;
int ILR=A1;

int MID = 10; // 10 mid point delta arduino, use 4 for attiny
int LRMID = 0;
int UPMID = 0;
void setup(){

  pinMode(DWN, OUTPUT);
  pinMode(UP, OUTPUT);
  pinMode(LEFT, OUTPUT);
  pinMode(RT, OUTPUT);

  digitalWrite(DWN, HIGH);
  digitalWrite(UP, HIGH);
  digitalWrite(LEFT, HIGH);
  digitalWrite(RT, HIGH);

  //calabrate center
  LRMID = analogRead(ILR);
  UPMID = analogRead(IUP);
}

void loop(){

  UD = analogRead(IUP);
  LR = analogRead(ILR);
  // UP-DOWN
  if(UD < UPMID - MID){
   digitalWrite(DWN, LOW);
  }else{
   digitalWrite(DWN, HIGH);
  }

  if(UD > UPMID + MID){
   digitalWrite(UP, LOW);
  }else{
   digitalWrite(UP, HIGH);
  }
  // LEFT-RIGHT
  if(LR < LRMID - MID){
   digitalWrite(LEFT, LOW);
  }else{
   digitalWrite(LEFT, HIGH);
  }

  if(LR > LRMID + MID){
   digitalWrite(RT, LOW);
  }else{
   digitalWrite(RT, HIGH);
  }

  delay(400);

}


Controlling a 5m LED strip with a Nano or Uno

You have a lot of LEDs that you need to power so lets run through the calculations. Assuming that they are RGB LED strips, ie 3 LEDs per physical LED:

5 x 60 x 3 = 900 LEDs

Assuming each has a current draw of 20mA, that is (900 x 20mA) 18A of total current if all are on at the same time at full brightness.

Since each colour will be controlled by its own FET, each FET will be required to drive 6A at full brightness.

The FET that you have is a Fairchild FQP30N06L 60V LOGIC N-Channel MOSFET that can drive up to 32A. Of course, that would need a large heatsink at that current.

If you plan to have any of the colours on at full brightness for extended periods I would recommend putting a heat sink on the tab to help dissipate the heat.

The Arduino Uno/Nano uses a 328P microcontroller at 5V which, according to the datasheet, is suitable to drive the FET.

These FETs should do the job.


Your methodology there is somewhat flawed. Not only will you never see that Counter1 >= 20 (since you immediately set it to 0 before returning the count), but if you never get a pulse (engine is stalled) you'll never reach 20 pulses anyway.

A better method is to reverse everything and instead of timing how long it takes to get 20 pulses, count the number of pulses you get in a pre-defined time period.

Your interrupt remains the same, counting each pulse as it arrives, but you then sit and watch the clock (using millis()) and when a certain (to be decided by you) time has elapsed (the sample time) you record the pulse count and reset it to 0. You then have a number of rotations per time period.

If you set that time period to be 1 second (the simplest) then you immediately have the number of rotations per second.

void loop() {
    static uint32_t ts = millis();
    uint32_t pulses;

    if (millis() - ts >= 1000) {
        ts += 1000;
        uint8_t sr = SREG;
        noInterrupts();
        pulses = Counter1;
        Counter1 = 0;
        SREG = sr;
        Serial.print(pulses);
        Serial.println(" revolutions per second");
    }
}

Decreasing the sample time means you can respond faster, but you are working with smaller numbers and hence less accuracy. For instance, setting it to 100ms instead of 1 second you need to multiply your count by 10 to get the current pulses per second. It all depends on how fast your engine runs as to what a good sample time would be.


Serial communication between PC and Arduino using C

Your program works flawlessly on my Ubuntu 18.04. I would guess that you
have a problem with your setup (flaky USB port, permission problems...)
rather than the program itself. Still, I would recommend you add some
error checking: right after the fopen() call,

if (!usb_port) {
    perror(arduinoPort);
    return 1;
}

I would expect you see something like

/dev/ttyACM0: No such file or directory

or

/dev/ttyACM0: Permission denied

that could help you pin down the real problem.


433 MHZ connection between two Arduino (nano,uno) fails after some time

Regarding the hardware problem, there are some advices in the comments.
As you wrote, the solution is to reduce the bitrate at 2000 bps.

The remaining question is why the receiver always truncates the message (after a receiving error occurs). The answer is in the definition of the buflen parameter of the vw_get_message function. The page https://www.pjrc.com/teensy/td_libs_VirtualWire.html says:

  "buflen" should have the array's maximum size upon input, and upon return the number of bytes actually copied is retured.

Therefore, when a transmission error occurs, the buflen variable returns a smaller number to inform you how many characters are received. If you do not reset the buflen variable to VW_MAX_MESSAGE_LEN before calling vw_get_message again, you are telling the library that you expect a smaller number of characters and the function respects that size (thinking that you have a smaller buffer).

In other words, if you want try to receive the full message after a transmission error occured, set the buflen variable to VW_MAX_MESSAGE_LEN before each call of the vw_get_message function.


I'm assuming that temp2 must be defined as a global or you'd be getting compiler errors.
You are re-defining temp2 within the else statement, that redefined value is then only local to that else and is lost as soon as you exit it.

void loop() {

double X_value = ((double)(analogRead(X_pin)-487))/540.00;
double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

double theta_rad = atan((double)Y_value/(double)X_value);
double theta_deg = ((double) theta_rad)*180.00/3.1416;

double temp = (double)abs(tan((double)theta_rad));

if (temp == 0.00) {
  temp2 = 0.00;
} else {

/* Bug here.                                                             */
/* this temp2 is local to these {} and is lost as soon as we reach the } */
/* at the end of the else.                                               */
/* Remove the word double and it should work                             */

  double temp2 = min(temp,1.00/temp);
}

Serial.print("Theta = ");
Serial.print(theta_deg);
Serial.print("\n");
Serial.print("temp 2 = ");
Serial.print(temp2);
Serial.print("\n");

delay(1000);

}

Personally I'd replace the entire if ... else with:

double temp = abs(tan(theta_rad)); // removed redundant casts to double

double temp2;
if (temp > 1.0) // 1/temp will be smaller if temp > 1
  temp2 = 1.0/temp;
else
  temp2 = temp;

It'll have exactly the same effect but avoids unnecessary floating point calculations


STM32 Nucleo F401RE in Arduino IDE - how to enable more than 1 Serial?

Frederic Pillon on Github has been very helpful and suggested me the solution, which is to define the serial via:

HardwareSerial Serial1(PA10, PA9);

instead of just giving Serial1 for granted as you would do on a regular Arduino mega


Arduino and PHP communication only work if I open the Arduino IDE

Here the setup block:

<?php
    require("php_serial.class.php");
    $serial = new phpSerial();
    $serial->deviceSet("/dev/ttyACM0");
    $serial->confBaudRate(9600);
    $serial->confParity("none");
    $serial->confCharacterLength(8);
    $serial->confStopBits(1);
    $serial->confFlowControl("none");
    $conect = mysql_connect("localhost", "root", "") or print (mysql_error());
    mysql_select_db("ANM", $conect) or print(mysql_error());
?>

And here the connection block:

<?php
    $serial->deviceOpen();
    exec("echo 'HEYARD' > /dev/ttyACM0");
    sleep(1);
    $read = $serial->readPort();
?>


How to convert voltage to current from ACS712-20A?

According to the datasheet you have 100mV per ampere, and a zero offset voltage of Vcc × 0.5.

So assuming you are correctly converting the ADC reading into a floating point voltage the instantaneous current can be calculated with the formula

i = (Vadc - 2.5) × 10

Or for milliamps,

i = (Vadc - 2.5) × 10000

If you are measuring a DC current that is then all well and good.  However, if you are measuring an AC current things get considerably more complex.

To work out an AC current you need to have the peak-to-peak voltage, not the instantaneous voltage.  To get that you need to sample the ADC over a number of cycles and find both the maximum and minimum values.  You can then subtract the minimum from the maximum to give you the peak-to-peak voltage.  That can then give you the peak-to-peak current.

From that you can then calculate the RMS current.


OK, so I just ran some really old benchmarks on a LightBlue Bean (AVR 328p Arduino at 16 MHz).  The Bean ran the Byte Sieve benchmark slightly slower than a VAX 11/780.  The Bean also ran some of my old floating point computations about 2X faster than the 11/750 (this VAX model has no FPU to be fair to the AVR).  That puts the Bean's math performance at somewhere around 70 kFLOPs (with few divides in the mix).  A DEC VAX is several times faster than vintage 8-bit personal computers, an IBM PC-XT being roughly 1/3 to 1/2 a VAX "MIP" in benchmark performance, with an Apple II being slower still.


Select Tools>Processor>ATmega328p(old bootloader)

I was having the same problem. The default uploaded sketch was causing the problem. The code was reading one of the analog pins and throwing the value via serial port and causing the problem. Changing to old bootloader fixed it for me


Sending data from a GUI to an Arduino nano via USB

Arduino Nano supports FTDI i.e. Virtual Serial Port. So all you have to do is initialize the serial communication using pySerial.

When the data is entered into the GUI, store it in some variables. Send the data in variables to Arduino using Serial Communication. You might have design your own communication protocol on top of Virtual Serial Port in order to identify the data.

You can also use the same library to send the acknowledgement or some data from Arduino to PC, if you want.

Hope this helps you.


Store RAM and PROGMEM strings in one variable

Is there a type that I can give to my strings variable that allows me to store both types of strings?

No, but you could tag the pointer or add a vector with type information or ultimately use a class hierarchy (BaseString<-SRAMString, PROMEMString).

As a pointer is 16-bit (Arduino Uno) and there is limited amount of SRAM it is possible to add a magic number to pointers to determine the address space.

Obviously the print() member function will have to use the right type and you will also need a new addString for F() strings. Check how F() is defined.

Cheers!


Does SoftwareSerial and the servo library produce interrupt conflicts?

I have heard that this may cause interrupt conflicts.

Indeed. The Arduino can only run one interrupt routine at a time, and:

Servos use rapidly firing interrupts
SoftwareSerial both turns off interrupts while sending (for relatively long periods)
SoftwareSerial uses an interrupt for receiving that runs for an extended period

So really you can't use both together.

Options?

Use hardware PWM to drive the servos (There is a library for this somewhere)
Use an external servo PWM driving board (Adafruit do one IIRC)
Don't use SoftwareSerial.  IIRC AltSoftSerial is better, though no software serial implementation will ever be particularly good.

The underlying problem is that the low-end Arduinos only have on serial port. If you need to use more than one serial port then you really need to be looking at using a different Arduino - one with multiple serial ports.


It sounds like you are going to be attempting software "bit-banged" USB.  That, while possible, is severely frowned upon, especially when you have the resources to do it properly at your fingertips.

In answer to your question, yes, you can use a USB mini B connector.  It is no different to a USB B connector except it is much smaller and contains one extra pin - USBID - which you can completely ignore (it's only used on USB On-The-Go devices).

USB is quite a heavy protocol to do in pure software - it won't leave much "room" for you to do much else.  Better would be to re-program the ATMega16U2 chip that is used for the current USB interface.  You will need some form of hardware programmer for it - you can use another Arduino Uno, and once done you won't be able to directly program the ATMega328P chip through the USB, so you would need some other method for connecting that (external USB serial adapter cable, or another Arduino), but the ATMega16U2 chip is specifically designed to work with the USB.  Offloading the USB portion of your project onto that chip and using the serial interface that is already wired up to communicate commands and instructions to/from the ATMega328P would be a much more powerful (and reliable) system.  There's plenty of tutorials and links around to show you how to reprogram that chip.


Can't get actual output when, both input logic is high

You can simplify your requirements somewhat by splitting your inputs up.

  light=0, ir=0 then output will pin 8 high & pin 12 low.

  light=0, ir=1 then output will pin 8 high & pin 12 high.

If light is 0 then pin 8 is high. AND ir is echoed to pin 12.

  light=1, ir=0 then output will pin 8 low & pin 12 low.

  light=1, ir=1 then output will pin 8 low & pin 12 low

If light is 1 then both pins 8 and 12 are low, and you don't care what ir does, since it doesn't have any effect on the outputs.

So your structure could look more like:

if (light == 0) {
    digitalWrite(8, HIGH); // 8 will always be high with light == 0
    digitalWrite(12, ir); // echo the ir value to pin 12
} else {
    digitalWrite(8, LOW); // if light is 1 then everything
    digitalWrite(12, LOW);// is low regardless of ir.
}


First, take a look at the two links provided in the comments to your question and explain why your question is different from them.  Start by describing your "buzzer."  If your question is not significantly different then it will attract downvotes instead of answers, or it may be marked as duplicate or just simply closed.

Here is one solution, making the assumption you are writing about a piezo beeper:

void setup() {
  pinMode(4,OUTPUT);
}
void loop() {
  digitalWrite(4,HIGH);
  delay(1000);
  digitalWrite(4,LOW);
  delay(1000);
}

Alternatively, take the first example program from your IDE, called blink, and hook your beeper to pin 13 (positive) and GND (negative) while that runs.  It does basically the same thing.


As long as the date is before 2038, and your code calls one of the time functions at least once every 49 days, rollover won't affect you.

Internally the library uses Unix epoch time. Every time you call a function it checks to see if 1 or more seconds have past since the last time it was called and then updates the epoch time accordingly. Only for this check it uses millis(). And in only checks the difference between the last call's millis-value and the current millis-value, and rollover has no effect on time differences (as long as they are less that 49 days).


The function I think you are looking for is strlen - STRing LENgth.

It counts the number of characters in a string up until it finds the "NULL" end of string marker.

Serial.println(strlen(t));


Why does starting the serial monitor restart the sketch?

The Arduino uses the RTS (Request To Send) (and I think DTR (Data Terminal Ready)) signals to auto-reset. If you get a serial terminal that allows you to change the flow control settings you can change this functionality.

The Arduino terminal doesn't give you a lot of options and that's the default. Others will allow you to configure a lot more. Setting the flow control to none will allow you to connect/disconnect from the serial without resetting your board. it's quite useful for debugging when you want to be able to just plug in the connector and see the output without having to start the sketch over.

Another way to disable the auto reset is to put a pull up resistor on the reset pin.

Disabling Auto Reset On Serial Connection


Using an Arduino as a crystal oscillator

You want to use the Uno? You can set up a timer to output varying frequencies and output them on a pin. I have a page about timers which might help. The fastest you can get with a 16 MHz processor is 8 MHz output however you can get other frequencies by changing the timer parameters.

The ATtiny85 can output higher frequencies if you use the PLL clock option, I think you can then adjust the resulting frequency.

  If not, is there a such thing as a variable oscillator?

Adafruit make a Clock Generator Breakout Board - 8KHz to 160MHz. You connect that via I2C to your Arduino and then program assorted frequencies as a clock output. That uses the Si5351A clock generator chip.

Example code to output 8 MHz on a Uno or Mega2560:

#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

To output 4 MHz change OCR1A to 1 rather than 0.


If you truly only have access to the red rectangle content, and not the Ground or +12V supply, you could use an opto-isolator, assuming you can use enough of the wire in the red rectangle to be able to form a voltage divider to get at least 1-2 mA through the input side of the opto.