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:
Why is there a plastic sleeve on my HC-05 bluetooth module
I would like want to know why the bluetooth module has a plastic sleeve covering it?
Is it possible to remove it?

It is to protect it. You should keep it so that the modules lasts longer.
If you remove it, just don't do anything stupid.

To protect it against ham fisted newbies from causing short circuits.
Yes, you can remove it, as long as you're not a ham fisted newbie that is going to cause short circuits.

source: Stack Exchange

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

sort: votes


text:
AC meter By ADC timer interrupt from Nick Gammon
I want to read ADC from the pin A0 and A1. I have written in this code, however.
I took this code came from Nick Gammon
Thank You
//////////////////////////////////////////////////////////////////////////////
this is code
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

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

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

What is the problem??

Just change ADMUX in the ISR.

I want to read from a0 and a1, but the code read from a0 alone.

what  change ADMUX ?

It is unclear what you are asking. Please improve your question.

This is code read ADC from A0  (voltage)  but I want to read ADC from A0 (voltage) and A1 (current )  I need to write code to add, however.

Please stop repeating the question! This question is very badly written, and hard to understand. Repeating does not help! Instead, read How to ask, click on the edit link, and take the time to write properly. You should also link to the Gammon's page from where you copied that code.

I want to read ADC from the pin A0 and A1

In the code you posted the first line is:

const byte adcPin = 0;  // A0

To read from A1 the change is simple:
const byte adcPin = 1;  // A1

i am sorry i come from thailand

Whatever country you are from does not excuse from you posting the same question many, many times.
I suggest you read the datasheet:
ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet
Scroll down to 24.9.1 ADMUX – ADC Multiplexer Selection Register

You can read two analog channels like this:
int first_reading = analogRead(A0);
int second_reading = analogRead(A1);

If this does not fit your purpose, then your question was not asked
properly: rewrite it and clearly state your requirements. Explain why
the simple solution does not work for you.
If this does work for you, then stop (for now) reading advanced
tutorials, like the one where you found your code, and focus on the very
basics: the Arduino examples in the 01.Basics section, then the
03.Analog section.

i want  interrup ADC A0 and A1

i am sorry i come from thailand

I am do Meter Ac.    adcPin A0(measure Voltage) and adcPin A1(measure Current)   Thank You

this code from Nick Gammon read adcPin = A0

constexpr byte  adc_mux_setting = bit(REFS0) | bit(ADLAR); // Left alligment for ADC result, so ADCH contains 8b result.

volatile uint16_t         sum_u = 0;
volatile uint16_t         sum_i = 0;
volatile uint8_t   resultNumber = 0;

// ADC complete ISR
ISR (ADC_vect) {
    if (resultNumber & 1) {
        sum_u += ADCH-(sum_u>>8);                  // 8bit resolution, something like floating average
    } else {
        sum_i += ADCH-(sum_i>>8);                  // 8bit resolution, something like floating average
    }
    ADMUX  = adc_mux_setting | (++resultNumber&1); // Expecting pins A0 and A1 (otherwise offset must be added)

    TIFR1 |= bit(OCF1B);                           // clear the flag otherwise it never starts ADC conversion (not without ISR)
                                                   // it's here because I don't want to ADC starts conversion before switching channel
}

void setup () {
    Serial.begin(115200);
    Serial.println("Start");

    // reset Timer 1
    TCCR1A  = 0;
    TCCR1B  = bit(CS11) | bit(WGM12);              // CTC, prescaler of 8
    TCNT1   = 0;
    //TIMSK1 = bit (OCIE1B);                       // it doesn't work without clearing OCF1B
    OCR1A   = 80;                                  // it never reaches 80 so it never sets interrupt flag
    OCR1B   = 79;                                  // 40 uS - sampling frequency 25kHz for both (15kHz for each)

    ADCSRA  = bit(ADEN)  | bit(ADIE) | bit (ADIF); // turn ADC on, want      interrupt on completion
    ADCSRA |= bit(ADPS2);                          // Prescaler of 16
    ADMUX   = adc_mux_setting;                     // A0 goes first
    ADCSRB  = bit(ADTS0) | bit(ADTS2);             // Timer/Counter1 Compare Match B
    ADCSRA |= bit(ADATE);                          // turn on automatic triggering
}

void loop () {
    if (resultNumber == 0) {                       // print results after 128 measures for both channels
        Serial.print(sum_u);
        Serial.print(' ');
        Serial.println(sum_i);
        while (resultNumber == 0);                 // I want to print it only once per iteration
    }
}

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


text:
and gate based on truth table
I have to code in arduino the logic gates based on the truth table with two inputs. I searched for some examples, however all that I found is using && to compared them using only onf if else condition. What I need is to do it using all the possible cases. This is what I have, however only the last condition is working. I ask you please clarify to me what concept I am not understanding well, or what is wrong in my logic. Thank you.
  const int p2  = 2;  //Ground G
  const int p13 = 13; //Input A
  const int p15 = 15; //Input B

  void setup() {
    // put your setup code here, to run once:
    pinMode(p2,   OUTPUT);
    pinMode(p13,  INPUT_PULLUP);
    pinMode(p15,  INPUT_PULLUP);
  }
void loop() {
  // put your main code here, to run repeatedly:
  if ( digitalRead(p13) == 0 && digitalRead(p15) == 0 ){
    digitalWrite(p2, HIGH);
  }

  if( digitalRead(p13) == 0 && digitalRead(p15) == 1 ) {
    digitalWrite(p2, LOW);
  }

  if( digitalRead(p13) == 1 && digitalRead(p15) == 0 ) {
    digitalWrite(p2, LOW);
  }

  if( digitalRead(p13)== 1 && digitalRead(p15) == 1) {
    digitalWrite(p2, LOW);
  }

}

"What I need is to do it using all the possible cases." Uh... there are only two possible cases. Either they are both HIGH, or the output is LOW.

Well, I am thinking in terms of input and output, no matter if the output is high or low, so there are 4 cases. I know what you mean, it is just this is an assignment. So I would like to check with the pin in my board, I do not know if I explain well, I  doing my best.

Let me give some feedback on your code, kind of a small code review:
const int p2  = 2;  //Ground G
const int p13 = 13; //Input A
const int p15 = 15; //Input B

This is useless. The purpose of creating these constants is to give them
meaningful names, and p2 is no more meaningful than just 2. You
can remove these definitions and replace in the following p2 with
2, etc. Or you could find better names:
const int inputA_pin = 13;
const int inputB_pin = 15;
const int output_pin = 2;

Notice that the comments that you put next to the constants are not
needed anymore, as the names are now explicit enough.
void setup() {
    // put your setup code here, to run once:

This comment is useless, better remove it. It is in BareMinimum.ino so
that you know what to put there, but now that you have done it, no need
to keep the comment.
if (digitalRead(p13) == 0 && digitalRead(p15) == 0) {
    digitalWrite(p2, HIGH);
}

I assume you are using negative logic: the user presses a button, and
makes the input LOW, to mean TRUE. If this is the case, you are not
being clear enough about it. You should at least have a comment to make
this explicit, e.g.:
int inputA = !digitalRead(inputA_pin);  // negative logic

where ! is the NOT logic operator.
Otherwise your program seems fine. If it does not work, check your
wirings. John Burger's suggestions on how to make it better are very
sound, and you should probably follow them. But I would like to show you
another way of writing this that could be relevant to your course: you
can implement the truth table as an actual table, i.e. a C++ array. Here
is my version:
const int inputA_pin = 13;
const int inputB_pin = 15;
const int output_pin = 2;

const bool truth_table[2][2] = {
            /* false  true  */
/* false */  { false, false },
/* true  */  { false, true  }
};

void setup() {
    pinMode(inputA_pin, INPUT_PULLUP);
    pinMode(inputB_pin, INPUT_PULLUP);
    pinMode(output_pin, OUTPUT);
}

void loop() {
    int inputA = !digitalRead(inputA_pin);  // negative logic
    int inputB = !digitalRead(inputB_pin);  // ditto
    int output = truth_table[inputA][inputB];
    digitalWrite(output_pin, output);
}

Notice that this uses the equivalence between false/true and 0/1.
In the case of the AND gate, this looks just like a silly classroom
exercise. However, for a complex gate with four inputs or more, and a
non-trivial truth-table, this technique may be the most straightforward
implementation.

Addendum – You wrote in a comment:

Not clear how your truth table works.

You are probably confused by the fact that I laid out the table in
compact form, with the first input in the row headings (comments on the
left edge) and the second input in the column headings (comments at the
top), just like a traditional multiplication table. Incidentally, it
happens to be a 2×2 multiplication table.
I could have used the more common “flat” layout, where each combination
of inputs is represented as one line of the table:
const bool truth_table[] = {
    /*   A     B     output  */
    /*-----------------------*/
    /* false false */ false,
    /* false true  */ false,
    /* true  false */ false,
    /* true  true  */ true
};

But then, since it's now a 1D table, the table index has to be computed
from both inputs, as each input provides one bit of the index:
int output = truth_table[inputA<<1 | inputB];

This is actually how I would do it if I had to simulate a gate with more
than two inputs. I've used this technique to make a 2-bit Gray code
adder (4 inputs, 2 outputs) which,
with a little bit of optimization, boils down to
for (;;) PORTB = truth_table[PINB & 0x0f];

Your explanation is very clear, I will try it. Negative logic is  Because the board I am using has the LED weld to it. Not clear how your truth table works.

@Sora: You may find the truth table easier to understand if it has the more common flat layout. See expanded answer.

I've got it, again your explanation has many details. Do not why the led is on if I have for A = false and B = true, in this case the led must to be turn off, the other cases are ok, should be something wrong with the pin of my board?

Your whole code can be replaced with one line:
digitalWrite(output_pin, digitalRead(inputA_pin) && digitalRead(inputB_pin));

That is, write out the results of a boolean AND on the state of the two inputs.

Your question title says "and", which means that if input1 is HIGH AND input2 is HIGH, then output should be HIGH. Your first line has
(...==0 && ...=0) digitalWrite(..., HIGH);

Surely these should be ==1?
Another thing is that every line of code in your program is re-reading the inputs. You should read them once, then decode the meaning behind them. So:
int input1 = digitalRead(p13);
int input2 = digitalRead(p15);

if (input1==1 && input2==1) {
    digitalWrite(p2, HIGH);
} // if
else if (input1==0 && input2==0) {
    digitalWrite(p2, LOW);
} // else if
else if ...

But note that the last three options are all the same: the code simply writes LOW. So you can combine all the last three cases into one step.
In other words, there's a single special case (both inputs ==1), and an everything-else case. In this code, I only read the inputs once, since I'm only looking for the special case. If it doesn't exist, then I simply do the alternative:
if (digitalRead(p13)==1 && digitalRead(p15)==1) {
    digitalWrite(p2, HIGH);
} // if
else {
    digitalWrite(p2, LOW);
} // else

"Your question title says "and", which means that if input1 is HIGH AND input2 is HIGH, then output should be HIGH. "
Yes, you are right.It has to be like that in the natural behavior of the and truth table, however here I just followed  an example my teacher gave to me. I do not get it. I am using this to turn on and turn off a led. I think he does it like that because the led is already turn it on before the push the pin. is it really a big difference?
Got it with the combination. Teacher ask us to write the code as it is in the truth table, that is why I did not combine it.

The official designation for what you supplied is called the NOT OR, or NOR. There are two ways to look at it: either it's "Neither input1 NOR input2 is HIGH", or that it's exactly like AND but in the opposite direction. Just to be even more confusing, some systems say that ON is 0 - but in those systems, the result of 0 AND 0 would be 0, not 1.


text:
Arduino resets my MacBook Pro
Every time I connect the Arduino Uno to the Mac through USB port, the Mac restarts. Why is this happening? How can Arduino make such a sophisticated machine reset? This also happens with my ESP12E Node MCU.

Have you considered blaming the cable? The port?

Is the arduino connected to anything else or is the only connection to the computer? It's just as easy if not easier to make a sophisticated machine reset than a simple one.

Tried using different cable, cant really blame the port because my Mac is pretty new. This is happening ever since i upgraded to Sierra. The Arduino is not connected to anything.

@MilapJhumkhawala - If the Arduino is not connected to anything how is it reseting you mac? :)  Is the port you are using on the new Mac a port that can be used with an Arduino (USB2)?
It sounds like an OS problem (if that is what sierra is) Could you try your Arduino on a real computer?

