text:
String operators
I have a section of code that I am unsure of what it is doing.
static int bufindw = 0;
static char buffer[4][96];
static char *strchr_pointer;
int result;

result = (int)strtod(&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1], NULL)

The part where I don't understand what is happening is strchr_pointer - buffer[bufindw] + 1. strchr_pointer and buffer[bufindw] will be strings. It gives the result I expect it to give because I know in the end it needs the correct index value in buffer[][] and in addition the number 1 is being added to it as well. How can a string minus a string?

Those are pointers,not strings.

Let's break it down logically for you.
You have 4 strings, each capable of containing 96 characters:
static char buffer[4][96];

That is a block of RAM that covers 4*96=384 bytes.  Let's say that block of ram starts at address 0x100.
result = (int)strtod(&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1], NULL)

The phrase buffer[x] returns the address of the string number x in your array of strings.  It's the same as &buffer[x][0] - the address of the first character in string x.
You also have a pointer strchr_pointer which contains something - what that is I don't know because you haven't told us.  Chances are it's the result of a strchr() call, which:

returns a pointer to the first occurrence of the character c in the string s.

So you have looked for a character in a string and found that it's at a specific address.  Let's say that's address 0x111 for the sake of argument.
Ok, so if we take bufindw as 0 for the first string in your array, and work from the inside out, we have:

buffer[bufindw] = 0x100
strchr_pointer = 0x111

strchr_pointer - buffer[bufindw] = 0x111 - 0x100 = 0x11
strchr_pointer - buffer[bufindw] + 1 = 0x100 - 0x111 + 1 = 0x12

Replace that into the function's parameters:

&buffer[bufindw][strchr_pointer - buffer[bufindw] + 1] = &buffer[bufindw][0x12]

So you have the address of the 0x12'th (18th) character (or character number 16 since they count from 0 not 1), which is address 0x112.
That address is then passed to strtod() to convert it into a double-precision number:
    strtod(0x112, NULL);
That value is then cast to an integer:
(int)strtod(0x112, NULL);

So the decimal portion is discarded (not rounded, chopped off).
Say your string contains: "This is the value:23.83589743" and is located at 0x100.
You use strchr() to find the first occurrence of ':', and it finds it at address 0x111, which is the 18th character of the string, so 0x100 + 17 = 256 + 17 = 273 = 0x111.  You subtract the start of the string and add one to it, so you end up with 18, which is the start of the numeric value (the 18th character).  The string from that point on contains "23.83589743".  That is then passed to strtod() and cast to an integer, and so is truncated to 23.
It's not surprising you're confused, the whole thing can be re-written much simpler:
strchr_pointer = strchr(buffer[bufdindw], ':');
result = (int)strtod(strchr_pointer, NULL);

All that manipulating of the buffer address is like doing "x = 6 + y - 3 + 4 - 7" - completely pointless, since you might just as well write "x = y".

And yes, strchr_pointer is the result of a strchr() call.


text:
What does it mean when there are two addresses listed in the data sheet for a particular register?
I have been trying to grasp a better understand of registers and port manipulation. I have been looking through the ATmega 328P datasheet to look at the different registers.
For some of the registers, I see that there are two addresses listed. For example, for PORTB is listed at 0x05 (0x25). Similarly, for its DDRB and PINB, they are listed at 0x04 (0x24), and 0x03 (0x23), respectively. What does this mean for the register? Thank you.

One (the lower number) is the IO port address which is used when using the IN or OUT op-code. The other (higher number) is the memory mapped address.
Different methods of access are more programatically efficient depending on how you are manipulating the values. For instance IN and OUT are more efficient at setting or reading the entire register value, but SBI and CBI on the memory mapped address are more efficient when manipulating individual bits.

source: Stack Exchange

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

sort: votes


text:
Double ## in macros
I was looking at some macro use in an Arduino code. I believe what this macro does is it expands into a state that basically sets a pin to either input or output, but I'm a little confused about everything going on in this macro.
I do understand the point behind the do{...} while(0), but I'm sure what the ## are accomplishing. Also, what if anything do the underscores before DDR and PIN do? I would very appreciative of a simple clarification. Thank you!
#define MASK(PIN)  (1 << PIN)

/// set pin as input
#define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)
/// set pin as output
#define _SET_OUTPUT(IO) do {DIO ##  IO ## _DDR |=  MASK(DIO ## IO ## _PIN); } while (0)

## is the concatenation operator in macros. It joins two macros or pieces of text together when expanded.
#define _SET_INPUT(IO) do {DIO ##  IO ## _DDR &= ~MASK(DIO ## IO ## _PIN); } while (0)

_SET_INPUT(3);

woukd expand to:
do {DIO3_DDR &= ~MASK(DIO3_PIN); } while (0);

You can read more about how it works here: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

It seems that SE's syntax highlighting can't handle those macros. Should it maybe be reported?

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


text:
Why is there already text in the serial monitor before the Arduino initializes?
I have encountered this several times before and I would like it if someone was able to give an explanation. In almost any sketch that I've ever created with Serial communication involved, I notice that I will get text that seemingly appears before the void setup() function has run. For example, I have the simplest sketch below where this occurs.
void setup(){
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Welcome");
}

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

If I upload this to one of my Arduino Megas, I will often get the output in the serial monitor:
WelcWelcome

When I open the serial monitor to view the output, the "Welc" is already written and then the rest of the "Welcome" come in a few moments later. If I close and re-open the serial monitor or reselect the baudrate setting within the serial monitor, the serial monitor clears, restarting the Arduino, and printing only "Welcome" to the screen without the "Welc", as I would expect.
However, if I upload the sketch, then disconnect-reconnect the Arduino-USB cable from the computer, and open the serial monitor, there is no leftover bytes printed to the screen like before.
The exact bytes leftover that appear before the void setup() function is called varies from upload to upload. Can anyone give me an explanation and is there a way to avoid the leftover bytes ? Thank you.

It's because the Arduino has started running the sketch and placed data into the USB chip's buffer. You then open the serial monitor which then opens the serial port thus resetting the Arduino. So the sketch runs again.
It only resets the Arduino, not the USB interface chip, so you get what was in there from the first execution plus the new text from the second (post-opening) execution.
You cannot "avoid" the extra bytes, that's just the way things are. The Arduino resets. There are buffers in various places. You have no control over those buffers.
As a side note: the serial monitor is completely disgusting. If you want to do things properly use a proper terminal emulator, then you can use ANSI control codes to do things like clear the screen, move the cursor around, apply colour, etc.

Because as soon as you start the serial monitor, it picks whats on the serial buffers and  then resets the arduino connected and also it would reset again when you try to upload code but luckily serial monitor is cleared in this instance;


text:
How to user timer interrupts for times longer than can TNCTx can keep track of?
I am trying to program my Arduino Mega 2560 to effectively create a PWM signal on any digital pin using timer interrupts and timer1. The pins will pulse a finite amount of times (not indefinitely). I am first trying this with a 256-prescaler value, which I believe means that each increment of my TCNT1 is 16.0 microseconds, and since it is a 16-bit register, it can reach a max. value of 1048567 microseconds.
I am designing the program so that the period and duty cycle are changed by Serial commands that the user can send (I already have that part figured out). I am using clear timer on compare mode and OCR1A and OCR1B to toggle the digital pin between HIGH and LOW.
If the desired period is less than 1048567 microseconds, I can divide the period by the modified clock (modified by the prescaler) to figure out the OCR1A value, and then based on the desired duty cycle, calculate OCR1B. Then I set the ISR vectors for A and B to toggle the pin and count down until the desired number of cycles is completed.
What I would like to also allow the user to do is set periods/duty cycles that would be longer than 1048567 microseconds, but I'm not sure how to accomplish that. For example, if I wanted to have the pin be HIGH for 2 seconds with a total period of 10 seconds, I would choose values for OCR1B and OCR1A that, through the ISR(TIMER1_COMPA_vect) and ISR(TIMER1_COMPB_vect), I could keep track (through a counter variable) of how many interrupts had occurred. If enough interrupts had occurred to equal the time of that the pin had to be HIGH and/or LOW, the ISRs would actually trigger the toggling of the pin (instead of just counting the number of interrupts).
How could I choose the OCR1B and OCR1A values that would accomplish this optimally? Is it reasonable to keep track of time this way as a workaround to the limitation of the timer counter max value? I am open to any suggestion and I appreciate any input. Thank you.

What sort of precision do you want? For something like 2 seconds on and 5 seconds off, I would have thought that simply toggling a pin by checking if time is up in the main loop would do it.

By maintaining your own second-level prescaler you can quite easily keep track of longer periods.
The most efficient method is to use a "divide and multiply by two" scheme.

Start with a custom pre-scaler of 1.
While the count period is > 65535:

Multiply the pre-scaler by 2.
Divide the count period by 2

uint16_t ps = 1;
uint32_t period = 429864;

while (period > 65535) {
    ps <<= 1;
    period >>= 1;
}

Then you can load the count period register with the now divided count period and use a variable to count the number of times the interrupt has been triggered. When it equals your custom pre-scaler value you reset the count to 0 and run your actual interrupt routine.
The left and right shifts multiply by two and divide by two respectively in a very efficient manner. Far more than multiplying by 10, or dividing the period by 65536 and using that as a prescaler.


text:
What are the basics in writing a program in Arduino?
I am an undergrad in ICE. I was searching for ideas to do mini projects on and found this Arduino boards and programs. So actually what are the basics to develop our own gadgets? Any guidelines...?

I suggest you Google for some ideas, blogs, tutorials, etc. Your question is basically asking us to summarize hundreds, if not thousands, of web pages.

There are some excellent books available as well as videos and articles on the Internet which will walk you through basic projects.  The most common method of programming is to use the free Arduino IDE which will talk to the board from your Mac or PC.  You can run the board straight from the USB port's power, or from an external source if you need it to be portable.
The programming language is very similar to C.  The program structure is basically a setup portion and then a continuous main loop that runs until the board is powered off.
If you want to experiment without actually purchasing one, there are some emulators available which will let you build entire project on a virtual breadboard before buying any actual components.  Fritzing is a great board planner that you can install, or if you would rather, you can use 123D Circuits from your web browser which will let you edit and simulated the circuits.
Basic knowledge of electrical circuits will be helpful for getting started, and is a great asset when designing larger projects.


