text:
How Bootload an Lilypad Arduino USB using Arduino UNO
I recently bought two lilypads USB, one works perfectly (it's recognized in my computer, but the other one it's never recognized, I even try in different computers and the same scenario with both devices)

So I think that maybe the second one doesn't have a bootloader installed. So I'm triying to "burn" a new bootloader. I have been triying following the guide on https://www.arduino.cc/en/Tutorial/ArduinoISP using as programmer an Arduino UNO but without luck. I ever get avrdude: Device signature = 0x000000 (retrying). Thanks for the help!

If it is showing up in the Device Manager as Arduino Lilypad USB then something is installed.

If you try uploading to a LilyPad USB with the wrong board selected, you may end up in a condition where the bootloader can no longer respond normally.
You can get the LilyPad Arduino into bootloader mode by tapping the reset button twice in under a second. Once in bootloader mode, the LED should blink at about 1Hz for about 8 seconds. My advice is to load a blank sketch (i.e., nothing in loop() or setup()) and then double tap the reset button shortly after hitting the upload button. That should restore the LilyPad USB to a working state.

Thanks for your answer! I tried this solution but same situation, even worse the LED never blink. Also it's imposible try to load something because the board it's never recognized by the IDE so I can't try to upload something. Finally I decided return the item.

The Lilypad is an official Arduino board. If you did not get it from other continents, it should have the bootloader in so don't try to burn something else. Check the traces of your Lilypad. Some short might occur because of and accidental short.
Whatever you do, DON'T TRY TO BURN SOMETHING THAT DOESN'T NEED TO BE BURNED.

Yes, essentially, if it doesn't work out of the box it should be returned - especially if it is from a less than reputable source rather than from one of the claimants to the Arduino name.

Thanks for the advice, it's true if it's not working out the box I should return the item. Thanks!


text:
TM1638 making high pitch sound?
I have a TM1638 board with 8 seven-segment displays, 8 LEDS, and 8 buttons. Each time multiples leds are on, the board makes an annoying high pitch sound.
I'm controlling it with an Arduino Uno.
Should I worry about the sound and is it normal?
This is my board :

What board do you have?

check your ground connections

Where does the sound come from exactly? When your LEDs are on, they draw power from the power supply. Cheap switching power supplies will exhibit a ringing sound under load (Spulenfiepen / coil whining, https://en.wikipedia.org/wiki/Electromagnetically_excited_acoustic_noise_and_vibration#Reduction_of_%22coil_noise%22)

I would guess it is a harmonic from the multiplex signal. Touch each part with a pencil eraser and see if it goes away.  Can you change the voltage by maybe 0.02 volts and see if it changes. Without a schematic I can only guess. I have seen these symptoms before but not with this hardware.

This thread is getting old but this LED&KEY device seems to still be fairly popular so this may still help someone else. I'm using one to control a radio receiver and the constant buzz can get pretty loud.
I found this article (A second look at the TM1638 LED & key controller) which mentions the same issue which was solved by inserting a 100Ω resistor between VCC and the VCC pin. I also added a 1000μF electrolytic capacitor across the VCC and GND pins (well, fairly close to them anyway). This quieted down the buzz a lot though it's still there. The resistor is key though the capacitor helps a bit.
I also tried moving the breadboard connections to a separate, smaller breadboard, away from the MCU and radio receiver chip and was able to use lower values (10Ω and 47μF). I was no longer able to hear the buzz at all.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Set local stratum 0 NTP server without internet
Currently, I'm doing a running track timing gate project to measure an accurate acceleration (a runner for example). The idea is when the runner triggers the first gate (start gate), the system will signals all other ESP32 to start the timing, and as the runner triggers other gates, the system will save each of their time. The expected precision is up to 10 ms.

I've managed to set up an NTP client with an NTP Server pool.ntp.org
#include <WiFi.h>
#include <sys/time.h>
struct timeval timeinfo;
volatile boolean flag = 0;
unsigned long prevTime = 0;
const char* ssid     = "********";
const char* password = "********";

void setup() {
  Serial.begin(115200);
  Start_WiFi(ssid, password);
  configTime(0, 0, "pool.ntp.org");
  attachInterrupt(digitalPinToInterrupt(27), printLocalTime, FALLING);
}

void loop() {
  //unsigned long int currTime;
  //currTime = millis();
  //if (currTime - prevTime >= 1000){
    //prevTime = currTime;
    if (timeinfo.tv_sec != 0 && not(flag)){
      Serial.printf("%ld.%06ld\n", timeinfo.tv_sec, timeinfo.tv_usec);
      flag = 1;
    }
  //}
}

void printLocalTime() {
  gettimeofday(&timeinfo, 0);
}

int Start_WiFi(const char* ssid, const char* password) {
  int connAttempts = 0;
  Serial.println("\r\nConnecting to: " + String(ssid));
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED ) {
    delay(500);
    Serial.print(".");
    if (connAttempts > 20) return -5;
    connAttempts++;
  }
  return 1;
}

However as I won't be having an internet connection I think that I need a different approach, I'm thinking of using a single ESP32 to behave like a stratum 0 NTP server or using Android phone as a stratum 0-like NTP server, which will be connected via a portable router. The other ESP32 will behave like a stratum 1 NTP server. I've read a solution to setup an NTP server using GPS, however actual current time is not necessary for this problem in my opinion.
Is this a good way to approach this problem? If yes, how do I setup a local stratum 0 NTP server?

why do you need an NTP server to time a race?

@jsotola I'm thinking to synchronizing 6 ESP32 to start their timer on a precision around 10 ms. Using NTP server is one solution that I can think of.

well, there is https://github.com/DennisSc/PPS-ntp-server

but you need only synchronize millis, not time and date.

I don't think you need to synch all the devices. Just have them send a packet as soon as the runner goes through the gate. The the single receiver-node will do the time measurements, based on the (local) times of the incoming packets. I don't think wifi jitter is more than 10ms, but you'd have to do some tests for that.

@Gerben, that sounds like an answer to the problem .... the OP's question is an X-Y question ...... the OP's system already has WiFi jitter ...... perhaps an initial handshake with one or more of  the sensor modules could be used to determine lag in the signal

@jsotola lag shouldn't matter. It's jitter that's potentially problematic. It is however possible to send raw packets though the ESP, (not adhering to the wifi specification). As far a I can see, that would eliminate all possible jitter.

Thank you for the feedback, I will try to implement the single receiver-node with raw packets.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to measure room light without LEDs interfering?
I'm trying to measure the light in a room with a simple circuit: a phototransistor connected in series with a resistor. An LED strip changes brightness according to the brightness level in the room.
The problem here is that the phototransistor also picks up the light from the LEDs. It is not an option using an IR phototransistor because I also need to measure the light from the room's light bulbs. Also, because of the device's casing, I need the sensor to be surrounded by the LED strip. Finally, I tried turning off the LEDs before measuring does not seem to work, as either the Arduino or the sensor is too slow, to turn off, perform the measurement, and turning back on the LEDs, without a human eye perceiving it.
Is there any standard or well known solution to this problem?
I will appreciate any help you can provide.
Additional Information
The LED strip is the WS2812B.
The phototransistor I'm using operates between 420 nm and 1130 nm, with peak sensitivity around 850 nm.
Furthermore, to specify the functionality I'm trying to achieve: whenever the room is dark, I want the LEDs to be not too bright. If the room is too bright, I want the LEDs to shine brighter as well.

do not measure brightness with LEDs off .... measure the overall brightness of the room and adjust the LEDs to keep it at a set level

Can you add some more information such as the LED strip you're using, and the photodetector?

Put the phototransitor in a tube so you can direct where the light can come from. Point it away from where the leds point. But I think you should look into your failed solution some more. Try playing with the value of the series-resistor. Try it with just a single led instead of a whole strip with mosfet(?), to figure out which is the culprit.

@jsotola, thank you very much. The issue, which I failed to mention, is that I don't want to keep the overall brightness at a certain level. What I wish to do is to have the LEDs to shine bright if the room is very bright, and to lower their brightness if the room is dimmer.

Normally you should be able to switch LEDs off, make a measurement and switch LEDs back on without a noticeable delay. Brightness variation is noticeable below 100Hz, which translates to 10ms period.
What you need is a photodiode with fast response time (under 0,1ms or so, though there are devices responding in nanosecond range). Phototransistors and LDRs are considerably slower.
LEDs response time is in single-digit microseconds even for white LEDs, and RGB LEDs are even faster. Below is a response of typical LEDs to a 200ns pulse:

Regular AnalogRead takes about 0.1ms (and, again there are faster alternatives), so you can easily achieve kHz measurement frequencies where brightness variation is completely unnoticeable.

My favourite answers are always "Have you tried turning it off and back on again"

Thank you. I did some timing tests, and I think the issue here is that the LED strip is relatively slow. To control it I use the FastLED library.

@DAVID You could make a "kill switch" for all LEDs in the strip with a BJT/MOSFET which you'd drive directly from a pin. That should be sufficiently fast.

@DAVID Alternatively, try to shield the phototransistor from direct LED light, maybe you get it working as is, without toggling the LEDs.

What you can try is to use a color sensor. Since you know the color of the LEDs you control, if the color sensor picks up a different color, you know it is because of other light.
Since this is not full proof (ambient color might be exactly as the LED color), you can check color differences (also with a non color sensor). If it differes without you changing the LED, you know there is ambient light (either increasing/decreasing).
It also will help if you put the sensor in a tube which is in a different direction than the LEDs to prevent as much as possible picking up the light from the sensors if possible.
(if you don't have color sensors you can use a normal sensor with some colored plastic above/around it).

Thank you very much, I will try this. However, in the long run I would like to be able to change the LED strip's color, so I guess using a color filter would not help in this situation.

In that case you need an RGB color sensor, or 3 LEDs with a red, green and blue 'filter'.

Ahh, perfect. I didn't think about it. Thank you very much.

Good luck with your project. I also might use something similar myself.


text:
How to filter the power supply for an Arduino in a vehicle (car, motorcycle)?
I want to use an Arduino (maybe Nano, maybe MEGA) in my motorcycle (a new KTM with lots of electronics).
I checked my test circuit (with the MEGA) and it uses about 100mA (with 5V connected to the 5V pin).
Edit: the bike has a 12v battery and when it's on the generator pushes this up to about 14.3v.
For my first tests I used a 3 terminals DC/DC Regulator with output 5V for the Arduino power supply. If the ignition is on the Arduino works. As soon as I start the bike the Arduino restarts every couple of seconds.
Currently I used the BP5293 DC/DC Regulator because it has 2% precision. Currently I don't have any capacitors on the input or output terminals of that regulator.
I guess I have the following options:
a) Use the BP5293 and add capacitors on the input and/or output terminals. In the datasheet an output capacitor of about 10-330uF is recommended. For the input it recommends a capacitor but without any value given.
b) Use another regulator to 5V
c) Use a regulator to i.e. 7V and then connect that to the Arduino power input and let the Arduino do the filtering of the input.
What is the proper solution and what are suitable values for the capacitors?
I have 100nF ceramic capacitors and Low ESR electrolyte capacitors with 6.3V, 16V and 35V from 68uF up to 3300uF in stock. Obviously I could just try but I prefer to know how it should be done.

