text:
Does IDLE Mode not power down an ATtiny85?
So I'm trying to power down my ATtiny85 to save power, but for some reason the ATtiny doesn't power down when I'm using the default IDLE mode, but when I start using the SLEEP_MODE_PWR_DOWN the ATtiny appears to go to sleep.
I'm testing it by calling a checkPower() method that blinks an LED after the sleepNow() method. In other words, if the ATtiny goes to sleep then the checkPower() method should not be reached and the LED should not blink. Here is the code:
void loop()
{
  doStuff();
  sleepNow();
  checkPower();
}

void sleepNow()
{
    // Choose our preferred sleep mode:
    set_sleep_mode(SLEEP_MODE_IDLE);
    // Set sleep enable (SE) bit:
    sleep_enable();
    // Put the device to sleep:
    sleep_mode();
    // Upon waking up, sketch continues from this point.
    sleep_disable();
}

void checkArrays()
{
  for(i = 0; i < 15; i++)
  {
     digitalWrite(1, HIGH);
     delay(1000);
     digitalWrite(1, LOW);
     delay(1000);
  }
}

Any idea why my LED would continue to blink when using the IDLE mode but no the PWR_DOWN mode?

In IDLE mode the timers still run. Arduino uses timer0 for millis. So when timer0 overflows the ATTiny will wake up and call the ISR.
So the ATTiny will go to 'sleep' but wake up a number of microseconds later.

So what can I use besides IDLE? If I try PWR_DOWN I won't be able to use an interrupt to wake the microprocessor. Is there an alternatice. Also how long does IDLE make the ATtiny sleep?

You can wake from power down using either a pin change interrupt or a watchdog timer interrupt.

@IsabelAlphonse: IDLE is fine. You just have to check, whenever you wake up, if there is job to do. If not, just go back to sleep.

As bigjosh said, pin change and watchdog timer interrupts will wake the processor from power-down. See my page about power - not specifically about the Attiny85, but the same processor family.


text:
What is the maximum prescaler you can set for an ATtiny85 Timer Interrupt?
I'm having trouble understanding the datasheets for the ATtiny and I need to know what is the largest prescaler that can be set for an ATtiny Timer Interupt? I'm new to hardware so can someone tell me if this is correct:
void setupInterupt()
{
  noInterrupts();
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = PERIOD - 1;
  TIMSK2 = _BV(OCIE2A);
  TCCR2B |= _BV(CS13) | _BV(CS12) | _BV(CS12) | _BV(CS10);
  interrupts();
}

Will this set a prescaler of 16384? Am I understanding the chart on page 89 correctly and is my syntax okay? This is my first Arduino Project.

You're using the registers for timer 2, which that chip doesn't have. Also, you're using CS12 twice.

So I only have Timer 1? I guest that limits the kind of sleep mode I can use since the power saver mode turns Timer 1 off.

Please clarify what you are trying to do with the timer. Short answer, looking, yes it does set a prescaler of 16384, that stuff is for the PWM stuff. Please clarify the your clock frequency and what you plan to do with the timer? Thanks

The ATtiny85 doesn't have Power-save mode, only Idle, ADCNR, and Power-down.

I'm trying to put my ATtiny to sleep after the program has run and then wake it up every 33 milliseconds. I need a large prescaler value because the ATtiny85 has a speed of 20MHz. I'm using the Power-down mode to maximize the amount of power saved.

@IsabelAlphonse  moving down to a smaller clock speed will start saving you power to begin with, is there any specific reason you have a 20MHz crystal?

TCCR2B should be TCCR1. I'm pretty sure the above code doesn't even compile.

Isn't 20MHz the speed of the ATtiny processor?

Why not just use the watchdog to wake?

I don't know the objectives of your project, or its constraints and requirements.  Thus, portions of the following might not apply.
If I were using an ATtiny85 in an application that needed to “maximize the amount of power saved” and also needed to wake up about every 33 ms, I'd use the factory-calibrated 8 MHz clock (rather than attaching a 20 MHz external crystal), and use system clock prescaling [see §6.3, System Clock Prescaler, on page 31 of the ATtiny85 specs, and Table 6-15. Clock Prescaler Select, p. 33] to scale that 8 MHz down to 250 KHz.  As implied by Table 21-1, DC Characteristics, page 162 of specs, this will drop CPU current draw down to under 0.1 mA if powered by 2 V, or under 0.35 mA if powered by 3 V.
With the system clock running at 250 KHz, you can use timer 0 prescaled by a factor of 1024 [see §11.3.1, Internal Clock Source with Prescaler, p. 166 of specs] to get an interrupt every 33 ms or so.
If 250 KHz is too slow to get done with whatever computation needs to be done every 33 ms, upon waking I would change the system clock prescale factor per §6.3.1, Switching Time, to 8 MHz or 4 MHz or whatever it needs to be to get the computation done at lowest power cost.  That might or might not be the same as getting the computation done most quickly.
Then, after the periodic computation is done, I'd revert the system clock to 250 KHz, and go to sleep in Idle mode (Ref §7.1.1, Idle Mode) with almost everything except timer 0 shut down via the PRR. (Ref §7.3, Power Reduction Register.)

source: Stack Exchange

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

sort: votes


text:
How can you count the number of interrupts that have taken place?
I'm trying to program a Timer Interrupt that will go off every 33 ms. I am doing this on the ATtiny85 which has a 20MHz clock. The maximum prescaler I can set is 32 so the longest possible time a single interrupt can be is 408 microseconds.
My plan to reach 33 milliseconds is to just run the interrupt 81 times and that will get me the desired 33 milliseconds. However, I have no clue as to how you can actually count how many time an interrupt has taken place. Anyone on here know how to do that or have any idea as to what would work?

Yes, just add a check inside your ISR statement.
ISR(TIMER0_OVF_vect)
{
  static uint8_t postscale = 0;
  if (++postscale == 81)
  {
    postscale = 0;
    do_stuff();
  }
  else
  {
    go_to_sleep();
  }
}

You always have to enter the ISR method once you're done with the interrupt so just add that if statement and use a static variable (so that it keeps its value) to check if you have made the correct number of loops.

else return; - I suggest. I wouldn't try sleeping inside an ISR.

What would it be returning?

Nothing. return on its own is used with a function returning void (like an ISR). So in fact you could omit the else and the return altogether.

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


text:
What would be the code for using Arduino UNO to alert by sound or LED when it detects a certain position through GPS?
I am in grade 6. I have a very nice pet dog in my house but it often enters Mom's kitchen to spoil all the foods. So I am thinking of a device to attach with him which can locate its position. But I am totally new to arduino programming. I have found some tutorials of arduino UNO to locate position with GPS. But I don't know how to set up the alarm when my dog reaches the position of our kitchen and what will be the code for it. If I wanna set alarm for different position, like kitchen and two toilets, what would be the code then? I know Java a very little bit. C too. Nothing else. Is there any altruist to help me out, please?

First things first: do you know that a GPS can locate your dog accurately enough in your home?
Basically, even with a good GPS receiver, the best accuracy you can expect (using off-the-shelf receivers, non-military or DGPS) is maybe 3 m. Typical performance is maybe 4 m, and indoors it will be even worse. The point is, your dog could be 5 m away from your intended location, and you will get an alarm. 5 m in a house might be the room over, two rooms over, or outside the house!
However, if you want to go forward with this, get yourself a GPS module, connect it to your Arduino, install the TinyGPS++ library (one of the better Arduino GPS libs IMO), and play with it. It's easy to figure out how to perform an action when the GPS coordinates are in range of a given coordinate set.
You might have better luck using a different form of dog location detection.

FYI, you might be interested in my library, NeoGPS.  It's smaller and faster, the examples are more robust, and the docs (hopefully) help new users avoid the many pitfalls in the TinyGPS examples.

A more low-tech solution might be better. For example, a couple of light beams across the doorway to the kitchen. An human would block both of them as they passed, and a dog only the lower one. You could sound an alarm if the lower one is broken, and the upper one is not broken (within a second).

Or do something with infra-red transmitters / receivers. There are lots of Arduino projects using those. You could have a transmitter in the kitchen pointing towards the doorway, sending some code (eg. 1234). Mount on the dog an Arduino with an IR decoder sketch. When the dog enters the kitchen it will get the code, and then you could sound a beeper. The beeper alone might make the dog change its mind about going in, especially if you go after it yelling "bad dog!" every time the beeper goes off.
Since the IR beam is just light, it would only go in a straight line, and if properly positioned would flood the kitchen, but not hit anywhere else.