text:
Handling serial streams biggers than the available ram
I need to parse text coming into my MC (Leonardo) over the hardware serial port. The data comes in burst, and the parsing routine manage the data flow with easy when it is less than the serial buffer.
I will like to be able to receive around 512Kb of serial data, save it somewhere (not in the arduino memory of course) and the execute the parsing routine on it. I think saving the stream to an external EEPROM and then retrieving it slowly so my parsing code can actually fallows will do the trick. I can control the speed of the serial stream from 300 bauds (not optimal) up to 112000 bauds.
Is the approach correct? Can I write to the EEPROM faster than a 9600 bauds serial stream without collapsing the arduino?

SD card would probably be a more sensible alternative.

Do you really need the all the data before you can parse it? Can't you parse it on-the-fly? Could you change the sender code so that it wait when the arduino is busy (send-ack pattern). EEPROM has a limited amount of write cycles, so it's not ideal. Serial RAM, like e.g. 23K256, would be more appropriate. (though I can't tell if the arduino can write fast enough, as you asked)

You can parse indefinitely large amounts of data with a state machine parser.
General description: State machines
As an example, I wrote recently an HTTP server which parses incoming HTTP data (eg. cookies, parameters, POST data, GET data) on-the-fly.
You need enough RAM for one item of data, naturally. But then you act upon it, and then discard it. In the case of the web server, you could conceivably process a complex form with thousands of actions on it (eg. turn on switch 5, pump 3, heater 22). It parses each action, and then you act on it, then you parse another action.

You can even consider the Arduino bootloader as an example of this. The Optiboot bootloader is 512 bytes on a Uno, but it can re-flash 32 KB of program memory. How? The programming data comes down in bursts (packets, if you like) and it processes each packet at a time, then discards it and reads the next one.

Hello @Nick! I keep seeing your name popping out in the Arduino forums and here in stackexhange always helping the comunity. Thank you!!!

@DomingoSL Nick's website is an excellent Arduino reference http://www.gammon.com.au/forum/index.php?bbtopic_id=123


text:
Passing user defined callback functions to a library method
I developed an Arduino library that have a method called "process". This method is a Void function and must be called inside the loop and most of the time the library handles everything by it self:
#include <HookNinja.h>

HookNinja hookninja;

void setup()
{}

void loop()
{
  hookninja.process();
}

The idea is to keep the user program a simple as possible. Sometimes "process" have some data to give back to the user so he can use it as he likes. A simple approach is not to make process void and make the user check for the return value of process:
void loop()
{
  someVariableType foo;
  foo = hookninja.process();
  if(foo) {
    //user defined things
  }
}

But the data returned by process could be anything, from an int to an array of Strings, only the user knows the return type, also this method seems not very elegant. Im not an expert of C++, for me the ideal solution will be an object oriented approach were the user pass a function to process that can be called from the library, but I have no idea how to do this in C++, something like:
void userFunction(type param) {
  //do something with param
}

void loop() {
  hookNinja.process(some how pass userFunction here)
}

A common solution would be to have the user provide a callback which
takes no arguments and returns nothing. This is how attachInterrupt()
works, so it may be the least surprising approach for your users. The
user function can then get data from the rest of the program using
globals.
If you really prefer passing an argument to the user function, the
problem is you do not know the data type. The usual approach in plain C
is to give it a “generic” pointer, and let the user cast it into a
pointer specific for his data type. This is how functions like qsort()
work:
HookNinja hookninja;

void userFunction(void *param) {
    someVariableType foo = * (someVariableType *) param;
    //do something with foo
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process((void *) &foo);
}

A cleaner C++ approach could be to make you class a template that is
specialized for the type of the user data:
HookNinja<someVariableType> hookninja;

void userFunction(someVariableType param) {
    //do something with param
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process(foo);
}

But keep in mind that many Arduino users may not be familiar with
templates.


text:
Light communication from pc/app to arduino
I will like to implement a serial communication protocol, using javascript in a mobile browser to make the browser background blink (alternating the color from black to white) according to the bits, to communicate a few bytes to an Arduino using some kind of light sensor (photo diode or resistor) to parse. Electric Imp did something with https://electricimp.com/platform/blinkup/ .
Is there any library or implementation or where to start guide?, if not, how would you implement it?
I fear one of the problems of using a mobile browser with javascript to light-encode the bits will be timing issues, since setTimeInterval is not perfect, I could split the screen, one half blinking continuously (clock) and the other half the data, but that will require two light sensors.

Doing bit stuffing can prevent timing problems when you are sending a lot of 0s or 1s in an row. Alternatively use Manchester encoding (slower).
On the browser side, I'd suggest using <Canvas>. Combine this with requestAnimationFrame which gives you a very accurate timestamp as an argument. Though you have to check for support as older browsers don't support that.

You should investigate communication protocols and encoding techniques that embed the clock signal into the same data stream as the data signal.
One common method is called Manchester Coding.  This entails splitting each bit into two halves.  A 1 sends light followed by dark, and a 0 sends a dark followed by a light.  It's then up to you to work out which transitions are which and where in a bit they occur (is a high transition the start of a 1 or mid-way through a 0?)
Another popular method (used in things like Ethernet) is called 8b/10b.  That involves sending 10 bits to represent every 8 - more efficient than manchester coding (that could be considered 8b/16b) and can be read about here: https://en.wikipedia.org/wiki/8b/10b_encoding It's somewhat harder to implement than Manchester Code, so although it's less efficient I'd recommend the simplicity of Manchester Code.


text:
Is serial modem routine written on the Arduino Leonardo bootloader?
I'm starting with Leonardo and I'm a bit confuse about the serial modem function. As you know on boot the Leonardo for the first 8 seconds wait for a program on the USB port and then it goes in serial modem mode while my program runs.
I'm designing a consumer product (open source) and I will like to make some modifications to my board in order to make it more friendly:

On boot it has to go into programming mode only if a jumper is set. Otherwise it goes directly into serial modem.
I need to change to modem name, instead of:

Have the operating system pickup the serial modem with no drivers request.

For 1 and 2, is it possible? should I try to modify Caterina or it will be easier to work with Optiboot? Number 3 works already in linux distributions, but in Windows some pcs ask for drivers are, and even worse, some windows 64bits + usb3 requires some minors hacks to pick up the Leonardo serial drivers, is it possible to improve? Ideally I want the board to be connected to a PC/Mac/Linux and get configured as a serial com with no user intervention.
I think this are questions that every person trying to create a consumer product with Arduino needs to answer before producing the actual product. So, and resources, references and where to start guides will help me and other people in the community.

Sounds like you need to be using the stock Atmel '32U4 firmware instead of any Arduino bootloader. Also, here's USB in a Nutshell so that you can handle items 2 and 3.


text:
Speaker not producing the right sound after a led strip was introduced

Grove speaker:
http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html
ws2812-led strip

Hi, I have been working to produce tones on a speaker and it works with the following code
    int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3, NOTE_B3, NOTE_C4};
    ...
    ...
    tone(pin, melody[pitch]);

After I included my addressable LED strip sketch codes, the speaker does not produce the same tone as normally it does. It sounded distorted this time round.
void loop()
{
  strip.Update(); //NeoPatterns strip(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800, &StripComplete);
}

Class:
// NeoPattern Class - derived from the Adafruit_NeoPixel class
class NeoPatterns : public Adafruit_NeoPixel
{
  public:

// Member Variables:
    ...
    ...

void (*OnComplete)();  // Callback on completion of pattern

// Constructor - calls base-class constructor to initialize strip
NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)())
  : Adafruit_NeoPixel(pixels, pin, type)
{
  OnComplete = callback;
}

// Update the pattern
void Update()
{
  if ((millis() - lastUpdate) > Interval) // time to update
  {
    lastUpdate = millis();
    switch (ActivePattern)
    {
      case RAINBOW_CYCLE:
        RainbowCycleUpdate();
        break;
      default:
        break;
    }
  }
}

// Initialize for a RainbowCycle
void RainbowCycle(uint8_t interval, direction dir = FORWARD)
{
  ActivePattern = RAINBOW_CYCLE;
  Interval = interval;
  TotalSteps = 255;
  Index = 0;
  Direction = dir;
}

// Update the Rainbow Cycle Pattern
    void RainbowCycleUpdate()
    {
      for (int i = 0; i < numPixels(); i++)
      {
        setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
      }
      show(); // When I comment this line, the speaker will work properly. What is happening?
      Increment();
    }

The tone() command is interrupt driven.
To get the tight timing needed by the LED strips interrupts are disabled while sending the data.
That means the tone() command stops while you're updating the LED strips and starts again afterwards.
The end result will be the sound is corrupted - maybe sounding like it's bubbly or underwater or just "rough".
The two basically can't work together and I'm not sure what to suggest to make them work together on a low-end MCU like the AVR.

What about using this library? http://forum.arduino.cc/index.php?topic=143940.0

or are there any possible workaround to play a sound together with the LED strip? My sketch will consist of a sensor,a servo and a LED strip.

That one also uses interrupts.

Either only update the led strip in between tones, or build your own tone function that changes the PWM frequency on one of the PWM pins (probably 9 or 10, since timer1 would be the most useful for that).