Connect ceramic capacitor, recommended 10μF from the datasheet. I'd start with the input side, as the Arduino boards already have some capacitors on the board itself. Low ESR electrolytic, instead of ceramic, is most likely fine. Just make sure you have the correct polarity. I'd go for the 35V rating, just to be sure.

Your motorcycle battery is 6V, correct? You're probably having voltage drop problems. A capacitor on the input side of your power supply might help. You might also need a buck/boost power supply, which is able to increase or decrease the output voltage, since 6V too close to 5V for a linear regulator to handle.

@DuncanC: I edited the question to show the bike has 12v. I didn't mention that because I think by now all bikes, even the smallest, use 12v. But if it would use 6v then you are obviously right about the consequences. Thanks

The solution depend on what causes the reset.
It might be EMI interference on the RESET, in this case a stronger pull-up might help. The standard pull-up for nano is 1kohm which should be enough but if you use a clone the value might be higher.
If the reset comes from power drops then only a higher capacitor on the regulator input would not be enough since you also have other consumers on the 12V line that will suck the energy stored in the input capacitor.
Feed the capacitor and the regulator input through a diode, anode to 12v, cathode to capacitor/regulator. This will stop the energy stored in the capacitor to go back to the 12V line.


text:
Delay between multiple analogReads
I'm trying to read 4 analog inputs (1kHz speed). I changed the prescaler to 16 for my Arduino Leonardo according to this link. I then tried to read the analog pins and I used the following code to display the time and the readings:

#define FASTADC 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
double t = 0;
void setup() {
  int start;
  int i;
  #if FASTADC
  // set prescale to 16
  sbi(ADCSRA, ADPS2);
  cbi(ADCSRA, ADPS1);
  cbi(ADCSRA, ADPS0);
  #endif

  Serial.begin(9600);
  Serial.print("ADCTEST: ");
  start = millis();
  for (i = 0 ; i < 1000 ; i++)
    analogRead(0);
  Serial.print(millis() - start);
  Serial.println(" msec (1000 calls)");
}

// the loop routine runs over and over again forever:
void loop() {
  // print out the value you read:
  t = millis() / 1000;
  Serial.print(t);
  Serial.print('\t');
  Serial.print(analogRead(A0)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A1)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A2)); delay(1);
  Serial.print('\t');
  Serial.println(analogRead(A3)); delay(1);
}

I connected 2V from the DC supply to all the 4 channels and the readings were similar. I used the output from the serial monitor and pasted the readings for 1 sec in Excel to see the frequency. With a 9600 baud rate and no delay between the readings I got 200 Hz (for the 4 analog inputs).
Why is that happening? And is there a relationship between the sampling frequency and the baud rate? Is my way of finding the frequency correct? If not what's the right way?
Finally, I'll be plotting the readings in Matlab, so I guess this will affect the sampling frequency. How can I control it so that I'm sampling with 1kHz rate for all the channels?
Here is the screenshot of the readings from the 4 channels (2V input).

Summarizing everything, I need to know the following:

The effect of adding a delay between every two readings on the accuracy of the readings and the sampling frequency.
How to find the best sampling frequency for every input and how to control it?
Will using Matlab to plot the data affect the sampling frequency?

Thanks.
EDIT: I accepted the answer below, if anyone has the same problem , please make sure that you change the prescaler as I mentioned above for the best results.

Taking a reading on a floating pin is meaningless. You can get anything. Please, connect something to the pins before doing the experiment.

At first I thought that the main problem was not that you too slow at sampling, but that you were too slow at transmitting the data. As Edgar already stated, at 9600 b/s you need 22.88ms to send a line, so the maximum frequency is less than 50Hz.
However as you experienced, the speed you are getting is 200Hz. This is because that calculation is right in the case of a real serial interface. Arduino Leonardo, on the other hand, emulates the serial interface. But.. There is no such thing as baud rate. If you look at the CDC emulation source code you will see that the baud rate you pass to the begin function is ignored.
So... Why is it still slow? Because you are using the delay function! You are waiting for 1ms every time you perform an acquisition, and then you still have to perform all the sending. This has two errors embedded: 1) using the delay function breaks the timing - better use a timer - and 2) you are too slow.
Now, if you want a 1kHz sampling (or any delay multiple of 1ms) you already have a timer running (so you can just use that):
#define INTERVAL_LENGTH_US 1000UL

unsigned long previousMicros;

void loop()
{
    unsigned long currentMicros = micros();

    if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
    {
        previousMicros += INTERVAL_LENGTH_US;

        int val_a0 = analogRead(A0);
        int val_a1 = analogRead(A1);
        int val_a2 = analogRead(A2);
        int val_a3 = analogRead(A3);

        Serial.print(((double)currentMicros) / 1000000UL, 1); // 1 is the number of decimals to print
        Serial.print('\t');
        Serial.print(val_a0);
        Serial.print('\t');
        Serial.print(val_a1);

        Serial.print('\t');
        Serial.print(val_a2);
        Serial.print('\t');
        Serial.println(val_a3);
    }
}

NOTE: The millis() function is replaced by micros() according to Edgar's and Nick's comments.
Change just the define to change the sample time. Now its set to 1000us (i.e. 1ms, so 1kHz), but don't go much higher otherwise you will have to check accurately the sampling time and the transfer speed. The t variable is not needed anymore.
Just a side note: this will also fix the bug in your code that prevents the program to display the current timing (instead of printing 2.5 it prints 2.0).
If you need a faster sample rate you should use another timer to get the correct timing, but again avoid delays. Not needed anymore

Note that millis() sometimes skips a millisecond, e.g. it jumps from 41 straight to 43. You can use micros() instead of millis() to avoid the problem: it gives a 4 µs resolution.

@EdgarBonet this sounds new to me... What are the cases when it skips (apart from when your loop code actually is longer than 1ms)?

On the 16 KHz AVRs, the millis counter is updated every 1024 µs: the millisecond count is incremented by one and the fractional count is incremented by 3 125ths of a millisecond. Whenever this fraction reaches a full millisecond, the millisecond count is incremented by two instead of one. This happens roughly once every 1000/24 ≈ 41.67 updates.

@frarugi87 I tried your code and it's working! I needed a way to fix my sampling rate and this does it. As you said, the baud rate doesn't affect anything. I tried 9600 and 250000 and both gave me 1kHz. Recieving the readings in Matlab instead of the serial monitor won't affect the frequency right?

@frarugi87 Edgar Bonet is right, I cover this issue here. As Edgar said, because of the timer prescaler, the millis "tick" is actually slightly slow. The code adjusts for that every 41/42 updates.

@EdgarBonet I make a (quick) search on google and couldn't find this behavior, so I tested it and... Well, 42 can be the Ultimate Answer to Life, The Universe and Everything, but not for millis... Thank you for pointing this out: I updated the answer with the code I think fixes this (so micros() / prescaler)

@NickGammon I read a lot of wonderful replies on SO and here by you, but I didn't know you had a forum where you put a lot of things. Thank you for your link: I'll read your website

@Isra please update the code with the one in the answer, since it fixes Edgar's issue. This one is a bit more flexible than the previous one and updates exactly (well, more exactly than millis) every ms. As for matlab, the data source is the same, so the speed is the same, provided that matlab is fast enough to read all the data

thank you @frarugi87 for pointing that out, I fixed it. But when I read the serial data in matlab, it gives me this error "Warning: Unsuccessful read: A timeout occurred before the Terminator was reached.. " Do you have an idea on why is that happening? I'm using fscanf(s, '%d')*(5.0 / 1023.0)); to read the values. One last point, if the analog readings are 10 bits wide, how is that transmitted ? I know serial communication's data width is only 8 bits (I set the baud rate to 250000 on both ends just in case)

While replacing millis() with micros(), you introduced an erroneous division by INTERVAL_LENGTH_US. I took the liberty to edit your code to restore its previous logic, which was good. Note that the test if (((currentMicros - previousMicros) / INTERVAL_LENGTH_US) > 0) is not technically wrong, and the compiler would optimize it into if (currentMicros - previousMicros >= INTERVAL_LENGTH_US) anyway. But I think it's clearer without the division. @Isra: you may try this new version.

@EdgarBonet I already noticed that, and fixed it as you fixed before writing the comments, but maybe I made a mess with the back button in the browser and the old version remained online. Thank you for fixing it...

@EdgarBonet Thanks very much, I tried it but I still get the same error: "Warning: Unsuccessful read: The input buffer was filled before the Terminator was reached.. " I've tried reading the pins with the regular rate and I was able to read it in matlab. This error shows up only when I set the rate to 1kHz.

