text:
How to setup OpenCV with Arduino?
My question is how to do it (set it up), not if I can do it or with what Arduino.
I've previously setup OpenCV with Visual Studio 2015. It was a tough one, but I made it through. Now I want to set it up so that it would work with the Arduino and its IDE.
How should I proceed? Is there any specific things to do?
My setup:

Windows 7
Arduino IDE 1.8.1
OpenCV 3.1

Which Arduino? It's unlikely the AVR-based ones will have the resources to run this library. Not sure about the ARM-based units.

I wanted to use an Pro Mini, but I'll upgrade if necessary.

Not a chance. Maybe on a Raspberry Pi, but never an Arduino - unless it's one of these strange Intel things that are being marketed as Arduino these days. Basically you need an OS (Linux) to run OpenCV - something a real Arduino will never ever run.

If you are thinking of using OpenCV with a "normal" Arduino, such as the Uno or Mega, then think again. OpenCV runs on a computer - be that a desktop computer or an embedded computer. Basically you need an operating system; "normal" Arduinos don't have an operating system.
It may be possible to run OpenCV on an Arduino that runs Linux (some of the strange Intel things that are being marketed as Arduino do, as does the Yún), but in that case you will be writing a Linux application, not working in the Arduino IDE. You would need to treat it as a normal Linux computer and use the normal Linux tools for developing on it (note that OpenWRT that the Yún runs is tricky to develop for - the best way is to cross-compile on a real computer running Linux using the OpenWRT "Buildroot" system).

As some people said before, you just can't run OpenCV on Arduino.
but, you can use Arduino/Raspberry Pi to capture information and send it to a server for analysis. For example, Azure, Bluemix or your main computer.
In your case, I would use Raspberry Pi + camera to capture images/videos.
then, send it through Wi-Fi to a server. Then, on the server, process all images using OpenCV.


text:
LED doesn't register as LOW after a switch has cut all power to it
I have the following build:

And the following code:
const int buttonPin = 3;
const int ledPin = 2;
int buttonState = 0;

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

  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  while (digitalRead(ledPin) != LOW){
    buttonState = digitalRead(buttonPin);

    if (buttonState == LOW){
      digitalWrite(ledPin, LOW);
    }
  }
}

But it doesn't seem like anything is registered, as my program doesn't respond to the shut down of the LED. What have I done wrong?

Please post an actual schematic. Why do you have constants like buttonPin and ledPin and then ignore them and have pinMode(2, INPUT); and pinMode(3, OUTPUT);?

I've tried to post an actual schematic now + changed the code

On what did you base your wiring? I think/see that there are multiple wiring issues.

Try again. R1 (at the top) doesn't seem to be connected to anything. And as for the switch, is it supposed to short out the LED?

Yes, it's supposed to turn it off

These things are called "circuits" for a reason. The electrons go around in a circuit. You only have one wire to the Arduino so it is hard to see how anything happens.

Modified the build, take a look again, please. I still don't register anything though when the LED gets shut down by the switch

Looking at your schematic, I get a bit confused.
You should start out with creating the schematic, try to base it on existing schematics on the web/tutorials.
I believe you're trying to read out a button and set an led accordingly?
So start out with the schematic and then try to build a breadboard setup for this. Randomly wiring things up on your breadboard doesn't really make sense, you need a plan.
I've created a shematic of which I believe should work a treat.