text:
Playing Melody with Tone() without using delay()
Is there a method to play a Melody with Tone() without using the delay() function?
tone(8, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration;
**delay(pauseBetweenNotes);**

Yes. The same method as is used in the BlinkWithoutDelay example sketch.

As others have noted, this can be done using the same method as used in the standard 'BlinkWithoutDelay' example sketch, and combining that with a state-machine type approach. In a simple state machine you'd assume you can be in one of two states: outputting a tone, and not outputting a tone.
Applying these ideas to your code snippet above:
// BEFORE SETUP
const int tonePin = 8;
unsigned long previousMillis = 0;
const long interval = pauseBetweenNotes;
const long interval = noteDuration;
boolean outputTone = false;                // Records current state

// IN LOOP
unsigned long currentMillis = millis();

if (outputTone) {
// We are currently outputting a tone
// Check if it's been long enough and turn off if so
    if (currentMillis - previousMillis >= noteDuration) {
        previousMillis = currentMillis;
        noTone(tonePin);
        outputTone = false;
    }
} else {
// We are currently in a pause
// Check if it's been long enough and turn on if so
    if (currentMillis - previousMillis >= pauseBetweenNotes) {
        previousMillis = currentMillis;
        tone(tonePin, melody[thisNote]);
        outputTone = true;
    }
}

Adding a bit to kabdulla's great example, to be able to use a MelodyArray
// declaring variables
const int tonePin = 10;
unsigned long previousMillis = 0;
const long pauseBetweenNotes = 250;   // interval between notes (ms)
const long noteDuration = 400;        // (ms)
boolean outputTone = false;                // Records current state
const int MelodyLength = 2;
const int Melody[MelodyLength] = {880, 698};
int MelodyIndex = 0;
unsigned long currentMillis;

void setup() {
}

void loop() {
  currentMillis = millis();
  PlayMelody();
}

void PlayMelody() {
  if (outputTone) {
    // We are currently outputting a tone
    // Check if it's been long enough and turn off if so
    if (currentMillis - previousMillis >= noteDuration) {
      previousMillis = currentMillis;
      noTone(tonePin);
      outputTone = false;
    }
  } else {
    // We are currently in a pause
    // Check if it's been long enough and turn on if so
    if (currentMillis - previousMillis >= pauseBetweenNotes) {
      previousMillis = currentMillis;
      tone(tonePin, Melody[MelodyIndex]);
      outputTone = true;
      //Update to play the next tone, next time
      MelodyIndex = MelodyIndex + 1;
      if (MelodyIndex >= MelodyLength) {
        MelodyIndex = 0;
      }
    }
  }
}

this is a minimal modification of the basic Arduino toneMelody example to a non-blocking version
#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

unsigned long previousMillis = 0;
unsigned long pauseBetweenNotes;
int thisNote;

void setup() {
}

void loop() {

  // iterate over the notes of the melody:
  unsigned long currentMillis = millis();
  if (thisNote < 8 && currentMillis - previousMillis >= pauseBetweenNotes) {
    previousMillis = currentMillis;

    // to calculate the note duration, take one second divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    pauseBetweenNotes = noteDuration * 1.30;

    thisNote++;
  }
}

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


text:
How to use a grove speaker without using delayMicroseconds?
is there another way to replace delayMicroseconds(BassTab[note_index]) as I cannot have delays in my loop due to the need of having multi-tasking in my sketch.
Grove speaker: http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html
/*macro definition of Speaker pin*/
#define SPEAKER 8

int BassTab[]={1911,1702,1516,1431,1275,1136,1012};//bass 1~7

void setup()
{
  pinMode(SPEAKER,OUTPUT);
  digitalWrite(SPEAKER,LOW);
}
void loop()
{
    sound(5);
    delay(5000); //Wait 5second and play the sound again
}

void sound(uint8_t note_index)
{
  for(int i=0;i<100;i++)
  {
    digitalWrite(SPEAKER,HIGH);
    delayMicroseconds(BassTab[note_index]);
    digitalWrite(SPEAKER,LOW);
    delayMicroseconds(BassTab[note_index]);
  }
}

It's just a small amplifier and speaker - what you put into the SIG pin gets amplified and sent out the speaker.
Instead of doing the audio generation manually like that I would suggest using the tone() function which will generate an audio tone at a desired frequency in the background.

https://www.arduino.cc/en/Reference/Tone


text:
WDT and RadioHead with delay()
The core I use is this one
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2
RadioHead ASK library (slimmed down)
What I want to do is:

deep sleep
wake up every minute
turn on sensor
take measurement
transmit data
back to sleep

This works when I test it seperatly, where it goes awry is when I combine RadioHead with WDT and then try to use a delay. This always hangs.
Probably a timer issue, I am looking for a work around.
I need the delay because I need to start the sensor, wait .5 sec and then take a measurement. Maybe I should give the ATtiny85 just some job to keep it busy for 0.5 sec?
This is working code, when I uncomment //  driver.init(); it will fail.
// RadioHead ASK
#include <RH_ASK.h>

// Sleep
#include <avr/sleep.h>
#include <avr/wdt.h>

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// Absolute reference PB to overcome inter-IDE issues
#define T_PIN 1 // transmission
#define L_PIN 3 // optional LED pin
#define S1 A2
#define S2 A1
#define BAUD 2000

// Baud rate, receiver, transmitter
RH_ASK driver(BAUD, 9, T_PIN); // pin 9 is non existent

// Watchdog
volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

// Sleep
void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

// Setup for Watchdog
void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

void setup() {
//  driver.init();
  setup_watchdog(8);
}

void loop()
{
  if (f_wdt==1) {
    pinMode(0, OUTPUT);
    digitalWrite(0, HIGH);
    delay(500);
    digitalWrite(0, LOW);
    delay(500);
    system_sleep();
  }
}

The instruction bb|= (1<<WDCE) looks wrong: in the timed sequence, you are always writing this bit to one. The datasheet says (emphasis mine): “2. Within the next four clock cycles, in the same operation, write the WDE and WDP bits as desired, but with the WDCE bit cleared”. I would do something like cli(); WDTCR = _BV(WDCE) | _BV(WDE); WDTCR = _BV(WDIE) | _BV(WDP3); sei();.

I do not understand this part of the code well enough to understand your suggestion.  I need to read up on it.

The RH_ASK library uses timer0, which is also used for millis and delay.
Quick workaround is to use the standard AVR delay instead.
#include <util/delay.h>

...

_delay_ms(500)

This point needs to be made in big bold red letters in the RadioHead documentation.  Many hours were spent {wasted?} trying to debug the issue. +1


text:
connect arduino to battery with 12V motor
I am looking  at this(instructable with circuit picture) tutorial for making a self-balancing robot. However, I am confused about how the battery connects to the arduino. I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply. How should I get a charger cable and solder on the battery wires to the charger? If so are there any tutorials? Is the connection to the Arduino necessary?
(please look at the Firizing diagram in the instructable)
Thanks

I am looking at this(instructable with circuit picture) tutorial for making a self-balancing robot.
  However, I am confused about how the battery connects to the arduino.

Well, it seems he has attached a 9V battery through a voltage regulator, to the Arduino.
Which is bullshit.
You can put the 9V directly into the barrel-jack of the Arduino. You actually should. Putting 5V on the barrel jack is not within the specs. (https://www.arduino.cc/en/main/arduinoBoardUno)

I know the 12 V must go to the motors to power them yet the diagram shows wires connecting to the Arduino through some kind of green device. I assume this connects to the power supply . However I do not have this green device and I don't know how to connect to the power supply.

Well, the motors only get 9V in this diagram (which might work neverthless). But bear in mind that 9V batteries won't last long.
I'm not sure what you mean by "Green device", the HC-05 or the L293D?
Anyway, the L293D are quadruple high-current half-H drivers, which basically is a way to switch 12V on/off/invert based on the 5V inputs (from Arduino).
You could do this with some circuitry, but I suggest picking up a "motor driver (arduino)"

How should I get a charger cable and solder on the battery wires to
  the charger?

You can't charge regular 9V batteries.

Is the connection to the Aruino necessary?

The specific connection he shows? No.
Power to the Arduino board? Yes.

Well, it seems he has attached a 9V battery through a voltage regulator, to the Arduino. Which is bullshit. - It's an instructable... what do you expect? It's a repository for complete rubbish and bullshit. The rule is: if you don't have the slightest clue what you are doing, do it anyway and then post it on instructables.

@Majenko that's true, but wanted to highlight it since it really confused the person who asked the question ;)
I was thinking of adding, and would like to add: "You should use reputable sources, this instructable is full of mistakes."


text:
Is this bluetooth setup good?
I am trying to do this tutorial http://www.instructables.com/id/Chappie-Self-Balancing-Robot/  on building a self-balancing robot with uno. However, I bothered by the Bluetooth wiring. I've done Arduino projects with Bluetooth before and all the Hc-05 wirings I've seen have it connected to the Tx and Rx pins.Currently, I have my Bluetooth module wiring like this :   with http://cdn.instructables.com/FSK/AI30/HMMFE6UO/FSKAI30HMMFE6UO.MEDIUM.jpg.
Will the different wiring need a different implementation, the code I see on the chappie instructable link does not have any pin mentions but I'm not sure. Is the chappie wiring fine? should I change my wiring? should I change my code?
I'm confused.

Which code are you reading? At step 5 he wrote

Complete code can be found on the GITHUB.

The sketch file (here is the direct link) has the following lines:
const int rxpin = 11; // pin used to receive (not used in this version)
const int txpin = 4; // pin used to send to LCD

SoftwareSerial blue(rxpin, txpin); // new serial port on pins 2 and 3

This means that the bluetooth is using a software serial on pins 11 and 4.
I don't know where you got the image you posted, but anyway that wiring is not the same as the one in the instructable. With your wiring, you can either use the software serial on pins 0 and 1, or (better) use the hardware serial. To do so, remove or comment the lines I highlighted and then replace every call to blue with Serial.


text:
How to use Arduino as RC Receiver
I want to use Arduino as my RC receiver. I will generate PPM signal from Arduino. Then I will send generated signal to my OpenPilot CC3D. I fetched following image from OpenPilot GCS. The diagram shows to use input 6.

Following is the image of my CC3D. The cable colors does not correspond to each other.

Which input cable should I connect to Arduino?
How should I connect black(ground) and red(5V) cables to Arduino:

EDIT this answer explains how you can put a Arduino between a (1 ppm pin per channel) RC receiver and a RC receptor. This allows for smart features (like autonomous control with RC overrule, or sensor based corrections,..)
It seems it is not the question of op.
What you want is easy but there are some pitfalls.
I can make a long story short by these links
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with.html
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_20.html
http://rcarduino.blogspot.com/2012/04/how-to-read-multiple-rc-channels-draft.html
if you are serious about RC this may be of your interest to
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_25.html
I also converted this info in a library you can find here:
https://github.com/jantje/ArduinoLibraries/tree/master/RCLib
And for stackexchange policy here the hightlights.
If I look at the picture you added you have a 6 channel ppm receiver. Each ppm channel you want to read must be connected to a interrupt enabled pin of your arduino (The drawbacks of software enabled interrupt pin is another discussion).
The high time of the ppm tells how high or low your lever is on the remote control.
You can then have arduino do with this info what you want. For instance use the servo library to generate a ppm signal out to servo's and ppm driven motors.

Your answer addresses a problem opposite of that in the question.  This is not about reading an RC receiver but about creating one.  The PWM(s) are outputs, not inputs.

I was wondering what was actually asked. It just shows the quality of the average question.  My answer is actually RC in RC out. and it is PPM not PWM. The servo library creates PPM

Radio PPM is not servo PWM

@ChrisStratton is right. I want to use Arduino as RC receiver. I will generate PPM signal from Arduino. Then I will send generated signal to my OpenPilot CC3D.

@jantje There are 6 channels. But only 1 of them is used as PPM channel. As shown in the image which I fetched from OpenPilot GCS software, the PPM channel is shown as 8th pin.

@Halil Your question is still not clear to me. As this is a Arduino forum and not a aviation forum I think it would be a good idea to place arduino in the middle and explain what your input is and what the output is you want to achieve.Just my 2 cent. From what I understand now your question is: "How can I -using a arduino- mimic a rc receiver compatible with a openPilot CC3D" (and if that is the question I can't answer it )

@jantje I think you didn't fully read the question. Please review again the last 2 lines which is below the photo. I am not asking how to mimic rc receiver using arduino in this post. I am asking how to connect CC3D controller to Arduino


text:
Difference between simple wifi transceiver and arduino yun
I am debating over getting arduino yun or 2pcs nRF24L01+ 2.4GHz Wireless Transceiver. Here is the link to the transceiver on amazon  amazon description. I do not know much about wifi but why would someone get the 70 dollar yun instead of the basic transceiver and a uno. In particular for my project I want my arduino to use Web API's like twilio to send messages to my phone. Can both products do that?I know the yun has linux but I don't know if I need that for my project.Is their a better option (price is part of my decision)

The nRF24L01+ modules aren't WiFi. They cannot talk to a WiFi router or the internet. They can only talk to other nRF24L01+ modules. They are good for connecting two or more UNOs together.
The Yún has a full WiFi connection and is also able to operate as a router itself. It is best suited when you need to run complex networking on an Arduino.  To access the WiFi on the Yún you need to communicate with it over the in-built serial connection. There are libraries to help you, but the overall package is really very much overkill unless you have a requirement to do complex network routing (VPN for instance) or run software (say a Python program) directly on the Linux portion of the device.
It sounds like what you are really after for your project is an Arduino UNO and WiFi shield.
Another popular option is the ESP8266 modules.  These can be controlled through serial using AT commands, or directly programmed using the Arduino-compatible core available from https://github.com/esp8266/Arduino

Good answer.Would getting a yun be equivalent to getting a UNO and WiFi shield.

Not entirely. A WiFi shield means the Arduino main chip has control over all aspects of the WiFi connection. On the yun the small Linux computer does the WiFi and you make requests through serial. For that sort of thing the yun is very much overkill.


text:
Faster and lighter approximate timing code without using timer
I want to use loop() iterations counter to execute some tasks periodically or tasks like debouncing. My other sketch is running every loop() at least 20 ms, and if i am using 5 ms time to wait to
debounce a button, it will still be at least 20 ms waiting, also cpu will have to compare two not zero values, which is a bit slower.
I think it is more difficult for cpu than just incrementing and decrementing one variable and comparing it to 0. So i came up with pattern like that:
boolean onOff=1; // arduino led state. My task here is LED blinking.
byte loopCounter=2; // number of iterations made by loop(). Set as little variable as possible to save ram and cpu time.
//Code will be executed every "loopCounter" iteration of loop().
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
      if (--loopCounter == 0) { //comparing with 0 should be a bit faster and easier for Arduino to process. Correct me if i am wrong.
        loopCounter=2; // That digit sets how often your code will be executed. Every 2(3,4... set your own value) iterations of loop().
        digitalWrite(13, onOff= !onOff); // the task itself.
        }
}

It may be more convenient in some ways than millis() and micros() patterns. Also i do want want to use hardware timers for timing.
It may be convenient in cases, when you don't care when exactly task will be done, you just want it to be done ASAP (as soon as possible), but
not during that particular iteration of loop(). Basicly you can use it as a timer if you know how it takes one iteration to be done.
So, if your sketch runs 1 iteration of loop() for 1 ms, and you need some action to be done every 1 sec, 1ms*1000 == 1 sec. So you
need it to be done every 1000 iterations.

So, is that really can save some ram and cpu time?
Is comparing with zero is faster for arduino than comparing with not
zero?
Are millis() and micros() timing patterns using more operations
(setting value to variable, computing the difference between 2
values and than comparing it to a period you have set) instead of
decrementing and comparing to zero with my pattern?
Any side-effects of using my pattern? I can only think of very
unaccurate timing and delays more than you think if your sketch done
smth more than usual, because of button push for example or some
sensor changed value.
Thank you!

Your use of digitalWrite will be the slow thing there, not comparing to zero, or comparing two numbers. Try looking up the digitalWriteFast library.

To put it another way, you are optimizing the wrong thing. :)

I know about digitalWrite, thank you. But readability is more important for stackoverflow i guess)