Proof of concept
I made up a test of my idea of the IR transmitter.
(Please don't report me to the moderators for being off-topic. I know the question was about a GPS, but the real question is how to detect that the dog has come into the kitchen).
You can get IR (infra-red) LEDs cheaply at any electronics supplier (or eBay). They are like normal LEDs except that they transmit in the IR light range. They can also usually handle higher currents, like 80 mA.

Sender
So, to drive that from the Arduino we need a transistor to boost the output from the Arduino pin, like this:

Note that the positive pin of the LED will have a longer lead. The positive pin goes to the 39 ohm resistor, and the negative (shorter) lead goes to the transistor collector. In the schematic the negative pin (cathode) is at the bottom and has a horizontal line (think of the horizontal line as a minus sign).
The 39 ohm resistor limits current through the LED to 74 mA. Assuming a LED forward voltage of 2.1V we have:
 (5V - 2.1V) / 39Ω = 74 mA

The 470 ohm resistor limits current through the transistor base.

Sender code
Then some simple code to send a IR code (using PWM modulation like TV remotes do). There is a library for that, so the code is very simple:
#include <IRLib.h>

IRsend My_Sender;

const unsigned long DOG_ALERT_CODE = 0xBADA;

void setup()
  {
  }

void loop()
  {
  My_Sender.send (NEC, DOG_ALERT_CODE, 20);
  delay (1000);
  }

That sends the code 0xBADA (which I just picked at random) every second using the NEC IR protocol.
The objective would be to have this plugged into the power somewhere in the kitchen, and aimed at the doorway. The IR library uses digital pin 3 (on the Uno at least). That happens to be the Timer 2 "B" output to send 38 kHz PWM (pulse-width-modulated) signal, which it interrupts from time to time to encode the code into it.

Receiver
Now we need something on the dog to detect the IR code. The objective is to notice the code above (eg. 0xBADA) and if found, sound a tone on a speaker, otherwise ignore it. That way we can still use remotes in the kitchen, and the speaker won't sound.

The code for the receiver is a bit more complex, but not much:
#include <IRLib.h>
#include <TonePlayer.h>

const byte SPEAKER = 9;  // output pin is fixed (OC1A)
const byte IR_READER = 11;
const unsigned long BEEP_WIDTH = 50;
const int BEEP_FREQUENCY = 880;  // Hz
const unsigned long DOG_ALERT_CODE = 0xBADA;

// pin D9 (Uno), D11 (Mega)
TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);

IRrecv My_Receiver(IR_READER);
IRdecode My_Decoder;

void setup()
  {
  My_Receiver.enableIRIn(); // Start the receiver
  pinMode (SPEAKER, OUTPUT);
  }

unsigned long lastTone;

void loop()
  {
  if (My_Receiver.GetResults(&My_Decoder))
    {
    My_Decoder.decode();
    if (My_Decoder.decode_type == NEC)
      {
      if (My_Decoder.value == DOG_ALERT_CODE)
        {
        tone1.tone (BEEP_FREQUENCY);
        lastTone = millis ();
        }  // end of wanted code
      }  // end of NEC type
      My_Receiver.resume();
    }  // end of if we got a result

    // if time up, stop the beep
    if (millis () - lastTone >= BEEP_WIDTH)
      tone1.noTone ();

  } // end of loop

This also uses the IR library, this time to detect an incoming code. You wire the "Data" pin of the IR detector to digital pin 11 on the Arduino (Uno or similar). The other two pins of the IR detector go to Ground and +5V as marked.
To play a sound get a small piezo speaker and wire that to digital pin 9 (one side) and Ground (other side).
Because of the way that the IR library uses interrupts, I had to use my own Tone library to generate a tone. You can download that from:
http://www.gammon.com.au/Arduino/TonePlayer.zip

Testing
How well did it work? Certainly at short distances (like three feet or one metre) we got a positive result. There could be variance based on the light conditions in the room, and the exact parts you get.
You might want to read the design notes for TV B Gone where they discuss the technicalities of sending IR beams. In particular for their design they used four IR LEDs to give adequate range. You could add more LEDs by duplicating the transistor driver shown above a few times. In other words, duplicate the transistors, LEDs and resistors. They could all be driven from the same output pin.
As mentioned in the TV B Gone article, you can get different IR LEDs. Some have a narrow beam, but go further, others have a wider beam, but go less far.
Also you could arrange them to point in slightly different directions to cover more of the room.
You could also change the length of the beep when the code is detected (BEEP_WIDTH) in milliseconds. And also the frequency (BEEP_FREQUENCY) which I had at 880 Hz. A higher frequency might annoy the dog more but be less audible to humans. I suppose it depends if you want the dog to hear it or the people in the house.

Hardware size and power
You probably want a small Arduino (like a Nano) which is physically quite small. Also powering it could be an issue. You could get 3 x AA batteries, which would nominally output around 4.5V, and connect them directly to the +5V pin of the Arduino.
To save battery power you could have the Arduino sleep for (say) a second, wake and eheck for a code, and then sleep again. See my post about power savings for more details about that sort of thing.

Hardware photos

I needed the GPS coding but thank you for it. Could you help me with the GPS coding and how to set up the buzzer?

There are many posts by people who have connected a GPS to an Arduino. Asking to "provide code" goes beyond the scope of this site. We are here to answer questions, and be helpful as much as we can. Writing code from scratch isn't really our purpose. If you find code and have trouble getting it to work, by all means ask about that. I would find something that gets the current position, work out what that position is, for the kitchen, and then detect if you are in the kitchen or not.


text:
Microcontrollers with built in HID support
I am trying to build a wireless gamepad for which i am using NRF24l01 module for my wireless need and for Sending data to computer i need an mcu which support to act as hid device. So far, i got Attiny85 and mcu with atmega324u. But the problem is that attiny85 has very few pins and i cannot use it as for both hid and nrf module simutaneously due to pins defficiency. And atmega324u mcu are not avialable in my country. Can anybody suggest me some mcu with built in hid support.

The ATTiny85 doesn't support USB. You can bitbang USB using the V-USB library. Kind of a hack, but it does work. An ATMega328 (used on the UNO) can do the same thing. So the ATMega328 would be an option too (if the ATTiny85 is).
The ATMega32u4 does support USB natively, so this might be better. The ATMega32u4 is the MCU used on the Arduino Leonardo and the Arduino MICRO. Those might be available where you live.
You can also use a regular Arduino UNO. As on the UNO there is also a ATMega16u2 that does the usb-to-serial. You can reprogram this ATMega16u2 to also act as a keyboard. Like in this project


text:
Arduino Uno as keyboard
I am trying to make Arduino Uno to act as a keyboard. I have successfully flashed the USB-HID firmware in it using this link also and programmed it like this.
uint8_t buf[8] = {
 0
};

int inpin1 = 7;
int inpin2 = 8;
int val1 = 0;
int val2 = 0;

void setup() {
  Serial.begin(9600);
  delay(200);
  pinMode(inpin1, INPUT);
  pinMode(inpin2, INPUT);
}

void loop() {
  val1 = digitalRead(inpin1);
  if(val1 != HIGH) {
   buf[2] = 80; // Left Arrow
   Serial.write(buf, 8);
   releaseKey();
  }
  val2 = digitalRead(inpin2);
  if(val2 != HIGH) {
    buf[2] = 79; // Right Arrow
    Serial.write(buf, 8);
    releaseKey();
  }
}

void releaseKey() {
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8);
}

The above code works fine but the problem is that when I tried to play a game, which uses right arrow and left arrow, and to control a car I was using the push button, which I connected to Arduino as left and right arrow keys. But suppose I want to turn a car. I have to press the key and then release the key to move it a very little to the right or left. So, if I want to turn the car either left or right, I have to press and release so many times that it becomes impossible to play the game. Do you anyone know how to resolve this problem?

I believe this library that goes along with it. That would be the way to go instead of sending byte array through serial. This way you have the functions press and release, that you need.

+1 for impressive.  I know the RpiZero has been used for this, but this is the first time I've seen a write-up of an Arduino doing it.  Coolness.

You should just not call the releaseKey function, until the button is released.
int oldVal1 = 0;
int oldVal2 = 0;

