text:
Jumping to bootloader from application code in atmega328p
I'm trying to program an Arduino Uno (atmega328p) using only the serial Tx/Rx lines (no DTR, so no automatic reset). This is so I can upload code via WiFi/TCP using an ESP-01.
To achieve this, I need to Arduino sketch/application to reset itself (and run the bootloader) whenever it sees avrdude trying to upload code (e.g. when 0 0  appears in the serial port).
I've tried a few approaches to jumping to the bootloader from application code but had no success so far.

Using the watchdog timer

void reset_to_bootloader() {
    // see 11.2.2 MCUCR – MCU Control Register
    // Enable change of interrupt vectors
    MCUCR = (1<<IVCE);
    // Move interrupts to Boot Flash section
    MCUCR = (1<<IVSEL);

    // enable watchdog timer
    wdt_enable(WDTO_30MS);

    // block waiting for the watchdog to timeout and jump to the bootloader
    while(1);
}

Unfortunately, the datasheet[1] mentions the IVSEL bit is not available in atmega328p, so even though this compiles, it simple resets the MCU and the bootloader does not run.

Jumping to the bootloader address directly

There is a table in the datasheet (Table 26-7. Boot Size Configuration, ATmega328P) that specifies the bootloader start address for the 4 supported bootloader section sizes, which are configured by the BOOTSZ fuse.
I have read the fuses and confirmed the bootloader section is 512-bytes (256 words) long.
Therefore, according to the datasheet, the Boot Loader Flash Section is 0x3F00 - 0x3FFF. So, the start of the bootloader should be at word-address 0x3F00.
I have even dumped the whole 32768-byte flash off the MCU and confirmed the bootloader is at byte-address 0x7e00, which matches the expected word-address 0x3F00 (0x7e00 / 2 = 0x3F00).
I have tried a couple methods of jumping to address 0x3F00. Here's a few. None of them seem to work. They just reset the MCU and the bootloader doesn't seem to run.
void jump_to_bootloader() {
    size_t bootloader_addr = 0x3F00;

    void (*bootloader_ptr)() = (void (*)())(bootloader_addr);

    SREG = 0;
    wdt_disable();
    bootloader_ptr();
}

void jump_to_bootloader2() {
    asm volatile ("ijmp" ::"z" (0x3F00));
}

Jumping and updating the value of MCUSR

I then realised the bootloader[4] checks the reset source and only runs on an external reset:
ch = MCUSR;
if (! (ch &  _BV(EXTRF))) // if its a not an external reset...
    pp_start();  // skip bootloader

So I tried faking it before jumping, but it didn't work either:
    MCUSR = _BV(EXTRF);
    asm volatile ("ijmp" ::"z" (0x3F00));
}

Any help is appreciated. Thanks in advance!

edit:

Jumping to after the bootloader checks the reset source

Following @Edgar Bonet's suggestion, avoiding the if (!(ch & _BV(EXTRF))) appStart(); check in the bootloader by jumping to the instruction that follows it:
void jump_to_bootloader2() {
    // the bootloader assumes these are true:
    cli();
    SP = RAMEND;
    SREG = 0;
    MCUSR = 0;
    asm volatile ("eor  __zero_reg__, __zero_reg__");
    asm volatile ("eor  r1, r1");
    // jump to after the bootloader checks the reset source
    asm volatile ("ijmp" ::"z" (0x7e0au / 2));
    while(1);
}

I could see it entered the bootloader (LEDs flashed a couple times), but avrdude was not able to upload code.
The bootloader sets up a watchdog timer (WDT), so I'm suspecting avrdude waits for to long after sending the initial 0 0 0  and since the bootloader does not see anything on the serial port the WDT resets it.

References:

[1] AVR Instruction Set Manual: http://ww1.microchip.com/downloads/en/devicedoc/atmel-0856-avr-instruction-set-manual.pdf
[2] atmega328p datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
[3] random forum thread I have also read: https://www.avrfreaks.net/forum/jump-bootloader-app-help-needed
[4] bootloader code: https://github.com/sparkfun/Arduino_Boards/blob/805def002e815509032fde37a674d2916af8aecc/sparkfun/avr/bootloaders/atmega/ATmegaBOOT_168.c#L299-L307

I don't see any way of doing this if the UNO is running optiboot. The only options I see is to slightly change, compile, and flash a new bootloader on the UNO. Or connect one of the Arduino pins, or one of the ESP pins to the UNOs reset pin.

The source of Optiboot on Uno is here.
I would prefer a simple watchdog reset with
  wdt_enable(WDTO_15MS);
  while (true);

But I am not sure now if it runs sketch upload detection in bootloader.
For direct jump to Optiboot on Uno (one flash page) this should work
typedef void (*bootloader_jump_t)();
const bootloader_jump_t bootloader_jump = (bootloader_jump_t)((FLASHEND-511)>>1);

and then you can call bootloader_jump();
EDIT:
while the Optiboot 4 on Uno from factory doesn't check for new upload after watchdog reset or direct jump, Optiboot 8 has checks to handle this right

It appear the new UNOs use the optiboot bootloader. Optiboot check if the reset button is pressed (or reset it pulled low via the DTR signal), and if not, will runs your sketch immediately (removing the 3 second delay). So I don't think these pieces of code will work.

@Gerben, Uno always used Optiboot. version 4 as bundled with the core package

Thank you for the reply.
((FLASHEND-512)>>1) gives 16127, which is 0x3EFF. The bootloader starts in the next flash word (0x3F00), so I don't think jumping to 0x3EFF will work. And, as I said, I already tried jumping to 0x3F00. :/

@Nuno, sorry. jumping to 0x3F00 with Optiboot 8 will work. https://github.com/Optiboot/optiboot/blob/6f98751c6d184ec4a9c7f1fe0f0dcf12f9db2cc9/optiboot/bootloaders/optiboot/optiboot.c#L628

@Juraj I see, if I change the bootloader to Optiboot 8 it may work. Thanks! I'll give it a try when I have some free time. I'm not sure if the bootloade can replace itself, so it'll take a little more effort as the arduino pins for SPI flashing are currently inaccessible.