I hope "real computer" isn't meant to start a flame war. We're big boys and girls in this space who use Unix/Linux, Windows, or MacOS on manufactured/purchased or home-built hardware according to what suits our own needs and wants. No one has to change hardware or OS to successfully develop embedded software for Arduino or something else....

... I can confirm that Apple hardware and operating systems support Arduino development absolutely as well as do Unix-oid or various flavors of Windows OSes on appropriate hardware. I made a living writing embedded systems with Digital, Data General, IBM, and Dell computers with Digital, Data General, and Microsoft (from DOS onward) operating systems and continue to develop with Apple hardware and operating systems, right up to Sierra including the Sierra betas. They all work. Use what works for you.

It is almost certainly a device-driver issue. Since Arduinos are probably a little way down the pecking order for things that Apple is interested in, they probably don't test as extensively as (say) printers.

How can Arduino make such a sophisticated machine reset?

Device drivers would operate with elevated privileges, because they need to control, well, devices, like hard disks, printers, etc. If one has a programming error (like dereferencing a NULL pointer) then it could crash the whole operating system.

I suggest you look at this page: IDE 1.6.12 released with Sierra support and more
It says there:

A new version of the Arduino IDE (1.6.12) supporting OSX Sierra is available for download! All OSX users updating to Sierra are invited to also update the IDE to avoid crashes when uploading sketches.

This may or may not help. They seem to be suggesting that the IDE crashes rather than the Mac, but it could be worth trying.

There are some posts on macOS Sierra Usb Serial Crash which seem relevant:

I need to use a arduino nano and my Mac with mac os sierra is rebooted when i plug in the arduino

It sounds like the CH340 chip set used on clone Arduinos is causing this.
A suggested new device driver fix is at ch340g-ch34g-ch34x-mac-os-x-driver

It's generally not "Arduinos" as such. Mainstream Arduinos with FTDI USB to serial chips or ATmegaXXu[24] microcontrollers are supported by drivers shipping with the OS, and those tend to be tested and work.
The problem tends to be with clones using CH340 based USB to serial chips, which are supported by vendor drivers of dubious reliability (though there are quite reliable third party drivers for them).

i have had the same problem and found that the CH340 driver was at fault.  With the Arduino MEGA clone attached to the computer, it would throw a kernal panic at startup, then keep restarting over and over.
With the clone unhooked, the computer started normally.  Therefore the driver when trying to load at startup was cauing a panic.
I went back to the web site and found an “updated” driver that solved the panic problem.  It starts and runs OK, BUT -

Every print command prints twice. A simple “Hello World” prints twice.

I don't have a solution for the double print.

The program would compile, but never load in to the clone.  When I switched the USB cable from a 6ft one to the included 1 ft blue one, it worked.

My MacOS is High Sierra 10.13.4 the simple solution is :

Download CH341SER_MAC.zip from here
https://github.com/awangga/NFCReader/raw/master/driver/CH341SER_MAC.zip
remove old driver, please open terminal and run command:
rm -rf /System/Library/Extensions/usbserial.kext
rm -rf /Library/Extensions/usbserial.kext
Unzip CH341SER_MAC and install CH34x_Install_V1.4.pkg then restart MAC,
after rebooting login to your MAC and open terminal,
Conect arduino into your Mac and Look at your serial folder :
ls /dev/
You can access your Arduino on /dev/cu.wchusbserialfa130 or /dev/tty.wchusbserialfa130 or just type : ls /dev/cu. then
tab twice.


text:
I2C on non I2C pins, possible?
I have 2 I2C devices that uses the same address. One of them is the DS3231 RTC. I use this library for the DS3231. I dont want to mess with the other one cause it is way more complicated then this one.:
#include <DS3231.h>

http://www.rinkydinkelectronics.com/library.php?id=73
Then, there is an object declaration for the real time clock:
DS3231  rtc(SDA, SCL);

I wounder if I can change that to:
DS3231  rtc(A0, A1);