@Isra try to use a step by step approach: first open and read only the strings you receive (with fscanf(s)), then read the integer value and finally convert and use it. See when you block and try to find a solution (I'm not very much into  matlab's serial port interface, so I don't know how to debug it properly). As for the 10 bits, well you are printing to serial, so the value you receive (for instance 1001) is transferred in ascii coding "1001", so four bytes ('1', which is 49, '0', which is 48, then '0' and '0'). If the error is the speed try lowering it to 100Hz (set the define to 10000)

@frarugi87 I did what you suggested, it turned out that I have to print the readings each in a single line (from Arduino), Matlab couldn't see the terminator (line end). Another issue, when reading the time in Matlab, you have to use fscanf(s,%f) instead of fscanf(s,%d) because it's a double number. Thank you all for your MASSIVE support and I hope this helps others as well!

Two ways to sample at or near a given frequency:

Select the right ADC clock prescaler. This has some limitations and may not get you too the precise sampling frequency.
Use a timer to trigger the sampling. Can be done in either. Hardware or software. It is the most flexible way here, especially if coupled with the ADC isr.

I tried your program on my Arduino Uno with similar results : it prints
about 44 lines per second. Then I did the math:
Each line consists of 22 characters, including the CR and LF at the end.
Each character is transmitted as 10 bits (8 data bits, one start bit and
one stop bit). At 9600 bits/second, each bit takes 0.104 ms to be
transmitted. All this amounts to 22.88 ms per line (22 × 10 × 0.104), or
about 43.7 printed lines per second, on average.
Now, since you are using a Leonardo, things could be a little different,
as the Leonardo does not use a real serial port, but a virtual one. You
may still try to increase the baud rate to see if it makes any
difference.

I was absolutely sure that this was the correct interpretation, but.. Well, the Leonardo (and all the arduino boards that emulate the serial port) ignores the baud rate you set. So the transfer speed is not the issue in THIS particular case (see my answer)

When a CDC/virtual comm port is involved, the setting of baud rate is done in the CDC device driver, on the host side. That would be windows or Linux or .... Or it wouldn't hand shake with your host terminally program.

@dannyf I never used a leonardo or micro, so I never used the CDC emulation. But... Is it really set on the host? I made a quick research on internet and I found this thread about microchip CDC. They say that there is no such thing as baud rate, since the data is transferred in blocks whenever there is the time, so there isn't a "baud rate"; you can set any value and it gets ignored on both the host and arduino... Is this wrong?

@Edgar I tried frarugi87's method and it worked with several baud rates! I never knew that Leonardo uses a virtual serial communication. I'd like to try this on an Arduino pro Micro (also Atmega32u4) and Arduino DUE (because it has a 12 bits ADC). I think with the pro micro it's going to be the same, but will it be the case with the DUE? unfortunately I don't have the two boards yet to test them myself.

@Isra: The Pro Micro should indeed behave like the Leonardo. The Due, however, seems to have an extra ATmega16U2 as an USB-to-serial chip. Thus I would expect it to behave like the Uno (i.e. the baudrate is relevant).

A few recommendations to get good performance out of the Arduino boards.

Maximize your analogResolution if the default is not already the max (as in the case of the Due.)
If possible, use a simple oscillator instead of a constant Voltage source.  If you can create a sine or triangle wave with its peaks within the Arduino's input voltage range, you can plot something more interesting than a straight line.
There is no need to do any analogReads in setup(), and you DON'T want to do anything with the Serial object in setup() except configure it.  (There is an under-the-hood reason for that.)
To get good sample rates from the Arduino boards, don't convert to text until MUCH later in the data flow.  TO try this SIGNIFICANT speed optimization, declare an array of 4 elements of type unsigned int, another array of 12 elements of type unsigned char, and an unsigned long to hold the time.
In loop(), start by assigning micros() to the unsigned long
Then call the four analogReads in an uninterrupted sequence, assigning them to the four elements of the unsigned int array.
Then copy the four bytes from the unsigned long and the eight bytes from the four unsigned ints into the 12 elements of the unsigned char array.  You will need to use the C++ shift right operator ">> 4" and the "(unsigned char)" type conversion to do this part.
Then, still in loop(), call Serial.write(byteArray, 12) once to send the time and digital representations all at once (in the byte order you specified) through the serial connection.
Place delayMicroseconds at the very end of the loop to get a higher resolution delay between loop iterations.
On the other side of the serial connection (the workstation or laptop) use dd or some other low level transfer program (instead of a terminal emulator) to copy from the binary 12-byte sample vectors from the serial device that your workstation or laptop uses to access the serial connection to a binary file.

The above eliminates several bottlenecks typical of the newbie example programs.  The issue remaining is that, to optimize speed, you never converted the raw binary data vectors to a tab-delimited text file that MATLAB or GnuPlot can read with ease.
A simple C, Java, or Python program can then read the 12 byte vectors and convert the byte groups of 4, 2, 2, 2, and 2 back into the 32 bit time stamp and the four 16 bit unsigned channel values in a loop.  The byte order is what you chose in your Arduino sketch.  You will need to use the left shift operator and bitwise and and or operations to reconstruct the time stamp and four channel values.  At the end of this loop, you can write these values as a single tab-delimited line coresponding to the current binary input vector.  Iterate through all the vectors to get a complete tab-delimited data file.
You can experiment with different delayMicrosecond values to get different sample rates, and you can calculate our baud rate to stay ahead of the sampling so that the program could theoretically run indefinitely without backing up the Serial buffer on the Arduino side.  Each Arduino analogRead and Serial object has its own maximum speed, which you can find by experimentation.

You wrote “you DON'T want to do anything with the Serial object in setup() except configure it. (There is an under-the-hood reason for that.)”. Could you elaborate? 2) You cannot get good control of the sampling rate with delayMicroseconds(), because the loop time is the delay plus the time needed to execute the code. Using micros(), like in @frarugi87's answer, is the standard method and it works well. Only a timer-triggered analog read will give you better accuracy (less jitter).

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Name of the Arduino Nano clone in the device manager
I'm working on an app using Matlab and it recieves data from an arduino. I've changed my board into an Arduino Nano (clone) recently. My program will automatically check for the device's name in the list of serial devices connected and it will connect to it directly once the user presses connect. The user doesn't have to input any Com port number or baud rate. This worked fine with my previous boards (UNO, Pro Micro, Leonardo). I just need to change the search string in my code and it'll automatically connect. My current board however is different, I'm using VMA102 (Arduino Nano clone). It uses FTDI drivers which I downloaded following this tutorial. I can upload the codes correctly to it but I just doesn't show a name with in the ports list in Arduino IDE as shown in the picture below.

Now when I looked it up in the device manager the name was 'USB Serial Port (COM5)' so I pasted 'USB Serial Port' as my search text in Matlab, it doesn't find it. I concluded that the correct name for it is not 'USB Serial Port' but rather the 'no name' as shown in Arduino IDE. Is there a way to find what is it called or how I can change it into a unique name so that my app can search for it?
Edit: here is the code, it works fine with all the other boards:
    devices = IDSerialComs();%gets all the avilabe com ports and thier names (name, com#)
    assignin('base','devices',devices);%save it to main workspace
i=1;index=0; tesst= zeros(length(devices),1);%saves the comparison results
while i<=length(devices)
    tesst(i)= strcmp(devices{i,1},'USB Serial Port');%compare the received names with the board's name
    % 'SparkFun Pro Micro''Arduino Uno'
    if ( tesst(i)==1 )
        index=i;%save the index
    end
    i=i+1;
end

if(isempty(find(tesst,1)))
    msgbox({'Connection failed' ' plug the device, wait for 5 seconds then try again'} ,'Connection Failure','error');
else
    msgbox('Connection successful, proceed to the next tabs', 'Connection success');
end
%get the COM# associated with the index and add COM before it to from the comport number as a string
COM_Num = strcat('COM',num2str(devices{index,2}));
comport= serial(COM_Num, 'BaudRate', 115200);

and here is a screenshot of my device manager

Thanks

Please include program code that performs search and connect a serial device and a screenshot of the device manager.

The name shown in the Arduino IDE's Tools > Port menu is set in the Arduino boards.txt file (https://github.com/arduino/Arduino/blob/1.8.2/hardware/arduino/avr/boards.txt#L49) so that is not relevant to Matlab. Can you search for VID/PID instead? FTDI FT232RL chips come with a default VID: 0403, PID: 6001 unless the purchaser specifies otherwise. That still won't help you if there are multiple FT232RL attached to the computer but it's an improvement at least.

Assuming that I only have 1 FTDI FT232RL (which is the plan), what should its typical name be "0403 6001"? and is this the same with CH430 drivers (in case I want to buy one)

I've done some debugging, and I found out that the function that searches for all the serial devices returns an empty cell when my Nano is the only board connected. Could this be because it has no name (Arduino shown "no name" only a port number)

CH340 is VID: 1A86, PID: 7523

The  IDSerialComs() function scans the Windows registry and associated active COM ports with their registered "Friendly Name". To scans using the following path:
'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\'

But driver FTDI uses another path:
'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\FTDIBUS\'

Try to modify the function so that it meets your needs.

Thank you very much @AltAir! I modified it an it worked! I hope this helps others as well.

If you do a windows search for the device manager you will be able to see all the com devices currently connected to your computer. Unplug and replug your Arduino and it should be pretty easy to spot.
Mine is the USB-SERIAL CH340

Yes i've done that, my board is called "USB Serial Port" which is not found when searched for. From my research, I read that with this driver all connected devices that use this FTDI driver will have exact same name, even if connected at the same time.

Does USB Serial CH340 appear when you look for your board in Arduino IDE? or does it only show the com port number?

It just shows up as a com port in my IDE, I use STINO

Matt, yes it will show as a com port only in the IDE, I realized that only the original boards will show up by their name in the IDE.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Cant's code against Yun Wireless Section
Just got my Yun today.  Successfully connected to my home wireless, installed YunSysUpgrade_v1.5.1,
and divied up my Micro SD card for Linino and Windows file system with YunDiskSpaceExpander,
and got files serving on the native file server from the SD card.
But I can't seem to touch the wireless section from a sketch.
I'm running a mod of the example ScanNetworks sketch - here's the relevant part:
void loop() {
  delay(1000);
  String fv = WiFi.firmwareVersion();
  Serial.println("Version: ");
  Serial.println( fv );
  Serial.println("Status: ");
  Serial.println( WiFi.status() );
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

Here is the ouptut: no version and a status of 255 (which I cannot find documentation on....)

Version:
Status:
  255
  Scanning available networks...
  ** Scan Networks **
  number of available networks:0

I looked at installing wifi_dnld.elf, but could not find jumper 3 on my Yun, so assumed it was for the 'true shield'.
What am I doing wrong, or do I need to return this to amazon?

WiFi library won't work with the Yun: it's meant to work only with the WiFi shield.
On the Yun, everything but the pins is connected to the linux cpu. For the microcontroller to use all the devices available to linux, including wifi, you need to use the Bridge library. Try running example WifiStatus (Examples -> Bridge -> WifiStatus)
A drop in replacement (almost) of both Ethernet and WiFi libraries is the YunClient/YunServer pair, part of the Bridge library. Check out the docs at http://arduino.cc/en/Reference/YunBridgeLibrary.


text:
I cannot find the I2C device by scanning
I've been trying to get a LCD I bought from deal extreme to work for some time with my ATTiny85 chip. It should be capable.
I've tried googling the device but there is no proper documentation, so I figured the best way to get the address is to scan for it. How ever, the code below does not work :( any pointers? Anyone else who has gotten this I2C LCD display to work with Arduino?
As I have no other output then the screen, the thought behind the code is to scan for devices and then when it finds one (the LCD is the only one connected to the bus) should then print the address :)
I only have a serial programmer and attiny85 chips, so I have no way to bring it to a full Arduino UNO or whatever for further debugging.
#include <TinyWireM.h>
#include <LiquidCrystal_I2C.h>

void setup()
{
  TinyWireM.begin();
}

void loop()
{
  byte error, address;

  for(address = 1; address < 127; address++ )
  {
    TinyWireM.beginTransmission(address);

    error = TinyWireM.endTransmission();

    if (error == 0) break;

    delay(5000);
  }

  LiquidCrystal_I2C lcd(address, 16, 2);

  lcd.init();
  lcd.backlight();
  lcd.clear();

  lcd.setCursor(0, 0);
  lcd.print("Hello World - " + address);
}

I2C LCD: http://www.dx.com/p/iic-i2c-2-5-blue-screen-lcd-display-module-for-arduino-green-black-266170#.U6f_B_l_vIc

Why has this question been downvoted? I'm curious, because it seems a legitimate problem the user is having, he has shown research, and although it isn't an arduino chip he's using, he's obviously using the arduino library to compile the hex file. He didn't post the question to Arduino SE, it's been migrated here. I don't mind downvoted questions for crap questions, but when there is at least an honest attempt, why not post constructive comments as to how he could improve it.

I'm not sure on your program, but I bought a LCD display from Deal Extreme. I use the following address to communicate with the display:
LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27

It seems as that is the correct address for the LCD.


text:
Bluetooth Stream to USB
I want to make a device that will take a Bluetooth stream and play it on speakers via the USB port for speakers that do not have Bluetooth.
I think it may be possible by taking the stream and using an Arduino to convert the stream to a virtual file so that the speaker will see the USB as a mass storage and play the file.
I am not sure that is just an idea, any thoughts or solutions?

What kind of speakers do you have that can play a file on a USB mass storage device?  I think you are barking up the wrong tree and need to examine your terminology and what can actually be done a little better.

What's an Arduino raspberry pi? I didn't know Arduino had bought out Eban and co...

If your target is a USB audio device - like a USB headset or USB speakers (NOT an MP3 player with USB interface) then you could connect it to something which can act as a USB host with USB audio device drivers.  That means not an Arduino, but something much more powerful like a Raspberry Pi or BeagleBone Black for instance.
If your target is basically an MP3 player that allows you to connect a USB stick with songs on it then you're completely out of luck.  There's this small thing called time that gets in your way.  You can't stream data to something that expects the data to already be there. You can't seek in a file that doesn't exist until the moment you try to read from it. Also you have to act as if you were a USB memory stick, and that's not easy, and certainly not something an Arduino can do. Even things like the Pi would have a lot of difficulty in managing that since they are hosts, not devices, as far as USB is concerned.
The key word here is stream.  Your target as to be able to receive a stream of data rather than request blocks of data from a file.  USB audio devices can do that, but USB audio hosts cannot.

Thank You majenko, one more question. So when you stream via bluetooth to any bluetooth speaker, how is the music able to play live? as in how does the speaker read the stream and play it live?
And above you mentioned that if the target is a usb audio device. if it is a usb audio device, how would that be able to take a live stream via the  rasberry pi and play it. Isn't that the same idea as if it was an mp3 player that plays music off an usb? I appreciate your help, I am just trying to figure this out.

The concept is completely different.  An MP3 is like a CD. A stream is like the radio. A bluetooth or USB audio device is sent a digital representation of the sound at that instant in time. An MP3 player reads blocks of compressed audio data, decompresses them, and generates the digital audio representation.

Ok that make a lot of sense. Thank You so much.


text:
Loading Leonardo bootloader to Atmega32U4 running at 8 MHz
I am currently using ATMega32U4 running at 16MHz using Leonardo. I can only supply 3.7V (I use LiPo batteries) and everything seems fine but this is not as per specs.
To run at 16 MHz, I have to supply 5V but I can't. I do not want to do any step-up. I am thinking of of using 8 MHz crystal so the processor will require only 3.3V, but I need to use a Leonardo.
Has anyone been successful in doing this?

Why do you "need" Leonardo?

Has who been successful? To whom are you addressing this?

Or is this a general survey? Finding out what proportion of the population have been successful in using an 8MHz bootloader on a Leonardo?

The bootloader does USB. I don't think you can do USB on the 32u4 on only 8mHz.
You can however set the system clock prescaler to divide the main clock by 2, making it run at 8mHz. The bootloader will however still run at 16mHz, but that's probably still fine (though out of spec).

The AVR USB has a system clock prescaler, and the system clock can be divided by setting the “CLKPR – Clock Prescaler Register” on page 38. This feature can be used to decrease the sys- tem clock frequency and the power consumption when the requirement for processing power is low. This can be used with all clock source options, and it will affect the clock frequency of the CPU and all synchronous peripherals. clkI/O, clkADC, clkCPU, and clkFLASH are divided by a factor as shown in Table 6-10.

To divide the system clock by 2, set the CLKPS0 bit in the CLKPR register. The code for this would be something like this:
void setup()
{
  cli();
  CLKPR = _BV(CLKPCE);
  CLKPR = _BV(CLKPS0);
  sei();

  ...

just note that everything runs twice as slow. So delay(1000) will take 2 seconds. You'll have to update F_CPU somehow to fix this if this causes a problem.

You can do USB on 8MHz. The first thing that happens to the 16MHz clock on its way to the USB PLL is it goes through a /2 prescaler.  That prescaler can be bypassed to make it /1 so it can run from 8MHz.  It's all in the datasheet.  These bits allow to configure the PLL input prescaler to generate the 8MHz input clock for the PLL from either a
8 or 16MHz input.


text:
Very easy Arduino code challenge for you brainiacs to solve
I've searched the forum for similar problems and still can't see my obvious issue. I'm working on a simple Halloween prop and I'm using an Arduino for the first time. I've tested each individual 'event' (i.e. fog machine, mp3, actuator, and LED strip) with a loop and all four have worked on continuous loop with no issue.
As soon as I combine them all together, the program runs successfully exactly one time. After that final 10 second delay, when I expect the program to start the loop again, it crashes. If it helps, right during the start of the next loop, the relay light turns on on the relay board for RELAY_1_A and sort of just flickers while the actuator hums. I usually shut it down quickly at this point. As soon as I turn the system back on, it successfully runs through another iteration until the loop hangs.
I'm happy to provide pictures or even a video of the issue if that helps. My guess is that you guys will spot my coding issue right away. Maybe some kind of memory overflow or something like that.
I know my code could be much more efficient but I'm just looking for the glaring problem that is keeping the loop from working.
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>

const int RELAY_1_A = 7; //the one with the issue
const int RELAY_1_B = 8;

SdFat sd;
SFEMP3Shield MP3player;
void setup() {
  // initialize the digital pins as an output.
  pinMode(10, OUTPUT); //Fog machine on Relay1 on 5V relay board
  pinMode(3, OUTPUT); //LED strip off breadboard MOSFET
   pinMode(RELAY_1_A, OUTPUT); //12V relay for actuator on Relay1 on 12V relay board
   pinMode(RELAY_1_B, OUTPUT); //12V relay for actuator on Relay2 on 12V relay board

  //start the shield
  sd.begin(SD_SEL, SPI_FULL_SPEED);
  MP3player.begin();
  MP3player.setVolume(10, 10);
}

void loop() {
  MP3player.playTrack(2);  // Play MP3. Track 1 is coffin and track 2 is bird
  delay(5000);              // wait for 5 seconds
  digitalWrite(10, LOW);   // Turns ON fog machine
  delay(3000);
  digitalWrite(10, HIGH);   // Turns OFF fog machine
  digitalWrite(3, HIGH);   // Turn the LED on (HIGH is the voltage level)

  delay(5000);              // wait for 5 seconds

  retractActuator();       //Open coffin
  delay (9000);
  stopActuator();      //Close coffin
  delay (9000);
  extendActuator();      //Close coffin
  delay(8000);
  digitalWrite(RELAY_1_B, HIGH);  //Turns off this relay during the wait period before next loop

  digitalWrite(3, LOW);    // Turn the LED off by making the voltage LOW
  delay(10000);              // wait for 20 seconds

}
void extendActuator() {
  //Set one relay one and the other off
  //this will move extend the actuator
  digitalWrite(RELAY_1_A, HIGH);
  digitalWrite(RELAY_1_B, LOW);
}

void retractActuator() {
  //Set one relay off and the other on
  //this will move retract the actuator
  digitalWrite(RELAY_1_A, LOW);
  digitalWrite(RELAY_1_B, HIGH);
}

void stopActuator() {
 //Set both relays off
 //this will stop the actuator in a braking
 digitalWrite(RELAY_1_A, HIGH);
 digitalWrite(RELAY_1_B, HIGH); }

My guess is you have a pin conflict between your MP3 shield and your relays. Looking at the MP3 library my guess is pin 7.

Majenko thank you so much! Absolutely incredible. You solved my issue less than an hour after I posted it. You response made me look up the schematic for the Sparkfun MP3 Shield and it turns out that shield hogs tons of pins which can't be used. In fact, only 0,1,5, and 10 can be used. As soon as I switched the 2 relays to 0 and 1, everything worked perfectly. Thank you so much again!

Excellent.  I'll craft that as an answer then.

You are attempting to use IO pins that are already in use by the MP3 shield.
According to your subsequent research, only digital pins 0,1,5, and 10 are available for use.
You should shy away from using pins 0 and 1 since they are also connected to the computer through the USB interface and are used for uploading sketches.  You will find that either you can't upload sketches with the relays connected to those pins, or the relays will "randomly" switch on and off while you're uploading a sketch.
Don't forget that the analog pins A0-A5 can also be used as digital pins, so you can quite happily drive your relays using any of those.

-Majenko, I hope you will appreciate this communication tip. It is much more effective to say "Remember to ..." rather than "Don't forget to ...".

@linhartr22 Not for a native English speaker. "Don't forget..." is far more common than "Remember...".


text:
Piezo connection causing RTC to go haywire
When I connect a piezo (to pin 8), it causes the output of my RTC to go haywire and throw 165 errors into the results.
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 165:37:4 // Connected piezo
2016/3/25 13:36:4
2165/165/45 13:36:4
2165/165/165 25:36:4
2016/3/25 13:36:4
2165/165/45 13:36:4
2016/3/25 13:36:4
2165/165/45 13:36:4
2165/165/165 165:165:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 37:36:4
2016/3/25 13:36:4
2165/165/27 13:36:4
2016/3/25 13:36:4
2165/165/165 25:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 25:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 25:36:4
2165/165/165 25:36:4
2016/3/25 13:36:4
2016/3/25 13:36:4
2165/165/165 25:36:4

Here's my current layout...

Worth noting:

Disconnecting the piezo instantly solves the problem.
Connecting to any other pins also caused the issue.

Here is the Fritzing diagram

and schematic

Here's the full code...
#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

#define PIN 6
#define TONE 8
const int buttonPin = 7;

long fadeTime = 1 * 60000L; // X minutes
int colorStops = 256;
int delaySpeed = fadeTime / colorStops;
int notes[] = {262,294,330,349};
int switchState = 1;         // variable for reading the pushbutton status
int timeHour = 13;
int timeMinute = 20;
uint32_t alarmLength = 5 * 60000L; // 5 minutes

Adafruit_NeoPixel strip = Adafruit_NeoPixel(4, PIN, NEO_RGB);

void setup() {
  Serial.begin(57600);

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }

  pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input

  strip.begin();
  strip.show();
}

void loop() {
  DateTime now = rtc.now();

  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(" ");
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();

  if (now.hour() == timeHour && now.minute() == timeMinute && now.second() == 00){
    // Fade in light
    for(int i = 1; i<colorStops; i++){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(i,i,0));
      }
      strip.show();
      delay(delaySpeed);
    }

    // Play tone after light fully bright
    for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(random(100,255),random(100,255),random(100,255)));
      }
      strip.show();

      tone(TONE, notes[random(0,3)]);
      delay(100);
    }

    noTone(TONE);

    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
  }
}