@Juraj I changed the bootloader to Optiboot 8 with a timeout of 4s (2s didn't work) and then used the WDT to reset to bootloader and it works ;) Many thanks!

Maybe you could jump to right after the line
if (!(ch & _BV(EXTRF))) appStart();

Here is an excerpt of the disassembly:
  if (!(ch & _BV(EXTRF))) appStart();
    7e06:   81 ff           sbrs    r24, 1
    7e08:   f0 d0           rcall   .+480       ; 0x7fea <appStart>

#if LED_START_FLASHES > 0
  // Set up Timer 1 for timeout counter
  TCCR1B = _BV(CS12) | _BV(CS10); // div 1024
    7e0a:   85 e0           ldi r24, 0x05   ; 5
    7e0c:   80 93 81 00     sts 0x0081, r24

The conditional call to appStart() is made by the instructions sbrs
and rcall. The instruction right after that is the ldi at byte
address 0x7e0c (word address 0x3f05). I would try jumping right there.
You won't miss much:

eor r1, r1 is not needed when jumping from C++, as the value of r1
is already enforced by the compiler as per the ABI.
in r24, 0x34 reads MCUSR into a register that is clobbered right
away
out 0x34, r1 clears MCUSR; if this turns out to be useful, you
could do it right before jumping to the bootloader.

You may want to check that the bootloader you have matches the
disassembly I linked to.

Thanks! Indeed, my dumped flash matches at least the 4 lines of the excerpt you quoted. I tried jumping to 0x7e0au / 2, which is right after the check for the EXTRF bit. I tried this and I could see the bootloader blinking the LEDs but avrdude was not able to sync. :/
I've updated the original question with this (see 4. Jumping to after the bootloader checks the reset source).


text:
does eeprom_write_block function of avr.eeprom.h writes a NULL terminated string or we have to manually null terminate it
http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html
I am trying to figure out that if we use eeprom_write_block function or eeprom_update_block function do we need to manually null terminate it?
I came across this tutorial on avr-freaks where in one comment it is said that you have to read the strings and null terminate them but there is no word about writing. Couldnt get anything the avr-libc manual as well.
UPDATE
I have reserved some parts of eeprom using EEMEM  and they are strings. I am not sure how long the string would be except that it would be smaller than a max value. Now When I would read the string back from the eeprom I would just be reading the maximum number of bytes as again I would have no idea of the size of the string. If the eeprom has a null value at the end of the string when writing to it, the read string will have that null at the correct place.
Situation
I am saving mobile numbers of users as:
uint8_t EEMEM users[numberOfUsers][maxChar4Number];

Now when I get a number parsed and then save it to eeprom
#define eepu(message, EEADDR, BLKSIZE) eeprom_update_block((const void *)message, (void *)EEADDR, BLKSIZE);

eepu(user, users[0], strlen(user)); //strlen(user) will be less than the maxChar4Number

This will write the number to eeprom. When I read the i would be reading maxChar4Number bytes and a number could have been shorter than that length.

If you write a block which happens to be null-terminated, then reading it back should be fine. I do that when I want to save a filename in EEPROM. Just declare a suitable length (allowing room for the null terminator) and write the entire block to EEPROM.

Since one normally does not know how long a character string is, we need a way to convey this information.  One technique used to avoid confusion is to add a NULL character (which is a zero) to the end of the string.  Another is to explicitly state how long the string is.
In the case of the function eeprom_write_block() talked about here, we see that we are formally passing not only a pointer to the string but also the size of the string.

I am using   eeprom_read_block((void*)&settings, (void*)0, sizeof(settings));. it has the size argument . do I need to Null terminate??

I have reserved some parts of eeprom using EEMEM  and they are strings. I am not sure how long the string would be except that it would be smaller than a max value. Now When I would read the string back from the eeprom I would just be reading the maximum number of bytes as again I would have no idea of the size of the string.

I would think you do not need a NULL at the end of your character string for the eeprom_read_block() method as you are telling it how many characters you are reading.  I don't think you need it for the sizeof() method call either as sizeof() uses the type of the argument.  That said, I believe you will always read the size of your array number of characters from EEPROM.  Is that what you want?

source: Stack Exchange

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

sort: votes


text:
Code is supposed To extract data between * ie *989*= 0989*; Runs only once then doesn't please help
void loop() {
       char *stptr=&string[0];
       if(Serial.available() > 0)
       {
          data = Serial.read();
          if(data=='*')
          {
            ib=1;jb=0;
            string[0]='0';
            //Serial.print("GOT INTO IF");
            while(string[ib-1]!='*')
            {
              //Serial.print("Got into reading while");
              //Serial.print(string[i]);
              if(Serial.available() > 0)
              {
                if(string[ib]!='*')
                {
                  string[ib]=Serial.read();
                  ib++;
                }
              }
            }
         }
      }
}

Please put your code in a code block so it is readable.

Do you seriously need those commented lines?

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  State a question and a context clearly in the body of the post, rather than just vaguely hinting at it as in the title.

Something like this should work:
void loop()
{
    char *stptr = string;
    if (Serial.available()) {
        data = Serial.read();
        if (data == '*') {   // Check for starting *
            *stptr++ = '0';  // Copy '0' to string

            // Loop until: no data in port, or second * received
            while (Serial.available() && '*' != (data = Serial.read())) {
                // Copy to string
                *stptr++ = data;
            }
            // Terminate string
            *stptr = '\0';
        }
    }
}

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


text:
Can both the 3.3V and 5V pins on the Arduino be used at once for power?
I'm supplying power to Arduino via PC USB.

Yes.
Here's a block diagram of how the Arduino power is arranged:

As you can see the USB power is fed through a FET (P-channel MOSFET) to isolate it when there is external power applied (as decided by the comparator COMP).  External power is fed through a 5V regulator and is fed to the same point as the USB power.  Thus you get the same 5V at the same point regardless of if you have USB or Barrel Jack power.  From there the 5V (wherever it comes from) is fed into a 3.3V regulator.  The 5V pin on the Arduino is connected directly to the 5V point where the USB and the 5V regulated input are connected. The 3.3V pin is connected directly to the output of the 3.3V regulator.
So no matter what input power arrangement you use - barrel jack, USB power, battery connected to the V IN pin (not shown, but connects to the barrel jack), or regulated 5V into the 5V pin, you get access to the same 5V and 3.3V power on the 5V and 3.3V power pins.


text:
MPU-9250 : How to convert pitch (+90/-90) to 360 degree?
I'm using Arduino Uno with MPU-9250 to find roll, pitch and yaw.
Everything works fine but I want to covert pitch from (+90/-90) to 360 degree.
I'm using this code:
vec.setX(atan2(2.0 * (m_data[2] * m_data[3] + m_data[0] * m_data[1]),
        1 - 2.0 * (m_data[1] * m_data[1] + m_data[2] * m_data[2])));

vec.setY(asin(2.0 * (m_data[0] * m_data[2] - m_data[1] * m_data[3])));

vec.setZ(atan2(2.0 * (m_data[1] * m_data[2] + m_data[0] * m_data[3]),
        1 - 2.0 * (m_data[2] * m_data[2] + m_data[3] * m_data[3])));

m_data[0] = scalar;

m_data[1] = x;

m_data[2] = y;

m_data[3] = z;

What should I do?

I assume you want to map the range -90...-1 to 270...359 and the range 0...90 to 0...90?
It's simple enough:
if (angle < 0)
    angle = 360 + angle;

Note that you are adding the negative value to 360, which is the same as subtracting the positive value.
Or do you want to map it so that -90 is 0 and +90 is 360?  In that case you need to offset and scale it:
angle = angle + 90; // Angle is now 0..180
angle = angle * 2; // angle is now 0...360

Or in one line:
angle = (angle + 90) * 2;

this answer is completely wrong. In the first case you are creating something that will range from 0 to 90 and then from 270 to 360. In the second case, adding 90 and multiplying by two will create a 0 to 360 range mapped to a 180 degree movement, meaning that every degree the accelerometer rotates in that axis will result in a 2 degrees output.

@SpaceDog You are saying that it is wrong, then proceeding to say that it is wrong because it does what it is designed to do. I don't understand how that can be wrong. In case 1 yes it is intended to range from 0-90 and 270 to 360. In case 2, yes, it is intended to range from 0-360 in 2-degree steps. Given the vagueness of the question the two interpretations of what is wanted are perfectly reasonable, and the two cases given (which you have confirmed in your "it is wrong") are correct solutions to them. If it is wrong at least say why it is wrong, not why it is right.

it is wrong because the poster probably needs the pitch to be from 0 to 360 degrees in 1 degree step. What I mean is this: suppose the rotating object rotates just along the pitch axis, I mean, the object does a 360 degrees pitch axis turn. Supposing the object is at 0 degrees when it started it will go 0 → 90 → 0 → -90 → 0. Look at this in a graph it will appear that the object rotated from 0 to 90 and back to 0 but in fact the object continued to rotate in the same direction. This is probably the reason why it would be nice to get a scale where you can represent the real movement.

@SpaceDog You are reading things into the question that aren't there, and ignoring things that are there. The pitch only goes from -90 to +90. How can it be doing a 360 turn if it only goes from -90 to +90? If it goes past 90 in either direction it's upside down and will plummet to earth. At that point the resolution of your data is the least of your worries.

what about a loop? Isn't a loop a 360 pitch revolution?

@SpaceDog Again you are making dangerous assumptions. Not all devices will be able to make a loop. At least not without incredibly clever flying. It takes an amazingly good pilot to do a loop in a helicopter for instance. The only person able to judge if this answer has made the correct assumptions is the person asking the question. The person asking the question has said the answer is correct, so the assumptions made in the answer must therefore be correct.  You are basically saying that you know better than the OP what the OP is asking, which is mighty presumptuous of you.

@SpaceDog Besides: THE OP STATES -90 TO +90!  If it was doing a loop they wouldn't state that. They would state -180 to +180!

The equations in you example convert a quaternion representation of rotation into euler angles correctly; The "pitch" euler angle only has a valid range of +90/-90 and changing it will make your angular representation invalid.
Euler angles specify an arbitrary rotation by 3 consecutive turns. You may want "apparent angle with the horizon", which is not the same thing, and does not define a sequential set of turns to get from rotation A to B.
To get pitch and roll with the horizon from a quaternion, I think you want something like:
float x = 2*m_data[1]*m_data[3] - 2*m_data[2]*m_data[0];
float y = 2*m_data[1]*m_data[0] + 2*m_data[2]*m_data[3];
float z = 1 - 2*m_data[2]*m_data[2] - 2*m_data[1]*m_data[1];

float pitch = atan2(y,z);
float roll  = atan2(x,z);

I got this by rotating the vector <0,0,1> by the quaternion and then measuring the angles of the result around x and y axis. This kind of freaks out when one of the angles is close to 90 degrees though; there are probably better equations out there.
"Yaw vs the horizon" doesn't make any sense, and people usually want the same "style" of yaw you are getting from the euler angle equations, so that shouldn't change.


text:
How can I exactly put my sensor at 4 Hz readings?
I'm using the grove GSR sensor: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor with this code:
const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;
void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){
  int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;
  delay(250);
  }

There is the delay way to skip milliseconds or the millis() function. Do you have ideas on how can I implement it? The delay has the problem that doesn't consider the time the sensor uses to read the data.
Here's what I am trying
const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;
unsigned long startTime=millis();

void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){

  if((millis() - startTime) % 250 == 0) {
   int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;

  }
  }

The difference between your first code and the second one is that the first one is blocking execution when it reaches the delay function, but the second code keeps running without being blocked.
Now your algorithm has a drawback, the loop may or may not reach the if condition exactly when the modulo is strictly equal to 0. So you may prefer to use something like :
unsigned long T = millis();

...

if( millis() - T >= 250 ) {
    ... // sensor stuff
    T = millis();
}

This idea is also presented in this article https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.
Another approach is to use Timers and Interrupts, but this is far more complicated (http://playground.arduino.cc/Code/Timer1).

So the first code uses more time? I had this impression when I measured less than 7600 seconds of data and it turned out to be 8000.

Both other answers are correct, but my usual way of dealing with this is
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
...
void loop()
{
    if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        // Do your job, such as
        int temp;
        sensorValue=analogRead(GSR);
        Serial.println(sensorValue);
        temp = threshold - sensorValue;
    }
}

The difference between this way and the other ones (Nick's way, i.e. saving millis and setting the startTime variable to it, or nico's one - which is worse - , to set it again), is that this way if there is some error (e.g. 260ms between two calls) it gets recovered by the next cycle (which will be of 240ms), while in their way it is not.

+1. lastReading = now; is the most common, and also the most appropriate when you want to guarantee a minimum delay between readings. But lastReading += period; is the correct solution when you want to guarantee the correct average period.

Something like this should do it:
const byte LED = 13;
unsigned long lastReading;
const unsigned long INTERVAL = 250;

void setup()
  {
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop()
  {
  unsigned long now = millis ();
  if (now - lastReading >= INTERVAL)
    {
    lastReading = now;
    digitalWrite (LED, HIGH);
    delay (50);  // simulate reading delay
    digitalWrite (LED, LOW);
    }
  }  // end of loop

This code saves when we are about to do a reading, and uses that as the basis for when to do the next one. This eliminates the reading time from the equation. In my example code I throw in a 50 ms delay to prove the point.
The LED flashes exactly at 250 ms intervals.


text:
c expected ; before ) token
void GravaFicheiros(CONFERENCIA *co)
{

    int i, ii, iii;

    FILE *fp;

    fp = fopen("grabameisso", "wt");

    fprintf (fp, "%s\n", co->nomeconf);

    int k = NSessoes(co);
    fprintf (fp, "%d\n", k);

    for (i = 0; i < k; i++)
    {

        fprintf (fp, "%s\n%d\n%d\n", co->sessoes[i].tema, co->sessoes[i].hora, co->sessoes[i].auditorio);

        int a = NArtigos(co, i);

        fprintf (fp, "%d\n", a);

        for (ii = 0; ii < a; ii++)
        {

            fprintf (fp, "%s\n", co->sessoes[i].artigos[ii].titulo);

            int aa = NAutores(co, i, ii);

            fprintf (fp, "%d\n", aa);

            for (iii = 0; iii < aa, iii++)
            {

                fprintf (fp, "%s\n%d\n", co->sessoes[i].artigos[ii].autores[iii].nome, co->sessoes[i].artigos[ii].autores[iii].idade);
            }
        }
    }

    fclose(fp);
    return;

You did not actually ask a question. Please read How do I ask a good question. I'm going to close this question. Please put a little more effort into your "question" next time, such as actually asking one.

Although you didn't ask a specific question I assume you want to know why there was an error in your code.
One of your for loops is missing a semi-colon.

for (iii = 0; iii < aa, iii++) //this line gives the error

Should be:
 for (iii = 0; iii < aa; iii++) //the comma should be a semi-colon

When it says ; expected before token ). It means quite literally that there is a ; missing before a ).