I've seen the library but I haven't understand it yet (duh... I'm so stupid!). But is it possible to use an other pair of pins for I2C communication.
Note that I've already tried to use the soft I2C library but I really want to avoid it because it is just too much. If it is the final solution then so be it.

I suspect it wouldn't work because of interrupts and stuff.  Its really a question against the Wire library, because I suspect that's what it uses underneath.

If you can't get it to work you might want to look at a I2C Multiplexer (http://www.ti.com/product/PCA9544A) or in a board (http://www.hobbytronics.co.uk/pca9544a-i2c-mux?utm_source=google&utm_medium=googleshopping&utm_campaign=googlebase&gclid=CPWPmOel1c8CFUKVGwodx1gAkQ).  From a quick glance it looks like these might do the job and they are relatively cheep (~£5).

Have you read the big yellow block on the web page you link to? It kind of answers your question quite succinctly.

What is the other I2C device?

The library above is actually software I2C (from what I can see in the source code).

@MikaelPatel the other board is a GY-521

You can change the address of the GY-521 by pulling the AD0 pin to Vcc. After that the address will be 0x69 instead of 0x68.

Thanks, I also have to add this line in my code. But it should work fine:     MPU6050 mpu(0x69);

Great. Good point about changing the code to select the correct address. Would be very helpful for others with the same problem.

Ok, so I've realise that the anwser was somewhat on the page of the library (that I completly ignored). I can change the pins like I did because the library uses a "TWI-/I2C-like protocol".

The library has not been tested in combination with the Wire library and I have no idea if they can share pins. Do not send me any questions about this. If you experience problems with pin-sharing you can move the DS3231/DS3232 SDA and SCL pins to any available pins on your development board. This library will in this case fall back to a software-based, TWI-/I2C-like protocol which will require exclusive access to the pins used.


text:
GSM and Bluetooth modules on 1 Arduino Uno board
I couldn't find anything on this topic.
Task: to connect sensors to Arduino board via Bluetooth module, process the received data and then send the data to server via GSM module.
Question: Is it possible to connect both of these modules to 1 Arduino board? If I'm not wrong, Arduino Uno has only one pair of Rx Tx pins, while for these two modules each has its own pairs on Rx Tx pins.
I need to know this before ordering them. So, please help

It sounds to me that a Raspberry Pi with a BT and GSM dongle would be better/easier/cheaper in this situation.

Or a cheap cellphone with a custom app.

Take a look at the SoftwareSerial library which allows other pins to be used for Serial at speeds <= 57600
https://www.arduino.cc/en/Reference/SoftwareSerial

This is still problematic, as typically only one instance is supported, so the hardware serial must be repurposed from debug/uploading, which creates a lot of development headaches.  Essentially a classic Arduino is not the right choice for this.  Even something like a Leonardo would be better.

Hi @Chris, a board such as a mega2560 would better because it has a number of extra hardware serial ports but the question was for the Uno. Marat confirmed he has the one pair of tx/rx working so second port via SoftwareSerial will work well.

It may work, but only problematically - that single hardware serial is usually reserved for communication between the ATmega and development system.  Using it for communicating with something else means losing that, and having to take steps to de-conflict it, ie, providing a way to disconnect the peripheral during programming or using a different programming method such as ISP than the bootloader which is typically used with an Uno.

There are plenty of solutions I know of on the main hardware serial that don't affect upload. I agree it's a bit cumbersome having to disconnect rx/tx during upload but it's been the default workflow for many users for a long time. Plus software serial tx (1 pin) for debug is okay alongside other software serial. Quite often the bluetooth and gsm code can perform tasks on demand and at separate times allowing them both to use SoftwareSerial leaving the main port free. It's only a problem if the two soft connections are streaming data over the tx at the same time. So does depend on the usage.


text:
Talking to ADS8698 (18-bit ADC) over SPI
I want to talk to an ADS8698 over SPI (see page 36 for details on their SPI implementation) using a Teensy 3.2. Right now I'm only getting zeros back and I feel like (perhaps wrongly) that I've followed the datasheet correctly. I believe my SPI mode is correct and, given the clock rates I'm using, I should be observing the timing constraints properly.
(1) Is there a glaring error here? I haven't coded that many SPI interfaces, so I might have a novice mistake in there.
(2) Is there existing code for a product that uses a nearly identical SPI interface to the ADS8698 (any product that has a similar timing diagram would do)?
#include <SPI.h>

#define USB_RATE 19200//usb transfer rate
#define SPI_CLOCK 10000000//spi clock frequency

#define CS0 10

SPISettings ADC_SPI(SPI_CLOCK, MSBFIRST, SPI_MODE1);

void setup()
{
  // disable both multiplexers
  pinMode(CS0, OUTPUT);
  digitalWrite(CS0, HIGH);
  // prepare serial protocols
  Serial.begin(USB_RATE);
  SPI.begin();
}

void read_ADC()
{
  // begin the session by taking CS0 low
  SPI.beginTransaction(ADC_SPI);
  digitalWrite(CS0, LOW);// slave select disable
  // delayMicroseconds((int) (1e6 * 20/SPI_CLOCK));// wait > 16 clock cycles
  // transfer 16 bits while the ADC performs conversion
  SPI.transfer(0); // I'm not trying to set any registers, just waiting (zero is fine)
  SPI.transfer(0); // I'm not trying to set any registers, just waiting (zero is fine)
  // data should be ready, so try to read it
  Serial.println(SPI.transfer(0));
  Serial.println(SPI.transfer(0));
  // end the session by taking CS0 high
  digitalWrite(CS0, HIGH);// slave select enable
  SPI.endTransaction();
}

void loop()
{
  delay(1000);
  read_ADC();
}

The system is wired like this:

How have you wired it all up?

What do have connected to  analog input 0? Having 0's would be the right result it it's connected to GND.

Hi Gerben, thanks for the response. The system certainly is not noiseless. With nothing connected there will be non-zero readings from the ADC.

I've added the system wiring diagram.

Per the Datasheet PG47
During power-up or reset, the default content of the command register is all 0's and the device waits for a command to
be written before being placed into any mode of operation.
If your still working with this I'm going to be tackling this same thing very soon, hopefully I can get it to work with DMA.
https://forum.pjrc.com/threads/34863-Teensy-CC-Dummy-Load-300W/page4


text:
Serial Monitor "button" implementation
I have a small project and I have some problems while working on that. The idea of the project is as below:
I have an LED which is operated by two "buttons". The buttons takes two values (1 or0) which I have to send from serial monitor.
One button is for LDR sensor, which lights up the LED when its value is below 300 (in my code). The other button turns it off (Value 0). The buttons are working together, so I have to consider both of them in my statements. The problem is that I cannot play with the serial monitor it's just looping continuously and I cant type anything as input.
Can anyone help me with this to find a solution to be able to input values for both buttons?
Here is the code:
const int analogInPin = A0; //LDR PIN
const int digitalOutPin = 13; // LED PIN
int outputValue;

int sensorValue = 0; //

char Buton1; //LDR button
char Buton2; //Blutooth button

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

void loop()
{
  while (Serial.available())
  {
    Serial.println("Button1 value: ");
    Buton1 = Serial.read();
    if (Buton1 == '1')
    {
      Buton2 = Serial.read();
      Serial.println("Button2 value: ");
      if (Buton1 == '1' and Buton2 == '0')
      {
        sensorValue = analogRead(analogInPin);
        outputValue = map(sensorValue, 0, 1023, 0, 255);
        Serial.print ("Sensor: ");
        Serial.println(sensorValue);
        if (sensorValue < 300);
        {
          digitalWrite(digitalOutPin, 255);
        }
      }
      else if (Buton1 == '1' and Buton2 == '1')
      {
        digitalWrite(digitalOutPin, 255);
        Serial.print("Both buttons are ON ! !");
      }
    }
    else if (Buton1 == '0')
    {
      Serial.println("Button2 value: ");
      Buton2 = Serial.read();
    }
    if (Buton1 == '0' and Buton2 == '1')
    {
      digitalWrite(digitalOutPin, 255);
    }
    else if (Buton1 == '0' and Buton2 == '0')
    {
      Serial.println("Both buttons are inactive ! Please reset");
      break;
    }
  }
}

How are you supposed to know which 1 and 0 come from which button?

A simple approach would be to use bit 0 of serial data to control "button 1", and bit 1 of serial data to control "button 2".  As follows:
char sd = Serial.read();
byte button1 = sd & 1;
byte button2 = sd & 2; // Or (sd & 2)>>1 if you prefer

With the above code, button 1 is true for odd-digit inputs, and button 2 is true when (sd & 2)>>1 is odd.  For example, input 0 to turn off both buttons, 1 to turn on only button 1, 2 for only button 2, and 3 to turn on both.
You might also wish to button1 or button2 only when the input character represents a digit.  For this, you can say:
char sd = Serial.read();
byte button1, button2;
... ;
if ('0' <= sd && sd <= '9') {
    button1 = sd & 1;
    button2 = (sd & 2)>>1;
}

The first problem is that your code does not wait for anything to be typed, so it loops very rapidly. Serial.read() returns -1 when there is nothing in the buffer, so I imagine your codes is printing something like:
Button1 value:
Button1 value:
Button1 value:
Button1 value:

Try inserting
while( !Serial.available() )
   ;

before your serial.read() calls. This will force it to wait until you type something before it continues.

Each button has a 1 state and a 0 state. The combination will always be something like this:
if (button1 == '1' and button2 == '1')
do something
if (button1 == '1' and button2 == '0')
do something
if (button1 == '0' and button2 == '1')
do something
if (button1 == '0' and button2 == '0')
do something

How does this solve the problem in the question? The problem was "it is just looping forever".

as it has been pointed before you the read function returns a -1 when there are no information to access, what you can do is
while( !Serial.available() )
{
  //do nothing
}
Buton1=Serial.read();
Serial.clear();   //for having the buffer clear for the next button

See if this helps:
const int analogInPin = A0; //LDR PIN
const int digitalOutPin = 13; // LED PIN
int outputValue;

int sensorValue = 0; //

byte Buton1; //LDR button
byte Buton2; //Blutooth button

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

void loop() {
  while (Serial.available() > 0) {
    char inChar = Serial.read();
    if (inChar == 'l' || inChar == 'L')
    {
      Buton1 = Serial.parseInt();
      Buton1 = constrain(Buton1,0,1);
    }
    else if (inChar == 'b' || inChar == 'B')
    {
      Buton2 = Serial.parseInt();
      Buton2 = constrain(Buton2,0,1);
    }
    else
    {
      Serial.println("invalid input");
      while (Serial.available() > 0)
        Serial.read();
    }
    Serial.print("Buton1 = ");
    Serial.println(Buton1);
    Serial.print("Buton2 = ");
    Serial.println(Buton2);
    Serial.println();
  }
}


text:
ESP8266 Upload hex file Arduino IDE
I am using ESP12E Wifi module, using library based on Arduino. Is there any way I can upload hex file of the project to esp8266 using Arduino or any tool?
I need to send hex file instead of code to my client. Is there any way?

Hex file of what?  A program built for the ESP8266, or a program built for a classic ATmega Arduino talking to it?  Either way, while you may be able to obtain a hex file, you probably can't upload it with the IDE without various hacks, but would need to use avrdude (for an ATmega) or some other tool (for an esp8266) directly.

Hex file of the code compiled in Arduino for esp8266

Hex file or binary file? Why can't you just use the Arduino IDE?  Esptool (https://github.com/themadinventor/esptool) should do what you want though, but finding out the correct arguments might take some effort.

I see the main question you are asking is: "I need to send a hex file instead of code to my client. I want to keep my source code with me."
The mechanics of the final hardware solution aren't supplied but I will guess that your client is also using an Arduino or at least the same Atmel chip that you have in your Arduino, and will be using that chip to control the ESP8266.
When you build your sketch, there is a .hex file created that you can send to your client.
There are a few ways to keep the hex file around, and IDE 1.6.5 and up has a way to easily find this file:
Sketch > Export Compiled Binary
The sketch will compile.
Sketch > Show Sketch Folder
The .hex file will be in the sketch folder.
You can send this hex file to your customer.
If he is using an Arduino or ATMega-based solution to connect to the ESP8266, then the hex file can be loaded into his Arduino or to his Atmel chip. However, the Arduino IDE doesn't support import of hex files at this time.
Your client would have to load that hex file onto the Arduino with an ISP programmer of some sort. There are many ways to do this, and the best one for you will depend upon your circumstances and your client's skill set.
If the client is using an Arduino or has just embedded the same ATmel chip that is in your Arduino into his solution, you could also just program your Arduino, and then send him that chip.

Turn on Show verbose output during compilation in your Arduino IDE and press Verify. After compile you can examine the parameters sent to esptool.exe in the last line before Sketch uses.... You will see some .elf, .bin and .text files. These are the files you want to send.


text:
Why is Serial.begin(9600) interfering with my multiplexor functioning?
I have an Uno hooked up to a sparkfun 8 channel multiplexer (https://learn.sparkfun.com/tutorials/multiplexer-breakout-hookup-guide). I have it wired up like this:
Arduino0 --> S0
Arduino1 --> S1
Arduino2 --> S2
Arduino3 --> Z
Arduino 5v --> VCC
Arduino GND --> GND

I'm running a simple code to blink two different LED's, one attached to Y7, and one attached to Y6.
//Define MUX pins
int pin0 = 0;
int pin1 = 1;
int pin2 = 2;
int zOutPut1 = 3;

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

    // Set controll pins
    pinMode(pin0, OUTPUT);
    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
    pinMode(zOutPut1, OUTPUT);
}

void loop() {
    samplerStarter();
}

void samplerStarter() {
    sample(1); // Takes sample for 5 min
    delay(1000);
    sample(2);
    delay(1000);
}

void sample(int noidNum){
    //MUX 1
    if(noidNum == 1) {
        digitalWrite(pin0, HIGH);
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(zOutPut1, HIGH); //Y7
    }
    else if (noidNum == 2) {
        digitalWrite(pin0, LOW);
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(zOutPut1, HIGH); //Y6
    }
    delay(500);

    //Set everythign back to Low
    digitalWrite(pin0, LOW);
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, LOW);
    digitalWrite(zOutPut1, LOW);

    delay(500);
}

