text:
Running Arduino code for Bluefruit LE on bare ATMega328
I need to hook up Bluefruit LE Breakout (nRF8001-based) to ATMega328 chip (to use it as wireless UART), and it seems like the library provided is for Arduino.
What I have is just bare ATMega328 (note the lack of "p"), which I am going to program (using avrispmkii directly). As I already have the MCU assembled, I do not want to change to, say, Arduino Uno to be able to use the library. Most likely, I will "play" with the Bluefruit on Arduino first to get the feel of it, but the code needs to be run on the "bare" ATMega328. The other part of the program (which prepare data to be sent from atmega) is trivial, so I will have no problem to rewrite it from C to Arduino. Porting Adafruit library from C++ to C is probably much more difficult.
Thus, one of the possible approaches is to compile the my code + Bluefruit LE code for Arduino, but upload to the ATMega328.
And this is where I need help:
How to make Arduino (command line tool is ok) to compile to the MCU I have? I guess, the result should be some kind of hex-file for flash (and eeprom?).
And, may be useful, which flags to use with avrdude, if there is anything specific for the Arduino-generated code. (I do not need any bootloaders on the chip, just the program, and I do not have UART-USB connected to atmega).
Of course, please, mention if there are better ways I overlooked, like some Arduino-compatible gcc toolchain to compile C++/C mix into avr code (avr-g++?). Or maybe there is some C-library for the component atmega needs to talk to.
UPDATE: Similar question: http://www.avrfreaks.net/forum/using-arduino-ide-general-atmel-microcontroller-no-bootloader-no-cristal

The UNO is basically just an ATMega328(P). So you can run the same compiled code for the UNO just fine on a bare ATMega328.
You don't have to worry about the P versus non-P version. They are basically the same except for some minor differences concerning low power settings.
You can just select the Arduino UNO board as you target. Select the avrispmkii as programmer. Then instead of Upload, choose Upload using Programmer (in the Sketch menu).

It is that simple then, thanks. I will check this as soon as I figure out how to adjust F_CPU and fuses in Arduino (I am using 8MHz internal clock) and decide what to do with RST pin for the BLE module.

Just download my boards definition. Just extract and place inside the hardware folder in the Arduino sketches folder (create if not yet present). The 328 @ 8mhz board should be added to the Tools->Boards menu after restarting the IDE.

The one place you will have to worry about the 328 vs 328P is in the programmer configuration - while the file will usually work between chips, the program will refuse to load it into a different one than it is expecting.

Just to confirm: I made my "board" definition (MCU, fuses, frequency), And "Upload using Programmer" definitely works: I was able to use BLE "UART"! As for refusing to load, yes, there was one warning, when I had intermediate configuration (forgot to change mcu from atmega328p to atmega328). I have not tried to change frequencies (and bootloader) on the Uno though, so switched to "bare" chip as soon as uart was understood.

A, right. In my boards from above, edit boards.txt and change atmega328-8mhz.build.mcu=atmega328p to atmega328-8mhz.build.mcu=atmega328.


text:
println() changes values of variables
I have a function which returns a float value.
I want to see what value is returned so I print it just before the return statement.
Surprisingly, the value is 0 (it shouldn't be 0).
When I want to debug the function and print more things, the value is correct. I do not change anything, I just add a couple of printl().
Let's say:

float func() {
  float a = some math calculation;

  some easy math
  Serial.println(a);
  some easy math
  Serial.println(a);

  Serial.println(a);
  return a;
}

If I comment out println() lines, I get 0, which is a wrong value.
If the lines stay uncommented, I get a correct value.
Does anyone have idea why?
I use Arduino Due.

Perhaps if you showed us the actual code we might be able to help you...

Please post a  Minimal, Complete, and Verifiable example and not a snippet. Perhaps you are dividing by zero? That's "easy math" to do. :)

Thank you Nick :)
I used millis() to calculate time and then I divided by the time step. After I changed to micros() everything is as it should be. I think serial printing added necessary time to make the time step not null.

Can you still post the minimal complete verifiable examples so that others can benefit from your question? They will benefit in two ways 1) an example of why prints can make a difference - especially where timing is important and 2) why it is important to post a complete example to enable when asking a question (a big problem on this site).

I would suggest adding the "complete example" as a second code block prefixed by "edit - complete code block". Or, simply answer your own question and put the "complete code" in your answer.

source: Stack Exchange

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

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

sort: votes


text:
Serial does not work when LiquidCrystal library is used
I have been struggling with a LCD for 6 hours straight - I've had many problems including random characters showing up, and this time (not quite sure what changed, I tried so many things) as soon as I instantiate a LiquidCrystal object the Arduino stops sending on the Serial port. On the following code, commenting the instantiation of lcd makes "Starting" and "Printing" appear in the serial terminal - otherwise nothing is displayed. Either way, the LCD is desperately blank (black spaces on the entire first line, and I tuned the contrast when random characters were displayed).

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
//RS EN D4 D5 D6 D7
//LiquidCrystal lcd(2, 3, 4, 5, 9, A5);
//RW to GND, VSS to GND, VCC to 5V, V0 to wiper of 5V-to-GND 10k potentiometer

void setup() {
  Serial.begin(9600);
  Serial.println("Starting");
  //lcd.begin(16, 2);
}

void loop() {
  //lcd.setCursor(0, 1);
  //lcd.print(millis() / 1000);
  Serial.println("Printing");
}

I'm using this Arduino Pro Mini, and this LCD. Note that on the Arduino, pins 10 11 12 and 13 are used for a SD (which works), and 6 7 8 are used for a RS232 driver (which is disabled).
Honestly I'm sending a message in a bottle, I'm out of ideas...
The wiring is as explained in the code, I checked it 5 times and it is matching. There is a 10k pot on GND-VO-5V of the LCD, and I haven't wired the backlight.
Edit1: With the LCD active (all lines uncommented) I probed all LCD pins with a 'scope and when it is triggered in Normal, I can see that they all have a pulse every time the LCD is updated (I added a delay in the loop to make it more obvious). HOWEVER pins 9 and A5 take much longer than the others to get back to a high state, around 3 microseconds. Why? It might explain why the LCD doesn't work, but I don't see how it can explain the apparent freeze.
Edit2: Okay, I desoldered pins 9 and A5 and placed the wires on pins A2 A3 instead. The square waves are all square now, and the Serial works - no idea why. And back to square 1, as the LCD prints random characters now...

Do you get the same behavior when the SD and RS232 hardware is detached from the Pro Mini?  Also, if you change lcd.print(millis() / 1000) to lcd.print(millis() & 1024 ? "ABCDEFGH" : "IJKLMNOP"); delay(1024); what does it display?

Jwpat7 that line was the issue for the garbage characters that I ended up having after solving this particular issue, well done. For this specific issue, apparently pins 9 and A5 weren't fast enough, no idea why.

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


text:
PWM supplying led breaks down at near to zero threshold
I use timer1, mode 8, on both pin 9 and 10 at 1 kHz my PWM signal breaks down when I turn the potentiometer just above where I set the zero at, no matter where I set the zero at.  I power the Arduino atmega328p with Vin and disconnect from the PC.  I have potentiometer to A0 and pin out 9 or 10 connected to the oscilloscope.  I have code and picture below.
The problem with my code is that I can't get TCNT1 or TCNT2 to start where I set it anywhere else but zero.
#include <avr/io.h>
#include <avr/interrupt.h>
//#include <SPI.h>
//ISR(TIM1_COMPA);
//ISR(TIM1_CAPT);

int analogInPin = PC0;
int analogOutPin9 = PB1;
int analogOutPin10 = PB2;
int analogOutPin3 = PD3;
int analogOutPin11 = PB3;
//int analogInPin = A0;
//int analogOutPin9 = 9;
//int analogOutPin10 = 10;

int sensorValueTimer1;
int sensorValueTimer2;

void sens(int &sensorValueTimer1, int &sensorValueTimer2){
   sensorValueTimer1 = (((long)analogRead(analogInPin)*1000)/1023);
   if (sensorValueTimer1 < 35){  //to stop flickering at low end
     sensorValueTimer1 = 0;
     }
        sensorValueTimer2 = (((long)analogRead(analogInPin)*255)/1023);
   if (sensorValueTimer2 < 0){  //to stop flickering at low end
     sensorValueTimer2 = 0;
     }
}

void updateOCRnx(){
  sens(sensorValueTimer1,sensorValueTimer2);
  int x = sensorValueTimer1;
  int y = sensorValueTimer2;
  OCR1A = x;
  OCR1B = x;
  OCR2A = y;
  OCR2B = y;
}

void setup() {
  Serial.begin(9600);
  //===============mode 5 pin 3,11==================//
  /*
  //TCCR2A = 0;
  //TCCR2B = 0;
  TCCR2A |= (1<<COM2A1);
  TCCR2A |= (1<<COM2A0);
  TCCR2A |= (1<<COM2B1);
  TCCR2A |= (1<<COM2B0);
  TCCR2A |= (1<<WGM21);
  TCCR2A |= (1<<WGM20);
  TCCR2B &= ~(1<<WGM22);
  TCCR2B &= ~(1<<CS22);
  TCCR2B |= (1<<CS21);
  TCCR2B |= (1<<CS20);

  //TIMSK2 |= (1<<OCIE2A);
  //TIMSK2 |= (1<<OCIE2B);
  //TIMSK2 |= (1<<TOIE2);
  //ASSR &= ~(1<<TCN2UB);
  //TIFR2 |= (1<<OCF2A);
  //TIFR2 |= (1<<TOV2);

  TCNT2 = 100;
 */
  //====================mode 5 pin 3,11=====================//
  //=====================mode 8 pin 9,10=====================//
  //TCCR1A = 0;

  TCCR1A |= (1<<COM1A1);
  TCCR1A &= ~(1<<COM1A0);
  TCCR1A |= (1<<COM1B1);
  TCCR1A &= ~(1<<COM1B0);
  TCCR1A &= ~(1<<WGM11);
  TCCR1A &= ~(1<<WGM10);
  TCCR1B |= (1<<WGM13);
  TCCR1B &= ~(1<<WGM12);
  TCCR1B |= (1<<CS11);
  TCCR1B &= ~(1<<CS12);
  TCCR1B &= ~(1<<CS10);

  //TCCR1B |= (1<<ICES1);

  //TCCR1C |= (FOC1A);
  //TCCR1C |= (FOC1B);

  ICR1=1000;  //1.333KH
  TCNT1=0;

  //TIMSK1 |= (1<<TOIE1);
  //TIMSK1 |= (1<<OCIE1A);
  //TIMSK1 |= (1<<OCIE1B);
  //TIMSK1 |= (1<<ICIE1);
  //TIFR1 |= (1<<TOV1);
  //TIFR1 |= (1<<OCF1A);
  //TIFR1 |= (1<<OCF1B);

  //EIMSK |= (1<<INT1);
  //EIFR |= (1<<INTF1);
  //EICRA &= ~(1<<ISC11);
  //EICRA &= ~(1<<ISC10);

  //PCMSK0 |= (1<<PCINT2);
  //PCICR |= (1<<PCIE0); //pin change interrupt 0 is enabled
  //PCIFR |= (1<<PCIF1); // triggers an interrupt request
  //=======================mode 8 pin 9,10=======================//

  sei();

  //pinMode(analogOutPin9,OUTPUT);
  //pinMode(10, INPUT);
  //pinMode(analogInPin, INPUT);

  //char data;

  DDRB |= (1<<analogInPin);
  DDRB |= (1<<analogOutPin9);
  DDRB |= (1<<analogOutPin10);
  DDRB |= (1<<analogOutPin11);
  DDRB |= (1<<analogOutPin3);
  //DDRB |= (1<<PB5);
  //DDRB &= ~(1<<PB4);

  //SPSR |= (1<<SPIF);

  //SPCR |= (1<<SPE);
  //SPCR |= (1<<MSTR);
  //SPSR &= ~(SPR1);
  //SPCR |= (1<<SPR0);
  //SPSR |= (1<<SPI2X);

  //SPDR = data;

}