text:
Difference between data type int and long on Arduino
I was learning to program for a void obstacle robot but when I looked at the code I saw two data types long and int.
Int are datatypes that holds  -2,147,483,648 to 2,147,483,647.
Long are also datatypes that holds -2,147,483,648 to 2,147,483,647.
Int and long are like same but I came up with the code where two types of datatype is used as seen below:
int trigPin = 2;
int echoPin = 4;
long duration, cm, inches;

But how can you know when to use which datatype? I searched a lot in the web but I didn't understand so can someone explain this to me please.

"Int are datatypes that holds -2,147,483,648 to 2,147,483,647" Where did you hear that?

On the Arduino (AVR models) an int is 16 bits, not 32 bits. Thus it goes from -32768 to +32767.
That is different from long which is 32 bits.

What are the widths of int and long on the 32-bit ARM Arduinos such as Due?

I think on the Due that an int is 32 bits, the same a long. See here for example.

According to the C language specification, int must be at least 16 bits or longer and long must be at least 32 bits or longer.
It is OK for a compiler to implement int as 32 bits or even 64 bits. It is OK for a compiler to implement long as 64 bits or longer. But it is not allowed for a compiler to implement long as 16 bits.
So when to use which type?
If the values you will be working with can be represented within 16 bits then it's OK to use int. If you need more than 16 bits use long. If you need more than 32 bits use long long.
Do not be caught up with compiler and/or CPU specifics. As mentioned by others, even within the same product range, Arduinos, there are 16 and 32 bit CPUs available. Instead, only trust what the standard guarantees.
The full specification of types in C are:

char must be at least 8 bits
int must be at least 16 bits
long must be at least 32 bits
long long must be at least 64 bits

Note: It is perfectly legal for compilers to implement char, int, long and long long as 64 bits. This is in fact not uncommon among DSPs.

Also: Read your compiler documentation

And: sizeof(char) <= sizeof(int) <= sizeof(long) <= sizeof(long long) according to standard. So, if int is 64 bits, then long must also be at least 64 bits.

int in AVR GCC is 16 bits, not 32.

It's the same reasoning as in C: the size of the int type is expected to be the natural word size that your system handles most efficiently. It must also be at least 16 bits wide, no smaller than a short, and no larger than a long.
So an int may be 16-, 32-, or 64-bits, based on the whatever your system handles best, and so is most likely to be 16 bits wide on an 8- or 16-bit CPU, 32 on a 32-bit CPU etc.
I use int when I want the best performance, whilst taking care to guard when I need more range than offered by 16 bits. These days, you tend to know when you are writing application code for 16-bit systems, although that's not so true for "library" code where portability may be of greater concern.
In your example, assuming the author had chosen their types carefully, the int variables probably require a small range and could afford to be word-size, leading to potentially shorter or faster code (or both). The long ones presumably required more than 16-bit range (they are guaranteed to be at least 32 bits wide). On the processor you'd selected as a compilation target, it looks like int and long were both implemented as 32-bit; this would be different (or should be) if you selected a 16-bit target CPU.

I like to use types from stdint.h.
While they do have minor drawbacks, the benefit they provide is you know exactly the size your are handling, even when compiling on other architectures.
#include <stdint.h>

uint8_t  my_byte = 0xf0;
int16_t  trig_pin = 2;
int16_t  echo_pin = 4;
uint32_t duration, cm , blah;
uint64_t big_int;

// etc.

But obviously you don't want to be moving around a bunch of int32_t when your data only needs int16_t.

So not using machine word size does not impact performance on AVR?

@René - Generally not using word size can impact performance on most CPUs.  But traditionally AVR CPUs have 8bit registers & accumulators with some 16 bit instructions for pointer operations.  So when I program, I get the code running first, then optimise for speed if it's too slow.

@René - But if you really want to be pedantic about it, you could use word as your data type.  This is 16 bits on Arduino Uno, and 32 bits on Arduino Due & Zero.  But this comes back to the problem of really only knowing the minimum size of your data type.  Say you use word on some Due code, but then want to back-port to Uno?!  Using uint32_t instead would solve this problem before it starts, but yes it will be word-size sub-optimal on Uno.   What about future Arduino boards ... what word size will they have? 32? 64? 128!?

OK. So I would use the machine word size (int? WORD seems to be an obselete windows type definition) if the lower limit is sufficient, I do not care about memory size and need the speed, *_t if I care about size?

scrap that ... http://www.gnu.org/software/libc/manual/html_node/Integers.html says *fast*_t seems to be the way to go ...

@René - Yes.  Also when you pack structures, make sure you pack all the variables to word-sized boundaries.  So full-sized words at the top, any single chars or bools at the bottom.

if you are using Esp32 boards in Arduino IDE:

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


text:
Cameras modules for my project
I would like to implement a camera to my Arduino project.
So far I have worked with some sensors (e.g. distance), Wifi and Bluetooth modules, buzzer etc. You can find some very good examples on the web on how to use these things on your project, from the wiring to the sketch.
But when we talk about cameras, I feel like things start to be more difficult - I don't know if it's because camera users should know better what they are doing and therefore don't need a step by step guide, if simply there is a lack of information.
I see myself like this guy and this guy. We just can't find a tutorial!
I'm looking forward to buy a VGA OV7670 AL422 FIFO camera or a Serial TTL JPEG with NTSC video, but I don't want to spend my money on something I won't be able to use.
There is any better camera I could buy (by better I mean an easier camera to start working and with some information for the implementation)?
Thank you.

An arduino really isn't a very good platform for camera projects - limited goals involving still or slowly updated images are possible but tricky and it isn't even remotely cost effective.  If you want to do something with a camera, get a low end embedded linux platform and a cheap webcam, or find an outdated Android phone.

Is there a particular reason why you want to specifically use an Arduino to use a camera?
There are ressources out there: haven't proofread in depth, but this example using a MSP430 launchpad looks good.
Also a good excuse to give Energia & launchpads a try, if you only know Arduino.

Funnily enough there is another question about cameras and the Arduino.

I am using this camera, it has an OV568 on board. Getting a photo takes a few seconds, on the UART, which is slow, but could probably sped up if I change the baud rate. But for now I don't need to fiddle with that. Also the image is a JPEG, and what can you do with that in an Arduino? In my little project, it doesn't matter, the Arduino passes the data along to a computer, which handles it. No problemo.
But as a proof of concept, I used the JPEGDecoder library to display the photo on my Arduino Mega, with a small 2.2" TFT screen. If takes between 50 to 60 seconds to decode the JPEG and display it on the screen. And that JPEG was in an array, not even on an SD card. Gasp.
So depending on what you're looking into, you might want to rethink the whole idea. You'd be better off with a Raspberry Pi or a Beagle. Arduino won't cut it. There may be some 32-bit MCUs, like the Chipkit series, that could provide a performance boost.

Take a look at the Arducam mini (http://www.arducam.com/tag/arducam-mini/)
I just made a custom Arduino based PCB using this camera and it works great.

I am currently experimenting with this module: http://www.uctronics.com/mega-pixel-camera-module-mt9d111-jpeg-out-p-227l.html
I2C connection and supplies are working fine with an Arduino Uno, but getting the image data with an Arduino might be not possible.
You can slow down the Pixel Clock of this module to 375kHz, bit I think the  GPIO read-out speed (at least with the standard digitalRead functions) and memory of the Arduino are not sufficient...


text:
Are there flexible pressure sensors for Arduino that can measure forces of at least 600 lbs?
I'm in need of flexible pressure sensors that can read how much force is exerted on someone's foot while running (these sensors would be placed inside the shoe). Since pressure can often be three times the weight of the person, I need something fairly strong. Are there fairly cheap sensors that are available or hacks that could do the same thing?
Thanks!

As you are presumably measuring changing (dynamic) loads, you could consider a piezo electric sensor.
At the simplest, use a piezo element usually sold as a buzzer (make sure you get the plain element with no electronics included, some 'buzzers' also have drive circuitry).

That will give you a voltage pulse proportional to applied pressure, which might give you the precision that you need, and is very small and light to insert in a shoe.
See this question for a similar solution (and the above image!)

This could be a great method! Thanks for pointing this out, I will need to try this.

Sensors such as you describe are usually called "Load Cell".
At the 600 pound weight, I haven't found any "flexible" load cells. A sensor would have to be quite robust.
Flexible might not be the best answer.
This load cell page has quite a range of load cells, several thousand pounds, also not very inexpensive.
This might be difficult to install in running shoes :

... unless you have big futs.

Thank you! Hopefully I can find one that's thin enough that I can just cut a small portion out of the shoe. I heard that you can change how sensitive some of these sensors are so that they can measure up to 500 lbs. Check out what Im talking about here: http://forum.arduino.cc/index.php?topic=304657.0


text:
Use LED on pin 13 again after using the SD library
The question in short:
On an Arduino UNO or Nano using the SD library, is it somehow possible to use the LED on pin 13 (or any other pin that is used by the library) again after finishing all SD operations?
Detailed explanation:
In my sketch, during setup() I need to read some data from a file on the SD card, which is being closed again before leaving setup().
Now, I wanted to use the LED on pin 13 during loop() as a status indicator for the user, but it seems that after SD.begin(), pin 13 (and its LED) cannot be used as an OUTPUT anymore.
Here is a minimum sketch to show the behavior. It doesn't matter if I try to turn on the LED right after the call to SD.begin() in setup() or in loop():
#include <SD.h>
#include <SPI.h>

#define SD_CS  4
#define LED    13

void setup() {
  pinMode(LED, OUTPUT);

  // This still works:
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);

  SD.begin(SD_CS);

  // This does not work anymore:
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);
}