But when I run this code, only the first LED attached to Y7 blinks. But if I remove the Serial.begin(9600) line:
//Serial.begin(9600);

Everything works fine. So I have no idea why this one line dealing with Serial Communication is affecting my multiplexor.

(Digital) Pins 0 and 1 are used by the hardware serial port you initialize with Serial.begin() on a classic Arduino like an Uno.
With this type of board it is generally best not to use those for any other purpose; if you do, you have to accept that you cannot use the hardware serial for input or debug/status output.
Even if you don't want to use serial during the operation of the your creation, having those pins connected to other functions can interefere with uploading sketches via the bootloader, or else the act of uploading a sketch can misoperate the functions connected to those pins.


text:
Does a GPS need a sim card?
I am trying to use a NEO-6M GPS to datalog my current position on a Micro SD card with the help of an Arduino Pro Mini. It doesn't transmit anything. So do I need a SIM card?

Caution:

The GPS tracker must be worked with a SIM card which may cost data and SMS fee.

No annual authorization fee for the first year. The coming annual fee details, please visit our company website.

There is nothing in this question relating to the Arduino. I suggest posting on the Electronics Stack Exchange.

For use as a GPS device, the NEO-6M doesn't need a SIM card.  For use as part of a tracker that sends SMS / GSM messages, ie, that uses the cell telephone system to send messages, you need a SIM card.  The SIM card is used to authenticate your system to the phone system.
See examples at "arduino gps and sms where are you arduino" (bigdanzblog.wordpress.com) and "vehicle tracking system using arduino gps and gsm" at circuitdigest.com.


text:
Comparing time_t values within an if statement
I am using an UNO with a RTC to control a light board. I'm using a simple control structure to decide when to turn things off and on. It's my understanding that a time_t value is just a number (number of seconds since 1970), and that I should be able to compare these time_t values as I would any integer- in this case comparing two time_t values to see which one is larger.
#include <Wire.h> // Needed for I2C protocol (RTC uses I2C)
#include "RTClib.h" //Good Library for RTC functions
#include <Time.h> // Needed for time_t variables and tmElements

RTC_DS3231 rtcVM; // From the RTClib library for use with an DS3231 RTC. Creates an object called rtcVM

DateTime nowVM; // Declare a Date Time object that will be used to hold the current time
time_t nowUniVM;// Declare a time_t object (Unix time) which is a float value (good for straight comparisons) to hold current time
time_t starter;// Declare a time_t object for the start time (time_t)
tmElements_t MagStart; // Declare a tmElement_t object to manually input the start Time

//FILL OUT START TIME AND DATE FOR FIRST SAMPLE (NO LEADIN ZEROS--"8" not "08")
byte startHour = 17;
byte startMin = 58;
byte startSec = 0;

byte startDay = 12;
byte startMonth = 10;
int twoDigYear = 16; // Enter last two digits of year

byte startYear = twoDigYear + 30 ; // This is a little confusing. This is the year offset from 1970 (AKA 2016 should be input as 46. Or just add 30 to last two digits).

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

  Wire.begin();
  rtcVM.begin();

  // Creates a tmElement by putting together all of Maggies Start Time and Dates
  MagStart.Hour=startHour;
  MagStart.Minute = startMin;
  MagStart.Second = startSec;
  MagStart.Day = startDay;
  MagStart.Month = startMonth;
  MagStart.Year = startYear;

  // Takes the tmElement and converts it to a time_t variable. Which can now be compared to the current (now) unix time
  starter = makeTime(MagStart);

  // Start message
  Serial.println("Start time is: ");
  Serial.print(hour(starter));
  Serial.print(":");
  Serial.print(minute(starter));
  Serial.print(":");
  Serial.print(second(starter));
  Serial.print(" ");
  Serial.print(month(starter));
  Serial.print("/");
  Serial.print(day(starter));
  Serial.print("/");
  Serial.println(year(starter));
  Serial.println("****************************");
}

void loop() {
  nowVM = rtcVM.now(); // get current time and hold in "nowVM"
  time_t nowUniVM = nowVM.unixtime(); // Calculate current time in Unix time

  samplerStarter();

  // RTC Get and Display
  DateTime now = rtcVM.now();// Getting the current Time and storing it into a DateTime object

  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();
  delay(3000);

  //Use these 2 to check the numerical values for comparisons
  Serial.println(starter);
  Serial.println(nowUniVM);
}

void samplerStarter() {
  if (starter < nowUniVM) {
    //if (1 < 2) {
    Serial.println("Start Time");
   }
}

I've included my entire test code here, but it's the last if statement that puzzles me. The idea behind that last statement is that it should print out "Start Time" when the start time is reached. The statement works if I compare something simple like (1 < 2), and the statement gets printed. So I assumed it would work if I did the same thing but with two different time_t values.
But if I input an appropriate start time under the "Fill Out Start Time" section, the print statement is not triggered when the start time comes to pass (AKA- when the start time (starter) is less than the current time (nowUniVM).
Is there something about time_t values that does not allow them to be compared like this? Or is there something in the way I'm creating my values that is messing up the comparisons?
My output to the serial monitor shows the actual time_t values, and they look like normal integers to me when they print out, so I'm not sure whats going on here. Why doesn't that last if statement print out when the start time is reached?

Please edit your question and state what error, if any, you are concerned about.   As is, your question provides some general background but it doesn't say what is wrong, or what is different from what you expected.

Thanks for the feedback, I made a few edits to further explain what I'm looking for.

Where did you get this Time.h?

Version 1.5 from the IDE Library downloader

You have two variables called nowUniVM. The fist one is a global
declared at the top of your program, and implicitly initialized to zero
by the compiler. Since you never update it, it is always zero. The
second one is local to loop(): it shadows the global variable inside
loop() and is updated periodically.
The function samplerStarter() only sees the global variable, which is
zero. Thus, the comparison boils down to
if (starter < 0)

But since time_t is an unsigned type, the test can never be
true.

Scope! Bad practice on my part

Though a quick question on scope in this matter. I defined the "starter" variable in my "setup" function. How is it that the "void loop" and "sampler starter" functions can see this "starter" variable, if void functions don't return any values?

You defined starter at global scope. You initialized it in setup(), which is perfectly fine.


text:
Using Arduino to pass data from a coin collector to android app
Okay. Basically I want the android app to be able to recognize that a coin was inserted into the coin collector before it allows the user to use certain functions of the app.
However I am unsure what would be the best way to pass the data from the coin collector to the Android app.  My currently train of thought is to have the coin collector connect to an Arduino board which would then connect to the android app and send the input through that connection.
I was wondering if anyone knows of a better way to achieve this, or whether this is an acceptable/standard solution.
Thank you in advance!

This is unanswerable without details of the Android hardware and security model on which the app will run.

The interface to the coin collector highly depends on the coin collector you use! The interface to the Android app highly depends on the Arduino environment you use; Bluetooth would be a reasonable approach. BTW, to me the idea of using high end electronics which requires old-fashioned coins to work sounds a little bit odd ;-)

Here are a couple of opitions for you:
1- Bluetooth - if in close range, an HC-05 will work great.
2- Wifi - wifi can work good. It is a little more complex then bluetooth but its range can get further. For example, a Tweet can be sent each time a coin is detected.
3- GSM - it is pretty much texting. You can make it so the coin collector texts you or someone there is a coin.
All of these solutions work great with the MIT app creator. It makes the data you receive much easier to process.

My take: use a nodeMCU (an ESP8266 based board) instead of Arduino.
nodeMCU have WiFi and you can run a minimal WebServer on it, so your Android app can communicate using simple HTTP GET commands. Using Bluetooth is not as convenient.
That's means the Android programming part will be easy and you can extend your solution to other platforms (iPhone).
And you only need a browser to develop and test the Android-Web Server interface on nodeMCU
Maybe you can even run your entire app in the nodeMCU, and use only a browser to interact with the coin collector.


text:
How to detect Genuino 101 from inside the code?
I am using a custom library for Arduino Mega which uses AES library for AES-128 encryption.
However, when I try to use that library in Intel Genuino 101 development board, it shows compilation error which is because the assembly language written in AES library was compatible with Atmel devices only.
And my question is whether there is a way, my code can automatically detect the GENUINO board by writing some sort of signature verification of this board and hence I can exclude the encryption part if it can successfully detect GENUINO 101.
For any queries, feel free to bug me, thanks.