millis() is one of the fastest function of the Arduino core. It just returns a copy of a global variable (timer0_millis) which is updated by a timer interrupt. The copy is performed with interrupts disabled in order to avoid a race condition. See the implementation.

I know about digitalWrite, thank you. But readability is more important - what's unreadable about: digitalWriteFast (13, onOff= !onOff);?

Oh, it is perfectly readable, Ijust did not know about it:)  Thank you!

Personally I wouldn't be putting too much effort into optimizing away your timers. millis() is pretty fast - the work needed to calculate the result is done in the background anyway (by interrupts). I tried some test code:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  unsigned long start, finish;

  start = micros ();
  for (byte i = 0; i < 100; i++)
    digitalWrite (13, HIGH);
  finish = micros ();

  Serial.print ("Time taken to do digitalWrites: ");
  Serial.println (finish - start);
  Serial.flush ();

  start = micros ();
  volatile unsigned long now;
  for (byte i = 0; i < 100; i++)
    now = millis ();
  finish = micros ();

  Serial.print ("Time taken to do millis: ");
  Serial.println (finish - start);
  Serial.flush ();

  }  // end of setup

void loop ()
  {

  }  // end of loop

Results:
Time taken to do digitalWrites: 520
Time taken to do millis: 188

You can see that the digitalWrite() (which you weren't worried about) takes 5.2 µs, whereas calling millis() (which you were worried about) takes 1.88 µs.

Are millis() and micros() timing patterns using more operations (setting value to variable, computing the difference between 2 values and than comparing it to a period you have set) instead of decrementing and comparing to zero with my pattern?

Yes, just adding one to a variable and then comparing will be faster. Whether it is worth the effort is debatable.

If 'millis()' is using interrupts, it's benchmarked time will be a bit more, at lest by the time needed to increment variable, starting and stopping an interrupt also takes some time i guess. So thank you very much for telling about interrupts:)

Or did i miss smth about interrupts? One more thing here. I have heard from an experienced programmer, that is is nice to count from 'n' to zero to optimise 'if()', especially in larger loops. Compilers usually do it themselves, but you can never be sure about that. So, it will be done 'for (byte i = 100; i >= 100; i--)' instead of 'for (byte i = 0; i < 100; i++)'. by arduino compiler?

I assume you mean 'for (byte i = 100; i >= 0; i--)'. Here's the flaw. In trying to outguess the compiler and maybe save one machine cycle, you've introduced a bug. The byte type is unsigned, and thus i will always be >= 0. Thus the loop will never terminate.

Well, i can see my mistake. And that is the reason i want to know if compiler can do hard work for me. I need to know should i think about it at all or not. I would find out about my mistake pretty soon in real code i guess, but still it is a loss of time...

Well, compilers are pretty good these days. You can help them out by choosing good data types (for example, byte as you did, rather than unsigned long when you only have to count to 10). I wouldn't be sweating over whether it is faster to count up to 10, or down to zero.


text:
Creating a keypad matrix that will communicate wirelessly with an Arduino Uno
I have a 30 button matrix and I would like to use a keyboard encoder to decipher what button was pressed. I would like that information (what button was pressed) to be wirelessly sent to my arduino uno nearby. What is the easiest solution? Can/how can I incorporate Arduino's Bluetooth shield to achieve this?

Which keyboard encoder? Or are you asking how to make one? Are you planning to have a second Arduino adjacent to the matrix to encode the keypresses?

Bluetooth is overkill, and unnecessarily complex for this simple task. Try looking and XBee, NRF24L01, or those cheap 433MHz transmitter/receiver pairs.

NRF24L01 is the best option. Takes the lowest amount of power if properly configured.


text:
Integrating two Arduino Ethernet libraries in one sketch
I am trying to integrate two different Arduino Ethernet libraries, EtherShield and UIPEthernet in one sketch.
EtherShield library is used to control LEDs via Android mobile application. While UIPEthernet is used to control the same LEDs via Web Server.
Both codes run perfectly when they're uploaded individually. But I need them to run in a single sketch. So I combined them in one sketch. That's where my problem is. They're not running smoothly anymore. My mobile app can only turn one LED off then the app will crash. Accessing my Arduino's web server gives me error as well (but before it is really, really working T.T)
Help me, please.
This is my code
// ========== UIPEthernet library
#include <Dhcp.h>
#include <Dns.h>
#include <ethernet_comp.h>
#include <UIPClient.h>
#include <UIPEthernet.h>
#include <UIPServer.h>
#include <UIPUdp.h>

// ========== EtherShield library
#include "EtherShield.h"
#include "ETHER_28J60.h"

// ========== MOBILE
//static uint8_t mac[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
//static uint8_t ip[4] = {192, 168, 15, 97};
static uint16_t port = 80;

ETHER_28J60 e;

// ========== WEB
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 15, 97 };
byte gateway[] = { 192, 168, 15, 1 };
byte subnet[] = { 255, 255, 255, 0 };

String inString = String(35);

int i;  // Used for looping
String Room;

int pin[] = { 0, 2, 3, 4, 5 }; // Lock pin num 0 in array is not used
int numOfRooms = 4; // Number of rooms
String value[] = { "OPEN", "OPEN", "OPEN", "OPEN", "OPEN" }; // Startup all rooms are closed

EthernetServer server(port);
String data;

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

  // ========== MOBILE
  e.setup(mac, ip, port);

  // ========== WEB
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();

  // Set pin mode
  for (int j = 1; j < (numOfRooms + 1); j++)
  {
    pinMode(pin[j], OUTPUT);
  }

  Serial.println("\n[ WEB + MOBILE ]\n");
  Serial.println("Serial READY");
  Serial.println("Ethernet READY");
  Serial.println("Server READY\n");
}

