text:
Multiple buttons activating different methods for an LED strip
I am trying to use different buttons to activate different methods for an LED strip. However, when one button is pressed after another has been pressed, I want it to interrupt the first buttons method and begin the second. For example: one button sends a rainbow pattern through the LED strip when pressed, however, while it is cycling through the rainbow, the second button is pressed which sends a white cycle through the LED strip. There will be 24 buttons total. I have gotten this to work with 2 buttons but am having trouble getting it to work for a third. The code is below:
     void loop(){

       if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
           stopCycle();
           theaterChaseRainbow(50);
       }
       if (digitalRead(inPin(2)) == HIGH){
           stopCycle();
           theaterChase(strip.Color(127, 127, 127), 50); // White
       }
       if (digitalRead(inPin(3)) == HIGH){
           stopCycle();
           rainbowCycle(0);
       }

     }

     //Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<100; j++) {  //do 100 cycles of chasing
    if (digitalRead (inPin(1)) == LOW) { //checks that other button(s) have not been pressed
      if (digitalRead (inPin(3) == LOW)){
      for (int q=0; q < 3; q++) {
        for (int i=0; i < strip.numPixels(); i=i+3) {
          strip.setPixelColor(i+q, c);    //turn every third pixel on
        }
        strip.show();

        delay(wait);

        for (int i=0; i < strip.numPixels(); i=i+3) {
          strip.setPixelColor(i+q, 0);        //turn every third pixel off
        }
      }
    }
    }
  }
}

void rainbow(uint8_t wait) {
  int i, j;

  for (j=0; j < 384; j++) {
   if (digitalRead (inPin(2)) == LOW) { // 3 cycles of all 384 colors in the wheel
    if (digitalRead (inPin(3) == LOW)){
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel( (i + j) % 384));
    }
    strip.show();   // write all the pixels out
    delay(wait);
   }
   }
  }
}

uint32_t Wheel(uint16_t WheelPos)
{
  byte r, g, b;
  switch(WheelPos / 128)
  {
    case 0:
      r = 127 - WheelPos % 128;   //Red down
      g = WheelPos % 128;      // Green up
      b = 0;                  //blue off
      break;
    case 1:
      g = 127 - WheelPos % 128;  //green down
      b = WheelPos % 128;      //blue up
      r = 0;                  //red off
      break;
    case 2:
      b = 127 - WheelPos % 128;  //blue down
      r = WheelPos % 128;      //red up
      g = 0;                  //green off
      break;
  }
  return(strip.Color(r,g,b));
}

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for (j=0; j < 384 * 5; j++) {     // 5 cycles of all 384 colors in the wheel
    if (inPin(1) == LOW) {
      if (inPin(2) == LOW) {
    for (i=0; i < strip.numPixels(); i++) {
      // tricky math! we use each pixel as a fraction of the full 384-color wheel
      // (thats the i / strip.numPixels() part)
      // Then add in j which makes the colors go around per pixel
      // the % 384 is to make the wheel cycle around
      strip.setPixelColor(i, Wheel( ((i * 384 / strip.numPixels()) + j) % 384) );
    }
    strip.show();   // write all the pixels out
    delay(wait);

      }
    }
  }
}

void stopCycle(){
    int i;
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0);
    }
    strip.show();   // write all the pixels out
}

Inside each inner loop, just test the switches and return if they are pressed.
eg.
//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<100; j++) {  //do 100 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (int i=0; i < strip.numPixels(); i=i+3)
      {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();
      delay(wait);

      // give up if switches pressed
      if (digitalRead (inPin(1)) == HIGH ||
          digitalRead (inPin(2)) == HIGH ||
          digitalRead (inPin(3)) == HIGH )
        return;

      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

am having trouble getting it to work for a third

If that doesn't help please explain the nature of this "trouble".

You may need to debounce the switch presses. And you may need to wait for them to release the switch, eg.
 if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
           stopCycle();
           while (digitalRead(inPin(1)) == HIGH)
              {  }   // wait for switch release
           delay (10);  // debounce
           theaterChaseRainbow(50);
       }

This is an excellent solution but is there a way to move the return statement to the loop? This way, I could call theatreChase multiple times with different buttons at different paramenters.

I'm not sure what you mean by "move the return statement to the loop". Can you elaborate?

I would normally do this (pseudocode):
void loop() {
    static state=state_off;
    if (button_1_pushed) {
        state=state_1;
    } elseif (button_2_pushed) {
        state=state_2;
    }
    if (state==state_off) {
        turn_all_leds_off();
    } elseif (state==state_2) {
        shownextframe_rainbow();
    } elseif (state==state_2) {
        shownextframe_chaser();
    }
    delay(1);
}