void loop() {}

It is possible to use the LED on pin 13 again by disabling the SPI bus that is used by the SD library to read/write data to/from the SD card. To disable the SPI bus, simply call SPI.end() after closing the file on the SD card.

Agreed. Betwen SPI.begin()  and SPI.end() the hardware takes over that pin.

Does anyone know, why the SD library has no .end()? Apparently you don't have to explicitly call SPI.begin() in your sketch, as SD.begin() seems to wrap this. So I think, a call to SPI.end() should also be wrapped in some complementary method like SD.end(). Should this be filed as a bug report/wishlist item to the library developers? Or is there any reason why there is no method like this?

Sounds odd to me. You could query it with the developers.

Any updates on your followup question @JohannesMaibaum?

@JaroslavZáruba: No, actually. I just checked the online reference for the SD library again, but still there is no SD.end() or similar. But simply calling SPI.end() worked and works for me.


text:
that no matter what the inputs are Motor1 always moves
int motor_forward1 = 7;
int motor_reverse1 = 6;
int motor_forward2 = 5;
int motor_reverse2 = 4;
int motor_forward3 = 3;
int motor_reverse3 = 2;
int sensor1 = A0;
int sensor2 = A1;

 void setup()
{

   pinMode(motor_forward1, OUTPUT);
   pinMode(motor_reverse1, OUTPUT);
   pinMode(motor_forward2, OUTPUT);
   pinMode(motor_reverse2, OUTPUT);
   pinMode(motor_forward3, OUTPUT);
   pinMode(motor_reverse3, OUTPUT);
   pinMode(sensor1, INPUT);
   pinMode(sensor2, INPUT);
 }

 void loop()
 {
   if (digitalRead(A0) == HIGH)
   {
     digitalWrite(motor_forward1,1);
     digitalWrite(motor_reverse1,0);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,1);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,0);
     delay(1000);
   }
   else if (digitalRead(A1) == HIGH)
   {
     digitalWrite(motor_forward2,1);
     digitalWrite(motor_reverse2,0);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,1);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,0);
     delay(1000);
   }
   else
   {
     digitalWrite(motor_forward3,1);
     digitalWrite(motor_reverse3,0);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,1);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,0);
     delay(1000);
   }
   delay(5000);
 }

Schematic here.

Could you add a little bit more than an un-formatted dump of code? Also circuit diagrams, possibly images... won't get closed then

@RSM before this I don't have any input and not using If else statement. My motor can rotate forward and reverse. after using if else statement my circuit not function correctly. How want to put image here?

An external link to the schematic is fine for now. I don't know why you're using a 5V regulator for each of the inputs - it seems a strange way of doing things. Proteus has some odd quirks, so pull each input to ground with a 10k resistor (between the switch and the Arduino) and see if that helps.

@RSM my push button in schematic circuit act as sensor. this software didn't have suitable sensor.

@CharlieHanson my sensor 5v at the input. my project using 2 sensor.

Be sure you if/else nestings are as you intend.

@RussellMcMahon I think switch/case and if/else most suitable in my project. I more understand using If/case. you have any idea about my project?

OK, that makes sense now, thank you. You say it doesn't function correctly - what does it do? It's very clear from the code what you want to happen, but we need to know what you're seeing. Update the question to say, for example, that no matter what the inputs are Motor2 always moves, or whatever it actually is.

@CharlieHanson my problem is when run the simulation and push the either button 1 or 2 only the motor1 always move. what I want in this project when push button 1 motor1 run forward and reverse and push button 2 the motor2 also run forward and reverse. the motor stop when the both button not push.

Looks like you use digitalRead to read analog pins A0, A1. Try changing to analogRead or using digital pins.

@tamberg I already change but it's didn't work. motor3 only run. I don't know what problem in my coding.

The code isn't wrong, it's far too simple to be at fault.
The error is from within Proteus. Those 'pushbutton' switches (and the other switch simulations) are not quite as straightforward as one would like. They have an OFF resistance, usually 100 Megaohms, but that's enough to trick the simulation into not behaving like it should do. You MUST pull the inputs to ground with a resistor - any sensible value will do as it's only required for the simulation. As they are, they're in some odd floating/magic/unknown state; common sense does not apply here!
An alternative is to swap the pushbutton for a SPDT switch; connect the common to the Arduino and the other contacts to the 7805 output and ground. You won't need the resistor in this case.

OK. Which code I need to use? mine code or need to replace "pinMode(sensor1, INPUT); pinMode(sensor2, INPUT);" to "pinMode(sensor1, INPUT_PULLUP); pinMode(sensor2, INPUT_PULLUP);"

I'd sick with the original code. Using INPUT_PULLUP will work but that places restrictions on the value of your external pulldown resistors. Nothing a bit of maths and datasheet-reading won't solve, but it's just extra work.


text:
Run a part of code upon call
Lets say I have something that sends a command to the Arduino (for example, a PC sending through serial, Ethernet, etc). I want the Arduino to "check" what command it is and run a specific function linked to that command.
I don't need a very explanatory answer, just give me something so I can learn from. A sketch that shows a similar idea would be good, I can try to interpret it and adapt/remake for me.
The idea is to use the Arduino for a lot of different things. Let's say:

Turn a bunch of leds on/off;
Read data from a sensor and send it through Ethernet/I2C/Serial;
Control a servo.

But I want the Arduino to do that when I tell it to (in this case, sending the command through serial, etc). So let's say I send it 1, I'll want it to run the 1 function (turning the LEDs on/off).
I already took a tutorial course on Arduino programming, but I'm clueless on how to do this job.

You might like to use my CLI library as a starting point: https://github.com/MajenkoLibraries/CLI

If you want it really barebones and easy, you can checkout the Arduino "Dimmer" example sketch.
Instead of changing the brightness of an attached pin, you could take the input you send it over the serial console and execute various functions, depending on what you receive.
Something like this:
boolean newCommand = false;
void setup()
{
  // initialize the serial communication:
  Serial.begin(9600);

  // other setup stuff here
}

void loop()
{
  byte command;

  // check if data has been sent from the computer:
  if (Serial.available())
  {
    // read the most recent byte (which will be from 0 to 255):
    command = Serial.read();
    // say that you received a new command
    newCommand = true;
  }

  // is there a new command?
  if (newCommand == true)
  {
    // do something depending on what command you received
    switch(command)
    {
      // if you receive command "1", do something
      case 1: functionWhatever();
              break;  // "break" out of the switch. otherwise it would continue executing the following commands as well
      case 2: functionWhatever2();
              break;
      //for cases that are not caught, send out an error
      default: Serial.write("invalid command");
              break;
    }
  }
}

If you want to use an existing library, you might want to check out:
EasyTransfer.
It can be used for communication between two Arduinos, which you then can use to execute functions on the other side of the line.
The code itself is relatively simple, so you might be able to adapt it to communicate with a processing script on your computer for example.

Thank you for your answer! The sketch was very clear, and the library seems like a good idea if I'm able to edit it... I'm thinking of connecting a Raspberry Pi and a Arduino via I2C. Would editing the library allow it?
I'll try to figure it out later

If you just want some example code, here is a smallish sketch I wrote that controls some LEDs via a shift register. Exactly how the shift register works isn't important, but you can see the basic idea for taking input from the serial port and decoding it:
#include <SPI.h>

const byte LATCH = 10;

const byte numberOfChips = 4;
const byte maxLEDs = numberOfChips * 8;

byte LEDdata [numberOfChips] = { 0 };  // initial pattern

void refreshLEDs ()
  {
  digitalWrite (LATCH, LOW);
  for (int i = numberOfChips - 1; i >= 0; i--)
    SPI.transfer (LEDdata [i]);
  digitalWrite (LATCH, HIGH);
  } // end of refreshLEDs

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 10;

void setup ()
{
  Serial.begin(115200);
  SPI.begin ();
  refreshLEDs ();
} // end of setup

// here to process incoming serial data after a terminator received
void process_data (char * data)
  {
  Serial.print ("Got command: ");
  Serial.println (data);

  // C: clear all bits
  switch (toupper (data [0]))
    {
     case 'C':
        {
        for (int i = 0; i < numberOfChips; i++)
          LEDdata [i] = 0;
        Serial.println ("All bits cleared.");
        refreshLEDs ();
        return;
        }

    // S: set all bits
    case 'S':
        {
        for (int i = 0; i < numberOfChips; i++)
          LEDdata [i] = 0xFF;
        Serial.println ("All bits set.");
        refreshLEDs ();
        return;
        }

    // I: invert all bits
    case 'I':
        {
        for (int i = 0; i < numberOfChips; i++)
          LEDdata [i] ^= 0xFF;
        Serial.println ("All bits inverted.");
        refreshLEDs ();
        return;
        }
    } // end of switch

  // otherwise: nnx
  //   where nn is 1 to 89 and x is 0 for off, or 1 for on

  // check we got numbers
  for (int i = 0; i < 3; i++)
    if (!isdigit (data [i]))
      {
      Serial.println ("Did not get 3 digits.");
      return;
      }

  // convert first 2 digits to the LED number
  byte led = (data [0] - '0') * 10 + (data [1] - '0');

  // convert third digit to state (0 = off)
  byte state = data [2] - '0';  // 0 = off, otherwise on

  if (led > maxLEDs)
      {
      Serial.println ("LED # too high.");
      return;
      }

   led--;  // make zero relative

   // divide by 8 to work out which chip
   byte chip = led / 8;  // which chip

   // remainder is bit number
   byte bit = 1 << (led % 8);

   // turn bit on or off
   if (state)
     LEDdata [chip] |= bit;
   else
     LEDdata [chip] &= ~ bit;

  Serial.print ("Turning ");
  Serial.print (state ? "on" : "off");
  Serial.print (" bit ");
  Serial.print (led & 0x7, DEC);
  Serial.print (" on chip ");
  Serial.println (chip, DEC);

  refreshLEDs ();
  }  // end of process_data