void loop()
{
  webModule();
  mobileAppModule();
}

void mobileAppModule()
{
char* params;
if (params = e.serviceRequest())
{

  //ROOM 311
  if (strcmp(params, "?cmd=1") == 0)
  {
        digitalWrite(pin[1], HIGH);
        Serial.println("ROOM311 is OPEN\n");
  }
  if (strcmp(params, "?cmd=2") == 0)
  {
        digitalWrite(pin[1], LOW);
        Serial.println("ROOM311 is CLOSE\n");
  }

  //ROOM 312
  if (strcmp(params, "?cmd=3") == 0)
  {
        digitalWrite(pin[2], HIGH);
        Serial.println("ROOM312 is OPEN\n");
  }
  if (strcmp(params, "?cmd=4") == 0)
  {
        digitalWrite(pin[2], LOW);
        Serial.println("ROOM312 is CLOSE\n");
  }

  //ROOM 313
  if (strcmp(params, "?cmd=5") == 0)
  {
        digitalWrite(pin[3], HIGH);
        Serial.println("ROOM313 is OPEN\n");
  }
  if (strcmp(params, "?cmd=6") == 0)
  {
        digitalWrite(pin[3], LOW);
        Serial.println("ROOM313 is CLOSE\n");
  }

  //ROOM 314
  if (strcmp(params, "?cmd=7") == 0)
  {
        digitalWrite(pin[4], HIGH);
        Serial.println("ROOM314 is OPEN\n");
  }
  if (strcmp(params, "?cmd=8") == 0)
  {
        digitalWrite(pin[4], LOW);
        Serial.println("ROOM314 is CLOSE\n");
  }

  //
  if (strcmp(params, "?cmd=9") == 0)
  {
        digitalWrite(pin[1], LOW);
        digitalWrite(pin[2], LOW);
        digitalWrite(pin[3], LOW);
        digitalWrite(pin[4], LOW);
        Serial.println("All rooms are now CLOSED\n");
  }

  e.respond();
  }
}