bool kill() {
  if (digitalRead(buttonPin) == LOW) {
    noTone(TONE);

    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
    return true;
  }
  else {
    return false;
  }
}

Could you please add a schematics diagram of your circuit, would make it easier to understand your connections as opposed to the picture. Could you also please attach your code

@evolutionizer Done.

Is it only in case of connection or also when you drive the piezo? Might it be because the piezo (and rtc) is drawing more current than the Arduino can supply?

@Paul I'm noticing only in the case of the connection, without trying to drive the piezo.

@Shpigford could you please add pinMode(TONE,OUTPUT); in setup and try again

@evolutionizer Boom! That did the trick. So, the follow up question being...why? :)

@Shpigford arduino by default sets pins to INPUT this could be causing things to screw up

I still don't get it (: but you might add it as an answer. So it can be accepted, this StackExchange  is still a little low on acceoted answers (:

@Shpigford Just an FYI the resistor connected to the LED is not doing anything, as both the legs are shorted

@Paul I am not very clear on why this issue either. I believe what is happening is that because the pin is set as INPUT by default there is not limiting in the amount of current this could lead to the m/c acting funny.

Add
pinMode(TONE,OUTPUT);

to setup() to fix the problem.

authors: Στέργιος Μέκρας


text:
Can a shift register be used to extend the Arduino pins when an ethernet shield is mounted on the Arduino?
I am currently working on a wireless home automation system. The system is connected to a wireless network in the home via the ethernet cable connected the ethernet shield and router. Hence, I need more pins on the Arduino to connect the appliances to be controlled in the home.

