text:
Testing Arduino with Visual Studio Community 2013 raise LNK error
I have two projects in my Visual Studio Community 2013 solution.
I created a project for Arduino, and create another project for Test. When I run the project tests without adding the Arduino project reference, it run ok, but when I add the Arduino project reference I get it error:
LNK1561: entry point must be defined D:\VisualStudioArduino\PrinterProject\LINK PrinterProject

What is the entry point for Arduino project?
It does not generate any file like a dll or main file?
What can I do to solve this error?
UPDATE I
I also tried this configuration in the Arduino Project but I get the same error:
Properties -> Linker -> System -> SubSystem to "Windows (/SUBSYSTEM:WINDOWS)"

UPDATE II
I am using Visual Micro extension. But the problems is when I try to compile the Test project. Then I recreate this scenario with a C++ console application and create a simple class, and create a test project and added the console application reference to test project and it worked. Then my doubts is about to how do I configure a Test Project to test my Arduino project.

When you create a Test project you need to add the project reference do you want to test. When I compile the arduino project it compiles ok, the problem is with the tests project.

I use Visual Studio Community Edition 2013 along with the Visual Micro extensions, which I think is what you need as the "missing link" between VS and Arduino.

I am using VSC Edition 2013 with Visual Micro, then when I compile the arduino there is not problem, the error is when I compile the Test project.

Sorry, I don't understand what are yout trying to do. You seem to want to "configure a Test Project to test your Arduino project.". What do you exactly mean with "test your Arduino project"? can you provide details?. do you mean to upload the program to the Arduino?

When I create a class I want to create a test for this class: an Unit Test. I am trying to do a TDD development approach. Some object and function need to be stub, fake and also mocking.

Visual Studio knows nothing about an Arduino project. Why would you be trying to reference it from the other project.  Short answer is that you are not  understanding how to use Visual Studio and / or Arduino. Are you using it with some plugin for visual studio? If you are more than likely it does not support being part of a multi solution (at least that has been my experience with them).
Long answer is give some more details about what you are trying to do, including code from both projects.
Update: Sorry but this is not an Arduino topic. You are fundamentally incorrect in your understanding of how compilers and linkers work and what they are for. As are the other answers.  You can not reference a project compiled for an Arduino, from a project compiled for Windows, period.  I ask you to explain what you were trying to do and I would give you some idea how to accomplish that, but you did not answer. Yes you can use Visual Studio to compile your Arduino project, I do it every day. But I do not 'reference' it from another project on Windows. Do you have any idea what a reference is?
update 2: You can not create a test suite for an Arduino project, at least not in the traditional way. You can not even debug an Arduino project in the traditional way.  Arduino is for prototyping, and very basic beginner stuff, and nothing more. What you are asking about is more traditional development, and the Arduino is not for that (and does not do it very well).
Create 2 separate solutions. One with only your visual micro project for the arduino, and another separate solution with a regular C++ or C# project, not a test project or anything special, just a plain console, or winforms, or WPF project.  The 2 pieces of code must be run at the same time (F5), and probably connect to each other via the serial port, but it depends on what you are doing.
This IS NOT testing in a traditional sense. This is test running a project. The traditional sense of testing is to test isolated portions of code, which is different, and again, can not be done with an Arduino and visual studio.  Since the Arduino only remotely provides 2 wire debugging, and I have never heard anyone actually get it to work at all, you can NOT do any traditional debugging or testing with an Arduino. Instead you are limited to beginner hacks (serial.print).

how do you create a test project for Arduino? Did you try something like it?

What are you asking? I am not the one with the question. I run a huge Arduino project every day, edited and built (from but not ) by Visual Studio. I used to run Visual Micro but stopped, it got in the way more than it helped.

ok, I just asked, maybe someone had been tried to test with visual studio. I am trying to run or create a TestSuite with native c++ to test my arduino classes. If I am using Visual Micro I thought to create the tests with Visual Studio but I am wrong. Thank you for your answer. If you have any idea or reference about how can I do tests for arduino I will be happy?

I think you might be a lot happier with .Net Microframework stuff. It is centuries ahead of Arduino for things like this. You still can not reference code directly, but at least you are working in the same framework (.Net). Problem is it is kind of mid-flux at the moment (Windows 10 IoT).

You are trying to build a Windows program.  You need a main() function as an entry point.  I suspect that when your code is built through the Arduino IDE it adds in a main function in.
You can tell Visual Studio to build your files differently by defining some build rules, but it sounds like someone may have done this sort of thing by looking at the other answers.
But the easiest short term solution would be copying and pasting into the Arduino IDE.

The best place for answers is in the Visual Micro forum.

Be sure about is that the main .ino source file of your Arduino project matches both the name of the Visual Studio project and the name of the folder they existing in. For example:

Folder = Sketch1
Master Source = Sketch1.ino
Visual Studio Project Name = Sketch1

This ensure Visual Micro will compile the project and also it will be compatible with the Arduino Ide.

With two projects in a Visual Studio solution it is important to note which is the "Startup Project". You can control which is the startup by right clicking a project in the explorer and clicking "Set as Startup project". The project name will then appear in bold.

The startup project affects which project is uploaded/started/debugged when you click any of the "Start" commands.

The menu item "Build>Configuration Manager" allows you to exclude your Arduino project from Visual Studio Win32 builds but changing this option should not normally be required.
You can right click each project and click "Start>New instance" to override the current "Startup project" and specifically build and upload a project.

Summary
If the build/upload fails and you see the visual studio c++ compiler error that you have described above this means that Visual Micro is not handling the build process for the project.
Therefore, please confirm point 1 is correct by trying out build task described in point 4 above.
It would be useful to know which build command you are selecting when the problem happens.


text:
Arduino and HC-05 hardware serial issues
I have a software sending bitmap data to an Arduino Pro 5V 16MHz 328P that drives an LED display (sketch). This works using the USB-Serial adapter for the Arduino Pro with baud rates up to 500000 Baud. Now I wanted to switch to Bluetooth...
I tried connecting a 5V HC-05 module (set to 230400 Baud 8N1) to the hardware RX/TX pins on the Arduino Pro (Pins 0/1) and connect the PC to the Bluetooth serial port wirelessly (e.g. /dev/rfcomm0 on Linux). My problem is that I can receive data on the PC side using a terminal (the 'Ada' string is received), but nothing is displayed on the LED display. I have tried connecting an oscilloscope to the RX/TX pins on the Arduino and Data is arriving from the HC-05 module TX pin to the Arduino RX pin.
When the USB-Serial adapter is connected to the same pins (0/1 instead of the regular pin header) it still works as before, so there should be no connection issues.
What I tried was adding a 5kOhm resistor from the Arduino RX line to ground. (I found this hint somewhere here), but no dice...
I'm not sure what's wrong, because communication IS working over the USB-Serial adapter. Any ideas on what to try?!

Start by using reasonable baud rates!   Whatever you think you are accomplishing by trying to make one piece of the system so fast, is almost certainly not going to result in meaningful improvement overall, yet vastly increases the change that the system won't work at all.

There's a few things I can think of that may be causing your issue. First, though, a few questions: (1) Which version of the Arduino Pro are you using (168, 328P, voltage, frequency, etc)? (2) Are you saying that you can connect the PC to the Bluetooth serial port via a USB cable or via a wireless Bluetooth link (a little confused by the wording)? (3) What model of the HC-05 are you using (I know you said 5V, but I've come across many variations of this device - a link of where you bought it would be great). Hope I can help once you have a chance to answer these questions!

@ChrisStratton: The HC-05 advertises Baud rate up to ~1MBaud, so imo 230400 is reasonable. Also it works with the USB-Serial adapter connected to the same pins.

@Mlagma: The model is an Arduino Pro 5V 328P 16MHz. I "connect"/pair the PC to the HC-05 wirelessly and then plug the module into the RX/TX pins (Pins 0/1) on the Arduino. The HC-05 Module is a regular board with a 5V level-shifter-breakout (very common). Sorry, but I don't have a link anymore. What I tried was adding a 5kOhm resistor from the Arduino RX line to ground. (I found this hint somewhere here), but no dice...

I have in fact used another HC-05 (no level shifters, 3.3V) sucessfully with an Arduino Due, plugging it into hardware Serial1 (Pins 18/19) and using the Dues' native USB port as a serial port to transfer text PC->HC-05->Arduino->PC back and forth. Even at 230400 Baud.

I have now tried connecting an oscilloscope to the RX/TX pins on the Arduino and Data is arriving from the HC-05 module TX pin to the Arduino RX pin. I guess the sketch is not working properly with the HC-05 connected, but I'm not sure why... What could I be missing?

No, 230400 is not reasonable unless you have verified for a fact that both your devices can generate the necessary timings signals accurately, which a little math would suggest an Arduino cannot.

@Chris: I did not say you don't have a point. I know you're referring to this problem. The error at 230400 should be ~8%, which is way off. I'll try with a lower bit rate.

115200 should be more than enough.

For everyone? You are probably joking and mean "640k". And no, it is not. I have too many LEDs for the Baud rate...

Have you actually calculated how many bits you actually need?