In shownextframe_chaser/shownextframe_rainbow, I would probably work out what should be shown based on the current millis() - e.g. if your chaser has 10 lights, and you want it to pulse over 1 second, then each led should be on for 100 millis, so at any instant, the led that should be on is (millis()/100)%10 (assuming the led's are numbered for 0 to 9).


text:
Anyone using ModBus RTU on Galileo gen 2?
I'm trying to communicate with some industrial hardware, on ModBusRTU, from my Intel Galileo Gen2 board. I use this board to convert UART to RS485 http://linksprite.com/wiki/index.php5?title=RS485_Shield_V2.1_for_Arduino and I can talk serially between Arduino (with SoftwareSerial on pin 2/3) and Galileo (with Serial1 on pin 0/1). So I know the RS485's link is working.
With Arduino Uno I can talk with my devices using ModBusRTU, thanks to this library https://github.com/4-20ma/ModbusMaster
On galileo gen2 I received this warning WARNING: library ModbusMaster claims to run on [avr, sam] architecture(s) and may be incompatible with your current board which runs on [i586] architecture(s). because of the different architecture.
Now I'm trying to use the examples of cooking hack's tutorial about modbus and rs485 for Arduino, Raspberry and Galileo but I can't make it works for me. I received tons of compiling errors like these:
C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp: In member function 'uint8_t ModbusMaster485::ModbusMasterTransaction(uint8_t)': C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:701:50: error: '_crc16_update' was not declared in this scope
C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:814:52: error: '_crc16_update' was not declared in this scope
C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp: At global scope:
C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:881:14: error: prototype for 'unsigned int ModbusMaster485::makeWord(unsigned int)' does not match any in class 'ModbusMaster485'
In file included from C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:25:0: C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.h:302:11: error: candidates are: uint16_t ModbusMaster485::makeWord(uint8_t, uint8_t)
C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.h:301:14: error: uint16_t ModbusMaster485::makeWord(uint16_t) C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:887:14: error: prototype for 'unsigned int ModbusMaster485::makeWord(uint8_t, uint8_t)' does not match any in class 'ModbusMaster485'
In file included from C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:25:0: C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.h:302:11: error: candidates are: uint16_t ModbusMaster485::makeWord(uint8_t, uint8_t) C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.h:301:14: error: uint16_t ModbusMaster485::makeWord(uint16_t) Error compiling.

Did someone has got ModBus working on Galileo Gen2?

source: Stack Exchange

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

sort: votes


text:
Buttons for LED strip only work when held down
I am trying to make a 24 button board that assigns different methods to each button. When a button is pressed, it should interrupt the method of the previous button and begin the new method. Currently, the button has to be held down in order to work. I'm not sure why since the methods should continue without being held down. All 24 methods are similar to the one posted below.
loop(){
  if (digitalRead(inPin(5)) == HIGH){
    fifthButtonTheatreChaseRedSlow(strip.Color(127,   0,   0), 100); // Red
  }

void fifthButtonTheatreChaseRedSlow(uint32_t c, uint8_t wait) {
  for (int j=0; j<100; j++) {  //do 100 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (int i=0; i < strip.numPixels(); i=i+3)
      {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();
      delay(wait);

      // give up if switches pressed
      if (digitalRead (inPin(1)) == HIGH ||
             digitalRead (inPin(2)) == HIGH ||
             digitalRead (inPin(3)) == HIGH ||
             digitalRead (inPin(4)) == HIGH ||
             digitalRead (inPin(6)) == HIGH ||
             digitalRead (inPin(7)) == HIGH ||
             digitalRead (inPin(8)) == HIGH ||
             digitalRead (inPin(9)) == HIGH ||
             digitalRead (inPin(10)) == HIGH ||
             digitalRead (inPin(11)) == HIGH ||
             digitalRead (inPin(12)) == HIGH ||
             digitalRead (inPin(13)) == HIGH ||
             digitalRead (inPin(14)) == HIGH ||
             digitalRead (inPin(15)) == HIGH ||
             digitalRead (inPin(16)) == HIGH ||
             digitalRead (inPin(17)) == HIGH ||
             digitalRead (inPin(18)) == HIGH ||
             digitalRead (inPin(19)) == HIGH ||
             digitalRead (inPin(20)) == HIGH ||
             digitalRead (inPin(21)) == HIGH ||
             digitalRead (inPin(22)) == HIGH ||
             digitalRead (inPin(23)) == HIGH ||
             digitalRead (inPin(24)) == HIGH)
               return;

      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

Not sure if it's a hardware issue or a software issue.

It's a software issue.  You are basically saying "If this button is currently pressed down then run this sequence once", rather than "If this button has transitioned from OFF to ON then set my current sequence to X"
You need to learn about the Finite State Machine and about switching from one state to another (or one selected sequence to another) when a button changes state not when it is in a state.
So basically the whole logic of your program is flawed and needs re-working.

Related to Multiple buttons activating different methods for an LED strip
 // give up if switches pressed
  if (digitalRead (inPin(1)) == HIGH ||
         digitalRead (inPin(2)) == HIGH ||
         digitalRead (inPin(3)) == HIGH ||
         digitalRead (inPin(4)) == HIGH ||
         digitalRead (inPin(6)) == HIGH ||
         digitalRead (inPin(7)) == HIGH ||
         digitalRead (inPin(8)) == HIGH ||
         digitalRead (inPin(9)) == HIGH ||
         digitalRead (inPin(10)) == HIGH ||
         digitalRead (inPin(11)) == HIGH ||
         digitalRead (inPin(12)) == HIGH ||
         digitalRead (inPin(13)) == HIGH ||
         digitalRead (inPin(14)) == HIGH ||
         digitalRead (inPin(15)) == HIGH ||
         digitalRead (inPin(16)) == HIGH ||
         digitalRead (inPin(17)) == HIGH ||
         digitalRead (inPin(18)) == HIGH ||
         digitalRead (inPin(19)) == HIGH ||
         digitalRead (inPin(20)) == HIGH ||
         digitalRead (inPin(21)) == HIGH ||
         digitalRead (inPin(22)) == HIGH ||
         digitalRead (inPin(23)) == HIGH ||
         digitalRead (inPin(24)) == HIGH)
           return;

Time to learn about loops, buddy. How about:
for (int i = 1; i <= 24; i++)
  if (digitalRead (inPin (i)) == HIGH)
    return;

My guess about this particular problem is that you are not debouncing. You enter the function, one of the bounces is detected, and you leave the function. I mentioned debouncing in your other, closely-related, thread.

Let me show you what a switch bounce looks like. Using a normal switch from my parts drawer, this is what you see when you press it:

See that? It looks to the (fast) Arduino that you pressed the switch 20 or 30 times. That is the physical metal bouncing back and forwards. So if you test for one press, and then stop when you get another, your chances of it working are rather slim. That's why a simple delay of (say) 10 ms after detecting a change in state of the switch can help debounce it.
See: Switches tutorial

Could also be a chance for the OP to learn about switch cases.

One thing you're missing there, mate - he's entering the function on button 5, but he's not checking button 5 as a reason for terminating the function - so it can't be debouncing that's causing it - button 5 only enters, it never causes it to leave.  So a loop would break that functionality and then bouncing would then become a problem. As it is, the problem is caused by the if (digitalRead(inPin(5)) == HIGH) { ... } in the main loop (which equates to "while input 5 is high ... ").

Thank you for your responses. It turns out the bread board was not working. Changed it out and everything is fine now. I replaced the if statements with a switch. However, your suggestion for the alteration for the for loop isn't working. I need to skip a single value in the loop. My understanding of for loops, however, would make each of the ((inPin(i) == HIGH)) statements an AND statement, not an OR statement. I need it to be an OR statement to work. Do you have a suggestion for how to get around this?

@JetPropelledInsectivore Personally I would have a single function which reads all the buttons and sets each bit in a 32-bit unsigned integer as a bit-field representing which buttons are pressed. You can then mask out the button you want to ignore and see if the result is anything other than 0.

@Majenko - but he's not checking button 5 as a reason for terminating the function - Not really. He is saying he needs to hold the button down for it to be noticed. The function is already written to only do 100 iterations. So you could count that as a debounce. My proposed code exits on any button press, so it can go back and test for other buttons immediately.

My understanding of for loops, however, would make each of the ((inPin(i) == HIGH)) statements an AND statement, not an OR statement. I need it to be an OR statement to work. - what do you mean by "not working"?

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


text:
Arduino timers. How they work
Explain this line in simple words.
TCCR0B=TCCR0B&0b11111000|0x01;

As the variuos arduinos have different chips. They also have different timers and different pins which use them.
Lately i want to rewrite a code(Arduino Uno) to make it work on a Arduino Micro.
I need to understand how this works in simple words. I normally write web based code(javascript,php...). Just lately i started writing in c++ or a "simplified" c++ in the arduino ide. It's not that hard. But some specific parameters are hard to understand for me.
Shortcuts like the following.
TCCR0B=TCCR0B&0b11111000|0x01;

What does that?
TCCR0B

TCCR = Prefix for timers. Correct?
0 = Timer1 or 0 call it however you want.
B = What is A,B,C and sometimes D for? What does this?why in that code is the programmer using B and not A,C or D
TCCR0B= Timer 0 B is equal to:
TCCR0B& if Timer 0 B return True .. exists "&" ?
0b11111000 What is this? i already asked this and the answer was something like "clears the low-order 3 bits". Like i said, i'm not very familiar with c++, bits and other stuff regarding the arduino. I now less about the various chips and also about how they implemented the various parameters from arduino ide to work with those chips. I know that i have here 8 values that i can change from 0 to 1. What does those values change relative to the timer. Please think of me as a 6 year old.
|0x01; I got this... it sets the prescaler... 1,8,32.. some timers have differnet values... no problem. I need it at 1.

Related question: http://arduino.stackexchange.com/questions/14298/arduino-uno-vs-arduino-micro-timers-pins/

i already asked this and the answer was something like "clears the low-order 3 bits". Like i said, i'm not very familiar with c++, bits and other stuff regarding the arduino. - OK, you don't understand what "clear the low-order 3 bits" does. Then in another comment you say: This part is actually easy to understand for me as i work alot with coding language. also you can find easely online hex to decimal converters and so on. It isn't clear what you are asking. First you say you aren't familiar with C++ bits, then you say that's not what you are asking.

i needed a simple explaination about what those 3 bits and the other 7 bit change. I also didn't know what ABCD's that are appended to the TCCR0 are for. Those are different registers of 8 bit each. On probably all arduino to change the prescaler you only need the register B. the last 3 bits. those change the multipler. "TCCR0B=TCCR0B&0b11111000|0x01;" this line: timer 0 register B is reset and newly set to 1.Appropriate timers for the arduino micro vs the uno are pin 9,10,12 ... all use timer4 register b...and i need to change the last bits

in your really nice, but to complex answer for me, i cant read that. You don't explain that those 0b11111000 last 3 bits are to reset the timer. you also don't explain what abcd means. then as i asked you more you told me to write a new question.. i did. you got the +1 and the correct answer.

Both Majenko and I posted an excerpt from the datasheet showing what each of the 8 bits in TCCR0B mean. If i don't know what i'm looking for i can't properly consult a 438 pages datasheet. - you look at the part for Timer 1 (or Timer 2 etc.) which is only a few pages. Then you look at the page describing TCCR0B. That describes each of those 8 bits. Each bit has a name (eg. WGMC13, CS10). Underneath the text in the datasheets explains what those bits do. The libraries on the Arduino are to help people write code without reading datasheets. If you want to go further, you have to read them.

i looked the datasheet various times , it's like looking at hyroglyphs. so showing me a part of the hyroglyphs does not the solve problem. i have already dificulties writing and reading everything in english. I need Simple explainations. @Majenko , as he saw that i did not undertsand opened a chat and explained me that those 3 bits are the same bits that change the prescaler... those 3 bits are probably always in the register B of the timer N.those 3 bits needed to be reset than you can change them to whatever you want again.

Let us continue this discussion in chat.

chat!chat!chat!

i tought those... 3 bits change something different somewhere and that A B C & D is some sort of subset of the timer... now it's clear... ABCD is the "memory" of each timer that contains all the various settings... only the 3 bits in memory B change the prescaler. now that i know that also your answer is alot clearer.much clearer than the actual datasheet... they should rewrite the datasheet...

TCCR0B=TCCR0B&0b11111000|0x01; is inscrutable w/o datasheet.  Searching the UNO's ATmega328P datasheet at  https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf for "TCCR0B" has 8 matches, one for section "14.9.2 TCCR0B – Timer/Counter Control Register B" that explains each of the bits, similar to TCCR0B on Micro's ATmega32U https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf . I'd write the clear/set TCCR0B=(TCCR0B & 0b11111000) | 0b001; There's TCCR0A and TCCR0B controlling Timer 0.

First I'll tackle what
TCCR0B=TCCR0B&0b11111000|0x01;

means from a pure programming perspective:
Let's break it down into parts:
TCCR0B = TCCR0B & 0b11111000 | 0x01;

TCCR0B is a register. It could be any variable really - it's just "a value" in this context. Just because it happens to control one of the timers is besides the point.
0b11111000 is a binary representation of a value.  It's the same as the hexadecimal number 0xF8.  F is 15.  15 in binary is 1111.  8 is 8 in both hexadecimal and decimal.  8 in binary is 1000.  Put the two together and you have 11111000.  Incidentally, in decimal that is 248.
0x01 is hexadecimal for 1 in decimal - it's also 1 in binary.
Between them are bitwise operators - & is a bitwise AND operation, and | is a bitwise OR operation.  AND calculates which bits in a pair of binary numbers are both on, and OR calculates which bits in a pair of binary numbers are on in either of the numbers.
So take the first one first.  Say the TCCR0B register contains the value 0x6F, which is 157 in decimal, or 01101111 in binary.  The first operation is to AND that with 11111000:
01101111
11111000 AND
--------
01101000

You can see that the last three bits of the value have been cleared because they aren't 1 in both the left and right operands to the & operator.
Ok, so the next operation is to OR it with 0x01:
01101000
00000001 OR
--------
01101001

Effectively the two operands have been overlaid on each other and any bits that are set in either operand will be reflected in the result.
So finally the value is then stored in TCCR0B.
In summary that specific operation clears the lower three bits then sets the lowest bit of TCCR0B.
Now what that actually means with respect to what the TCCR0B register does can be gleaned from the datasheet for the chip.  For instance, take the ATMega328P chip from the Arduino UNO board.  Section 14.9.2 "TCCR0B – Timer/Counter Control Register B" of the datasheet describes that register in detail.  The bit-wise overview looks like this:

Those bits all correspond 1:1 to the binary bits from above in the same order.  So the first stage, clearing of the lowest three bits, sets CS02, CS01 and CS00 to 0.  The second stage, ORing 0x01, then sets CS00 to 1.
The datasheet goes on to tell you what those mean:

Bits 2:0 – CS02:0: Clock Select

The three Clock Select bits select the clock source to be used by the Timer/Counter.

And a table to show the different meanings of the possible values:

The value that has been masked and created for those three bits is, of course, 001, which in that table is "CLK I/O / (No prescaling)", which is the timer running at the frequency of the IO clock.  If you were to set those bits to 010, you'd get "CLK I/O / 8 (From prescaler)".  So your masking would change to:
TCCR0B = TCCR0B & 0b11111000 | 0x02;

Or more explicitly so you can see the bits easier:
TCCR0B = TCCR0B & 0b11111000 | 0b010;

As to what the "A" and "B" mean (TCCR0A and TCCR0B), there are two registers that are used to control the timer.  They each serve a different purpose.  TCCR0A has bits that control PWM, and TCCR0B has bits that control the timer itself.
Not to be confused with OCR0A and OCR0B which are two separate numeric values that are compared to the timer's counter value TCNT0 to provide two separate PWM outputs (OC0A as Uno pin D6, and OC0B as Uno pin D5) synchronised from the same timebase. (See sections 14.9.4 OCR0A – Output Compare Register A and 14.9.4 OCR0B – Output Compare Register B in the datasheet)

Actually i'm trying to get exactly not that as an answer.I need the part you skipped. This part is actually easy to understand for me as i work alot with coding language. also you can find easely online hex to decimal converters and so on. My question is what that line actually does in simple words. If i don't know what i'm looking for i can't properly consult a 438 pages datasheet. All i know is i need to set a timer to a prescaler of 1. Understanding whats the difference between TCCR1A,TCCR1B,TCCR1C or what those 8bit (0b11111000) represent.

Consider this.. i know nothing. i can code. "TCCR is just a value" you said. Why can't i just write: "Timer1 setPrescaler 1". Why do i need to write "Timer1b dosomething or set to 1"

If i knew where to look in the datasheet i would not be here. All i know is i need to change the prescaler of various pins of various timers of various chips of various boards. And now they are all different.

At the other side. if i would like an answer like this i would ask in stackoverflow and not here. It's an Arduino specific question.

In the datasheet, select "8-bit Timer/Counter0 with PWM" or whatever it's called for your chip.  Then select "Register Description", then "TCCR0B" and it tells you what each bit means.  In the 328p datasheet that's section 14.9.2 on page 109. Indexes are wonderful things.

@cocco On the other-other side, since this has nothing specific to do with Arduino, and is in fact about the ATMega chips that are on them, you would really ask this question on Electronics.SE.  Most people who land here lack the basic programming skills to understand the bitwise operations, hence that is the answer given here - it is an answer for Arduino users, whereas you sound more like you may be looking for an EE answer.

Sorry i didnt mean to be bad... but: those sites are made to simplify the life of people. i'm registered on various stack sites, i answered more questions that i asked. i write code since alot of years now. not c++ in simple javascript php and others... understanding this language is easy for me as it uses almost the same syntax as javascript or php... at the end they are almost the same. i know the bitwise oerators even if they are slightly different in js/php. Each language has it's own function reference. The arduino reference is limited and does not properly describe each function

The quesiton is very specific. It talks about Arduinos. the point is each individual arduino has differences, depends on the chip. I can't find the "Register Description".

The Arduino site only really talks about the Arduino specific API functions, not the underlying language, which is C++.  For anything that isn't specific to the Arduino standard C and C++ tutorials and references should be used (though they don't mention that).  Things like the bitwise operators are standard C so don't get explained properly on the Arduino site.

but also i don't get the difference between TCCR0A,TCCR0B,TCCR0C you said it... they are all the same timer.. so why is there a difference between those values.?

TCCR0A = not arduino specific? not c++?

So basically your saying that TCCR0A is not arduino specific but more Atmel specific? if so tell me where to go to ask this question.

Let us continue this discussion in chat.

i'm in chat if you want

It's specific to the chip that is on the Arduino. Arduino don't make the chip, they just buy them from Atmel.  It's Atmel that defines the registers and what they do.  I have expanded the answer with information about the registers from the datasheet and how to interpret it.

To add to Majenko's very thorough and excellent answer (which I can't yet upvote because I'm very newbie):
Let's try to hone in on the line of code you need:
TCCR0B=TCCR0B&0b11111000|0x01;

On that particular Ardiuno, TCCR0B is the register that controls the rate of that particular timer. More specifically, the lowest 3 bits (the last in the 8-bit value) control the prescaler. The manufacturer labels those as CS02, CS01, and CS00. The combination of 1s and 0s in those three bits determines if the clock time is scaled or not, and by how much (or even if there is an external clock source). The reproduced table 14-9 will tell you how much the clock is "slowed down". This lets you create a 1Hz (1-second) timer, for example, rather than the 16Mhz (or whatever your particular board runs at) by scaling down how fast the timer "ticks".
If you google "Arduino hardware timer calculator" or similar, you can find very helpful tools to help you set the clock frequency you want. Do that, since there are dangers to setting the wrong values, and your compiler may not catch what can be a serious error.
I only learned about hardware timers after exploring Arduino for a few years. Turns out they are very, very useful!

The answer, at high level, is: each bit (or group of bits) in a register is, in practice, like a knob that can configure certain parts of the HW.
For each peripheral you want to control, you have to understand the block diagrams, the related knobs and in which registers those knobs are located.
Sometimes there are multiple (almost) identical instances of a certain HW block and in the ATMega case these instances are often addressed with letters.
So registers that have almost identical names, apart from A, B, C, are basically identical, but each of them will affect a separate instance of a certain peripheral.
Depending on which pins or interrupt you want to use, you can choose the specific instance of a certain peripheral.
You should check the ATMega328p programmer's manual (it's 2k pages, but it's easy to find the desired section.)

I understand your question is not about c++ and bit manipulation.
It's not about "Arduino" neither, because your code line does only make sense for a certain avr microcontroller with a register named TCCR0B.
Sure, some arduinos are based on such microcontrollers and the c++ compiler used in the arduino toolchain allows access to those hardware registers via their names used in the datasheets.
Details however are beyond "Arduino" and should be looked up in the corresponding controller datasheet.

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


text:
Arduino Uno Rx/Tx + Arduino Serial
I was wondering if I can use the Rx and Tx Hardware on the Arduino Uno and also add another Rx/Tx pins using SoftwareSerial at the same time ? cause I need two to communicate with two motor Controllers (Roboclaw controller)
Thx

Yes, you can.  That's the purpose of the SoftwareSerial - to allow you to complement the hardware TX/RX with other pins defined by software.
One thing to note with SoftwareSerial - it's half duplex. It can either send or receive, it can't receive while it's sending.

Agreed. See MIDI decoder demonstration - that reads a MIDI device using SoftwareSerial and outputs using HardwareSerial. As you can see it keeps up with the MIDI gadget. As Majenko said, you can't transmit and receive simultaneously using SoftwareSerial.

You can, but be aware that SoftwareSerial can cause problems if you need strict timing, as it will keep the Arduino stuck while it is receiving, as it polls in interrupt context.
I would recommend to check which one of the two serial channels is more likely to receive data and use the real HW Serial port for it.
The duration of the polling of the SoftwareSerial library is also influenced by the bitrate used on the port: the higher the bitrate, the shorter the duration of the lockups, so try to use the highest bitrate you can afford, on the Software Serial port.
In case you find out that you cannot afford letting SW handle one of the 2 serial ports, you can try the Arduino Mega 250, which has several UART HW blocks.
About the specific use case: if either of your motor controllers supports I2C or SPI, you could consider using that, as alternative to the SoftwareSerial.


text:
counting pulses from encoder on interrupt 0 pin every 50 ms
I want to calculate the number of pulses coming from motor1 encoder pin2 (Int0) as input , and motor 2 encoder pin3 (Int1), I am working now for the first motor (just for the first motor ) so I set timer 2 to count 50 ms then throw flag in this moment I have to send the number of pulses to my screen, but not succeeded cause i see   on my screen zeros and ascii caracters but not the  number of pulses.:this my code .
 volatile int  pulses = 0;

 int flag=0;
 int setbit = 0;
 int encoder_in = 2;
 void count() {

       pulses++;
     }

  void setup()
   {

 Serial.begin(115200);
 pinMode(encoder_in, INPUT);
digitalWrite(2, HIGH); //Enable pullup

// initialize timer2
 noInterrupts();           // disable all interrupts

TCCR2A = 0x00;
 TCCR2B = 0x07;
TCNT2 = 0x64;
//EIMSK = 0x03;     // Enable external interrupt INT0
//EICRA = 0x0f;    // Trigger INT0 on falling edge

 TIMSK2 |= 0x01;  // enable timer compare interrupt
interrupts();             // enable all interrupts
attachInterrupt(0,count,RISING);

 }
  ISR(TIMER2_OVF_vect)
{
TCNT2 = 0x64;            // preload timer
 setbit=setbit+1;
  if(setbit==5)
  {
  flag=1;
 setbit=0;

   }
}

 //ISR(EXT_INT0_vect)
 //{ pulses++; }

 void loop()
{

 if (flag==1)
 {

   Serial.println(pulses);
    pulses=0;

  }
  }

a) what is your question?, and b) what does "not succeed" mean?  Does the  print statement not work?  Is the count it shows inaccurate?  See http://stackoverflow.com/help/how-to-ask

i see on my screen zeros and ascii caracters not number of pulses.

Separate out the problem.  Just try to print ANY integer, and don't worry about counting the pulses until you have this right.  Note that at first glance, your issue seems to have NOTHING to do with what you said it was in the title.

Try changing volatile int  pulses = 0; to volatile int  pulses = 1; and see if you now get 1s printed. Also which ascii characters do you see? Can you give us a sample output.

Do you have anything attached to pins 0 or 1 of the Arduino?

Your technique looks convoluted to me. How about this?
volatile bool counting;
volatile unsigned long events;

unsigned long startTime;
const unsigned long INTERVAL = 50;  // ms

void eventISR ()
  {
  if (counting)
    events++;
  }  // end of eventISR

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (2, INPUT_PULLUP);
  attachInterrupt (0, eventISR, RISING);
  }  // end of setup

void showResults ()
  {
  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of showResults

void loop ()
  {
  if (counting)
    {
    // is time up?
    if (millis () - startTime < INTERVAL)
      return;
    counting = false;
    showResults ();
    }  // end of if

  noInterrupts ();
  events = 0;
  startTime = millis ();
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  counting = true;
  interrupts ();
  }  // end of loop

Explanation
Using a timer to detect when 50 ms is up isn't particularly helpful in this case. You can't do printing inside an ISR, so you would have to set a flag that can be checked in the main loop.
If you are going to check a flag anyway, you may as well just check if the time is up, as my code does.
Inside the ISR, I stop adding to events if the flag counting is false. This is to stop events being changed at the exact moment it is being printed.

that's work thank you Mr Nick, but I tried to calculate for both Motor but it not Works , I Tried  many Times but not works, may you  can see my code:

whats the "Return" instruction in loop() exactly do.
I am working to calculate for the second Motor but it not work.

may you can see my code - amend your question to add this new code so I can see it.

whats the "Return" instruction in loop() exactly do - it returns from the loop() function, which then gets called again.

Check the Baud Rate in Serial Monitor. If baud rate is not correct i.e. 9600 bps then it will show garbage.
Remove the Timer and Wire Libs
add this code in void setup()
attachInterrupt(0,void_counter,RISING);

the above is for the the external interrupt input.
and attach your sensor/incoming pulse wire on Pin 2 on arduino.
make a new function like this
void_counter(){
pulses++;
}

I agree with this. But it is more appropriated as a comment.

New to stack exchange.

Also he already enabled the Interrupt, but by registers

i did this change before and now too i did what you told me, but  I still see characters like {0¤0, A,P,. . }

I see the pulses on oscilloscope but still I cant see the number of pulses on my monitr


text:
How can I add additional boards to Eclipse with the Arduino add-on with only a URL, not a zip file
I want to add the following boards:
https://redbearlab.github.io/arduino/package_redbearlab_index.json
Which I can add in the Arduino IDE by going to File -> Preferences -> Additional Boards Manager URLs and just pasting it there
Where is the equivalent function in Eclipse, or how do I configure Eclipse to allow me to develop for those boards?
From Eclipse, I have tried Window-> Properties -> Arduino and from there "Private Library Path" and "Private hardware path", and I have tried pointing them to "C:\Program Files (x86)\Arduino\hardware" and "C:\Program Files (x86)\Arduino\libraries", but that didn't seem to change anything (i.e. no new board options, even after running Eclipse as admin) - while the boards show up (examples and all) in the Arduino IDE

Until someone writes such a capability, there is none.

Read the JSON data, find the URLs, and download the zip files.  Then use your normal method of adding boards from zip files.

@Majenko so the zip files are all I need? I also see some .tar.gz stuff for the tools (i.e. gcc/etc.) - would I treat them the same way?

If you need tools they will also be in the JSON file.  Do the same with them as you do with the boards. I don't know Eclipse, so I don't know how you "install" things in there. You said you know how to do it with zip files, well the zip files (and all other forms of archive) are listed right there for you. The rest is up to you.

With arduino eclipse plugin 2.4 you simply install the boards with the arduino ide -like you described- and you can use then in the arduino eclipse plugin.
Version 3.0 (that is the nightly as 3.0 still needs to be released) contains it's own boards and library manager in windows->preferences->arduino.


text:
How to power an Arduino Uno with 3 1.5V batteries?
I have an Arduino Uno (a SainSmart model, actually). I intend to power it with three 1.5V batteries. I measured them and they yield 4.67V in total. The Arduino requires 5V.
The question is, if the arduino will work this way.
I'm not powering complicated microcontroller components here. These components are used:

A buzzer
An LED
A unit of 4 seven segment displays
A couple of buttons as input elements

If the volume or brightness of these components is slightly decreased, it doesn't matter at all. But I would like to know if it will work in the first place.
And also...
Where exactly do I plug the power source in? The power jack, the USB jack, pins, somewhere else?

The schematic looks like this, just to illustrate it. I'm not a good drawer, but you'll get the idea...

According to the datasheet of the ATmega 328P (figure 29-1, page 303), you need at least 3.78 V to run the Arduino at 16 MHz. This is 1.26 V per battery. Many 1.5 V batteries will drop below that level way before being exhausted. You can use the clock prescaler (c.f. chapter 9) to throttle down the clock to 8 MHz (minimum = 2.4 V), at which frequency you can use the full capacity of your batteries. But your timing functions will be off by a factor 2.

The Arduino doesn't require 5V.
The Atmel chip on the board requires somewhere between 1.8V and 5.5V, the Arduino just happens to have chosen 5V as a good common widely used voltage to run at.
If you provide a voltage within that range to the +5V pin the board will operate.  There's a couple of caveats though:

Anything below about 4V will mean the 3.3V regulator won't be working right, so the 3.3V pin won't be functioning properly
At lower voltages the Atmel chip can't operate reliably at higher frequencies, which is why 3.3V Arduino boards operate at 8MHz instead of 16Mhz.

So 3 x AA batteries is a perfect power source for running the Arduino, direct into the 5V pin.  Just make sure that you don't power it any other way at the same time or you'll be pumping 5V into your batteries.  You may want to add a Schottky diode in series with your battery + (between battery + and the 5V pin) to stop that ever causing a problem.  Choose one with a very low forward voltage drop though, otherwise you could end up dropping too much of your precious voltage over the diode.
By the way, when you're powering it from USB the 5V could be anywhere between 4.75V and 5.25V.

So the 5V output pin is a 5V input pin at the same time?

@bytecode77 The 5V pin doesn't have a "direction". It's just a connection to the 5V power rail.  You can use power from it, or you can give power to it, depending on what power you have where.

Good. Very nice answer by the way. Lots of facts, information beyond the asked question. +1!

As per @Majenko's answer, yes, this will work fine.
Some caveats: the Atmel chip at the center of the Arduino has brown-out detection - if it drops below a certain voltage, the chip will shut down. This voltage is selectable: 4.3v, 2.7v, 1.8v, or off. The factory default for the chip is "off", I found a reference that the Uno sets this at 2.7V.
Also, if you are powering anything else with your battery, e.g. a motor, the voltage is will drop - if it drops below the brownout, the arduino will shut down (usually also shutting down the external device, causing the voltage to rise again, causing it to power up again). An LED (with a correct resistor) should be fine.

2.7V as the threshold sounds fair. And my components draw constant and very low current (I think).

Just something to remember if your project seems to be randomly resetting.

While I have your attention: How long do you think I can operate an LED, 4 seven segment displays and a buzzer (buzzer has a duty cycle or 7,5%) with 3 1.5 AA batteries?

@bytecode77 That depends if you invest some time in learning how to use sleep mode or not.  I am in the process of designing a PIC32 based system with LCD screen and all sorts that can run for a month off a small PP3 9V battery.

You mean that the Atmel chip doesn't consume energy when it doesn't do anything? As far as I saw it, delay() does nothing more than a blocking for-loop. But that's a different question, I will also look into that. Does the Arduino drain much current when running?

40-50mA while running. If you enable sleep you can reduce that significantly.

@Majenko "delay" draws about 50mA (same as doing anything else). You can, however, put the Arduino to sleep. If you want to save power, read Nick Gammon's most excellent treatise on the matter at http://www.gammon.com.au/power. Having said that, one LED uses 20mA (40% of the Arduino running at full power), I'd imagine 7 segments use that per-segment (check the data sheet!). There are tricks to reduce this - PWM being the usual one for LED and LED segments. I'm guessing you're not going to run the speaker continuously. How much the speaker draws depends on the speaker, and how much you use it.

Why are you telling me? Tell bytecode. By the way most LEDs are plenty bright enough at 1mA. Just because the upper limit its usually around 20mA doesn't mean you have to run them at that.

For battery-operated Arduino Uno's I recommend thinking bigger (in terms of power, not physical size).
I power several by using 3x 18650 batteries in series, (providing about 14 Volts, connected to a 4x USB 5 Volt module.
The Unos are connected to power by a standard USB cable (into the programming port), and then you also have 3 other 5V USB charging or power ports available.
Or you can get a small converter unit that provides just one 5V USB.
Either way, bringing the power to the UNO is as simple as using the programming cable that comes with the board.
Or you can use any other converter and use wires to bring in Vin and GND.
You don't need to use 3 of the 18650s.  2 will do fine.  Or 4 in series/parallel for longer battery life.  No converter would be needed but again you would need wires to bring the voltage into the Unos.
18650s are very common, and are inexpensive.  They pack a whole lot more mAh than any AA battery you will find.
One warning about buying 18650s:  There are Chinese companies that advertise 9,800 mA batteries.  Don't believe it.  3,000 is about the max any reputable manufacturer will claim.

You can power the Arduino via the 5V pin - but you need make sure you disconnect it when you are connected via USB - ie. don't power both the 5V pin and via the USB.
Any even better way is to power it from the USB socket - I use those emergency Phone battery packs, but you could cut up a usb cable and use that - this is a much better socket fit to use than the 5v pin and more energy efficient than passing a higher voltage through the 9V supply.

The requirements of my project are tight and therefore batteries are the only options. But still useful information to keep in mind, thanks.

@user23096 - are you suggesting you could use the USB power socket  and still use batteries by wiring a AA batteries to a USB cable that is cut off at one end and the other end plugged into the board?  (I am a noob - forgive the stupid questions)

authors: Μάνος Σταθόπουλος


text:
I can upload via USB but not FTDI
I have a Adafruit Pro Trinket. I'm having issues getting GPS and and SD card working together. The trinket can be connected via USB but there is no serial connection do debugging my program is hard.

I purchased an FTDI connector from sparkfun, installed the FTDI software and connected to the trinket. My code complies but it won't flash. The error is confusing:
Can anyone please help me figure out how to get it to flash?
Arduino: 1.6.4 (Mac OS X), Board: "Pro Trinket 3V/12MHz (FTDI)"

Sketch uses 19,896 bytes (69%) of program storage space. Maximum is 28,672 bytes.
Global variables use 1,476 bytes of dynamic memory.
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1a21": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Here is the "verbose" version of the error:
Arduino: 1.6.4 (Mac OS X), Board: "Pro Trinket 3V/12MHz (FTDI)"

Using library SPI in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SPI
Using library Adafruit GPS Library in folder: /Users/futurebird/Documents/Arduino/libraries/Adafruit-GPS-Library-master
Using library SoftwareSerial in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial
Using library SdFat in folder: /Users/futurebird/Documents/Arduino/libraries/SdFat (legacy)

/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=12000000L -DARDUINO=10604 -DARDUINO_AVR_PROTRINKET5FTDI -DARDUINO_ARCH_AVR -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/variants/eightanaloginputs -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SPI -I/Users/futurebird/Documents/Arduino/libraries/Adafruit-GPS-Library-master -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial -I/Users/futurebird/Documents/Arduino/libraries/SdFat /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp -o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.o
Using previously compiled file: /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SPI/SPI.cpp.o

(^^repeats many times for different files)

/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc -Wall -Os -Wl,--gc-sections -mmcu=atmega328p -o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SPI/SPI.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/Adafruit GPS Library/Adafruit_GPS.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SoftwareSerial/SoftwareSerial.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/MinimumSerial.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdFatBase.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdFatUtil.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiCard.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiSAM3X.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiSTM32F1.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiTeensy3.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFile.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFileLFN.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFilePrint.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFileSFN.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatVolume.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FmtNumber.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/fstream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/istream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/ostream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/StdioStream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/core.a -L/var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp -lm
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.eep
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.hex

Sketch uses 19,896 bytes (69%) of program storage space. Maximum is 28,672 bytes.
Global variables use 1,476 bytes of dynamic memory.
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbmodem1a21 -b115200 -D -Uflash:w:/var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/futurebird/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbmodem1a21
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1a21": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

UPDATE
I looked in the /dev/ directory and found these which match the menu in Arduino.
cu.Bluetooth-Incoming-Port
cu.Bluetooth-Modem
cu.JabraREVOa400-SPPDev
cu.LightBlue-Bean

The above files are int the dev folder but not cu.usbmodem1a21. How can I get it? Or is it looking for the wrong file?
This is what my board selection looks like. I think the issue is the port?

"can't open device "/dev/cu.usbmodem1a21": No such file or directory"

I made an update after looking for the file.

Have you installed the FTDI driver? The error message means avrdude can't find your trinket.

Things to check:

Does the file exist? check with ls if the file that avrdude tries to open is actually there
Do you have the right to open it? Opening a serial port requires having the appropriate rights, iow you user belongs to the same group that the device belongs to.
On linux this is usually wheel or dialout, depending on the distro. Again, ls -la is your friend.
Is your device identified correctly? Meaning that you are not trying to have avrdude address the device wit the wrong protocol.

The device is identified as Adafruit pro, 3v FTDI. I can flash successfully with Adafruit pro, 3v USB. The file in question is not there. I don't know how to get it ... or ... I suspect another file since the file is the name at the bottom of the compile window.


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:
What does a higher clock signal frequency actually mean for my AHRS?
I've got an Arduino with an ATmega328 processor. It can be operated at 3.3V which nets a clock signal frequency of about 12 MHz respectively 16 Mhz at 5V.
I've got an IMU connected to the Arduino and a AHRS algorithm turning accelerometer, gyroscope and magnetometer data into orientation data.
What does the higher frequency of 16 MHz actually mean in this context?
Will the AHRS be calculated faster so I get a lower latency? Can I poll the sensors more often? I want a deeper understanding of what I'm doing here.

What does the higher frequency of 16 MHz actually mean in this context?

The Arduino will run a bit faster (33% faster). Therefore it could calculate things faster. Whether you can poll the sensors more often might depend on the sensor. Limiting factors could be how fast you can communicate with the sensor, how often the sensor takes readings, what you are going to do with the readings, and whether it matters if calculations are a bit slower.
For a better response I suggest you post a link to the particular sensor, the AHRS algorithm you are using, and describe the application you are using it for.

Thanks Nick, this was just about making sure that I "get it". I'm already satisfied with how my AHRS performs. I'm interested in improving the latency of my system but there are worse bottlenecks like the serial communication via Bluetooth, how fast my node.js middleware processes it, how fast that communicates with the actual application I'm using it in.


text:
What does “LSB per degree per second” mean?
I'm currently working with a digital output gyroscope. Its sensitivity is given as 120 least-significant bit per degree per second.
While every single component of that unit is easy to understand I don't quite get what it means altogether.
Can you explain it to me?

Which digital output gyroscope?

There is a similar post in this forum with an answer which I find much easier to understand.

Let us say we have a number, "4025". The "most significant digit" of the number is the 4 in the thousands position, since it tells us the most about the magnitude of the number ("in the four thousands"). Consequently, the "least significant digit" is the 5 in the units position, since it tells us almost nothing about the magnitude of the number. "Most/least significant bit" is the same, except it applies to binary numbers (which the MCU cares about, of course; we can still use any radix we like to talk about them). So the device's output count can change by up to 120 per degree per second.

Isn't the LSB in a binary number always either incrementing the number or not? I mean  the value of the LSB has to be always 1 or 0. I understand what the LSB is but not its roll in the unit.

@Hedge: 125 is 2 LSBs greater than 123.

I don't really understand the question, nor the answer. What does "120 least-significant bit per degree per second" mean? Let's say the gyroscope returns some units. Without knowing the model they could be anything, but let's say it's 100th of a degree. Isn't that just saying it is accurate to 120 units per degree per second? I mean, a least-significant bit is 1, right? So that is 120 x 1 (of whatever units) per degree per second?

@NickGammon: The gyro returns a count. 1 LSB is 1 count.

Didn't I say that? Why doesn't it just say "120 counts per degree per second"? I mean, that's like saying LSB of 1 + LSB of 1 = 2.

@NickGammon: Because long, long ago someone decided to call it that.

OK I will give you +1 LSB of rep for that. :)

Here's a real example for the MPU6050, when set at 250 degrees/sec range. The code says that is 131 LSB/deg/sec. The code returns a signed 16 bit int, from -32768 to 32767. The 250 degree range divides into the 32767. 32767 / 250 = 131. So if the part comes back with 262, take that and divide by 131, and you get 2 deg/sec rotation. 32767 is 250 deg/sec rotation, etc. Back to the original question and the part Hedge is using, and @NickGammon is right, it really translates to "120 counts per degree per second".

With further elaboration on Ignacia's answer:
A gyroscope itself is generally an analog device in the sense that in reality, it will have a continous output. This output is digitized using some form of Analog to Digital A/D converter where the analog output is converted to a digital number. The output from the gyroscope is a measurement of angular speed, generally millidegrees/sec.
The number read by your Arduino from the gyroscope will be a digital version of your current angular speed at the time of measurement. For example, if you're getting an 8bit number back equal to 121, this in binary is equivalent to 01111001, where the '1' furthest to the right is the least significant bit.
The term "lsb per degree per second" means how many bits change with your angular speed. For example, with a gain of 1 (meaning 1 degree/second = 1 bit), an angular speed of 90 degrees/sec will produce a read value of 90 or 01011010. Therefore, 1 bit changes per degree/second. Increasing the essential "gain" (which will most likely be referred to as "dps" will change how many lsb's change per degree/second.


text:
Pass a member function pointer to a method of a foreign class (EDB Lib)
I'm currently working on my own arduino library and I'm becoming exasperated with the following problem: I want to store data with the extended database library (https://code.google.com/p/arduino-edb/) on a sd card. I tried to follow and adapt the instructions on this page and I gave my custom library a property "File dbFile" as well as a property "EDB db". Additionally I have to pass two function pointers to the constructor of the EDB library. So my custom library got two more properties: a writer and a reader function. My class looks roughly like that:
class myLib
{
   public:
      myLib();
      ~myLib();
      void configWriter( unsigned long address, byte data );
      byte configReader( unsigned long address );
      File dbFile;
      EDB configDB;
}

...so far so good. But here comes the pain in the ... When I'm trying to instantiate a new EDB object in the constructor of my class by passing two pointers to the member functions I'm constantly getting an error. Here is how I call the constructor of the EDB library:
configDB = new EDB( &myLib::configWriter, &myLib::configReader );

I get the following error:

no matching function for call to 'EDB::EDB()'
[...] note: candidates are:
note: EDB::EDB(void ()(long unsigned int, uint8_t), uint8_t ()(long
  unsigned int))
       EDB(EDB_Write_Handler *, EDB_Read_Handler *);

The prototype of the EDB constructor looks like this:

EDB(EDB_Write_Handler *, EDB_Read_Handler *);

EDB_Write_Handler and EDB_Read_Handler are defined like so:

typedef void EDB_Write_Handler(unsigned long, const uint8_t);
  typedef uint8_t EDB_Read_Handler(unsigned long);

So I assume that my constructor call doesn't work because the functions that I'm passing are from a foreign class: (myLib::) and not just ()
I have no idea how to solve that problem. Does someone of you have any idea?
Thanks,
Andy
EDIT:
Here is a Minimal, Complete, and Verifiable example:
myLib.h:
#ifndef myLib_h
#define myLib_h

#include "Arduino.h"
#include <SPI.h>
#include <SD.h>
#include <EDB.h>

#define SD_CS 4
#define SD_SS 10

class myLib
{
  public:
    myLib();
    ~myLib();
    void begin();
    void configWriter( unsigned long address, byte data );
    byte configReader( unsigned long address );
    File dbFile;
    EDB * configDB;

};

#endif

myLib.cpp:
#include "myLib.h"

myLib::myLib( void )
{}

myLib::~myLib()
{}

void myLib::begin()
{
  // Init SD
  pinMode(SS, OUTPUT);
  SD.begin(SD_CS);

  // Load Config
  configDB = new EDB( &myLib::configWriter, &myLib::configReader );
  dbFile = SD.open("config.db", FILE_WRITE);
}

void myLib::configWriter( unsigned long address, byte data )
{
  dbFile.seek(address);
  dbFile.write(data);
  dbFile.flush();
}

byte myLib::configReader( unsigned long address )
{
  dbFile.seek(address);
  return dbFile.read();
}

Arduino sketch:
#include <SPI.h>
#include <SD.h>
#include <EDB.h>
#include "myLib.h"

myLib* a;

void setup()
{
  a = new myLib();
  a->begin();
}

void loop()
{
}

Have you tried passing it methods of an instance instead of the class?

new EDB( &this->configWriter, &this->configReader ); like so? already tried it. same problem...

The problem here is a common one with C++.  It basically boils down to how C++ handles member functions.
You define a member function as, say,
class myLib {
    void myFunc(int val);
};

When you call the function it's actually not defined as that - it's instead had its definition change to:
void myFunc(myLib *this, int val);

The addition of the myLib *this is an implicit parameter, and it's how C++ keeps track of its object instances when calling different functions.
So a function which expects a parameter of void (*func)(int) won't accept your method because it's actually void (*func)(myLib *, int).  Hence the error you are seeing.
There is no easy, clean, way around it that I have found as yet, I am afraid.  The closest you can do is to move the reader and writer functions outside of your class and store a global pointer to the actual class, something like:
static myLib *globalLib;
void globalConfigWriter( unsigned long address, byte data ) {
    globalLib->congigWriter(address, data);
}
byte globalConfigReader( unsigned long address ) {
    return globalLib->configReader(address);
}

Then in the constructor for your lib you can do:
myLib::myLib() {
    globalLib = this;
}

You then register the global reader and writer functions with the EDB constructor instead of the class member functions.
It does have the rather major down-side that there can only be one instance of your class since there is only one global pointer and only one pair of reader / writer functions.  There are ways of supporting a finite number of instances, but it basically involves having a reader/writer pair for each instance and allocating one to an instance when it's constructed and de-allocating it when its destructed.  Keeping track of them and knowing which object is associated with which function pair is tricky at best...

Thanks, Majenko for your easy explanation! Now I can see where the problem is. Being able to create only one instance of the class isn't a problem in my case. I'll give your solution a try and let you know how it went.

Can you post a  Minimal, Complete, and Verifiable example? We don't care what the functions do, just make up an example that demonstrates the message.

Having said that, this looks wrong:
class myLib
{
   public:
      myLib();
      ~myLib();
      void configWriter( unsigned long address, byte data );
      byte configReader( unsigned long address );
      File dbFile;
      EDB configDB;
}

Here is how I call the constructor of the EDB library:

 configDB = new EDB( &myLib::configWriter, &myLib::configReader );

OK so myLib is a class, not an instance of a class.

The prototype of the EDB constructor looks like this:

    EDB(EDB_Write_Handler *, EDB_Read_Handler *);

So you want an instance of EDB_Write_Handler.

Let's say that EDB needed a dog and a cat. You don't pass "dog" and "cat" you pass "Fido" and "Fluffy". They are instances of the classes.

You have this:
configDB = new EDB( &myLib::configWriter, &myLib::configReader );

The constructor for EDB expects two functions:
EDB(EDB_Write_Handler *, EDB_Read_Handler *);

These are declared like this:
typedef void EDB_Write_Handler(unsigned long, const uint8_t);
typedef uint8_t EDB_Read_Handler(unsigned long);

These are static functions, that is, they cannot be class functions. Why not? Because a class function has an implicit pointer this which points to this instance of the class.
So, you cannot pass a non-static class-function to the EDB constructor.
Now you can make the functions configWriter and configReader static, but then they can't access class variables (eg. dbFile) because they belong to an instance of the function.
I've tried fiddling around with your code, but without a clear understanding of your intentions, I can't get it to compile. Do you mean to derive your class from EDB?
Why do you even want a class myLib? Are you planning to have multiple instances of it? If so, why? If not, why make a class?

Thanks for your reply Nick! I'm quite familiar with the difference between a class and an instance (aka object) of a class but I'm a little unsure when it comes to the syntax of c++. Thanks for your suggestion! I've added a minimal, complete, and verifiable example.

See amended answer.

This is not at all an Arduino problem. It is a C++ problem.


text:
Arduino Servo.h library returns error in compilation
I have a problem with Servo library. This is my (very short XD) "code":
#include <Servo.h>

void setup() {
  Servo.attach(9, 554, 2400);
}

void loop() {
  Servo.write(2000);
}

And it returns:
Arduino:1.6.5 (Windows 7), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

sketch_aug24a.ino: In function 'void setup()':
sketch_aug24a:4: error: expected unqualified-id before '.' token
sketch_aug24a.ino: In function 'void loop()':
sketch_aug24a:8: error: expected unqualified-id before '.' token
expected unqualified-id before '.' token

Like there is no included library. What can I do with it ?

Servo is a class not an object. You have to instantiate it, and then call the functions on the instance. For example:
#include <Servo.h>

Servo sv;

void setup() {
  sv.attach(9, 554, 2400);
}

void loop() {
  sv.write(2000);
}

(Unlike some other libraries, it's done this way so that you can use more than one servo at the same time. You'd make one instance for each servo you want to control.)

Oh, I get it :o Clever!

But I think, my servo is broken ;_;, dammit xd


text:
ESP8266 as I2C client
I've got an ESP8266 that takes instructions from a web page and sets a series of NeoPixels to flash in different sequences.
I noticed that when the Wi-Fi got data and parsed it, my LEDs would "stutter" as the processor ignored them for a moment while processing the incoming instructions.
So I added a 2nd ESP8266. This one just handles the LEDs. So the 1st ESP gets the Wi-Fi data and parses it. It then sends an interrupt to the 2nd ESP which breaks out of the LED display loop, checks the interrupt pin for HIGH or LOW and sets the LEDS based on HIGH/LOW.
However, I would like to send more data from the Wi-Fi ESP to the LED driving ESP. e.g. Colour data, transition speed, rotation direction etc. All of these settings I can send to the ESP from a web page.
I thought I2C (the wire library) would help but all comments seem to say that the ESP8266 cannot act as a slave so I can't send to it.
So it appears I'm left with Serial comms (the interrupt is over by the time comm start because I realize Serial does not work in an interrupt).
So my questions are:

Am I right that I2C will not work?
If I am wrong does anyone have a working end to end example?
If I am right is there an approved way to do ESP to ESP serial comms?

I assume that you are using the Arduino core for the ESP8266 (https://github.com/esp8266/Arduino)

Am I right that ic2 will not work?

I am not certain, but I get the same impression as you.  It seems that the Expressif SDK only supports master mode.

If I am right is there an approved way to do ESP to ESP serial comms.

There is no "approved way", but there are many ways you can do it.  A direct serial link will give you a simple pipe of data - what you put in at one end comes out the other.  It's up to you to decide how you format and interpret that data.
My ICSC library may help you with that - I use it to connect an ESP8266 to an BeagleBone Black through serial: https://github.com/MajenkoLibraries/ICSC

The issue with the ESP8266 is that it is multitasking, and only 80% of the CPU time is available to developers. This manifests as an outage of 100-200us every 500ms or so, which rather complicates all sorts of software serial interfaces, such as I2C, SPI and UART. As a bus master the ESP8266 hides these issues as it is responsible for the bus clock, but as a bus slave it needs to halt data transfer for the duration of these random events.
A typical solution for this inter-CPU issue is to provide an external RAM cache to act as a mailbox, where each CPU will periodically check to see if any actions are outstanding and leave any requested data.
Has anyone explored this option for the Arduino to ESP8266 interface?

If you wish to ask a question please use the "Ask Question" button in top right corner.

I am not certain, but I get the same impression as you.
  It seems that the Expressif SDK only supports master mode.

Sorry no.
Espressif SDK supports Slave Mode too.
official the Master works with 50 kHz (CPU 80MHz), and  100 kHz in technical referenz  and unofficial in my test with !1.2MHz you must switch then to the 160 MHz CPU and you must work for delays with
asm ("nop") 12.5 ns at 80MHz and 6.25 ns at 160 MHz
then you can toggle the pins at 80 MHz with 700 kHz and with 160 MHz with 1400 kHz. because there are instruction to the gpio ( toggle output low, "opendrain" clear output with pullup high ) it will be a netto rate of
620 kHz, and 1260 kHz.

best wishes
rudi ;-)

Read in
http://bbs.espressif.com/viewtopic.php?f=49&t=2092#p6897

youtube video:https://www.youtube.com/watch?v=P_KAMJCImzA


text:
Two sensors on one input
I got this question from my teacher the other day and I can't figure it out:

If you have two sensors from two different outputs but want them to go into one input, what do you need, and how can you read the input?

In short, the project includes an Arduino Uno with two ultrasonic sensors.

Well, i guess one correct answer would be "Multiplex",  you'll have to switch the outputs inside the loop(). One output have to be HIGH during the other one is LOW, so you always get the input from one sensor only. Ofc you'll have to check which sensor is active to get the correct sensors signal. Another way would be using analog input and different resistors for each sensor. So you get different voltage signals from the sensor.

I think those unit pull low to send a signal. So you could use just two diodes. Though I'm unsure where the out signal is going, as most ultrasonic units have only one SIG pin to use as both input and output.

If you multiplex then you need another pin to control which multiplexer input is going to be selected. Please state which sensor you are planning to use. Without knowing any more the "two diodes" answer seems to be the most likely.

There are two basic solutions to your problem, an active one and a passive one, and which is best (or will even work) depends on the rest of your setup.
The active solution requires a device called a multiplexer.  This is basically a switch and it selects one of its inputs to route through to its output, so it can be used to connect your input pin to the output of one of the sensors.  It requires an extra IO pin, though, so is pretty pointless as you could just use that IO pin as an input from the second sensor.  It does mean, though, that both sensors can be active at once and you just select one to read the output from.
The passive solution is called open drain or open collector (if you are using TTL not CMOS terminology).  This means you convert each of the outputs of the sensors into a switch using a transistor (NPN BJT or N-Channel MOSFET) to connect your input pin to ground.  When then transistors are off the input pin is pulled up through a pullup resistor (could be internal or external to the IO pin).  When one sensor's output activates it turns on the transistor which then pulls the input pin low.  This means that you can only have one sensor active at a time, so they have to be triggered by separate output pins.

Open Drain is how things like I2C support multiple devices on the same bus without any voltage conflicts.

Isn't it right that the Multiplexer is not needed as you can switch the outputs by yourself in code?

@nouseforname As long as you have separate outputs to control the sensors then the second (passive) option is for you. That is why that's the option that I put most detail into.  A multiplexer may be needed if the signal is analog though (analog mux) since the OD won't work for that.

understood, i am also new to this and just learned i can do the "multiplexing" in code...thats why i asked. Your solution seems to be  the very perfect one for this case here

Is it a diode in a parallel with the MOSFET?

That is called the body diode and is integral to all MOSFETs.

As I know the MOSFET, then input (1) is gate, output (2) is source and ground (3) is drain?

No, 2 is drain, 3 is source.  The source always connects to the most common point (ground in this case) since it's the voltage difference between the source and the gate that controls the MOSFET - in this case that's the voltage difference between the gate and ground.

I think the last one is the right one though I can't figure out how to implement it in my figure

The outputs of your two ultrasonics go to the INx pins on the schematic.  The OUT of the schematic goes to the IN on your drawing.  The Vdd is the +5V pin of the Arduino and the ground symbols go to the GND pin of the Arduino.

Let us continue this discussion in chat.

Assuming IN1 goes HIGH, there will be a low impedance path between OUT and ground. Won't this cause excessive current to flow out of the OUT pin? Or is there a resistance to the right hand side of the OUT that isn't shown? And if there is, what would happen if the user erroneously set the pin to be OUTPUT (either through real error or because the previously loaded sketch had it set up this way and he's only just plugged it in to write the real sketch, if you know what I mean.)

This solution only actually uses one pin, but only works with simple things like push buttons (which are either open, or closed).
Connect a (different) resistor in series (end-to-end) with each switch. Connect the loose end of each resistor together to +5V. Connect the loose end of those two switches together, then via another resistor to ground. Where the two switches meet, connect them to an analog pin on your Arduino.
For example, you might use a 20k resistor with button A, and a 10k resistor with button B, and a 10k resistor connected to ground. They should be pretty close to the same value, and at least 1k each.
Use the ReadAnalogVoltage sketch to measure the voltage with different combinations of button presses (no button pressed, A, B, A+B), then, in your final sketch, you can compare the value read with the values in this table - pick the closest one, because actual readings may vary slightly. For the resistors above, you should get about: (no button = 0v; A=1.7v, B=2.5v, both 3v). Sort these numerically (which in this case they already are), and work out the values exactly between each pair (up to 0.85 is closest to 0=> no button; else up to 2.1=> button A; else up to 2.75 is closest to B; otherwise, both are pressed.
The circuit described looks like this:

The wire leading off to the right goes to the analog pin on the Arduino. Switch A is on the left.
The results can be used either in a table, with a loop, or in an if/else if statement (I used this technique on a 12-key keypad, so the list was a lot longer).
Read up about voltage dividers https://learn.sparkfun.com/tutorials/voltage-dividers and, for both buttons being pressed at the same time, resistors in parallel https://learn.sparkfun.com/tutorials/series-and-parallel-circuits

If you have two sensors from two different outputs but want them to go
  into one input, what do you need, and how can you read the input?

If you want your teacher lose his mind answer his question with this:
What I need? :)

A wire

The solution is to use one trig for both ultrasonic sensor and two echos.
or one echo and two triggers.
ultrasonic sensor sends the pulse > pulse back > now echo pin is connected to second sensors trig > the Second Ultrasonic sensor sends the pulse then starts listening. When the second ultrasonic echo back, it sends to other Arduino pin, reverse it if you want it on one input pin :)
#define trigPin 6
#define echoPin 4
#define echoPin2 7

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
   pinMode(echoPin2, INPUT);
}

void loop() {
  long duration, distance, distance2;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(20);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  duration = duration + pulseIn(echoPin2, HIGH);
  distance2 = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println("cm");
       Serial.print(distance2);
    Serial.println(" cm");
        Serial.println("HHH");
  }
  delay(500);
}

that's it.

I ran into the same question, except I wanted to put 8 of the HC-SR04 sensors on pro-mini.
I used an I2C pin expander for the triggers, and an octal OR/NOR chip to multiplex the return.
Library, examples and pictures
https://github.com/arielnh56/SonarI2C
http://redhunter.com/blog/2016/04/28/sonari2c-multiple-hc-sr04-sensors-on-arduino-i2c/

The OP does not specify whether the focus is on hardware or software.
So I will presume that what the professor might looking for is a solution using minimal circuitry; as close to the diagram as possible.  Thus, the solution would be implemented in software.
Given all that, I'd propose that the trigger signal be sent out on sensor 1, and the reflection measured at the receiving pin.
It is time-gated (the time for the sensor to react to an object at maximum range).  If detected, then set a variable saving the distance measured on sensor 1.
Then the same could be sent from the second sensor's trigger pin.  And if there is a reflection within the time-gate then that can be recorded in another variable.
It would require creating two instances of the ultrasonic sensor, and they would just happen to share the same receive pulse pin.

Try the above logic use a 555 timer with  C1: 10uF, R2: 300k and R1: 30k for 1.1 sec switching time,now for approx every one second data from USS1 goes to SIN(Arduino IN) when the timer OUT is high and  similarly when timer OUT is LOW signal from USS2 goes to SIN(Arduino),,,
But you will not be able to know from which sensor is the output coming.
If you would like to know from which sensor the output is coming you can just add one INVERTER to one of the branch so so both the sensors will give different states i.e one will return HIGH and other will return LOW
hope this helps
Edited:Please note 555 timer design part is not complete ,,i am just giving an idea :)

A SPDT switch would fit nicely in your diagram where the question mark is.

The question is two Ultrasonic data get input on one.  Its simple.  You just need two IDs.  Creat a IDs of each sensors.  You can use I2C bus too.  You need to hub who keep the two input in raw.  And than digitally write with address and than do codding for read the data.  Howz my idea guys?

Welcome to Arduino Stack Exchange.  Please take the Tour at https://arduino.com/Tour to get the most out of this site.  FYI - Normal ultrasonic detectors do not work on I2C - they wrok by pulsing a signal pin then monitoring an output pin.  The library measures the time and infers the distance.


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.