You can control a shift register with shiftOut or bit-banged SPI.
My page about SPI has a small library that does bit-banged SPI.
It is also possible to control a shift register using the same pins (MOSI/MISO/SCK) that the Ethernet interface uses, as long as you use a different SS (slave select) pin for your shift register. This may not be practical if the Ethernet card is active all the time. It is probably easier to do the bit-banged SPI or use shiftOut.

Yeah, if the Arduino has available pins to run a bit-banged SPI, it would likely be a bit safer overall.

Not all shift registers have an SS pin. But that doesn't matter as long as you don't latch the data sent to the Ethernet shield.


text:
Arduino connecting relay has no power output
I'm a newbie trying to control something through a relay. I've tried two relays with two different setups.
Setup 1
External 12V dc input to the relay (SRD-12VDC-SL-C) and signal pin from arduino to the IN pin, GND of ext. power supply to the GND of the Arduino, NO and COM to the load object (i.e. an LED).
Setup 2
Similar to setup 1, but using SRD-05VDC-SL-C, 5V from Arduino (Vin from Arduino also tested).
Test program
Modified version of the 'blink' example.
Symptom

The load object has been verified to be working before the testing.
Both setup can be verify the input is working, the power led and switch led of the two relay module are lighted as expected, and I can hear the click sound while switching.
No output can be obtained, both from the load object and using a multimeter.

Update

Sorry, I'm supposed to upload a Fritzing schematic, but I can't find a proper relay as I'm using.

The DC+ (red) of the relay is connected to the external ATX 12V.
The DC- (black) of the relay is connected to the external ATX ground.
The IN (blue) of the relay is connected to the Arduino pin 8.
The external ATX ground (white) is connected to the Arduino ground.
The NO (red) of the relay is connected to the load object Vcc.
The COM (black) of the relay is connected to the load object ground.

Sketch
A simple modified version of Blink example is used for testing.
const int relaySignalPin = 8;

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

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(relaySignalPin, HIGH);
  delay(1000);
  digitalWrite(relaySignalPin, LOW);
  delay(1000);
}

Question
I have no idea on why there's no voltage can be obtain between NO and COM while the switch is on, what's wrong with my setup?

Can you draw a schematic please? Even if you have to use pencil and paper and take a photo of it. Or a clear photo of your actual wiring.

It sounds, from your textual description (please post a schematic or at least a photo of your setup) that you aren't providing power to the relay.
A relay doesn't have a power output.  It never provides power - it is merely a magnetically operated switch.  It is used to switch an external source of power on and off.
Treat the NO and COM pins as either side of a normal button or switch and wire it accordingly - that is (for example) connect COM to the positive of your power supply, NO to one side of your load, and the other side of your load to the negative of your power supply.
You can share the same power supply as you are feeding to the logic / drive side of the relays.

So basically there are two wires connected to the same positive 12v source, one connected to VCC on the input side of the relay board and the other connected to the output side common terminal.
And there are three connections from the same negative 12v source, one connected to the ground of the relay board, one connected to the ground of the arduino, and the other connected to the ground of the load.
Then, of course, the connection to the relay to one of the digital pins of the arduino.
Well I'm pleased to report it works!
Now to discover what the jumpered COM/GND connection on my relay board does or does not do. I will report back.


text:
avrdude: ser_open(): can't open device "\\.\COM4": Access denied
I installed the new IDE Environment 1.6.6 and I got this error when compiling a program. I am using an Arduino Uno
avrdude: ser_open(): can't open device "\\.\COM4": access denied

I need your help.

finnaly, it works after restarting my computer

If you have solved the issue, please post the solution as an answer.

I think you used "Eclipse" and "Arduino" at the same time. so, I guess that a "com4 Port" conflict has occurred and the upload could not was done.

restart  your computer and try to open "Arduino" first and upload. not open "Eclipse" at the same time.

I had this very same issue. I solved the problem by shutting down my outside cameras. Once cameras were off (the software) the program worked. It was the camera software that was using the port.
So if you have a lot of other software or equipment running in the background this may be your problem. Just try shutting down things one at a time. That's what I did until I found that the camera software was my problem.


text:
Marlin Firmware troubles: <time.h> error
I am trying to upload the Marlin Firmware to my 3D printer's Arduino Mega 2560 and I am experiencing a problem. It keeps saying:
qr_solve.cpp:7:18: fatal error: time.h: No such file or directory
 #include <time.h>
                  ^
compilation terminated.
Error compiling.

Please help as I'm lost as how to fix it, because I try to scroll up to see what is highlighted in red and I can't find anything.

This might be helpful; https://groups.google.com/forum/#!topic/deltabot/IknX0wamH2M

Gerben's comment fixed my issue.

Hi @Rdawg33 - If one of the answers below solved your issue, can you mark it as the accepted answer, using the tick icon next to the answer, in order to remove your question from the Unanswered Questions list? Thanks.

From Gerben's link to the googlegroups's thread, Delta robot 3D printers › compiling jcrocholl's Marlin (Ubuntu), as Francis Mallet points out, at the bottom of the thread, it is necessary to change <time.h> to "Time.h":

I copied the content of the Time library right in the Marlin folder, then changed line 7 of qr_solve.cpp from #include  to #include "Time.h"
The code compiled and everything seems to be working ok.

So, to iterate, the line in qr_solve.cpp:
#include <time.h>

becomes
#include "Time.h"

Now, Marlin.ino should compile as expected.
Note that the latest version of Marlin, from github.com/MarlinFirmware/Marlin no longer suffers from this issue, but older versions of the software, such as github.com/gpfwestie/kossel_2020_sintron will do, due to line 7, in qr_solve.cpp.

interestingly changing to Time.h didn't work for me (arduino sdk 1.6.9) however commenting out the include line did...


text:
Error Downloading http://downloads.arduino.cc/packages/packages_index.json
I managed to update the library but getting error "Error Downloading http://downloads.arduino.cc/packages/packages_index.json" when updating the Board Manager. I switched the proxy to no proxy instead of automatic. Anyone can help me?

use your computer web browser to see if the URL is valid

I had the same issue and the fix that worked for me is to directing the jvm to use the Windows Certificate Store instead of the ancient cacerts file that comes with java 1.8. This may also help people behind a Cisco Umbrella filter.
One does this by adding the following lines to "C:\Program Files (x86)\Arduino\arduino.l4j.ini" (note, you will need to open a text editor as an administrator, then open the file in question, in order to edit it):
-Djavax.net.ssl.trustStore=NUL
-Djavax.net.ssl.trustStoreType=Windows-ROOT

I found this answer here

The URL is wrong, and should read:
https://downloads.arduino.cc/packages/package_index.json

Note that "package_index" is in the singular, not the plural.
Check what you have in the "Additional Boards Manager URLs:" section of Preferences.


text:
Krida 4 ch ac dimmer triac fails to initialize from an Arduino
None of my channels initialize. I suspect a driver issue, but I have tried 2 different libraries.
I have this device:
Krida 4 channel
connected exactly like:
GND - > GND
VCC -> 5V
SYNC -> DIGITAL.3
CH1 -> DIGITAL.7

Libraries attempted:
https://code.google.com/archive/p/arduino-timerone/downloads
and the stock Arduino <TimerOne.h> from libraries manager
I tried all the different code samples but here is the most recent.
Code sample:
#include <TimerOne.h>