No, you do not want your code to detect the Genuino 101. Your code cannot run until is is compiled. You want the compiler to detect whether it is compiling for an AVR-based Arduino or for something incompatible (whether it's ARC, ARM or Intel is irrelevant). What you want is called conditional compilation, and that is what KIIV's answer is about.

Yeah, True. Pardon me for the misunderstanding. This is what I exactly asked.

Arduino defines some macros so you can use conditional compilation. For example these are from boards.txt:

use ARDUINO_AVR_PROMICRO if it's specific for board variant
use ARDUINO_ARCH_AVR if it's specific for Arduino with AVR

Also avr-gcc defines macros according to cpu settings (this should be similar for other platforms too):

use __AVR_ATmega32U4__ if it's specific for only one MCU
use __AVR__ if it's compatible with all AVR based MCUs

And code examples:
#if defined(__AVR_ATmega88__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__)
// something for ATmegaXX8 family...
#else
// ...
#endif

#ifdef __AVR__
// Code related to AVR
#else
// Code for other architectures
#endif

More about predefined macros in avr-gcc.

Since the library seems to be compatible with all AVR-based Arduinos, it is probably best to test for #if __AVR__ (or #ifdef __AVR__) rather than for specific MCUs.

@KIIV I tried #if defined AVR and it accepts, but for #if defined(AVR_ATmega328), I could not find the expected solution. Can you suggest any link which explains more on this?

@goddland_16 That was an example. Arduino MEGA 2560 uses __AVR_ATmega2560__. You can check label on the MCU.

The correct Arduino architecture macro is ARDUINO_ARCH_AVR, not DARDUINO_ARCH_AVR.

@per1234: Fixed, copy&paste error as usual...

@KIIV yeah checked it. Working and for UNO it is [AVR_ATmega328P] .


text:
How to clear output buffer of Arduino Uno?
I have coded arduino for DHT11 which used to print humidity in first and temperature in second line. But some times when I open SerialPort I get absurd data.

Possible duplicate of https://stackoverflow.com/questions/10105666/clearing-the-terminal-screen

I am sending this data from arduino to pi serially and from pi to cloud. So some times I used to receive humidity as 6767.0 on the cloud. I am printing on console just for showing an example.

You can't.
The data you are seeing has already been sent by the previous execution of the sketch before the main MCU was reset. That data resides in a small buffer within the USB interface chip (or even within the USB CDC/ACM / USB UART driver itself, depending on your OS) to which you have no access.
You just have to ignore that data. The simplest way is to put a marker at the start of your program to indicate that whatever is receiving the data should start its receiving from this point on. Something like:
Serial.println();
Serial.println("START");

You could disable reset, by adding a capacitor between GND and RESET. Though this make uploading new code less convenient.

@Gerben It also means that you can start reading partway through a line of digits giving you similar garbage at the start of your reception. Doesn't really cure the problem. Better is to use a proper protocol rather than plain ASCII text.

Good point. Didn't think of that.

I am sending this data from arduino to pi serially and from pi to cloud. So some times I used to receive humidity as 6767.0 on cloud. I am printing on console just for showing an example. So is there no way to clean output buffer of arduino when ever it starts.?

I've circumvented this issue by sending a byte to the Arduino whenever I'm ready to receive data using this quick-and-dirty method:
if(Serial.available() > 0) {  // At least one byte is available
  Serial.println(millis());
  Serial.read();  // Read the (one) character to empty the buffer
}

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


text:
How to switch 12V water pump
I found this pump:
https://www.aliexpress.com/item/Free-Shipping-Ultra-quiet-DC-12V-3M-240L-H-Brushless-Submersible-Water-Pump-High-Qualtiy-mini/32472119699.html
Now, I want to control it from an Arduino.
Is this a good relay to use?
https://www.pololu.com/product/2480?
I want to use a 12v battery for the pump.

You don't need a relay - a simple N-channel MOSFET will do the job. Oh, and don't forget the flyback diode. A pump is just a motor, after all.

You need to check the voltage rating and the current rating of the relay. So in your case, the relay should have a rating of at least 12V DC, and 0.35A of current. Both values are really low, so almost any relay will work. The relay you linked to doesn't have a DC rating, only an AC. But I don't think that's a problem in this case.

@Gerben A general rule of thumb: DC rating is 1/10th - 1/20th of the AC rating. Current remains constant. It's all about arc extinguishing - AC auto-extinguishes at the zero crossing, DC doesn't.

@Majenko thank you. I didn't know about that rule of thumb. I knew it was lower. Since the pump in question is only 350mA,  the 10/5A relay from pololu should work.

I see people are recommending mosfets (which is the best option). Keep reading this if you still want to use relay. There are two kind of relays, mechanical and solid state. Mechanicals are cheap but they can be noisy (they make sound) also they have low life expectancy compared to solid state relays. On the other hand solid state relays are faster with everything else but they are expensive. Also you need to check voltage and max current rates before buying.

Some solid state relays only work on AC, so they won't work in this application.

@Gerben . . There are solid state relays for DC :  http://www.crydom.com/en/products/catalog/e_l_dc.pdf

About the relay, you can buy a low cost relay from aliexpress like the following one or other variant.
https://m.aliexpress.com/item/32392799916.html#autostay
It's well within your desired voltage and current  range and works readily with arduino.


text:
Help managing the fallout from timer0 mode and prescaler change on ATMega2560 without modifying wiring.c
For a driving application I need the PWM mode to be phase correct and the prescaler to be 1. The issue is that the board I am working with has the load hooked up to a PWM pin reliant on timer0. The firmware running on this board makes use of the delay(), delayMicroseconds(), and millis() functions from wiring.c. The goal is to make the timer0 change, shown below, and then make small modifications where the firmware calls the wiring.c timing functions. My approach was to find a scaling factor to be applied to the call of these functions. The scaling factor I came to was 32.12549, calculated by taking the wiring.c expected timer0 behavior: prescaler=64 and TOV0 flag every 256 counts, and comparing it to the actual values after my change: prescaler=1 and TOV0 flag every 510 counts
Calculation: 64*256/510=32.12549
Timer0 change:
// Set timer0 to phase correct PWM
TCCR0A = TCCR0A & 0b11111100 | 0x01;

// Set prescaler for timer0 to 1
TCCR0B = TCCR0B & 0b11111000 | 0x01;

The other timers are all configured in phase correct PWM mode, with a prescaler of 1.
...When I apply this scaling factor to a value returned from millis() to keep time it works well. For example the two pieces of code below proved to be equivalent through the timer0 change:
Use of millis() before timer0 change:
//current time
long unsigned now = millis();

//delay for 1 second
while(millis() - now < 1000){}

Use of millis() after timer0 change:
//current time
long unsigned now = millis();

//delay for 1 second, with x32.125 scaling coefficient
while(millis() - now < 32125){}

The two snippets of code above both delayed for 1 second
Now comes the problem: when I try to apply that same scaling factor to delay() or delayMicroseconds() it seems to give unreasonable delays...
Use of delayMicroseconds() before timer0 change:
// wait 1.5ms for mux to switch
delayMicroseconds(1500);

...this delays for 1.5ms
Use of delayMicroseconds() after timer0 change:
// wait 1.5ms for mux to switch, with x32.125 scaling coefficient
delayMicroseconds(48188);

...this delays for ~20ms.
Assuming this is still linearly scalable:
 if 48188 -> 20ms, therefore 1.5ms -> 3614
But when the following code is used...
// wait 1.5ms for mux to switch, scaled
delayMicroseconds(3614);

...this delays for ~4.5ms
Why is it that delayMicroseconds() and delay() cannot be linearly scaled to account for a timer0 change? Furthermore, is there any simple modification to how these functions are called or utilized that can account for the effect of changing timer0?

You might want to check the Arduino source code. It seems like delayMicroseconds doesn't even use timer0. Does your code use any interrupts, as that would skew the result of delayMicroseconds? Did you run out of PWM pins on the Mega, that you need to use timer0?

Yes, timer0 must be used here. The code does use interrupts, which might be effecting this (I hadn't notice that delayMicroseconds() doesn't utilize micros(), which blocks interrupts; I assumed it did since delay() does) - although I am using a scope to measure the output (toggling a pin on either side of the delay) and the delay is repeatable, where-as our interrupts may happen at any time during the code. If it is an interrupt causing the issue I would expect the delay to vary as the loop runs, which it does not. I'll do my best to read through the source code for delayMicroseconds()

I think you are right actually, and I think the interrupt that is causing this mistake could actually be the timer overflow interrupts. By changing the clock speeds (I actually increased the clock speed of all PWM timers) I caused each clocks TOVn interrupt flag to be raised every 31.875us, as opposed to the standard operation which is every 1024us.

The millis() roll over
By making Timer 0 faster, your millis() will roll over much more
often than normal: every 37.1 hours instead of every 49.7 days. Thus,
when you “scale” millis(), you should be careful to do it in a
rollover-safe way. From the code you show, it appears that you are doing
exactly the right thing. Well done! Don't change anything. Don't be
tempted to scale the value returned by millis().
The overflow in delayMicroseconds()
As this function just burns cycles in a busy loop, it is not affected by
your configuration of Timer 0. You can just use it as is, with no
scaling. Beware however that it's argument should always be smaller than
16384 (on a 16 MHz board). Otherwise it will overflow when it is
multiplied by 4 in order to get a loop count.
For example, when you call delayMicroseconds(48188);, the function
computes the number of loop iterations to make as
48188 × 4 − 5 = 61675 (modulo 216)
Then, it burns about 15 ms of CPU time (0.25 µs per
iteration), which is close to the 20 ms you see. For the
difference, see below.
The cycles burned by the Timer 0 ISR
This ISR, which keeps the millis() counter updated, is supposed to run
every 1024 µs. Each time it runs it burns a few cycles, but it's
usually not a big deal. With your new timer configuration, it is now
running far more often: every 31.875 µs.
From the numbers you give in the question, I would say the ISR is
eating about 20% of your CPU power: when you call
delayMicroseconds(3614);, that function burns 3614 µs of CPU
time, yet you measure a delay of about 4500 µs. The difference is
taken by the Timer 0 ISR.
Use another timer for millis()
If you can spare a timer, you could both restore the normal behavior of
millis() and avoid wasting so much CPU in the Timer 0 ISR:

configure Timer 0 to not trigger interrupts
configure your spare timer just like the Arduino core would normally
configure Timer 0
write an overflow ISR for your spare timer that just calls the Timer 0
overflow ISR.

This way your spare timer is basically replacing Timer 0. Example using
Timer 2:
// This Timer 2 overflow ISR simply forwards the call to the Timer 0
// overflow ISR from Arduino core.
ISR(TIMER0_OVF_vect);
ISR(TIMER2_OVF_vect, ISR_NAKED) {
    TIMER0_OVF_vect();
    asm volatile("reti");

    // Alternatively, just:
    // asm volatile("jmp __vector_16");
}

void setup()
{
    // Set timer0 to phase correct PWM
    TCCR0A = (TCCR0A & 0b11111100) | 0x01;

    // Set prescaler for timer0 to 1
    TCCR0B = (TCCR0B & 0b11111000) | 0x01;

    // Disable Timer 0 interrupts.
    TIMSK0 = 0;

    // Configure Timer 2 to replace Timer 0.
    TCCR2A = _BV(WGM20)   // fast PWM, TOP = 0xff
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(CS22);   // clock at F_CPU / 64
    TIMSK2 = _BV(TOIE2);  // enable overflow interrupt

    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    // Blink the LED at 1 Hz.
    uint32_t now = millis();
    static uint32_t last_toggle;
    if (now - last_toggle >= 500) {
        last_toggle += 500;
        digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    }
}

I wrote a “naked” ISR to avoid having plenty of CPU registers saved and
restored twice (once by each ISR in the call chain), but then I had to
put the return instruction explicitly in assembly (ret and reti
would be equivalent in this instance). The version with jmp is
slightly more efficient, but you have to know the “real” name of the
ISR, which is MCU-dependent (__vector_16 on an Uno).
Notice that with this technique micros() will not work, as it reads
TCNT0 directly. And delay() will not work either because it relies on
micros().

Fantastic response, thank you. It seems delayMicroseconds() is not going to be reliable, and based on the length delays my project requires I think relying exclusively on millis() would be fine. We are using all the timers for PWM outputs at this point, and as you can probably deduce from that we have a fairly weighed down microcontroller. I believe the other timers are 16-bit, so would roll-over way less often - I'm starting to think we cannot handle timer0 being sped up and still manage the communications and calculations in a reliable fashion.

Out of interest, how did you come to this conclusion: "From the numbers you give in the question, I would say the ISR is eating about 20% of your CPU" ?

How did you configure the other timers? Could they work in fast PWM mode at 977 Hz? You may want to add this info to the question. Arduino configures the only 16-bit timer in 8-bit mode anyway. 2) Out of 4500 µs, 3614 are spent inside delayMicroseconds(3614). The rest, namely 886 µs (i.e. 20%) is eaten by that ISR.