simulate this circuit – Schematic created using CircuitLab
Using internal pull-ups on the SW1, to avoid the input floating.
Using 220ohms resistor, based on "Basic Red 5mm - Sparkfun LED", 5V source, 2V forward 16mA (http://led.linear1.org/1led.wiz).
Be carefull not to set the SW1 as an output (high) and push the button, this theoretically burns out the I/O pin.
But even then, this is only basic, you may want to consider input protection (http://www.thebox.myzen.co.uk/Tutorial/Protection.html)
It's very easy to mess something up or do something incorrectly in electrical engineering. To be honest, it may help to watch a lot of tutorials or read books on electronics. It's very usefull to have a basic understanding before wiring things up.
At least base your actions on a (good) tutorial or reference material from Arduino self.
Try to wire up the circuit according to my schematics
Mouseover for example (but please try it yourself before checking!)

The same actually counts for programming, first try to make it clear what you want to achieve. Maybe even write out the steps that your program should do on a functional level.
I have no idea how you program could actually compile, the while and if statements don't have any closing brackets.
const int buttonPin = 2;//I switched the LED and button in my design.
const int ledPin = 3;//So the LED is on a PWM pin, which makes more sense.

void setup() {
  //Serial.begin(9600); //We're not using serial, so why start serial?
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}

void loop() {
   int value = digitalRead(buttonPin);
   digitalWrite(ledPin, value);
   //or digitalWrite(ledPin,digitalRead(buttonPin));//for short
}

Thank you for this elaborate answer ... Seems like I made everything more difficult, hah. Sorry everyone. Anyway, I forgot to add the closing brackets, I've added them now.

@andrew no point, starting out with something can be hard/confusing. That's why it helps to read some tutorials, they often include wiring diagrams (and sometimes pictures) and put the code in the end, so you can verify if it's working.

Indeed, thanks. I have a question though, why does it make more sense to put the LED on a PWM pin?

Ah, pwm can be used to dim the LED, it's nothing critical, but it's nice to have such a feature.

Alright, I'll keep that in mind. Thanks for all the help, doesn't seem like my badly-formulated question deserves an answer.

The diagram is open to several different interpretations, depending on what's inside the four-terminal switch.  On many such SPST switches, two adjacent terminals are connected to each other inside it, and the other two likewise.  Which are which in the diagram isn't indicated.
That aside, what is clear from the diagram is that pin 2 is connected by wires to +5V, and will always read in as high.

Edit 1:
The schematic [posted later] is unclear.  It should be arranged so that solid lines represent wires or pins, with solid lines between things that are connected.  Place items in the drawing to reduce unnecessary and confusing crossing lines.  For example, supposing that the dashed line from pin 2 of R1 represents a wire between pin 2 of R1 and pin 2 of LED1, it is unclear whether the wire bends around the top right pin of S1 (can't read number) or connects with that pin on its way to LED1.  For another example, nothing is shown connecting to pin 1 of R1, and only one long dashed line connects the R1/S1/LED1 group to the Uno.

Please take another look, I added a new diagram.

I don't get a plausible understanding of the wiring from either the diagram or the schematic.  Also see edit 1.

Sorry ... I'm new at this. Pin3 is connected to the LED. It is the crooked wire. Pin2 is connected to the switch. It is wire no. 2 from the left. The first wire from the left connects the resistor to the switch

source: Stack Exchange

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

sort: votes


text:
Serial Communication Issue with Telit LE910 LTE Modem
I have a project that uses a Telit LE910 4G LTE Modem to allow me some basic monitoring via SMS and HTTP POST to Exosite.
I can connect to a Exosite server with and send a successful HTTP GET request to pull a UNIX timestamp (as a test).
Problem
The problem lies with receiving.  The information received cuts off halfway through the HTTP headers, before reaching the body of the information.
This image shows what prints out on the Serial monitor:

This image shows what the expected result should be:

And this image shows the code the executes to send the request:

The result is the same with PrintModemResponse() and with GetModemResponse().  Additionally, I have the same issue with receiving SMS messages.  The data appears to cut off partway through the expected response.  The modem serial (SW_Serial) baud rate is set to 115200.
Question
Am I doing something wrong with reading the Serial information from the modem?  Am I hitting a timeout of some sort?

First, please don't post screen images.  Just select the text and paste it into your questions.  You can copy code from the editor or messages from the Serial Monitor window.  Paste into your post, select the section again, and press ctrl-K to format it as a code block in your question (like below).

Am I doing something wrong with reading the Serial information from the modem?

Yes, you are using delay to "wait" for the response to appear.

Am I hitting a timeout of some sort?

In a way.  The input buffer only has room for 64 characters.  If you don't read any of them because you're blocked at a delay statement, the 65th character (and all others) will be ignored.  These answer your specific questions.

Further Suggestions:
To fix the real problem, not just the symptoms, you will have to change your sketch structure.
There are many ways to implement this in a non-blocking way (i.e., without using delay).  I prefer Finite-state Machines; there are many good tutorials for this  technique (e.g., Nick Gammon's site).
Although it's not as flexible, you could also use your own while loop for each response, with a timeout.  Here's a simple example that reads one line.
char resp[20];
char resp_Len = 0;
const uint32_t TIMEOUT_MS = 5000UL; // 5 seconds

AltSoftSerial modem_port; // pins 8 & 9 ONLY

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

void loop()
{
  uint32_t startTime = millis();
  while (millis() - startTime < TIMEOUT_MS) {
    if (modem_port.available()) {
      char c = modem_port.read();
      if (c == '\n') {
        resp[ respLen ] = '\0'; // NUL terminate
        respLen = 0; // reset for another line
        break;

      } else if (respLen < sizeof(resp)-1) { // Room for more?
        resp[ respLen++ ] = c; // accumulate one more character
      }
    }
  }

  Serial.print( F("Response = '") ); // F macro saves RAM
  Serial.print( resp );
  Serial.println( '\'' );
}

But when the response is long (hundreds of bytes), you may not have sufficient RAM to save the whole response, and then parse it.  You MUST use an FSM to parse the bytes as they are received.
For your application, you should skip all the stuff at the front and watch for the "Content-type:" pattern and the two newlines, then save the next line (as above) for parsing:
enum state_t { SKIP_TO_CONTENT_TYPE, SKIP_TO_EMPTY_LINE, SAVING_TIMESTAMP };
state_t state = SKIPPING
uint8_t index = 0;

const char ContentType[] = "Content_type:";

bool watchForTimestamp()
{
  if (modem_port.available()) {
    char c = modem_port.read();

    // Handle this one character, based on our current "state"

    switch (state) {
      case SKIP_TO_CONTENT_TYPE:
        if (c == '\n')
          index = 0;

        else if ((index < sizeof(ContentType) && (c == ContentType[ index ])) {
          // next char matches
          index++;

          if (index == sizeof(ContentType)) {
            // All matched!
            state = SKIP_TO_EMPTY_LINE;
            index = 0;
          }
        }
        break;

      case SKIP_TO_EMPTY_LINE:
        if (c == '\n') {
          index++; // this counts newlines since "Content-type:"

          if (index == 2) {
            state = SAVING_TIMESTAMP;
            index = 0;
          }
        }
        break;

      case SAVING_TIMESTAMP:
            ... Hint: something like the line-saving technique above.
        if (something) {
          return true;
        }
        break;
    }
  }

  return false;
}

Some part of loop will just call waitForTimestamp over and over:
void loop()
{
    ...

  bool gotResponse = false;
  state = SKIP_TO_CONTENT_TYPE;

  while (millis() - startTime < TIMESTAMP_TIMEOUT) {
    gotResponse = waitForTimeStamp();
    if (gotResponse) {
      // parse the timestamp from the resp array
         ...
      break;
    }
  }

  if (gotResponse) {
    Serial.print( F("Timestamp = ") );
    Serial.print( resp );
    // now you can parse the small response array
       ...

  } else {
    Serial.println( F("Didn't receive timestamp!") );
     ... other error code
  }
}

This may be a "main" FSM for loop, with a nested FSM for parsing the HTTP response.  The rest is up to you.  :)
BTW, SoftwareSerial is very inefficient.  It cannot send and receive at the same time, and it disables interrupts for long periods of time.
If you can use pins 8 & 9, you should use AltSoftSerial instead.  It is very efficient.
If you can't switch to those pins, you could use NeoSWSerial if the modem is running at 9600, 19200 or 38400.

Thank you for your response.  I will do some research into FSM and your suggestions and attempt to incorporate them.  I guess the trick will be in the loop, catching the response before it fills the buffer.
Just for clarification, I am using a hardware UART for the modem (defined as SW_Serial, SW for Skywire) at 115200 baud.  Thank you for the suggestion of AltSoftSerial though, may come in handy for other projects.

At the modem's default baud rate of 115200, I found I needed to check SW_Serial for data so frequently that it was basically blocking code in and of itself.  I found two alternatives:  The first is to implement flow control, which I have not done but may look into should the need arise.  The second was easier for me, and it was to just modify the HardwareSerial.h header file and up the buffer to 256 bytes.  This should be more than enough for my purposes.

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


text:
How do I stop 5v on the I2C port of a pro mini so I can use 3.3v devices?
The theory is that you can use 3.3v I2C devices from a 5v device as long as the pull ups are only to the 3.3v. I have a 5v pro mini connected to a bmp180 board which has a 3.3v regulator but no level shifters. It is working and giving me data but I am hoping I can get better quality measurements. One observation is the power rail on the BMP board after the 3.3v regulator is being pulled towards 5v. On the scope this looks to happen between i2c messages. I am using the "Adafruit-BMP085-Library" which is in turn using "Wire". In the wire library there is a comment that says that the writedigital() of 1 to the port is setting the pull ups.
Does anyone have any general advice on this issue?
What does the comment about setting the pull-ups mean? How is that function setting the pull ups?
When does the I2C switch back to being an GPIO? Are the lines being pulled high between messages because it is reverting to an GPIO?

This page explains the problem and offers some solutions. http://www.varesano.net/blog/fabio/how-disable-internal-arduino-atmega-pullups-sda-and-scl-i2c-bus

Your question is unclear. What is a bmp180 (I could google, but you should include a link). I²C is open drain and requires pullups. The Arduino does not have these, and they are often on the  I²C board. If these are to 3.3V OK, otherwise you have to remove, and install pullup to 3.3V. You could disable any internal pullups, which are useless, but if you use 1.8kΩ they would swamp any internal pullups.

Whoever decided it would be a good idea to default to using the Arduino internal pull-up resistors on I2C needs taking out back and giving a good kicking. It is so wrong on so many levels.
Yes, if you disable the internal pull-up resistors you can safely use 3.3v devices. The simplest way to do this is to turn them off again as soon as you have done Wire.begin(); by writing 0 to the pins with digitalWrite().

I think it has been done this way so you can just connect chips to it without having to bother with any pull-ups. But it is kind of lazy and if you want it to work in the real world then it does need to be done properly. The AdaFruit module has level shifters on it. Overkill if everything is set up OK. There is still a 5v spike. Not sure if this will cause a reliability problem later. But looks a lot better on the scope now.

@BillyBag2 Not only is it kind of lazy, but it teaches new users that you don't need pullups on an I2C bus, so they get into all sorts of trouble when they transition to a better system.


text:
How to store 1 bit Boolean data into EEPROM and retrieve this 1 bit data?
I am building a project where I have to store the digital state which is Boolean (either HIGH or LOW) of each I/O port such that after power off the state of I/O ports store in EEPROM and I can retrieve this I/O port's state after power on.
This is my code..
    #include <IRremote.h>
    #include <EEPROM.h>
    int EEPROMaddress = 0;
    int EEPROMaddress1 = 1;
    byte EEPROMbyte = EEPROM.read(EEPROMaddress);
    byte EEPROMbyte1 = EEPROM.read(EEPROMaddress1);
    int RECV_PIN = 11;
    int led = 10;//1FE50AF
    int led1 = 9;//1FED827
    boolean previousState = bitRead(EEPROM.read(EEPROMaddress), led);
    boolean previousState1 = bitRead(EEPROM.read(EEPROMaddress1), led1);
    boolean state;
    boolean state1;
    IRrecv irrecv(RECV_PIN);
    decode_results results;
    void setup()
    {
      Serial.begin(9600);
      pinMode(10,OUTPUT);
      pinMode(9,OUTPUT);
      irrecv.enableIRIn();
    }
    void loop() {
      if (irrecv.decode(&results))
      {
        Serial.println(results.value, HEX);
        switch(results.value)
        {
           case 0x1FE50AF:
           if (previousState == LOW)
           {state = HIGH;
            digitalWrite(led,state);
           previousState=state;
           bitWrite(EEPROMbyte,led,state);
           EEPROM.update(EEPROMaddress,EEPROMbyte);
           delay(50);}
           else
           {state=LOW;
           digitalWrite(led,state);
           previousState=state;
           bitWrite(EEPROMbyte,led, state);
           EEPROM.update(EEPROMaddress,EEPROMbyte);
           delay(50);
           }
           break;
            case 0x1FED827:
           if (previousState1 == LOW)
           {state1=HIGH;
           digitalWrite(led1,state1);
           previousState1=state1;
           bitWrite(EEPROMbyte1,led1, state1);
           delay(50);}
           else
           {state1=LOW;
           digitalWrite(led1,state1);
           previousState1=state1;
           bitWrite(EEPROMbyte1,led1,state1);
           delay(50);}
           break;
}
        irrecv.resume();
      }
}

Out of curiosity, how are you going to do this after power off? And if you do it before power off, the EEPROM has a limited number of writes it can do.

Are these input or output ports you want to store the state of?

In my code, the state of  each arduino's pin will change randomly within a loop and present(changed) state of each pins will store in EEPROM parallely. So that if power failure will occurs any instance of time during running this code then after power on I can get the each pin's state from EEPROM which were before shutdown.

The chip on the Uno is designed for 100,000 writes to EEPROM. That's a lot, but if you are doing it every time around a loop, you may exceed that number in a couple of minutes.

Since this is Arduino SE I'm going to do this with the Arduino functions, there are other ways of course.
Write a bit to EEPROM:
byte EEPROMbyte = EEPROM.read(EEPROMaddress);
bitWrite(EEPROMbyte, pinBit, pinState);
EEPROM.update(EEPROMaddress, EEPROMbyte);

Read a bit from EEPROM:
boolean pinState = bitRead(EEPROM.read(EEPROMaddress), pinBit);

This is for updating/reading a single bit at a time as asked. If you need to read/write multiple bits at the same time(as I'd assume you are doing after power on) then it's more efficient(and less wear on the EEPROM in the case of the write) to do all the bits at once instead of one EEPROM read/write per bit.
I assume by "I/O ports" you mean Arduino pins. If you're working directly with the PORT registers(e.g. PORTB) then you can just write or read the whole register to the EEPROM, no need to deal with the individual bits.

Thank you Sir for your great contribution. In my code, the state of  each arduino's pin will change randomly within a loop and present(changed) state of each pins will store in EEPROM parallely. So that if power failure will occurs any instance of time during running this code then after power on I can get the each pin's state from EEPROM which were before shutdown. have some doubt  which EEPROM library need to run these code which you given in your comment?

It's the EEPROM library included with the Arduino AVR Boards core but there should be a similar API for any hardware core for an MCU with EEPROM(or pseudo-EEPROM in the case of ESP8266). Which board are you using?

I am using arduino uno  board.. .after successful implication in this board I will implement it on AVR atmega 32 MCU later

You just need to add #include <EEPROM.h> to the top of the sketch and the code I wrote will work fine. The core you use for ATmega32 will probably either have the same library or reference the Arduino AVR Boards core so it will work either way. If it doesn't you can use avr-libc's avr/eeprom.h library, you just need to change EEPROM.read/EEPROM.update to eeprom_read_byte/eeprom_update_byte. Keep in mind that the ATmega328P/ATmega32's EEPROM is only rated for 100000 writes/cell so you need to do some calculations of the expected lifetime and maybe do some wear leveling.

Sir I have written my sketch as per your instruction but the memory part is not functioning.. If I make any particular ardunio's pin HIGH before power off after power on it goes to LOW but it should be HIGH.. I have Added my Ardunio's Sketch in my Post Please check it. Thank you

Each EEPROM cell is one byte. There are 8 bits per byte. You're trying to read and write from bits 10 (led) and 9 (led1). The bits are zero indexed so you need to define a bit for each pin that's between 0 and 7. If you're not running short of EEPROM memory you might consider just using a whole byte for each pin's state.

You also forgot to write the state of led1 to EEPROM in your case 0x1FED827.

Also, I don't know exactly what your intent is in your code but it seems like you would want to set the pins to the states read from EEPROM in setup().

I want to control electrical appliance its state(On/OFF) also its power by using PWM technique through IR remote.. but right now I just written the code to control appliance's State(ON/OFF) only for real time

Note that writing EEPROM is slow - on the order of milliseconds per write - which may limit the performance of your sketch.
A better technique is to provide a limited backup power supply to the MCU; enough to complete a set of EEPROM writes + a safety margin. A capacitor could possibly provide enough run time if doesn't have to power much else. Then, detect and interrupt on a failure of the main supply, immediately write your backup data to EEPROM, and enter an infinite loop to wait for the backup supply to fail. When the system resets, examine the EEPROM to be sure there is valid backup data there, restore what needs to be restored, and resume your task.
Update:
A search for "arduino backup power" finds a number of articles related to switching an Arduino from mains power to battery power when the mains fails. You would only need a very small battery if you're willing to only save necessary information then shut down until the power returns. A capacitor might keep your MCU running long enough to do that. Designing the circuit depends on too much we don't know about your system, though.
In fact, simply switching a backup battery as some of these articles describe, or better, running on a battery which is kept on a mains charger, may make a much simpler system that can surviVe reasonably long power outages without shutting down. Again, we don't know how often or how long your power goes out, and how reliable your system is required to be.

Thank you sir for your suggestion. But I understand your suggestion but its not clear to me how it will done. Actually I am beginner in this field.. so my request to you please explain me details with an example whatever you wanted to say.. then it will be very helpful to me.

You can store any bits or bytes into eeprom in byte units. The eeprom itself doesn't care whether the data ISS bits or bytes or multi bytes.
Your code only needs to make sure that consistency is maintained in storying and retrieving of eeprom data.


text:
Is it better to use Vraw or Vcc on Mini Pro?
I have 12V and 5V power available. Is it better to feed the 5V through the Vcc pin or either the 12V or 5V through the Vraw pin?

Use the 5V connected to the Vcc pin.
If you use the Vraw pin, the voltage goes through a voltage regulator. This voltage regulator will convert the higher voltage down to 5V by converting the extra volts to heat. So in case of using 12V you'd be throwing away around 60% of the power. Which is both wasteful, and will heat up the regulator quite a bit (depending on the load).

But with feeding 5V, would there be a difference between the Vcc and Vraw? Or does the voltage regulator automatically incur a 1.2V penalty?

Voltage regulators always have a certain dropout voltage. So you always have to provide a voltage a bit higher that the output voltage of the regulator.


text:
Huge nested loop in Arduino
I am completely new to programming and I am trying a brute force programming on my garage door opener. I want to use an Arduino for learning purposes. I wrote the following program that finally did what it should and now I am wondering whether there is a shorter code that does the same. Is anyone able to help me in that matter?
I do know that about 2^12 possibilities existed so I ran through all of them. I also knew that some parts of the "pulsetrain" (the set of necessary pulses) start with a particular sequence that is always the same (for all "brute forced" trains) and that the closing sequence is also always identical. I then simply wrote that down in the following, nasty code:
/*
  Transmitter is connected to Arduino Pin #2
*/

void setup() {
  pinMode(2, OUTPUT);
}

void pulsetrain(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m) {
  PORTD &= ~_BV(PD2);
  //set to LOW, hardwired to make it faster, see http://www.instructables.com/id/Arduino-is-Slow-and-how-to-fix-it/?ALLSTEPS
  delayMicroseconds(283); // (D2)
  PORTD |= _BV(PD2); //set to HIGH
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(283);
  PORTD |= _BV(PD2);
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(a);
  PORTD |= _BV(PD2);
  delayMicroseconds(b);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(c);
  PORTD |= _BV(PD2);
  delayMicroseconds(d);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(e);
  PORTD |= _BV(PD2);
  delayMicroseconds(f);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(g);
  PORTD |= _BV(PD2);
  delayMicroseconds(h);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(i);
  PORTD |= _BV(PD2);
  delayMicroseconds(j);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(k);
  PORTD |= _BV(PD2);
  delayMicroseconds(l);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(m);
  PORTD |= _BV(PD2);
  delayMicroseconds(283);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(566);
  PORTD |= _BV(PD2);
  delayMicroseconds(283);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2); // last LOW
}

void loop() {
  int signals[2] = {283, 566};
  for (int a = 0; a < 2;  a++) {
    for (int b = 0; b < 2;  b++) {
      for (int c = 0; c < 2;  c++) {
        for (int d = 0; d < 2;  d++) {
          for (int e = 0; e < 2;  e++) {
            for (int f = 0; f < 2;  f++) {
              for (int g = 0; g < 2;  g++) {
                for (int h = 0; h < 2;  h++) {
                  for (int i = 0; i < 2;  i++) {
                    for (int j = 0; j < 2;  j++) {
                      for (int k = 0; k < 2;  k++) {
                        for (int l = 0; l < 2;  l++) {
                          for (int m = 0; m < 2;  m++) {
                            pulsetrain(signals[a], signals[b], signals[c], signals[d], signals[e], signals[f], signals[g], signals[h], signals[i], signals[j], signals[k], signals[l], signals[m]);
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Just look at at like 283 is a low bit, and 566 is a high bit. So a-m would become a 13 bit number. Loop through those numbers with a for loop (0-8191). Then in the pulsetrain function read one bit, apply the delay of 283 or 566 based on the bit being 0 or 1. Then shift all the bit (left or right), and repeat (13 times).

My problem is not that I cannot program the opener (the above code did what it should) and I also understand the Manchester Coding. I wanted a code that does the same but consists of less than the above 84 lines! I do not know how to handle binary() and DecimalToBinary() (if it is even defined) with an arduino.

All those variables a, b, etc. are just the individual bits of a
13-bit number. When you loop through all combinations, you are actually
looping through all the possible numeric values of a 13-bit number.
This can be simplified as this (warning: not tested):
void setup() {
    pinMode(2, OUTPUT);
}

// the bitstream is: 0.101x xxxx.xxxx xxxx.0101
void pulsetrain(uint16_t code) {
    uint32_t bitstream = (((uint32_t) code) << 4) | 0x0a0005UL;
    for (uint8_t i = 0; i < 21; i++) {
        PIND = _BV(PD2);    // toggle pin
        if (bitstream & 0x100000)
            delayMicroseconds(566);
        else
            delayMicroseconds(283);
        bitstream <<= 1;
    }
    PORTD &= ~_BV(PD2); // last LOW
}

void loop() {
    for (uint16_t code = 0; code < 0x2000; code++) {
        pulsetrain(code);
    }
}


text:
Electronically, should single or several ground pins be used?
I have heard two theories of grounding: pretty much ground a board at single point, or ground everything in sight.
With the Mini Pro, is it better to provide one source of ground through the Gnd pin next to the Vraw pin, or ground with multiple Gnd pins on the board?

All GND pins on the Arduino board are interconnected, so it doesn't matter which one you use.

There are times when you want a single ground point (star grounding), separate grounds with filters (separate analog and digital grounds, for instance), or you just don't care (99% of the time).
Regardless, this is usually a concern when you are laying out a circuit on a PCB. When you already have a PCB the grounds become a moot point because the PCB dictates how they operate.
For a module like an Arduino, unless otherwise stated, all grounds are equal and can be used for whatever whenever.


text:
Set pins to LOW over time
I've written a simple sketch that adds threshold to an PIR sensor. If the PIR sensor sends 3 HIGH ex. HIGH...LOW...HIGH...LOW...HIGH (The LOW == no movement) it will trigger and alarm.
I want to reset the counter of HIGHs if there's no movement detected. The problem is the loop will get delayed if I put it inline. My code: (Don't mind my code, I'm pretty newbie)
int calibrationTime = 30;
int pirPin = 5;
int ledPin = 6;
int sensorState;
int stateCount = 0; //How much movement is detected
int stateThreshold = 3; //THRESHOLD
bool isSensorHigh;

void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  digitalWrite(pirPin, LOW);
  Serial.print("calibrating sensor ");
  for (calibrationTime; calibrationTime > 0; calibrationTime--) {
    Serial.print(calibrationTime);
    delay(1000);
  }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}
void loop() {
  sensorState = digitalRead(pirPin);
  //Serial.println(sensorState);
  if (sensorState == 1) {
    isSensorHigh = true;
  }
  if (sensorState == 0 && isSensorHigh == true) {
    isSensorHigh = false;
    stateCount++;
  }
  //Set pins 2,3,4 here to LOW if there's no movement detected over time
  if (stateThreshold == 3) {
    switch (stateCount) {
      case 1:
        digitalWrite(2, HIGH);
        break;
      case 2:
        digitalWrite(3, HIGH);
        break;
      case 3:
        digitalWrite(4, HIGH);
        break;
    }
  }
  if (stateCount == stateThreshold) {
    blinkLeds();
    delay(3000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(ledPin, LOW);
    stateCount = 0;
  }
  Serial.println(stateCount);
  delay(150);
}

void blinkLeds() {
  for (int x = 4; x > 0; x--) {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    delay(1000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    delay(1000);
  }
}

Use millis() instead on delay.
Ref: https://www.arduino.cc/en/reference/millis

I could get the span between the millis() and use that value. Pretty much all I need. Thanks


text:
Arduino stops loop randomly whenever a button is pressed
I'm having a problem with this Arduino code.
So whenever I press the "button" in port 11, which is supposed to either reset the burglar alarm or stop it, the whole program stops (the void loop() function stops). The wiring is most likely not the problem, because I've tested it on multiple occasions with different codes. The button, too, works perfectly well as a button with different codes.
In the Serial port, it keeps printing "78005", which it should before the button is pressed, until when I press the button, at which it randomly breaks off printing (resulting in 78, 780, 7, 7800, or 78005 as the last line printed).
Can anyone explain why the arduino will behave in this way?
Thank you so much.
int button = 11;
int receiver = 12;
int buzzer = 13;
int frequency = 1000; // frequency of buzzer

bool keepAlerting = false; // toggles Alarm regardless of detected charge
int receiverVal = LOW; // value from port 12
int buttonVal = LOW; // value from button
int oldButtonVal = LOW;

int setupTime = 5000; // time the user has to close the box after toggling alarm

bool alarmOn;
int buttonMode = 0;
const int resetButton = 1;
const int stopButton = 2;
int buttonModeDecider = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(buzzer, OUTPUT);
  pinMode(receiver, INPUT);
  pinMode(button, INPUT);
  Serial.begin(9600);

  noTone(buzzer);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print("7");
  receiverVal = digitalRead(receiver);
  buttonVal = digitalRead(button);
  Serial.print("8");

  if(alarmOn == true){
    Serial.print("6");
    setAlarm();
  }

  Serial.print(buttonVal);
  Serial.print(oldButtonVal);

  if(buttonVal == HIGH && oldButtonVal == LOW){
    buttonModeDecider = 1 - buttonModeDecider;
    Serial.print("Toggled");

    if(buttonModeDecider == 1){
      buttonMode = resetButton;
      Serial.print("1");
    } else {
      buttonMode = stopButton;
      Serial.print("2");
    }

    switch(buttonMode) {
      case resetButton:
      {
        delay(setupTime);
        alarmOn = true;
        break;
        Serial.print("3");
      }
      case stopButton:
      {
        alarmOn = false;
        Serial.print("4");
      }
    }
  }
  Serial.println("5");
  oldButtonVal = buttonVal;
}

void setAlarm() {
  if(receiverVal == LOW || keepAlerting == true) {
    tone(buzzer, frequency);
    keepAlerting = true;
  }
}

How is the button wired?

You claim "the void loop() function stops", then you say "or 78005 as the last line printed". Can you really confirm this is the last line printed ONCE then nothing, or the last line reprinted forever, which would be much different than "the loop() stops" then.

For your inputs you use INPUT mode not INPUT_PULLUP, this means you added yourself a pullup or pulldown resistor "between" your button and the input pin, can you confirm this wiring? And then the opposite button side is connected to GND (if you use a pullup resistor) or +5V (if you use a pulldown resistor). A bad wiring here could make your program fail unexpectedly.

Add debouncing for your mechanical button. Your probably false detecting button press and release caused by bouncing. https://www.arduino.cc/en/Tutorial/Debounce

jfpoilpret: Yes, I can confirm that the last line printed is definitely the last line. It is not reprinted. Also, I can confirm the 10 ohm resister exists between my button and the input pin, and that the opposite button side is connected to GND. The wiring probably isn't a problem because if I use a different code with the same wiring to do other similar behaviors, it still works.

I have exactly the same problem. My friend just advised me to install the diode, as this apparently fixed his problem. We are working on the project from a couple of days and we wasted around 3 days, purely because of that. I have 20 lines of code, as everything was stopping working, as soon as we connect more devices. It like just stops working and it is broken and then suddenly become back to life. Yeah. We know what is going on. I may post the update about this diode once I install it on my rig.

Arduino stops loop randomly whenever a button is pressed

your button is shorting the supply?

A 10 Ohm resistor when switched to ground can cause the power supply to drop below the operating voltage of the Arduino. If you mean to have a pulldown resistor to ground use a 10K value instead.
Note that a 10 Ohm resistor across a 5V supply draws 0.5 Amps of current.


text:
Change select pin of USB Host library
TL;DR
With regards to the USB host library:

Which is the correct file to modify the Arduino pin used for the USB Host slave select (SS) line?

I would like to add USB host functionality, to a particular Arduino setup, whilst, also, being able to use an Ethernet/SD (or just SD) shield.
As both the Ethernet shield and USB Host shield use pin 10 to select the W5500 and MAX3421E respectively1, obviously I can not use a standard USB Host shield. However, I could employ one of the small form factor boards, such as the USB Host Shield 2.0 Arduino UNO MEGA ADK Compatible Google Android ADK which I found on eBay:

As this board is not in the usual shield "shape", one would not be constrained by which pin to connected to which MAX3421E input/output, in particular the chip select (SS) input. So, one could use a pin (or pins) that is not reserved by the Ethernet shield.
However, it does not appear to be possible to simply specify the "select pin" (i.e. the Arduino pin connected to the SS line) when using the USB Host shield library (or any of the pins used by the library), in setup().
Therefore, I wondered if it was possible to modify the library, so that the pin used to select the USB/MAX3421E could be changed, either by:

"Hardcoding" a different "select" pin number into a header file;
Adding an argument to the Init() method, or;
Adding a method to the USB class, such as Usb.DefineSelect().

The latter two options, I could work through, given the time. However, as a quick and dirty hack, where would I hardcode in a change from pin 10 to a pin of my choosing? Does anyone know? Has anyone had to do this?

Nitty-gritty
I have had a look through the library to see where pin 10 is defined as the chip select, and avrpins.h looked like a possible candidate for modification, although it would be rather "rude" (for want of a better word) and probably mess up the other boards.
usbhost.h seems a much better proposition. Looking at usbhost.h, the lines 88-91:
#if defined(__AVR_ATmega1280__) || (__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;
#elif  defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

Looking at the statement
typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

the last argument appears to be the pin used for select. For the Uno (ATmega328P), in avrpins.h (line 535) Pb2 is P10 (pin 10), so I could substitute Pb2 for some other pin definition, i.e. Pd5 for P5 (pin 5) (line 529 in avrpins.h).
However, what I don't understand is that for the statement
typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;

which deals with the Mega (ATmega2560), in avrpins.h (line 512) Pb0is P53 (pin 53). As Pb4 is actually P10 (pin 10) (line 466), why is Pb0 en lieu of Pb4 used? That doesn't tie up with the fact that Pin 10 is used for both the Uno and Mega boards. It seems to suggest the pin 10 is used on the Uno and pin 53 is used on the Mega. Unless I have misinterpreted the typedef.

Footnote
1 For the USB host shield, from Arduino USB Host Shield

Arduino communicates with the MAX3421E using the SPI bus (through the
ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno
and pins 10, 50, 51, and 52 on the Mega. On both boards, pin 10 is
used to select the MAX3421E. Pins 7, 8 and 9 are used for GPX, INT and
RES pins.

The key piece of information here is that pin 10 is used by both the Uno and Mega boards.
For the Ethernet shield, from Arduino Ethernet Shield V2

Arduino communicates with both the W5500 and SD card using the SPI bus
(through the ICSP header). This is on digital pins 10, 11, 12, and 13
on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10
is used to select the W5500 and pin 4 for the SD card. These pins
cannot be used for general I/O. On the Mega, the hardware SS pin, 53,
is not used to select either the W5500 or the SD card, but it must be
kept as an output or the SPI interface won't work.
Note that because the W5500 and SD card share the SPI bus, only one at
a time can be active. If you are using both peripherals in your
program, this should be taken care of by the corresponding libraries.
If you're not using one of the peripherals in your program, however,
you'll need to explicitly deselect it. To do this with the SD card,
set pin 4 as an output and write a high to it. For the W5500, set
digital pin 10 as a high output.

Here, yet again, the key piece of information here is that pin 10 is used by both the Uno and Mega boards to select the Ethernet.

It look like you are correct, and that you should edit the usbhost.h file.  Not sure what you mean in the second question. The library uses the Arduinos SS pin. It does have to use this pin, but this prevents the pin from being an input and accidentally putting the atmega into SPI slave mode. The library also prefers to have all the pins on Port B.

@Gerben - Thanks for the confirmation of the first question. I have edited my post to try to clarify what my second question is, which is "shouldn't the last argument to the typedef for the Mega board be Pb4 and not Pb0?" Maybe I need to recheck my understanding of the code, in the morning.

Trying to put both an Ethernet adapter and USB host adapter on an ATmega based Arduino is evidence of bad hardware selection.  You should probably either consider something that does both natively (for example some of the STM32F4's, and likely choices from other vendors) or unless your needs are very narrow and never expected to change, more likely a more sophisticated system capable of running an actual operating system.

Like I said, pin PB0 is the SS of the ATMega. When using SPI you shouldn't use this pin as an INPUT. It's therefor a good idea of the library maker to choose that pin, so it's always an OUTPUT. Also pin 53 is close to the other SPI pins. Using pin 5 would be at the other side of the board, which make wiring messy pretty quick. No big reason to choose PB0, just a few small reasons.

@Gerben - Thanks for pointing me in the right direction. At first I couldn't understand what you meant, but after re-reading SPI library, I see that the source of my confusion is that P53 (Mega) and P10 (Uno) are the Arduino's SS pin, which obviously must be set as an output, to maintain them as the SPI master. I was looking for the point in the code where pin 10 is set to select the USB shield's SS line, not the Arduino's SS line, if that makes sense... So the typedefs that I found in usbhost.h are not what I should be looking at.

@Gerben - After trawling most of the source files, I have found the point where P10 is set as the USB SS line. It is, in fact, at line 43 in UsbCore.h. It seems at bit ruthless to modify this file, but that is where the change needs to be made. See my posted answer.

I don't get it. The Arduino has a SS pin, but you can ignore this if you aren't using the the Arduino as an SPI slave. If you don't use the Arduino as a slave, the SS pin is just a regular input/output pin.

@Gerben - I think that we have our wires crossed, so to speak... :-) My answer below will hopefully clarify what I mean. If not, then I will need to reword my answer. The Arduino is the SPI Master, and the small USB host device, that I show in my question, will be the SPI slave. With my suggested modification to the code, Pin 5 would go to the USB Host SS line and then there would be no conflict with the Ethernet board that uses Pin 10 for its SS line.

In order to change the Arduino pin used to select the USB Host board, in order words, where the device's SS line is assigned to an Arduino pin (with the Arduino as the SPI Master and the USB host is the SPI slave), the line to change is at line 43 in UsbCore.h:
typedef MAX3421e<P10, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

So to use pin 5, for example, en lieu of pin 10, the line would become:
typedef MAX3421e<P5, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

The clue was in the comment on line 27 in UsbCore.h
/* shield pins. First parameter - SS pin, second parameter - INT pin */

With this suggested modification to the code, Pin 5 would go to the USB Host SS line and then there would be no conflict with the Ethernet board that uses Pin 10 for its SS line.

This issue, I have subsequently discovered, is covered by the USB Host Shield Hardware Manual, under the Interface modifications section. I guess I should have just read the manual first! RTFM...

Clarification of the issue
I must be honest that my question was somewhat confused. After having read the SPI library, it states that

Note about Slave Select (SS) pin on AVR based boards
All AVR based boards have an SS pin that is useful when they act as a
  slave controlled by an external master. Since this library supports
  only master mode, this pin should be set always as OUTPUT otherwise
  the SPI interface could be put automatically into slave mode by
  hardware, rendering the library inoperative.
It is, however, possible to use any pin as the Slave Select (SS) for
  the devices. For example, the Arduino Ethernet shield uses pin 4 to
  control the SPI connection to the on-board SD card, and pin 10 to
  control the connection to the Ethernet controller.

With respect to the first paragraph, the Uno uses pin 10 and Mega uses pin 53 as the Arduino SS line - so that must be set as an output in order for the Arduino to be the Master. Are realising this as being my source of confusion, it became apparent that the typedef statements, in usbhost.h, were not where I should have been looking to change the device's Slave Select pin.
With respect to the second paragraph,  I want to use pin 5 (for example) to control the Slave Select (SS) for the USB Host device, instead of the default pin 10.

The link seems to have died and this google site search finds nothing seemingly related

See section Interface modifications in the USB Host Shield Hardware Manual. Address updated.

So, it is the same link as was in my answer?

Yes, that is the only surviving link I can find. It is linked from the README of the library repo on GitHub.

Ah, ok. Thats a shame. I never got around to seeing the original link that you posted. I wonder if it was dramatically different.


text:
How to detect pinout at run-time
Is it possible to query the pin-out and each pin's attributes at run-time with Arduino?
If not, can it be done at compile-time?
Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?
I am looking for something like this:
PinProperties props= getPinProperties(pinNumber);

props.supportsDigitalInput();
props.supportsDigitalOutput();
props.supportsAnalogInput();
props.supportsAnalogOutput();
props.supportsPWM();
props.analogInputBits();
props.analogOutputBits();
props.pullupResistance();
props.pulldownResistance();

etc.
NOTE: This question is similar and I might use the board model to look up a pre-stored pin-out.

I did not know about it! Moderators,  please migrate this question!

It's a nice thought, but I'd suggest this could most practically only be done at compile time (selecting an Arduino model based on cpu ID).   The only situation where you'd actually need this would be if you deployed the same firmware image to multiple cpu ID's ...but that seems beyond the expectations of the Arduino dev environment.

I am actually going this route in my project.  The idea is to abuse Arduino to the benefit of the ease of use for end user.

pins_arduino.h has some standard macros that can be used for some of what you're looking to do. Using the arduino:standard variant used by Uno for example:
https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L35:
#define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11)

Or if you want to use your naming scheme:
#define supportsPWM(p) digitalPinHasPWM(p)

After that it gets a bit more sketchy:
https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L28
#define NUM_DIGITAL_PINS 20

So, assuming that Arduino digital pins will always be numbered consecutively from 0 and any pin that supports digital input also supports digital output(which is the case in any variant I'm familiar with), you could use that to write some macros:
#define supportsDigitalInput(p) ((p) < NUM_DIGITAL_PINS)
#define supportsDigitalOutput(p) supportsDigitalInput(p)

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L29
#define NUM_ANALOG_INPUTS 6

Could be used to write this macro(with numbering assumption):
#define supportsAnalogInput(p) ((p) < NUM_ANALOG_INPUTS)

Note that this will not work for the An analog pin names(e.g. A0 vs 0).
As for:
props.supportsAnalogOutput();
props.analogInputBits();
props.analogOutputBits();
props.pullupResistance();
props.pulldownResistance();

I'm don't know of pre-existing code for those. There is probably a way to get it for the first three in an architecture specific manner. The last two you'd most likely need to get the information from datasheets for all of your target microcontrollers and define then using processor specific macros.

There is no strong relation with pin numbering and the hardware as far as I know.
To be more specific, the datasheet tells you what registers can be used for what functions. The microcontroller does not neccesarily know what registers it has or what functionality it's registers have.
You could make your own library or class for a pin.
I would go by something like:
Pin input1 = new Pin(.....);

if(input1.isAnalog()){
   input1.setupAnalog();
}

if(input1.analogIsReady()){
   input1.readAnalog();
}

Instead of having a "pinproperties" object for a pin.
You'll have to look how you want to make the class.
You can create one single class that has all functions and just checks if there is an implementation for that pin.
You may go by classes like:
class pin

class analogPin extends pin

class pwmPin extends pin

However, this may fail if your analog pin doesn't support the regular "pin" functions (like I/O).
Theoretically you could use C++'s multiple inheritance to inherit things as I/O, PWM and Analog, but I've heard that it doesn't perform very well on embedded targets.

Alternatively you could make a list of pins that support PWM. And a list of pins that support Analog. And a list of pins that support I/O.
When a person (runtime) tries to set a pin's state, you can check if that pin supports I/O, but I'm not sure what behaviour you'll expect if one tries to set a pin that doesn't support that option.

Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

The libraries are designed so that you don't really need to know that. One issue is the relationship between the chip pins and the board pins. Just as an example, pin 19 on the Atmega328P goes to the board pin 13 (digital pin 13) on a Uno.
If your program needs a couple of digital inputs and a couple of digital outputs, you could use (say) D2 and D3 as inputs and D4 and D5 as outputs. Then let the underlying libraries work out which chip pin that is, and configure it correctly when you use digitalRead, digitalWrite and pinMode.
You can self-query for the chip type (for example here) however that doesn't tell you what board the chip is mounted on.

to avoid completely rewriting my program for each possible Arduino model

What are you envisaging that would require a complete rewrite? Many libraries and projects are written to work on multiple boards with only minor changes (if any). You can detect the processor type at compile-time.
I simply don't see where "complete rewrite" comes into it. Use functions to abstract out the parts that interface with pins (as digitalRead, digitalWrite and pinMode already do) and a few constants at the start of the code to indicate which pins you have chosen for this particular board.

Sorry ,I should have explained better. My program is datadriven so that the serial protocol will tell it which pins to use for what. To make that happen it needs to know which pins are available, and what they can be used for. So instead of maintaining many images, I would like to maintain only ONE that adapts to the current hardware.

I see. Well, different Arduinos have different processors. For example ones like the Atmega2560 have different addressing models internally than the chips with less RAM. Your goal of sharing a single executable amongst various processors is probably not very achievable. It's like hoping to run Windows software on OS/X.


text:
How safe is it to use my body as part of a circuit?
I have two polystyrene balls wrapped in copper tape. When the balls touch, the tape completes a circuit from a digital pin on an Arduino inside one of the balls to an Arduino inside the other (both powered by 9v batteries). This allows them to send information to each other via the copper tape path.
I was testing the balls out, and they were working too well. Even when the balls weren't quite touching, the signal was getting through! Turns out that's because the signals were travelling via my body. Even if I held one ball in one hand and the other ball in the other hand, digital reads on one Arduino were correctly reading the digital writes from the other.
This is actually great for my project!... unless it's not safe. So I'm looking for two things:

A reliable reference on what is and isn't safe in terms of voltage/wattage/amperage travelling from hand to hand.
A second opinion on the voltage/wattage/amperage that two Arduinos will actually pump through me (from digital pin to digital pin).

You say the tape completes a circuit when the balls touch ... do the balls have some wires connecting them, besides the tape?  Or are you just doing capacitive signalling?

@jwpat7 I guess "completes the circuit" is the wrong wording. One Arduino sets a pin to 0V or 5V in a recognizable pattern, that pin leads to a pin on the other Arduino (via the copper tape), where the voltage is read. When the balls aren't touching, the pins aren't connected.

So it is like you have two metal globes, with no wires coming out, and when they are connected you are able to detect signals between them?  If so the mechanism is capacitive and current probably is on the order of nanoamps if that.  What's your signalling protocol?  Do you have to have some min or max data rate, Manchester coding, and so forth?

@jwpat7 I haven't decided on the protocol yet. I just confirmed that the distinction between high and low was getting through. The data rate I need is super low (<10bps) so basically anything I use will work. The main complication is cross-talk, or negotiating who sends and who receives.

If you ever switch to a wall-adapter, make sure it's not one of those ultra-cheap chinese ones.

If you are talking about running at 5V, then I doubt there is any safety issue. After all, 9V batteries (the sort you put in your smoke detector) just have bare terminals and no-one tells you not to touch them.
There is quite a bit of related information at How much voltage is “dangerous”?. That link seems to have enough information that there isn't a lot of point of repeating it all here.
There is a reference on that page to someone holding a metal pole connected to a 12V battery wading through water which completed the circuit and he was unable to let go of the pole. But that is 12V (more than twice 5V) and in circumstances where there was good conduction (his body was wet).

In the interests of science I set up a small test. I connected myself to a 5V lab supply via an ammeter. I grasped the terminals firmly (with dry hands) and measured about 3 µA of current. From the page I referenced above there seems to be a consensus that 1 mA would be just noticeable, so this is about 300 times less.
I found if I wet my fingers I got up to about 20 µA of current, still a lot less than 1 mA.
That page mentions that 60V is getting into the range where you might get a shock.

Hopefully it goes without saying that if you are going to touch metal balls then you need to be certain that 5V is the maximum, and that some sort of failure in a power supply might not deliver a lot more. But if the balls are battery powered you should be pretty safe.

You've added that they are powered by 9V batteries. That doesn't change my answer much. The most that could "escape" due to some malfunction is then 9V. Under normal operation you would have 5V from a digital output pin.
I measured my body resistance as being around 1.5 MΩ, which is consistent with getting 3 µA of current through it.
I = V / R
I = 5 / 1500000 = 0.000003 A

Have you tried licking the terminal on a 9V battery, they don't say you shouldn't do that either :)

Yes I did that when I was a lot younger. The pain caused me to stop doing it. :)

In fact the voltage is almost irrelevant. The current is the issue. 30mA is normally considered the limit - this is the value RCD are set to trigger at.
Even low voltages applied to intimate places can be fatal. (I have a couple of wires in my heart, these can certainly cause a significant impact).
There is little risk with the low energy available, but if you want to be safe you can use a series resistor. I have (a very early) touch sensor installed on lights in my house. The touch pad is effectively connected to 240V, but is quite safe as the pad is connected through 2 10MΩ resistors. (2 are needed as they are rated at 500V.)

2 are needed - plus that is a precaution if one fails and becomes closed circuit.

In fact the voltage is almost irrelevant. The current is the issue. - Check out "It's not the volts that kill you, it's the amps"

@NickGammon I didn't "read" the link, because it is to a video. Like most such issues this is not simple, because people are not a simple linear resistance. I bow to the recommendations of the of the Standards authorities, which admittedly only apply to "Low Voltage" (contrary to most expectations this is 1000V - with its own caveats).

If you had "read" the link you would see that he agrees with you. It isn't simple. Higher voltages, however, break down the surface resistance of things like bodies.

@NickGammon, apparently there are no wires coming out of the spheres (see comments to question) so typically any volts or amps occuring will be from capacitive effects as a few nanocoulombs of charge move around.

@jwpat7 - not wires, but he said in the question I have two polystyrene balls wrapped in copper tape.. I count the copper tape as "wires".

@NickGammon, ok, but no additional wires that can complete an electrical circuit per se.  Toggling a bit in the Arduino inside a ball shifts the shell up or down relative to the matter inside the ball, which I think has a capacitive effect.  If no wires come out (besides the shell) then no steady current can flow.

@jwpat7 - yessss, but the OP said When the balls touch, the tape completes a circuit. So I am reading that as "there is conductive stuff on the outside that completes the circuit" - not a capacitance effect. His surprise was that by holding the balls in each hand his body completed the circuit.

@jwpat7 If you want to have a discussion why not do it in Chat, rather than in Comments to this Answer


text:
Communication between 2 nRF24l01s and 2 Arduino unos
I am having a logical error that I can not figure out with the communication. I am communicating fine with the two boards such that I can send and receive data. Code to my Transmitter and Receiver. Serial outputs here. Using library from this site: (Sorry reputation too low to add another link)
www.instructables.com/ORIG/FV6/0AAE/IBXM5ZIY/FV60AAEIBXM5ZIY.zip
(WARNING: will download with out permission if you visit link above. Use below link if dont want to download)
www.instructables.com/id/Wireless-Remote-Using-24-Ghz-NRF24L01-Simple-Tutor/?ALLSTEPS
(Scroll down to step 4, library's are labeled as "library files.zip". Names inside the zip folder are "nRF24L01" and "RF24")
From the Serial outputs I do not understand why on my transmitter it says it sent the time in milliseconds, 5873, but on my receiver output it says it received 241. Also I do not understand how the millis() function on the receiver returned a lesser value than what the transmitter should have sent.
I have novice understanding of c++ and the nRF24L01 radio at best. Any information is appreciated.
Thank you in advance!

Hint: 5873 = 22 x 256 + 241. It seems you transmit (or receive, or print, I did not check your code) only one byte.

@jfpoilpret Good catch. This looks like the culpret: radio.write(msg, 1); - wite just one byte from the msg start address.

@Majenko Thank you for the feedback I changed the .write(msg, 1) to .write(msg, 2) but after a while it goes back to sending the wrong time i'm assuming the byte got larger. How would I write it to receive all bytes?

A long is 4 bytes.

Use sizeof() to get a type's lenght. Also check out github.com/TMRh20/RF24Network and RF24Mesh.


text:
String use in arduino IDE (this question for understanding)
I'm using arduino several month now, And i don't understand when i can use the arduino object of String. I'll explain, I read a lot and the it's look like that this object is a good way to read/write and use strings, But everywhere they say that this object take a lot of RAM. So i made some project, And almost in all of them the String object not work as i expected. When i check the RAM in my projects i see that when my usage of RAM is greater then 65% the string object start to do problems. Because of this i stop use the string object and use only char arrays.
So my question is:

How can i know when i can use String from the beginning?
there is a way to change from char array to string or vase versa easily (i know this is completely different logic)?
How can i avoid the memory problems with the String object?

All this questions come from that the String object is very effective and easy to use and i want to use it, But i'm fear from RAM problems so i'm not using it.
Thank you very much for reading all this, Hope you can help me!

I recommend looking at thsi question: http://arduino.stackexchange.com/questions/19294/what-is-the-memory-expense-of-creating-a-string-from-a-char-array and this answer http://arduino.stackexchange.com/a/19295/84 with which I fully agree: DO NOT use String. The linked answer provides all (good) reasons for that.

@jfpoilpret this is not a duplicate, I'm trying to understand how can i use string sometime, in all my project i'm using char array and it's very sad there is such a good object for this and i don't know if i can use it at all.

For me the answer to your question is the answer to the above question, then I don't see the point having the same answer here. If you read the answer I linked to, then you shall understand that String usage is generally bad, except if you do simplistic projects and only for fun. I NEVER use String (and never will).

I read the answer, And this is a very good one, thank you for that. According to that, i now sure that is no usage with this object.

I've added an answer to the cited question, which will be relevant here as well, with the understanding that Uno's memory size is borderline to use String objects any more than trivially.

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

By adding one character to a string the class has to allocate new memory for the slightly longer string. If you keep doing this you get memory fragmentation.
You are probably better off deciding what your maximum size string is and making that a static array of characters.

So should I use the String objects?
For occasional use they are fine (for example, holding the name of something). They tend to fall down once you start with a small String and keep adding to it, because the code has to dynamically allocate memory, allocating (say) 5 bytes, then 6 bytes, then 7 bytes, and in the process freeing up the original 5 bytes, then 6 bytes and so on. This allocating/freeing process can leave holes in the "heap" causing a thing known as memory fragmentation.
Done to excess you can run out of memory. That is, you might need 100 bytes but have 10 lots of 10 bytes free, with stuff in-between that isn't free.
You don't have lots of memory to start with, so it is probably better, faster and more efficient to decide the largest amount you need for some string, and just make that a character array.

so, you said not use the String object?

See amended answer.


text:
Is there a way to "list" (in BASIC, or "cat" in LINUX) the current sketch loaded in my xxxDUINO?
I was surprised when I couldn't find an old post where someone asked this question. Seems like a natural beginner, uh excuse me, "newbie" question, but then I'm a throw-back to the days when a home computer came with 3,583 bytes (three-thousand, five-hundred eighty-three). So again, as seen in the title, can I "list" my sketch? I'm pretty sure the answer is NO since if it were a good question someone would have asked it already. It just strikes me as odd that my old VIC-20 could do something this phenomenal techno-marvel can't. Not much of an accomplishment for the dinosaurs, but HEY! We're on the scoreboard now! [nothing's worse than that miserable goose-egg :(   ]

What is the problem you are trying to solve? You have an Arduino and you want to "list" its contents?

I was surprised when I couldn't find an old post where someone asked this question. -- How about the first in the "Related" list...?

Sorry about that, I really hate posting nuisance threads. I almost always prefer  to find a good answer and be on my way. I so don't want to be the that type of person who wont put in any effort. I know I can't see you or will ever meet you, but I find it embarrassing, unpleasant, uncomfortable, unnerving, and unsettling when I bring down the room or step on someone's leisure. I should have dug more, and not been so hasty when going through the search results. But most annoying to me, was dropping the ball when trying to articulate what I wanted, which wasn't LIST or PRINT, but DOWNLOAD! sorry

If you can't find your answer whilst searching it is often easier to start typing out your question. While you are doing so the system is constantly analysing what you are asking and offers you suggestions. Because you put so much more detail into a question than you do into a search box those can often be far better results than a simple search. Especially when search really relies on you knowing what to search for in the first place, which isn't always the case.

And anyway, when I'm around the room can't get any lower ;)

No. the code burned in an Arduino is compiled not interpreted like Basic.
Basically your C language sketch is compiled into AVR assembly language. The resulting hexadecimal is what is burned to the Arduino.
Yes you could disassemble the hex like we used to do in the good old days, but as before it is highly unpredictable and most of the time not very useful.
Just a quick example. The following simple Arduino sketch that just sets a pin in output and then sets it HIGH:
void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
}

void loop() {
}

The resulting hex file is 3.5Kb.This include various sections of data and code. One would have to analyse the section, convert the hex (op-code) to assembly language and find which part correspond to the C code.
It is possible, and there are probably tools that do a fairly good job. Would the C language generated by the decompilation once recompile perform exactly like the original compiled cole. I doubt it.

Hmmm, I'm intrigued! I love a fool's errand (sometimes). Just out of curiosity then, could you briefly outline the disassembly process, and perhaps some idea in broad terms what makes this unpredictable and the obstacles that prevent useful results. I have not Idea what I'm asking of you, so please forgive me if this is an imposition. I know I'd be less than receptive to someone wanting to know what the average mass of a fastener was in my collection of old machine screws!

Well, you have to take the hex codes (called op-code) and convert that to assembly language. Then you have to match the part of assembly language and find what they would represent in C.

edited my answer to provide more details.

Regarding the disassembly process see my answer here.


text:
How to burn bootloader/program an ATMega 328P with an external crystal 8 MHz oscilator?
I need to program a ATMega328P on a breadboard, running on an external crystal at 8 MHz.
All of the guides I can find either use the arduino environment and describe a 16 MHz config, or using the 8 MHz internal oscillator - which is too inaccurate for this project.
How do I do this?  Configure the chip to run at 8 MHz and upload the program?

why don't you use the internal 8Mhz crystal?

Because I'm using serial communication with another device - the internal 8Mhz crystal is only rated as accurate within 10% at 25 degrees C.  Serial communication tolerates an error of about half this.

There is no such thing as an internal 8 MHz crystal, just an 8 MHz RC oscillator.

I accept the correction that the on chip device isn't a crystal.  Doesn't change the reason I can't use it :)

you forgot to ask a question.

Edited to make question explicit.

Because you edited this in once more (and I corrected it): The unit is spelled "MHz", not "Mhz".

Solution used an arduino, but I'd happily accept (and prefer) a lower level solution.  Even so, surely that's a vote to move, not vote to close?

why don't you use the internal 8Mhz crystal? There is no "internal crystal". the internal oscillator is a rc oscillator. fairly imprecise and not as stable as a crystal oscillator.

myself as of 3 hours ago.

Get an arduino or similar, install the ArduinoISP sketch
Connect the two as described here.
Change the board to Arduino Pro or Pro Mini, Processor to 3.3V, 8Mhz, Programmer: Arduino as ISP
Hit burn bootloader button
Load up the sketch that you want on the device
Without changing anything, use "Upload using programmer"
Remove arduino, fix wiring changes required to use as programmer

Committed to Electronics Stackexchange  for posterity.  Or so I can find it when I forget next time...

authors: นีโอ แอนเดอสัน


text:
Wireless Sensor communication with 100Hz rate
I'm doing my project on haptic feedback systems. I need a 56bits of data transmitted over wirelessly to a computer to process and send the output to another arduino. I tried ESP8266 using TCP/IP protocol. But it is very slow. Are there any faster modules to do the above task with 100hz speed?

Note, please edit your question in reply

Usually protocols that package up data and test for errors are too slow for real time purposes.  This is why gamers, for example, like using a corded mouse over a wireless mouse.  Unfortunately when you go this route you are usually left with out all the abstractions that make using a common protocol like TCP/IP almost easy.  It is up to you to research this more.  But it sounds like you are entering into the world of serial port radios using simple but very specific proprietary protocols.  And, for all I know, you only need to communicate in one direction.  Which would simplify your hardware.

[edit of my earlier comment, with bps correction] Have you also tried UDP/IP? Lower overhead might make a difference. Although if you aren't getting 5600 bps thruput (ie, 56*100 payload bits) with TCP/IP, probably something's wrong in your setup, which you haven't detailed enough for comment upon. You could provide a Minimal, Complete, and Verifiable example code and part numbers plus name of host computer; could be most of the delay is in the host.

With TCP/IP most of the delay is the act of opening the socket. If you open a socket, send a couple of bytes, then close the socket, yes it is going to take a long time. However, if you open the socket and keep it open then TCP/IP can be quite fast. Over a local network it's as good as a serial connection.

Make one static tcp connection with a regular check and on error event to restore it in case it drops. Tcp must be able to run data at your rate.
If not, maybe the main arduino loop has delays in it.


text:
Avrdude fails to verify after upload
I'm using the most recent Arduino IDE to upload a sketch to an Arduino Uno, and the upload seems to succeed, but the final verification step fails with the error:
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file ".build_ano/uno/firmware.hex"
avrdude: writing flash (30908 bytes):

Writing | ################################################## | 100% 5.01s

avrdude: 30908 bytes of flash written
avrdude: verifying flash memory against .build_ano/uno/firmware.hex:
avrdude: load data flash data from input file .build_ano/uno/firmware.hex:
avrdude: input file .build_ano/uno/firmware.hex contains 30908 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 3.96s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x7800
         0xff != 0xfe
avrdude: verification error; content mismatch

avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

I've re-ran the upload several times, and tried different USB cables, but I get the exact same verification error each time. Does this mean the upload effectively failed (presumably because the flash memory has gone bad), and that my sketch is not running on the Arduino? Is there any way I can fix this?
I tried uploading to a different Arduino Uno, and I received the exact same error.

Try uploading a simply sketch link blinking the onboard LED on pin 13.

@AndreCourchesne, That works. I only get the error for my sketch.

Genuine Arduino or cheap chinese knock-off?

I think your sketch is to big. The Uno has 32k of flash. 2k is used by the bootloader leaving 30k or 30720 bytes. Your binary is 30908 bytes.

So here is my official answer ;-)
Your sketch goes above the 30k flash available on the Arduino Uno.
Yes the Uno has 32k of flash, but 2k is used for the Arduino bootloader. if you convert 0x7800 in decimal that gives you 30720 which is exactly 30k. And your sketch is 30908 bytes so it's 188 bytes too long.
Try optimizing it.
A second alternative would be to use the Optiboot bootloader replacement (https://github.com/Optiboot/optiboot) which only uses 512 bytes.

This seems to be the cause. I flashed a bootloader from a more recent Arduino IDE. I'm assuming it comes with that more efficient bootloader, because it fixed the error.


text:
Is it possible to have an Adafruit music maker shield and a sensor connected to the same Arduino?
Are the analog I/O pins on the Arduino still available for sensors when there is an Adafruit Music Maker shield attached to it? I want to play a sound file, but only when a PIR sensor senses motion.

What does the schematic and/or datasheet for the music maker say?

If you look at the PCB of the Adafruit Music Maker here:
https://learn.adafruit.com/assets/16643
You can see that there are no connections on the analog I/O of the Arduino.

Could you please expand your answer a bit? Actual pin numbers would be great.


text:
Multi-LED Toggle Switch
I am using a Python3 GUI on my RPi3 to control my DFRobot Bluno Mega 2560 via USB.  The Mega is hooked up to a breadboard with 4 LED's and I am trying to control each LED with their own toggle switch.  I was able to do this with one LED but for some reason when I try to achieve the same with more than one it doesn't work, I get absolutely no response from the LED's whatsoever.  It is something to do with how the arduino is receiving the ASCII code, or I think it may be a problem with how I am implementing tkinter as I have little experience with it.  If anyone can tell me what I am doing wrong please let me know.
Here is the Python3 GUI code:
import serial # import the serial library
import time # import the time library
from tkinter import * #import Tkinter GUI library

def toggleRed():
    if redBtn.config('relief')[-1] == 'sunken':
        redBtn.config(relief="raised")
        arduino.write('a'.encode())
    else:
        redBtn.config(relief="sunken")
        arduino.write('b'.encode())

def toggleGreen():
    if greenBtn.config('relief')[-1] == 'sunken':
        greenBtn.config(relief="raised")
        arduino.write('c'.encode())
    else:
        greenBtn.config(relief="sunken")
        arduino.write('d'.encode())

def toggleBlue():
    if blueBtn.config('relief')[-1] == 'sunken':
        blueBtn.config(relief="raised")
        arduino.write('e'.encode())
    else:
        blueBtn.config(relief="sunken")
        arduino.write('f'.encode())

def toggleYellow():
    if yellowBtn.config('relief')[-1] == 'sunken':
        yellowBtn.config(relief="raised")
        arduino.write('g'.encode())
    else:
        yellowBtn.config(relief="sunken")
        arduino.write('h'.encode())

print ('Connecting...')
arduino = serial.Serial("/dev/ttyACM0", 9600)
time.sleep(3)
print ('Connection established successfully')

appWindow = Tk() # creates the application window (you can use any name)
appWindow.wm_title("RGB LED Control") # displays title at the top left
appWindow.config(bg ="#037481")

mainFrame = Frame(appWindow, bg="#037481") #define the main frame of the GUI
mainFrame.grid() #grid the frame into the App Window

btnFrame = Frame(mainFrame, bg="#037481") #define the frame within the main frame that holds buttons
btnFrame.grid() #grid the frame into the main frame

redBtn = Button(btnFrame, text="RED", width=12, bg="red", relief="raised", command=toggleRed)
redBtn.grid(column=0,row=0,sticky='EW')

greenBtn = Button(btnFrame, text="GREEN", width=12, bg="green", relief="raised", command=toggleGreen)
greenBtn.grid(column=0,row=1,sticky='EW')

blueBtn = Button(btnFrame, text="BLUE", width=12, bg="blue", relief="raised", command=toggleBlue)
blueBtn.grid(column=0,row=2,sticky='EW')

yellowBtn = Button(btnFrame, text="YELLOW", width=12, bg="yellow", relief="raised", command=toggleYellow)
yellowBtn.grid(column=0,row=3,sticky='EW')

appWindow.mainloop()# begins main loop

Here is the arduino code:
int ledRed = 13;
int ledGreen = 11;
int ledBlue = 9;
int ledYellow = 7;

//int ledRedStatus;
//int ledGreenStatus;
//int ledBlueStatus;
//int ledYellowStatus;

void setup() {
  pinMode(ledRed, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledBlue, OUTPUT);
  pinMode(ledYellow, OUTPUT);
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() == '97') {
    digitalWrite(ledRed, LOW);
  }
  if(Serial.available() == '98') {
    digitalWrite(ledRed, HIGH);
  }
  if(Serial.available() == '99') {
    digitalWrite(ledGreen, LOW);
  }
  if(Serial.available() == '100') {
    digitalWrite(ledGreen, HIGH);
  }
  if(Serial.available() == '101') {
    digitalWrite(ledBlue, LOW);
  }
  if(Serial.available() == '102') {
    digitalWrite(ledBlue, HIGH);
  }
  if(Serial.available() == '103') {
    digitalWrite(ledYellow, LOW);
  }
  if(Serial.available() == '104') {
    digitalWrite(ledYellow, HIGH);
  }
}

I think that code won't compile; it should get error messages about invalid character constants like '97' ... '104'.
Either take away the single-quote marks so that you match against numbers (representing ASCII characters), or, better, substitute valid character constants like 'a', 'b', ... Also, as noted in answer, use Serial.read() to get actual data instead of number of buffered characters

Adding comments to your code would help us understand your intentions.
It is assumed you are sending the ASCII values for 'a', 'b', 'c', ... for different buttons and their actions.  And that you want to receive these on an Arduino over the USB using the USB serial port protocol. It is also assumed that your Python script works and the Linux OS is creating a /dev/ttyACM0 or some such serial device when you plug in your Arduino.
Looking at your Arduino code we see you are only checking for the number of bytes in the Arduino's serial port receive buffer by using the Serial.available() method call.  If your intentions were to read a byte of data you would instead call the serial.read() method.
It is suggested that you check if there is any data available and if there is you would read it once and save it to a variable. Then you can check this variable many times and decide what action to take based on its value.  If you read the buffer many times you would be pulling a new byte of data from the buffer with each read.  If you run out of data to read you will be supplied with the value of -1 as an indication there is no more data.

  if(Serial.available() == '97')

Make sure the comparison is actually valid and Serial.available() does what you think it does. If you wish to read a value from serial port, .available() doesn't seem to be the right function for that.

I think the author of this answer asked this question to direct attention to the validity of the comparison not to get an answer.


text:
Using both a stepper motor and a DC motor with Arduino motor shield R3
We are trying to reprogram a remote control car with an Arduino Uno. This car runs the power with a DC motor, and it controls steering using a stepper motor.
We have the Motor Shield R3 attached to the Arduino, but it has just now occurred to us that we can't support both motors with the motor shield (as the motor shield only allows for two DC motors or one stepper motor). Is there a way to somehow work around this? Or is it possible that we would need to replace the stepper motor with DC?

You are right: Motor Shield R3 can drive two DC motors or one step motor. So, there are 2 (maybe  3) solutions:
1. Have another shield - now you can drive 2 step motors, or one DC motor(using 'half' of shield, and one step motor using another whole shield.
2. Replace your step motors with DC motor. This option can be more complicated, as no precise position control will be possible when you try to use DC motor for steering. (DC motor are hard to select and hold position, when stepper motors are quite easy to 'go to certain position' AND 'hold'). There is also good mechanical skill needed to remove/place it precisely.
optional option 3. Instead of Motor Shield R3 you can try to use cheap Easy Driver to drive your step motor.

authors: Мимо Траходил


text:
SocketIO Arduino TCP Port ISSUE
Initially I was sending sensor data to NodeJS using socketIO and this worked perfectly. I had to add a function to control an RGB LED using this. This also works but I'm unable to perform these two functions simultaneously.
I have tried to use two different ports on my Arduino. One to send data and another to control the LED but one overrides the other.
Question: Is there a way around this ? Is it practical to use two different ports?
arduino sketch
if (client.connect(server, 4000)) {
    Serial.println("connected");
  }
  else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }

  pinMode(pin, OUTPUT);
}

void loop()
{

  //if you are connected and data is available
  if (client.available()) {
    char c = client.read();
   // Serial.print("Message is :  ");
    Serial.print(c);

    // '1' was received, return '1' for HIGH
    if (c == '1') {
      pinVal = HIGH;
    //  client.print("ON");
    }
    else if (c == '0') {
      pinVal = LOW;
    //  client.print("OFF");
    }

    //turn led pin to new position
    digitalWrite(pin, pinVal);

  }

int chk = DHT.read11(DHT11_PIN);
  int t = DHT.temperature;
  int h = DHT.humidity;

          // send data to the server
        sendData(t, h);

  Serial.print("Temperature = ");
  Serial.print(t);
  Serial.print( "," );
  Serial.print("Humidity = ");
  Serial.print(h);
  Serial.print("\n");
   delay(6000);

}

void sendData(int temperature, int humidity)
{
  if(!client.connected())
  {
    if (client.connect(server, 3000)) {

      Serial.println("Sending data...");
      // send the HTTP PUT request:
      client.print("GET /weatherserver/");
      client.print(temperature);
      client.print("/");
      client.print(humidity);
      client.print("/");

      client.println(" HTTP/1.1");
      client.println("Host: localhost");
      client.println("User-Agent: arduino-barom");
      client.println("Connection: close");
      client.println();
      client.stop();
    } else {
       Serial.println("Could not connect.");
       client.stop();
    }
  }
  delay(6000);
}

I'm not sure what you are doing, but you seem to be using two different protocols on two different ports.  So does you server side code open two ports? and does it accept the two different protocols?
If I was you I would change the RGB control to use REST (like you are doing with the DHT)  So you would send something like GET /RGB/<id>/<state>.
I'm not sure how your temperature is arriving at the server since you have sent a GET command rather than a PUT command (this could be the bug you are looking for).

Thanks for responding. This is how i'm sending my temperature to my server. However you're right I am using two different protocols on two different ports. My server accepts two ports perfectly. But my Arduino doesn't initiate both connections. From my server side i'm sending my commands to the LED using a TCP protocol. Do you think if I change this I can achieve my goal? Do know if any documentation that shows how I can implement this?

I'm trying to implement you solution you suggested. I really can't find anything to help. Would you be kind to show me a link that could guide me?

This page explains what to do, it has all the code you want, but it is not doing exactly what you want, it should help you understand though.  https://learn.adafruit.com/a-rest-api-for-arduino-and-the-cc3000-wifi-chip/overview I don't know if you can open two sockets, but even if you can I don't think the temperature will work because you are using GET, you should use PUT, you'll understand why when you read the link.

Thanks Matt! I believe I mentioned in my post that I'm using NodeJS. However your solution isn't related to the NodeJS platform. That being said, I thank you for taking your time to help. I was able to find a better solution.

I implemented a better solution differentiating the client as EthernetClient clientA & EthernetClient clientB

Client A handles TCP port and Client B handles HTTP GET Request.


text:
Arduino Mega prototype analog timer interrupts: newbie question
I am currently using an Arduino Mega with a fast vibration sensor to trigger the components operation (force sensor, temperature sensor) and also toggle sleep mode.
I am very new at this and I have been doing some googling, but I just can't seem to understand it.
So, my questions are:

How would I toggle(on/off) sleep mode?
How would I use interrupts (timer, pin change interrupt?) for an analog pin that triggers when the vibration sensor is triggered, resulting in other components operating?

I am currently working on a Mega, but I will eventually move on to the Arduino Mini Pro. I hope there are no exclusive problems later on.
I realize that this is not a professional question, but I find these tasks very challenging.
Please help me. An example link or perhaps example code to help me understand better.
Thank you very much.

What do you mean by “an analog pin that triggers when the vibration sensor is triggered”?

so when the vibration sensor gets triggered, then then the analog pin goes out of sleep mode(or the entire board goes out of sleep mode) and the analog pin will start getting inputs from external components in a specific frequency (how much is the analog reading [every 15 sec ])

You don't sleep an analog pin, you sleep the CPU. Given your current understanding level, you should really forget about your project for now and focus on learning the basics. Then go through tutorials about sleep mode and interrupts. If you get stuck on your learning process, you can use this site to ask focused questions. Once (and only once) you are comfortable with all that material, you can come back to your original project. You want to run an obstacle course: you should first learn to walk.

How would I use interrupts (timer, pin change interrupt?) for an analog pin that triggers when the vibration sensor is triggered, resulting in other components operating?

Thee best and most authoritative answer to that and all your other questions about the chip can be found in thee device data sheet and the compiler manual. Read them thoroughly and then write code to the data sheet to experiment.
Your can fire example have an analog interrupt where the chip constantly does ADC on the pin attached to the sensor and you can test the value of the ADC to see if certain trigger conditions are met and take appropriate actions.
The same with timers, etc. The data sheet is your best friend.


text:
Issue with Arduino Timing
I am working with an Arduino on a project for which timing is very important. I use TimerOne to trigger timer interrupts and use micros() for delays (delayMicroseconds() was causing problems worse than the one explained below). The program is sending a manual PWM signal to an LED and it is very important that the signal is sent with an error that is less than 8 microseconds (ideally, the signal is sent at the same time in each period). My test code is shown below:
#include <TimerOne.h>
#include <SPI.h>

const int LED_PIN = 3;
const int CHIP_SELECT = 12;

const int PERIOD = 4000;
const double DUTY_CYCLE = .5;
const int HIGH_TIME = PERIOD * DUTY_CYCLE;
const int LOW_TIME = PERIOD - HIGH_TIME;
const int INITIAL_SIGNAL_DELAY = LOW_TIME / 2;
const int HIGH_TIME_TOTAL_DELAY = INITIAL_SIGNAL_DELAY + HIGH_TIME;

const int RESISTOR_VALUE = 255;

boolean triggered = false;
boolean data = false;

unsigned long triggeredTime;
unsigned long s;
unsigned long e;

boolean found;
int i = 0;

void setup()
{
  s = micros();

  Timer1.initialize(PERIOD);
  Timer1.attachInterrupt(trigger);

  pinMode(LED_PIN, 3);
  pinMode(CHIP_SELECT, OUTPUT);

  SPI.begin();

  digitalWrite(CHIP_SELECT, LOW);
  SPI.transfer(B00010001);
  SPI.transfer(RESISTOR_VALUE);
  digitalWrite(CHIP_SELECT, HIGH);

  e = micros();

  Serial.begin(115200);
  Serial.print("s: ");
  Serial.println(s);
  Serial.print("e: ");
  Serial.println(e);
}

void loop()
{
  if(triggered)
  {
    while(micros() - triggeredTime < INITIAL_SIGNAL_DELAY)
    { }
    s = micros();
    digitalWrite(LED_PIN, data);
    while(micros() - triggeredTime < HIGH_TIME_TOTAL_DELAY)
    { }
    digitalWrite(LED_PIN, LOW);

    data = !data;
    triggered = false;

    e = micros();
    //micros();

    if(s % 100 > 28 || s % 100 < 12)
    {
     found = true;
    }

    if(!found)
    {
      Serial.print("s: ");
      Serial.println(s);
    }
    else
    {
      Serial.print("ERROR: ");
      Serial.println(s);
    }
    //Serial.print("e: ");
    //Serial.println(e);
  }
}

void trigger()
{
  triggeredTime = micros();
  triggered = true;
}

(it should be noted that the first signal sent is always xx20, usually 5020).
So, with this code, I eventually get an error. I am not sure why, but this error occurs at the same point every single time:
.
.
.
s: 1141020
s: 1145020
s: 1149020
ERROR: 1153032
ERROR: 1157020
ERROR: 1161020
.
.
.

Now, the really weird part is if I remove the comments before micros() (the micros() right after e = micros()), there is no error (or at least there is not an error within the first 30 seconds). I was wondering if anybody could provide an explanation for why this happens. I have dedicated many hours trying to get the timing working properly and everything was working well until I encountered this error. Any help would be very much appreciated. Thank you!

Why not set up a timer interrupt to trigger every 8us then instead of depending on the Arduino timing routines to possibly get it right?

My apologies, perhaps I was unclear about the intention of my code. The signal is supposed to be sent once every 3 milliseconds. The time at which it is sent within each cycle should be the same, though (with a maximum deviation of 8 us). Also, I found that if I do not print s on every cycle, the problem goes away. I was wondering if anyone knew why this fixes the problem.

Fair enough. But replacing 8us with 3ms in my comment should fix that.

That was actually how my initial code was structured. Arduino does not work well with long interrupts, unfortunately,  and that was causing sporadic behavior (the interrupt would have to be able to be 1.5 milliseconds long)

The Seiral library uses interrupts, so will jitter the timings of other interrupts. This may or may not cause your error message, but it will mess up your other timings. If I rely on interrupt timing, and I need the UART for debug, I don't use Serial, but hit the hardware UART with single byte writes from within my sole interrupt routine (after it's done what it's meant to do) so only one thing is in charge of timing.

I don't understand from the code or the problem statement exactly what waveform you are trying to generate, but have the impression that it can be generated using timer 1 pwm.  Note that micros() resolution is 4 μs which eats up a lot of your ±8 μs tolerance, and the busy waiting adds jitter as well.

Your whole post makes little sense to me. You set up the timer to interrupt every 4 ms, but you send a signal only every other interrupt (because of data = !data). Thus you signal period is 8 ms, whereas in the comments you state you want a period of 3 ms. Why don't you rewrite your question clearly stating what you are trying to achieve? Please, describe precisely the shape of the waveform you want to generate. Your best bet is probably to configure Timer 1 as PWM. If you really want a 3 ms period, you can set the prescaler to 1 and have single-cycle resolution.

Don't cross post questions

the code flow doesn't make a lot of sense to me. seems to me that you can simplified quite a bit.

if(s % 100 > 28 || s % 100 < 12)

I would use a few brackets to make it clear to the compiler what you want it to do.