void loop()
{
static char input_line [MAX_INPUT];
static unsigned int input_pos = 0;

  if (Serial.available () > 0)
    {
    char inByte = Serial.read ();

    switch (inByte)
      {

      case '\n':   // end of text
        input_line [input_pos] = 0;  // terminating null byte

        // terminator reached! process input_line here ...
        process_data (input_line);

        // reset buffer for next time
        input_pos = 0;
        break;

      case '\r':   // discard carriage return
        break;

      default:
        // keep adding if not full ... allow for terminating null byte
        if (input_pos < (MAX_INPUT - 1))
          input_line [input_pos++] = inByte;
        break;

      }  // end of switch

  }  // end of incoming data

  // do other stuff here like testing digital input (button presses) ...

}  // end of loop

Example of commands understood by the above code:
C    <-- clear all LEDs
S    <-- set (turn on ) all LEDs
I    <-- invert all LEDs (turn off if on, and vice-versa)
021  <-- turn LED 02 on
020  <-- turn LED 02 off
161  <-- turn LED 16 on

This code processes a 3-digit string as:
nnS

Where "nn" is the LED number and S is the new state (1 = on, 0 = off).

Other examples

There is a more elaborate example on my page about using a 74HC595 output shift register as a port-expander
How to process incoming serial data without blocking
State machines

Your answer actually made me research about a shift register and now I'm actually considering it for saving some output pins on my project, thanks!


text:
Can wifi shield connect to local network without internet?
I have an Arduino Uno and a Texas Instruments CC3000 WiFi shield. I need to connect the Arduino to a local network which has no Internet access so that it can send information to a computer also connected to the same local network. I am using a Linksys WRT120N for the local network.
I can't use the Internet access WiFi because it is WPA2 Enterprise which is why I created the local network. Currently the computer is connected to the local network via WiFi.
I have downloaded and installed the correct library but when I run the connection test, it searches for Internet access which doesn't exist and sends back errors.
How do I verify that it is connecting to the local network?
Btw, I have almost no experience coding an Arduino but I have access to people who are proficient; However, they have no experience with a WiFi shield.

Why not modify the connection test to look for a local system instead?

Hi Nick, If my answer below doesn't help, please provide the EXACT error message/output, a link to the library, and a copy of your code.

So, I took the arduino home to attempt to connect to my own WPA2 network and for some reason, the serial monitor keeps showing it attempting to connect with the old network name. I have reloaded the code and changed the SSID and password within the code. Here is a link to the library I downloaded. The library zip file download link is at the bottom of the page under documents.  https://www.sparkfun.com/products/12071  Also, I am using the code provided by the library called connection test. The only things I changed within the code are the SSID name and the password.

I don't know how to share my code with all of you because it is too long to place in here. The code is available in the library zip file.

Hi Nick. I reviewed the ConnectionTest.ino file and it should be providing some good diagnostic information through the serial port. Have your colleagues show you how to use the Serial monitor. I'd be happy to review the Serial Monitor output if you post it here.

If you have created your own local network, you may need a DHCP server to give it an IP address, or you will have to configure your Arduino with a static ip. I can't think of a reason why it would need internet access, but it is not uncommon for devices to refer (incorrectly) to connectivity issues on the local network as "internet" issues.


text:
Problem with codebender project not compiling
I have written a codebender project which returns this error:
Oops! Looks like there was a serious issue with your project.

If you are not sure what could be wrong please contact us