Things are changing as I dig into this, and it looks like getting away from timer0 is important enough to merit hardware modifications. Also, I am using an ATMega2560, which has 4x 16-bit timers (1,3,4,5) and 2x 8-bit timers (0,2). I have to go back through the firmware and verify that we have them set as 16-bit (does Arduino default all timers to 8-bit?), but it seems you have given me more than enough reason to dedicate my effort to working away from timer0.


text:
How to repair or work around a damaged usb port on the Arduino?
While unplugging the usb cable from the Arduino, the plastic piece in the center of the port (the part that separates the pins) broke off and lodged into the end of the usb cable. I didn't notice that it broke off and when I plugged the cable back into the Arduino it bent one of the pins back onto itself.

How would you go about repairing this?
If I fail to repair it is there an alternate method to programming the board?

I was able to use a paperclip to carefully bend it back and put the plastic divider back in. I will just have to leave the cable plugged in from now on.

You would need to replace the whole socket in order to repair it. For that you would need:

Soldering iron
Solder sucker
Solder wick
Patience and experience

Or you just connect an FT232 breakout board to TX, RX and RESET as if you were making a breadboard arduino and program the board through that.

Also connect Vcc and GND of course.

That would (I hope) go without saying, although if the Arduino is separately powered the power connection is not needed, only ground.

You could try bending the pin back, removing the white part from your cable, and gluing it back in.
Second option is to replace the USB socket on the Arduino board. You might be able to salvage a socket from some old electronics you still have lying around.
Third option is to cut one end of a spare USB cable, and solder the 4 wires inside the cable directly to the corresponding pads on the bottom of the broken socket. Add some glue to provide some strain-relieve to the cable.
Fourth option is an external USB to serial converter, like @Majenko suggested.

I would suggest to actually remove the whole thing and resolder it. There are many tutorials out there is you're new to soldering. This way, it is less probable that it creates a short or data loss during compilation.
If you don't want to solder, then you might be able to use an FTDI connector. FT232s are quite cheap.
Tx > Rx
Rx > Tx
Reset > Reset
Vcc > Vcc
GND > GND


text:
Did I just brick my ATMEGA 2560?
I bought an ATMEGA2560 on eBay and programmed it with Arduino IDE 1.6.9 using the USB cable, and the LED blinked as expected - All well and good.
Now I wanted to program the mega from my UNO as follows:

Uploaded ArduinoISP to the UNO
Changed the Board to Mega2560 and changed the Programmer to Arduio as ISP
Connected the two ICPS sockets with a 6 wire cable, where pin 5 on the UNO ICPS is cut and instead connected to D10 on the UNO
Upload the Blink sketch: IDE says Uploading for a minute, then some errors:
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

5) Upload Using Programmer: Activity on the UNO (RX/TX) and the LED on the mega lights constantly - And I can no longer program the mega using the IDE
Any pointers to what I did wrong and how to fix it?
Best regards

Once you use ISP to erase or program anything other than the bootloader, you lose the ability to use the bootloader until you use ISP (or a more drastic method) to replace the bootloader.  So while you have not "bricked" you device, you have put it in a state that will require getting your ISP setup working to recover from.  There are countless questions and answers on proper ISP all over the web, your issue is unlikely to be unique but rather something you can solve by finding and reading them.

I have no doubt the truth is out there - I just don't know the right questions :-)
I tried burning the bootloader with the same setup, and that got the mega back (the led started blinking, and I can program it using USB), but I still don't know how to program the mega using ICPS - Any pointers what to look for?

All pages I have looked at says to connect MOSI to MOSI and MISO to MISO - The caveat is NOT to connect RESET to RESET but D10 to RESET, correct?

Ah, the problem seems to be in the IDE - Something with the fuses when programming the mega (I won't even pretend to understand that yet).
I upgraded to 1.6.12 and everything works like a charm. Best regards
Stefan


text:
Arduino Uno Wifi Module ESP8266 AT Command Test error
When i Connected Rx>Rx (Rx Of module To Pin 0 Of Arduino) And Tx>Tx ( Tx Of Module To Pin 1 Of Arduino), The AT Command Test shows The Following error With Scrambled Words, but when I Connect Rx>Tx (Rx Of Module To Pin 1 Of Arduino) And Tx>Rx(Tx Of Module To Pin 0 Of The arduino), The AT Command Test Shows a Blank Screen. I Connected VCC, CHPD and RST Of Module to 3v Of Arduino and GND Of Module To GND Of Arduino. So How Do I Connect Arduino To Wifi Module which passes the at command test, Btw i Have an Intermediate, ie Motor Shield, I Connected Motor Sheild To Arduino And Then I connected Wifi Module To Motor Shield. Listen So  I need To Connect Wifi Module To Arduino, such that there isnt any error. what do i do?

You cannot connect an Arduino's digial pins 1 and 0 to both an ESP8266 and the serial USB,  unless you disable their use by the ATmega, for example hold it in reset if you are just trying to borrow the Arduino's USB serial.

many ESP8266's operate at 74880baud by default - this is 115200 * 26 / 40 ... because most ESP's use a 26Mhz crystal as opposed to a 40Mhz one

@ChrisStratton - unless the unposted code doesn't open the serial port as discussed here

Sounds like a baud rate issue as others have mentioned. Posting code would make things clearer. Please read How do I ask a good question?.

You have three hardware serial devices: the ATmega's pins 0 and 1, the ESP8266, and the USB serial converter to which the serial monitor is linked. You can only connect two of these, not all three. If you want to connect the serial monitor directly to the ESP8266, you have to disconnect the ATmega pins 0 and 1, either electrically or by making sure they are not activated for serial. If you want to insert the ATmega and its program between the serial monitor and the ESP8266, then you have to move the ESP8266 connections to some other ATmega pins and use a software serial instance on them.

The first connection you made between arduino and esp which resulted in some random data means both are communicating whereas the second connection where the screen shows blank means communication hasnt been established on account of incorrect wiring. So your first connection tx>tx and rx>rx is correct.
The only two area which you need to check is the baud rate and the mode of return. Some Esps work at 115200 with mode carriage return. So you can try different combinations of baud rate and mode to check which one does your Esp support.

"Random data" normally means the baud rate is to high.  No data means its to low (or 'broken' in some other way)

@Matt you might be right but in this case the results are observed when wiring is interchanged. Your point would have been valid when the connection is correct and the above mentioned observation would have been observed on changing baud rate. Here the connection itself is an issue.


text:
Why am I not receiving codes from IR receiver over the serial monitor?
I'm using the Keyes Infrared Receiver Module on an Arduino Uno R3 with the IRemote library included and running the IRrecvDemo example sketch included in the library.
I wired the IR receiver incorrectly the first time I ran the program. I wired the data pin to 5V and wired the Vcc pin on the module to the digital I/O pin. The ground was wired correctly.
Did I destroy the IR receiver by doing this? There was no noticeable overheating.
I corrected the wiring and tried again but still nothing over the serial monitor while pushing buttons on the IR remote that came with it. I wondered if the issue was with the remote so I hooked up a IR LED to flash using the following code:
#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

IRsend irsend;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  for (int i = 0; i < 3; i++) {   //// for statement controls IR LED
    irsend.sendSony(0xa90, 12);
    delay(40);
    if (irrecv.decode(&results))    //// if statement controls the receiver
    {
     Serial.println(results.value, HEX);
     irrecv.resume(); // Receive the next value
    }
  }
}

Nothing showed up on the serial monitor. However, the LED on the IR receiver module began flashing when the receiver was exposed to the IR LED, leading me to believe that I did not destroy the module when I wired it incorrectly.
Update:
I took the IR led and simply lit it with a coin cell battery and the IR receiver detected it and sent data over serial monitor. The remote powered by that same coin cell battery will not trigger the IR receiver. Can I conclude that this is a problem with the remote?

What is transmitting here? Are you sending from a remote?

@Nick Gammon Yes,the IR receiver came with a remote. I also have a simple IR LED that I set up just to see if the receiver would recognize it and send data over serial monitor. Neither worked.

I'm just wondering why your posted sketch has an irsend in it. What is the point of that?

Just shining an IR led on the module, shouldn't trigger the receiver, as it requires 38kHz modulated IR-light. So that's very suspicious.  I'd also check the remote by shining it towards a camera (e.g. the iPhone front camera, as it doesn't have an IR filter). Or just use the remote from your TV.

@Nick Gammon The posted code both sends IR signals using the IR led and receives the signals. The posted code is was for testing the receiver with the IR led. The code that I'd like to ultimately use is the IRrecvDemo sketch from the library to be used with a remote.

First, you can harvest this IR ASK receiver from almost any discarded entertainment equipment.  Second, as @Gerben said, you need a modulated signal.  A constant IR source (like the sun for example) should do nothing. Next, there are many ASK code variations.  Try several remotes.  Lastly, the camera trick should work with almost any CCD type camera.  I use my phone for this all the time.


text:
The best signal source for a path-finding robot
Newbe question - I'm thinking of creating a simple robot that heads to a signal source.
Ie, when you press a button on some remote control - the robot will head towards its source.
What would be the best choice of signal? A strength of a wifi, sound?
AD