void loop()
{
    val1 = digitalRead(inpin1);
    if( val1!=oldVal1 )
    {
        oldVal1 = val1;
        if(val1 != HIGH)
        {
            buf[2] = 80; // Left Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

    val2 = digitalRead(inpin2);
    if( val2!=oldVal2 )
    {
        oldVal2 = val2;
        if(val2 != HIGH)
        {
            buf[2] = 79; // Right Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

}

Right sort of idea, but I don't this is going to work since there are two buttons and releaseKey() doesn't seem like it will distinguish.  So probably the un-pushed button will immediately undo the pushed one, preventing any improvement.  I'm not sure if the problem can be solved with shared "had anything been pushed?" tracking or if the key states will need to be tracked and released independently.

Perhaps things might be simplified by writing the code so that if one button is pushed the other gets ignored, but the code will need to be sure to release any pushed  button before it indicates the push of another.

Just asking, why not using "while-loop" instead?

@ChrisStratton good point. Changed it so it only send press or release when the button state has changed. That doesn't handle pressing multiple buttons at the same time, but keeps it simple enough to understand.

@dhimaspw A while loop would block any other code. So that will work for this simple sketch, but will cause issues if you ever want to add additional code. Like for example pressing multiple buttons at the same time.

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


text:
Using HC-12 radio on UNO or NANO without software serial
On the Arduino UNO and NANO with the serial port connected to an on-board device connected to a USB port, I can obviously send and receive messages to the serial console......now the question:
I have no idea how to use the serial port to send data elsewhere, specifically to an HC-12 radio type device that communicates serially. I cannot use a software serial port because of timing issues, so I need to use the HW port.
During development I expect to use the serial console for diagnostic messages, but I also need to use the port to send and receive data using the radio.
So, how does the handshake/protocol handle both the serial console in the IDE and something else, or better yet, can it handle sending OR receiving data to or from 2 devices at the same time?
Does anyone use the HC-12 type device using the one onboard serial port on an UNO or NANO?
Remember, the goal is to use the HW serial port to communicate with the HC-12 buy issuing Serial.print commands, which logically will also go to the serail console of the IDE.

So you want to design a protocol to exchange data on two devices? You will need a way do discriminate between them. If you can modify the bytes you can send 7 bits per byte (the standard ASCII values) and use the most significant to send the information of the stream you are using (e.g. if the bit is 1 you are using the HC-12, if it is 0 the debug). Then each program will ignore the wrong bytes. If you want to be able to view all the bytes in a serial monitor (so no modification allowed), then, you can force each message to be new-line-terminated and begin with a character. continue..

continue.. e.g. "D: Message content" is a debug message and "H: Message content" is a HC-12 message. Then you read the stream line by line and you will find the receiver reading the first bit. Just a side note: on both devices you will see what you are sending to both of them, i.e. the HC will see the debug and the serial monitor will see the HC, BUT the arduino will listen ONLY to the HC12. If this is an issue, you can put a 3-state buffer to block the HC-12, then enable or disable it with a pin. You will still receive the HC commands on the debug, but the other problems are solved.

The primary function is to send or receive HC-12 data, but the USB HW will obviously be connected to the same HW ports......simply put, if I send data to the radio, will it also be seen on the serial console through the USB?

I'd like to just use Serial.print commands to send data to the radio and the USB at the same time....no special or different protocol, just simple serial communications. The USB is only for debugging.

Well, as I said if you directly connect the TX of the HC to the RX of the arduino and the RX of the HC to the TX of the arduino you will get the following behavior: what you send through Serial.print or write will go to BOTH the debug console and the HC. What you receive through the HC12 will enter the arduino. What you receive from the debug console (i.e. what you type in the console) gets lost.If you want a different behavior, use a 3-state buffer. When it is enabled you get the previous behavior, when disabled you just send data to the serial console and receive from the serial console too.


text:
conflicts with LiquidCrystal.h and SoftwareSerial.h library?
Simply put, if I include and initialize both libraries, the LCD displays junk. If I don't include and use the software serial lib, the LCD displays correctly.
BTW, there are no devices physically connected to the software serial defined pins.....
Yes, I've verified that there are no pin definition conflicts.
The code is large (> 1200 lines, with multiple #ifdef statements for conditional target configurations) so I won't include it unless someone wants to see it.
So, does anyone know of a conflict with these 2 (current) libraries?

No, I can't think that there would be a conflict. It must be how you're using them.

I suggest making a MCVE to see if the problem exists without the rest of your code.

I simply commented out ALL the lines that setup or use the software serial, leaving all the other code intact, and the LCD then works fine.

The only thing the software serial does is read an hc-12 radio that's not even installed at this point.....

So make an MCVE that contains JUST lines for the LCD and the serial and see if it breaks.

The basic code wasn't the problem, but these statements were: radioSerial.print(F("AT+C001\r\n")); // set to channel 1

I 'borrowed' that code from some examples, not familiar with the code itself, will try something else.......

I removed the F( stuff from the code(not sure what it does) and the LCD works as expected......just what is that construct that I borrowed from the examples??

I found out what that construct does, and for the life of me I see no reason that it caused issues with the LCD.....my code doesn't use and special constructs or anything that would leave me to believe that there's a memory size issue......Now I can actually debug the code for serial communications for the radio module.


text:
Arduino MEGA Timer Help
Nick Gammon posted some code to setup a counter on an Arduino UNO using timer2 to generate a 38KHZ signal, and I've used it on several IR projects.
On my current project, I'm using FreeRTOS for the Arduino, and the source says it uses timers 0-3 for its own kernel operation, so the timer code obviously will interfere with the RTOS.
I'm using an Arduino MEGA for this project, and AFAICT it also has a timer4 and timer5. Unfortunately, my programming ability for the ATMel products is lacking at that level, so I'm looking for some help to create a timer that will generate a 38KHZ output using timer4 or timer5 of the MEGA 2560 on any output pin. Interrupts shouldn't be used because it would also probably cause issues with RTOS.
BTW, on the Arduino MEGA, you can do a context switch between tasks in less that 200usec, and be able to determine what task YOU want to execute next.

Can you show me where I can read that freertos uses timers 0-3? In my opinion it does not use any of those timers.

For the life of me, I can't find what I found before.....I did find some example code that setup the watchdog timer to generate the basic tick function time, and the code allows using almost any of the HW timers. I did see that some of the docs posted say that the RTOS timers don't depend on any HW, but it also says that the SW timers don't use any processor time?? That doesn't make sense. The lack of documentation in this area may show that no HW is indeed used, especially because the RTOS will run on almost any Arduino, and the timers are quite different in capability.

The file that has the timer stuff is; \avrfreertos-master\avrfreertos-master\freeRTOS10xx\include\FreeRTOSBoardDefs.h

The watchdog timer is recommended, but I see that for the arduino mega 2560 the timer3 is used in this one: https://github.com/feilipu/avrfreertos/blob/master/freeRTOS10xx/include/FreeRTOSBoardDefs.h That is okay, since timer0, timer1 and timer2 are not used by freertos. The library manager in the arduino ide uses a mini version of freertos, and that one uses the watchdog timer: https://github.com/feilipu/Arduino_FreeRTOS_Library/blob/596a743509309121afcf7fa95c4d17d6d7fdd7ce/src/FreeRTOSVariant.h Why did you choose the larger version of freertos?

I just downloaded the version that the IDE showed. I didn't know there was another, smalled version. The size of the code isn't important to the project, as there will be only 3 tasks running that are all process dependant, but just scan while running in a state machine. They'll all run at the same priority, and at each exit from each state in the loop they're in, they will yield to the next task. ALL of them will always be in the ready state. Originally, I setup the code to chage their own priority to match all the rest, and then raise the priority of the next task to run.

Then that task lowers its prority and then raises the priorty of the next task to run. I set this up with dummy tasks to measure the context switch times, and couldn't tell any difference between the two techniques. As I stated above, the context switch time was less than 200usec. I need to do this because the original code ran in separate Arduino modules, and monitors IR detectors setup in a quadrature configuration with less than 0.030" separating them.

So, the state machines need to be very responsive, and the 200usec context switch will minimize any latency in the detection because the state machine stays in a switch statement loop, and the execution time is very fast, actually many times faster than needed for detection. So, the code should function with minimal changes. AFAICT, the only real difference would be just to do the context switch right before the break statement for each case.

I installed the "FreeRTOS by Richard Barry" from the library manager and I got the mini version. I think you don't need a rtos, you can put three finite state machines in the loop and remove all delays and use interrupts for the ir detectors. An interrupt itself uses a few microseconds in a avr microcontroller: https://gammon.com.au/interrupts The code inside an interrupt takes often more microseconds, because a single digitalread uses about 4 microseconds.

The state machine is complex, and with 2 running in each task, having 6 total machines interacting would be a ZOO trying to troubkeshoot. I really don't want to start all over. Currently the code works fine, but if I run into performance issues, I'll reconsider. BTW, the code that Nick wrote for the 38KHZ output works just fine in the RTOS, but it outpouts on data pin 10 on the MEGA instead of data pin 11 on the UNO. So, the project continues to its next phase.

I think we both learned from this. I have created an answer (with my opinion). I have used freertos, and it is working well. However, I think that the disadvantages are larger than the benefits.

Using a pre-emptive Real Time Operating System on a Arduino board with a AVR microcontroller (Arduino Uno, Leonardo, Mega 2560) is an academic exercise.
The FreeRTOS is reliable, and for someone that is used to write multitasking code, it can be useful.
In my opinion, the FreeRTOS does not match with the simple AVR Arduino boards:

Not enough ram memory.
Every task gets its own stack.
The ram memory is limited on a AVR board. That means that every
task should be written very careful to limit the stack usage.
Not enough ram when the fun is about to start.
When there are a few tasks and perhaps a few interrupt routines,
then a number of buffers and message queues are needed.
There is not enough ram memory for that.
The Arduino was not developed with a multitasking system in mind.
The Arduino libraries are not suitable for that.
Some functions wait
for something (Serial.parseInt, Wire.requestFrom,
Wire.endTransmission)
and that makes a RTOS work worse than expected.
The FreeRTOS is large, it requires memory and cpu time.

Without FreeRTOS, some known techniques are very efficient for the AVR Arduino boards:

A Finite State Machine uses very little ram memory.
A Finite State Machine without delay()
that uses millis() can be very responsive.
Avoiding interrupt routines.
It is often possible to avoid interrupt routines.
Reading buttons can often be done by polling the buttons
in the loop().
Avoiding the String object and moving text into PROGMEM
can be used
to have enough memory for a more complex and reliable sketch.

At this moment the "FreeRTOS by Richard Barry" is in the Library Manager. It is a smaller version of FreeRTOS and it only uses the WatchDog timer. It has no conflict with Arduino libraries.
A larger FreeRTOS version and many examples can be found at https://github.com/feilipu/avrfreertos
Not every version of FreeRTOS uses the WatchDog timer. Look for the file FreeRTOSBoardDefs.h to see which timer is used for your specific Arduino board.
crusader27529, I don't see a problem to remove the FreeRTOS and call the three tasks sequencially.
void loop() {
  task1();
  task2();
  task3();
}

The nature of the tasks is that they never terminate, but continuously monitor multiple IR sensors that are time critical, all run in multiple state machines. Using RTOS, I can use the YIELD function to force the running task into a state that allows the next task to run. Since all the tasks are the same priority, it results is a cooperative task switching operation with extremely low context switching overhead. AAMOF, I can switch sequentially among 4 tasks in sequence in less than 200usec. That actually works out tf about 50usec per task context switch, with minimal changes to the old code.

@crusader27529 I understand now, you stay in the finite state machine and perform a yield to the other ones. Without a RTOS, the loop() runs over and over again and rushes through the finite state machines. That is a different approach.

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


text:
Initialize a class (HX711) within a class with constructor and parameters
I am far from being an Arduino specialist, so please bear with me if some of my code below is far from correct.
I am writing a sketch in which I need to use 3 instances of the HX711 library, as I am using 3 different weight sensors.
In order to try to clean up the code, I want to put basically all the code using HX711 in my own class.
Here is what my ScaleMeasure.h looks like:
// ScaleMeasure.h
#ifndef _SCALEMEASURE_h
#define _SCALEMEASURE_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

#include <CmdMessenger.h>
#include "HX711.h"

class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale = HX711(_dout_pin, _clk_pin);
};

and .cpp
#include "ScaleMeasure.h"

ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
{
    _clk_pin = Clk;
    _dout_pin = Dout;
    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

void ScaleMeasure::Setup()
{
    _scale.power_up();
    _scale.set_scale();
    _scale.set_scale(_calibration_factor);
    _scale.tare();
    _scale.read();
}

float ScaleMeasure::Measure()
{
    return _scale.get_units(5);
}

but there is obviously something wrong, as a call to the constructor lock the rest of the program. I believe that my instantiation, of HX711 in ScaleMeasure.h  HX711 _scale = HX711(_dout_pin, _clk_pin); is not correct, or not in the right place. The code compile fine, though.
Thanks for your help.

The right way, in C++, to properly construct a field member b (of type class B) inside a class A is to do it as follows in A's constructor:
A::A() : b(...) {
    // Other init code here
}

In your situation that would mean:
class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale;
};

Note that I have removed the init part for _scale.
ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
: _scale(Dout, CLk)
{
    _clk_pin = Clk;
    _dout_pin = Dout;
    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

Ha! I tried "something like" this BEFORE asking here, but I may have made an error I did not saw. Thanks, I may get back to this, as it would allow to keep HX711  as is<. Thanks!

Unfortunatly HX711 has no default constructor. So the easiest way would be to add one in the header:
HX711() {} // default constructor, empty

Add member function to do the init job (done by original constructor), also in the header file
    void Init(byte dout, byte pd_sck, byte gain = 128) {
    PD_SCK  = pd_sck;
    DOUT    = dout;

    pinMode(PD_SCK, OUTPUT);
    pinMode(DOUT, INPUT);

    set_gain(gain);
}

Now your ScaleMeasure class will be like (header):
class ScaleMeasure
{
 public:
    ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
    void Setup();
    float Measure();

private:
    int _dout_pin;
    int _clk_pin;
    float _calibration_factor;
    byte _scaleID;
    HX711 _scale;
};

and cpp
ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
{
    _clk_pin = Clk;
    _dout_pin = Dout;

    _scale.Init(_dout_pin, _clk_pin);

    _calibration_factor = CalibF;
    _scaleID = ScaleID;
}

Thanks for this different approach. I'll test and let you know how this goes.

Modifying the code of a library that you use is probably not the best way to solve this problem as it will prevent easy upgrades later on if the library in improved.

It's the solution I choosed, as it's simpler and safe, IMHO. If the need .arise, version control will easily allow to implement eventual modifications

The line
HX711 _scale = HX711(_dout_pin, _clk_pin);

would be executed at construction time, which is the wrong time for it to run since _dout_pin and _clk_pin won't be set. Instead (much as it pains me to recommend it) you will have to use dynamic allocation:
HX711 *_scale;

Then you can, in your constructor:
_scale = new HX711(_dout_pin, _clk_pin);

Since you now have a pointer all your accesses to it need to change to -> instead of .:
_scale->power_up();
... etc ...

Also you should add a destructor to your class that deletes the object pointed to by _scale if it has been created.

I would refrain (at any cost) to introduce dynamic allocation (with new) just to solve a problem related to proper use of the C++ language itself.

There are many ways to skin a cat, all of them perfectly valid and correct. Dynamic allocation is absolutely fine in a memory constrained system as long as it is used "statically" - that is, allocated at init time and not deallocated. Heap fragmentation occurs only when objects are deleted, so if deletion is never needed or used then fragmentation never happens. There still more ways of solving the problem including passing a pointer (or reference) to an HX711 object to the custom class which alleviates the need to pass pins to said class. Like I said - skinning a cat.

I finally decided to add a default constructor to the library. Thanks anyway.


text:
Possible Arduino Uno c++ compiler bug?
I recently gave the students in my Arduino-based programming class a project to write some simple unit tests and fix the bugs that they encountered as they did.  The class in question mostly stores a bunch of Arduino-style String objects, with various getters and setters and a couple of constructors.
The test code that they're supposed to write involved creating two instances of the class (on the stack) and verifying that the constructors set the values correctly.  When I went through the exercise myself, everything worked.
When the students repeated the exercise, the first object worked.  The second object returned empty strings.  If they commented out the first object, the second object began working.  I couldn't find any obvious mistakes that could explain these failures.
After staring at their code for about ten minutes to make sure I wasn't losing it, I compared Arduino IDE versions to make sure my machine was running the same version.  It was.
Next, I unplugged one of their Arduino Uno devices and plugged in my Mega 2560.  The exact same source code passed the unit tests as expected.  That means the test failures were caused by some subtle difference between the Arduino Uno and the Mega 2560—either in the hardware or in the compiler.
Before I file a bug against the Arduino Uno compiler (v1.6.7, though I don't see anything in the 1.6.8/1.6.9 release notes that imply any compiler changes since then), I wanted to make sure I wasn't missing something subtle.  Could somebody take a look at this and see if I missed anything?
I've included a condensed version of the class in question below (with irrelevant bits removed).  You can see the complete set of exercises at:
https://sites.google.com/a/cabrillo.edu/cs-11m/schedule/unit-testing-exercises
The tests failed unexpectedly after they added the second AddressBookEntry object.
Class Declaration (partial)
class AddressBookEntry {

  public:
    AddressBookEntry(void);
    AddressBookEntry(String title, String firstName,
                     String middleName, String lastName,
                     String suffix);

    String title(void);
    String firstName(void);

...

  private:
    String _title;      // Mr.
    String _firstName;  // Barack
    String _middleName; // Hussein
    String _lastName;   // Obama
    String _suffix;     // Sr.

    String _addressLine1; // The White House
    String _addressLine2; // 1600 Pennsylvania Ave.
    String _city;         // Washington
    String _state;        // DC
    String _zip;          // 20500
    String _plusFour;     // 0001   (from 20500-0001)

    String _homePhone;    // Unknown
    String _mobilePhone;  // Unknown
    String _workPhone;    // 202-456-1414

Implementation (partial)
#define assert(condition) { \
  if (!(condition)) { \
    Serial.print(__FILE__); \
    Serial.print(":"); \
    Serial.print(__LINE__); \
    Serial.println(": Assertion failed: " #condition); \
    while (1); \
  } \
}

bool AddressBookEntry::runTests(void)
{
  Serial.println("Running tests.\n"); Serial.flush();

  AddressBookEntry testEntry("Mr.", "Jim", "Bob", "Murphy", "Sr.");

  Serial.println(testEntry.title());
  Serial.flush();

  assert(testEntry.title() == "Mr.");
  assert(testEntry.firstName() == "Jim");
  assert(testEntry.middleName() == "Bob");
  assert(testEntry.lastName() == "Murphy");
  assert(testEntry.suffix() == "Sr.");
  testEntry.setMiddleName("Phil");
  assert(testEntry.middleName() == "Phil");

  AddressBookEntry obamaEntry("Mr.", "Barack", "Hussein", "Obama", "");

  assert(obamaEntry.title() == "Mr."); // fails
  assert(obamaEntry.firstName() == "Barack"); // fails
  assert(obamaEntry.middleName() == "Hussein"); // stopped checking here.
  assert(obamaEntry.lastName() == "Obama");
  assert(obamaEntry.suffix() == "");

  Serial.println("All tests passed.\n"); Serial.flush();
}

AddressBookEntry::AddressBookEntry()
{
  _title = "";
  _firstName = "";
  _middleName = "";
  _lastName = "";
  _suffix = "";

  _addressLine1 = "";
  _addressLine2 = "";
  _city = "";
  _state = "";
  _zip = -1; // Deliberate bug
  _plusFour = -1; // Deliberate bug

  _homePhone = "";
  _mobilePhone = "";
  _workPhone = "";
}

AddressBookEntry::AddressBookEntry(String title, String firstName,
                                   String middleName, String lastName,
                                   String suffix)
{
  _title = title;
  _firstName = firstName;
  _middleName = middleName;
  _lastName = lastName;
  _suffix = suffix;

  _addressLine1 = "";
  _addressLine2 = "";
  _city = "";
  _state = "";
  _zip = -1; // Deliberate bug
  _plusFour = -1; // Deliberate bug

  _homePhone = "";
  _mobilePhone = "";
  _workPhone = "";

String str = "";
  Serial.println(str + "title is \"" + title + "\"");
}

String AddressBookEntry::title()
{
  return _title;
}

String AddressBookEntry::firstName()
{
  return _firstName;
}

... // remaining getters are similar

Calling Code (from setup() function)
  Serial.begin(9600);
  AddressBookEntry myEntry;
  myEntry.runTests();

That's a lot of strings. Sounds like a lack of RAM to me.

I agree with @Majenko, the most likely culprit is RAM which is why it's compiling on the Mega, since it has much more RAM than the Uno.

This is really not an appropriate application for a tiny embedded system with only 2048 bytes of RAM and an inability to make ordinary access to constants stored in flash.

That means the test failures were caused by some subtle difference between the Arduino Uno and the Mega 2560—either in the hardware or in the compiler.

Not a subtle difference - a big difference.  The Mega2560 has considerably more RAM than the UNO (8kB compared to 2kB).
All those strings are using RAM. Lots of RAM.  Your Mega2560 has enough RAM to cope (just), but the UNO just dumps its stack in a heap all over the floor1 at the mere thought of trying to handle that quantity of string data.

1: That's a technical way of describing the stack and the heap meeting and, if there were no protection, colliding into each other.

That's certainly possible, but I would expect to get some sort of error if the String class tried to allocate memory and failed, rather than a silent misbehavior like this.

@dgatwood - how would you expect a tiny embedded system to communicate a runtime error?  Without an MMU, even detecting one requires extra code, nevermind that there's no established way to report the situation as it is not a safe assumption that "Serial" is "stderr".  This exercise is one you should probably have your students build to run on the development machines - save the embedded target for tasks that fit it, and contexts where you are prepared to keep the limitations constantly in mind.

You mean at the String class level, I assume, by detecting a NULL pointer exception.  I would have expected the code to die much sooner than that, the moment the heap allocator failed to find space.  That's usually considered a fatal error, and if the allocator is already detecting the error, it would make more sense to spew an error on the serial port and spin forever than to silently fail in unpredictable ways.  But maybe that's just because I'm used to kernel code, where if an allocator fails and is allowed to return NULL, somebody's disk is going to get wiped....

Okay, the more I study this, the more baffled I am by what I'm seeing.  if I add the following line to a function: String x = "Mr.";, the global variable space remains constant, as expected, but if I add this line: assert(obamaEntry.title() == "Mr."); in the same function, it adds 48 bytes to the global variable size, despite not adding any global variables.  Something is not right here.  At best, that should have constructed some temporary String objects on the stack, then immediately discarded them, but global storage shouldn't have changed at all.  Yet it did.  A lot.

Never mind.  I figured it out.  The strings in the assert macro were ballooning the global storage.  I wrapped them in F(), and suddenly my global storage shrank by more than 1k.  Ugh.  What an ugly hack to work around what should have been the default codegen behavior....

You should learn the difference between Harvard and Princeton architectures and why things like the F() macro are needed.

I fully understand the difference between the architectures.  I also understand that as long as it is possible for the compiler to support the F() macro, there can be no reason why the equivalent code couldn't automatically be generated by the compiler, rather than requiring additional decoration.  And there's similarly no reason that it can't be considerably more robust when done in that fashion.  The only argument against doing so is efficiency, which is why it would make sense to make that a compiler switch—optimizing between speed and time.


text:
MPU6050, Bluetooth — FIFO Overflow and Breakdown
I am quite new to all the arduino stuff and right now I am struggling with a Problem that seems to be easy, but I have honestly no idea how to deal with it.
I would like to read the data from a gyroscop and transmit the raw values via bluetooth to another device.
I am using the arduino uno r3 (it should be quite new since I bought it yesterday), the famous MPU-6050 Gyro-GY521 and for bluetooth De-HC-06BT.
I could already manage to assemble everything and send the data via bluetooth. To read the data from the gyro I am using the famous library MPU6050, which comes with some examples and seems to be the de facto standard for this.
The whole script is based on the MPU6050_DMP6 example and utilizes a SoftwareSerial to transmit the data.
Unfortunatly has two major issues:

It just stops to send data after some time (~2 Minutes) and a restart makes it send again.
It prints FIFO Overflow ~ each 20th frame, so I guess there is an ongoing failure which might stop the system.

If anybody could give some hint how to solve the »FIFO-« and »Breakdownissue« I would be very glad and I appreciate any kind of help!
Thanks in Ahead!
The whole code:
#include <SoftwareSerial.h>

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

//RX und TX gekreuzt vom Bluetooth board
SoftwareSerial serial2(10, 11); //RX, TX

#define OUTPUT_READABLE_YAWPITCHROLL

//#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
//bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    serial2.begin(9600);
    //serial2.println("Hello");

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {

        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    //pinMode(LED_PIN, OUTPUT);
}

void loop() {

    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {

    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        //Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

            serial2.print(ypr[0] * 180/M_PI);
            serial2.print(",");
            serial2.print(ypr[1] * 180/M_PI);
            serial2.print(",");
            serial2.print(ypr[2] * 180/M_PI);
            serial2.print("\n");

        #endif

        delay(5);
    }
}

See if you can determine if it is the serial link that is not keeping up.  You might try increasing the baud rate.  You could also try to reduce the rate at which samples are produced, make the output more compact, or even do something as crude as only producing output for every second sample.  You could also add extra output to see where it gets "stuck"

I have the same issue. I get disconnected after a few seconds/minutes when I send data from mpu6050 via BT HC-06. Have you found your answer in 1 year ?


text:
Prevent reiteration of loop instruction in Arduino/Execute instruction via off switch
I'd like to make an Arduino play a (2sec).wav file once when it is powered on (via push button) and another when it is switched off i.e. when the push button is pushed there is a 2sec delay and the .wav file plays, then the arduino turns off.  What would the best way be to implement this?  So far I've come up with:
void loop()
{
//play .wav file

while(1){}
}

or:
void setup(){
//play .wav file
}

void loop(){
//empty
}

An Arduino doesn't understand the concept of "powering off".  It is either on (running) or off (not able to do anything).
Your first task must be to design a system whereby the Arduino can control its own power so the Arduino can then go "I have been asked by this external stimulus to switch off. Therefore I will play this sound and then perform whatever actions are required to remove power from myself."
Only when you have worked out how you can get the Arduino to control its own power and still have the ability to manually turn the power on can you begin to think about adding things that happen "when it powers off".

Thanks for your clear explanation Majenko.  I'm a novice and am merely looking to play a sound effect when the Arduino switches on and off.  Designing a "self-controlled power system" for the Arduino sounds a little daunting at this point in time : ]

Nevertheless, it is required.  The Arduino can't play the sound once it is turned off, and it doesn't know you're about to turn it off, so you need some way of telling the Arduino that it should turn itself off once it has finished playing the sound.

Thanks again Majenko.  Is this the type of direction I might take if undertaking it: http://forum.arduino.cc/index.php?topic=118504.0

Yep, that kind of thing would be good.

Ok great, thank you.  I'll look into it and see exactly what's involved.

Neither way addresses your second requirement. I would do something like:
void setup()
    {
    pinMode (OFF_BUTTON, INPUT_PULLUP);

    //play .wav file
    }

void loop()
  {

  if (digitalRead (OFF_BUTTON) == LOW)  // depending on how it is wired
    {
    delay (2000);   // 2 second delay
    // play .wav file
    // power self off somehow
    }

}

Thanks a lot Nick. So placing the .wav instruction within setup() should do the trick for making it play once only, when the Arduino is switched on?  Am I understanding your code correctly if I say that you've set the push button as a digital input pullup, which if read in as being low/off will cause a 2 sec delay followed by the .wav file playing and (in theory) then the Arduino will power itself off?  I'm trying to understand why you used INPUT_PULLUP as opposed to INPUT http://electronics.stackexchange.com/questions/67007/whats-the-difference-between-input-and-input-pullup

It makes the switch read reliably. See Switches


text:
Powering Arduino Uno and Ardumoto Motor Driver Shield
I need to power an Ardumoto Shield to drive two 12V DC motors. I was planning to connect a 12V battery to the Max 18V input on the Ardumoto and a 9V battery to the barrel jack input of the Arduino Uno.  Can you tell me if this should be ok or if it would cause any damage to the Arduino?
It mentions in the Ardumoto hookup guide:

There's no mention of the Max 18V input on the Ardumoto.. Advice appreciated, thanks.

The L298 used in the Ardumoto shield has a maximum supply voltage of 46V. Hence 18V should be sufficient to power it as long as the motors have enough power too.
The Arduino voltage regulator, on the other hand, won't be able to handle such a high voltage. Hence you will have to remove the Vin pin that connects the Arduino & the shield in order to isolate the power supplies of the two.
Only then should you attempt plugging in the shield & then powering the Arduino through the 9V battery.

Do not supply power to both the Arduino barrel jack input and VIN on the shield!

There goes the simple answer. Choose one.
If you power the system through arduino barrel jack input, you will have polarity protection, but the voltage output on VIN pin (which also used by Ardumoto shield) is slightly lower, about 0.6V lower than the input voltage because of the voltage drop on the protection diode.
If you have want to differentiate the supply for Ardumoto and Arduino (as described on your plan), you have to tamper the Ardumoto shield to isolate both supply. Although I never try it myself, it seems possible if you understands how L298 works.

I'll probably just use the 18V Max Vin on the Ardumoto shield.  Or maybe get rid of the Vin header pin on the Ardumoto that connects to the Arduino Vin.


text:
Why were Atmel MCUs used for Arduino?
Atmel microcontrollers are not cheap compared to STM and Microchip. Why did Arduino select Atmel MCUs such as atmega328 and atmega2560 on their board out of so many alternatives?

Simply because the Wiring system that Arduino stole was written for the Atmel chips.
Arduino didn't "invent" the Arduino system - they just took an existing system called Wiring and adapted it slightly and branded it Arduino.

I wonder why did Arduino succeed when Wiring failed given that Wiring had first-mover advantage.

It's called Marketing. If you have it then you win.

Actually, "stolen" is quite a bold word. If Wiring didn't want any forks, they should use licence that prevents them, not GPL created exactly to allow them. At least that's for software, can't find licences for actual wiring, but arduino uses open licence for them as well.

@Mołot Maybe "Appropriated" then?  Blatantly used and pretty much claimed as their own with little or no reference to the original Wiring project.  Actually, "stolen" fits that quite well...

@Majenko AFAIK they posted all references actually required by original licence. Of course, GPL is easygoing about that. But that's what Wiring decided to use. Are you using any sources just the way licence allows you to? Does it make you a thief?.. Would you find it fair to call you thief if you follow licences of code you use?.. OK, they wasn't as nice as they might be, but they fulfilled their duties. It's not like Wiring ever forbade what they did.

This was the first time I've heard of Wiring. It's interesting how little recognition they've received. Also it's not easy to google their name, since the name is so generic.

The site is wiring.org.co and yes, it's hard to search for something that is named after such a generic word. @Mołot The license allows them to use the code without asking etc, which is fine. But they completely stole the whole market segment from Wiring, and that isn't covered by the GPL license.

I don't really get the impression the Arduino crew misrepresented themselves as far as their use of Wiring. And a probably more significant part of what Arduino is about is making the hardware easy to use (IMHO).


text:
Problem in Uploading a Bootloader to Atmega8A
I am getting an error while Uploading the Bootloader to Atmega8A
I am selecting..
  Board -> Arduino NG and Older
  Processor -> Atmega8A
  Programmer -> USBasp

and sketch code is ArduinoISP, After selecting port then I do "Burn Bootloader"
But getting an error of...
   "efuse" memory type not defined for part "ATmega8"
    Error while burning bootloader.

Please tell me what to do. Any help will be appreciated.
Thank you

I used Programmer "AVRUPro+" for Uploading Program. I downloaded its Software "Progisp" Then I did some few steps....
1) After downloading it, Run the Progisp.exe file.
2) Then went to Command tab, and clicked “Program Fuse”, It just did my fuse  set.
3)Then I just did the simple process of burning the bootloader to my Atmega Controller.
4)After this I was able to upload my program to my new Atmega Controller.
Thank you

Google is your friend!!!
Apparently this is a known regression bug not yet corrected. The possible solution is also suggested there by user rigelinorion and here is the quote:
Hello, I solved it this way...

Open for edit the file C:\Program Files\Arduino\hardware\arduino\avr\platforms.txt
this is standard section uploader/programmers tools

#==============================================================================
tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
tools.avrdude.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
tools.avrdude.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

tools.avrdude.upload.params.verbose=-v -v -v -v
tools.avrdude.upload.params.quiet=-q -q
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.program.params.verbose=-v -v -v -v
tools.avrdude.program.params.quiet=-q -q
tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.erase.params.verbose=-v -v -v -v
tools.avrdude.erase.params.quiet=-q -q
tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Uefuse:w:{bootloader.extended_fuses}:m -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude.bootloader.params.verbose=-v -v -v -v
tools.avrdude.bootloader.params.quiet=-q -q
tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
#==============================================================================

create a new tool called, for example, avrdude1
simply copy section tools.avrdude and name it tools.avrdude1
the trick is that we remove switch "-Uefuse:w:{bootloader.extended_fuses}:m" from "tools.avrdude1.erase.pattern="

#=============================================================================
tools.avrdude1.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
tools.avrdude1.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
tools.avrdude1.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
tools.avrdude1.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

tools.avrdude1.upload.params.verbose=-v -v -v -v
tools.avrdude1.upload.params.quiet=-q -q
tools.avrdude1.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude1.program.params.verbose=-v -v -v -v
tools.avrdude1.program.params.quiet=-q -q
tools.avrdude1.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude1.erase.params.verbose=-v -v -v -v
tools.avrdude1.erase.params.quiet=-q -q

#this line was edited
tools.avrdude1.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude1.bootloader.params.verbose=-v -v -v -v
tools.avrdude1.bootloader.params.quiet=-q -q
tools.avrdude1.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
#==============================================================================

Here is an example of the use of the tool avrdude1 in boards.txt file

atmega8.name=ATmega8 OPTIBOOT
atmega8.upload.protocol=arduino
atmega8.upload.maximum_size=7168
atmega8.upload.speed=115200
atmega8.upload.tool=avrdude1
atmega8.bootloader.low_fuses=0xbf
atmega8.bootloader.high_fuses=0xCC
atmega8.bootloader.path=atmega8
atmega8.bootloader.file=optiboot/optiboot_atmega8.hex
atmega8.bootloader.unlock_bits=0x3F
atmega8.bootloader.lock_bits=0x0F
atmega8.bootloader.tool=avrdude1
atmega8.build.mcu=atmega8
atmega8.build.f_cpu=16000000L
atmega8.build.core=arduino
atmega8.build.variant=standard

If it's a regression bug, you could also try using an older version of the Arduino IDE.

@Gerben, yes indeed, a valid solution too. However I would probably stick with this solution because this is a minor issue compared to maybe a lot of bugs or improvements done in new IDE's.

Thanks to all of you, I got it, Actually there was the fuse bit problem.

@Naveen Thats great. Post your solution here and mark it as answer because it may help others too.


text:
What is the Mark and Space of Ir remote of Airtel?
Can you please tell me to find out Airtel IR Remote Mark and Space coding. I am making a project in which i have to Airtel IR Remote But I do not have decoding style of it. So please help me out. Any help will be appreciated.
Thank you

What have you tried? Isn't it a standard ir-protocol? The IRremote library supports raw ir-data.

I have tried IRremote library of arduino, But it is not decoding the Airtel ir remote code. I found that there is no protocol set for airtel in its library. So if you have any idea please suggest me.

Just write a simple sketch, that logs the lengths of marks and spaces to the serial console. I did just that to decode the Samsung TV remote protocol. I loaded the values into excel to easily get the min and max lengths etc.

I have tried that too,  #Gerben, but getting the garbage output ( mark and space ). Th is is not able to distinguish between the header, bit- mark & space. All are coming same. And the main part, it is not giving the code length that I am sending through Airtel ir remote.

If it's garbage, then there is something wrong. Are you using the correct frequency receiver? Could you post a sample output. There aren't a lot of people from India here.


text:
Is it possible to simulate PWM using delay() function?
I was thinking about if it is possible to simulate PWM (AKA pulse width modulation).
Is it possible to reach the speed of the PWM using the delay() function ?.
Note : I am talking about the pins which does not support PWM, Arduino uno Pin 13 for example.

Why do you want to? Please specify what speeds you are hoping to achieve. The hardware can output 8 MHz. Simulated PWM cannot.

It is possible to create a PWM signal from a non-PWM digital pin although you would not want to use delay, but timer interrupts for accuracy and finite timing. PWM intervals are typically measured in (μs[microseconds] vs ms[milliseconds]).
The standard Arduino servo library  does this: Servo.

It would be possible to do it. Would it be a smart thing to do ?
I do not think so. Micro-controllers (not just Atmel's) have dedicated hardware modules to manage the signals for PWM. What happens when you use AnalogWrite is the compiler/interpreter/whatever uses these informations to modify the appropriate registers so the toggling is not managed by the code.
If you use the delay() functions, you are simply letting clock cycles pass by until the time you set is passed which is a lot less efficient. Plus, you would probably not get the same PWM frequency.

What you are talking about is more appropriately called Bit-Banging. Check out this link. It even has an example of what you are trying to do. @Jason is correct that it causes a number of issues. The link above will also run you through the draw backs of this method which I will summarize.

Jittery due to interrupts (Interrupts can be disabled)
The Processor cannot do anything else and keep the output working
Frequency and Duty Cycle are difficult to determine

If you disable interrupts, delay will no longer work.

@Gerben Right, so in that case I'd use millis() and use a similar method without delaying the function. That would get rid of the first issue. The second problem might also be fixed as long as your Timer ran fast enough to catch each cycle.

Sorry :-p. Without interrupts, millis is not updated.

I think it depends on what you want to use it for. I compared using PWM and bit banging to run a small DC motor.  PWM produced an audible whine that I found very irritating.  Using the delay function removed that (a delay on/off cycle of 10 milliseconds).  I also found that it was relatively easy to control not only the ratio of on/off (PWM) but also the length of the cycle.  This was useful for starting the motor with a slightly higher "push" to get it moving. (I'm sure that this could be done using PWM too) With respect to performance of the engine, I didn't find much actual difference.
The key issue with a DC motor is that while the digitalWrite() is LOW, the inertia of the motor carries the rotation on and so the effect of the delay is smoothed.  In addition the RPM of the motor wasn't critical for my application.
However, if one was running a LED then using delay() might be visibly discernable and cause discomfort (and possibly seizures?).  For this, I'd definitely use PWM.
regards
Mark


text:
How to know if arduino activated its short breaker?
today i was trying to use arduino power headers as a power source for my basic laser.
I used pin "5V" to connect it to the laser anode and the "GND" pin to the laser groung pin.
after doing this arduino turned restarted, so I removed all the connections to the laser, now the arduino is normal.
booth "5V" and "GND" pins is working normal.
does this mean that I made a short circut and arduino protected it self ?
should I do anything now ?

What's the rated current and voltage for your laser?  Laser diodes, like LEDs, typically need a constant-current controller (or a properly sized series resistor).  Eg a red LD might use about 200 mA and develop a voltage of about 2.35 V.  Putting 5 V straight into it may ruin it.

It sounds like connecting your Laser to the 5 volts power supply did draw too much current, thereby the 5 volts dropped to very low voltage.
The Arduino didn't "protect" itself.  The Arduino simply shut down because of voltage being too low. Then, upon reapplication of 5 volts the Arduino re-started as normal.
You don't mention any details about the Laser.  But if your Laser is simply a Diode, the Laser diode would draw a lot of current, resulting in the 5 volts power source giving reduced voltage.
If your Laser is a "laser module" with a built in driver, perhaps you connected the Laser backwards to the 5 volts.
EDIT 11/20/2015 :  IF you are using the Arduino UNO ,  : The  PolyFuse only protects from 500 mA overload on the USB connector.  Schematic for the UNO shows that 5 volts for USB is called "XUSB". The  PolyFuse connects from "USB VCC" to the XUSB.  When you connected your Laser to the +5 and ground, the  PolyFuse was not involved. (Unless of course you did connect to the USB 5 volts (XUSB), and didn't tell us that.
HOWEVER,  if you powered your UNO from the USB port, then the  PolyFuse WAS involved and did shut you down as others have commented.

You uses more the 500mA limit, and the PolyFuse tripped. After unplugging the polyfuse cooled down and "reset" itself.


text:
what is the difference between providing 7 volts or 12 volts to arduino uno?
according to this the recommended input voltage is between 7 and 12 volts.
The question is what is the difference between providing 7 volts(minimum recommended volts) and 12 volts(maximum recommended volts) ?.

The amount of heat dissipated by the voltage regulator.  The higher the voltage you supply the hotter the regulator will get.

I agree with Majenko. A higher voltage will make the voltage regulator run hotter, particularly if you are drawing a lot of current (eg. to power LEDs or similar). However since you probably won't find a 7V wall-wart, they give you a range of voltages that are acceptable.


text:
Arduino Part Needs Identified

I do not know what part this is. I ordered an Arduino beginners kit and this part was not labeled. Please help!

It seems that it is an MPU6050 Module 3 Axis Accelerometer Gyroscope Module for Arduino.
Learn more: http://playground.arduino.cc/Main/MPU-6050


text:
Unstable reading from Raspberry Pi
I'm trying to send a signal from Raspberry Pi GPIO to Arduino. I made a sketch that basically reads the state of the digital read, but the reading are very unstable. I understand that there is a floated voltage and the obvious solution is to configure the pullup resistor and connect the input to ground, but my goal is to read the incoming signal.
I'm using Arduino Mega 2560 and Raspberry Pi 2B.
I hope this info is enough!

Please show your schematic.

It is just GPIO 5 conected to A3 of Arduino Mega.

If GPIO5 is the only thing connected and the Arduino/Rpi are on seperate power supplies then you are certainly missing a common ground reference if you want them to talk directly.

Thank you guys for your answers! Now,  what should I do?

Connect the grounds together.

Thank you! I know this was a silly question, buy I really apreciate your help! Have a nice day!

Did that comment resolve your problem? If it did it would be nice to create an answer so that others will see this as a resolved question.

You might want to check the details on the answer of Majenko (https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/#more-12)

As Majenko commented, you need to not only connect the data wires together but also the ground wire (from the Arduino to the Pi).

... the reading are very unstable ...

Without a consistent "ground reference" the readings would indeed be unstable.

Occasionally you run into situations where connecting grounds causes problems in which case a dual supply buffer or isolator can be used

@crasic that's a very interesting point (maybe not in this case, but) you might want to elaborate it in your own answer or by editing Nick's answer. In what cases should it be used, why and how?


text:
Arduino MEGA with RTOS
I've been coding for FreeRTOS on the MEGA 2560, and was using some LEDs to determine activity per task by toggling each individual LED each time through the task, and monitoring the time using a scope on the LED pin(s). All worked fine until I added the code for the last task.
Only the LED for the last task showed activity, and I assumed I screwed up in the new code, and spent a full day re-doing the code and troubleshooting. Well, it turns out that the code was working just fine. The problem appears to be RTOS is not manipulating the appropriate LED for each task, but using some other pin. The same configuration but with simple test code works fine.
I've tried just about everything I know, with negative results. The 3 tasks are running OK (I still need to do much more testing) so it's not like there is an issue with stack overflow, plus I decided to make ALL the variables as global variables to minimze stack use, and possible conflicts with the variables, which were the same on two of the original programs. I'm using about 600 bytes of RAM for those variables, and have tons of spece in the MEGA in all aspects. The code only uses 14K of the 256K available.
So, I'm officially stumped, and I assume that there's a problem with the task switching somehow, but I'd expect the code to crash eventually if that were the case, but it runs for hours and hours.
Does anyone have any real experience with FreeRTOS that have experienced similar issues related to simple digitalRead and/or digitalWrite problems similar to what I'm seeing?

Just had an idea.....looking at the code size, I realized that it would fit on an UNO. I can't use the UNO for the project because I needs many more pins than it has, but running the code on a different and smalled piece of HW could show some results, either it works better or has a stack size issue.

Well, it runs the same, and doesn't crash, so other than that the problem isn't MEGA specific, no useful data was obtained.

Well, DUMBO (that would be me) found the problem, and it was a real bonehead error.
When I applied the stand-alone code to the RTOS environment, I did not reallocate pin assignments, so there were multiple I/O events writing to the same port that was using the Test LEDs.
I knew that FreeRTOS couldn't be that bad, as if the I/O went to the incorrect pins, the code would be useless.
So, don't take shortcuts, even if you're not ready to complete all segments of the project. Check for duplicate definitions or they will bite you in the ass.......


text:
FreeRTOS Timer Use
I use Timer1 on an UNO to generate a 38KHZ signal for IR communications. It all works as expected.
BUT, I need to convert the code to run as a task under FreeRTOS, and can't seem to find any details about which HW timers are available for the UNO or MEGA.
Also, as long as I'm asking about FreeRTOS, is it reliable for the timer tick to be changed from the 15ms that I think is standard to something faster?

FYI, I found my own answer by looking into the FreeRTOS source code.
FreeRTOS uses timer0, timer1, timer2 and timer3 according to the source code. I assume that it uses the timers as required based on CPU type and capability.


text:
How many bluetooth modules can be interfaced with Arduino UNO?
At most how many bluetooth modules(HC-05) can be interfaced to Arduino UNO?

Two. One on the hardware UART (TX/RX pins with the Serial object). One on SoftwareSerial on any two pins you choose.
Any more than that and you will need more hardware UARTs.

You can create as many SoftwareSerial objects as you like, with a BT module on each, within memory, pin, and power constraints. But only one SoftwareSerial object can be listening at a time, which may make any others less than useful.

Also while you are sending on one reception is completely disabled (interrupts disabled) so you can only use one at once. As a rule of thumb, while you can define more than one SoftwareSerial you can only really use one of them. Personally I never even use one. I pick hardware that has enough hardware UARTs to do the job at hand.


text:
Arduino rc plane logger
Well, I want to make an rc plane with an arduino that logs to an sd card
A) Video
B) Accelerometer data
C) Tempature
D) Humitity
E) Atmospheric pressure
F) Gyroscope Data
What arduino/parts should I use? I have a maximum of 170 grams or 6 OZ.
The arduino will not control the plane, just log data. I'm thinking an arduino 101... but I would like to know if there is a lighter/better way.  THANKS! :)

I'm voting to close this question as off-topic because this is a "shopping" question.

OH, sorry. I didn't know.

It is not an Arduino answer but a Raspberry Pi with a Sense hat will record most of what you need with little coding.  Add a Pi camera and you have all this for about $100.  The Sense Hat temperature sensor doesn't work because it is too close to the CPU but you could get a digital thermometer for a few bucks.

This is VERY false. You don't need to learn Python. You can easily make a Pi and Pi Cam work with C++, a much more powerful language. WiringPi also has many functions such as pinMode() and digitalWrite()... Sounds familiar.

Thanks for the corretion @Dat Ha.  I have edited my post.

I've completed a similar project.

For the Arduino, I used a Pro Mini for its small size and weight.
For the accel/gyro, I used an MPU-6050. 2 bird, 1 stone!
For the Temp/Baro, I used an MPL3115A2. Again, 2 bird, 1 stone!
For the camera feed, use one of these pre-built things.


text:
Why does the serial monitor needs to be repeated a command?
I am experimenting with the serial monitor in an Arduino Uno. My project consists in a simple LED turning on and off at will with the commands "ON" and "OFF" respectively.
To achieve this, I use an HC-06 Bluetooth module, but because of the nature of the test I decided to disconnect it and 'debug' my project using the serial monitor as an equivalent.
The circuit has the following connection table:
LED +: Pin 12 on my Arduino.
LED -: GND on my Arduino.
...as you can see, I have tried to simplify as much as I can the circuit, as I wanted to make sure I didn't have wire problems.
Here's the code:
char command;
String string;
#define led 12

void LEDOn()
    {
          digitalWrite(led, HIGH);
    }

void LEDOff()
    {
      digitalWrite(led, LOW);
    }

void setup()
{
      Serial.begin(9600);
      pinMode(led, OUTPUT);
}

void loop()
{
     if (Serial.available() > 0)
           {string = "";}

     while(Serial.available() > 0)
    {
           command = ((byte)Serial.read());

           if(command == ':')
           {
                  break;
           }

           else
           {
                  string += command;
           }

           delay(1);
    }

    if(string == "LO")
    {
           LEDOn();
     }

   if(string == "LF")
    {
           LEDOff();
    }

The problem comes when I type the commands. Normally, an LED in the board will react (I think it's the RX one), but the LED in pin 12 will not react at all. After testing ten times with each command alternatively, I calculated the serial needs an average of 6 command repetitions in order to react. Exactly the same happens when the HC-06 is connected.
Is there a reason for this?

Does the problem occur at higher BPS?  For example, try changing Serial.begin(9600); to Serial.begin(115200); (and change serial monitor BPS also).  Note, you should do string = ""; only in setup() and after processing :, LO, or LF, or something like that, since it perhaps could be loop() loops before getting a complete command

Please read and digest this, then re-write your code accordingly: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

@jwpat7 There's no response at all if I set a baudrate higher than 9600.

There is a problem with your code: Serial.available() > 0 might be false at your if test, but true at your while loop condition, which means that string has a chance of not being correctly initialized to "" before you start chaining characters to it. I would also add some sanity check on the input stream, because as it is now any failure is silent. When you exit the loop, either string == "LO" or string == "LF". If not, then you could print the content of string to Serial and see why the command was not taken. What's the point of delay(1)?

The baudrate needs to be changed both within the Arduino program and on the serial client you use on your pc, otherwise they can't talk to one another. I doubt that's the cause of it, though.

Another problem in your code is that whenever there is nothing to read on serial input, the Arduino keeps going through the loop and repeating the last instruction it received. You could look up how to put the Arduino to sleep while it waits to be awaken by more input on the Serial interface pins. As it is, you should at least reset string right after executing the command.

So how should I implement this to my code? I'm still new at programming Arduino.

I said that you could do something better, just to mention that it is possible, not that you should now. First fix those things in your code and see whether it solves the issue or not.

Your problem is, amongst other things, that you are assuming that all the serial data arrives at once, which doesn't necessarily happen at all.
I have a discussion about this sort of thing.
Rewriting your sketch using the ideas presented there we get this:
#define led 12

void LEDOn()
{
  digitalWrite(led, HIGH);
}

void LEDOff()
{
  digitalWrite(led, LOW);
}

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

void setup ()
{
  Serial.begin (9600);
  pinMode(led, OUTPUT);
} // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
{

  if (strcmp (data, "ON") == 0)
    LEDOn ();
  else if (strcmp (data, "OFF") == 0)
    LEDOff ();
  else
    {
    Serial.print (F("Unexpected command: "));
    Serial.println (data);
    }
}  // end of process_data

void processIncomingByte (const byte inByte)
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  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 processIncomingByte

void loop()
{
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

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

}  // end of loop

with the commands "ON" and "OFF" respectively.

I changed the test to be for "ON" and "OFF" not "LO" and "LF" which seems a weird way of meeting your requirements.
For this to work you need a delimiter (which tells the Arduino when you have finished sending a command). I have used linefeed which you can automatically send in the IDE's serial monitor (see bottom RH corner).

I also put in code to show "Unexpected command: " if you don't get ON or OFF (note that "on" is not the same as "ON").

Nice! Now it works perfectly from the serial monitor. But if I wanted to send this command from an external device via Bluetooth (a smartphone, for example). how could I force the newline after the command? Using ON\n or ON"\n" does not return anything.

Sending "ON\n" should work. You could of course use a different delimiter. Instead of checking for \n in the code you could check for :.

It worked with ':'. Is there a reason why it's not working with '\n'?

No, not unless you didn't send "\n" properly.

It worked fine for me, if I typed the entire command, "LO:" or LF:" (without the quotes of course). However, if I typed and sent one character at a time, it failed. The problem is quite likely the code:

   if (Serial.available() > 0)
         {string = "";}

If you send all of the characters at once, the while( Serial.available() ) loop will get the whole line and match it. But if there is any pause between characters, what does that if statement do? (Hint: loop() executes way faster than you can type!)
I was using the serial terminal built into the Eclipse IDE. Different terminal software might behave differently when you type a string and send it. Remember, any gaps between characters, and that first if statement gets time to do its dirty work.


text:
Are there ultrasonic transducers which are able to produce a "chirp" sound wave?
I'm working in a ultrasonic radar project and the supervising teacher wants us to produce a chirp sound wave (a frequency-varying sinusoid).
I'm familiarised with the usual ultrasonic module, but as far as I know, it cannot do the task.
I searched on-line for transducers that I could use, but couldn't find anything useful.
Are there any commercially available component that could do this task? If not, what could I possibly do?

Ultrasonic chirp, or an (human) audible chirp? It sound to me like the teacher doesn't know what he/she is talking about.

Why won't usual ultrasoud modules work - are they physically limited to a narrow range of frequencies? (I know they are usually run at a particular frequency, but if driven at other frequencies there might still be a measurable response - is it just a case of doing some tests?)

The most common ultrasonic modules for Arduino use have self-contained pulse generation and detection (actually done by abusing a serial line driver charge pump chip!)  To build a chirp system you would need transducer(s) with a suitable bandwith, and either a chirp generator/detector or interface/conversion circuitry to put a DSP algorithm in those roles.

Piezoelectric speakers, the kind commonly found in ultrasonic transducers generally operate in a narrow frequency range when operating at ultrasonic range (a resonate frequency of the metallic diaphragm). This is very true once you get above about ~60 kHz. However if the ultrasonic "chirp" you are looking for can be in the range of say 20-60 kHz you could be in luck, i.e., http://www.conrad-electronic.co.uk/ce/en/product/710991/KEPO-piezo-element-25-60-kHz-515-mm
You could use the Tone function (which goes up to 65535 Hz) to produce the frequency sweep you desire. However if you want to go up to frequencies in the 100+ kHz range you will be delving into research territory and hence extremely expensive equipment.
Having said that, technologies change very quickly and I my knowledge may already be out of date. Hope this helps.


text:
Windows 10 problem installing driver
So the arduino shows up as "Unknown device" when connected to my computer. Followed somr guides on google but still failed, this error came up, what should I do? I've tried "Disable Driver Signature Enforcement" and the regedit thing..

Install the latest Arduino IDE with windows administrator rights.


text:
How do I control 4 LEDs with 2 Digital Outputs?
In an effort to learn about transistors that seemed easy enough. But I can't get it to work in practice
Can I control 4 LEDs with just 2 digital outputs (High, Low). So I figured I would use the difference between PNP and NPN transistors to create logic gates.
[00,01,10,11]
But I can not seem to get this to work in practice for the life of me.
I read about Charliplexing, but that is n*(n-1), which isn't good enough. I've also read about shift registers, but I'm not sure I fully understand (I'm a noob), and it sounds like you need a minimum of 3 pins. Is what I am trying to do even possible? If not, then why?

Using two pins it is possible to drive 4 LEDs as long as you only want one of them on at a time.  One LED will always be on - it's not possible to have a setting where there is no output selected.
Basically you are "decoding" a binary value output:
00 = LED 1 on, other three off
01 = LED 2 on, other three off
10 = LED 3 on, other three off
11 = LED 4 on, other three off

To do that you need to use (or construct) a 2-to-4 decoder.
Using logic gates it can be constructed like this:

If you can translate that into transistors then you'll end up with quite a lot of transistors.  Most people would use a specific 2-to-4 decoder chip such as the 74HC139.
Shift registers usually require three pins, yes, though there are possible ways of working with two pins.  You require two pins to provide the data and clock signals, and a third pin to latch the shifted data out to the outputs. However it is possible to use the first leading edge of the clock signal or a specially formatted data signal with a capacitor to create a pulse just before sending new data which can latch the old data.  This requires careful consideration though regarding how fast you would be transmitting, etc, and is not really recommended.
A better solution if you are limited in pins and need to drive multiple LEDs is to use WS2812 "NeoPixel" LEDs which chain together and use a single wire protocol to send data to all the LEDs in the chain.  You can support many LEDs (even hundreds) on a single IO pin, and they are full 24-bit RGB to boot.


text:
Why does my Arduino keep waking up?
This is my first post. Please excuse me if this is a repost, but I couldn't find a similar question via search.
I have some experience with Arduino and I'm looking to utilize AVR's sleep mode in a project. I followed along with this tutorial here. However, when I modify the code as follows, the uC seems to wait 4.09 seconds before waking up the first time. After that, it wakes up repeatedly (about every 6 milliseconds).
In my mind, the Arduino should enter sleep mode and not wake until the timer interrupt wakes it every 4.09 seconds (and then repeats and sleeps again). When I add a delayMicroseconds() after each wake up, it seems to function correctly. I want to accomplish sleep until interrupt wakes, perform interrupted action, then go back to sleep. What's going on? Am I missing something obvious? Is the Serial.println() causing an interrupt that wakes the uC right as it enters sleep?
Thanks for the help!
#include <avr/sleep.h>
#include <avr/power.h>

ISR(TIMER1_OVF_vect)
{
 //do nothing
}

void enterSleep(void)
{
  set_sleep_mode(SLEEP_MODE_IDLE);

  sleep_enable();

  /* Disable all of the unused peripherals. This will reduce power
   * consumption further and, more importantly, some of these
   * peripherals may generate interrupts that will wake our Arduino from
   * sleep!
   */
  power_adc_disable();
  power_spi_disable();
  power_timer0_disable();
  power_timer2_disable();
  power_twi_disable();

  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the timer timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  /* Re-enable the peripherals. */
  power_all_enable();
}

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

  /*** Configure the timer.***/

  /* Normal timer operation.*/
  TCCR1A = 0x00;

  /* Clear the timer counter register.
   * You can pre-load this register with a value in order to
   * reduce the timeout period, say if you wanted to wake up
   * ever 4.0 seconds exactly.
   */
  TCNT1=0x0000;

  /* Configure the prescaler for 1:1024, giving us a
   * timeout of 4.09 seconds.
   */
  TCCR1B = 0x05;

  /* Enable the timer overlow interrupt. */
  TIMSK1=0x01;
  while(!Serial);
}

void loop()
{
    enterSleep();
    Serial.println("Waking");
    //delayMicroseconds(10000);
}

Yes.  Arduino's buffered serial output is interrupt-based, in that it uses interrupts to refill the UART transmit register when it runs empty, until the software-managed transmit buffer has been drained.
You cannot put the ATmega back to "lasting" sleep until the last byte of the serial transmission has been written to the UART hardware.
If the goal of your serial output is only debug, it might be simplest to shorten it to a single character and either send that directly or wait long enough that it should have sent.  If you want to keep the full message, it may take exploration of the Arduino source code to figure out how to determine when the transmission is done.  A simpler, if cruder option might be to just keep going back to sleep until a readback of the counter indicates that your intended sleep is over.

You can use Serial.flush() to block until all the data has been sent from the buffer (and the last byte has been sent from the UART internal buffer register).

Great! Thank you! Both very helpful answers.