void loop() {
  updateOCRnx();
  Serial.println(TCNT1);
  //delay(100);
  //int sensorValue = (((long)analogRead(analogInPin)*1000)/1023);
  //int sensorValue = analogRead(analogInPin);
  //analogWrite(analogOutPin9, sensorValue/4);
  //analogWrite(analogOutPin10, sensorValue/4);
  //Serial.println(analogOutPin9);
}

What is your oscilloscope Trigger Mode set to? Auto or Normal?

The trigger mode was set to auto, I set it to normal, I still see the square wave expand out a little bit for about  1/10 a second and repeats every half a second.  I see the same thing on the light fixture with CREE XPE2 LED.  It flickers about the same as the oscilloscope flickers when I have my MCIGICM 10K Ohm potentiometer at very near to where I set zero at.  My corals and my eyes are thank full for a direction.

The analogread pin is unstable. This fixed it,ResponsiveAnalogRead, from github

That's a vague explanation and IMHO not evident


text:
Fujitsu FMC-16LX(MB90F387) Pulse Sensor BPM formula displaying only 96BPM
#include "_ffmc16.h"
#include "extern.h"
#include "monitor.h"

void initLCD();
void delay();
void instCtrl4(unsigned char data);
void display(unsigned char temp);
void display1(unsigned char pulse, int counter);
void decoder(int newtemp);
void instCtrl(unsigned char data);
void dataCtrl(char data);

#define RS IO_PDR2.bit.P24
#define RW IO_PDR5.bit.P53
#define E IO_PDR5.bit.P52
#define LCD IO_PDR2.byte
#define BUZZER IO_PPGC23.bit.PEN1

unsigned char AD_DATA, temperature, bpm;
int count = 0, counter=0;
int UpperThreshold = 518;
int LowerThreshold = 490;
int IgnoreReading = 0;
int FirstPulseDetected = 0;
    unsigned char FirstPulseTime = 0;
    unsigned char SecondPulseTime = 0;
    unsigned char PulseInterval = 0;
    unsigned char BPMResult;

void main()
{
    __set_il(7);
    __EI();

    IO_DDR2.byte = 0x1F;
    IO_DDR5.bit.D53 = 1;
    IO_DDR5.bit.D52 = 1;

    IO_ADER.bit.ADE3 = 0;
    IO_ADER.bit.ADE2 = 0;

    //BUZZER
    IO_PPGC23.bit.PE1=0x01;
    IO_PPG23.byte=0x00;
    IO_PRL23.byte.PRLL3=0xFA;
    IO_PRL23.byte.PRLH3=0xFA;

    initLCD();
    instCtrl(0x84);
    dataCtrl('T');
    dataCtrl('E');
    dataCtrl('M');
    dataCtrl('P');
    dataCtrl('E');
    dataCtrl('R');
    dataCtrl('A');
    dataCtrl('T');
    dataCtrl('U');
    dataCtrl('R');
    dataCtrl('E');
    dataCtrl(':');

    instCtrl(0x99);
    dataCtrl('P');
    dataCtrl('U');
    dataCtrl('L');
    dataCtrl('S');
    dataCtrl('E');
    dataCtrl('R');
    dataCtrl('A');
    dataCtrl('T');
    dataCtrl('E');
    dataCtrl(':');

    while(1)
    {
    counter++;

    IO_DDR5.bit.D55 = 0;    /* PORT5 DDR set(AD1) */
    IO_ICR03.byte = 0x00;   /* A/D INT level set */
    IO_ADCSH.bit.BUSY = 0;  /* ADC stop */
    IO_ADER.byte = 0x02;    /* ADC input enable, ch-1 */
    IO_ADCSL.byte = 0xAD;   /* ADC mode set */
    IO_ADCRLH.byte.ADCRH = 0xF8;    /* set 8bit-AD, comp.176cycle, sample.128cycle */
    IO_ADCSH.bit.INTE = 1;  /* interrupt enable */
    IO_ADCSH.bit.STRT = 1;  /* start ADC */

        display(AD_DATA);

        /*if(temperature>38)
        {
            BUZZER=0x01;
        }
        else if(temperature<34)
        {
            BUZZER=0x01;
        }
        else
        {
            BUZZER=0x00;
        }*/

    IO_DDR5.bit.D54 = 0;    /* PORT5 DDR set(AD1) */
    IO_ICR03.byte = 0x06;   /* A/D INT level set */
    IO_ADCSH.bit.BUSY = 0;  /* ADC stop */
    IO_ADER.byte = 0x10;    /* ADC input enable, ch-1 */
    IO_ADCSL.byte = 0xA4;   /* ADC mode set */
    IO_ADCRLH.byte.ADCRH = 0xF8;    /* set 8bit-AD, comp.176cycle, sample.128cycle */
    IO_ADCSH.bit.INTE = 1;  /* interrupt enable */
    IO_ADCSH.bit.STRT = 1;  /* start ADC */
        display1(AD_DATA, counter);
    }
}

void delay()
{
    for(count=0; count<1000;count++)
    {
    }
}

void initLCD()
{
    delay();
    instCtrl4(0x03);
    delay();
    instCtrl4(0x03);
    delay();
    instCtrl4(0x03);
    delay();
    instCtrl4(0x02);
    delay();
    instCtrl(0x28);
    instCtrl(0x08); //off
    instCtrl(0x01); //clear
    instCtrl(0x06); //entry mode: increment or shift mode
    instCtrl(0x0C); //display on; cursor on;blink on
    instCtrl(0x01);
}

void instCtrl4(unsigned char data)
{
    LCD = data;
    RS = 0;
    RW = 0;
    E =1;
    delay();
    E =0;
}

void display(unsigned char temp)
{
    temperature = (temp * 500) / 255;
    instCtrl(0xC8);
    decoder((temperature/10)%10);
    decoder(temperature%10);
    dataCtrl(0xDF);
    dataCtrl('C');
}

void display1(unsigned char pulse, int counter)
{

    /*if(pulse > UpperThreshold && IgnoreReading == 0)
    {
        if(FirstPulseDetected == 0)
        {
          FirstPulseTime = counter;
          FirstPulseDetected = 1;
        }
        else
        {
          SecondPulseTime = counter;
          PulseInterval = SecondPulseTime - FirstPulseTime;
          FirstPulseTime = SecondPulseTime;
        }
        IgnoreReading = 1;
      }

      // Heart beat trailing edge detected.
      if(pulse < LowerThreshold)
      {
        IgnoreReading = 0;
      }

      BPMResult = (1 / PulseInterval) * (60000);*/

      //bpm= pulse; /* default n ??*/

    instCtrl(0xD9);
    decoder((BPMResult/100)%10);
    decoder((BPMResult/10)%10);
    decoder(BPMResult%10);
    dataCtrl('B');
    dataCtrl('P');
    dataCtrl('M');
}

void decoder(int newtemp)
{
    switch(newtemp)
    {
        case 0:
            dataCtrl('0');
            break;
        case 1:
            dataCtrl('1');
            break;
        case 2:
            dataCtrl('2');
            break;
        case 3:
            dataCtrl('3');
            break;
        case 4:
            dataCtrl('4');
            break;
        case 5:
            dataCtrl('5');
            break;
        case 6:
            dataCtrl('6');
            break;
        case 7:
            dataCtrl('7');
            break;
        case 8:
            dataCtrl('8');
            break;
        case 9:
            dataCtrl('9');
            break;
    }
}

void instCtrl(unsigned char data)
{
    LCD=data>>4;
    RS =0;
    RW=0;
    E=1;
    delay();
    E=0;
    LCD=data;
    RS=0;
    E=1;
    delay();
    E=0;
}

void dataCtrl(char data)
{
    LCD=data>>4;
    RS=1;
    RW=0;
    E=1;
    delay();
    E=0;
    LCD=data;
    RS=1;
    E=1;
    delay();
    E=0;
}

__interrupt void ADC_int(void)
{
    IO_ADCSH.bit.INT = 0;       //interrupt flag clear
    AD_DATA = IO_ADCRLH.DATA8;  //A/D conversion interrupt vector
}

/* Vector Table */
#pragma section INTVECT, locate=0xfffc00
#pragma intvect _start      0x8     0x0 /* Reset Vector */
#pragma intvect ADC_int     18      /* AD converter vector */

what is your question?

Agreed, if you don't actually ask anything, then what replies do you expect to receive?

Can you check my code.. because my Pulse Sensor Formula is only displaying 96BPM

@jsotola Do you have a formula for pulse sensor?

what pulse sensor?  .... a quick google search reveals that the MB90F387 is a fujitsu microcontroller and FMC-16LX is a cable that is used to program the MB90F387 ..... the whole thing is not even related to an Arduino .... either way, as far as i can tell, you have provided no information about the sensor

@jsotola I am using this sensor https://www.google.com/search?q=pulse+rate+sensor&rlz=1C1CHBF_enPH810PH810&source=lnms&tbm=isch&sa=X&ved=0ahUKEwixxYWv1uLfAhUMdt4KHb3aApIQ_AUIDigB&biw=1437&bih=652#imgrc=Vm-dILTaaC0WuM: I already displayed the values but I can't get the exact BPM because of my formula.. yes I know its not related to arduino but they are both microcontroller