Will it have line-of-sight to the remote control? If so infrared (IR) would be my choice. You would have to place IR receivers all around the robot.

IR sensor in combination with an ultrasonic distance sensor would work great.
You can mimic a radar with an IR sensor so that it can detect from where the IR source from your remote is comming from. Then from there, process the angles and make you robot go towards it.
The ultrasonic distance sensor can be used a "fail" prevention system. In the sense that if it detects an object in front of the robot, it will stop, go around it and then continue towards the target

I like @Canadiancyborg's IR solution, but the same theory can be applied to any other emitter, and RF emitters may be preferable to an IR emitter since IR light can be blocked by intermediate objects. Also an omnidirectional RF transmitter is easier to arrange than an omnidirectional IR transmitter.
The basic theory is that you need to work out which direction a signal is coming from. In order to do that you need to "look around you" and find at which angle the signal is strongest.
A highly directional receiver (parabolic dish, IR receiver with lens, etc) will allow you to sense the signal strongest when the receiver is pointing directly at the source. By then rotating the receiver (either on its own independent rotational system, such as a servo motor, or by rotating the entire robot using the wheels) you can "lock on" to the direction where the signal is strongest and drive towards it.

Well RF is a little too powerful. My idea was to isolate the ir in something like a PVC pipe so it would detect the IR signal only at a specific angle. Otherwise, you can't really know where the target is.

@canadiancyborg RF doesn't need to be powerful - it all depends on the power of your transmitter, the sensitivity of your receiver, and the field of vision of your detector. Hence the parabolic dish (like a mini satellite dish). For IR you really want a lens to focus the receiver on a narrower point (the optical equivalent of a parabolic dish).

authors: Роман Деньгин


text:
Attiny85 code on Attiny84
I made OLED timer/watch using Attiny85, but as internal clock isnt accurate i need external crystal. On Attiny85 im short on pins so i am switching to Attiny84 but i have problems to compile/upload same code to Attiny84. Even if i stay on Attiny84 8mhz internal clock as on Attiny85 i still cant compile.
Im using Arduino UNO as ISP.
Error what i have:
WDT_Time.cpp: In function 'void setup_watchdog(uint8_t)':
WDT_Time.cpp:272: error: 'WDTCR' was not declared in this scope
WDTCR |= (1 << WDCE) | (1 << WDE);
^
In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,
             from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:88,
             from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,
             from WDT_Time.cpp:12:
WDT_Time.cpp:276: error: 'PCIE' was not declared in this scope
   sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
              ^
WDT_Time.cpp:276:3: note: in expansion of macro 'sbi'
   sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
   ^
WDT_Time.cpp:277: error: 'PCMSK' was not declared in this scope
   sbi(PCMSK, PCINT3);
       ^
WDT_Time.cpp:277:3: note: in expansion of macro 'sbi'
   sbi(PCMSK, PCINT3);
   ^
'WDTCR' was not declared in this scope

There are slight differences between registers, register names and registers bit names:

WDTCR is named WDTCSR
PCIE doesn't exist in GIMSK as there are two IO ports, so there are two pin change channels: PCIE0 and PCIE1
and PCMSK is similar to PCIE. There'll be two of them too.

Basically you have to look into both datasheets and compare what you are using and check if it's correct.

In code i changed: WDTCR to WDTCSR

and other changes:
GIMSK  = bit (PCIE0);   sbi(GIMSK, PCIE0); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))   PCMSK0 = bit (PCINT1) | bit (PCINT2);   sbi(PCMSK0, PCINT1);
Now its working. Thanks!


text:
Serial loop stopped after a while, I don't know why
I am very new to Arduino. I wrote a program in order to read some registers in a I2C device. I receive HEX datas.
So the Arduino LEONARDO is connected to the external board using the 2-wires-bus.
Then informations are sent to my computer by using Serial.println.
My problem is my Arduino stops working after a while, maybe 25 or 30 loops. Sometimes I loose communication and I have to reboot the Arduino.
I guess it's an overflow issue or I'm loosing connection randomly :
int dt = 500;
int dt2 = 1000; // used for delay duration
#include "Wire.h"
#include <Process.h>
#define pot_address 0x25 // each I2C object has a unique bus address, the MCP40

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

}

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

  Wire.beginTransmission(pot_address);
  Wire.write(0); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
  byte b = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(1); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte c = Wire.read();

   Wire.beginTransmission(pot_address);
  Wire.write(2); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte d = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(3); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte e = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(4); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte f = Wire.read();

  Serial.print("b");
  Serial.println(b, HEX);
  Serial.println("-");
  Serial.print("c");
  Serial.println(c, HEX);
  Serial.println("-");
  Serial.print("d");
  Serial.println(d, HEX);
  Serial.println("-");
  Serial.print("e");
  Serial.println(e, HEX);
  Serial.println("-");
  Serial.print("f");
  Serial.println(f, HEX);
  Serial.println("-");

 delay(dt2);

}

On each transaction, you request 8 bytes from the MCP40 (second argument of Wire.requestFrom()), yet you read only one (one single call to Wire.read()).

Add:
while(!Serial) ;

I'll make sure the Leonardo is in sync with the Serial communication.
It is the case because the Leonardo is USB native thus the Serial communication works differently.


text:
Amplified piezo sensor wiring problem
I am trying to amplify the signal from an Adafruit Small enclosed piezo.  The piezo is working using the Arduino Knock example but I want to increase the sensitivity using an amplifier.  The wiring shown below does not work using the Knock sketch and I am assuming it is a problem with the wetware and the wiring(NOOB here).
Any advice in amplifying the piezo is appreciated.

You don't seem to understand how to wire an OP-AMP. Here is a quick tutorial on their basics:
https://www.youtube.com/watch?v=kqCV-HGJc6A
The thing is that you are missing a LOT of resistors. An usual OP-AMP circuit contains many resistors to determine the amount of amplification and more...
The tutorial explains quite well what resistor and where do you need to put them in order for your circuit.


text:
Returning an int array from a function
I have a function that needs to return 3 int values. I currently use an array declared in the global scope and I ask the function to write into them. Is there a way to make a function return an array?
Here is what I want to do:
int function()
{

int array[3];

array[0] = 19;  //these are just random numbers

array[1] = 7;

array[2] = 69;

return array[]; //is this possible??

}

It won't work, or at least not reliably: you could only return a pointer to memory that is no longer allocated (bad). You can return an array embedded into a struct. Since it's only 3 ints, it should be fine.

That actually anwsers my question. You should have put it as an anwser, I'll acept it.

I have a function that needs to return 3 int values.

In the interests of completeness I'll suggest another method. Let's assume that you really need 3 values and not 300.
void foo (int & a, int & b, int & c)
{
  a = 19;  //these are just random numbers
  b = 7;
  c = 69;
}

void setup() {
  Serial.begin (115200);
  int x, y, z;
  foo (x, y, z);
  Serial.println (x);
  Serial.println (y);
  Serial.println (z);
}

void loop() {
}

This conceivably will use less memory because the compiler may be able to optimize all 3 values into registers. In fact in that specific example, it has optimized away the entire function call:
000000be <setup>:
  public:
    inline HardwareSerial(
      volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
      volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
      volatile uint8_t *ucsrc, volatile uint8_t *udr);
    void begin(unsigned long baud) { begin(baud, SERIAL_8N1); }
  be:   26 e0           ldi r18, 0x06   ; 6
  c0:   40 e0           ldi r20, 0x00   ; 0
  c2:   52 ec           ldi r21, 0xC2   ; 194
  c4:   61 e0           ldi r22, 0x01   ; 1
  c6:   70 e0           ldi r23, 0x00   ; 0
  c8:   82 e2           ldi r24, 0x22   ; 34
  ca:   91 e0           ldi r25, 0x01   ; 1
  cc:   0e 94 64 01     call    0x2c8   ; 0x2c8 <_ZN14HardwareSerial5beginEmh>
  d0:   4a e0           ldi r20, 0x0A   ; 10
  d2:   50 e0           ldi r21, 0x00   ; 0
  d4:   63 e1           ldi r22, 0x13   ; 19  <---------- x
  d6:   70 e0           ldi r23, 0x00   ; 0
  d8:   82 e2           ldi r24, 0x22   ; 34
  da:   91 e0           ldi r25, 0x01   ; 1
  dc:   0e 94 4d 03     call    0x69a   ; 0x69a <_ZN5Print7printlnEii>
  e0:   4a e0           ldi r20, 0x0A   ; 10
  e2:   50 e0           ldi r21, 0x00   ; 0
  e4:   67 e0           ldi r22, 0x07   ; 7   <---------- y
  e6:   70 e0           ldi r23, 0x00   ; 0
  e8:   82 e2           ldi r24, 0x22   ; 34
  ea:   91 e0           ldi r25, 0x01   ; 1
  ec:   0e 94 4d 03     call    0x69a   ; 0x69a <_ZN5Print7printlnEii>
  f0:   4a e0           ldi r20, 0x0A   ; 10
  f2:   50 e0           ldi r21, 0x00   ; 0
  f4:   65 e4           ldi r22, 0x45   ; 69  <---------- z
  f6:   70 e0           ldi r23, 0x00   ; 0
  f8:   82 e2           ldi r24, 0x22   ; 34
  fa:   91 e0           ldi r25, 0x01   ; 1
  fc:   0c 94 4d 03     jmp 0x69a   ; 0x69a <_ZN5Print7printlnEii>

00000100 <loop>:
 100:   08 95           ret