/mnt/tmp/compiler.amxHJ9/files/Many Games.o: In function `gamesMaster::gamesMaster()':
Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xa): undefined reference to `vtable for gamesMaster'
Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xc): undefined reference to `vtable for gamesMaster'

What does it mean by vtable?
The code uses basic classes and inheritance.
The program is designed to select and play the game of your choice.  I have only programmed the basic structure.
Class games contains a ref to the class gamesMaster.
Class gamesMaster contains a ref to simpleTimer.
Classes playHiLow and playSimon are children of gamesMaster.
Class games handles and input and outputs, win and lose control and keeps track of lives.
Class gamesMaster handles the simpleTimer, displays a new round, checks for the correct answer, and checks if game has finished successfully.
The main() function runs a routine in the games class.
The code is listed here: https://codebender.cc/sketch:144869
class simpleTimer
{
private:
    unsigned long _previousMillis;
    unsigned long _interval;

public:
    simpleTimer()
    {

    }
    void start(float mins)
    {
        _interval = (unsigned long) (mins * 60 * 1000);
        _previousMillis = millis();
    }
    bool stillRunning()
    {
        return (millis() - _previousMillis < _interval);
    }
};

class gamesMaster
{
public:
    unsigned short lives;
    gamesMaster()
    {
        timeOutTimer = new simpleTimer();
        gameTimer = new simpleTimer();
        gameTimer->start(1.5);
        lives = 5;
    }
    void right()
    {
        Serial.println("Correct");
    }
    void wrong()
    {
        Serial.println("Wrong");
    }
    void winGame()
    {
        Serial.println("**********");
        Serial.println("* WINNER *");
        Serial.println("**********");
    }
    void loseGame()
    {
        Serial.println("\\ /          \\ /");
        Serial.println(" X    LOST    X");
        Serial.println("/ \\          / \\");
    }
    void startTimeOut(float mins)
    {
        timeOutTimer->start(mins);
    }
    bool notTimedOut()
    {
        return timeOutTimer->stillRunning();
    }
    bool gameTimerOver()
    {
        return !gameTimer->stillRunning();
    }
    simpleTimer *timeOutTimer;
    simpleTimer *gameTimer;

    virtual void setupForNewRound(void);
    virtual bool checkAnswer(unsigned short);
    virtual bool reachedEnd(void);
};

class gameHiLow: public gamesMaster
{
public:
    gameHiLow() : gamesMaster() {}
    void setupForNewRound()
    {
        Serial.println("  ->(HiLow) New round");
    }
    bool checkAnswer(unsigned short answer)
    {
        Serial.println("  ->(HiLow) Correct Answer");
        return HIGH;
    }
    bool reachedEnd()
    {
        Serial.println("  ->(HiLow) End of game");
        return HIGH;
    }
};

class gameSimon: public gamesMaster
{
public:
    gameSimon() : gamesMaster() {}
    void setupForNewRound()
    {
        Serial.println("  ->(Simon) New round");
    }
    bool checkAnswer(unsigned short answer)
    {
        Serial.println("  ->(Simon) Correct Answer");
        return HIGH;
    }
    bool reachedEnd()
    {
        Serial.println("  ->(Simon) End of game");
        return HIGH;
    }
};

class games
{
private:
    unsigned short _gameToPlay;
    unsigned short _levelToPlay;
    gamesMaster *myGame;
    unsigned short _getAnswer()
    {
        if (Serial.available() > 0)
        {
            int inByte = Serial.read();
            Serial.println("  ->(games) Decode Answer");

            switch (inByte)
            {
                case '<':
                    return 1;
                    break;
                case '>':
                    return 2;
                    break;
            }

        }
        return 0;

    }
    bool _respond()
    {
        unsigned short answer;
        while(myGame->notTimedOut())
        {
            if((answer = _getAnswer()) != 0)
            {
                if(myGame->checkAnswer(answer) == HIGH) return HIGH;
            }
        }
        return LOW;
    }
public:
    games(unsigned short gameToPlay, unsigned short levelToPlay)
    {
        _gameToPlay = gameToPlay;
        _levelToPlay = levelToPlay;
        switch(_gameToPlay)
        {
            case 1:
                myGame = new gameHiLow();
                Serial.println(" ->(game) play Higher or Lower Game");
                break;
            case 2:
                myGame = new gameSimon();
                Serial.println(" ->(game) play Simon Game");
                break;
        }
    }
    void play()
    {
        unsigned short answer;
        while(!myGame->gameTimerOver())
        {
            myGame->setupForNewRound();
            myGame->startTimeOut(.5);
            if(_respond() == HIGH)
            {
                myGame->right();
                if(myGame->reachedEnd())
                {
                    myGame->winGame();
                    return;
                }
            }
            else
            {
                myGame->wrong();
                if(--myGame->lives <= 0)
                {
                    myGame->loseGame();
                    return;
                }
            }
        }
        myGame->loseGame();
    }
};

//////////////////////////////////////////////////////////////////////////////////
games *game;

void setup()
{
    Serial.begin(9600);
    unsigned short gameToPlay = 1;
    unsigned short levelToPlay = 1;
    game = new games(gameToPlay, levelToPlay);
}

void loop()
{
    Serial.println("Let the games begin");
    game->play();
    Serial.println("Program Complete");
    delay(5000);
    exit(0);
}

I agree with @GeryOshlike.  But that's not the only option.
Yes, you can make them pure virtual:
virtual void setupForNewRound(void) = 0;
virtual bool checkAnswer(unsigned short) = 0;
virtual bool reachedEnd(void) = 0;

Or you can make them virtual with a default function:
virtual void setupForNewRound(void) { }
virtual bool checkAnswer(unsigned short) { return false; }
virtual bool reachedEnd(void) { return false; }

Pure virtual will complain when you compile if you haven't implemented those functions in your child class.  By providing a default function body it will not complain if you haven't implemented it, and will just use the default body.
If it's a function which you know will always have to be implemented at the child level (will always be different) then go the pure virtual route.  If it's a function that will be the same in a number of children but differ in only a few, then providing the default body and overriding with different ones when needed is the better way to go.

As discussed here
https://stackoverflow.com/questions/3065154/undefined-reference-to-vtable
declare these functions pure virtual:
virtual void setupForNewRound(void) = 0;
virtual bool checkAnswer(unsigned short) = 0;
virtual bool reachedEnd(void) = 0;


text:
Human circuit trigger
The main idea is to create trigger which can be switched on by touching 2 plates on opposite walls. And these should be performed by few peoples holding each other hands.
Obviously human body has big resistance so I couldn't just connect these plates to ground and to one of Arduino pins.
There is a toy that do almost what I what (see it there). But I haven't found any information about how to create it by myself.
Do you have any ideas how to create it?

Interesting idea... I think it would be difficult to detect two people though. What if one person touches one plate by hand, and reaches for the other plate with a long metal rod?

Yeah, there are many ways to cheat but for office Halloween quest it should work just fine (it would be easier to find a few people than long metal rod). Also I've already found another project on amplifier + transistor. But firstly i'm going to check solution by @A3ruz as it looks like the simplest one.

The human body certainly has a measurable resistance. I measure around 1.5 MΩ holding the multimeter probes. Trying with two people holding hands still only gave 1.5 MΩ, so it seems the problem point might have been the contact with the probes.

Here's a DIY for the toy in the link you posted. It's not arduino but I hope it helps. https://en.vmaker.tw/archives/work/the-energy-stick

I just tried it (using my own method), and I got it working with very good sensitivity (should be fine for two people) using a TIP102 Darlington transistor and some resistors. Here is what I did:

R1, the 1M pulldown resistor on the first pin of the Darlington is necessary to keep the light off when nobody is touching the wires. Without this, the light will turn on and off frantically.
R2, the 1k resistor keeps the Arduino from draining too much current (since that would be bad for the pin) in the case that your A0 is in OUTPUT mode and set to LOW.
R3 keeps the LED (or in my case, an AC relay connected to an actual light) from draining too much current from the Arduino. Note: The LED leads may be backward (reverse polarity) in the provided diagram.
Here is the code:
// I release this code under the standard MIT licence;
// (in addition to whatever StackExchange implies);

const short triggerThreshold = 10;// Lower is more sensitive;

void setup() {
  pinMode(A0, INPUT);
  pinMode(A5, OUTPUT);
  digitalWrite(A5, LOW);
  delay(1);
}

void loop() {
  short value = analogRead(A0);
  digitalWrite(A5, (value > triggerThreshold) ? HIGH : LOW);
  delayMicroseconds(10000);// 10ms;
}

Note the triggerThreshold setting in the code. If you want more sensitivity, try changing the 10 to a 5. I just tried it, and it becomes extremely sensitive, yet it still appears to reliably stay off when I don't touch it. Naturally if you use large plates for touching, electrostatic in the air could set it off, so you may need to change this number to be higher to make it less sensitive, depending on your setup.

I had a lot of noise, so added a debounce function:
    // The input is noisy and flips high and low frequently.
    bool debouncedInput() {
      static uint16_t state = 0;
      // Get a simple 1 or 0 for input.
      short value = (analogRead(A0) > triggerThreshold) ? 1 : 0;
      // Bit shift state left, or against the new value and mask out high byte.
      state = (state<<1) | value | 0xfe00;
      return (state == 0xffff) ? HIGH : LOW;
    }
    void loop() {
      digitalWrite(A5, debouncedInput());
      delayMicroseconds(10000);// 10ms;
    }

The idea is intriguing, but you are not limited to use electricity.
You could experiment with some other type of signal. Sound, for example.
That would be safer.

You can do it with an Arduino !
Use any of the ADC pins
There will be change in the ADC i/p when there is some resistance b/w the pins !
Try both
+ve > (people) > ADC
-ve > (people) > ADC
Just do some trials and probably will notice the change in ADC pin outputs .
If you want to make  it more sensitive
Add a high resistance to the ADC pin
if you are giving +ve to touch plates add a resistance from ground to that ADC pin

Just make sure your power supply isn't earth referenced, so no current can flow thought the floor back to the arduino. But depending on the kind of floor and other factors this might not be a big issue.

No.  The ADC converter has too low of an input impedance to work with megaohm paths.  It is quite probable that detection can be accomplished, but by using either the dedicated comparator or possibly the ordinary digital input mode with an opposing resistor of several magaohms, not the ADC input mode.  If you really want to use the ADC, you will need to precede it with a high-impedance buffer amplifier


text:
Problem with uploading my sketch to my Arduino
I chose the correct COM port but it won't upload.
Arduino: 1.8.3 (Windows 10), Board: "Arduino Leonardo"
Sketch uses 5252 bytes (18%) of program storage space. Maximum is 28672 bytes.
Global variables use 228 bytes (8%) of dynamic memory, leaving 2332 bytes for local variables. Maximum is 2560 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:713)
    at processing.app.SketchController.exportApplet(SketchController.java:686)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2149)
    at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port 'COM4'.
    at processing.app.Serial.touchForCDCReset(Serial.java:99)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:93)
    ... 6 more
An error occurred while uploading the sketch
Exception in thread "Thread-124" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:123)
    at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:106)
    at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:682)
    at processing.app.Base.onBoardOrPortChange(Base.java:1297)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2179)
    at java.lang.Thread.run(Thread.java:745)

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

You tagged the question "Arduino-Nano" but said you have a Leonardo. Which is it?

did you find anything on this? i have a similar issue with an arduino nano 33 ble sense. it reccently rrived from pihut, but i can send it back if its the device. The drivers are uptodate. dont have another micro-usb cable that is used for data transfer, as most of the cables only support power. if anone found the solution, please update me !!

I had the same problem. try checking the crystal on your arduino

This is the relevant bit in your error output:
Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.

Is your Leonardo on COM4, or some other port? Does some other program have that port open?

Yes I now  it is a nono and not a Leonardo. I have trieyd with nono sketches and thers the same problem.

It doesn't really matter if it's a Leonardo or Nano -- the problem is that the Arduino application can't open COM4. Is the device you are programming on COM4? Is there any other application opening COM4?

I don't see any trivial solution from the error log, but you can try one or more of the following items:

Unplug and replug the USB cable (to check if the connection is ok)
Change your USB cable in another USB port from your computer
Restart computer
Change USB cable
Try another Arduino (if you have two megas, or change to Uno if possible), just to check for uploading
Reinstall Arduino

I install arduino on another device and same error happend. I haven't a other cabel or a arduino.

I found a new cabel ant it wont work. Weeks ago i have the same problem with an other nano. I think my  settings are incorect.

If you remove the Arduino, see you that COM4 is not in use anymore? And when you reconnect COM4 shows up again?

Yes. after remove com4 disappear. Plug in again an it shows me com 4

Than you can be sure the Arduino is on COM4. If your settings are incorrect, try to reinstall the IDE.


text:
Connect arduino with C# Desktop application wireless using esp8266
I am using wifi module esp8266 , what is easiest way to communicate arduino with desktop application and make a wireless communication between them. Please refer any useful resources

Are you using the ESP with an Arduino or stand-alone?

I am using esp with Arduino

There are many options. What exactly do you want to do?

Either use TCP or UDP to communicate. With TCP one end will be the server and will open a socket (your choice) and the other end will connect to it (much like communicating with a web server). With UDP both ends will open a socket and send discrete packets backwards and forwards.
How you would do either of those in C# is outside the scope of this website.
The ESP8266 has AT commands that perform the task for you - chiefly AT+CIPSTART.
The simplest to understand is probably TCP communication where you can just follow any of the myriad of website based examples. However instead of communicating with a website using HTTP you will be communicating with your own server software written in C# using your own custom designed protocol.
A simpler option may be to use a real web server as a "man in the middle" to which both the ESP8266 and your C# program communicate. That website could become a database back-end for your program.
Of course, what you decide to do depends entirely on how complex your program is and what data it is you want to transfer.

I just want to send a simple string from esp8266 to my C# application. I do not want to go for a web server. Can we do this like we do with serial port and arduino. Can you send me some useful links

Learn what TCP sockets are.

you can use a serial port, but a web server would be much simpler to deploy as it would not require client drivers.


text:
'tmElements_t' does not name a type
I've connected a real time clock ZS-042 to my Arduino Uno. I tried to set the time, using an example from DS1307RTC library. Here is my code:
#include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>

*const* char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

  tmElements_t tm;//it says that problem is in here

void setup() {

  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}

and this is my output:
Arduino: 1.6.12 (Windows 10), Плата:"Arduino/Genuino Uno"

In file included from C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino:1:0:

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:19:22: error: 'tmElements_t' has not been declared

     static bool read(tmElements_t &tm);

                      ^

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:20:23: error: 'tmElements_t' has not been declared

     static bool write(tmElements_t &tm);

                       ^

SetTime:10: error: 'tmElements_t' does not name a type

   tmElements_t tm;

   ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'void setup()':

SetTime:21: error: expected primary-expression before ')' token

     if (RTC.write(tm)) {

                     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getTime(const char*)':

SetTime:54: error: expected unqualified-id before '.' token

   tm.Hour = Hour;

     ^

SetTime:55: error: expected unqualified-id before '.' token

   tm.Minute = Min;

     ^

SetTime:56: error: expected unqualified-id before '.' token

   tm.Second = Sec;

     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getDate(const char*)':

SetTime:71: error: expected unqualified-id before '.' token

   tm.Day = Day;

     ^

SetTime:72: error: expected unqualified-id before '.' token

   tm.Month = monthIndex + 1;

     ^

SetTime:73: error: expected unqualified-id before '.' token

   tm.Year = CalendarYrToTm(Year);

     ^

exit status 1
'tmElements_t' does not name a type

Check the order of header files and check the dependencies. Do you have the right libraries. Looks like you have modified this example sketch; https://github.com/PaulStoffregen/DS1307RTC/blob/master/examples/SetTime/SetTime.ino

IDE 1.6.10: compilation of sketches wich time library fails

Welcome to Arduino Stack Exchange.  You can take the tour at https://arduino.stackexchange.com/Tour to get the best out of this site.

Clearly the compiler does not know what tmElements_t means.
It is defined in TimeLib.h
In your program you reference Time.h instead, where it is not defined.
So:  Change
include <Time.h>

to
include <TimeLib.h>

and it should clear that error.

Time.h was changed to TimeLib.h specifically to combat this problem. The compiler started providing time.h, and on operating systems like Windows that use a case-insensitive filesystem it confuses Time.h and time.h.

Thank you for help! It works! The problem was in TimeLib.h. Literally, it wasn't in my lib, so i had to re-install it. Then I changed include as you said and it works.

But for now I've got another trouble. My serial port doesn't print anything.

Take out the while (!Serial) - once you do the Serial.begin(9600) you can assume it is ready to receive output.  Also, be aware that in the Arduino IDE, opening the serial monitor will restart your program.


text:
Webservice C# JSON to Arduino
I have a project in Microsoft Visual Studio C# and I have to pass JSON data to my Arduino via Ehternet Shield.
This is how it works:

Is it possible? How to do it?

Yes.
If you're using an Ethernet Shield, you should be able to run a webserver on the Arduino and simple do an HTTP request from your C# webservice to the Arduino.
Check this tutorial on how to write a webserver for arduino using the ethernet shield: http://arduino.cc/en/Tutorial/WebServer
Doing an HTTP request of any kind from C# should be easy enough and is not in the scope of this site.


text:
Arduino + Web Service
I am doing my CBT, and i need help...
I need a Webservice in C#, and it will send commands to my Arduino( Mega 2560 + Ehternet Shield )...
My Webservice will recibe commands from Android and Web

EDIT
I wanna know what kind of C# WebService Project I have to create...

What is your question exactly? If you want to know where to begin: google. Find some tutorials and do them to get familiar with all the different parts of the project. If you run into any troubles with those, maybe we can help you.

Go easy on this forum please. Dont be as strict as stackoverflow.com. Arduino does take a bit of time to learn. Tolerate basic questions please.

The question is probably better suited to another stack exchange forum. The question really isn't Arduino related, but more about web programming on a PC. Once you have that and it is ready to send commands to the Arduino, I hope you'll come back here with your Arduino questions. It sounds like a fun project.

@Siddharth it's not really our opinion that counts. If you'd like a change in policy, propose it on meta. However, this type of question wouldn't be allowed anywhere on SE because it would  be opinion based which often leads to bad content.

@JRobert this wouldn't be allowed on SO for sure. However, yes, we can help with specifics on the Arduino side....


text:
How to split in string
I want to split this:
char* value = "12;32;blue";
or
string value = "12;32;blue";

into this vars:
TV = 12;
AR = 32;
LED = "blue";

is it possible?

For C-strings (char*), your best option (in terms of performance and memory consumption) is to use strtok:
char* value = "12;32;blue";
char* token = strtok(value, ";");
int TV = atoi(token);
token= strtok(0, ";");
int AR = atoi(token);
token = strtok(0, ";");
char* LED = token;

Note 1: the code above takes it for granted that value is properly formatted, i.e. contains 3 parts split by ;. If it is not sure, then you should add additional checks on token value returned by strtok.
Note 2: strtok is modifiying its value argument, so that at the end of the code above, value will not be equal to 12;32;blue any longer.
Note 3: LED variable above will point directly to the character b inside value, which means that if value is modified afterwards, LED might be modified as well.

Scan function should do the job.
int tv, ar;
char color[10];
sscanf(value, "%d;%d;%s", &tv, &ar, color);

That's a great old trick. I totally forgot about it! https://www.daniweb.com/software-development/c/code/216535/parsing-a-string-into-tokens-using-sscanf

I think you meant sscanf not scanf as the latter needs stdin which Arduino doesn't have. Also in your example you shouldn't pass &color, but rather color.

and where do i tell the sscanf to get val from my var 'value' ?

@Thiago: as first parameter. Corrected.


text:
Cant connect to localhost
I have a project um Visual Studio with a GET method:
http://localhost:4548/Arduino/request?id=12&user=username&pass=password
When I open it in my browser, it works fine
But I want http GET in my Arduino, using the WebClient exemple:
EDIT
I used solution number 1. of @Matt and it worked:
Get a full licensed copy of IIS.
And this is the code after all:
#include <SPI.h>
#include <Ethernet.h>

//Informacoes de endereco IP, gateway, mascara de rede
byte mac[] = { 0xA4, 0x28, 0x72, 0xCA, 0x55, 0x2F };
byte ip[] = { 192, 168, 1, 200 };
byte gateway[] = { 192, 168, 1, 1 };
byte subnet[] = { 255, 255, 255, 0 };
byte server[] = { 192, 168, 1, 100 };

EthernetClient client;

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /myProject/request?id=12&user=username&pass=password HTTP/1.1");
    client.println("Host: 192.168.1.100");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

My Serial displays as connected, but the http GET does not work
Am I missing something?

You understand that "localhost" is literally the machine that the code is running on, right?

Yes. I tryed 192.168.1.100 instead of localhost but didnt work.

I believe the Visual Studio built in web server (when you 'Run' your app/site) only listens on localhost. So even substituting the IP address is not going to work. You might need to 'publish' your web service/site before it will work.

@Thiago in the stack exchange system, questions are marked resolved not by editing the question, but by accepting an answer. Could you please put the corrected code as an answer to this question and maybe it will help someone else.

Visual Studio's web server is restricted to only servicing clients on the machine it is running on.
To do what you want to do there are a number of things you can do.

Get a full licensed copy of IIS. (Please stop laughing)
Get a version of Apache (might affect your server code and will take a while to setup)
Write yourself a 'proxy server'.  I think if you write a program to run on you PC that creates a socket that listens to port 8080 and forwards any messages on to the VS Web Server (use "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\WebDev.WebServer40.EXE" /port:6666 /path:C:\WebServer\Root to start it on a fixed port) and forward any replies back to you client.

Get a full licensed copy of IIS. -> It worked, Thanks!!!


text:
Is it possible to upload previously compiled binary?
I have a number of sketches that I keep wanting to load into the Arduino but I don't necessarily need to recompile them because I haven't changed anything since the last compile. Since the compile takes a minute or 2 each time, this would save me some waiting.
I can see that the IDE has the option to "Export Compiled Binary", but doesn't seem to have the converse option of Uploading a previously compiled binary. Is there any way to do this?

Arduino 1.8.10 is using upload.py

@FallenDragon. it is not. only the esp8266 arduino boards package has upload.py

Yes!
Its possible that you can upload a previously complied binary, using
AVRDUDE - a command line utility which is actually used to upload binaries, behind the arduino IDE.
You can find AVRDUDE in
Arduino folder > hardware  > tools > avr > bin
This some documentation for AVRDUDE
http://www.nongnu.org/avrdude/user-manual/avrdude.html
else simplest thing you can do is turn on verbose output during upload and watch for a command in the end with AVRDUDE in it along with the path of hex file, just copy paste &  run the same command in CommandLine; your task is accomplished.

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


text:
Powering Arduino Pro Mini + Driving LED Strip
Just looking for a second opinion on my circuit below. Wired up everything works great, but last night as i was unplugging the FTDI programmer something seemed to have happend, and the mini was bricked.
I'm not sure if it has to do with my wiring below, or if it was me unplugging the cable in a haphazard manner.
What I'm attempting to do is run my arduino from 12v wall supply, but also drive an LED strip with it. I'm just unsure if this is the best way to go about it, any advice is welcome.
Thanks
Justin

Is that just a Fritzing artifact, or is that power supply in backwards? It looks to me like the center pin is going to ground. See have I bricked my Arduino for possible tests you can do to confirm if you really bricked it.

Ya, that's just fritzing showing it backwards.

I would try (amongst other things) removing it from the breadboard, and trying to program it just with the FTDI cable.

Oh yea, sorry I didn't completely respond. The arduino is definitely bricked. I just wanted to make sure the 12v led circuit wasn't wired incorrectly and overheating caused the brick. Should there be a capacitor somewhere? It seemed like when I unplugged the ftdi it blew something.

A little off topic- but what program did you use to make the above diagram?

According to the schematics, the Pro Mini uses the MIC5205, which is a linear regulator.
Using it directly with 12V is not a very good idea, in terms of power efficiency, as it will dissipate 35mW vs 25mW provided to the ATMega board.
From this perspective, I'd recommend a step-down converter for powering the Arduino.
However it will not cause any damage, at least at room temperature, as the power dissipation is well within operating margins, see calculation at page 8 of the MIC datasheet.
Edit: detailed pros and cons, power wise.

Arduino says input voltage can range up to 12V: https://www.arduino.cc/en/Main/ArduinoBoardProMini Is my circuit correct, or is this damaging to the Arduino?

I'm trying to keep my circuit as compact as possible, which is the reasoning for wiring 12v into RAW, allowing arduino to step the voltage down.

not a very good idea; please explain. In this circuit it's probably just fine, as an ATMega328 by itself only uses around 5mA, so the voltage regulator would dissipate only 35mW of heat.

Are you telling me it's not a very good idea, or are you asking Igor Stoppa to explain further?

It dissipates 35mW vs 25mW provided to the Arduino. Not very efficient, power-wise.
The preference for using the absolute minimum set of components was not part of the original question.

Fundamentally though, there's nothing wrong with wiring 12V into arduino, and also using that 12V to power an LED strip right?

From page 8 of the MIC5205 data sheet, the max power dissipation at room temperature is in excess of 400mW >> 35mW, so yes, it should be safe practically in any reasonable operating condition it might see.

Thank you very much for the help. I'm going to assume it has something to do with the act that I was powering from 20v via raw pin, but also had ftdi plugged in. The issue happened right when I pulled the headers off of the arduino. I threw in a new mini and the circuit is working just as it was. Would programming while powered cause an issue?

I always program while powered the Mini Pro I use as development setup.
In my case the power comes from a 5V regulator, though. However, if you are using the RAW input, it should be the same. As programmer I have an AVRDragon.

Let us continue this discussion in chat.


text:
I would like to control 16 motors with a servo shield
Ok so I've used nicks code and have the code running once ok.... I the noticed however I had a fast 180 sweep and then it returned under control of code. I then noticed the comments wrt pulselen of 1000 being zero degrees and using 1500 as 90 degrees.... Wow so I get a single movement which holds but it doesn't go 90 degrees...
I'm using an Adafruit servo shield.
I can make my servo move. However, I want to stop it at 90 degrees without it returning to 0 degrees each time.
What am I missing?
The code I've used is as follows:
void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
}

void loop()
{
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
  {
    pwm.setPWM(0, 0, pulselen);
  }
  delay(500);
}

If you don't want it to keep going back to zero, don't have a loop that resets to zero when it reaches 90.

You are right by putting it in the setup the code does only runs once. However my problem is the servo arm sweeps 90deg as coded and returns to where it started (not coded). Putting the code outside Void Loop () or using a count based approach makes no difference. To recap my issue is how do I hold the servo at 90degrees ???

Please post the amended code. You tell it to go to 90 degrees and then you do not tell it to do anything else.

@NickGammon please note that this is in the main loop(), so it will wait half a second and then reset to SERVOMIN.

Andy: do you want it to just go from 0 to 90 one time, or what do you want it to do?

please note that this is in the main loop(), so it will wait half a second and then reset to SERVOMIN - incredibly quickly, yes. The loop executes very quickly so it would go back up to SERVOMAX within a short time. In fact my testing indicates that it executes that loop in 72 ms.

The code in loop is called repeatedly. Thus it does this:

Go from SERVOMIN to SERVOMAX very rapidly (I measured 72 ms)
Pause half a second
Repeat the above

To make it pause at SERVOMAX you need to either not repeat the loop, or put it all in setup, eg.
#include <Adafruit_PWMServoDriver.h>
#include <Wire.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)
void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
  {
    pwm.setPWM(0, 0, pulselen);
  }

}

void loop()
{
}

Thanks Nick, using your code I've added a delay just after. I then noticed when executing the code the servo arm rapidly swings 180 degrees and then it slowly sweeps back the other direction due to the delay as 'pulselen' increases.....

Thanks Nick, using your code I've added a delay just after pwm.setPWM(). I then noticed when executing the code the servo arm rapidly sweeps 180 degrees and then it slowly sweeps back the other direction due to the delay and as 'pulselen' increases..... But what is causing the initial fast sweep as I only need the slow sweep?

Hi nick I noticed if I changed servo max and min to 1500 and 1000 respectively I loose the fast sweep..

Servos differ, and the pulse width for the sweep at max and min positions may well vary. You have it solved then? Good.

The variable pulselen in your code corresponds to the angle you want the servo to turn to. For most servos the pulselen is supposed to be a number from 1000 to 2000, where 1000 corresponds to 0 degrees and 2000 corresponds to 180 degrees, but some servos may be different. It's probably safe to assume that you want a value close to 1500.
Of course the servo takes a while to get to its position, so the best approach usually involves changing pulselen gradually until you get to the desired position.
Once you get to 90 degrees stop changing pulselen. At that point you should still be sending the PWM but keep it at 1500. You'll want to keep sending the PWM signal, or the servo will have no resistance to external forces.


text:
NRF24L01+ PA not working with Arduino Mega (works with Nano)
Full disclosure: I'm a newbie.
I've got an Arduino Nano and a Mega, and a pair of NRF24L01+ PA modules (exactly these: http://www.elektrotedarik.com/Images/Urun/11122013173429.jpeg)
I'm trying to get them to work. I am on this tutorial with the RF24 library: https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
On Arduino Nano, it works perfect. I wire everything as told, and set up my radio:
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
fdevopen( &my_putc, 0);
radio.begin();
radio.setPALevel(RF24_PA_MAX);
radio.setDataRate(RF24_250KBPS);
radio.openWritingPipe(pipe);

When I call radio.printDetails(); I get a nice output in serial monitor:
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1    � = 0xe8e8f0f0e1 0xc2c2c2c2c2
RX_ADDR_P2-5    � = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe8e8f0f0e1
RX_PW_P0-6  � = 0x20 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR   � = 0x03
RF_CH        = 0x4c
RF_SETUP    � = 0x27
CONFIG       = 0x0c
DYNPD/FEATURE   � = 0x00 0x00
Data Rate    = 250KBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_HIGH

Everything as expected. If I remove a wire (for testing), it displays all zeroes, when I plug it back, it displays right again, so I assume that it's in working condition. I then try the same with Mega, but even after re-checking the wiring after 4 times, it's not working. Here's what I get with the same code:
STATUS       = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1    � = 0x0000000000 0x0000000000
RX_ADDR_P2-5    � = 0x00 0x00 0x00 0x00
TX_ADDR      = 0x0000000000
RX_PW_P0-6  � = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x00
EN_RXADDR   � = 0x00
RF_CH        = 0x00
RF_SETUP    � = 0x00
CONFIG       = 0x00
DYNPD/FEATURE   � = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = Disabled
PA Power     = PA_MIN

Tried many times, no avail. Then I've came upon several threads talking about the different pins. Changed the pins to match Mega's MOSI, MISO, SCK, CE, CSN pins, no avail. I've tried exact same configuration with people who say that it's working, no avail. Then I've stumbled upon that Mega ironically can't supply enough current from the 3V3 pin (while Nano perfectly can) and it can't power the NRF24L01+ PA. I've tried drawing 3V from my power supply (my power supply has either 3 or 4.5 volts, I can't risk burning my transceiver with 4.5 volts). It still doesn't work, and it became extremely hot in seconds (the one attached to my nano doesn't heat up at all). I immediately turned it off, thought that I've burned something, swapped with the Nano's transceiver, and it (fortunatelly) works. So there's no problem with the NRF24L01+ PAs. Why would it not work with Mega (I've also tried the lowest power setting too), and why would it get extremely hot when attached to an external power supply? What else can I do?
UPDATE: I've added a 470uF decoupling capacitor to the receiving end (the one attached to Mega), it seems to be worse.
A very interesting observation: If I touch the receiver when it's not working, it starts receiving the signal excellently. If I let it go, signal is lost again.
UPDATE 2: Nevermind the last "when I touch..." update, it appears to be related to wiring (haven't soldered them yet, just using jumper wires)
UPDATE 3: My initial assumption is correct, something happens when I touch the cables. Something more weird is going on. I soldered my module on a prototype board, and my module sometimes works even without CE pin plugged in. When I touch the cable, it transmits, and stops. Here, TX pin lighting up means it's receiving the signal (I'm writing data to serial). It receives the data (and yeah, the correct data) when I touch the CE pin's cable:

How on Earth is this possible? Does the CE pin/cable (and myself) act as an antenna? Makes no sense.
UPDATE 4: If I plug that pin to 5V, the whole receiver starts working absolutely perfectly, with no errors/drops at all. But I can't get it: why? And would it overheat/short something?

Lack of power sounds right, getting hot sounds wrong. Even when not working correctly when powered from the 3v3 pin, did you have a 10uF cap across the nRF power pins?

You never did mention if you applied the capacitor suggested by Roger. Even the tutorial you linked to mentions the Megas in particular exhibit this problem.

@JakeC I've soldered a 470uF capacitor and it made everything worse. Now it connects much harder and disconnects immediately.

@JakeC it transmits at bursts. For a second or two, excellent transmission, then, say about for 5-6 seconds, nothing at all.

I have a NRF24L01 - not that exact model, mine looks like this:

Pin-outs:

I hooked it up to my Mega2560 like this:
NRF24L01     Mega2560
----------   ----------------

  VCC         3.3V pin
  Gnd         Gnd
  CSN         D10
  CE          D9
  MOSI        D51 - (MOSI)
  SCK         D52 - (SCK)
  IRQ         N/C
  MISO        D50 - (MISO)

I used the RF24 library. Then I hit a number of issues.
For one thing, the "Getting Started" sketch doesn't seem to work too well, even between two Unos, for reasons I haven't worked out.
However the "pingpair" sketch worked OK between two Unos. But not when one device was moved to the Mega2560! I tried various things including a separate power supply, and moving the CSN/CE pins around, but to no avail.
Then I had a look at Vcc/Gnd using the scope:

That's over half a volt of ripple! I soldered on a 0.1 µF capacitor between Vcc and Gnd on the NRF24L01 and the problems went away. Using the pingpair sketch I now have:
Now sending 56...ok...Got response 56, round-trip delay: 23
Now sending 1080...ok...Got response 1080, round-trip delay: 21
Now sending 2103...ok...Got response 2103, round-trip delay: 21
Now sending 3126...ok...Got response 3126, round-trip delay: 21
Now sending 4148...ok...Got response 4148, round-trip delay: 22
Now sending 5171...ok...Got response 5171, round-trip delay: 22
Now sending 6194...ok...Got response 6194, round-trip delay: 22
Now sending 7217...ok...Got response 7217, round-trip delay: 22
Now sending 8240...ok...Got response 8240, round-trip delay: 21
Now sending 9263...ok...Got response 9263, round-trip delay: 21
Now sending 10286...ok...Got response 10286, round-trip delay: 21

So, my suggestion is a decoupling capacitor on the NRF24L01.

Extra
I still had some weird issues where the above results actually came from a NRF24L01 without the aerial. The one with the aerial had much more marginal results.
These are the results with the aerial:
Now sending 181378...ok...Failed, response timed out.
Now sending 182581...ok...Failed, response timed out.
Now sending 183784...failed.
Failed, response timed out.
Now sending 185047...failed.
Failed, response timed out.
Now sending 186309...ok...Got response 186309, round-trip delay: 26
Now sending 187336...ok...Got response 187336, round-trip delay: 22
Now sending 188359...ok...Failed, response timed out.
Now sending 189561...ok...Got response 189561, round-trip delay: 22

Still, I think it is worth trying the decoupling capacitor.

and why would it get extremely hot when attached to an external power supply?

Did you have the grounds connected?

Nope, didn't have the grounds connected, moreover, it was a faulty supply, in 3V mode I saw about 4-4.2V in voltmeter. I think those combined explain it.

Whatever else you do, always connect the grounds. Otherwise you may have some massive voltage which happens to be the difference in the grounds in your house wiring appearing at your processor chip.

You are definitely right, and I actually knew about that (and it does make perfect sense intuitively too, GNDs should be equal). My newbie-ness and lack of experience made me forget about that :)

An old thread.
But I want to share my fix when hooking nRF24 with MEGA. I forgot the website where I got the solution.
It is simply adding a pinMode(x, OUTPUT) in the setup, where x is the CSN pin you choose.
I believe the issue is only on pin 53 only on MEGA.
However, add this in all my sketches with or without MEGA just for precaution.