text:
USB upload to Pro Micro (32u4)
My project is based around the ATMEGA32u4 microcontroller.
I followed the Arduino Pro Micro schematic to design my own board layout and build a custom PCB, soldered on the components.  Then I used the Arduino IDE to successfully upload the Arduino bootloader with SPI.
Currently I can also upload programs to my `32u4 over SPI (using "in-serial programming").  Tested that with Blink.
But I cannot upload programs with the USB, like you would normally be able to do with a Pro Micro.  What things should I look for to debug this?
avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Users\Myname\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

     Using Port                    : COM12
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

When you program the blink sketch using ISP, you overwrite the bootloader!!! Did you set the correct fuses? How did you program the bootloader?

Oh, I did not know that.  I used an Arduino UNO as a SPI master to upload the bootloader to my 32u4.  After that I uploaded a blink sketch the same way.  I will try uploading the bootloader again and then the sketch via USB.

Yes, that worked.  Thanks, would have taken me a long time to work that out.  I will post a reply.

It’s one of those gotchas. Glad you got it working now.

The answer, as kindly pointed out by Gerben, is that ISP program upload overwrites the bootloader.
Only upload the bootloader via ISP, then switch to USB for uploading Arduino sketches.


text:
Uniform timing when using Arduino for data acquisition
I am using Arduino UNO together with a SPI ADC (LTC1859) and SRAM (23CL1024) to record a series of data points at approx 2 kHz sampling rate (let's say a few thousand data points).
I have some questions about how to ensure the data points are sampled at uniform time intervals, down to the precision of a clock cycle.
What are the limitations of Arduino macros in respect to this?  Can I replace SPI.transfer() with some lower-level code that will make an improvement?
Even if my code is precise, is the relatively low CPU speed of 16 MHz something to worry about for data sampling rates up to a few kHz?
The time-critical part of my code is as follows, and I'd appreciate suggestions:
**RE-EDIT.  As has been requested, the ADC is LTC1859 and triggers on the slave select falling edge active high of input on the CONVST pin, which is the same time that I make ADC SS low (first line inside the for loop).
Digital outputs:
CONVST  = Port B, bit 2
SS ADC  = Port B, bit 1
SS SRAM = Port B, bit 0
      for(unsigned int i=0;i<DATA_LENGTH;i++){
        PORTB=B11000101;                     // ADC Slave select
        __builtin_avr_delay_cycles(112);     // ADC conversion time
        DATA_MSB=SPI.transfer(ADCbyte1);     // Get 16-bit ADC value as 2 bytes
        DATA_LSB=SPI.transfer(ADCbyte2);
        PORTB=B11000010;                     // SRAM Slave select
        SPI.transfer(WRITE);                 // Write data value to SRAM as 2 bytes
        SPI.transfer((uint8_t)(DATA_ADDRESS >> 16)&0xFF);
        SPI.transfer((uint8_t)(DATA_ADDRESS >> 8)&0xFF);
        SPI.transfer((uint8_t)(DATA_ADDRESS));
        SPI.transfer(DATA_MSB);
        SPI.transfer(DATA_LSB);
        PORTB=B11000011;                     // Deselect both ADC and SRAM slaves
        DATA_ADDRESS++;
        DATA_ADDRESS++;
        __builtin_avr_delay_cycles(7600);    // Delay makes 1/sampling rate.  7600 = 2 kHz
      }                                      // Repeat for number of data points

**EDIT.  Also, I have done some further tests and replaced occurrences of SPI.transfer(data);  with SPDR = data; followed by waiting a constant number of clock cycles to ensure the data clears.  I checked out the timing accuracy by measuring a sine wave voltage input and analyzing the FFT of the recorded data.  Overall timing accuracy was improved but I do not see evidence that this part of code limits how uniformly the data are sampled.  I have not tried Nick Gammon's suggestion yet to use timer interrupts.
Below is an example of the real-world data that I am recording.  The ADC is digitizing data at 16 bit, 2 KHz from a magnetometer with around 10-15 T/Hz1/2 sensitivity, then passing to a PC running Qt where I plot the time-domain data and frequency-domain data after FFT.
The signal is laboratory magnetic background and contains harmonics of the 50 Hz line frequency from mains cables etc.  The point of showing the data is that I am not stuck getting the data acquisition to work. I want to improve the data acquisition code as far as possible within the limits of Arduino.

SOLUTION: I modified Edgar Bonet's code in the accepted answer to use timer1 for PWM control of ADC trigger (CONVST, OC1B = Arduino pin 10).  This worked successfully.
Learning points for me were:
(1) much greater accuracy in ADC sampling rate. The resonator frequency is accurate enough for my purposes at kHz sampling that I don't need fiddly calibrations of for loop duration;
(2) much better way of programming a DAQ.  Using the state machine concept, I can run other processes in parallel with the DAQ without penalties in timing accuracy.
void loop(){

switch (statemachine){

// other cases, including reading serial data from PC

case 2: // Initialize data acquisition
cli();
data_address=0;
data_counter=0;
statemachine=3;
TCCR1A=0;
TCCR1B=0;
OCR1A=124; // 16 MHz / (64 * 125) = 2000 Hz
OCR1B=1;
TCCR1A = _BV(COM1B1)  // Clear pin OC1B on compare match, set at BOTTOM, noninverting
| _BV(WGM10)          // fast PWM mode 15, TOP = OCR1A
| _BV(WGM11) ;        // fast PWM mode 15.
TCCR1B = _BV(WGM12)   // fast PWM mode 15
| _BV(WGM13)          // fast PWM mode 15
| _BV(CS11)           // Set timer prescaler to 64.
| _BV(CS10) ;         // Set timer prescaler to 64.
TCNT1=0x03;
TIFR1 |= _BV(OCF1A); // Clear match flag
break;

case 3: // Acquire data and store.
loop_until_bit_is_set(TIFR1,OCF1A);
TIFR1 |= _BV(OCF1A);              // Clear match flag
PORTB=B11000101;                  // ADC SS
__builtin_avr_delay_cycles(160);  // 10 us
msb=SPI.transfer(ADCbyte1);
lsb=SPI.transfer(ADCbyte2);
PORTB=B11000010;                  // SRAM SS
SPI.transfer(WRITE);
SPI.transfer((uint8_t)(data_address >> 16) & 0xFF);
SPI.transfer((uint8_t)(data_address >> 8)  & 0xFF);
SPI.transfer((uint8_t)(data_address));
SPI.transfer(msb);
SPI.transfer(lsb);
PORTB=B11000011;
data_address++;
data_address++;
data_counter++;
if(data_counter==data_length){statemachine=4;} // Data capture complete
break;

// other cases, including data transfer to PC
}
}

You should consider triggering the most time-critical part of your code using a hardware timer rather than delay loops.

You think the for() loop is the most likely source of error?  I have considered hardware timing but thought that each SPI.transfer() waits for an interrupt to conclude the transaction.  If I did do hardware timing, what timer of the AVR is best to use?  Note that I care most about uniform timing and not absolute accuracy.

First thing you need to do is look at the chip data sheet and see exactly what triggers a conversion.  Is it a particular part of the SPI cycle, like a given clock or deassertion of the select?   Is there an option to use a distinct signal to trigger it after priming it with the SPI?   Or is this one of the ADCs where the a successive-approximation conversion is directly clocked by the SPI, and any jitter in the SPI clock contaminates your measurement?  If you do keep software in the critical loop, you'll want to disable the interrupt that advances the Arduino millis()

The way I am triggering the ADC should not be an issue as it is rated to 100 ksps.
My question was specifically about the Arduino code and how to improve it.  For example, if SPI.transfer() (and there are 8 of them to handle each data point acquisition) has the potential to add a few microseconds here/there.

DATA_ADDRESS++; - as a convention, don't use all capitals for variables. All capitals are usually used for constants.

Again, you need to read the data sheet and determine what actually governs the timing of the ADC.  It's not a question of speed but of which specific action (or actions) causes the ADC to take a reading.  Whatever that is, it is what you need to remove jitter from.

Please, edit the question to provide the missing information you have been asked for: what specific action triggers your ADC? We cannot provide any meaningful answer without this. If you cannot find it, then provide a link to your ADC's datasheet. In the meantime, I'm voting to close the question, and I will retract my vote if you provide the info.

Since pretty much the same code is called every cycle, the timing should be pretty uniform. Do you measure how long it takes to do a few thousand acquisitions? If you do that, you can calculate the sampling rate, and see if you can get close to 2kHz by tweaking the delay at the end __builtin_avr_delay_cycles(7600);.

Edgar Bonet: I have provided info about the ADC, which triggers on slave select falling edge.

@Gerben - measuring across a lot of samples averages the timing - that's important for things like buffer usage, but it doesn't reveal if there is jitter to the samples or the clock which may be used to measure them.

the ADC is LTC1859 and triggers on the slave select falling edge.

No, it doesn't. Here is a link to its datasheet. It has a pin
labeled CONVST, for “conversion start”. According to the section Pin
functions, “This active high signal starts a conversion on its rising
edge.”
If you want your sampling to be at 2 kHz with cycle-accurate
timings, you have to send to this pin a train of pulses which are at
least 40 ns wide and have a period of 500 µs, i.e.
8,000 CPU cycles. This can be done with any of the three timers of
the Uno. For example, you can set Timer 2 to repeatedly count from
0 to 124 with a prescaler of 64. Your initialization would have
something like this:
// Initial transfer to configure the ADC.
PORTB &= ~_BV(SS_ADC);
SPI.transfer(ADCbyte1);
SPI.transfer(ADCbyte2);
PORTB |= _BV(SS_ADC);

// Configure Timer 2 for PWM on pin OC2B = PD3 = digital 3.
DDRD  |= _BV(PD3);    // pin PD3 as output
TCCR2A = 0;           // undo the Arduino core's configuration
TCCR2B = 0;           // ditto
OCR2A  = 125 - 1;     // period = 64 * 125 CPU cycles = 500 us
OCR2B  =   2 - 1;     // high for 64 *   2 CPU cycles =   8 us
TCNT2  = 122;         // first pulse in 8 to 12 us
TIFR2 |= _BV(OCF2B);  // clear the output compare flag
TCCR2A = _BV(COM2B1)  // non-inverting PWM on pin OC2B
       | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
       | _BV(WGM21);  // ditto
TCCR2B = _BV(WGM22)   // ditto
       | _BV(CS22);   // clock at F_CPU/64

Note that the timer will also set a flag when the pulse is done, at
which time you can start the data transfer. You would then start your
data-taking loop with:
// Wait for the output compare flag.
loop_until_bit_is_set(TIFR2, OCF2B);

// Clear the flag.
TIFR2 |= _BV(OCF2B);

// Now transfer the data.
...

Edit 1: I would just want to add that cycle accurate timing does
not mean perfectly uniform timing. The Arduino Uno is clocked off a
ceramic resonator. This kind of resonator, in addition to having bad
accuracy, has poor frequency stability. To get an idea of how bad it can
be, see the Allan deviation plots on the article Arduino clock
frequency accuracy, by Joris van Rantwijk.
Edit 2: After some tests, I wrote a more complete initialization:

An initial SPI transaction is used to prime the ADC, as suggested by
Chris Stratton
the PWM pin is configured as an output
the Arduino core's Timer setup is undone before applying the new
configuration
the very first pulse on CONVST is scheduled to happen not too long
after the initialization, yet after tACQ
the output compare flag is cleared during the initialization.

Yes, though to clarify, the conversion must be primed by an SPI operation, then the actual measurement triggered by CONVST.  Typically the way to get regular spacing is to have software prime early, and then as wisely shown here have a hardware timer trigger the actual conversion at more evenly spaced intervals than software will normally achieve.  Then software claims the data and prime for the next.

You are right, and that was sloppy of me.  The conversion is triggered by CONVST which happens to be the same time that I slave-select the ADC.  Thanks for the info on hardware timer interrupt, I'll investigate that.

@MichaelT: I think you misread my answer. I am not suggesting you use a timer interrupt, I am suggesting you use a timer to generate a low-jitter trigger signal for your ADC. Then you can use an interrupt flag (namely OCF2B) to know when it is safe to do the data transfer. Note that the interrupt flag is independent from the actual interrupt mechanism: it can be used when the interrupt is disabled, which is the case here. I am suggesting a polling, rather than interrupt based, approach. Of course, you can do interrupts if you prefer, but you don't have to.

OK, got it.  I will try that approach and append the findings to my original posted question.  I think it will be interesting to compare with the code I have been using so far and see if there is much difference.

Thanks, in the end I used timer1 not timer2.  While I don't need the 16-bit timer resolution, timer1 controls PWM on Arduino pin 10 and that saves me making a new circuit board/"shield" for the ADC, for the time being.  I'll post the code in the main question

I did a project generating VGA signals that required highly precise timing for the sync pulses.
The technique that worked for me was:

Use the hardware timers to generate the required pulse interval
Put the processor to sleep (set_sleep_mode (SLEEP_MODE_IDLE);) to remove jitter caused by whether the interrupt occurred while an instruction was executing (interrupts can't interrupt half-way through a multi-cycle instruction).

So in your case I would set up the timer (eg. Timer 1) to generate the appropriate interrupts. Then go to sleep waiting for the interrupt. The ISR doesn't have to do anything in particular, you just want to pause until the interrupt happens. For example you could do this:
EMPTY_INTERRUPT (TIMER1_COMPA_vect);

That will generate a "do nothing" interrupt handler for Timer 1 compare-A vector.
Once the interrupt happens you will pass the sleep instruction and then you can do your ADC sample and send the results. You may want to scale back the ADC clock a bit (eg. a prescaler of 64) to speed up the ADC sample a bit.
See my page about the ADC and my page about interrupts.

Automatic mode
Another possibility is to use the automatic ADC conversion, as in this example from my page about the ADC:
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

The code above will take 256 samples at 50 kHz frequency. You could modify the ISR to send the results by SPI (SPI transfers should be OK inside an ISR) if you needed to take more samples and save them elsewhere.

Even if my code is precise, is the relatively low CPU speed of 16 MHz something to worry about for data sampling rates up to a few kHz?

No, I don't think so.

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


text:
Unpacking Arduino binary data on a python sketch
As a follow up to my earlier post: Simultaneously reading data from multiple serial ports, I am stuck trying to develop a python sketch that can read the incoming serial data from the com port on my Arduino and unpack them from the buffer into two separate cvs files.
One of the csv files would contain the data from the first sensor, while the other would contain the data from the second sensor. I have been able to develop the sketch to a point where on receiving the first header byte the first sensor data is unpacked. I am finding it hard to adjust the sketch to allow for the second byte header to be called to unpack the second sensor data from the data packet. Below is my abbreviated sketch thus far. Thanks all.

def run(self):
    #Creating a csv file to read data from the first sensor
    self.click = open("ball_Data.csv", "wb")
    #Creating a csv file to read data from the second sensor
    self.flick = open("rugby_Data.csv", "wb")
    #creating the serial port object
    self.push = serial.Serial('COM6', 9600)
    while True:
        #If the incoming byte is equivalent to '$'
        if node == b'$':
            # the byte object is equivalent to the available bytes
            node = self.push.read()
            #an array to hold the sensor data
            sensor_array = []
            i = 0
            #This while loop initiates a count from 0 to 9
            #through the sensor array
            while i < 10:
                #The available byte present
                malcolm = self.push.read()
                #The next byte
                turnbull = self.push.read()
                #The incoming uint_16 data is unpacked into the variable lingo
                lingo= (struct.unpack('b', turnbull)[0] << 8) | struct.unpack('B',malcolm)[0]
                #The variable lingo is then appended to the sensor array
                sensor_array.append(lingo)
                #If the length of the sensor array is equivalent to 9
                #write the data through each count into the sensor array
                if len(sensor_array) == 9:
                    self.click.write(str(sensor_array[0] ..+ str(sensor_array[9]))
                    #My idea is that this else statement was supposed to trigger
                    #the next header for the second sensor which would be an '#'
                    #sign before unpacking the data
                    else:
                        oldde = self.push.read()
                        sensor_array = []
                        i = 10
                        while i < 20:
                            #The available byte present
                            malcolm = self.push.read()
                            #The next byte
                            turnbull = self.push.read()
                            lingo= (struct.unpack('b', turnbull)[10]<<8)|struct.unpack('B',malcolm)[10]
                            sensor_array.append(lingo)
                            if len(sensor_array) > 19:
                                self.flick.write(str(sensor_array[10]..+ str(sensor_array[19]))

                                The Packet data structure for the first and second sensor is:
                                    Packet1 from sensor 1:
                                        data_array[0] = headerbyte('#')
                                        data_array[1] = acceleration_xAxis
                                        data_array[2] = acceleration_yAxis
                                        data_array[3] = acceleration_zAxis
                                        data_array[4] = temperature
                                        data_array[5] = gyro_xAxis
                                        data_array[6] = gyro_yAxis
                                        data_array[7] = gyroz_xAxis
                                        data_array[8] = checksum
                                        Packet2 from sensor 2:
                                            data_array[9] = headerbyte('$')
                                            .
                                            .
                                            .
                                            data_array[17] = checksum

Please fix the code format. The indentation is "off".

@dada He means that it's a snippet and as such there is massive amounts of white space to the left of your listing that causes much of it to be scrolled off the side. You don't need to keep that indenting since it is not in context (which is actually an altogether different issue - we don't deal in snippets here : http://snippets-r-us.com ) so delete that excess indenting to make it easier to read, or better still, post your entire code so we might have a chance of understanding it.

@MikaelPatel, I adjusted the code format as requested.

and @majenko , I would comment more on the code to give you a better understanding of what i'm trying to do.

Can you post an example of the data that is being sent from the Arduino to your computer so that we know what it is that's trying to be parsed?

@majenko i just uploaded a screenshot of the data packet on the serial monitor

Urk. That's pretty meaningless like that I'm afraid. Can you create a packet description, similar to how I describe the ICSC packet format on here: https://github.com/MajenkoLibraries/ICSC

@majenko does this help

That's more usable, yes. Those are all BYTE values are they?

@majenko ..Yes they are

I'm somewhat confused by the flow of your program, so instead I will tell you how I would handle the data.
You have a single-byte header, then 7 bytes of data, followed by a single byte checksum.
PySerial's read is (I believe) blocking by default, so it's simple to read the next serial character - unlike an Arduino.  It also has a "multi-byte" read version where it can read a pre-set number of bytes from the stream for you.
So my methodology would be:

Read a byte.  Is it a '#' or a '$'?
If it is, remember which stream you are dealing with, then:
Read 7 bytes with this.push.read(7) into a byte array (or a string in python < 2.6)
Read one byte for the checksum. If the checksum is correct (whatever calculation you use for that) then unpack the data in the array.
Write the data to the correct file depending on the stream you remembered in step 2.

That way you're not duplicating code for each sensor stream, you are just saying "this packet is stream 2" and using that remembered fact once you have received the packet and verified that it's correct.
A better protocol arrangement, though, which is more reliable, involves both a start byte and an end byte, and your whole packet is wrapped in that pair of bytes.  You then have a "sliding window" arrangement whereby the incoming data bytes scroll past a window of a fixed width, and when the first and last characters in that window match your start and end bytes you then extract the middle section and do what you need to do with it.  That way if you have a $ or a # that is midway through a stream of data it won't trigger reception since the end byte doesn't match. It makes the whole synchronisation of the data more reliable.
For instance, if you have the current data packet that looks like $ho9*$fup and you miss the first bit of the data for whatever reason (arduino started transmitting before you were ready to receive, for instance) it might trigger reception on the second $ which would give you incorrect values.  So instead if you have the start character as $ and the end character as # and include a stream number, so your packet looks like:
$1ho9*$fup#

Then when you scroll that past the window it would look like:
 $         #
 v         v
[..........$]
[.........$1]
[........$1h]
[.......$1ho]
[......$1ho9]
[.....$1ho9*]
[....$1ho9*$]
[...$1ho9*$f]
[..$1ho9*$fu]
[.$1ho9*$fup]
[$1ho9*$fup#]

And the first and last characters match, so you receive the content.
If you were to miss the first $ the second $ wouldn't match - say the extended stream looks like: $1ho9*$fup#$2hdiw83bf# and you missed $1, the window would look like:
 $         #
 v         v
[..........o]
[.........o9]
[........o9*]
[.......o9*$]
[......o9*$f]
[.....o9*$fu]
[....o9*$fup]
[...o9*$fup#]
[..o9*$fup#$]
[.o9*$fup#$2]
[o9*$fup#$2h]
[9*$fup#$2hd]
[*$fup#$2hdi]
[$fup#$2hdiw] <= Doesn't match even though it starts with $
[fup#$2hdiw8]
[up#$2hdiw83]
[p#$2hdiw83b]
[#$2hdiw83bf]
[$2hdiw83bf#] <= Matches - starts with $ and ends with #

As you can see the synchronising of your packet is then much more reliable. It would normally have incorrectly triggered on the first $ it saw.
There is always a chance that there may be a $ and a # in just the right positions within successive packets to fool the system, but the chances of that are somewhat slim.  You can add extra protection against that by "escaping" the start and stop bytes if they appear within your stream. There's many possible ways of handling that if you really need it.

...Lord God!!! Thanks alot.!!!!!!!!!!!!!!!!!! ...I'm much obliged


text:
How to use SIM908-C BY UNV shield
I have a shield with a SIM for GSM/GPRS communications and GPS module.
As visible in top-left corner its name is "SIM908-C EVB v1.0 designed by UNV".

I found some basic information on Arduino forum but they are discordant about baud rate so I tried different configuration: https://forum.arduino.cc/index.php?topic=302982.0
I tried to use several libraries (such as sim900 or tinyGPS) for GPRS communication or simply for getting GPS position, but without results. Shield not respond to serial commands at any baud rate.
Connections that I used:
shield <--> aruino mega
GPRS TXD <--> D2
GPRS RXD <--> D3
GPS TXD <--> D4
GPS RXD <--> D5
GND <--> GND
5V <--> VCC_MCU

Obviously I set D2..D5 in library according to TX/RX pins on shield.
I also tried with a simply code to send AT commands and... no results again.
Here is the code:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2,3);

void setup() {
    Serial.begin(115200);
    Serial.println("Begin");
    mySerial.begin(115200);
}

void loop() {
    if (mySerial.available())
        Serial.write(mySerial.read());
    if (Serial.available())
       mySerial.write(Serial.read());
}

Shield seems to be well powered and connected to SGM net. Infact:

power led: is on
ring led: is on
net status: blinks one time in three seconds

Has someone used this shield? What is a good library to use?
Every help is very appreciated.

Have you tried other baud rates with this sketch? 9600, 19200, 57600, etc? Is your serial monitor set to "Both NL & CR" at the bottom? Explain the connections between the Arduino and the module.

Thank you for interest.
Shield not respond to serial commands at any baud rate.
Serial monitor is set to "Both NL & CR".

Dont connect the GPS pins for now. Try using the other hardware serial ports of the Mega like Serial1 instead of SoftwareSerial. You say the module is powered well. How exactly are you powering the module? Try using 4V/2A supply. Also connect the VccMcu pin to the same 4V source and level-shift TX signals from the Arduino to 4V.

OK, I'll try connecting TX1 <-> GPRS_RXD and RX1 <-> GPRS_TXD.
I'm using a 12V/1.5A power supply connected to the shield. Arduino Mega is connected via USB to computer.
I'm not sure what do you mean with "level-shift TX signals from the Arduino to 4V"

Surely you arent connecting the 12V supply directly to the shield? There must be some regulator in the middle? By level-shift, I mean using a simple voltage divider to reduce 5V signals from the Arduino TX line to 4V that can be used by the module. Does the module have any sort of datasheet about the voltages it supports?

From datasheet I find that power supply can be 5-18V and Vcc_mcu must be connect to level of serial port: I think that is correct to connect to 5V of Arduino.
I'm trying now (baud rate 9600) and with AT command I receive a response made by ten bytes:
65 (A)
84 (T)
13 (CR)
10 (LF)
13 (CR)
10 (LF)
79 (O)
75 (K)
13 (CR)
10 (LF)
It seems to work.
How to use GPS, now?

What did you change that made it work now? I havent used GPS with these modules before but I imagine another serial port is all you need. Download the sim908 AT command set.

I tried a lot of configurations: I don't know exactly what is different now.
I think that the main difference is the use of TX/RX native serial ports of Arduino Mega.

I thought as much. I had the same problem with a similar module and a Mega. Didnt work till I used Serial3.


text:
Using CLion as Arduino IDE — Cannot find Libraries
I'm having a problem using CLion as Arduino IDE when integrating 3rd-party libraries:
Here is the CMakeList.txt

cmake_minimum_required(VERSION 2.8.4)
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/cmake/ArduinoToolchain.cmake)
set(PROJECT_NAME ArduinoIceCream)
project(${PROJECT_NAME})

set(${CMAKE_PROJECT_NAME}_BOARD mega)
set(${CMAKE_PROJECT_NAME}_PORT COM4)
set(mega.build.mcu atmega2560)
LINK_DIRECTORIES(C:\\Users\\Xybrek\\Documents\\Arduino\\libraries)

set(${CMAKE_PROJECT_NAME}_SKETCH ArduinoIceCream.ino)
generate_arduino_firmware(${CMAKE_PROJECT_NAME})

Here is the log:
"C:\Program Files (x86)\JetBrains\CLion 2016.3\bin\cmake\bin\cmake.exe" --build C:\Users\Xybrek\ClionProjects\ArduinoIceCream\cmake-build-debug --target upload -- -j 4
-- Generating ArduinoIceCream
-- Using C:/Program Files (x86)/Arduino/hardware/tools/avr/bin/avr-objcopy.exe for converting firmware image to hex
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/Xybrek/ClionProjects/ArduinoIceCream/cmake-build-debug
[ 89%] Built target mega_CORE
Scanning dependencies of target ArduinoIceCream
[ 92%] Building CXX object CMakeFiles/ArduinoIceCream.dir/ArduinoIceCream_ArduinoIceCream.ino.cpp.obj
C:/Users/Xybrek/ClionProjects/ArduinoIceCream/ArduinoIceCream.ino:22:32: fatal error: BasicStepperDriver.h: No such file or directory
 #include "BasicStepperDriver.h"
                                ^
compilation terminated.
CMakeFiles\ArduinoIceCream.dir\build.make:65: recipe for target 'CMakeFiles/ArduinoIceCream.dir/ArduinoIceCream_ArduinoIceCream.ino.cpp.obj' failed
mingw32-make.exe[3]: *** [CMakeFiles/ArduinoIceCream.dir/ArduinoIceCream_ArduinoIceCream.ino.cpp.obj] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/ArduinoIceCream.dir/all] Error 2
CMakeFiles\Makefile2:103: recipe for target 'CMakeFiles/ArduinoIceCream.dir/all' failed
mingw32-make.exe[1]: *** [CMakeFiles/upload.dir/rule] Error 2
CMakeFiles\Makefile2:211: recipe for target 'CMakeFiles/upload.dir/rule' failed
mingw32-make.exe: *** [upload] Error 2
Makefile:169: recipe for target 'upload' failed

authors: البطل القاهر


text:
Problem using 74HC595 with ULN2803A as LED driver
For a final project I'm making a word clock using three 74HC595 registers and three ULN2803A transistor arrays as led drivers, as well as a DS1307 RTC.
The program works great, except for one large problem. While chips 2 and 3 work correctly, the outputs of the first chip are always lit.
I've tried several different programs online, I've done a lot of research and I just couldn't find the answer.

The code:
#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>

#define BUTTON_HOUR 8
#define BUTTON_MINUTE 7
#define DATA 2                    // digital 2 to pin 14 on the 74HC595
#define LATCH 3                   // digital 3 to pin 12 on the 74HC595
#define CLOCK 4                   // digital 4 to pin 11 on the 74HC595

// Variables will change:
int buttonStateHOUR = 0;          // current state of the button
int buttonStateMINUTE = 0;        // current state of the button
int lastButtonStateHOUR = 0;      // previous state of the button
int lastButtonStateMINUTE = 0;    // previous state of the button

byte registerByte1 = 0;           // 0 IT IS | 1 FIVE  | 2 EIGHT | 3 QUARTER | 4 THREE  | 5 TEN | 6 MINUTES  | 7 TWENTY
byte registerByte2 = 0;           // 0 TO    | 1 PAST  | 2 HALF | 3 FIVE    | 4 ONE   | 5 NINE | 6 TWO | 7 THREE
byte registerByte3 = 0;           // 0 FOUR   | 1 SIX | 2 EIGHT| 3 SEVEN  | 4 TWELVE | 5 TEN | 6 ELEVEN  | 7 O'CLOCK

tmElements_t tm;

void setup()
{
  // ***********************************
  Serial.begin(9600);
  while (!Serial) ; // wait for serial
  delay(200);
  Serial.println("DS1307RTC Read Test");
  Serial.println("-------------------");
  // ***********************************

  // Buttons
  pinMode(BUTTON_HOUR, INPUT);
  pinMode(BUTTON_MINUTE, INPUT);

  // Shift Register
  pinMode(LATCH, OUTPUT);
  pinMode(CLOCK, OUTPUT);
  pinMode(DATA, OUTPUT);
}

void loop()
{
  // read the pushbutton input pin:
  buttonStateHOUR = digitalRead(BUTTON_HOUR);
  buttonStateMINUTE  = digitalRead(BUTTON_MINUTE);

  // Detect HOUR Button
  if (buttonStateHOUR != lastButtonStateHOUR) {
    if (buttonStateHOUR == HIGH) {
      addTime(1,0);
    }
    lastButtonStateHOUR = buttonStateHOUR;
  }
  // Detect MINUTE Button
  if (buttonStateMINUTE != lastButtonStateMINUTE) {
    if (buttonStateMINUTE == HIGH) {
      addTime(0,1);
    }
    lastButtonStateMINUTE = buttonStateMINUTE;
  }

  // Generate time and shiftOut
  timeToBytes();
  updateShiftRegisters();
  printTime();
}

void timeToBytes()
{
  if (RTC.read(tm)) {
    int deutschHour = shortHour(tm.Hour);
    int halb = 0;
    registerByte1 = 0;
    registerByte2 = 0;
    registerByte3 = 0;
    bitSet(registerByte1,0);    // "ES IST"

    if (tm.Minute >= 0 && tm.Minute <= 5) {
      bitSet(registerByte1,1);    // "FIVE"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,1);    // "PAST"
    } else if (tm.Minute >= 10 && tm.Minute <= 19) {
      bitSet(registerByte1,5);    // "TEN"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,1);    // "PAST"
    } else if (tm.Minute >= 20 && tm.Minute <= 24) {
      bitSet(registerByte1,7);    // "TWENTY"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,1);    // "PAST"
    } else if (tm.Minute >= 25 && tm.Minute <= 29) {
      bitSet(registerByte1,7);    // "TWENTY"
      bitSet(registerByte1,1);    // "FIVE"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,1);    // "PAST"
      halb = 1;
    } else if (tm.Minute >= 30 && tm.Minute <= 34) {
      bitSet(registerByte2,2);    // "HALF"
      bitSet(registerByte2,1);    // "PAST"
      halb = 1;
    } else if (tm.Minute >= 35 && tm.Minute <= 39) {
      bitSet(registerByte1,7);    // "TWENTY"
      bitSet(registerByte1,1);    // "FIVE"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,0);    // "TO"
      halb = 1;
    } else if (tm.Minute >= 40 && tm.Minute <= 49)  {
      bitSet(registerByte1,3);    // "QUARTER"
      bitSet(registerByte2,0);    // "TO"
      halb = 1;
    } else if (tm.Minute >= 50 && tm.Minute <= 54) {
      bitSet(registerByte1,5);    // "TEN"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,0);    // "TO"
      halb = 1;
    } else if (tm.Minute >= 55 && tm.Minute <= 59) {
      bitSet(registerByte1,1);    // "FIVE"
      bitSet(registerByte1,6);    // "MINUTES"
      bitSet(registerByte2,0);    // "TO"
      halb = 1;
    }

    deutschHour = shortHour( deutschHour + halb);
    if ( deutschHour == 1 ) {
      bitSet(registerByte2,4);    // "ONE"
    } else if ( deutschHour == 2 ) {
      bitSet(registerByte2,6);    // "TWO"
    } else if ( deutschHour == 3 ) {
      bitSet(registerByte2,7);    // "THREE"
    } else if ( deutschHour == 4 ) {
      bitSet(registerByte3,0);    // "FOUR"
    } else if ( deutschHour == 5 ) {
      bitSet(registerByte2,3);    // "FIVE"
    } else if ( deutschHour == 6 ) {
      bitSet(registerByte3,1);    // "SIX"
    } else if ( deutschHour == 7 ) {
      bitSet(registerByte3,3);    // "SEVEN"
    } else if ( deutschHour == 8 ) {
      bitSet(registerByte3,2);    // "EIGHT"
    } else if ( deutschHour == 9 ) {
      bitSet(registerByte2,5);    // "NINE"
    } else if ( deutschHour == 10 ) {
      bitSet(registerByte3,5);    // "TEN"
    } else if ( deutschHour == 11 ) {
      bitSet(registerByte3,6);    // "ELEVEN"
    } else if ( deutschHour == 12 ) {
      bitSet(registerByte3,4);    // "TWELVE"
    }
    bitSet(registerByte3,7);    // "UHR"
  }
}

void updateShiftRegisters()
{
   digitalWrite(LATCH, LOW);
   shiftOut(DATA, CLOCK, MSBFIRST, registerByte3);
   shiftOut(DATA, CLOCK, MSBFIRST, registerByte2);
   shiftOut(DATA, CLOCK, MSBFIRST, registerByte1);
   digitalWrite(LATCH, HIGH);
}

void addTime(int addHour, int addMinute)
{
  // get time from RTC
  if (RTC.read(tm)) {

    if (addHour > 0) {
      tm.Hour = tm.Hour + addHour;
      if (tm.Hour > 12) {
        tm.Hour = tm.Hour - 12;
      }
    }

    if (addMinute > 0) {
      tm.Minute = tm.Minute + addMinute;
      if (tm.Minute > 59) {
        tm.Minute = tm.Minute - 60;
        addTime(1,0);
      }
    }

    tm.Second = 0;
    RTC.write(tm);
  }
}

int shortHour(int tempHour)
{
  tempHour = tempHour % 12;
  return tempHour == 0 ? 12 : tempHour;
}

void printTime() {

  if (RTC.read(tm)) {
    Serial.print("Ok, Time = ");
    print2digits(tm.Hour);
    Serial.write(':');
    print2digits(tm.Minute);
    Serial.write(':');
    print2digits(tm.Second);
    Serial.print(", Date (D/M/Y) = ");
    Serial.print(tm.Day);
    Serial.write('/');
    Serial.print(tm.Month);
    Serial.write('/');
    Serial.print(tmYearToCalendar(tm.Year));
    Serial.println();
    Serial.print("registerByte3 = ");
    Serial.print(registerByte3, BIN);
    Serial.println();
    Serial.print("registerByte2 = ");
    Serial.print(registerByte2, BIN);
    Serial.println();
    Serial.print("registerByte1 = ");
    Serial.print(registerByte1, BIN);
    Serial.println();
  } else {
    if (RTC.chipPresent()) {
      Serial.println("The DS1307 is stopped.  Please run the SetTime");
      Serial.println("example to initialize the time and begin running.");
      Serial.println();
    } else {
      Serial.println("DS1307 read error!  Please check the circuitry.");
      Serial.println();
    }
    delay(9000);
  }
  delay(1000);
}

void print2digits(int number) {
  if (number >= 0 && number < 10) {
    Serial.write('0');
  }
  Serial.print(number);
}

Do you use a breadboard? Perhaps it is a bad connection. Did you solder it? perhaps there is a solder splat between two pins. Check the wiring, and try to  replace the bad 74hc595. Do you have a logic analyzer? If not, you can try to add delays and measure the signals with a voltagemeter.

I'm using a breadboard. I did try switching them around, and the problem is still there. I actually did buy three new registers, and I switched them around, the problem is still there. Sadly I'm not knowledgeable enough for the last 2 steps you mentioned. One thing to add is, on that first chip, the pins which are supposed to light up are brighter than the ones that arent supposed to.

Check the gnd of that 74hc595. Try to add another gnd wire or move that 74hc595 to a different location on the breadboard. Could you make a photo of it? This site is for questions and answers, you mention that the pins that are supposed to light up are brighter, please add that to your question, it is important information.


text:
H Bridge for microcontroller power management?
Is it fine to use L298 N Dual H Bridge Stepper Motor Driver Module to control power of other ICs in a multiple microcontroller setup?
I intend to reduce power consumption in by powering communication ICs through the H bridge to allow switcching them off if not needed. Does a L298 based H bridge module like shown below supply clean stable DC current to someting like the ESP8266?
Module shown below contains condensators, i assume to reduce ripple effect created by L298.

While it may be possible to bend one of those to your proposed usage, it's far from ideal, for a number of reasons:

It's far more expensive than the single P-FET that you need to get the job done
It's risky: you can easily reverse the current through your components and blow them up
It imposes a ground offset which can cause you communication problems.

All you need is a single P-channel MOSFET (assuming you are switching 5V with a 5V logic signal) and a single resistor (10kΩ would be fine, but any large value is ok).

simulate this circuit – Schematic created using CircuitLab
Pull the GPIO LOW and the power switches on. As simple as that.
If you want to switch a higher voltage then simple use an N-channel MOSFET to pull the GPIO line LOW for you - which you then switch with your GPIO signal.


text:
Float to int conversion not working right in method using varargs
I am trying to convert a floating point number to an integer, but it seems like the conversion is not working properly.
I am using the math library to calculate the power of 10 based on the number of varargs, where the first argument is the number of arguments followed by the varargs.
int charsToIntValue(int argc, ...) {
  int multiplier = (int) pow(10, argc - 1);
  va_list argp;
  va_start(argp, argc);
  Serial.println(multiplier);
  ...
  va_end(argp);
}

For some reason, multiplier is always stored as 1 less than the actual result.
e.g. If charsToIntValue(4, 1, 2, 3, 4) is executed, the multiplier is stored as 999 rather than 1000. However, when it is printed as a float, it does show 1000.00. And whenever I change it to a constant ((int) pow(10, 3)) it works fine, returning 1000.
I've tired storing the value of argc into a local variable but that didn't seem to change anything.
Full project is here for context: https://github.com/Pyrodron/charger-destination-board
File in question is charger-destination-board.ino; lines 32 to 51

A minimal test setup around your charsToIntValue doesn't show me what you're talking about.  I don't think this has anything strictly to do with variadic function support.  Nor Arduino.  I will just add that pow(10, argc - 1); could be better written as a small function that takes an int, returns an int, and consists of a switch statement with no float at all.

I'm currently not sure, if pow() returns a float. If yes, that that behavior seems normal. Floats can only save an aproximation of the wanted number. The actual float value, that is calculated  might be something like 999.99. When you them convert to an int, the digits behind the decimal point get thrown away, leaving 999. Thats something, that you would need to accept, when you want to work with floats. And thats one reason, why it is often better, to just use an integer representation.

@timemage I took inspiration from your comment and implemented my own power function rather than using the math.h library. It works now!

With some inspiration from timemage's comment, I decided in the long run to implement my own power function that takes two int arguments and returns an int. Rather than use the pow function in the <math.h> library which returns a double when I only need an int.
int power(int x, int y) {
  return y == 0 ? 1 : x * power(x, y - 1);
}

Now the program works as intended!

I'd had some doubt about this actually solved the problem, because I'd tested the handful of exponent values you were using to see if the pow() happened to produce the values you wanted.  Turns out avr-gcc will use higher precision if the optimizer can determine at compile time irrespective of whether it's doing this is a constexper context, meaning so much as having an argument something volatile qualified will cause pow() to evaluate at lower precision.  Just more reason to not use float on an AVR.

When the optimizer kicked in pow(10, 4)'s result had significand field 0b00111000011111111111110 and where the optimizer couldn't determine the exponent at compile time a significand field of 0b00111000100000000000000.  The former converts to int with the expected (for certain values of "expected") 10000 while the latter produces a value closer to 9984.  Something also you should be aware of is that in avr-gcc, there really is no double.  It's a distinct type for overload purposes, but it's implemented as single precision float.

@timemage all helpful information. Thank you

As explained by @chrisl in a comment, the issue is that pow() does not
return an exact result, only an approximation. It works fine with
compile-time constants because in this case it is evaluated at compile
time, by the compiler, on you PC.
Simple solution: replace the cast to int with round():
int multiplier = round(pow(10, argc - 1));

This works, but is awfully inefficient, as pow() involves the
computation of both an exponential and a logarithm, both very expensive
on an AVR-based Arduino. The int-only function in your own answer is
certainly better. However, it is generally advised to avoid recursion on
low-memory Arduinos like the Uno. Prefer an iterative algorithm if you
can.
Also, the complexity of you int-only function is O(y). There is a
well-known algorithm for integer powers that goes like O(log(y)):
int power(int x, int y)
{
    int z = 1;  // Invariant: result = x^y * z
    while (y) {
        if (y & 1) z *= x;
        y >>= 1;
        x *= x;
    }
    return z;
}

Maybe I am nitpicking, as your y cannot go beyond 5 without
overflowing the result...

"works fine with compile-time constants because" as I said in the the comments on the O.P.'s own answer, it's actually more complicated than that.  It has nothing to do with whether or not they're technically "constant".  You can elicit the difference in this behaviour without crossing between constant expressions and non-constant expressions.  The standard makes provisions for differences in precision between the two cases.  So that is fin.  But, the fact that it will give two completely different results outside the constexpr context is probably a bug.


text:
Does bool return an int?
I know that for the Arduino (and C in general) that for comparison sake, "false" is 0, while any non-zero integer is "true". The question that I have is does the bool data type "return" a concrete integer for "true" or "false"?
When I tried Serial.print(true == 1), it printed 1 (which I assumed to be "true"), but when I tried Serial.print(true == 2), it printed 0 (which I assumed to be "false"). When I tried Serial.print(false == 1), it printed 0 and Serial.print(false == 0) printed a 1.
I didn't know if "true" always evaluated to 1 and "false" always evaluated to 0, or if this is not supposed to happen.

Never use if(flag==1), don't even use if(flag==true), but use if(flag), when the variable flag is a bool or boolean. The bool is part of the c++ language and the boolean is made up by arduino. The Serial.print function prints integers and floats, but sadly not "true" or "false" for a bool, so it uses the integer value and prints "1" or "0".

@Jot, I was mainly seeing if it would be the same because I have function foo(int tf) where tf is either a 1 or a 0, and merely wanted to see if tf == true would be the same as tf == 1. But if the printer is translating true to 1, then it sounds like what I'm proposing is a bad idea.

If you look at Arduino.h, you'll see true, false and bool defined as:
#define true 0x1
#define false 0x0
typedef uint8_t boolean;

Using a simple test sketch, it appears that comparing true or false to anything besides a 1 or 0 does not "work".
void setup(){

  Serial.begin(9600);

  if(false == 0){Serial.println("false=0");}
  if(false == 1){Serial.println("false=1");}
  if(false == 2){Serial.println("false=2");}
  if(false == -1){Serial.println("false=-1");}
  if(true == 0){Serial.println("true=0");}
  if(true == 1){Serial.println("true=1");}
  if(true == 2){Serial.println("true=2");}
  if(true == -1){Serial.println("true=-1");}

}

void loop(){}

A 'bool' is defined data type based on (and identical to) an int. It's reason for existence is documentary: it's name describes how you intend to use it. There is no other difference.
'true' and 'false' are the constants 1 and 0, respectively. If you assign 'true' to a bool or any other integer type, it will get the value '1'. If you make a comparison or any other logical test (one that evaluates to true or false), that test results in a numerical value, either 1 or 0.
However you can evaluate (i.e. test) any integral value logically (true or false): if it is equal to zero the result will be false (0); otherwise the result will be true (1) - no matter what non-zero value the expression itself has. That is because the logical operators, '==', '!=', '>', etc., are (similar to) functions which can only return one of two values 'true' and 'false', regardless of the values of their inputs. That is another meaning of the bool datatype: when it is applied to a function, it implies to the compiler and to the reader that this function returns either true or false.

true is indeed 1, and false is 0.
This follows your tests:
(true == 1) -> prints 1, because 1 == 1
(true == 2) -> prints 0, because 1 != 2
(false == 1) -> prints 0, because 0 != 1

In C true and false are defines and a bool/boolean is a typedef (mostly to an int, unsigned int or unsigned char), where normally false is defined to 0 and true to 1 OR 255. So you cannot rely on a specific value.
In C++ the values of true and false are resp. 1 and 0, when casted to an int.


text:
Arduino: How to get the board type in code
I want to write a sketch that can be compiled on different Arduino boards.
I want to display on the PC which board is currently connected.
This means that the user connects the PC via USB cable to the Arduino/Teensy board in which runs my sketch and my sketch tells the PC via Serial which board is connected. On the PC runs my C# application which receives this data and displays it.
Therefore I need the board that has been selected when the sketch has been compiled:

I found the code on https://github.com/backupbrain/ArduinoBoardManager
but it does not give correct results (apart from the fact that several boards are missing).
Here a snippet from the code:
static const uint8_t BOARD_MICRO= 0x04;

....
#elif defined(__AVR_Atmega32U4__) // Yun 16Mhz, Micro, Leonardo, Esplora
  static const uint8_t BOARD = 0x04;
  static const uint8_t NUM_BITS = 8;
  static const uint16_t CPU = __AVR_Atmega32U4__;
  static const unsigned long SRAM_SIZE = 2500;
  static const unsigned long EEPROM_SIZE = 1000;
  static const unsigned long FLASH_SIZE = 32000;
#elif defined(.....

So this code gives the same result (BOARD = 0x04 = Micro) for Yun 16MHz, Micro, Leonardo y Esplora.
Is there any way to get in my C code exactly the string that the user has selecetd in the menu of the Arduino compiler?

If you're using the arduino IDE to build the firmware, there's no provision to pass a project-level #define to the compiler, aside from F_CPU ARDUINO and AVR_whatever. You may need to grauate to using a makefile to build, instead of arduinio IDE. Check the arduino.SE site, Nick and Ignatio have some good examples.

I cannot find anything interesting on Arduino.SE. (Is that swedish?)

@Elmue arduino.StackExchange.com is Arduino SE.

Ahhhh. OK. But arduino.se exists!

By “I want to display on the PC which board is currently connected” do you mean to display it when a compiled and uploaded sketch runs, or display it while a sketch is being compiled, or while the IDE is just sitting there with a particular board attached?  (In the latter two cases, board selection shows up in lowest line of the 1.6.3 IDE, but if you have an older or different IDE maybe not.) (If first case applies, do you want it to appear in the serial monitor?)

I updated my question to make it clearer. What I want is without IDE and without serial monitor. Just my sketch tells the PC via Serial: "Who am I".

Thanks to the help of Charlie Hanson and jantje I found the universal solution!
Because it is a pity that every Arduino programmer has to go through the same pain to figure out how to get the board name, I will offer my code to the public so everybody can just copy and paste it.
Here it is:
#if defined(TEENSYDUINO)

    //  --------------- Teensy -----------------

    #if defined(__AVR_ATmega32U4__)
        #define BOARD "Teensy 2.0"
    #elif defined(__AVR_AT90USB1286__)
        #define BOARD "Teensy++ 2.0"
    #elif defined(__MK20DX128__)
        #define BOARD "Teensy 3.0"
    #elif defined(__MK20DX256__)
        #define BOARD "Teensy 3.2" // and Teensy 3.1 (obsolete)
    #elif defined(__MKL26Z64__)
        #define BOARD "Teensy LC"
    #elif defined(__MK64FX512__)
        #define BOARD "Teensy 3.5"
    #elif defined(__MK66FX1M0__)
        #define BOARD "Teensy 3.6"
    #elif defined(__IMXRT1062__) && defined(ARDUINO_TEENSY40)
        #define BOARD "Teensy 4.0"
    #elif defined(__IMXRT1062__) && defined(ARDUINO_TEENSY41)
        #define BOARD "Teensy 4.1"
    #else
       #error "Unknown board"
    #endif

#else // --------------- Arduino ------------------

    #if   defined(ARDUINO_AVR_ADK)
        #define BOARD "Mega Adk"
    #elif defined(ARDUINO_AVR_BT)    // Bluetooth
        #define BOARD "Bt"
    #elif defined(ARDUINO_AVR_DUEMILANOVE)
        #define BOARD "Duemilanove"
    #elif defined(ARDUINO_AVR_ESPLORA)
        #define BOARD "Esplora"
    #elif defined(ARDUINO_AVR_ETHERNET)
        #define BOARD "Ethernet"
    #elif defined(ARDUINO_AVR_FIO)
        #define BOARD "Fio"
    #elif defined(ARDUINO_AVR_GEMMA)
        #define BOARD "Gemma"
    #elif defined(ARDUINO_AVR_LEONARDO)
        #define BOARD "Leonardo"
    #elif defined(ARDUINO_AVR_LILYPAD)
        #define BOARD "Lilypad"
    #elif defined(ARDUINO_AVR_LILYPAD_USB)
        #define BOARD "Lilypad Usb"
    #elif defined(ARDUINO_AVR_MEGA)
        #define BOARD "Mega"
    #elif defined(ARDUINO_AVR_MEGA2560)
        #define BOARD "Mega 2560"
    #elif defined(ARDUINO_AVR_MICRO)
        #define BOARD "Micro"
    #elif defined(ARDUINO_AVR_MINI)
        #define BOARD "Mini"
    #elif defined(ARDUINO_AVR_NANO)
        #define BOARD "Nano"
    #elif defined(ARDUINO_AVR_NG)
        #define BOARD "NG"
    #elif defined(ARDUINO_AVR_PRO)
        #define BOARD "Pro"
    #elif defined(ARDUINO_AVR_ROBOT_CONTROL)
        #define BOARD "Robot Ctrl"
    #elif defined(ARDUINO_AVR_ROBOT_MOTOR)
        #define BOARD "Robot Motor"
    #elif defined(ARDUINO_AVR_UNO)
        #define BOARD "Uno"
    #elif defined(ARDUINO_AVR_YUN)
        #define BOARD "Yun"

    // These boards must be installed separately:
    #elif defined(ARDUINO_SAM_DUE)
        #define BOARD "Due"
    #elif defined(ARDUINO_SAMD_ZERO)
        #define BOARD "Zero"
    #elif defined(ARDUINO_ARC32_TOOLS)
        #define BOARD "101"
    #else
       #error "Unknown board"
    #endif

#endif

You can even put this code into a new header file and #include it into your project.
P.D.
If you want to know additionaly to the board also the CPU model, search for the file avr_cpunames.h

another thing. instead of using "return "?";" when you don't know use #pragma warning board name is unknown

1.) I have replaced the "?" with an #error. 2.) I don't think that the strings are really a problem. You did understand that only ONE string will be compiled at the end? See my update that explains this above. The longest string is 11 bytes. If you need to optimize your code so much that you care about 11 bytes, I recommend to define an enum and return that instead of a string. Then your function will return one byte instead of 11.

3.) And what concerns the maintainability: It is sad that I have to write such a function. This should be already part of the header files that are installed with the compiler and should be maintained by the developers and updated with every new version.

2)I made a mistake when writing the remark on the size. I made a remark on that 5 hours ago. Sorry for that. 3)The maintainability is a problem. I have written very similar code in the past. I'm sure many others have as well. It is the maintainability why I prefer the "better IDE solution". I'm pretty sure all "better IDE's" will have similar solution as the one I mentioned in my answer. See it as a complement: You are outgrowing the Arduino IDE.

If you wrote a wrong comment, the best would be to delete it.

I like this solution.
Here's a suggested addition for the ESP8266.
#elif defined(ESP8266)
    #define BOARD "ESP8266"

note this is a windows mod something similar must exist on linux.
The first is quick and easy. Simply modify the platform.txt files you are using as described nelow. The draw back of this is that you will need to change platform.txt files with each release.
add -DBOARD=\"${build.board}\" to the recipe. This will allow for
   const char boardName[]=BOARD;

Which gives you the string "ARDUINO_AVR_LEONARDO" (for the leonardo) in boardName.
The second way is to switch to a better IDE (like already proposed by others). As the creator of the arduino eclipse plugin I would advice to use the arduino eclipse plugin. In the arduino eclipse plugin you do this as follows:
Right click on the project->properties->arduino->tab "compile options" put
-DBOARD=\"${A.BUILD.BOARD}\"

in the append to C and C++ field.
This will make the code above to compile
Adendum
I wasn't aware you wanted the "nice name". I'm not sure this can be fixed in the platform.txt in arduino IDE. In the arduino eclipse plugin change the fixe above in
-DBOARD=\"${A.NAME}\"

to get the nice name (for the leonardo "Arduino Leonardo") in the define Board.

Would the downvoter or anyone else please be so kind as to specify why this is answer needs downvoting?

1.) Yes, StackExchange should force everybody who votes down to write an explanation. (It was not my downvote) 2.) There is no need to use Eclipse to solve this problem. 3.) See my answer here.

Elmue, 1) thanks for agreeing :-). 2) I agree. The first part of the answer is how you can fix this modifying the platform txt so it works in the Arduino IDE. Your answer goes in more detail on how to fix this.No need to have eclipse or any better IDE for that. The better ide solution is mentioned because a Arduino ide needs to parse the boards.txt so it probably has this info somewhere and has the possibility to work without need for modifying the platform.txt. As I happen to know the arduino eclipse plugin very well I give an example on how to do this with this tool. 3)See my edit

Does Eclise also work with Teensy? What other advantages has Exclipse?

Yes teensy is supported by the arduino eclipse plugin but you'll have to mod the platform.txt (should be fixed in teensyduino 1.28)

The advantages: It is hard to say as there are so many. I personally like the click to see the code (when you ctrl click on a method you jump to the implementation/declaration of that function/variable; even if it is arduino core code). The call tree (Where is this used?) is a really powerfull view. Auto completion, the scope, multiple projects(=sketches) in one place, integrated version control ...

The original answer is out of date as new boards have been added.  The basic test is correct, but it's not clear where the list of boards come from.
If you locate the boards.txt file and look through it (eg. ~\Library\Arduino\hardware\arduino\avr\boards.txt on a Mac), each board will have an entry along the lines of <BOARD>.build.board=<NAME>, so for example, the MKR1000 would have a line:
mkr1000.build.board=SAMD_MKR1000
The corresponding #define can be generated by prefixing the <NAME> with ARDUINO_ so in this example, the following code will error for an MKR1000 board...
#if defined(ARDUINO_SAMD_MKR1000)
  #error

I asked a related question a while ago.
An internal *.h file exists which is created by the IDE, and holds in it the type of board that has been selected. The list of possible options is given in the linked question, but only for AVR boards. I believe the non-AVR list is much shorter.
It is simply a matter of adding some conditional statements to send the PC the correct information. A simple example:
//...within your code, perhaps during setup()...
#ifdef ARDUINO_AVR_UNO
    serial.println("UNO");
#endif
#ifdef ARDUINO_AVR_LEONARDO
    serial.println("LEONARDO");
#endif
// etc...

If you need to refer to the board type more than once in the sketch, use the following format:
//...BEFORE setup(), or otherwise in the global namespace...
#ifdef ARDUINO_AVR_UNO
    #define __BOARD_TYPE "UNO"
#endif
#ifdef ARDUINO_AVR_LEONARDO
    #define __BOARD_TYPE "LEONARDO"
#endif
// etc...

// within your code, wherever necessary:
serial.println(__BOARD_TYPE);

The latter is much tidier, even if you only need __BOARD_TYPE once, as it removes the cumbersome #ifdef chunk from your functions.
You will, of course, have to write one for each board that you expect your end-user could have, and you will possibly need to update this list as new models appear.

Thanks for your answer. It helped me lot. (See my answer here) But there is an error in your code. Instead of AVR_UNO it must be ARDUINO_AVR_UNO.

You might want to remove the semicolons at the end of your #defines; they are not C statements and do not need separators; in fact the separators will be inserted where the macros is used, link inside the parens of the println() function.  (If the semicolons are removed, this comment won't make sense to later readers).

For Adafruit boards, specifically a Feather M4, the following worked for me.
#ifdef _VARIANT_FEATHER_M4_
serial.println("Feather M4");
#endif

The exact names in the menu come from boards.txt file in your Arduino IDE (Arduino\hardware\arduino\avr\boards.txt). I think you would have to parse the file by yourself and find the detected board there.

Parse the file ?? And how do I know which one is selecetd in the menu?


text:
Arduino parsing JSON
I have created an API in Ruby on Rails and it send the following JSON response:
{"sun_position":{"altitude":"32.46","azimuth":"223.93"}}

I'm able to successfully hit the API and store the response. But when I try to parse it and store data it gives me an error. I have used the Arduino JSON library.
The code for parsing the JSON is as follows:
bool parseSunPosData(char* content, SunPosData* sunPos) {
  StaticJsonBuffer<JSONBUFFER_SIZE> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(content);
  Serial.println("In parse fuc");
  Serial.println(content);
  Serial.println("==============");
  if (!root.success()) {
    Serial.println("JSON parsing failed!");
    return false;
  }

And the output on the serial monitor is as follows:

In parse fuc 38
{"sun_position":{"altitude":"32.46","azimuth":"223.93"}} 0
==============
JSON parsing failed! Disconnect

My guess is it can't parse the data due to the numbers 38 and zero printing... I don't know what that is and what it is.
PS: New to Arduino coding.

you have the HTTP chunked transfer encoding numbers in the content. 38 is the length of the body and it is on the first line of the HTTP body and 0 marks the end.
maybe try using ArduinoHttpClient library for HTTP

Thanks Juraj, That helped.. I changed the HTTP version to 1.0 from 1.1 and it worked like a charm


text:
Urgent help/advice needed for a fish autofeeding device using NodeMCU
I have been assigned to set up these fish autofeeders that have been assembled . The goal is to have the autofeeders installed on top of the fish tank and dispensing food at chosen times (so somehow retrieving information about global timing).
I need to program and install 15 such systems. I also have access to 1 Raspberry pi (which I think will help with keeping clock time? I am not sure).
A NodeMCU board is attached to a custom PCB. It seems through the PCB the servo (which controls and rotates the feeder to allow food to drop) is connected to the board's D4 pin. An LED also seems to be connected to the D5 pin (not sure what this can be used for, maybe showing that the system is active or food is being dispensed something of that sort).
This connection goes through a resistor on the PCB (labeled 1k). There also seems to be a small battery or something connected via the PCB (I think it is connected to VIN and has a label of 70uF, so might be a capacitor instead).
According to online sources I cannot retrieve the program that was uploaded onto the board when they were used before, so I need to code the program from scratch and I have no idea how to start.
I tried to upload the example blink sketch, changing the LED pin to D5 but nothing happened.
Any and all guidance on how to proceed would be really really appreciated. If any more information about the system/pictures are needed I'll be happy to add on too.
/*
  ESP8266 Blink by Simon Peter
  Blink the blue LED on the ESP-01 module
  This example code is in the public domain

  The blue LED on the ESP-01 module is connected to GPIO1
  (which is also the TXD pin; so we cannot use Serial.print() at the same time)

  Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

const int LED_Pin = D5;

void setup() {
  pinMode(LED_Pin, OUTPUT);  // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_Pin, LOW);  // Turn the LED on (Note that LOW is the voltage level
  // but actually the LED is on; this is because
  // it is active low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_Pin, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

what is your question? ... please add a focused, answerable question to your post

So the upload succeeded, but the LED doesn't blink, right? And the connection for it goes D5 -> resistor -> LED+, LED- -> ground ? Have you a multimeter to check the voltage on D5? Is it changing? Are you sure, that you are compiling for the NodeMCU in the Arduino IDE? Please also try changing D5 to 14 (as D5 should be GPIO14).

If you are sure it is a NodeMCU, then LED_BUILTIN is defined as 2 which is D4. See pin_arduino.h of NodeMCU.

You can also try this fish feeder using Arduino Nano: https://www.pcbway.com/project/shareproject/Automatic_Fish_Feeder_Using_Arduino_Nano_525798ea.html  This tool uses Arduino nano as the main controller to drive the servo in the feeding process. The full setup is here. You can replace the nano with the NodeMCU.

Since you have 15 systems but only one Raspberry Pi, you can use the Raspberry Pi to retrieve the current time via NTP (Network Time Protocol) and then broadcast it to all the NodeMCU boards. You have to set up NTP on Raspberry pi. Then you can write a Python script that sends the current time to the NodeMCU boards over Wi-Fi using UDP or MQTT. You must program the NodeMCU for Scheduled Feeding. The NodeMCU should connect to wifi, Sync time with the Raspberry Pi (using UDP or MQTT) and Rotate the servo at the scheduled feeding times.

You might also want to ensure the fish will be fed, even if the local clock-time is stale, to prevent the case where none of the fish get fed if the RPi hasn't updated the local clock when it should have.

there's an NTP library for the ESP, no need to make it more complicated than needed.


text:
Arduino Uno: Driving a small LED strip with 2N3904 NPN
I'd like to know why I cannot dim the small LED strip with my design. I can only turn them on and off. This is a problem for me as I wanted to have a fade effect. Here is my circuit:

The voltage from the power jack is 5 volts. My NPN transistor is a 2N3904 (from left to right: emitter, base, collector).
For the Arduino I am only using the fade exemple sketch:
int led = A2; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
   pinMode(led, OUTPUT);
 }

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
     fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

By the way, this is my first post so please tell me if something is wrong with it! Thank you for your help!
Have a nice day.

The voltage from the power jack is 5 volts - what do you mean by that? Are you feeding 5V into that thing at the top of the picture (into Vin?). I'm a little surprised the LEDs light up at all, since the forward voltage for a red LED is around 2V, and with 5 in series, they will be getting 1V each.

The analogWrite works only on PWM pins (in your scheme it's marked by ~). On the other pins it's possible to set only LOW/HIGH (values under 128 are translated to the LOW)
Not to mention weirdly used NPN with LEDs as negative feedback. But that's why it doesn't burned out yet. The usual way is connect the Emmiter to the ground and base is driven over current limiting resistor (about 1k).
This is how we usualy use PNP transistor (again with 1k resistor and emitter to the Vcc, not the collector). But PNP won't work with 5V logic and higher Vin than 5V as there will be current flow from 0V or 5V to the Vin.

The unusual NPN connection you show is called an emitter follower circuit.  The emitter will follow the base voltage -.7V or -1.4v for a darlington. I assume you are powering it by the USB.

@gil He has 5 LEDs in series (roughly about 9V @ 10mA) and emmiter follower with 0 or 5V in the base...


text:
Forcing bootloader startup through program
I am trying to find out if it is possible to trigger programmatically the double-tap on reset button function, implemented in modified version of Atmel's SAM-BA bootloader. The board of interest is Arduino Zero.
In case this is not possible using the stock board setup, if this can be achieved by hardware or bootloader modifications.

Theoretically it is quiet easy to fake that double-tap with software, but there might be some obstacles in practice.
The bootloader uses an unsigned long value in RAM memory to indicate if the double tap happend. The actual bootloader for the zero uses the following definitions.
// zero specific; but other boards use the same values AFAIK
// (in board_definitions_arduino_zero.h)
#define BOOT_DOUBLE_TAP_ADDRESS  (0x20007FFCul)
#define BOOT_DOUBLE_TAP_DATA  (*((volatile uint32_t *) BOOT_DOUBLE_TAP_ADDRESS))

// for all bootloader (in main.c)
#define DOUBLE_TAP_MAGIC 0x07738135

When the bootloader is started after a reset, it checks, if that was a power on reset (POR) or not. If it has been a POR, it sets the indicator value to 0 BOOT_DOUBLE_TAP_DATA = 0;.
If it does not detect a POR, the bootloader continues with checking the indicator value whether it is set to the tap magic.
If the magic can be found  the indicator value is set back to 0 and the bootloader is started. Otherwise the value is set to the "double tap magic": BOOT_DOUBLE_TAP_DATA = DOUBLE_TAP_MAGIC. The bootloader waits for 500 ms to let the user reset the zero a second time (double tap) and resets the indicator value after that time interval.

How to:
To simulate a double tap, you just need to set the indicator variable with the magic value from within you program. Use the definitions above. Then perform a software reset.

The caveats:

If the bootloader was changed, that could make you code useless.
I have not the time to test my ideas, so this is just an unverified method. It might fail for some reasons, I do not see actually.
You have to find a method to reset the zero with the program. Iknow some methods but I've not tried any of them so far.

Reset Methods: (as a starting point for your search)
I've read somewhere that the zero supports the CMSIS method NVIC_SystemReset.
This is a method often used for M0 ARM controllers (like SAMD11).
SCB_AIRCR = SCB_AIRCR_VECTKEY(0x5FA) | SCB_AIRCR_SYSRESETREQ_MASK;

Here is my code "idea" (untested):
#define BOOT_DOUBLE_TAP_ADDRESS  (0x20007FFCul)
#define BOOT_DOUBLE_TAP_DATA  (*((volatile uint32_t *) BOOT_DOUBLE_TAP_ADDRESS))
#define DOUBLE_TAP_MAGIC 0x07738135

// lots of code ....

void resetWithDoubleTap()
{
   BOOT_DOUBLE_TAP_DATA = DOUBLE_TAP_MAGIC;
   NVIC_SystemReset();
}

I would be lucky, if you succeed with this. Please let us know your outcomes, either write your own answer or tell me what you've done and I will correct my answer if necessary. Good luck.

Thank you very much. I will have a board available for testing in a week or so. Anyway  I will definitely post the results here. For now this is the accepted answer.


text:
How to get current time and date in arduino without external source?
I'm working on a project using Arduino Uno and SD card shield.
I'd like to store a variable at a specific time everyday in the SD card. How can I get the current time in Arduino ?
Any help would be appreciable.
NOTE : Arduino is NOT connected to PC.

An accurate enough way is to use the millis() function. It  will return the value in milliseconds since the start of the Arduino. If you start the Arduino at a specific time, you will be able to calculate the exact date and time.

Why not an external module?? An RTC such as the DS3231 in merely 5$ and it includes a temperature sensor for you!

Watch out the millis() function will wrap around after about 50 days.

@AndreCourchesne : http://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover

So what if it wraps around? A properly written clock program will not care about that.

without external source

You can't. The Arduino Uno has no real-time clock. A real-time clock is only something like $1 from eBay. For example the DS1307 or DS3231. I found 5 x boards pre-assembled with the clock chip, including battery holder, crystal, chip, and circuit board for $US 4.20 on eBay. Batteries not supplied.
Hook that up to the I2C pins (A4 and A5), set the time once using a suitable sketch, and then you are ready to roll.

If you just want to do something every 24 hours (not necessarily at 9:36 a.m.) then you can just use millis to find when the appropriate number of milliseconds has elapsed. The result from millis will wrap every 49 days roughly but you don't have to worry about that.
Note that this won't let you log the date and time, but you can log something (eg. the temperature) every day, you would just have to know when you started logging.

One possibility to consider is to use a 24-hour plug-in timer that controls the power to the Uno.
I.e. something that looks like this:

The circuit would be: AC outlet -> Timer -> USB charger -> Arduino
You could set the timer to turn off the power to the Uno at say 11:30 PM and turn on again on midnight.
Under such setup, millis() will be the time since the last Uno start, which will usually be the time since the previous midnight.
When debugging, you could set the time-at-Uno-start to other than midnight.
The caveats are:

Your situation allows for daily 30-minute (or whatever the timer increments are) downtime
Can tolerate timer shifts due to power outages