unsigned char channel_1 = 7;    // Output to Opto Triac pin, channel 1
unsigned char channel_2 = 6;    // Output to Opto Triac pin, channel 2
unsigned char channel_3 = 5;    // Output to Opto Triac pin, channel 3
unsigned char channel_4 = 4;    // Output to Opto Triac pin, channel 4
unsigned char CH1, CH2, CH3, CH4;
unsigned char i=0;
unsigned char delay_time=25;     // delay ms or flashing SPEED
unsigned char clock_tick;        // variable for Timer1
unsigned char CHANNEL_SELECT;    // variable for channel select

unsigned char CH[]={CH1,CH2,CH3,CH4};

unsigned char dim_level[]={5,8,10,12,15,18,20,25,30,35,45,50,55,60,65,70,75,80,82,85,88,92,95};   // don't use this massive for 60Hz
                                                                                // create new massive for 60Hz
void setup() {

  pinMode(channel_1, OUTPUT);// Set AC Load pin as output
  pinMode(channel_2, OUTPUT);// Set AC Load pin as output
  pinMode(channel_3, OUTPUT);// Set AC Load pin as output
  pinMode(channel_4, OUTPUT);// Set AC Load pin as output
  attachInterrupt(1, zero_crosss_int, RISING);
  Timer1.initialize(100); // set a timer of length 100 microseconds for 50Hz or 83 microseconds for 60Hz;
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here

}

void timerIsr()
{
    clock_tick++;

      if (CH[0]==clock_tick)
    {
      digitalWrite(channel_1, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_1, LOW);    // triac Off
    }

      if (CH[1]==clock_tick)
    {
      digitalWrite(channel_2, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_2, LOW);    // triac Off
    }

      if (CH[2]==clock_tick)
    {
      digitalWrite(channel_3, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_3, LOW);    // triac Off
    }

      if (CH[3]==clock_tick)
    {
      digitalWrite(channel_4, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_4, LOW);    // triac Off
    }
}

void zero_crosss_int()  // function to be fired at the zero crossing to dim the light
{
  // Every zerocrossing interrupt: For 50Hz (1/2 Cycle) => 10ms  ; For 60Hz (1/2 Cycle) => 8.33ms
  // 10ms=10000us , 8.33ms=8330us

    clock_tick=0;
}

void loop() {

for (CHANNEL_SELECT=0;CHANNEL_SELECT<4;CHANNEL_SELECT++)  // fade up
 {
  for (i=22;i>1;i--)
  {
    CH[CHANNEL_SELECT]=dim_level[i];
    delay(delay_time);
  }
 }

delay(2000);

for (CHANNEL_SELECT=0;CHANNEL_SELECT<4;CHANNEL_SELECT++)  // fade down
 {
  for (i=0;i<22;i++)
  {
    CH[CHANNEL_SELECT]=dim_level[i];
    delay(delay_time);
  }
 }
delay(1000);

}

The code uploads error free to one of the many Arduino Nanos (I tried fresh hardware) that I have.
I cannot establish continuity with my load input channel to any of the load output channels. It is though D7 never never does its job and flip the channel open. Nor can I get any continuity on any of the other channels.
The code is supposed to cycling through all of them but no current ever hits any of the 'load' on any of my channels (Chan 1-4).
Deeper inspection of the Arduino with a voltage meter shows that I am getting reverse polarity on my d7 pin. actually, d7 - d4 all have what appear to be incorrect cycles (reverse polarity) on them. These are all the pins that are supposed to be turning on channels. This does not look correct to me at all.
I suspect driver but I cannot find any other libraries to try that look sane.
How do I initialize my d7 Arduino pin correctly to bring my Krida 4 chan triac Load channel live?
or, did I miss something exceptionally ignorant? I am not experienced with this particular module.
photos:

First of all you should test if the SYNC interrupt is working, like turning on one LED or something you can debug. You switch on the mains AC and then you should detect this zero cross interrupt. If not, then maybe you configured an interrupt event on wrong pin.
Further, making do-while loops in interrupt routine is a no go. Your timeISR turns on one triac, then loops for 10us and turns the triac off. Well not so good implementation. You could skip delay, and turn off after another timeISR by making this ISR at 10us instead.
void timerIsr()  //10us
{
    clock_tick++;
    digitalWrite(channel_1, LOW);    // triac Off
    digitalWrite(channel_2, LOW);    // triac Off
    .....
    if (CH[0]==clock_tick)
      {
        digitalWrite(channel_1, HIGH);   // triac firing
      }

I made the code changes  https://bpaste.net/show/428d553e9881  and it stopped the LED from blinking on the device, but all the other behaviors are still the same.

But I am no longer reversed polarity on my arduino.

The reversed polarity is somehow impossible, because you supply the circuit with your Vcc and GND. The device has wired an optotriac to your Arduino outputs. Perhaps you swapped the voltmeter tips?

I can flip that reverse polarity back and forth by changing the code back and forth like a switch. I am using a Greenlee DM-45. Its old but pretty reliable. I can literally watch the flip live.

@boobie, is the problem solved? (you marked the answer accepted)

@Juraj yeah, gross n00b error. I had tested live AC with a 3rd party fan and got no response. But a tradition florescent lamp with an LED bulb fired up. Not sure why, but thats enough for this ticket.


text:
What are these components in Arduino Mega Schematic?

I was looking at Arduino Mega's reference schematic here and trying to understand how the circuit functions. However, I am unable to understand what these schematic symbols (marked in black rectangles) represent or what their function is. Can anyone please explain it to me?

@Transistor accurately answered what they are. I'll approach their specific function.
The Arduino Mega documentation gives some information on "RESET-EN" and "UBOOT."

"RESET-EN" allows you to enable/disable the auto-reset feature. By default there is a trace between the pads. That's why it look like there is a short in parallel below it. Cut the trace to disable auto-reset. Solder bridge back together to re-enable.
With auto-reset enabled, the board will automatically reset every time the serial communication is initially established. This causes problems if you are using a non-usb power supply and want to plug in for some debugging or have a design that opens and closes serial comm.
"UBOOT" is related to the DFU (Device Firmware Update) bootloader. This may be on the back of the board and will be different between revs.

The ATmega16U2/8U2 is loaded with a DFU bootloader, which can be activated by:

On Rev1 boards: connecting the solder jumper on the back of the board (near the map of Italy) and then resetting the 8U2.
On Rev2 or later boards: there is a resistor that pulling the 8U2/16U2 HWB line to ground, making it easier to put into DFU mode.

You can use this to update the USB firmware and even change the device name when you plug it in. More info here.

"GROUND" can optionally link USB ground (UGND) to the main circuit ground. I don't know enough about USB comm circuit design to understand what the advantages or disadvantages are here. Perhaps someone else can clarify this idea. ATMEGA8U2-MU datasheet for reference.

The symbol indicates a pair of solder pads that can be bridged by the user using a blob of solder.
Here's something similar.

Figure 1. Source: CyberGibbons.


text:
Only getting error from ESP8266 AT commands
I am trying to get the ESP8266 work with Arduino AT commands. I am using the due. How do I get the ESP8266 to respond with anything other than ERROR?
Here is the current serial output:
AT
ERROR

Here is my code:
void setup() {
    Serial.begin(9600);
    Serial3.begin(115200); //Manufacture said this is the correct baud rate
}

void loop() {
    if ( Serial3.available() ) {  Serial.write( Serial3.read() );  }

    if ( Serial.available() )  {  Serial3.write( Serial.read() );  }
}

Here are my pin connections:
RX3  -> ESP TX
TX3  -> ESP RX
GND  -> GND
3.3V -> CH_PD + VCC

do you have CR/LF set in Serial Monitor?

Don't cross post. You also asked this on SO.

I didn't have CR/LF set. That fixed my problem

The AT firmware responded with ERROR because it received data, but timed out waiting for the CR/LF line ending.
AT commands must be terminated with Carriage Return '\r' and Line Feed '\n' control bytes/characters.


text:
Interfacing Figaro KE25 Oxygen Gas Sensor with Arduino Uno
I have been trying to interface the Figaro KE25 2 lead fuel cell type oxygen gas sensor with Arduino Uno. I am not getting the required output on the Serial Monitor for regular air (Oxygen concentration of 19%).
I have attached the sketch I have typed out, the output I have obtained on the Serial Monitor, the output(mV) vs Oxygen concentration (%) graph of the Figaro KE25 sensor I have obtained from the datasheet, the chemical reactions governing the working of the sensor,the circuit diagram I have used, and the construction of the sensor.
In this question; I will explain the sensor first, then my circuit, then my sketch, and lastly the problem I have with my output.
In electronics, the Anode is the positive electrode and the cathode is the negative electrode. In electrochemistry, the Anode is the Negative electrode and the Cathode is the positive electrode. Do check the image of the construction of the sensor I have provided obtained from the datasheet.[![image of the construction of the sensor][1]][1] Full Technical Datasheet
The Cathode, that is, the positive electrode is the sensing electrode (Oxygen gets consumed here and an electric current is generated). Since a current is being generated by the sensor (fuel cell), no power supply needs to be given to the sensor. Check the image of the chemical reactions provided (obtained from the full technical datasheet of the sensor). Technical Datasheet
The sensor in question is an analog voltage type sensor. Keeping this and everything I have mentioned above in mind, I have constructed the following circuit with Arduino Uno. Refer the picture I have put up. I have connected the Cathode (the sensing positive electrode, red in colour) to the Arduino's analog A0 pin and the Anode (negative electrode) to the Arduino's ground.
The sketch I have used is as follows:
 /*the analog pin of the alcohol sensor goes into analog pin A0 of the
 Arduino*/

 void setup()
 {
     Serial.begin(9600); //sets the baud rate
 }

 void loop()
 {
     float v1;
     float oxy = 0.0;
     float v2 = 0.0;
     pinMode(A0,INPUT_PULLUP);

     /*To make sure that reading is zero when the circuit is open*/

     v1 = analogRead(A0);

     /*reads the analog value from the Oxygen gas sensor and this value can
     be anywhere from 0 to 1023 (10 bit ADC used in Arduino Uno)*/

     if(v1>900) //To make sure that reading is zero when the circuit is open
     {
         v1=0;
     }
     v2 = (v1*3000)/992;

     /*The above line calculates the output of the sensor in mV using the
     fact that a HIGH reading in an input pin of an Arduino Uno board is
     equivalent to a voltage of 3V or higher. When I displayed just 'v1',
     the lowest of the high values I got was 992. So I equated it to 3V
     (3000mV) and used the unitary method to find out what a non-HIGH v1
     value would be in terms of mV.*/

     oxy = v2/0.6;

     /*The above line calculates the Oxygen concentration from the mV output
     of the sensor using the output(mV) vs concentration(%) graph from the
     sensor's datasheet. The graph is a straight line passing through (0,0)
     and hence the governing equation is of the form y = m * x. Where 'y' is
     'v2' and 'x' is Oxygen conc. in %.*/

     Serial.print("Oxygen value: ");
     Serial.print(v1);
     Serial.print("    ");
     Serial.print(v2);
     Serial.print("mV    ");
     Serial.print(oxy);//prints the Oxygen value
     Serial.println("%");

     delay(1000);
 }

he output(mV) vs Oxygen concentration(%) graph provided in the datasheet is shown below. The straight line labeled as 'KE25' is to be considered.  Product information (datasheet)
he output I have obtained on the serial monitor is as follows:

Such a high voltage from the sensor is not possible. My output reading is not possible at all. Where have I made a mistake and how do I correct it?

Update 1 : I changed the line pinMode(A0,INPUT_PULLUP) to pinMode(A0,INPUT). Now I am getting sensible values on my Serial Monitor. However, I am also getting many '0' outputs (many). I am also getting many random values (many). I need more information on how to interface a fuel cell type Oxygen sensor using Arduino Uno in terms of how to get a proper voltage reading across such a sensor. I have found no question on electrochemical, fuel cell type Oxygen gas sensor interfacing. All questions asked are regarding sensors that require a power supply. In case of fuel cell type Oxygen gas sensors, current is generated when Oxygen is sensed and hence, no power supply is required. Also, if anyone is into electrochemistry, how do I check the voltage output of a fuel cell type Oxygen gas sensor using a voltmeter? Do I use a DC voltmeter or an AC voltmeter?
Update 2: I've made changes to the code based on @EdgarB's suggestions. The output I am getting now is better but still wrong. I checked if the sensors I am using are functional using a multimeter (I confirmed if the method I am using is right, and it is), and they are. The Oxygen values I am getting now are still really low: 6-8%. I should be getting: 19-21%. I used a reference voltage of 600 mV and modified the code.
Modified code:

 void setup()

 {

     Serial.begin(9600);//sets the baud rate
     analogReference(INTERNAL);
 }

 void loop()
 {
     const float A_REF = 0.6e3;
     const float Scalc = (1/0.6);

     float v1;
     float oxy = 0.0;
     float v2 = 0.0;
     pinMode(A0, INPUT);
     v1 = analogRead(A0);
     v2 = (v1 * A_REF) / 1024;
     oxy = v2 * Scalc;
     Serial.print("Oxygen value: ");
     Serial.print(v1);
     Serial.print("    ");
     Serial.print(v2,4);
     Serial.print("mV    ");
     Serial.print(oxy,4);//prints the Oxygen value
     Serial.println("%");
     delay(1000);
 }

Output:

If you remove the pinMode(A0,INPUT_PULLUP); does it improve the readings?

Read this page: https://www.arduino.cc/en/Tutorial/AnalogInputPins - Especially the bit entitled "Pull-up resistors".

@Majenko Thanks! That really helped. I changed pinMode(A0,INPUT_PULLUP); to pinMode(A0,INPUT);I had read that page before typing out my sketch, but I didn't pay much attention to the line that said: "Be aware however that turning on a pull-up will affect the values reported by analogRead()." Is this because in a short time interval like 1000 ms there isn't enough time for the voltage to drop to low and then rise again to the correct input given from the sensor?

Your problem stems from having the internal pullup resistor for A0 turned on.
The sensor is a current generator with a load resistor (plus thermistor) built in to convert the current into a voltage. By adding a pullup resistor you turn it into a voltage divider across 5V with a small current being injected into the central node:

simulate this circuit – Schematic created using CircuitLab
Since the datasheet doesn't specify the load resistance nor the source current I have made up some values to demonstrate.
If we take just the current source and load resistance RL+RT and calculate the voltage drop across that we get:
V=R×I = 5000 × 0.00001 = 50mV

Which is a reasonable value. It's a lot of oxygen, but that's because these are made-up values.
Now what would be the voltage with the pullup resistor added? Well, this is where it gets a little more complex. At times like this it's easier to just simulate the circuit in something like the falstad simulator and I can tell you it's 757.1mV (If you want to learn how to do this kind of circuit analysis manually you should learn superposition theory).
A massive change.
Obviously you're not seeing a change that big - and that's because the pullup resistor is more than just a simple resistor. There's many more factors that influence the reading, including the output impedance of the network, as well as the rest of the internal ADC circuitry.
Suffice it to say, though, adding a pullup resistor is a bad idea when using the ADC.
But you want to keep the pullup resistor so you can know if the sensor is connected or not. That's not a problem. Just turn it on and off at will:
pinMode(A0, INPUT_PULLUP);
delay(1);
bool connected = analogRead(A0) < 900;
if (connected) {
    pinMode(A0, INPUT);
    delay(1);
    v1 = analogRead(A0);
}

It's recommended to wait a moment after changing the pullup resistor state before reading from the ADC to reduce electrical noise picked up by the ADC - hence the delay(1) calls.

You have three different issues here:

improper use of the pullup resistor
incorrect interpretation of the analog reading
too small input signal

Pullup resistor
Majenko already covered the first issue, with very good advice.
Interpretation of the analog reading
Code Gorilla already explained the second issue. However, since you do
not seem to understand, I will add my take here.
The formula to convert an analog reading to an actual voltage is
voltage = reading × analog_reference ÷ 1024.
Yes, it's 1024 rather the often seen (but erroneous) 1023. See the
manufacturer's datasheet, which is the only authoritative
reference. Doesn't make much of a difference anyway. The main issue is
the analog reference voltage which, in the default configuration, is the
same as the voltage powering the Arduino, i.e. 5 V.
In a comment, you wrote:

if a pin is configured as INPUT, then the voltage at the pin is 3V or
  higher

This is complete nonsense. The voltage on an input pin is whatever
voltage is provided by the circuit connected to that pin. If you
actually mean the threshold voltage for the pin reading HIGH, well,
that threshold is typically 2.6 V (see the “typical
characteristics” in the datasheet), but the exact value is not
guaranteed. The number you quote is “the lowest value where the pin is
guaranteed to be read as high”. In other words, the voltage threshold
can be lower than 3 V, but not higher.
And all this is completely irrelevant to you. The input thresholds are a
feature of the digital input circuitry attached to the pin. This circuit
is responsible for deciding whether the pin is LOW or HIGH when you
digitalRead() it. But you don't care about the digital value: you are
using the pin as an analog input. The ADC converter is a different
circuitry that has absolutely nothing to do with the digital input.
You can even disable the digital input of the pin and still use the ADC.
Low signal
According to the graph you provide, the sensor should output
12.6 mV in normal air (21% O2). That's about
2.58 ADC steps. Thus you expect the reading to fluctuate between
the digital values 2 and 3. This is really quite low for your ADC.
A simple way to mitigate this problem is to change the analog reference.
The default is 5 V, but you can switch it to an internal
1.1 V reference that will significantly increase
your resolution: in setup(), call
analogReference(INTERNAL);

Then you can compute the oxygen level as follows:
const float A_REF = 1.1e3;         // analog reference = 1,100 mV
const float SENSOR_CAL = 1 / 0.6;  // calibration: %(O2) / mV

void loop()
{
    int reading = analogRead(A0);
    float voltage = reading * (A_REF / 1024);
    float oxygen = voltage * SENSOR_CAL;
    // ...
}

Another way to mitigate the signal weakness is to average multiple
readings. This can make your effective resolution better than the raw
ADC resolution.
ADC offset
The formula
voltage = reading × analog_reference ÷ 1024
applies only to an ideal ADC. In practice, any ADC has some offset error
and gain error. Taking them into account, the formula becomes:
voltage = (reading + offset_error) × analog_reference ÷ (1024 + gain_error)
In many cases these errors are too small to care about. However, since
you are working near the resolution limit of your ADC, the offset error
can be an important concern. The gain error is no issue here, so you can
forget about it.
If you have a voltmeter, you can easily determine the offset error:
measure a low voltage, like the one from your sensor, with both the
voltmeter and the ADC. Ideally, you would average many ADC readings to
get a better resolution. From the voltmeter measurement, you compute the
average reading you would expect from your ADC, then you get
offset_error = expected_ADC_reading − actual_ADC_reading
Then you use this measured offset to correct your readings:
const float offset_error = ...;  // measured with the voltmeter

void loop()
{
    int reading = analogRead(A0);
    float voltage = (reading + offset_error) * (A_REF / 1024);
    // ...
}

I meant that if a pin is configured as INPUT and is at HIGH then the voltage at that pin is 3V or higher. I will read the rest of your answer and update on  the status soon.

@athindrapavan: Understood what you mean, but: 1. It's wrong (a pin can read HIGH even at 2.2 V) 2. It's irrelevant to an analog reading.

First of all, thanks! That helped in getting a better, more precise output. Plus, I understand the assignable constants better now. But I'm still getting a wrong output in terms of the range of Oxygen percentage values I should be getting. I'm getting around 6-8% of Oxygen which is still too low. It has to be 19-21% in regular air. I checked if the sensors I am using are functional with a multimeter and they are. I'll update the question with the modified code and the output I am getting in some time. Please do check it.

@athindrapavan: 1. The internal analog reference is 1.1 V, not 600 mV. You cannot just make up a number and expect that to work. 2. You may also suffer from ADC offset error. See the amended answer.

@ EdgarB Your answer made a lot of sense and the setup is working now. Is the offset error value sensor dependent? That is if I use 2 new Figaro KE-25 sensors, then will it cause an error in one of the 2 sensors depending on which one I used to calculate the offset error?

@athindrapavan: No, the offset error is intrinsic to the ADC. It should not depend on the sensor. It may depend though on whether you are using analogReference(DEFAULT) (i.e. Vcc) analogReference(INTERNAL) (i.e. 1.1 V).

So since I've used the latter, it's intrinsic to the ADC? Also, thanks a ton! Your answer was very detailed and a lot of help.

You calculation of v2 is incorrect.
v2 = (v1 * 3000) / 992;

The maximum value v1 will have is 1023 and this equates to 5v (not 3v).  So to calculate the voltage v2 I think you should be doing:
v2 = (v1 / 1023) * 5000;

But this will make your calculations even further out!

The maximum voltage at a pin that is configured as OUTPUT is 5V in a 5V Arduino Uno board. However, on the same board, if a pin is configured as INPUT, then the voltage at the pin is 3V or higher. Check [https://www.arduino.cc/reference/en/language/variables/constants/constants/]

I was just reading what analogInput() said.


text:
How do I configure a pin to be a bidirectional and open collector?
I want to communicate with a keyboard asynchronously through a single open collector, bidirectional data pin. As part of the protocol, the data pin is active low and is pulled low by either the host or connected device.
Some code examples configure the pin direction to switch input to output depending on wether the host want to input or output a signal. Constantly switching the pin directions seems a bit naive.
Are there better methods?

Depends on the MCU in use.

If the other end of the link has the same signal voltage as your
Arduino, you can simulate an open collector with a single pin:

digitalWrite(pin, LOW); pinMode(pin, OUTPUT); sets the pin to output
an active low signal.
pinMode(pin, INPUT_PULLUP) sets the pin to input mode, or output
passive high which, in open-collector mode, is the same thing.

Note that in the first case the order of the commands is important: on
AVR microcontrollers, if you set the mode to OUTPUT before writing
LOW, the pin will for a short time output an active high, which is
forbidden in open-collector mode. I don't know how other MCUs would
behave in the same situation though.
Edit to address Ignacio Vazquez-Abrams’ comment: An open-collector
bus needs a pullup resistor on each data line to function properly. If
that pullup is already provided by your keyboard, or your cable, then
you should use pinMode(pin, INPUT) to accurately emulate an
open-collector output on the Arduino side. Otherwise you have to provide
that pullup, either as an external component or by using the internal
pullup of the MCU. Beware that the latter may be a little bit weak,
depending on your data rate.

You do not want the pullup enabled if you are trying to accurately emulate an OC output.

@IgnacioVazquez-Abrams: Right. I edited my answer to address this very valid point.

Depending on the data rate it also may be good to write the pins PORT and DDR registers directly, which works way faster than usage of digitalWrite(). Though for slow communication it doesn't really matter.

Just to clarify, issuing those two commands will enable the pin to input and output a signal?  Correct?  Also, just for out of curiosity, could splitting the data pin between an input and output pin work as well?  Thanks.

@ATL_DEV: Yes, that's it. Splitting the data pin can work, but it will not make matters simpler, and it is essentially pointless.


text:
How do i send ads1115 data over spi to master arduino
I am trying to send ADS 1115 data which is connected with Arduino mega_1 over I2C and arduino Mega_1 is connected with arduino Mega_0 over SPI.
Arduino Mega_1 is act as a slave and send ADS 1115 data to master device..
I think my whole setup is working but i want to received actual data of ADS 1115 on master Arduino
Here is screenshots of results of my code
master
#include <SPI.h>

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

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait

void loop (void)
{
byte a;

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('a');  // add command
a=transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("results:");
  Serial.println (a);

  delay (1000);  // 1 second delay
}  // end of loop

slave
#include <Wire.h>
#include <Adafruit_ADS1015.h>
int out_buf;
int adc0;

// Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */
Adafruit_ADS1015 ads;
// what to do with incoming data
volatile byte command = 0;
void ss_falling ()
{
  command = 0;
}
void setup (void)
{
 ads.begin();
 Serial.begin(9600);
 //ads.startComparator_SingleEnded(0, 1000);
// have to send on master in, *slave out*
 pinMode(MISO, OUTPUT);

// turn on SPI in slave mode
 SPCR |= _BV(SPE);

 // turn on interrupts
 SPCR |= _BV(SPIE);
 attachInterrupt (0, ss_falling, FALLING);

}

// SPI interrupt routine
ISR (SPI_STC_vect)
{
 byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = out_buf; // add 15
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
adc0 = ads.readADC_SingleEnded(0);
Serial.print("AIN0: "); Serial.println(adc0);

out_buf=adc0;
//int buff = atoi(out_buf);
Serial.print("AIN1: "); Serial.println(out_buf);
delay(1000);
 }

i am sending 1570 but on Master side i received 35 i think ADS data is of 16 bits i.e 2 bytes and SPI received only 1 byte at a time i am stuck here please help me.
Thank you in Advance
example

My Problem is solved now, thanks to the almighty. I did few changed in code as:
1. Converted the received int type data from ADS to Char.
2. Stored it in an Array, to form a string.
Here is my Modified Slave Code:
#include <Wire.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1015 ads;
void setup (void)
{
ads.begin();
 Serial.begin(9600);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit(SPE);

  // turn on interrupts
  SPCR |= bit(SPIE);
}  // end of setup

char buf[20];
volatile int pos;
volatile bool active;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  if (c == 1)  // starting new sequence?
    {
    active = true;
    pos = 0;
    SPDR = buf [pos++];   // send first byte
    return;
    }

  if (!active)
    {
    SPDR = 0;
    return;
    }

  SPDR = buf [pos];
  if (buf [pos] == 0 || ++pos >= sizeof (buf))
    active = false;
}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
int adc0=0;
adc0 = ads.readADC_SingleEnded(0);
itoa(adc0,buf,10);
Serial.print("AIN1: "); Serial.println(buf);
delay(500);
}  // end of loop