There are several ways to achieve what you want:
The way that does not work
Did you try to compile the code you gave in the question? Then you
probably noticed it does not compile. I tried and got: “error: expected
primary-expression before ‘]’ token”, meaning the compiler expected
return array[some_index];.
The way that almost works
Remove the brackets and just return array:
int *function()
{
    int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

This may work, or not, depending on the surrounding code, on how the
optimizer processes your program, and on how lucky you are when you test
it. It is called “undefined behaviour” and is something you should
always avoid.
Here is what happens: in C (and C++) you cannot return an array. The
identifier array “decays” to a pointer pointing at its first element.
Then return array is essentially equivalent to return &array[0]. The
problem is that, since the array is allocated in the function's stack
frame, it ceases to exist when the function returns, thus the caller
gets a pointer to an area of memory that is not allocated anymore.
Likely memory corruption ahead. The compiler warned me when I tried to
do that: “warning: address of local variable ‘array’ returned”. It's a
very serious warning that should never be ignored.
The simplest fix: make the array static
As suggested by Chris Stratton in a comment, you can make the array
static, so it will be allocated for the whole life of the program:
int *function()
{
    static int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

The only catch is that the function is now not reentrant, meaning that
every time you call it it will clobber the same array it returned on the
previous calls. Depending on your use case, this may not be an issue,
but it's something you need to be aware of.
Have the caller manage the allocation
A safer (reentrant) way is to have the caller provide the memory needed
for the array. This is a very common method in C, and is suggested both
by Harper Shelby's answer and Chris Stratton's comment:
int *function(int array[3])
{
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

The caller can allocate in static memory, or in it's own stack frame, or
on the heap... but you do not care, the allocation is the caller's
problem now.
A couple of things to note here:

The prototype is equivalent to int *function(int *array): the
function receives only a pointer. Writing array[3] instead of
*array has the sole effect of documenting that the function
expects the pointer to point to somewhere with room for 3 values. You
could document that in a comment instead.
The function could return void, since the caller presumably knows
the address it is giving you. Returning that same address is just for
convenience, as it can help you chain calls like
another_function(function(array)).

Return the array in a struct
One may wonder: why can't we return an array in the first place. I do
not know for sure why the authors of the language made this choice, but
one possible explanation is that it is expensive to return a big array
by value, as it involves copying the whole of it. Now, if your array is
really only three ints, then that argument does not apply, and you may
reasonably want to really return the whole array by value. This can be
done by embedding it inside a struct:
// Struct definition.
struct Array3 {
    int array[3];
};

Array3 function()
{
    Array3 a;
    a.array[0] = 19;
    a.array[1] = 7;
    a.array[2] = 69;
    return a;
}

Which of those would use the less memory possible?

Making the array global and letting both functions (caller and called) assume the use of that array, only requres the space for the 3 ints (6 bytes) but they remain reserved for the purpose for the entire program run, whether they are in use or not.
The other option is for the caller to allocate the array memory in its own stack and pass the called function a pointer to it. That uses not only the three ints but possibly, memory for the pointer as well (unless the compiler chooses to pass the pointer in registers - but lets assume worst case - that it gets passed in stack memory). ...

...  Then there is the additional memory (two more bytes) for the pointer), but the pointer's memory is only reserved while the called function is running. The array itself is only reserved while the caller (and thus the called) function is active. When the caller returns to its caller, the array space becomes free. So which uses less memory? It depends on when you look!

There are 2 ways to do what you want in C. One relies on the function caller managing memory, the other on the "library" code managing the memory. If you go with the caller-managed memory, your function accepts a buffer and fills it. For "library" managed memory, you provide additional functions to allocate and release the buffer that the caller then calls
If you want to use C++ idioms, you can make a class (possibly static) that allocates the memory and provides access to the data.

If you are going to allocate memory in the function/method be sure to do it in a lasting way - something placed on the stack for example will not outlive the return of the function call - it might still be there, but only unreliably.  Personally I'd use either a static allocation, or the caller's stack, as lasting runtime allocation introduces failure modes and is going to require about as much space to track the allocation as the 6 bytes that 3 Arduino ints would actually consume.

Absolutely true - I didn't go in to all the details, just pointed out the basic strategies. In the Arduino environment, having tracked allocations (and in most cases, any dynamic allocations) is probably not the way to go, for the reasons you mention.


text:
Cisco Switch not receiving serial communication from Arduino
So I have an issue that I can't really think of a reason why it would be happening. I have an Arduino Mega connected on Serial3 to a RS232 breakout board with a male DB9 connector on it. I then have two female breakout boards connected. One is connected to the RS232 breakout board and the other to a Cisco DB9 to roll over cable, which is connected to my Cisco Switch, or if it is, it is being ignored.
For some reason no data sent from the Arduino is making it to the Cisco switch that I can tell. I did confirm that it is sending data using a USB to DB9 adapter and PUTTY. I can send and receive data from both the Arduino and PUTTY correctly to the other.
I can receive data from the switch perfectly. Cisco's default settings are the same as the Arduino's, 9600, 8bits, no parity, 1 stop bit etc...
I can also connect the switch to the USB to DB9 adapter directly and send and receive fine through it / PUTTY as well.
Does anyone have any suggestions why I'd be able to send data to and from Putty, but only receive data from the switch, or why the data going to the switch is failing?

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  Serial3.begin(9600, SERIAL_8N1);
  Serial.println("Ready....");
  Serial.println();
}

void loop() {
  // read from Serial3, write to Serial
  if (Serial3.available()) {
    int inByte = Serial3.read();
    Serial.write(inByte);
  }
  // read from Serial, write to Serial3
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial3.write(inByte);
  }
  Serial3.println(); // Added just to test if a cr could be passed
  Serial3.write(98); // Added just to test if a character could be directory passed
  Serial3.write(10); // Added just to test if a cr could be passed
}

Consider in band verses out of band flow control.

Is there such a thing as inb vs oob for a serial console connection? This isn't on the internal network of the switch in any way but the console port.

Ug, I can't answer in the comments as I'm running out of characters...  See my Answer.  We'll just have to change the Answer to match the actual problem once you solve it later...

It seems you have demonstrated that the Arduino is transmitting, so this is more likely a fit for a networking equipment site than the Arduino one.  Looking at line ending cases was a good idea, you might look there a little more, or make sure you are using the same putty or Arduino serial monitor settings in both the PC-switch test and the PC-Arduino-switch experiment, ie, don't use putty for one and the serial monitor for the other.

Of course your "Added just to test" would break any meaningful traffic by inserting these extra characters between those of the intended message, and if the source data is keeping the PC-Arduino link full potentially make the Arduino-switch one fall behind.  Presumably you also tried without those llines.

Hey thanks for the replies. Yes I tried without, and the only thing that I have noticed is that adding those lines does not seem to make any different to the switch, HOWEVER they do seem to cause some sort of interference with the received traffic from the switch causing text artifacts.
The reason I put them there was to see if any characters valid or not made it to the switch. I would transmit with the arduino, and then change the serial connection back to the PC and press the enter key to see if any characters were received. If there was, I'd get an error since they'd be a bad command.

I'm not sure how to use the Arduino Serial mon to monitor my USB to DB9 adapter, or are you saying there is a way to use Putty as my Arduino Serial monitor instead of the IDE, or either / both?. Here is the setups that I have tested.
Switch TO DB9 Adapter (Putty) - Works
Switch TO Arduino (Arduino IDE Serial Monitor) - Receives only.
DB9 adapter (Putty) TO Arduino (Arduino IDE Serial Monitor) - Works

I have not used stack all that much, is there an easy way to copy a question to the network group, or link back to this one? Seems like the comments here would be relevant to them too.

Networking Comm considers this off topic for their community.

They are probably wrong - this is far more a Cisco question than it is an Arduino one.  But questions that lack information to make them answerable tend to be unpopular everywhere.

You can use putty with an Arduino just by choosing the appropriate serial device and line settings, in your case you want the line settings to be the same as those you were able to talk to the switch with, unless you have misreported what they are.

So I used putty to connect to the arduino but I couldn't enter commands via putty at all. I was able to power cycle the switch though and it did correctly read from Serial3 and Write it back out to Serial which putty was connected to. Fairly similar to the arduino IDE. I should point out though, that this should not really matter since I have matched the settings putty uses on the arduino to talk to the switch, and I couldn't even manually send a character to it. If anything I think I'm probably dealing with some missing element the cisco switch requires. Any more Ideas I will gladly try.

So you get valid behaviour with Putty but not the Arduino serial monitor?

Assuming this is a flow control problem:

Is there such a thing as inb vs oob for a serial console connection?
  This isn't on the internal network of the switch in any way but the
  console port

It assumed this is a managed switch and the traffic on the console port has nothing to do with the traffic going through the switch. Rather this is likely a port to the computer inside the switch.  Such a port might be able to use RTS/CTS/DSR or X-on / and X-off.
If this is a flow control problem, consider first looking for thumb switches on the back of the switch to see if the method used for flow control over the console port can be selected. If that is not possible, consider simply hardwiring the out of band flow control pins to always allow for data to flow.  At 9600 baud, a dedicated Aruidno should be able to keep up.
Refer to the 9 pin connector in this chart to find the out of band flow control pins.

This is unlikely to be the answer.  Flow control usually means the receiver allowing, or impeding the transmitter.  An Arduino ignorant of it would transmit blindly, and there's little reason why a switch not heavily burdened by previous traffic from the Arduino would be trying to suspend incoming data.  In the other direction, if the switch where looking for flow control inputs it wouldn't send, but it apparently is is sending.

Good point.  So what do you think?  Cross over cable confusion?  Like switching Rx & Tx or DTE & DTC?  Maybe a difference in the EOL (End Of Line) character?  Could be that Putty is tolerant of different EOL characters and works with both while they don't work with each other?

Swapped wiring seems unlikely given that something is allegedly received from the switch.  In terms of line endings, it would not be the terminal program's "tolerance" but rather what it transmits.  If the same terminal program is used for both tests that should not be the issue either, but we don't know that the same program was used for both the direct and arduino-in-the-middle tests.

Yeah I don't think this is what I need but thank you for the reply. Also these switches don't have anything like that on the back, you change all the serial connection settings on the switch itself when you are connected to it, but this needs to work with stock switch settings to be useful for what I need. Very few people every change these settings on Cisco routers and switches since they usually just use console to configure network settings, and then all times after that connect with telnet or ssh.

Could be a voltage problem. You're using an TTL->RS232 Adapter as far as I can tell from the picture, which is absolutely necessary. Arduino only gives out TTL Signal Level, which would not be "understood" by the Cisco Switch, which works on RS232 / Serial Voltage Level (which is a lot higher). However, maybe the RS232 Converter Module is faulty. You could check the output voltage level with a Multimeter and see if it actually is in the required range (http://www.radio-electronics.com/info/telecommunications_networks/rs232/signals-voltages-levels.php).
Also connecting ground correctly is important, but that should be ok on your setup :).