I have ~600 LEDs * 3 color * 8 bit resolution = ~14400 Bit / frame. This amounts to max. 8 frames/s for 115200 Baud, which is not enough. With 230400 It'd be ~16 frames/s, which is usable for me. I am testing simple compression algorithms too, so I can reduce the amount of data a bit, but ~10-20% size reduction will be the maximum.

A simple 10k/20k voltage divider is enough to bring the 5V arduino logic-level voltage down to ~3.3 for the HC-05.  It worked for me anyway.
The default baud rate for HC-05 is 9600 baud.  So unless you've changed this with AT- commands you will run into issues.  Although I read that some boards default to 38400 - best check your documentation.  All the cheap HC-05 boards I've tested default to 9600.

Communication works up to 115200 Baud, but not more. The goal was to get higher Baud rates...

@Bim - My HC-05 doco says my HC-05 hardware is only good for up to 115200.  Hopefully yours is a better brand.

Can you provide a link? A quick look in [http://www.instructables.com/files/orig/FOR/4FP2/HKZAVRT6/FOR4FP2HKZAVRT6.pdf](here, page 8) says it should allow up to ~1.5MBit, which makes sense, because Bluetooth 2.0 does. I also tried with two different modules.

The HC-05 requires a 5V power supply and 3.3V logic.
Using SoftwareSerial might be easier for you as you can use pins 8 and 9 rather than 0 and 1, because there can be issues with the USB.
Are you transmitting the data you think you are, might Big/Little Endian be an issue?
I can get two HC-05 devices to communicate when they are connected to the PC via serial port adapters.  However when I replace the receiver with a HC-05 connected to an UNO I get intermittent garbage received.  So I suspect there may be some sort of problem with PC->Arduino.

My HC-05 has level shifters, so it it suitable for 5V. Software serial is no option, because it is just too slow and blocks the Arduino. There should no issue with USB, because the Arduino Pro does not have USB. I don't think the Bluetotth module can change the endianess of the data. I'm interested what that "some sort of problem" is...

I've run into similar issues with the Arduino and serial communications - it's quite a pain.
There really shouldn't be an issue with your sketch if PC->USB->FTDI->Arduino is working since the same protocols are used (UART is UART, after all).
In regard to the BAUD rate, sure, 230400 should work just fine. For purpose of testing, though, I would slow it down to a measly 9600 or something like that just to rule out any possible issues. (Plus, if I remember right, 9600 or ~11000 is the rate at which it operates when being programmed via AT commands).
Now these are my thoughts on what the problem may be:
You said several times that you have a 5V HC-05 with level shifters. The HC-05 chip itself operates on 3.3V, so typically there is a voltage regulator on the breakout board dropping the voltage down to 3.3V for the Vcc pins and whatever else is pulled high on the chip.
However, I have never seen an HC-05 on Amazon, Sparkfun, or Ebay that actually has a true logic-level shifter on the board itself. Instead (and this is true from my experience with Ebay sellers who claim logic-level shifting built in), there is a voltage divider on the HC-05 RX pin that allows you to send a 5V signal without external resistors. But this isn't bidirectional, so your TX pin still has a logic high level of 3.3V. In short, I think your HC-05 chip really doesn’t have a logic-level shifter.
You may be thinking I’m totally wrong about this, and I very well could be since I don’t have your module in front of me, but just hear me out by reading my reasoning below.
(1) You said you can receive data on your PC. This means the HC-05 is receiving data from a 5V signal and successfully converting it to 3.3V. Great. That works!
(2) You said you were able to get an HC-05 (presumably the same model) to work with an Arduino Due in both directions. The Arduino Due operates on 3.3V, so its logic high threshold is around 2.1v.
(3) On the 5V Arduino Pro, the minimum logic high threshold is (0.6)*Vcc -> 3V. So if the HC-05 is transmitting a signal with a logic high of 3.3V, the Arduino is barely registering it. Factoring in resistance and noise, your signal is probably less than 3.3V. (In fact, my HC-05’s usually push out a signal of ~3V).
Reading that you can see a signal on the HC-05 TX line, but the Arduino is not registering it, I’d bet your signal is below the threshold.
So, I’d fire up your oscilloscope again and check the peak voltage to see what it is.
Additional (Response to "what can I do?)"
You have a few options. The best option would be to use a bidirectional 3.3V-5V level shifter, but not many people have those laying around. If you happen to have some common components, you could try building a makeshift level shifter like in the images below:

The first "level-shifter" is a a voltage comparator using an opamp. If you go this route, ground V-, tie V+ to 5V, and calculate a voltage divider for around 1.5V. (Note: use the non-inverting setup). A cheap TL272 from Radioshack should work.
The second level shifter uses two NPNs and is self-explanatory.
Note, though, that I haven't tried any of these setups nor know their frequency responses. However, the TL272 should handle signals into the MHzs, and BJTs handle high frequencies rather well. My gut tells me it should work, but just in case, I would use a low BAUD rate.

DAMN! You seem to be right! The HC-05 puts out ~3V on its TX line. The RX line shows a maximum of 3.8V. What can I do?

@Bim I added some suggestions

Thanks a lot! I don't have a TL272 (or other OpAmps) at hand and don't really want to build a level shifter for 3 channels (RX/TX/EN) right now, so I ordered a bi-directional 4-Channel level shifter board. I still have a 3.3V linear regulator lying around. I seem to have broken the EN/KEY pin of the HC-05, but have a working one for 3.3V. It should take a couple of days for the stuff to arrive and for me to try things out, but then I'll get back with the results...

The parts have arrived and I tried connecting the HC-05 to the Arduino Pro through the level-converter. The voltage levels are now around 4.5V. It all works well through bluetooth at 115200 Baud, but not at 230400 Baud.I also tried using a Arduino Due instead and connecting the HC-05 directly (TX0/RX0). As before, I can receive data on the PC side (The "Ada" status message), but no data arrives on the Arduino side... I'm at loss what to try to get higher throughput through the HC-05...

@Bim Just to be sure, it is working now in both directions at 115200 Baud? The problem is that 230400 isn't working?

Yes.It is working at 115200 Baud in both directions. I captured the waveforms of a bit for 115200 and 230400. The signal generated by the Arduino looks good, but that of the HC-05 is pretty crappy: 115200
230400

A problem in the code could be that FastLED takes a lot of time in "show()" and due to that the serial port is overrun and data dropped... But at some point the code should recover. I uncommented the "while (Serial.available() > 0) { Serial.read(); }" loop (Line #83 in the sketch) to make sure incomplete data is consumed and the code will "sync" again, but that didn't help. It seems the other baud rates above 115200 the HC-05 supports are all not compatible with the (16MHz) Arduino... :(

@Bim One thing that might be worth checking is the signal after the level converter. The part you bought said its used for I2C, and 115200 BAUD is around the standard I2C frequency. When you double it, the signal might be attenuated you're nearing the crossover point of the frequency response.

See my previous reply that has screenshots of the signals linked. I grabbed the signals on the Arduino RX/TX pins so they are "behind" the level converter in relation to the HC-05. The TX signal from the HC-05 (RX on the Arduino) looks a bit distorted to me... They time the signal is HIGH might not be long enough for the Arduino.

@Bim I didn't notice the links before. They definitely look distorted, and it also looks like they only go up to 4V (which is fine, I was just expecting a little less than 5V). In any case, it could be, like you said, there isn't enough time for the Arduino to register the logic high signal being that it takes a while to pass the threshold. You could try a pull up resistor, but the trade off is a longer fall time. Also, the level converter could be messing with the high frequencies, which can cause what you're seeing. If you really want, you could generate a sine wave and watch the response.

I found this which suggest what you said (level-shifter distorts signal). I'll attach a probe and check the input/output signals of the level converter. I tried a pull-up resistor on the arduino side, but that didn't help. Will try one on the HC-05 side too...

I captures the signals on the HC-05 TX line at 230400 Baud before and after the level converter now. Images here. The upper image is without a pull-up. The lower image is with a ~1.5kOhm pull-up from 5V to the RX pin of the Arduino (behind the level-converter). It looks like the signal should be fine with the pull-up... It could still be that the bit rates of the HC-05 and Arduino are not matching as Chris Stratton mentioned. In that case I guess I'm lost?

Well this is really irritating. The signals look fine, so I doubt there are any problems left there. Another thing I can think of is in regard to the BAUD rate. The 16MHz crystal doesn't play too well with standard baud rates (even 115200 is a little off). However, multiples of 250k may work for you. The Arduino can deal with these speeds (others have done this). The HC-05 can also handle this, but it requires flashing it with different firmware.

I can run the Arduino at 250k and 500k Baud and it still works via standard serial, thus switching the HC-05 to those Baud rates might be a solution. Could you point me to a firmware/page that does this? I have already searched but not really found anything useful...

@Bim I'll throw some stuff together tomorrow. I didn't get a chance to do so today.

No sweat. I've got it hooked up via USB-Serial atm. I took a look at the CSR toolchain. Are you using the BlueCore SDK for this? If yes, in case you have sources I can compile, I could give it a shot too... That said, flashing the firmware seems to be the hard step. What would you recommend? I found this, which suggest using an Arduino as an SPI programmer. Sadly I have no access to a proper LPT port or FTDI232L atm.

I have used HC-05 modules earlier, with baud rate 9600. But the Chinese modules I recently purchased from eBay appear to be pre-wired for 38400. The module refused to transmit anything, and was receiving garbage on the Rx side. So I changed the line
softSerial.begin (9800);

to
softSerial.begin (38400);

This solved my problem.

source: Stack Exchange

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

sort: votes


text:
Change code so motion sensor prints time instead of a button
I have the code below. At the moment there is a proximity sensor that makes a speaker play happy birthday when it is set off. I also have an LCD shield attached and when one of the buttons on LCD screens interface is pressed, the time that it was when the button was pressed prints on the screen. I need to get it so that when the proximity sensor is set off it plays the sound on the speaker and then prints the time which is was set off on the screen.
/*--------------------------------------------------------------------------------------
 Includes
 --------------------------------------------------------------------------------------*/
#include <Wire.h>
#include <LiquidCrystal.h>   // include LCD library

int timer = 1000;
int C = 262;
int D = 294;
int E = 330;
int F = 349;
int G = 392;
int A = 440;
int B = 494;
int Bflat = 466;
int Chigh = 523;

const int analogPin = A1;    // pin that the sensor is attached to
const int threshold = 400;

/*--------------------------------------------------------------------------------------
 Defines
 --------------------------------------------------------------------------------------*/
// Pins in use
#define MILLIS_OVERFLOW 34359738
#define BUTTON_ADC_PIN           A0  // A0 is the button ADC input
#define LCD_BACKLIGHT_PIN         3  // D3 controls LCD backlight
// ADC readings expected for the 5 buttons on the ADC input
#define RIGHT_10BIT_ADC           0  // right
#define UP_10BIT_ADC            145  // up
#define DOWN_10BIT_ADC          329  // down
#define LEFT_10BIT_ADC          505  // left
#define SELECT_10BIT_ADC        741  // right
#define BUTTONHYSTERESIS         10  // hysteresis for valid button sensing     window
//return values for ReadButtons()
#define BUTTON_NONE               0  //
#define BUTTON_RIGHT              1  //
#define BUTTON_UP                 2  //
#define BUTTON_DOWN               3  //
#define BUTTON_LEFT               4  //
#define BUTTON_SELECT             5  //
//some example macros with friendly labels for LCD backlight/pin control,     tested and can be swapped into the example code as you like
#define LCD_BACKLIGHT_OFF()     digitalWrite( LCD_BACKLIGHT_PIN, LOW )
#define LCD_BACKLIGHT_ON()      digitalWrite( LCD_BACKLIGHT_PIN, HIGH )
#define LCD_BACKLIGHT(state)    { if( state ){digitalWrite(     LCD_BACKLIGHT_PIN, HIGH );}else{digitalWrite( LCD_BACKLIGHT_PIN, LOW );} }
/*--------------------------------------------------------------------------------------
 Variables
 --------------------------------------------------------------------------------------*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds = 0, minutes = 34, hours = 8;

byte buttonJustPressed  = false;         //this will be true after a        ReadButtons() call if triggered
byte buttonJustReleased = false;         //this will be true after a     ReadButtons() call if triggered
byte buttonWas          = BUTTON_NONE;   //used by ReadButtons() for detection of button events
/*--------------------------------------------------------------------------------------
 Init the LCD library with the LCD pins to be used
 --------------------------------------------------------------------------------------*/
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2     LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
/*--------------------------------------------------------------------------------------
 setup()
 Called by the Arduino framework once, before the main loop begins
 --------------------------------------------------------------------------------------*/
void setup()
{
  //button adc input
  pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
  digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
  //lcd backlight control
  digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is     high (on)
  pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
  //set up the LCD number of columns and rows:
   pinMode(13, OUTPUT);
  lcd.begin( 16, 2 );

  //Print some initial text to the LCD.
  Serial.begin(9600);
  lcd.begin( 16, 2 );

}
/*--------------------------------------------------------------------------------------
 loop()
 Arduino main loop
 --------------------------------------------------------------------------------------*/
void loop()
{

  setClock();
  byte button;

  button = ReadButtons();

  /**
   * After set clock now you have 3 int variables with the current time
   */
  //seconds
  //minutes
  //hours
  lcd.setCursor ( 0, 1);
  lcd.print(hours);
  lcd.print(":");
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  lcd.print(":");
  lcd.print(elapsedMillis);

  //get the latest button pressed, also the buttonJustPressed,     buttonJustReleased flags

  //blank the demo text line if a new button is pressed or released, ready for a new label to be written

  //show text label for the button pressed
   if(buttonJustPressed || buttonJustReleased)
  switch( button )
  {

  case BUTTON_LEFT:
    {
      lcd.setCursor( 0, 0 );
               lcd.print(hours);
               lcd.print(":");
               lcd.print(minutes);
               lcd.print(":");
               lcd.print(seconds);
               lcd.print(":");
               lcd.print(elapsedMillis);

      break;

    }
  default:
    {
      break;
    }
  }

  if( buttonJustPressed )
    buttonJustPressed = false;
  if( buttonJustReleased )
    buttonJustReleased = false;
}
/*--------------------------------------------------------------------------------------
 ReadButtons()
 Detect the button pressed and return the value
 Uses global values buttonWas, buttonJustPressed, buttonJustReleased.
 --------------------------------------------------------------------------------------*/
byte ReadButtons()
{
  unsigned int buttonVoltage;
  byte button = BUTTON_NONE;   // return no button pressed if the below checks don't write to btn

  //read the button ADC pin voltage
  buttonVoltage = analogRead( BUTTON_ADC_PIN );
  //sense if the voltage falls within valid voltage windows
  if( buttonVoltage < ( RIGHT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_RIGHT;
  }
  else if(   buttonVoltage >= ( UP_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( UP_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_UP;
  }
  else if(   buttonVoltage >= ( DOWN_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( DOWN_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_DOWN;
  }
  else if(   buttonVoltage >= ( LEFT_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( LEFT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_LEFT;
  }
  else if(   buttonVoltage >= ( SELECT_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( SELECT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_SELECT;
  }
  //handle button flags for just pressed and just released events
  if( ( buttonWas == BUTTON_NONE ) && ( button != BUTTON_NONE ) )
  {
    //the button was just pressed, set buttonJustPressed, this can optionally be used to trigger a once-off action for a button press event
    //it's the duty of the receiver to clear these flags if it wants to detect a new button change event
    buttonJustPressed  = true;
    buttonJustReleased = false;
  }
  if( ( buttonWas != BUTTON_NONE ) && ( button == BUTTON_NONE ) )
  {
    buttonJustPressed  = false;
    buttonJustReleased = true;
  }

  //save the latest button value, for change event detection next time round
  buttonWas = button;

  return( button );
}
void setClock()
{
  currentMillis = millis();
  /**
   * The only moment when currentMillis will be smaller than previousMillis
   * will be when millis() oveflows
   */
  if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
  }
  else {
    elapsedMillis += currentMillis - previousMillis;
  }

  /**
   * If we use equals 1000 its possible that because of the mentioned loop limitation
   * you check the difference when its value is (999) and on the next loop     its value is (1001)
   */
  while (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
  }

  if (seconds == 60){
    minutes++;
    seconds = 0;
  }
  if (minutes == 60){
    hours++;
    minutes = 0;
  }
  if (hours == 24){
    hours = 0;
  }

  previousMillis = currentMillis;

 int analogValue = analogRead(analogPin);
  if (analogValue > threshold) {

tone(13,C,timer/2);// Happy Bday to You
delay(200);
tone(13,C,timer/2);
delay(200);
tone(13,D,timer/2);
delay(400);
tone(13,C,timer/2);
delay(400);
tone(13,F,timer/2);
delay(400);
tone(13,E,timer);
delay(750);
 }
else {

}
}

Why are you still posting code with the MILLIS_OVERFLOW stuff now that you know it's both useless and bogus? Do you at least follow the answers to your previously posted questions?

Dude, I'm completely new to this and not good at knowing which parts to take out. I do follow the previous answers I get which is why I've gotten to where I am, I'm just trying to get it all working before I simplify it cause every time I try to I end up deleting stuff I shouldn't on accident and it all stops working, but I'll try again now

The code seems a little hotchpotch; is the code for reading the sensor supposed to be within the setClock() function? It would be better to put the following within loop():
if(analogRead(analogPin) > threshold)
{
    playMelody();
    printTriggerTime();
}

And create two new functions that handle the playing of 'Happy Birthday' and the printing of the time:
void playMelody()
{
    tone(13, C, timer / 2);// Happy Bday to you
    ...
    delay(750);
}

...which is just a cut-paste of what you've got in the setClock() function, and:
void printTriggerTime()
{
    lcd.setCursor(0, 0);
    ...
    lcd.print(elapsedMillis);
}

...which is a copy-paste of the code from within case BUTTON_LEFT:.
This will now play 'Happy Birthday' and print the time whenever the proximity sensor is triggered, AND it will print the time when the left-button is pressed (unless you remove that part of the code).
On a separate point, it's bad coding practice to use #define for a function, as you have done with #define LCD_BACKLIGHT(state) { if ( state )... - it makes it quite difficult to read the code, and can't conceive any reason why this isn't its own function. However, a nice trick in C is the following 'shortcut' statement:
( CONDITION ? DO_IF_TRUE : DO_IF_FALSE )

Thus you should change that line to:
#define LCD_BACKLIGHT(state) ( state ? digitalWrite(LCD_BACKLIGHT_PIN,HIGH) : digitalWrite(LCD_BACKLIGHT_PIN,LOW))

That being said, "LCD_BACKLIGHT(state)" isn't actually used anywhere in the program!

(state ? digitalWrite(LCD_BACKLIGHT_PIN,HIGH) : digitalWrite(LCD_BACKLIGHT_PIN,LOW)) can be simplified to digitalWrite(LCD_BACKLIGHT_PIN, state ? HIGH : LOW), and then further to digitalWrite(LCD_BACKLIGHT_PIN, state), as digitalWrite() interprets its second argument as a boolean.

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


text:
How shiftOut function works internally? (explanation on source code)
I were examining shiftOut() function code in wiring_shift.c and I didn't quite understand what is going in digitalWrite function. I see !!(val & (1 << i)) is taking the bit value from val but how exactly it works?
The whole function is below.
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

!!(val & (1 << i)) is the most complex part of this code. If you do understand this, then what is the part you do not understand?

@edgar-bonet Actually this was the question. I can see it somehow calculates the bit value, but I didn't understand how it do this.

You do understand the behaviour of the shiftOut function?
I mean, you do understand that it'll shift out a value (in binary form). And will give a clock pulse along with it.

I'll assume bitOrder == LSBFIRST.

i is the bit number, i.e. the “index” of the next bit to write
1 is 00000001 in binary
<< is the shift left operator. It returns its first argument shifted left by as many positions as indicated by the second argument
1<<i is binary 00000001 shifted left by i positions, i.e. something like 0...010...0, where the single 1 is in the i-th position counting from the right (rightmost being position 0)
& is the “bitwise and operator”, where any_bit & 0 is zero and any_bit & 1 is any_bit
val & (1 << i) is 0...0(i-th bit of val)0...0 in binary, where the i-th bit of val is in the i-th position of the result
!! is a double negation: it converts zero to zero and any non-zero value to one
!!(val & (1 << i)) is either 0 or 1, and is exactly the i-th bit of val

let me summarize what I understand. Let assume val = '10010111';
`for i=2`
  `!!(val & (1 << i))` = `!!('10010111' & '00000100')` = `!!('00000100')` = `1`

If i is = 3
!!(val & (1 << i)) = !!('10010111' & '00001000') = !!('00000000') = 0

This is correct!

And this means if I give 16bit or longer data to shiftOut, it will send least significant 8 bits and ignore the rest.

shiftOut() takes uint8_t data. If you call it with a 16-bit argument, the compiler will implicitly remove the 8 most significant bits before the actual call to shiftOut().

Thanks for the explanations above. This has been invaluable helping with understanding and re-using the code elsewhere. I see that double negation converts zero to zero and any non-zero value to one; I can't see what else it could be. Without double negation, wouldn't the output be the same anyway? What is it I am missing?

@SteveMcDonald: Yes, the output would be the same without the double negation, because digitalWrite() interprets any non-zero value (not just 1) as meaning HIGH. Apparently, the author of shiftOut() did not want to rely on this behavior, and instead wanted to always call digitalWrite() with either 0 (i.e. LOW) or 1 (HIGH).


text:
Can I use an arduino as a ground short?
I have a little personal project involving an Arduino Uno and an amp board from Sure Electronics. The amp has contacts for a mute function that involves shorting the contact to ground. I would like to control this muting with the Arduino which I was planning to do with a relay. However I think I might be complicating things and I thought it might be possible to do it directly with the pins.
Can I use the Arduino to directly short a circuit to ground? Or would I need something more complicated to be safe?

@FuaZe - no, that is extremely incorrect.  The limit for a given signal is at least 10 times lower!   And there is a maximum voltage, too.

"For 328P, the max current rating is 400mA for the TQFP package" - http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations
"DC Current per I/O Pin: 40.0 mA"
How stupid, I took the max current rating for the complete package... per pin it indeed is ~40mA.
Also, ofcourse it shouldn't surpass the arduino voltage limits (5V?)
I'll delete my comment before anyone will burn his/her arduino because of it :)

Depends on the voltage that is on that mute pin. If it's below 5 volt, you could use the arduino pin. You can measure the voltage using a multimeter.
If it's more than 5v you can use a NPN transistor and resistor combination.
Current isn't a problem with these kinds of "settings" pins, as there is just a pull-up resistor that by default (unconnected) sets the pin to HIGH. By connecting the pin to ground you set the pin to LOW.

I would recommend an optical coupler: http://en.wikipedia.org/wiki/Solid-state_relay, which will let the Arduino survive even in case of severe overvoltage in the amp. They also come in 2 or 4 per package, so this could control also the power of the amp, in a small footprint. Example: http://www.ebay.com/itm/6N136-Highspeed-Transistor-Optocoupler-DIP-8-/251561136534?pt=LH_DefaultDomain_0&hash=item3a92365196

I missed the product link in the question. The SD pin is pulled up to the voltage applied to the amp (page 20 datasheet). The voltage for the amp is 8-24 volts. So you can connect the pin directly. And optocoupler is a bit overkill with these low voltages. Solid state relays are uber-overkill.

I can't see how much current the amp board will sink into the Arduino so like FuaZe I would recommend using your Arduino to drive an external component that you know can take the current.  This isn't really complicating the design too much, use an NPN transistor, with the P connected to the Arduino and just write High to the pin when you want to apply the mute.  If you blow the transistor then its going to cost you a few pence for a new one, if you blow your Arduino you are down £20!

Don't forget to add a resistor between the base (P) and the Arduino pin, or you will definitely blow your Arduino, regardless of the amp board.

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


text:
Books on Arduino development in C++
I will be using the Arduino platform with other data acquisition hardware for a school electronics project. I have limited knowledge of C++ syntax.
Are there good introductory to intermediate books that can bring a high school student with some programming experience to proficiency on Arduino?

IMHO the only way to learn it is to program it. So grab any arduino (UNO, Mega, Nano... I suggest you the mega 2560 because it'll be useful for more projects) and then go on the arduino website and follow the tutorials. Then choose a device (e.g. an LCD with Hitachi HD44780 controller) and search for "Arduino *", where * is the device; learn how to use it. Then move to the next one. The learning curve is not steep at all, and there are not many things to learn. Just, please, keep in mind that it is a MICROcontroller, not a PC. So avoid using complex structures. Keep it as simple as you can

I'd recommend you go to cplusplus.com. Plenty of tutorial pages and topics to further your knowledge. However, be aware that Arduino uses a variant of C designed for microcontrollers (the exact flavour depends on the microcontroller type/family), rather than C++, so do be aware that some of the topics are not implementable on an Arduino. That said, I can't think why you'd be using some of the more elaborate C++ exclusive features in a fairly middle-of-road embedded system.
The only thing you need to ignore in C++ is memory allocation specifics - you're limited to the 'original' malloc() based functions rather than the all-singing-all-dancing operator new from C++. If you are in need of memory allocation functions, malloc is well-documented and a tutorial is only a quick Google away.
Of course I must also point you in the direction of the highly popular Stack Overflow site, part of this Stack Exchange network. While they don't have tutorials, there are plenty of great answers to common questions.

Only Intel's arduinoesque offerings use uClibc.

Most Arduinos (notably not the Due) run AVR microcontrollers. On these, the Arduino core library is based on AVR Libc.

@Ignacio Vazquez-Abrams: I thought "uClibc" was a generic term for a specific hardware-orientated C libraries, not a specific one; I stand corrected. Answer edited to remove direct reference.

Also, Arduino (at least for some of the boards) does use C++ the language proper; only some library support (notably the entire STL) is missing.

Recent versions of the IDE support new and delete. Thus you can instantiate classes on the heap without any trouble (excepting possible memory fragmentation). Plus what @IgnacioVazquez-Abrams said. You can basically program in C++. The STL can be installed if you want it. However exceptions are not supported as far as I am aware.

I would start with a standard C++ introduction book to get an understanding for the language. After that I would read a book on object-oriented design and implementation.
There is a lack of books on how to systematically approach programming small scale embedded systems such as Arduino. Due to the restrictions on resources, both processing and memory, C++ has to be used "carefully". There is a need to understand some of the more difficult concepts such as volatile, virtual, ISR, etc.
Reading others code is also a very good way to learn. I would recommend looking at the source code and example sketches to Cosa. This is an OOP framework for Arduino/AVR.
Last but not least - learning by doing!
Cheers!

There is a book called "C Programming for Arduino" by Julien Bayle that introduces it pretty well if you are just getting started at it. I think it's from Packt Publishing.
Another I found interesting is called "Practical AVR Microcontrollers" by Alan Trevennor that gives examples of programming using C without having to get an Arduino.
Otherwise, Stack Exchange is always really great to browse.

You don't actually need an Arduino to use Arduino libraries though. They work just fine with discrete MCUs.

I found the Arduino examples a good reference for refreshing/learning C++.
Important Arduino C++ classes are:

String: https://www.arduino.cc/en/Reference/String
Arduino classes for components: https://www.arduino.cc/en/Reference/Libraries

To learn more about the syntax of the language, the inventor of C++ has also a couple of videos online.


text:
Arduino raise the error: `does not name a type` when an Object is used outside of the main two blocks setup and loop
I have this:
class Person{
public:
    int age;
};

Person p;
p.age;

void setup() { ... }

void loop() { ... }

And I got this error:
Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
MyProgram.ino:18:1: error: 'p' does not name a type
Error compiling

But is I use the Person instance inside setup or loop functions it compiles find.
void setup() {
    // initialize digital pin 13 as an output.
    Person p;
    p.age;
}

I got this:
Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
Binary sketch size: 4,674 bytes (used 2% of a 253,952 byte maximum) (3.45 secs)
Minimum Memory Usage: 428 bytes (5% of a 8192 byte maximum)

What is the different? Why the instance only can be used into the blocks?
I also declared a file with a simple class and then create a instance of it class outside the blocks and I got the same error. If I put the instance inside the blocks it works. So, any tips?

As you have already noticed, you cannot call methods of a class, nor access its properties, outside a "block" (as you call it).  More specifically, you can only perform "programatical" operations from within a function.  Anything outside a function (known as the global scope) is purely for declaration and initialization of variables and types, etc.
Any class variables declared in the global scope have their constructor executed before the rest of the program (even before setup) gets run.  However, setup is not the first function to be called at startup.
Anything you put into a constructor has to take into account the fact that anything might be happening between the constructor being called and the object instance actually being used.  Things like pinMode and digitalWrite are unsafe to use in a constructor, since there is a chance they may be negated during the startup.  That is why the majority of Arduino classes have a .begin() method which is called from setup().
The proper method for using classes with pin control and similar operations is:

The constructor takes the pins to use
The constructor saves those pins in variables
The begin() method is called in setup()
The pins are configured appropriately.

For example:
class myClass {
    private:
        int _myPin;
    public:
        myClass(int pin) : _myPin(pin) {}

       void begin() {
            pinMode(_myPin, OUTPUT);
            digitalWrite(_myPin, HIGH);
        }
};

myClass p(4);

void setup() {
    p.begin();
}

void loop() {
}

The object instance p is in the global scope and can be referenced from any function. The pin is configured only when setup() is run.
The startup sequence, more specifically, is typically this:

The memory used by global and static variables is "zeroed".
Any pre-defined variable values (BSS) are copied from flash into RAM.
Any object constructors are called.
The main() function is called (main startup function).
The init() function is called which configures the Arduino platform.
The initVariant() function is called which performs any board specific setup routines.
USB is configured on the boards that have it
Your setup() function is called.
Your loop() function is called.
The serialEvent() system runs if defined.
Go to 10.

As you can see quite a lot happens between the constructor being called and setup() being called, and you cannot reliably predict what that might be.  Some boards may do nothing more than configure interrupts and enable timers (for things like delay and millis), but other boards may configure IO pins to default settings (especially more complex boards with multiple functions per IO pin), so really the only safe operations you can perform in a constructor are operations which act directly on the internals of the class itself.  Anything outside the scope of the class could be changed before you come to use it.

All code intended to be executed must be inside a function block in C++.

So, I can create an object instance but if I want to use it I have to invoke the functions inside the block? Is that correct? I am asking because right now I cannot test the arduino project.

That is correct. You can declare and initialize an object in the global scope, but you cannot call its methods or access its fields.

Having said that, it is possible to create additional memory segments that are executed prior to main(), but I don't know if the Arduino IDE will handle them appropriately.

I am trying to create a simple instance before the setup() and loop() blocks. Inside the instance I configure some pins to the output mode. But Arduino show a wrong behavior. But if I configure this pins into the setup blocks the Arduino show me the right behavior. I am really confuse. Because I want to use some class to reuse some functions.

Then put the code to configure the pins in the constructor block.

 pinMode(this->m_stepPin, OUTPUT);
 pinMode(this->m_direction, OUTPUT);``` I have this inside the constructor block but If does not run like I expect. When I create this configuration inside setup() function the problem is fixed. Then I am thinking that maybe Arduino is not handle this instance in the right way.

Let us continue this discussion in chat.


text:
My arduino won't show up in Device Manager in any way, neither in unknown devices nor in COM port.
I have a brand new arduino(original), and it is not showing up in Device manager or anywhere else. Even the computer doesn't Prompt anything. I am using Windows 7 32 bit.

Have you tried a different cable? Different computer?

Is there anything connected to it? (Like sensors and what not) that could be wired up wrong. Is the power light on?

It worked with a different cable.

As the OP reported: It worked with a different cable.
I converted his comment to an answer so the system would regard this issue as solved. Please accept this answer.

Some cheap USB cables only carry power, and not data. I have such a cable that came with a USB desk light. To save money they only run two wires and not four, since the desk light is not a data device.
Be cautious about grabbing any old cable from your desk for testing. Make sure it is designed for data use. If in doubt, try a known good cable.


text:
Serial communication stops when I connect the tx cable
I'm using the apc220 rf modules. Now I'm having the following problem:
My receiving arduino uno only receives data when the tx pin on the arduino (rx pin on the rf module) is disconnected. As soon as I connect the tx pin my serial monitor receives only the value 0.
Is my rf module broken, or can someone help me with this?

Which Arduino board are you using?

The Uno only has a single hardware UART. Are you attempting to use it to connect to both the USB-UART bridge and the RF module at the same time?

To have two serial ports on Arduino board like Uno use SoftwareSerial.h.
Example
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2,3); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  Serial.println("Hello!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Now after opening Serial monitor you should see Hello! and then you can test SoftwareSerial.
DO NOT FORGET!!!
When you connect to pins 2,3 or etc, this is TTL voltage level. You can't connect direct to RS232.

I know about Software Serial. The problem is that I use the rf modules for a quadcopter project and I need the memory of the rx pin, I think (correct me if I'm wrong).

Ok, so if you know more than i expected :) Clear for me this: How you connect RF module and debug it at the same time having only 1 serial port? Remember that : pins 0 and 1 ar Tx, Rx for USB. You can use them only without USB attached

And yes it takes more than memory. I would go for HW serial. replacing with Mega maybe

Haha, I'm starting to know arduino bit by bit. :) Whem I'm uploading the code I always disconnect the rf module. After uploading the code I connect the rf module again. If I open the serial monitor it seems to work on 1 serial port. But I just ordered my arduino Mega because the serial communication is a big pain in the ass with the uno... :)


text:
What is the difference between a motor driver and a motor shield?
what is the difference between a motor driver(like L293D) and a motor shield?
what are the advantage?disadvantages of both?
And which one do you suggest ?

A motor driver is a chip that drives motors.  A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.
A shield is convenient since you can just plug it in to your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands.

Not sure if it's correct, but my definition of shield is: something that is pluggable on the arduino, iow has connectors and board that allow for stacking. There are a variety of boards that are not stackable and must be connected with wires, even if they contain more than just the driver.

The differrence is usablilty and, in some cases, the protection of your chip; if there is a surge of more than 5V to your driver it will fry, which is why some drivers have onboard voltage regulators and a heatsink for overheating problems. Advantage of motor driver is that you can use it as per your requirements, whereas a shield is fixed and you cannot change any aspects.

A motor driver is a chip that drives motors. A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.
A shield is convenient since you can just plug it into your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands


text:
Serial Communication with two bluetooth modules on Arduino Mega
I'm trying to communicate with two bluetooth module (RN-42) on the Arduino Mega.
I studied about Serial communication in Arduino, and I used Serial1, Serial2 to get information at the same time from the modules.
At the setup period, baud rate will be set. The command "$$$" makes the bluetooth module go into the configuration mode. Until this, everything works pretty well.
The problem is, it seems nothing works inside the loop(). I think Serial1.print(inByte), Serial2.print(inByte) doesn't work properly. I checked the TX1, TX2 port whether it sends any data or not by using LED, and the LED never blinked.
Here's the code that I used.

void setup() {
  // initialize both serial ports:
  Serial.begin(9600);

  Serial1.begin(115200);
  Serial1.print("$$$");
  delay(100);
  Serial1.println("U,9600,N");
  Serial1.begin(9600);

  delay(100);
  Serial1.print("?");

  Serial2.begin(115200);
  Serial2.print("$$$");
  delay(100);
  Serial2.println("U,9600,N");
  Serial2.begin(9600);

}

void loop() {
  // read from port 1, send to port 0:

  while(Serial1.available()>0) {
    char inByte = Serial1.read();
    Serial.print(inByte);
  }

  while(Serial2.available()>0) {
    char inByte = Serial2.read();
    Serial.print(inByte);
  }

  // read from port 0, send to port 1:
  while (Serial.available()>0) {
    char inByte = Serial.read();
    Serial1.print(inByte);

    delay(10);
    Serial2.print(inByte);
  }
}

Thank you

Maybe try a Serial1.end() before the second Serial1.begin? Arduino reference documentation gives no specific info here. How do you exit command mode?

What i dont see is the part where you are asking module 1 to act as master, module2 to act as slave. And ask module 1 to connect to module 2.

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


text:
Arduino uno RF transmitter and receiver, MYSQL
i tried to connect my arduino uno and ethernet shield with Mysql and everything works fine. Then I tried to connect the RF transmitter and receiver. I use a similar code, but i have problem with connection with database.
For the project i use:2xArduino Uno,Rf transmitter and receiver ,DHT11 and BMP080,and Ethernet shield. This is my Code:
transmitter:
#include <VirtualWire.h>
  #include "LowPower.h"
  #include "DHT.h"
  #include "Adafruit_BMP085.h"
  #include "Wire.h"

  #define DHTPIN 8     // what pin we're connected to
  #define DHTTYPE DHT11   // DHT 11
  DHT dht(DHTPIN, DHTTYPE);
  Adafruit_BMP085 bmp;
  int ledPin = 13;
  char Msg[30];// The string that we are going to send trought rf transmitter
  void setup()
  {
    Serial.begin(115200);
    dht.begin();  // initialing the DHT sensor
    bmp.begin();
    pinMode(ledPin,OUTPUT);
    // VirtualWire setup
    vw_setup(2000); // Bits per sec
    vw_set_tx_pin(12);// Set the Tx pin. Default is 12
  }
  void loop()
  {
     Serial.print("Pressure = ");
     Serial.println(bmp.readPressure());
     Serial.print("Temperature = ");
     Serial.println(bmp.readTemperature());
     Serial.print("Humidity = ");
     Serial.println(dht.readHumidity());

    // Read and store Sensor Data
    int humidity = dht.readHumidity();
    int temp = bmp.readTemperature();
    unsigned long pressure = bmp.readPressure()/100;
     Serial.print("Pressure = ");
     Serial.println(pressure );

    sprintf(Msg, "%d,%d,%d", humidity,temp ,pressure);
   // Turn on a light to show transmitting
    digitalWrite(ledPin, HIGH);
   //LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
    delay(100);
    vw_send((uint8_t *)Msg, strlen(Msg));
    vw_wait_tx(); // Wait until the whole message is gone
   // Turn off a light after transmission
    digitalWrite(ledPin, LOW);
    // put 5 mins sleep mode
    // As lowpower library support maximam 8s ,we use for loop to take longer (5mins) sleep
    // 5x60=300
    //300/4=75
    for(int i=0;i<75;i++)
    {
    LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF);    // Instead of delay(4000);
   //delay(4000);
    }
  }

reciever:
#include <SPI.h>
#include <Ethernet.h>
#include "Wire.h"
#include <VirtualWire.h> // use Virtual library for decode signal from Rx module

 EthernetClient client;
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  char server[] = "192.168.0.101";

  int humidity=0;
  int temp=0;
  unsigned long pressure=0;
  char MsgReceived[21];

  void setup()
  {
    Ethernet.begin(mac);
    Serial.begin(115200);

    // VirtualWire
    // Bits per sec
    vw_setup(2000);
    // set pin for connect receiver module
    vw_set_rx_pin(5);
    // Start the receiver PLL running
    vw_rx_start();

  }

  void loop()
  {
    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;
    //Taking the data from the control base
    if (vw_get_message(buf, &buflen))
    {

      delay(100);
      int i;
      // Message with a good checksum received, dump it.
      for (i = 0; i < buflen; i++)
      {
        // Fill Msg Char array with corresponding
        // chars from buffer.
        MsgReceived[i] = char(buf[i]);
        Serial.print(MsgReceived[i]);
      }
  connection();

    sscanf(MsgReceived, "%d,%d,%d",&humidity, &temp, &pressure); // Converts a string to an array

    memset( MsgReceived, 0, sizeof(MsgReceived));// This line is for reset the StringReceived

    Serial.print("Temperature = ");
    Serial.print(temp);
    Serial.println(" *C");

    Serial.print("Pressure = ");
    Serial.print(pressure);
    Serial.println(" hPa");

    Serial.print("humidity = ");
    Serial.print(humidity);
    Serial.println(" %");

    delay(10000);
    }
}

  void connection()
  {
    if(client.connect(server, 80)) {

      client.print( "GET /diplomna/Arduino/add_data.php?");
      client.print("temperature=");
      client.print( temp );
      client.print("&&");
      client.print("humidity=");
      client.print( humidity );
      client.print("&&");
      client.print("pressure=");
      client.println( pressure );
      client.println( "HTTP/1.1");
      client.println( "Connection: close" );
      client.stop();
      Serial.println("CONNECTED");
    }
    else {
      // you didn’t get a connection to the server:
      Serial.println("-> connection failed");
    }

  }

Output receiver:
70,23,100-> connection failed
Temperature = 23 *C
Pressure = 1001 hPa
Pahumidity = 70 %

without : #include <VirtualWire.h> and rf function I connect with the database and make a record :(

Do you really want a 10 second delay in there?

it is not necessary, but without it does not work too :)

I found where is the problem. It is function of virtualwire.h - rx_setup. It use a timer and there is  conflict with any of the libraries. Can anybody tell me how то change the timer, that is used by the function.


text:
FTDI Adjustable 3v3/5v only outputs 5v
I bought the below FTDI programmer for use with my 3v3 arduino pro mini. But even when the switch is set to 3v3 it is powering the board with 5v, (hence the IO voltage is also 5v). Note that when the pro mini is powered by batteries on the RAW input the IO voltage is 3v3 as expected. The problem is that when programming at 5v, any 3v3 peripherals (such as the BMP180) will be surely damaged.
http://www.ebay.co.uk/itm/301597777458?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
Now on the eBay description it says:

This board ship default to 5V, but you can cut the default trace and add a solder jumper if you need to switch to 3.3V

Which trace needs to be cut, and where does the jumper need to connect to/from?

The 5V/3.3V switch is fed into the "VCCIO" pin which sets the voltage of communication and nothing else.  The 5V pin of the header is connected straight through to the USB port's 5V pin.
You can either take a separate 3.3V feed from the 3V3OUT pin of the FT232RL (limited to 50mA) which is easiest to take from the 3.3V side of the switch's pins (on the underside, either or both of the two pins with no visible trace connecting to them - the lowest two in your top picture), or you can re-wire the header so it takes its voltage from the output of that switch (the middle two pins).  It looks like it would be a case of cutting the left hand portion of the long fat trace at the top edge of the back (on your top picture) then soldering a wire from the 5V pin on the header to the center pins of the switch.  That should make the output power switchable between 5V and 3.3V.


text:
Stop at the end of a track
I would like to create a camera dolly for capturing timelapse movies.
i.e. something like this:
http://youtu.be/Qce1f6SKEMU
Whats a reliable way to detect the end of the track and stop the stepper motor moving the camera? In other words how is it possible to get the current position of the camera and stop the motor before the track ends to prevent crashing into the bumpers?

Many thanks for all of your answers. I think I need to get familiar with all of the mentioned methods to finally decide what's the best for my project.

The simplest way is to have an opto-interrupter fitted at one end of the track (IR LED and IR Phototransistor), and a small bit of plastic or whatever on the dolly which interrupts the IR beam.
Printers have been doing it that way with their print heads for decades.
http://www.martyncurrey.com/connecting-an-photo-interrupter-to-an-arduino/

I find a mechanical switch the simplest and cheapest. But technically it is the same as an opto switch.  These are often refered to as limit switches.

You tie the switch to a pin with the normally closed (NC) pin, set it to pinMode(pullup), and check it each each loop. When the read value goes low (0), you stop moving your motor.

Many methods exist:
References to unpowered means the switch does not draw power when not operated. When a motor is activated it will draw power.

Mechanical switch- microswitch is the most common (as per Spiked3's suggestion). Contamination and weather may be issues (depending on how waterproof your camera is). No power needed for actual switch.
Optical (a la Majenko). Some environmental issues. Effect of ambient light needs to be considered.
Capacitive. Can be fully sealed. Need to be powered.
Magnetic - Hall (powered) and Reed (unpowered).

Whatever is used, the current and voltage ratings need to be compatible with the load. In many cases the actual switch will need a transistor or relay or similar to provide the power drive to the dolly motor. This is not hard to do but needs to be noted.

An end of track signalling method that is relatively unaffected by environmental issues is to use a magnet and magnet detector. The most common detectors are either a "Hall sensor" IC or a reed switch.
Reed switches are mechanical and more fragile than Hall sensors but need no power when unoperated and can be bought in ready made encapsulations that are robust enough to be reliable. Properly implemented a reed switch can be essentially indestructible.
Hall sensors need to be powered but power levels are small compared to eg dolly motor current and low current versions are available.
Both Hall sensors and reed switches have a degree of "hysteresis" - the point in the travel where they operate is past the point where they release again, but this is easily allowed for in practice.

Reed switch demonstration - 38 seconds video - simple and obvious.
Instructables DIY powered dolly wity reed swithes
Sparkfun magnetic door switch set and encapsulated reed switch and magnet.
Hall sensor theory of operation
Many ideas here for using hall sensors.
Reed switches


text:
reading from an array and writing into a servomotor
I have an Arduino Uno.
I am trying to write a code that reads a command and according to that command it saves angles into an array or writes the angles of the array into a servomotor.
I am facing some problems with my code such as executing the instructions of boucle FOR without ending and other strange things.
#include <Servo.h>

Servo s;
int t[6];
int n, r = 2, b = 4 ;
char c;
String ch = "" ;
int i = 0;
int nb, rep = 0;
int cmd = -1;

void setup() {
    Serial.begin(9600);
    pinMode(r, OUTPUT);
    pinMode(b, OUTPUT);
    digitalWrite(r, LOW);
    digitalWrite(b, LOW);
    s.attach(9);
    t[0] = 0;
    t[1] = 90;
    t[2] = 180 ;
}

void loop() {
    while ((cmd == 0) || (cmd == -1)) {
        cmd = lirecmd();
        delay(20);
    }

    if (cmd == 1) {
        digitalWrite(r, HIGH);
        digitalWrite(b, LOW);

        while (i < 3) {
            while (Serial.available() > 0) {
                c = Serial.read();
                ch.concat(c);
            }

            if (ch != "") {
                nb = ch.toInt();
                t[i] = nb;
                i = i + 1;
                ch = "";
            }
        }
    } else if (cmd == 2) {
        int x;
        cmd = -1;
        digitalWrite(b, HIGH);
        digitalWrite(r, LOW);

        for (i = 0; i < 3; i = i + 1) {
            Serial.print(i);
            x = t[i];
            delay(1000);
            s.write(x);
            delay(1000);
            break;
        }
    } else {
        digitalWrite(r, HIGH);
        digitalWrite(b, HIGH);
    }

    i = 0 ;
    cmd = -1;
    rep = 0;
    digitalWrite(r, LOW);
    digitalWrite(b, LOW);
    delay(50);
}

int lirecmd() {
    if (Serial.available() > 0) {
        n = Serial.read() ;
        n = n - 48 ;
    }

    return n ;
}

Please find a style guide. It will make your code easier to read.

You should rearrange your code.
Global variables, like that
int i = 0;
are not a good idea: it makes the code much harder to read and much easier to make mistakes, by using the wrong variables in the wrong places.
Also, try to break down all those nested loops, create functions with a meaningful description.
That too will help making the variables more local: pass parameters and return values.
As empirical rule of thumb, do not nest more than 1 or 2 times and keep the functions 10-15 lines long.
If you cannot do it, there is probably something wrong in your algorithm.

ok,i will try to do that,thx.


text:
Is arduino suitable for high frequency application?
Can I use the arduino for an application with a frequency of 4 MHz?
I need to create a clk with this frequency and send and receive data on the rising and falling edges. and it is not a normal SPI interface I have my own conditions so I need to do it manually.
If it is not suitable, is it technically possible?

How can we tell you whether an AVR can speak the protocol you need, if you don't tell us what that protocol is?

Most Arduinos are based on AVR chips clocked at 16 MHz. On those,
you can generate a 4 MHz clock using hardware timers. Bit-banging
data at this speed would be difficult though. It may be possible,
using unrolled loops and hand-crafted assembly... or not, depending on
the specifics of your application. Even if possible, it would be a nice
challenge for an assembly programmer.
The Arduino Due is based on an ARM chip clocked at 84 MHz. This
gives you more leeway to bit-bang at 4 MHz. But even on the Due you
would certainly need hand-crafted assembly.

No, it's not suitable due to the inherent maximum pin output frequencies in relation to the clock divider setting.
Yes, it's technically possible. Edit the divider to a value that sets the output to close to what you need. However this is annoying to do, and has serious repercussions in your code. (i.e. having to multiply every timing/bit value by 16, 8, 4, 2 or whatever you choose)
A clock of that high of a frequency would have to be some crystal to set the base time, and then a comparator circuit that could vary fast enough to push data into the edges.
You could, however, simply note the absence of the 4MHz signal as 0, and it's presence as 1, sending binary data that way it probably a lot easier than encoding it between each individual edge.


text:
Leonardo broken?
My leonardo was working fine until today, when I plug it to my computer all led (RX/TX/L/ON) stays on (Green for on, amber for others) and my computer no longer see a com port.
(by the way, do you know what the L led mean ?)
If I add external power, TX goes off then after few seconds RX goes off too then back on.
With external power, the atmega goes very hot (I can't touch it).
RESET button do nothing.
Is my Leonardo dead ? Any idea what could have cause that ? The fact that the atmega is so hot when the board is powered up with 12V let me think that the voltage regulators is no longer working. Good guess ?

By your description, I'd say:

Quite Probably.

You should check what the 5V and 3.3V voltages are using a DMM.

Confirmed, i have 12V on 5V pin when I put external power. I guess it would be safer to have something which can limit the input current on the external power supply. Any idea how I could do that ?


text:
Being able to run two functions at once
So I am doing a project where a bunch of servos are moving from 90 - 120 degrees and slowly speed up over time until they reach their max speed and so stay at that speed.
This is being done by editing the delay under the servo sweep for loop.
However though this works it doesn't work with the next component.
WHat I want to happen next is an MFRC522 RFID reader to always be scanning and at any time it detects a card and verifies it the servos from whatever speed they are now at start to slow down.
The problem is I can't get the two functions to run simultaneously. IF the servo is running its sweep function it must finish before the RFID tag can scan. This makes the whole device look very lagy.
Is there a way I can get the RFID scanner to be reading all the time even when the servo sweep for loop is working?
Here is the code:
Please note that I have put printins everywhere to see how often the RFID is scanning etc just while I test the code out.
I essentially have two functions one called nocardservo and yescardservo each one activating if there is a card there or not.
Any help would be fantastic!!
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>

#define RST_PIN     9       //
#define SS_PIN      10      //

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

Servo myservo;
int pos = 0;
int y = 15;
int z = y;
void setup() {
  myservo.attach(6);
  myservo.writeMicroseconds(1518);
  Serial.begin(9600);       // Initialize serial communications with the PC
  while (!Serial);      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();          // Init SPI bus
  mfrc522.PCD_Init();       // Init MFRC522
  //ShowReaderDetails();    // Show details of PCD - MFRC522 Card Reader details
  //Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}

void loop() {
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
nocardservo();
    return;
  }
  delay(20);
  Serial.println("carddetected");
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {

  }
  Serial.println("correctcard");
  yescardservo();
delay(20);
return;
}

//***If card not detected this function runs**//

void nocardservo() {

  for (pos = 90; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
  { // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 90; pos -= 1) // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);

  }
}
}

//***If card is detected this function runs**//

void yescardservo() {

  for (pos = 90; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
  { // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(50);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 90; pos -= 1) // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(50);

  }

}

The "secret" is in the use of the millis() function which allows you to take a snapshot of the current time and compare it to a later time . This is how JamesG referenced 'Blink Without Delay' achieves its result.Note that any copies of the value of millis()  must be stored in an "unsigned long" variable and use of eg "long" as in the previousMillis() save in the 'Blink Without Delay' example will cause errors in some cases.

What you want to implement is described in Blink Without Delay.  Basically, instead of using the delay function to just wait until your time has elapsed, you use variables to measure how much time has elapsed and only execute your operation when it has.  In the mean time, you can check on other things and do those in the mean time.

Good reference. Comment only: Note that any copies of the value of millis()  must be stored in an "unsigned long" variable and use of eg "long" as in the previousMillis() save in the 'Blink Without Delay' example will cause errors in some cases.

have a look my example program below for you reference.
/*
 * Author BALASAIDULU.N
 * function -1 : Fading led with pwm pin 9
 * fucntion -2 : Blinking LED on pin 13
 * connect an LED on pin 9 with a 330 ohms resistor
 */
     int leda=9;
     int ledd=13;
int i,g,s1,s2;
int switchPin=8;

void setup() {
pinMode(ledd,OUTPUT);
pinMode(switchPin,INPUT);
}

void fading()
{
  st:
  if(s1==0){
if(s1==1){goto hy;}
analogWrite(leda,i);
delay(30);
i+=5;
if(i>255){s1=1;}
goto st1;
  }
hy:

if(i<0){s1=0;goto st;}
i-=5;
analogWrite(leda,i);
delay(30);
 st1:
delay(10);
}

void blinking()
{
digitalWrite(ledd,HIGH);
delay(30);
digitalWrite(ledd,LOW);
delay(30);

}
void loop() {

int g;
g=digitalRead(switchPin);
if(g==1) {delay(50);}
if(g==0){
blinking();
fading();}
}

What is wrong with using goto: https://stackoverflow.com/questions/3517726/what-is-wrong-with-using-goto


text:
Motorcycle Battery Powering Arduino UNO

Folks
I am planning to power my Arduino, which will be mounted on a motorcycle, using the motorcycle's battery. So the same battery will be starting the engine and powering other electrical components.
I am wondering if this circuit will work fine.
C1 - 1000uF 50V;
C2 - 1000uF 25V;
D1 - 1N4001 ;

Your circuit is 'going in the right direction' but can be improved.
If you wish to use the regulator shown:

The larger the input capacitor (C1) the better; it will survive noise spikes and low voltage "droops", eg during starting.

Adding a series resistor to drop some of the input voltage will help C1 filter out noise.
Rin should be V/I = V_drop_max/I_maximum .
With a 9V regulator and 12V supply you cannot afford much drop in the resistor.
If you use the 6V output system I recommend below then you could allow closer to 3V drop in Rin.
If Imax is 100mA then Rin = V/I = 3/0.1 = 30 Ohms.
Typically you'd use 27 Ohms (which is the closest E12 standard value.

Power dissipation is the resistor = I^2 x R.
So for eg 27 Ohms and 0.1 A (100 mA) power dissipation in the resistor is
I^2 x R = 0.1^2 x 27 = 0.27 Watt
So you'd use at least a 0.5 Watt resistor and ideally  Watt or more. Air cooled resistors are relatively low cost and a much better way of dealing with heat than trying to cool a regulator.

Adding a ~15V zener diode at the input to U1 will help protect against spikes. This works better if Rin is used. Without Rin the zener may be destroyed by spikes. If you use the LM29xx regulators that I mention below the zener is not needed as the regulator has its own internal protection circuitry.

The LM7809 regulator is somewhat unusual. If you have them available they could be used but there are much more common and/or modern regulators available.
The regulator's Vout should be fed to the Arduino's Vin terminal, which supplies the Arduino's internal regulator, to provide 5V or 3V3 depending on which Arduino you are using. With a 5V Arduino, using Vin of 6V or more will be adequate. Higher Vin causes more heat in the Arduino on board regulator. (As Chaaarlie2 noted, 6V on Vin may be a bit on the low side for heavy loads on the Arduino 5V supply - as may happen if shields use the 5V supply. Increasing Vin to say 6.5V should allow the Arduino's internal regulator to supply its maximum rated current if desired.
9V output is higher than the Arduino needs. It is an acceptable voltage but 6V to 7V will cause less heat on-board the Arduino (and more in the external regulator).
Vehicle power systems can have extremely high voltage spikes present and sudden changes in supply voltage. Some regulators are made to work well in the automotive environment. One such family are the LM29xx series of regulators.
One superb version of this regulator is the LM2931-N [Data sheet here] - this is available in a range of versions but the simplest is the 3 lead type in a range of packages. The TO220 package is recommended due to its good power dissipation capability and ease of heatsinking if necessary. This data sheet covers versions with about 100 mA output rating, but higher output examples are available. Fixed 3.3V and 5V output versions are available but in this application the variable output version, set to about 6V or maybe 6.5V is "safest". These are very similar to the common LM317 in operation. The basic regulator produces 1.26V output and 2 resistors are used to set the desired output voltage. The advantages over the LM317 are the lower dropout voltage and the protection against typical automotive input problems.
The datasheet description states:

Designed originally for automotive applications, the LM2931-N and all regulated circuitry are protected from reverse battery installations or 2 battery jumps.
During line transients, such as a load dump (60V) when the input voltage to the regulator can momentarily exceed the specified maximum operating voltage, the regulator will automatically shut down to protect both internal circuits and the load.
The LM2931-N cannot be harmed by temporary mirror-image insertion. Familiar regulator features such as short circuit and thermal overload protection are also provided.

6V isn't quite good enough for Vin, especially when the OP has the means to provide more. Despite the Arduino website saying 6V is suitable - although not recommended - looking at the datasheet for the 5V regulator (on the genuine board) the dropout voltage at 100mA load is up to 1.1V; I wouldn't be comfortable so close to this limit. On clone boards the dropout could be even higher. Therefore, why not just provide 5V to the 5V input? The inclusion of the Vin and power jack is for convenience, not necessity! This will help minimise wasted power, as the voltage is only regulated once.

@chaaarlie2 You may be right about the std regulator. I've had no problem with clones at 6V. If you use the Arduino to supply an unknown external load you could (of course) have problems. The reason for suggesting using the internal regulator is several fold. It adds another layer of protection against the nasty automotive (or motorbikeomotive) environment. If things go wrong at the input the Arduino may not die with 12V++ on Vin. With 12V++ on the 5V pin you usually don't even see the magic smoke. I've been blowing things up for somewhat over 50 years and have become averse to giving ....

@chaaarlie2 ... Murphy more chances than possible. Adding another 0.5V to Vin is easy if an LM2931 is used. Low Vin keeps dissipation down on the Arduino board. |Power wasted is the ame whatever the regulator arrangement. You use 5V x Iin and you dissipate (V12in - 5V) x Iin somewhere or other. Dissipating as much of it as possible in the resistor I mentioned is often a very good idea.

@chaaarlie2 Added comment on using 6.5V for heavier loads with hat tip to you.

My batch of Uno clones all shut down at ~6.8V - looks like I've been mugged off! As you've championed the LM2391 so heavily, why now doubt its ability to provide a safe 5V without frying the Arduino even "if things go wrong" ? Of course I see the benefit of belt and braces, which is why I'd use a zener and quick-blow fuse as a backup. Ultimately it's going to depend on the OP's situation, so it's relatively moot. As I side note (from experience of the very same), cooling a regulator on motorbike isn't difficult - attach the simplest of heatsinks and hang it somewhere windy!

@chaaarlie2 I trust the LM2931 well enough when fed and watered as per growing guide - but reality often does not match desire, as I know you know. || You have an imnteresting profile page - closer to mine than many. ME both. I had C4-C5 spinal fusion Jan15 and MAY need another foray early 2016 but will resist if all all possible. Results very good but indications that spinal cord is still being impacted in a way that may cause progressive issues. Gaabapentin helped less for me than I'd expected. | Diclofenac worked utter miracles for me pre-opn. Do try if you have not done so.  ...

@chaaarlie2 ... it has risks and also progressively degrades renal function :-( so gains need to be balanced against issues. I do not now use it regularly except as 1 off prophylactic for 'big days out' - eg with 2 heavy cameras flash etc when it helps muchly. ('EE is day job'  - Photography an obsession  my wife says ) (Balboa (unarmoured version) was foreign to me - I'd take photos :-)  )

@chaaarlie2 Re UNO clones and Vin min. I have had very good results from Baite electronics via AliExpress. I have a UNO and a Spark Core at the same Vin=6V  talking to it . Both are happy. | I just did a test. Clone UNO:  5V output drops out of regulation at around 5.9 -  5.95V on Vin with Uno only on Vin. | Added first 60mA and then 120 mA loads to 5V out pin (82 Ohm resistor then 2 in parallel). Dropout voltage rose maybe 0.05V to say 5.95V - 6V on Vin for load of UNO + 120 mA on 5V out pin. | Once they use other than original regulator they can use anything. Looks like Baite chose well.


text:
Arduino stops working after some receivings from RF
I made a sketch that receives an rgb code from a remote Arduino using nrf24l01 and while it works for the first receivings then it stops working. I placed a testing Serial.println in the loop to test if Arduino stops to work completely or it doesn't receive any other data. Finally, I understood that it continues to work but it doesnt receive more data. Bellow is my code:

#include <RF24Network.h>
#include <RF24Network_config.h>
#include <Sync.h>

#include  <TimerOne.h>
#include <SPI.h>
//#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(8,10);
RF24Network network(radio);
volatile int i=0;
volatile int d=0;     // Variable to use as a counter
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin= 4;    // Output to Opto Triac pin
int dim = 0;  // Dimming level (0-128)  0 = ON, 128 = OFF
int freqStep = 65;

struct payload_rgb
{
  unsigned int red;
  unsigned int green;
  unsigned int blue;
};
struct payload_lightuv
{
  unsigned int light;
  unsigned int uv;
};
RF24NetworkHeader header;
payload_rgb payloadrgb;
payload_lightuv payloadl;
void setup() {
  // put your setup code here, to run once:
  pinMode(AC_pin, OUTPUT);// Set AC Load pin as output
  pinMode(9, OUTPUT);// Set AC Load pin as output
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  attachInterrupt(0, zero_cross_detect, RISING);  // Choose the zero cross interrupt # from the table above
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);
  Serial.begin(115200);
  radio.begin();
  network.begin(90,01);
}

void loop() {
  network.update();
  while ( network.available() )
  {
    Serial.println("Rec");

    network.peek(header);
    if(header.type=='r'){
      network.read(header,&payloadrgb,sizeof(payloadrgb));
      analogWrite(6,payloadrgb.red);
      analogWrite(9,payloadrgb.green);
      analogWrite(5,payloadrgb.blue);
    }
    if(header.type=='l'){
      network.read(header,&payloadl,sizeof(payloadl));
      dim=payloadl.light;
    }
}
Serial.println("!"); //this is the test println
}
void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(AC_pin, LOW);       // turn off TRIAC (and AC)
}
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim) {
      digitalWrite(AC_pin, HIGH); // turn on light
      i=0;  // reset time step counter
      zero_cross = false; //reset zero cross detection
    }
    else {
      i++; // increment time step counter
    }
  }
}}

Additionally, this Arduino controls an ac dimmer. Bu I have not done it yet.
How can I fix the problem without removing any feature?

Is it maybe running out of memory? I am not familiar with network.read but does this memory get free'd ?

Why network.read should use memory? The only thing that uses memory are the variables and structures. And even if it used, shouldn't the arduino stop completely?

I think it would have to buffer that input and if it is allocating memory each time and not cleaning up, maybe its running out. But this is just a guess. ..."If you run out of SRAM, your program may fail in unexpected ways; it will appear to upload successfully, but not run, or run strangely"...http://www.arduino.cc/en/Tutorial/Memory

So that would be library's problem?

It's not likely, I thought there was something that you needed to call to free it but it doesn't seem to be the case. Don't you need to declare the variables that are modified in the interrupts as volatile?

Will that solve the problem?

Try reducing memory footprint, see if that helps.

Try resetting the nrfs with the below answer: https://arduino.stackexchange.com/a/54604/35167

See this. https://arduino.stackexchange.com/questions/55042/how-to-automatically-reset-the-nrf24l01-with-code