void webModule()
{
     EthernetClient client = server.available();

 if (client)
 {
 // An HTTP request ends with a blank line
 boolean current_line_is_blank = true;

 while (client.connected())
 {
  if (client.available())
  {
    char c = client.read();
    // If users have gotten to the end of the line (received a newline
    // character) and the line is blank, the HTTP request has ended,
    // so users can send a reply

    if (inString.length() < 35)
    {
      inString.concat(c);
    }

    if (c == '\n' && current_line_is_blank)
    {

      // Send a standard HTTP response header
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();

      client.println("");

      client.println("<title>CONTROL PANEL</title>");

      client.println("");

      client.println("
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
COMPUTER ENGINEERING LABORATORY
");
      client.println("

");
      client.println("

");
      client.println("
");
      client.println("

CONTROL PANEL

");

      client.println("<form method=get>");

      for (i = 1; i < (numOfRooms + 1) ; i++)
      {
        Room = String("ROOM") + (i + 310);

        if (inString.indexOf(Room + "=OPEN") > 0 || inString.indexOf("All=OPEN") > 0)
        {
          Serial.println("\n" + Room + " is OPEN");
          digitalWrite(pin[i], HIGH);
          value[i] = "CLOSE";
        }
        else if (inString.indexOf(Room + "=CLOSE") > 0 || inString.indexOf("All=CLOSE") > 0)
        {
          Serial.println("\n" + Room + " is CLOSE");
          digitalWrite(pin[i], LOW);
          value[i] = "OPEN";
        }

        client.println("
" + Room + "     <input type='submit' name=" + Room + " value=" + value[i] + " style='height: 50px; width:100px;' />

");
      }

      client.println("

All <input type='submit' name='All' value='OPEN' style='height: 50px; width:100px;' />    <input type='submit' name='All' value='CLOSE' style='height: 50px; width:100px;' />");
      client.println("</form>");

      for (i = 1; i < (numOfRooms + 1); i++)
      {
        if (value[i] == "ON")
        {
          i = i + 310;
          client.println("

Room " + String(i + 310) + " is OPEN
");
        }
        else if (value[i] == "OFF")
        {
          client.println("

Room " + String(i + 310) + " is CLOSE");
        }
      }
      client.println("
");
      client.println("
");
      client.println("");
      break;
    }

    if (c == '\n')
    {
      // we're starting a new line
      current_line_is_blank = true;
    }
    else if (c != '\r')
    {
      // we've gotten a character on the current line
      current_line_is_blank = false;
    }
  }
}

    // give the web browser time to receive the data
    delay(1);
    inString = "";
    client.stop();
    }
}

MOBILE means code for Arduino-Android
WEB means the code for Web Server

You can't.

The code has both libraries trying to run on the same port which is not allowed (in fact you couldn't even do that on a computer). You could try setting one to one port and the other to another port, but that might not work because...
These libraries most likely are both expecting to be the only code accessing the hardware and they will step over each other and cause problems. Sharing hardware between different pieces of code is an advanced programming topic not suited for beginners and would involve rewriting significant portions of these libraries.

The best course of action is to either re-implement your app functionality to use the UIPEthernet Library, or re-implement the webpage using the EtherShield library. You should be able to do this because your app interface is supplying parameters (e.g the "?cmd=" part) and the webpage is not. You should be able to set it up so that if it has "?cmd=" in the request, it should perform the command, otherwise it should return the webpage.


text:
Can I stack an Arduino to another Arduino?
I'm using Arduino clones, which have pin headers the same as Arduino's shields have (with extended "legs" below the board to be stackable).
Can I stack my Arduino (Mega) clone to an Arduino (Uno) clone without destroying both? Wouldn't it explode or something?
Just asking before trying it.
Thanks!

Is this a curiosity question or do you have a goal in mind? Just curious....

No, I don't think that is a good idea. You would basically short the pins of each of them together, plus their power supplies. The only way it might conceivably work was if one Arduino had all its pins as inputs and the other as outputs, otherwise they would be "fighting" each other to drive a pin high or low. You would also have connected together their Reset pins so they would both reset at the same time. And doing serial comms would be problematic as the serial ports would be fighting each other.

Also, uploading sketches would be virtually impossible, as when you started the upload, both would be reset, both bootloaders would try to read the incoming data, and reply at the same time. Plus, the Mega and the Uno have different uploading protocols. So at the very least, you would have to separate them every time you uploaded new code, to either one.


text:
"Sharing" used GPIO pins
I have a question regarding the ARDuino uno and some shields. I currently have a shield on my Uno, which takes the pins 0 to 7. However, on top of that board there is an extension of those 8 pins. If they were always in use, I suppose that the extra ports wouldn't be on top of the board, right?
Here's how it looks:
So it seems like you're able to "share" them. Is it possible to do so in real-time or is that there so you can use the ports when you disable the shield?
If its possible in real-time, how would I go about doing that? I've searched a little but couldn't find anything. I suppose i'd need some kind of clock to make the switch between the shield and the other components on pins 0-7, but not sure how to do that.
I'm kind of an electrics newbie, so hence the question might be a little silly :)

No, you can't "share" pins between shields, except in specific circumstances (open-drain interrupts, I2C or SPI buses, etc).  General GPIO pins connect to just one device at a time.
I can't tell from that picture, but it is highly unlikely that all 8 of the IO pins are actually in use by the shield, and the ones that aren't actually connected to anything within the shield are available for another shield placed on top to use.  You'll have to look at the schematic or manual for the shield to know exactly which pins are used for what and which are available for other shields to use.
However, one thing to note with that shield - it doesn't appear to pass through the power header, so how a shield on top would get powered at all is a mystery to me.

Its using the ICSP headers to power the board :) But this makes sense. The board (and the arduino, and the extra hardware) would need an interrupt controller to check whoose turn it is to listen / write to the ports, if I understand correctly. Thanks for the answer!

Interrupts are far from the only means of deconflicting.


text:
Updating the ARDuino code over GPRS
I've been searching a little for self-updating the ARDuino, and most i've come about is updating it using a wifi / lan shield.
Now I have a GPRS shield that can connect it to the internet. Say that I want to remotely update the shield - how would I go about doing that?
I'm guessing I need some kind of bootloader - but is that extra hardware?
Actually the question boils down to:

How can I flash the ARDuino Uno with new software, that I'll receive over a GPRS connection using a GPRS shield?

It sound a lot like the OverTheAir update system used by Moteino. They use an external SPI flash chip to store any updates. The main program check for updates and downloads them (and then reset the board). The bootloader only has to read the flash chip to see if there is an update. This will make the bootloader a lot smaller. Imagine having to load the GPRS library in both your main program and the bootloader. It also makes things less likely to go wrong.

Thanks, thats interesting. I might be able to use some information from that system. I have some information to get me started :) Thanks a ton guys!

@RobQuist Did you managed to update the arduino using GPRS?

@MuzahirHussain No, sorry! It was a fun project to work on but never came around on doing it. I did manage to write a ATMEGA328P chip to flash other ATMEGA328P chips, so it probably is doable just like described up here :)

You would either have to replace the bootloader on your chip (software) with one that knows about your GPRS shield (I don't know if there is one, so you would most likely have to write your own and that is not a trivial task), or use a second microcontroller to act as a programming interface between the GPRS shield and the main Arduino.  That could be another Arduino.
The second option is probably the simplest to create:

The GPRS is connected to Arduino A.
Your main software runs on Ardiuno B.
Both Arduinos are connected by serial
Normal operation Arduino A passes all serial verbatim through to Arduno B
Arduino A receives programming instructions and downloads the new code - maybe storing it on an SD card temporarily (not enough RAM in an Arduino) then resets Arduino B into the bootloader.
Arduino A then sends the serial instructions in the same way that avrdude does to program the downloaded HEX file.

Arduino A is then a proxy between the GPRS and Arduino B.  Arduino A does all the control of the GPRS and sends data between Arduino A and the internet and vice versa - it's up to you to decide how best to achieve that, depending on what information you have going backwards and forwards.
Both solutions require a certain level of programming knowledge and skill and aren't trivial, but are perfectly possible if you set your mind to it.

Cool! Thats the answer I was looking for. But instead of using an extra Arduino, wouldn't it be possible to download the hex file to some persistant storage, and tell the bootloader to restart, and write that hex file to the ATMega, and restart the arduino? I've seen some external bootloader thingsies like these; https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader/uploading-code---hard-way - would it be possible to use that? It would require less space and save me an arduino :)

You could do it with one Arduino, but you will need to write a custom bootloader which knows what you are doing - you could download to SD card then reboot into a bootloader that understands what an SD card is and can find your file on it, but again it's not a trivial bit of programming.  By the way, the "bootloader" is just a special sketch that runs on the Arduino before your sketch runs. It's not an external thing. It's just software that has to be installed on the main chip before it becomes an Arduino.

Cool, thanks. That'll help me get started :)


text:
Emulate RFID Tag
I just got my RFID-RC522 Reader and was wondering one thing. Can i Use an RFID Reader to emulate an RFID Tag, so that if i have another reader it will detect the other one as a card and transfer data. It should be detected as a Tag like a midfare Classic but the data sould be supplied by the Arduino. Is this possible? At all? Or does it require another type of reader? If you know a solution please share it.

I'm almost positive you cant use a RFID Reader to talk to another RFID Reader with the basic libraries and resources we have. You are best just getting an actual tag may it be Mifare classic or another type of RFID Tag.
I'm sure this is possible but the amount of development you will need to dedicate towards this would out weigh just getting a cheap RFID tag.
What you can do is look around see what type of things you have laying around maybe something has an RFID tag in it, or maybe you have a phone with NFC. You can use your phones NFC to send data to a RFID reader, but you will need to find the resources to do this. Sorry I'm not much help but maybe someone has done this before and has a simple solution.

This is not a very useful answer - first it is based on speculation rather than facts, and second your proposal "just getting an actual tag" ignores the question's goal that "the data should be supplied by the Arduino".


text:
Multiple servos noise
I'm building  an application that uses 20 servo motors, and i control then with an Arduino Mega. The servos are having some instability, to the point where they make small random swings. Im powering then from a 7.4V LiPo battery and I drop the voltage to around 6V with 2 series diodes. I've made some research and found 4 things that may help stabilize the servos.

Put a 1000uF eletrolitic capacitor between the battery VCC and GND pins.
Put a 470uF eletrolitic capacitor between each servo VCC and GND pins.
Put a 100nF ceramic capacitor between each servo SIGNAL and GND pins.
Put a 10k pull-up resistor on each servo SIGNAL pin.

My question is, how to make the right decision here. It is better for the project if I take all this designs into account, or I shouldn't be making some combination of this, or one in particular?

My first question is do you have enough power available? As the servos work they may be drawing enough current to pull down your power supply. The capacitors will help, but have you actually checked so see if they are sufficient?

The battery is strong enought to keep 7.4V out while the servos are on.

OK, so probably not that…

Do u use a software serial? That can make you're servos jitter because it uses the same interupts as the servo lib.

I don't think that 7.4V are good for servos. And if very little current is drawn, the diodes have a much lower voltage drop. Measure the voltage after the diodes with an oscilloscope. And then I suggest you to fix your power supply part: use a LDO if the battery voltage is high enough even under stress or a buck-boost module to stabilize it even under heavy load. I prefer the second one, but it depends on you. Probably it can be better to split the 20 motors group in smaller groups to use less costly converters

I've tested the voltage after diode voltage drop and its normaly around 6V, that may not be the problem. The servos consume a mean current of 15 to 20 amps, so the low current drawn problem problaby don't interfere. Im thinking the problem is more due to signal.

I've used it a bit. I'll check that as soon as I can. Do you have any idea how to solve this, because I really need to use both.

This is a bad design!  Your "7.2v"  battery when freshly charged will be 8.4v, which means around 7.2v to the servos, in excess of normal ratings.  Further, the voltage drop through a diode is not truly constant, but current dependent, and your current varies widely depending on how many servos are moving to a new position or stalled.  Use proven battery eliminator circuits or possible switch regulator modules.  Also consider using only a few servos per supply module.

You can use the old software serial library from mikal heart. that one does not die interupts. You can do a google search on it.
here is a forum topic about it:
http://forum.arduino.cc/index.php?topic=82596.0


text:
Updating Array Values Incrementally Overwrites The Existing Values, Why?
I have a global array. I'd like to update the array while the program running.
But, I've found that my program below doesn't work as I expected.
Please checkout the program source:
#define RespLength 10
char* response[] = {"0","0","0","0","0","0","0","0","0","0"};
int idxUpd  = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("Start");
}

void loop() {
  // put your main code here, to run repeatedly:
    char assign[5];
    int wkt = random(10, 99);
    dtostrf(wkt, 4, 1, assign);

    response[idxUpd]  = assign;

    Serial.print("Iteration "+String(idxUpd)+" : ");
    for (int i=0;i<RespLength;i++){
        Serial.print(response[i]);Serial.print(",");
    }
    Serial.println();
    delay(500);

    idxUpd++;
    idxUpd = idxUpd >= 10 ? 0 : idxUpd;
}

Expected output: please concern to the patern
Iteration 0 : 12.2,0,0,0,0,0,0,0,0,0,
Iteration 1 : 12.2,23.7,0,0,0,0,0,0,0,0,
Iteration 2 : 12.2,23.7,65.3,0,0,0,0,0,0,0,
Iteration 3 : 12.2,23.7,65.3,0,0,0,0,0,0,0,
Iteration 4 : 12.2,23.7,65.3,15.9,0,0,0,0,0,0,
Iteration 5 : 12.2,23.7,65.3,15.9,10.1,0,0,0,0,0,
Iteration 6 : 12.2,23.7,65.3,15.9,10.1,11.6,0,0,0,0,
Iteration 7 : 12.2,23.7,65.3,15.9,10.1,11.6,78.9,0,0,0,
Iteration 8 : 12.2,23.7,65.3,15.9,10.1,11.6,78.9,98.2,0,0,
Iteration 9 : 12.2,23.7,65.3,15.9,10.1,11.6,78.9,98.2,68.6,90.1,

Current output:
Iteration 0 : 85.0,0,0,0,0,0,0,0,0,0,
Iteration 1 : 28.0,28.0,0,0,0,0,0,0,0,0,
Iteration 2 : 36.0,36.0,36.0,0,0,0,0,0,0,0,
Iteration 3 : 70.0,70.0,70.0,70.0,0,0,0,0,0,0,
Iteration 4 : 56.0,56.0,56.0,56.0,56.0,0,0,0,0,0,
Iteration 5 : 74.0,74.0,74.0,74.0,74.0,74.0,0,0,0,0,
Iteration 6 : 94.0,94.0,94.0,94.0,94.0,94.0,94.0,0,0,0,
Iteration 7 : 94.0,94.0,94.0,94.0,94.0,94.0,94.0,94.0,0,0,
Iteration 8 : 26.0,26.0,26.0,26.0,26.0,26.0,26.0,26.0,26.0,0,
Iteration 9 : 71.0,71.0,71.0,71.0,71.0,71.0,71.0,71.0,71.0,71.0,

From the result above, I can conclude that if I update the array value incrementally, it just overwrites the other element in the array.
So, How can I have my expected output?

C/C++ Arrays don't work the way you are used from scripting languages.
Your
char* response[] = {"0","0","0","0","0","0","0","0","0","0"};

allocates a consecutive space in memory with the lenght of 20 bytes.
So you have 10 pointers that point to static memory.
In your loop you have a array of char assign[5] that gets assigned to every single of those pointers with response[idxUpd]  = assign;. You copy pointers and not values here. So the only value you really have is that in your assign variable. So as you update the pointes of the array, you get the results you see.

I thought the pointer is char *response not char* response :D. Now I know why sizeof(response) returns 20.


text:
Firmware update for remote situations
We are currently deploying units with the ATMEGA328 chip. Currently, all ICs have been flashed using the Arduino IDE. Upon release, we would like to offer updating of firmware in some cases, but obviously we would not want to send them the source code and let them download the arduino IDE.
We would like to send a firmware file, and an .exe file like a firmware upgrader, as most companies do. How would I start to go about this?

Send them avrdude (including the config file) and the hex file. Look at the commands the IDE runs to see the right command format. You can then put that into a batch file if you like.


text:
Making servo spin and able to detect angle
After researching other posts I can see how to make a servo spin continually and remove the ability to set to a specific angle.
What I'm trying to do is make a small project that has a spinning 'game wheel', each segment of the wheel has a prize on it (think almost wheel of fortune). The catch is when someone has landed on a prize once it cannot be landed on again so I want to manipulate the spin slightly so it doesn't stop on the same prize. Do do this I need to be able to get the spin AND know where the needle is pointing.
Is there a component that will allow both a full rotation AND the ability to control the location of the needle at the same time? I suspect servos can do one, or the either but not both.

I think you should look into stepper motors

Look into 'optical encoders'

The way I'd do it is the following:

use an optical encoder with an endstop, they come @ 1€ on ebay, bought 4 today :-) - this will tell you the angular speed and incremental position
use a photo transistor to detect a specific point on the wheel (make a small hole or paint a spot in a different colour) - this will give you
the absolute position of the wheel, to calibrate the previous step.

With this solution you do not even need a step motor, a DC motor will do it and probably has better characteristics, for the same cost.
So you could explore the DC option if it turns out that the stepper is not good enough.

As for Me the Best Way to To Use a Position Servo with the Feedback in it ( it comes with 6 wire ) then You put all Your Positions For the prizes in An Array and if Anytime You Land on An Index then You Should but it in an Array that Holds all the prizes angle visited Which you will use as a check Before Turning the Servo

Darkclaude X, please edit your question to get rid of all those capitalization errors.


text:
Any explanation for this behavior?
For the below code snippet
const char* fr_fbdb(char tag[30]) // fn for retrieving data
{
  char full_path[120];
  const char *_dt ;
  strcpy(full_path , base_path);
  strcat(full_path , tag);
  Serial.print( "retrieving from " );
  Serial.println(full_path) ;
  Firebase.get(firebaseData, full_path);
  _dt = firebaseData.cstrData();
//  Serial.print("while ext: ");
//  Serial.println(_dt);
  return _dt ;
}

void retreive_sch()
{
  int no_tag = strlen(*tag) ;
  //Serial.print("no. of tags in the DB: ");
  //Serial.println(no_tag);
  const char *_data[no_tag];

  Firebase.get(firebaseData, "/SCHEDULE DETAILS/SELECTED");
  sch_no = firebaseData.cstrData();

  Serial.print("extracting schedule");
  Serial.println(sch_no);

  strcat(base_path , sch_no); // base path w/ sch no.

  for (int i = 0 ; i < 6 ; i++)
  {
    _data[i] = fr_fbdb(tag[i]);
    Serial.print("while ext: ");
    Serial.println(_data[i]);

  }

  for(int i=0 ; i<6 ; i++)
  {
    Serial.print("after extraction:");
    Serial.println(_data[i]) ;
  }
}

This is the output:
retrieving  schedule changes -- setup
extracting schedule3
retrieving from /SCHEDULE DETAILS/SCHEDULE3/DATE
while ext: [1609612200000,\"inf\"]
retrieving from /SCHEDULE DETAILS/SCHEDULE3/FREQ FR
while ext: \"-2\"
retrieving from /SCHEDULE DETAILS/SCHEDULE3/FREQ TO
while ext: \"-2\"
retrieving from /SCHEDULE DETAILS/SCHEDULE3/WEIGHT
while ext: 29
retrieving from /SCHEDULE DETAILS/SCHEDULE3/TIME
while ext: \"6:30\"
retrieving from /SCHEDULE DETAILS/SCHEDULE3/frequency
while ext: \"-1\"
after extraction:"root":[]
after extraction:\"-1\"
after extraction:keep-alive
after extraction:\"-1\"
after extraction:"root":[]
after extraction:\"-1\"

As you can see, the output of the same variable _data[] inside that particular function changes.
Any idea why?

I would suggest you pick up a book about C++ and understand how to use const and what happen and the scope of a locally declare variable within a function.

_data is a global var & both set of print statements are within the same Fn. I hv used const char* fr_fbdb bcos firebaseData.cstrData() returns a c-string. Here's how I thought the flow was going to be: I call retrieve_sch() in the setup() . Then I get no. of tags from strlen(*tag) (tag holds strings such as DATE , WEIGHT, etc.). Then using a for loop that calls fr_fbdb() n no. of times get the req. tags. I also print the value that was retrieved here and in the for loop below. Pls point out where there might be flaws.

_dt is a locally declared variable, its scope remain local and when a call is return from the function, whatever stored in the _dt could be free up and the memory could be override.

"_data" has the value that is returned by the function fr_fbdb() which is confirmed by the print statements in the 1st for loop of retreive_sch() . In the second for loop of retreive_sch() the same var, _data gives different values. My claim is, if there was a pblm (bcos of scope of variables), then it should have been shown in the first print statement. (In case you haven't noticed, I've commented the print statements in fr_fbdb())

The problem is these lines of code in your function fr_fddb():
  Firebase.get(firebaseData, full_path);
  _dt = firebaseData.cstrData();

You didn't share enough code to make this clear, but firebaseData appears to be a global which you reuse. When you call its .cstrData() method you're getting a pointer to the same buffer each time, and that buffer is overwritten each time you call Firebase.get().
You can verify this by printing the pointer value each time through, like so in your retrieve_sch() function:
  for (int i = 0 ; i < 6 ; i++)
  {
    _data[i] = fr_fbdb(tag[i]);
    Serial.print("while ext: ");
    Serial.println(_data[i]);
    Serial.printf("_data[i] pointer %p\n", _data[i]);
  }

You'll likely see that the 6 pointers are identical. The value is changing because you keep reusing the same string.
The easy fix is:
  Firebase.get(firebaseData, full_path);
  _dt = strdup(firebaseData.cstrData());

This allocates memory and stores in it a duplicate of the string that was fetched from Firebase. Your function will now return that and firebaseData can safely be reused.
This solution will require you to free that memory at some point when you're doing using it by calling free(_dt); or whatever you're holding the pointer in when you're done. I leave that as an exercise for you.

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


text:
how to use the decoded raw value to send IR signal in arduino
I am IR library from Ken Shirrif at https://github.com/z3t0/Arduino-IRremote/releases/download/MAJOR/IRremote.zip
It is good and I have used the examples to receive and send and to playback IR signals from the library. And they are working good.
To send Unknown signals we should use sendRaw() method with a list of integers got from the receiver.
My question is when I use the receive program, I get the decoded hexadecimal value for even the Unknown signals. And can I use this small decoded signal to send signals apart from the long list of integers.
I am trying to send these codes from android. It would be quite easy to send and store the small hexadecimal decoded value.
Is there a way to use the decoded value to send for raw signals with some encodings at arduino?

You'd have to find out the proper protocol used. Most often used is NEC. Apart from that, you question has to little information. As it sound like you are controlling both the sending and receiving side, which makes it pointless to use an unknown protocol.

The library recognises NEC, Sony and some other protocols if you could look at the IRrecorder file in the library. And it gives Decoded signals for recognised protocols and for unknown protocols(protocols it don't know) it just gives a list of integers. It can duplicate the signal I give from my remote and to the IR transmitter I have connected to my arduino. I want to know how to converted the integers into decoded format like the Protocols recognised by the library. @Gerben

You'll have to figure out the protocol, and extend the IRremote library to include this protocol, like Jefferson said. You could try adding some of the raw codes to your question and see if anyone is willing to decode if for you. I'd also be helpful to know what the remote you used is for.

If the signal is reported as "unknown" the library couldn't identify the protocol (RC5, RC6, NEC, SONY, etc).  If the library doesn't know the protocol,  the decoded number is meaningless. Simply put, an IR remote transmission has a frequency; a header; some data (the actual remote command); and a footer.  Without knowing the protocol the library doesn't know the length and shape of each section, so the purpose of the decoded number is only to show quickly if the decoding is receiving the same code at each keypress. You can verify this yourself.  Every time something makes an already known remote code be reported as "unknown", the code received is different from a real code, so simply guessing (or knowing beforehand) the protocol is not going to help anyway.

The library recognises NEC, Sony and some other protocols if you could look at the IRrecorder file in the library. And it gives Decoded signals for recognised protocols and for unknown protocols(protocols it don't know) it just gives a list of integers. It can duplicate the signal I give from my remote and to the IR transmitter I have connected to my arduino. I want to know how to converted the integers into decoded format like the Protocols recognised by the library. @Jefferson Ryan

@abdul rahuman, that is the role of recognizing the protocol. In order to achieve what you want, you need to analyze the list of integers to learn how the protocol works, write your own protocol functions for the library and output your commands using these functions.

The list of integers the library shows to you is just a representation of the ON-OFF duration of the remote pulses so with patience or a suitable software you can draw graphics of the received streams and by comparing the graphics of a good number of commands you can usually understand how the protocol works. This is not easy, but if it would, the library could automatically "learn" unknown protocols for you. Sorry for any mistake, but English is not my first language.

Thank you for your comment Jefferson. I would try to do it.

As a side note, I learnt the bad way that sometimes the library is unable to understand the protocol because you are using an unsuitable receiver. For example, the library is unable to recognize 40bit commands (XBOX and some sattelite TV remotes) with some old receivers.

If you are going to reverse engineer your remote protocol, some tips: it is very important to understand the most common protocols first. For example, the Samsung protocol is just a little header pulse duration different from the NEC protocol. And air condittioning remote protocols can be very hard to decipher.

I am not an expect in the field. I am just trying to make and Ir signal duplicater to duplicate the given signals. Could you suggest an easy way for that?

The only easy way I know is to use the Send Raw function

Yeah. You see the send raw function. It's first parameter is a list of integers. I want it in a hex code format like the known protocols. Is it possible?


text:
Is there something I can use to control Arduinos easily over Ethernet with .NET?
I'm wondering if there's anything out there that maybe works pretty similarly to Firmata, runs on Unos or Megas, and can be controlled over Ethernet. I am writing a home automation system with .NET, and I see some options for supporting Firmata with .NET, but I want to be able to connect my devices over Ethernet.

I don't use .net but I have done this using php website to control a door lock over ethernet.
My solution was to use the ethernet to recieve commands and be able to use them on the arduino through http calls. And when it was done send a http call back to the server with some data. I was doing a door lock program for example. Please ignore anything talking about doors, locking, unlocking, or other requirements to certain calls, I am just providing examples about how it COULD be used, not that you need to include my door lock code in your project to get it to work.
As far as how that works out with .net that's up to you, however I can give you a hand getting your messages back and forth.
first you want to create the ethernet connection to your router. put this in your header section.
#include <UIPEthernet.h>
// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(127, 0, 0, 1);

// initialize the library instance:
EthernetClient client;

char server[] = "www.example.com";
//IPAddress server(127,0,0,1);  // numeric IP for www.example.com (no DNS)

int waitTime = 3L;

unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
const unsigned long postingInterval = waitTime * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

throw this in your main loop so it doesn't constantly make http requests spamming a server.
// if ten seconds have passed since your last connection,
// then connect again and send data:
if (millis() - lastConnectionTime > postingInterval || buttonState == 0) {
  httpRequest();
}

Create a method to handle httpRequest because shoving everything under the main is kinda sloppy.
Alright so there will be quite a bit here because http headers are kinda lengthy.
// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();
  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
  Serial.println("String is " + readString);
  if(readString == "Ready" || readString == ""){
    client.println("GET /command.txt HTTP/1.1");
    where = "web";
    waitTime = 5L;
  }
  else{
    // here is the basic format of sending a get command
    //this specific request is so that I can tell where the command came from. I had a web client / mobile app that could control the door AND you could also control it from a physical buttom. The door would have to reply either way to the web server (READ: .net application) in order to have the correct status always show up on the web end.

    client.print("GET /update.php?where=Arduino&command=Ready&status=");
    if(readString == "Reset"){
      client.print("Reset");
    }
    else if(isLocked){
      client.print("Locked");
    }
    else{
      client.print("Unlocked");
    }
    client.println(" HTTP/1.1");
    waitTime = 1L;
  }
  client.println("Host: www.example.com");
  client.println("User-Agent: arduino-ethernet");
  client.println("Connection: close");
  client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

TL;DR if you wanna use ethernet you need to use all of ethernet.
Start by creating your connection to the router statically (watch for conflicts).
Then create a method of watching for incoming data or waiting for a command if there isn't one. (server call).
Then create A FULL HTTP REQUEST in order to pass your request through. Shorting any parts of this last part and you will either end up with bad request errors or will simply fail.
Let me know if you need anything else or if this was useful to you!

Having to run a web server might be a bit of an uncomfortable requirement for how I'm coding this application. It's a VB .NET console application effectively (currently it has a form, but I'm going to get rid of it), and since I'm going to control various devices, including a few direct serial, and a few various Ethernet devices likely, I don't want to have it serve web just to control Arduinos.

I was hoping for something a bit lighter on the server. I almost recall some examples where the actual "web server" bit was on the Arduino, which might be a more elegant solution, in terms of my automation controller just needing to make HTTP requests that way.
I had just been hoping there might be something a bit more pre-packaged and already out there I didn't know about.

You don't have to. You asked about how to use ethernet to send data. You can pass php to a single local page on a local computer. Have that write the data to a text file and have your vba program pick that up. How did you think ethernet worked?

Also using arduino as a web server is very Ill advised

But doesn't that single local page need some sort of web server on the PC to serve it up so it's reachable by the Arduino? What's the reason for ill-advisement on using the Arduino as a web server for similarly minimal commands?

Yes, I guess it does. It was a long night mb. You're welcome to try it but I had performance issues and it wasn't stable. Came down to space and flexibility. There are light weight servers out there so you don't have to run full blown apache if you don't want to.

Poor stability would definitely be an issue for me. I do have like Megas I can work with, which I'd hope would handle the added load okay. (Megas are $10 now at a local store.)

Do what you want man. I've been working on these for a year. Up to you how to solve your problems. Some answers are easier than others


text:
Trinket: Battery + USB at the same time?
Is it allowed to have battery and USB connected to the Trinket(3.3V) at the same time?
I am using the battery to also power other components, so always disconnecting power, hooking USB to re-program and vice-versa is quite time consuming (and I fear to ruin the connectors).

From https://learn.adafruit.com/system/assets/assets/000/010/773/original/adafruit_products_trinket3.png?1378223258 it looks OK -- there are blocking diodes D3 and D2 that prevent backfeeding either the battery or the USB +5.
If you are worried, or want to monitor battery-only performance, you could make a special USB cable with the +5 red wire disconnected, and rely on the in-circuit battery to power the device, while still using the USB data lines.  See https://www.pjrc.com/teensy/external_power.html Option 2 for an example of the cable surgery.

So that worked. Unfortunately I did not really achieve my goal entirely as the ATTiny on the trinket seems only to enter the bootloader when the controller is powerless and the USB-connection to it is made. Not after a Reset. So back to square 1 :-)


text:
Is the Uno Vin pin protected by the voltage regulator?
I guess it's all in the title. When using Vin as input, does it go through voltage regulator, or must I feed it precisely 5V?

If you look at the schematic you'll see Vin is connected to the input of the voltage regulator. Just like the barrel-jack (except for the diode).
So the same input-voltage of    7-12V applies to Vin.

Actually because of the lack of the diode the lower bound for the input voltage is slightly lower. I am not sure on the specs of the diode they use, but it could be as low as 6.3v.

@Majenko the limit is 6-20V (according to the website), so it could be even lower.

when you connect you regulated 5V at Vin port your 5V output will be lower than 5V as it have to pass through the 5V regulator. The input voltage should range from 7-12V.


text:
Set avrdude transfer baud rate in Arduino IDE
I just got an Arduino nano (from arduino.cc, not a knock-off), and have issues uploading sketches. It refuses to upload, with the error message "programmer is not responding".
Some searching led to an incorrect transfer baud rate. Indeed, the IDE (1.8.5) output before uploading displays "overriding baud rate: 57600", and the command line has a -b57600 argument. By copying this command in a terminal and removing this parameter, the upload works. It also works with -b115200. All other values I tried do not work.
Is there a way to configure the IDE to use the correct baud rate ? I know I could use the command line, but that's not very practical, I would prefer to keep the Integrated part of the IDE :).

Update the boards package for the AVR hardware. That will give you new options in the tools menu.
Then you should just select the right CPU variant.

From top to bottom those are 115200, 57600 and 19200 baud.


text:
Looking for a Mega 2650 drawing or picture that shows the components labeled
I am Looking for a Mega 2650 drawing or picture that shows the components labeled.
I've seen the schematics but didn't find a labeled assembly drawing yet.  Should this exist?
Thanks

Yes, it exists, but not (commonly) as an "image" in the traditional sense.
You need to install Eagle PCB design software and open the PCB file downloadable from the Arduino site from where you can see exactly which component is where.

Hi thanks for responding.  I got Eagle installed and downloaded the files from the arduino website.  Thanks. It would still be nice to have a labeled picture to easily tell what the components are.


text:
Controlling HC-05 from a sketch
Hi I am making a sketch and circuit with a HC-05 BT receiver to upload sketches via Bluetooth to my Uno.  This requires giving AT commands from the sketch.  I would like to see the response from the HC-05 but so far I haven't got it to work.  I want to view the response via the standard serial connection and serial monitor.  The commands from the sketch are not being recognized by the HC-05 and I would like to see the HC-05 response to troubleshoot it.
If you have a minute would you mind giving me a tip?  I would greatly appreciate it.  See the ArdProgramModeOn() and Off functions at the end.
Thanks

int ATModePin = 2;  // pin for HC-05 AT comand mode
int HC05powerPin = 3;  // pin for powering HC-05 when high
char btserialrx;  // data through from bt connection
char myChar; // data through serial port connection
#define rxPin 8 // HC-05 bt serial pin
#define txPin 9 // HC-05 bt serial pin

#include <SoftwareSerial.h>
SoftwareSerial btSerial(rxPin, txPin); // RX, TX

void setup() {
  pinMode(ATModePin, OUTPUT);
  pinMode(HC05powerPin, OUTPUT);
  pinMode(5, OUTPUT);
  Serial.begin(9600);
  btSerial.begin(115200);

  digitalWrite(HC05powerPin, HIGH);
  delay(2000);
  }

void loop() {

  while (btSerial.available()) {
    btserialrx = btSerial.read();
  }

  if(btserialrx == '1'){  // change to upload / reset mode
    Serial.println("switching to upload mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
  else if (btserialrx == '2'){  // change to normal mode
    Serial.println("switching to normal mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
}

void ATModeOn(){  // reset HC-05 and change HC-05 to AT Command Mode
  digitalWrite(5, HIGH);
  digitalWrite(ATModePin, HIGH); // AT command mode on upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ATModeOff(){  // reset HC-05 and return HC-05 to std. operation
  digitalWrite(5, LOW);
  digitalWrite(ATModePin, LOW); // AT command mode off upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ArdProgramModeOn(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,0");  // Arduino reset mode upon HC-05 connection for programming
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    Serial.print(myChar);
  }
  delay(4000);
}

void ArdProgramModeOff(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,1");  // Arduino normal mode no reset upon HC-05 conection
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    Serial.print(myChar);
  }
  delay(4000);
}

Unless you've manually set the btSerial speed, you need to be at the default for AT commands which is 38400 -> btSerial.begin(38400);
If you want to read regular Serial communication, you'll need to monitor 9600 -> btSerial.begin(9600);
If you are unable to to send commands, I feel as if you wouldn't have changed the default speeds.
I used this link as a reference with my project: Modify The HC-05 Bluetooth Module Defaults Using AT Commands
Lastly, you didn't mention whether or not you soldered a jumper wire to PIN 32 for your ArdProgramOff/On. Another reference for you as well: DIY Arduino Bluetooth Programming Shield
Hope my answer helps! Good luck!

Thanks for responding.  The Make article is the one I followed to make the setup.  I have wires soldered to the HC-05 32 and 34 pins for the reset signal and AT command mode.  I pre--programmed HC-05 from the serial monitor to operate at 115200 baud to be able to upload to the Uno.  In the example pages you sent the HC-05 and serial monitor are communicating at different baud rates but I guess a buffer handles that difference?  Thanks.

Basically I'm wondering about the While loops to monitor serial received from the HC-05.  I have one at the start of the loop, and then one in both functions (ArdProgramMode...) where I am sending commands to the HC-05 from the Uno sketch.  Do you see a conflict in the code here, should this code design work correctly?  Thanks.


text:
Can the servo pulse width range be changed?
I recently found that standard servos only rotate 90deg total rotation for a pulse width range of 1-2 usec.  To rotate 180deg total rotation they need a .5-2.5 usec pulse range.  The arduino is programmed to only output the 1-2 usec range for 0-180 deg rotation.  Is there a way to make the arduino output the .5-2.5 usec pulse range to get full 180deg rotation?
Thanks

The Servo Attach method has two forms,
servo.attach(pin)
servo.attach(pin, min, max)

In the latter form, you can specify values for the min and max microseconds that servo.write() will use to represent 0° and 180° respectively.
Note, default values are 544 μs and 2400 μs, which is not so different than the range you say you want, so perhaps some other problem is afflicting your setup.
Also, as explained in my answer to question  “Change Servo Speed With RedBearLabs BLE Shield”, you can issue servo.write(value) calls with value in microseconds instead of in degrees, which may allow more precise control.

Thanks for responding to my post.  I thought I read somewhere that the Arduino outputs only the 1000usec to 2000usec pulse range, but I see from testing it that the standard range is as you say it is.  When you go to buy a servo, most that I've found say they only turn 90 deg, but can turn 180 deg. if you supply the greater pulse range of 500 usec to 2500 usec.  Hitec has a "180 deg. rotation" option that costs $10 but I think its not needed, the Arduino already can output the extended pulse range.  Hitec shows that standard RC servo controllers only output the smaller pulse range.


text:
Multiple Arduino Uno Slaves
I am working on an Arduino project where I need more digital and analofgpins than the Uno offers. I was wondering how to hook up multiple Arduinos (4) together so I can use their digital and analog pins. Thanks in advance.

http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem

I suggest using a single Arduino Mega.  It offers 54 digital I/O and 16 analogue inputs.
I suppose you could also use I2C or SPI to communicate between multiple Uno's.

Ryan Griggs' suggestion of the Mega is likely to be easier and more economical than using multiple Unos. That said can you say more about what you want to do with your proposed design? There are good reasons for distributing the load and the problems are interesting – so it is not obvious that the "right" answer is just to use a bigger central machine.
Besides tightly coupling them with the SPI or I2C you could also consider using Ethernet or Bluetooth. Arduino Ethernet shields tend to be expensive, but there are some wireless devices like the Adafruit Huzzah that are more economical.
You may find this post on I2C by Nick Gammon helpful. There is a similar example in this question.

I can only use Uno's for the project so that is why... I am using them to read multiple voltages