On Master side
We are receiving string by sending one dummy value at a time.
Here is modified master code:
#include <SPI.h>

void setup (void)
{
  Serial.begin (9600);
  Serial.println ("Starting");

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{
  char buf [20];

  // enable Slave Select
  digitalWrite(SS, LOW);
  SPI.transfer (1);   // initiate transmission
  for (int pos = 0; pos < sizeof (buf) - 1; pos++)
    {
    delayMicroseconds (15);
    buf [pos] = SPI.transfer (0);
    if (buf [pos] == 0)
      {
      break;
      }
    }

  buf [sizeof (buf) - 1] = 0;  // ensure terminating null

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.print ("We received: ");
  Serial.println (buf);

  delay (500);
}  // end of loop

Implementing SPI slave mode is a little more tricky than you may think.  The most important thing to remember is that it's not a "Give me X" -> "Ok, here is X" kind of protocol.  It's actually a "Here's X" <=> "Here's Y" protocol.
That is, at the same time that the master sends X to the slave, the slave sends "Y" to the master.
The way you have it is that the master sends "a" as a command and discards what it receives.  The slave remembers that "a" as the "command". Then the master sends 0, and remembers what it receives. The slave receives that 0 and thinks "Ah, I got the command last time, so it must want the value" and queues up the value to be sent the next time a transaction occurs.  That then gets thrown away, since that occurs when the next "command" is sent.
You need to be a little more cunning, and implement a finite state machine to work out where in the stream you are.

When SS falls set a "byte counter" to 0.
When a byte is received examine the "byte counter":

Byte 0: If it's an "a" then place the first byte of the value in SPDR.
Byte 1: Place the second byte of the value in SPDR
Byte 3: Do nothing (or place 0 in SPDR)

Increment the byte counter

So the transaction goes something like this (1570 is 0x622 in hex, and I choose "little endian" since the AVR is naturally little endian):
Master Sends        Slave Queues          Master Receives
'a'                 0x22                  Rubbish
0                   0x06                  0x22
0                   0x00                  0x06

'a'                 0x22                  0x00
0                   0x06                  0x22
0                   0x00                  0x06

The important thing to remember is that the master receives what the slave queued on the next transfer.

My SPI communication is working fine because i also tried addition and subtraction between master and slave and the result was "ok "

If your spi communication were working fine you wouldn't be here asking us for help...

dude read this lines "i am sending 1570 which is a ads1115 data but on Master side i received 35 i think ADS data is of 16 bits i.e 2 bytes and SPI received only 1 byte at a time." SPI is ok to me.... i think there is something missing like byte to char conversion or split 16 bit adc data into 8 bits and thn sent to master that is my real problem.

35 has no relation to 1570. The closest you could be receiving would be 34 (0x22). Fixing your code in the way I specify not only fixes the mess you made of the sending system, but also fixes the 16-bit issue. Oh, and make your out_buf volatile. Also the out_buf should be "captured" at the point you either queue the first byte, or when SS falls.

i added two more screenshots in which i send 10 and in return i received 20  "20=10 +10"

It's pure chance that sometimes you happen to receive a result you think is right. It isn't You're receiving old results from previous transactions that never got sent.

ok if i am doing wrong thn what is the right way to send ads data to master arduino by using spi

How I detailed in my answer.


text:
Programmatically Upload Arduino Sketch From Android App
I am attempting to build an Android app from which I can can upload a .hex file to my Arduino(Leonardo). I am aware of a few apps in the Google Play store that are capable of this functionality but I can't seem to find any actionable resources on how to go about doing this. I am aware that the desktop Arduino IDE uses AVRDude to perform the upload but I don't believe AVRDude is available on Android so I'm at a complete loss here. Does anyone know how I would go about accomplishing this?
After some more searching I now know that the Leonardo(ATMega32u4) uses the AVR109 Protocol to flash new programs onto the hardware but I'm still at a complete loss as to what that process is and how I'd reproduce it in Java.

If you need the result, use one of the existing apps or see if its author will license the key parts to you.  If you want something of your own, then you may end up having to do most of the work of creating (or at least porting) it yourself.

@ChrisStratton I need a solution which I have full insight/control over. I have no problem doing the work and would actually prefer it, but I have very little understanding of the work that needs to be done which is why I'm here. I've been in contact with one developer but the interaction hasn't been as helpful as I thought it might be. I am unfortunately fairly new to this side of things so I don't know the right things to look for, search for, etc.

If I wanted to do this for a conventional Arduino I'd start by figuring out the operations against a serial API to talk to the bootloader, and perhaps test it against something exposing desktop serial ports to Java, as debugging Android host mode stuff is a pain given you have to use ADB-over-wifi.  You might try to figure out how avrdude works, for example.  Then I'd try to combine that with existing code that is out there for talking serial-over-USB to Arduino boards with the various device-side chipsets.  For a leonardo type board the two pieces may be more tightly coupled.

Solid tips. I'll start looking through all of that, thanks a bunch!

Try the Physicaloid library for Android which seems to be a complete AVRdude implementation on Java.

If I wanted to do this for a conventional Arduino I'd start by figuring out the operations against a serial API to talk to the bootloader, and perhaps test it against something exposing desktop serial ports to Java, as debugging Android host mode stuff is a pain given you have to use ADB-over-wifi. You might try to figure out how avrdude works, for example. Then I'd try to combine that with existing code that is out there for talking serial-over-USB to Arduino boards with the various device-side chipsets. For a leonardo type board the two pieces may be more tightly coupled.
Copy of Chris Stratton's comment which was acknowledged as an answer.