How to properly handle the Arduino String I've read that the Arduino String is bad as it causes memory fragmentation, so I try to avoid them mostly. But I still have some occurences where I'm not quite sure if they are ok after all.
The first is in print statements:
I have a function which prints a success or error message to the serial port, like so: Serial.println("Success");. Is this ok or should I (for example) pre define the String using #define SUCCESS "SUCCESS"?
Which leads me to the next case, defines:
I'm using MQTT and have the topics defined like above, e.g. #define TOPIC_COLOR "light/color". Is this fine?
A third one is with ArduinoJSON:
I'm using Strings as keys, like so lights["red"] = redVal;. This call is made at multiple places so I assume the string would be created multiple times? A workaround/improvement I've thought of is using an enum defining the properties and using that as key.
Thanks for all comments, tips and explanations!

+1 to @majenko's comments. I tend to avoid the String class, as I like to know what is actually going on, and I stick to char * and char [] in general (and the stdlib functions like sprintf, strlen, etc).
Couple of notes on your question:

"foo/bar" is fine. Some characters have special meanings in the C language itself, so you need to escape them with the \. For example if " was part of your literal string, you'd write "foo\"bar\""

I tend to use ArduinoJSON to parse. If my app is just sending JSON payloads, I just build it with sprintf or print which results in smaller programs. But, I guess it is a matter of choice. It is a great library.


Powering 3.3v sensors from a coin cell I want to build some small wireless temperature measurement boards, to sprinkle around the house. I'd like to power these from a single coin cell battery (CR2032).

For these I'd like to use the DS18B20 sensor. These sensor require a minimal voltage of 3v. A coin cell will however only provide 3v when it's full, and will drop to around 2.6v when 90% discharged.

From what I've read the DS18B20 will give some strange results when the supply voltage is below 3v. Also the precision can be off, when the supply voltage isn't regulated.

(The ATMega328p and NRF24L01, I plan to use, will work just fine at voltages down to 2v, so only the DS18B20 requires 3.3v.)

So I've come up with the following solutions:

Use two coin cells, and a (low quiescent current) voltage regulator. (Disadvantage: takes more space, more batteries, slightly more expensive.)
Use a boost regulator. (Disadvantage: even more expensive, and a lot more complex (for me at least).)
Implement a voltage doubler to power the DS18B20 when needed (every 15 minutes). To regulate the voltage I'd add a 3.3v zener diode to the output. (dirt cheap to implement)

I tend to lean toward option 3, but my question is, could it even work?

Is there something to look out for?

Or is there an even better solution?

edit I was planning to use the Dickson doubler circuit.

You're missing out option 4, which is the option I would personally go for:

Use a different temperature sensor.

A quick parametric search on Microchip (my favourite, I'm a Microchip fanboy after all...) I find quite a nice one - the MCP9844.

  Microchip Technology Inc.’s MCP9844 digital temperature sensor converts temperature from -40°C and +125°C to a digital word. This sensor meets JEDEC Specification JC42.4-TSE2004B1 mobile Platform Memory Module Thermal Sensor Component. It provides an accuracy of ±0.2°C/±1°C (typical/maximum) from +75°C to +95°C.

  Operating Voltage Range (V): +1.7 to +3.6

However it is only available as a TDFN which makes prototyping difficult, although it is one of my two preferred footprints for real building - the other being variants of QFN.

I am sure you can search other makers for similarly specified chips that will do the job without the need for fancy boosters or doublers or the expense of multiple batteries etc.

One of the first steps of any design is the component identification. Often the chip or component that many people automatically reach for because it's the first one they used, or it's the one people most often talk about, may not be the right tool for the job. It pays to shop around a bit and look to see if there is something better that will fit the bill and save cost and time in the long run by ending up with a simpler system.


How to dynamically switch between between 2 objects? I have a 40x4 LCD which internally consists of 2 40x2 LCDs.
To control this LCD I have to create 2 LiquidCrystal objects and than later on in code decide which one to use depending on which of the 4 lines I want to change.

Due to the size of my project, I split all the LCD handling off to a separate class.
To make my code as readable and easy as possible, I want to create a member method of this class, to which I can just pass line number 1-4, and have this method take care of deciding which LiquidCrystal object to use.

LCDController.h:

#include <LiquidCrystal.h>
class LCDControllerClass
{
 protected:

 public:
        void init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2);
 private:
   void _UpdateLCD(int _iLine, int _iPosition, String _strText, int _iFieldLength);
   LiquidCrystal* _Clcd1;
   LiquidCrystal* _Clcd2;
};
extern LCDControllerClass LCDController;

My 2 LiquidCrystal objects are initialized in my main .ino file like so (before the setup() loop)
:

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

These two objects are then passed as pointers to my LCDControllerClass like so:

LCDController.init(&lcd, &lcd2);

The init() member method of my LCDControllerClass then puts these pointers in private variables like so:

void LCDControllerClass::init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1->begin(40, 2);
   _Clcd1->clear();

   _Clcd2 = Clcd2;
   _Clcd2->begin(40, 2);
   _Clcd2->clear();
}

Then I have another private member method which should take care of updating the correct LCD object:

void LCDControllerClass::_UpdateLCD(int _iLine, int _iPosition, String _strText, int _iFieldLength)
{
   LiquidCrystal* CActiveLCD;
   if (_iLine > 2)
   {
      //DisplayLine is higher than 2, this means we need to update the 2nd LCD
      LiquidCrystal** CActiveLCD = &_Clcd2;
      _iLine = _iLine - 2; //Convert line number to correct line number for 2nd display
   }
   else
   {
      //LiquidCrystal** CActiveLCD = &_Clcd1;
   }
   /* we have to convert this number
      to a real display line (0-1) by substracting 1 again
   */
   _iLine = _iLine - 1;

   CActiveLCD->setCursor(_iPosition, _iLine);
   CActiveLCD->print(_strText);
}

Now in this last member mehthor my code goes into the woods for some reason. The LCD is not updated at all and it seems the arduino is freezing as well since I put a small Serial.print() test in the main loop and it's not printing anything...

What is the correct way to pass the correct LiquidCrystal object to the CActiveLCD
object?

The problem is that you're declaring multiple pointer variables called CActiveLCD in the _UpdateLCD() function. You do it once at the start of the function like this:

LiquidCrystal* CActiveLCD;

You then declare a new and totally separate pointer inside the if block like this:

LiquidCrystal** CActiveLCD = &_Clcd2;

This is called masking. The original pointer you declared at the start of the function still exists, but you can't access it because it's temporarily replaced by the new one. When the if block finishes, that new pointer is destroyed (it goes out of scope) and the old one is available again.

All of that means you never actually store a value in the original pointer variable. The result is that it contains an arbitrary memory address, so attempting to use it at the end of the function results in undefined behaviour.

When you are assigning to the pointer inside your if block, you need to do it like this:

CActiveLCD = _Clcd2;

Notice that this doesn't declare a new CActiveLCD pointer. It simply copies _Clcd2 into the existing one. Additionally, it's important not to use the address-of operator here (&). Adding that in this context gives you a pointer-to-a-pointer. It is technically legitimate in C++, and sometimes does serve a useful purpose, but it's not what you want to do here.

As a side note, when declaring a pointer variable it's usually a good idea to initialise it to something. If you're not assigning an actual address to it right away then initialise it to 0, like this:

LiquidCrystal* CActiveLCD = 0;

This means you can check the pointer later on before using it. If it's 0 then you know it's not got a valid address yet so it's not safe to use. This isn't always strictly necessary, but it can help avoid some frustrating bugs.


P I D AND GY80 10 DOF I am running the program for GY80 10 DOF , and runs fine . Date is printed on the serial monitor
How ever I have failed to use this program for my WalkerBot
(walker bot is a Robotic suit that I want to build for 4 years old my grand son He can not walk due to C P )
Unless the PID is not introduced in the program it will not be good for Balancing of the walker Both the program is as under , and my further questions are in comments
I need help Please
I tried to use the Code Control to insert the codes But it did not work , I may be excused for that Please

the codes

  #include <Wire.h>
  #include <GY80.h>

     GY80 sensor = GY80(); //create GY80 instance

  void setup()
  {
    // initialize serial communication at 115200 bits per second:
    Serial.begin(115200);
    sensor.begin();       //initialize sensors
  }

     // How to envelop this program with PID
     // where the gyro output is supposed to maintain the vertical position of the //bot , and the accelerometer will be doing countermeasure of tilts
// unless they both are on a feedback with PID this bot will not balance
//as the servomotors if do not respond in runtime the bot will fall
void loop()
{
    GY80_scaled val = sensor.read_scaled();       //get values from all sensors
    // print out values

    Serial.print("Mag:");                         //magnetometer values
    Serial.print(val.m_x,2);
    Serial.print(',');
    Serial.print(val.m_y,2);
// tried to get some output from here for using in PID but failed
if(val.m_y,2 >2 ||val.m_y,2<0){Serial.print("Output has been managed");}
but there was no output
    Serial.print(',');
    Serial.print(val.m_z,2);
    Serial.print(' ');
    Serial.print("Acc:");                         //accelerometer values
    Serial.print(val.a_x,3);
    Serial.print(',');
    Serial.print(val.a_y,3);
    Serial.print(',');
    Serial.print(val.a_z,3);
    Serial.print(' ');
    Serial.print("Gyro:");                        //gyroscope values
    Serial.print(val.g_x,1);
    Serial.print(',');
    Serial.print(val.g_y,1);
    Serial.print(',');
    Serial.print(val.g_z,1);
    Serial.print(' ');
    Serial.print("P:");                           //pressure values
    Serial.print(val.p,5);
    Serial.print(' ');
    Serial.print("T:");                           //temperature values
    Serial.println(val.t,1);

    delay(250);        // delay in between reads for stability
}

I am sorry, but I may not have understood your post, but I think the problem is your code doesn't work and you don't know why.  I think the problem is with this line:

if(val.m_y,2 >2 ||val.m_y,2<0){

It is because it is not valid code, I suspect its a cut and paste error and should be

if(val.m_y > 2.0 || val.m_y < 0.0){

the ,2 you use in the print statements specifies the number of digits to print after the decimal point (I think).


Is it possible to find the time taken by millis? The function millis would be running in the span of 100+ microseconds or less. Is there a reliable way to go about measuring the time taken by a single millis call?

One approach that comes to mind is using micros, however, a call to micros will include the time taken by the function call of micros itself as well, so depending on how long micros takes, the measurement for millis may be off.

I need to find this as an application I am working on requires accurate time measurements for every step taken in the code, including millis.

If you want to know exactly how long something will take, there is only one solution: Look at the disassembly!

Starting with the minimal code:

void setup(){};

volatile uint16_t x;
void loop()
{
  x = millis();

}

This code compiled and then fed into avr-objdump -S produces a documented disassembly. Here are the interesting excerpts:

void loop() produces:

000000a8 <loop>:
  a8:   0e 94 a7 00     call    0x14e   ; 0x14e <millis>
  ac:   60 93 00 01     sts 0x0100, r22
  b0:   70 93 01 01     sts 0x0101, r23
  b4:   80 93 02 01     sts 0x0102, r24
  b8:   90 93 03 01     sts 0x0103, r25
  bc:   08 95           ret

Which is a function call (call), four copies (which copy each of the bytes in the uint32_t return value of millis() (note that the arduino docs call this a long, but they are incorrect to not be explicitly specifying the variable sizes)), and finally the function return.

call requires 4 clock cycles, and each sts requires 2 clock cycles, so we have a minimum of 12 clock cycles just for function call overhead.

Now, lets look at the disassembly of the <millis> function, which is located at 0x14e:

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;
 14e:   8f b7           in  r24, 0x3f   ; 63

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
 150:   f8 94           cli
    m = timer0_millis;
 152:   20 91 08 01     lds r18, 0x0108
 156:   30 91 09 01     lds r19, 0x0109
 15a:   40 91 0a 01     lds r20, 0x010A
 15e:   50 91 0b 01     lds r21, 0x010B
    SREG = oldSREG;
 162:   8f bf           out 0x3f, r24   ; 63

    return m;
}
 164:   b9 01           movw    r22, r18
 166:   ca 01           movw    r24, r20
 168:   08 95           ret

As you can see, the millis() function is fairly simple:

in saves the interrupt register settings (1 cycle)
cli turns off the interrupts (1 cycle)
lds copy one of the 4 bytes of the current value of the milli counter into a temporary register (2 clock cycles)
lds Byte 2 (2 clock cycles)
lds Byte 3 (2 clock cycles)
lds Byte 4 (2 clock cycles)
out restore interrupt settings (1 clock cycle)
movw shuffle registers around (1 clock cycle)
movw and again (1 clock cycle)
ret return from subroutine  (4 cycles)

So, if we add them all up, we have a total of 17 clock cycles in the millis() function itself, plus a call overhead of 12, for a total of 29 clock cycles.

Assuming a 16 Mhz clock rate (most arduinos), each clock cycle is 1 / 16e6 seconds, or 0.0000000625 seconds, which is 62.5 nanoseconds. 62.5 ns * 29 = 1.812 microseconds.

Therefore, the total execution time for a single millis() call on most Arduinos will be 1.812 microseconds.

AVR Assembly reference

As a side-note, there is space for optimization here! If you update the unsigned long millis(){} function definition to be inline unsigned long millis(){}, you would remove the call overhead (at the cost of slightly larger code size). Furthermore, it looks like the compiler is doing two unnecessary moves (the two movw calls, but I haven't looked at it that closely).

Really, considering the function call overhead is 5 instructions, and the actual contents of the millis() function is only 6 instructions, I think the millis() function should really be inline by default, but the Arduino codebase is rather poorly optimized.

Here is the full disassemby for anyone interested:

sketch_feb13a.cpp.elf:     file format elf32-avr

Disassembly of section .text:

00000000 <__vectors>:
    SREG = oldSREG;

    return m;
}

unsigned long micros() {
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   8:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  10:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  14:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  18:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  1c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  20:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  24:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  28:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  2c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  30:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  34:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  38:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  3c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  40:   0c 94 5f 00     jmp 0xbe    ; 0xbe <__vector_16>
  44:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  48:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  4c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  50:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  54:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  58:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  5c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  60:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  64:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>

00000068 <__ctors_end>:
  68:   11 24           eor r1, r1
  6a:   1f be           out 0x3f, r1    ; 63
  6c:   cf ef           ldi r28, 0xFF   ; 255
  6e:   d8 e0           ldi r29, 0x08   ; 8
  70:   de bf           out 0x3e, r29   ; 62
  72:   cd bf           out 0x3d, r28   ; 61

00000074 <__do_copy_data>:
  74:   11 e0           ldi r17, 0x01   ; 1
  76:   a0 e0           ldi r26, 0x00   ; 0
  78:   b1 e0           ldi r27, 0x01   ; 1
  7a:   e2 e0           ldi r30, 0x02   ; 2
  7c:   f2 e0           ldi r31, 0x02   ; 2
  7e:   02 c0           rjmp    .+4         ; 0x84 <.do_copy_data_start>

00000080 <.do_copy_data_loop>:
  80:   05 90           lpm r0, Z+
  82:   0d 92           st  X+, r0

00000084 <.do_copy_data_start>:
  84:   a0 30           cpi r26, 0x00   ; 0
  86:   b1 07           cpc r27, r17
  88:   d9 f7           brne    .-10        ; 0x80 <.do_copy_data_loop>

0000008a <__do_clear_bss>:
  8a:   11 e0           ldi r17, 0x01   ; 1
  8c:   a0 e0           ldi r26, 0x00   ; 0
  8e:   b1 e0           ldi r27, 0x01   ; 1
  90:   01 c0           rjmp    .+2         ; 0x94 <.do_clear_bss_start>

00000092 <.do_clear_bss_loop>:
  92:   1d 92           st  X+, r1

00000094 <.do_clear_bss_start>:
  94:   ad 30           cpi r26, 0x0D   ; 13
  96:   b1 07           cpc r27, r17
  98:   e1 f7           brne    .-8         ; 0x92 <.do_clear_bss_loop>
  9a:   0e 94 f0 00     call    0x1e0   ; 0x1e0 <main>
  9e:   0c 94 ff 00     jmp 0x1fe   ; 0x1fe <_exit>

000000a2 <__bad_interrupt>:
  a2:   0c 94 00 00     jmp 0   ; 0x0 <__vectors>

000000a6 <setup>:
  a6:   08 95           ret

000000a8 <loop>:
  a8:   0e 94 a7 00     call    0x14e   ; 0x14e <millis>
  ac:   60 93 00 01     sts 0x0100, r22
  b0:   70 93 01 01     sts 0x0101, r23
  b4:   80 93 02 01     sts 0x0102, r24
  b8:   90 93 03 01     sts 0x0103, r25
  bc:   08 95           ret

000000be <__vector_16>:
#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
  be:   1f 92           push    r1
  c0:   0f 92           push    r0
  c2:   0f b6           in  r0, 0x3f    ; 63
  c4:   0f 92           push    r0
  c6:   11 24           eor r1, r1
  c8:   2f 93           push    r18
  ca:   3f 93           push    r19
  cc:   8f 93           push    r24
  ce:   9f 93           push    r25
  d0:   af 93           push    r26
  d2:   bf 93           push    r27
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long m = timer0_millis;
  d4:   80 91 08 01     lds r24, 0x0108
  d8:   90 91 09 01     lds r25, 0x0109
  dc:   a0 91 0a 01     lds r26, 0x010A
  e0:   b0 91 0b 01     lds r27, 0x010B
    unsigned char f = timer0_fract;
  e4:   30 91 0c 01     lds r19, 0x010C

    m += MILLIS_INC;
  e8:   01 96           adiw    r24, 0x01   ; 1
  ea:   a1 1d           adc r26, r1
  ec:   b1 1d           adc r27, r1
    f += FRACT_INC;
  ee:   23 2f           mov r18, r19
  f0:   2d 5f           subi    r18, 0xFD   ; 253
    if (f >= FRACT_MAX) {
  f2:   2d 37           cpi r18, 0x7D   ; 125
  f4:   20 f0           brcs    .+8         ; 0xfe <__vector_16+0x40>
        f -= FRACT_MAX;
  f6:   2d 57           subi    r18, 0x7D   ; 125
        m += 1;
  f8:   01 96           adiw    r24, 0x01   ; 1
  fa:   a1 1d           adc r26, r1
  fc:   b1 1d           adc r27, r1
    }

    timer0_fract = f;
  fe:   20 93 0c 01     sts 0x010C, r18
    timer0_millis = m;
 102:   80 93 08 01     sts 0x0108, r24
 106:   90 93 09 01     sts 0x0109, r25
 10a:   a0 93 0a 01     sts 0x010A, r26
 10e:   b0 93 0b 01     sts 0x010B, r27
    timer0_overflow_count++;
 112:   80 91 04 01     lds r24, 0x0104
 116:   90 91 05 01     lds r25, 0x0105
 11a:   a0 91 06 01     lds r26, 0x0106
 11e:   b0 91 07 01     lds r27, 0x0107
 122:   01 96           adiw    r24, 0x01   ; 1
 124:   a1 1d           adc r26, r1
 126:   b1 1d           adc r27, r1
 128:   80 93 04 01     sts 0x0104, r24
 12c:   90 93 05 01     sts 0x0105, r25
 130:   a0 93 06 01     sts 0x0106, r26
 134:   b0 93 07 01     sts 0x0107, r27
}
 138:   bf 91           pop r27
 13a:   af 91           pop r26
 13c:   9f 91           pop r25
 13e:   8f 91           pop r24
 140:   3f 91           pop r19
 142:   2f 91           pop r18
 144:   0f 90           pop r0
 146:   0f be           out 0x3f, r0    ; 63
 148:   0f 90           pop r0
 14a:   1f 90           pop r1
 14c:   18 95           reti

0000014e <millis>:

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;
 14e:   8f b7           in  r24, 0x3f   ; 63

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
 150:   f8 94           cli
    m = timer0_millis;
 152:   20 91 08 01     lds r18, 0x0108
 156:   30 91 09 01     lds r19, 0x0109
 15a:   40 91 0a 01     lds r20, 0x010A
 15e:   50 91 0b 01     lds r21, 0x010B
    SREG = oldSREG;
 162:   8f bf           out 0x3f, r24   ; 63

    return m;
}
 164:   b9 01           movw    r22, r18
 166:   ca 01           movw    r24, r20
 168:   08 95           ret

0000016a <init>:

void init()
{
    // this needs to be called before setup() or some functions won't
    // work there
    sei();
 16a:   78 94           sei

    // on the ATmega168, timer 0 is also used for fast hardware pwm
    // (using phase-correct PWM would mean that timer 0 overflowed half as often
    // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
    sbi(TCCR0A, WGM01);
 16c:   84 b5           in  r24, 0x24   ; 36
 16e:   82 60           ori r24, 0x02   ; 2
 170:   84 bd           out 0x24, r24   ; 36
    sbi(TCCR0A, WGM00);
 172:   84 b5           in  r24, 0x24   ; 36
 174:   81 60           ori r24, 0x01   ; 1
 176:   84 bd           out 0x24, r24   ; 36
    // this combination is for the standard atmega8
    sbi(TCCR0, CS01);
    sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
    // this combination is for the standard 168/328/1280/2560
    sbi(TCCR0B, CS01);
 178:   85 b5           in  r24, 0x25   ; 37
 17a:   82 60           ori r24, 0x02   ; 2
 17c:   85 bd           out 0x25, r24   ; 37
    sbi(TCCR0B, CS00);
 17e:   85 b5           in  r24, 0x25   ; 37
 180:   81 60           ori r24, 0x01   ; 1
 182:   85 bd           out 0x25, r24   ; 37

    // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
    sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
    sbi(TIMSK0, TOIE0);
 184:   ee e6           ldi r30, 0x6E   ; 110
 186:   f0 e0           ldi r31, 0x00   ; 0
 188:   80 81           ld  r24, Z
 18a:   81 60           ori r24, 0x01   ; 1
 18c:   80 83           st  Z, r24
    // this is better for motors as it ensures an even waveform
    // note, however, that fast pwm mode can achieve a frequency of up
    // 8 MHz (with a 16 MHz clock) at 50% duty cycle

#if defined(TCCR1B) && defined(CS11) && defined(CS10)
    TCCR1B = 0;
 18e:   e1 e8           ldi r30, 0x81   ; 129
 190:   f0 e0           ldi r31, 0x00   ; 0
 192:   10 82           st  Z, r1

    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
 194:   80 81           ld  r24, Z
 196:   82 60           ori r24, 0x02   ; 2
 198:   80 83           st  Z, r24
#if F_CPU >= 8000000L
    sbi(TCCR1B, CS10);
 19a:   80 81           ld  r24, Z
 19c:   81 60           ori r24, 0x01   ; 1
 19e:   80 83           st  Z, r24
    sbi(TCCR1, CS10);
#endif
#endif
    // put timer 1 in 8-bit phase correct pwm mode
#if defined(TCCR1A) && defined(WGM10)
    sbi(TCCR1A, WGM10);
 1a0:   e0 e8           ldi r30, 0x80   ; 128
 1a2:   f0 e0           ldi r31, 0x00   ; 0
 1a4:   80 81           ld  r24, Z
 1a6:   81 60           ori r24, 0x01   ; 1
 1a8:   80 83           st  Z, r24

    // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
 1aa:   e1 eb           ldi r30, 0xB1   ; 177
 1ac:   f0 e0           ldi r31, 0x00   ; 0
 1ae:   80 81           ld  r24, Z
 1b0:   84 60           ori r24, 0x04   ; 4
 1b2:   80 83           st  Z, r24

    // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
    sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
    sbi(TCCR2A, WGM20);
 1b4:   e0 eb           ldi r30, 0xB0   ; 176
 1b6:   f0 e0           ldi r31, 0x00   ; 0
 1b8:   80 81           ld  r24, Z
 1ba:   81 60           ori r24, 0x01   ; 1
 1bc:   80 83           st  Z, r24
#if defined(ADCSRA)
    // set a2d prescale factor to 128
    // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
    // XXX: this will not work properly for other clock speeds, and
    // this code should use F_CPU to determine the prescale factor.
    sbi(ADCSRA, ADPS2);
 1be:   ea e7           ldi r30, 0x7A   ; 122
 1c0:   f0 e0           ldi r31, 0x00   ; 0
 1c2:   80 81           ld  r24, Z
 1c4:   84 60           ori r24, 0x04   ; 4
 1c6:   80 83           st  Z, r24
    sbi(ADCSRA, ADPS1);
 1c8:   80 81           ld  r24, Z
 1ca:   82 60           ori r24, 0x02   ; 2
 1cc:   80 83           st  Z, r24
    sbi(ADCSRA, ADPS0);
 1ce:   80 81           ld  r24, Z
 1d0:   81 60           ori r24, 0x01   ; 1
 1d2:   80 83           st  Z, r24

    // enable a2d conversions
    sbi(ADCSRA, ADEN);
 1d4:   80 81           ld  r24, Z
 1d6:   80 68           ori r24, 0x80   ; 128
 1d8:   80 83           st  Z, r24
    // here so they can be used as normal digital i/o; they will be
    // reconnected in Serial.begin()
#if defined(UCSRB)
    UCSRB = 0;
#elif defined(UCSR0B)
    UCSR0B = 0;
 1da:   10 92 c1 00     sts 0x00C1, r1
#endif
}
 1de:   08 95           ret

000001e0 <main>:
#include <Arduino.h>

int main(void)
 1e0:   cf 93           push    r28
 1e2:   df 93           push    r29
{
    init();
 1e4:   0e 94 b5 00     call    0x16a   ; 0x16a <init>

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();
 1e8:   0e 94 53 00     call    0xa6    ; 0xa6 <setup>

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
 1ec:   c0 e0           ldi r28, 0x00   ; 0
 1ee:   d0 e0           ldi r29, 0x00   ; 0
#endif

    setup();

    for (;;) {
        loop();
 1f0:   0e 94 54 00     call    0xa8    ; 0xa8 <loop>
        if (serialEventRun) serialEventRun();
 1f4:   20 97           sbiw    r28, 0x00   ; 0
 1f6:   e1 f3           breq    .-8         ; 0x1f0 <main+0x10>
 1f8:   0e 94 00 00     call    0   ; 0x0 <__vectors>
 1fc:   f9 cf           rjmp    .-14        ; 0x1f0 <main+0x10>

000001fe <_exit>:
 1fe:   f8 94           cli

00000200 <__stop_program>:
 200:   ff cf           rjmp    .-2         ; 0x200 <__stop_program>


How I can send data information without work WiFi to LCD? Hi everyone I am beginning learn coding and the second language English. I have small project I use Arduino uno , esp8266 , dht11 , lcd I2C and use blynk app in my project I have the code and work probably when WiFi ON but I have question How I can get the information data from dht to lcd without open the WiFi. Now I get information ( Temp and humidity ) on LCD when WiFi ON only. How I can make Temp and humidity display on LCD with and without WiFi.
#include <BlynkSimpleShieldEsp8266.h>
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 20, 4);
char auth[] = "*******************************";
char ssid[] = "***********";
char pass[] = "*********";
#include <SoftwareSerial.h>
SoftwareSerial EspSerial(2, 3); // TX, RX
#define ESP8266_BAUD 9600
ESP8266 wifi(&EspSerial);
#define DHTPIN 8
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup()
{
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  EspSerial.begin(ESP8266_BAUD);
  Blynk.begin(auth, wifi, ssid, pass);
  dht.begin();
}

void loop()
{
  LCD();
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  Blynk.virtualWrite(V1, t);
  Blynk.virtualWrite(V2, h);
}
void LCD()
{
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(" ******************");
  lcd.setCursor(3, 1);
  lcd.print("TEMP: ");
  lcd.print(t);
  lcd.setCursor(3, 2);
  lcd.print("HUM : ");
  lcd.print(h);
}

Blynk.connected() returns true when hardware is connected to Blynk Server, so you can guard Blynk code with
if( Blynk.connected() ){
  // do Blynk things here
}

// Update the LCD anywhere outside of the above "if" statement.


Use Adafruit Colorsensor to distinguish between green and red I am using the Adafruit TCS34725 to sense color. I have used the Colorview code example to set it up to sense all colors, works great. The thing I want is for it to tell me if it is seeing either green or red, I don't care about the other colors.

Can anyone suggest what I can do?

Based on what I could find, you will have to calibrate the sensor to recognize these colours. First, run the Colourview code. Take down the raw RGB and CLEAR values obtained for an object you consider green and another you consider red. Find out if these values are consistent, each time you power down the sensor and turn it on again. If they aren't, record how much dead zone there is i.e. the maximum difference in readings (between resets) that you get for the same colour. Then using the values you get, try this code:

#include <Wire.h>
#include "Adafruit_TCS34725.h"

#define MAX_OFFSET 50  // the maximum diff you found between readings

typedef struct {  // struct to hold raw color data
   uint16_t red;
   uint16_t green;
   uint16_t blue;
   uint16_t clear;
} Color;

Color my_red = {3344, 3333, 23444, 3333}; //here you enter your minimum recorded values for red in the order of the struct members above
Color my_green = {22222, 4444, 5555, 3333}; //the same for green

void setup() {
  Serial.begin(9600);
  Serial.println("Color View Test!");

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1); // halt!
  }
}

void loop() {
  uint16_t clear, red, green, blue;

  tcs.setInterrupt(false);      // turn on LED

  delay(60);  // takes 50ms to read

  tcs.getRawData(&red, &green, &blue, &clear);

  tcs.setInterrupt(true);  // turn off LED
  if (compare_colour(&my_red, red, green, blue, clear)){
      Serial.println("I see red.");
  }
  else if (compare_colour(&my_green, red, green, blue, clear)){
      Serial.println("I see green.");
  }
}

boolean compare_color(Color * std, uint16_t r, uint16_t g, uint16_t b, uint16_c){
if ((r - std.red <= MAX_OFFSET) && (r - std.red >= 0) &&
      (g - std.green <= MAX_OFFSET) && (g - std.green >= 0) &&
      (b - std.blue <= MAX_OFFSET) && (b - std.blue >= 0) &&
      (c - std.clear <= MAX_OFFSET) && (c - std.clear >= 0))
  {
      return true;
  }
  return false;
}

You can use this code directly after you have gotten the sensor readings for red and green objects.


ESP8266 WiFi Not Connecting to Internet Without Static IP I am seeing some very strange behavior with my ESP8266. When I connect it to the WiFi for the first couple of times I am not seeing any issues and the ESP8266 connects just fine.
But after an arbitrary amount of times (like when I restart the unit) it tries to connect for AGES (like multiple minutes). Eventually it says "Connected" but the IP is completely wrong and it is not connected to the internet (GET request fails).
Here are the odd things:

If I assign a static IP then it ALWAYS works and connects within seconds
If I factory reset my router then it works again for a few times
I have not seen this with any other device (like laptops or cellphones)

It is almost as if the DHCP is failing to assign an IP and then returns some random default.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

// Replace these with your WiFi network settings
const char* ssid = "MYSSID"; //replace this with your WiFi network name
const char* password = "MYPASSWORD"; //replace this with your WiFi network password

void setup() {
  Serial.begin(115200);
  delay(1000);

  IPAddress ip(192,168,1,77);
  IPAddress gateway(192,168,1,1);
  IPAddress subnet(255,255,255,0);

// If I uncomment this line then it works fine
//  WiFi.config(ip, gateway, subnet);

  WiFi.begin(ssid, password);

  Serial.println();
  Serial.print("Connecting");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("success!");
  Serial.print("IP Address is: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  HTTPClient http;

  String serverPath = "http://www.google.com";
  http.begin(serverPath.c_str());

  // Send HTTP GET request
  int httpResponseCode = http.GET();
  Serial.print("HTTP Response code: ");
  Serial.println(httpResponseCode);
  String payload = http.getString();
  Serial.println(payload);
  // Free resources
  http.end();

  delay(1000);
}

When DHCP magically works it assigns: 192.168.1.159
When DHCP does not work I get: 169.254.104.241
When I use a static IP then the static IP is assigned.
So the question is: Has anyone seen this behavior and maybe give some hints about how I can get the internet connection to be consistent without needing a static IP?
Update:
If I run a ping to 169.254.104.241 I get a reply. But if I try to get anything from the internet I get HTTP Response Code = -1.

This is normal behavior. well not really, that address is called a apipa address.
It's normal behavior for alot of O.S's to give itself an address in the 169.254.x.x range when they fail to get DHCP responses.
My guess is your library is doing this for you.
It's kind of like the ad-hoc of addressing, if all devices fail to get a dhcp response they will all be assigned to the same subnet, and can communicate with those apipa addresses.
My suspicion is that it may be your router.
You can verify this by downloading a free DHCP server application for your OS. Plug in via Ethernet for the PC that's running the DHCP App, Turn off DHCP in the router. If it stops happening you know it's the router.
Edit: Also, this may be a firmware caveat in the router. Check the router manufacturers website and see if any firmware updates are available. if it hangs with DHCP, most likely every customer with that firmware revision has had this problem. This sort of thing usually gets patched very quickly.


Making three led's blink at different times in Arduino I have a breadboard connected to an Arduino Uno, 220k resistors connected to an led, of course it has a common ground and a pin connected to 5v. All pins are digital.

Now, I want led 1 to turn on for one second, the next led for two seconds and the next for three seconds, but that means, when the second led which has to be on for two seconds then the first led will come back on after one second has past on the second led, the third led would be on for three seconds, so the second led will also be on when two seconds pass and the first would be on when one second passes. So basically, all leds are on for their given duration.

How do I do this? I have been trying to do this since three days. It would be a pleasure if someone helps me out. Thanks.

int ledPin1= 2;
int ledPin2 = 4;
int ledPin3 = 7;

void setup(){
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  }

  void loop(){
  digitalWrite(ledPin1, HIGH);
  delay(500);
  digitalWrite(ledPin1, LOW);
  delay(500);

  digitalWrite(ledPin2, HIGH);
  delay(1000);
  digitalWrite(ledPin2, LOW);
  delay(1000);

  digitalWrite(ledPin3, HIGH);
  delay(1500);
  digitalWrite(ledPin3, LOW);
  delay(1500);
    }

So far this is the code. But it delays the whole program. Need leds on at given times.

Using a 220k Ohm resistor will lead to approximatively 20µA to light the LED. This is not enough to light the LED, you should replace the resitor by one of value 330Ohm (220 to 470 could be OK depending of the LED)


Wake up Arduino Uno by RTC I intend to make the device runs about couple hours a day(let say 2hrs) -> go to deep sleep -> wake up in next 7 days -> repeat the process.

I got the code from one of member here (DotPi) which I can able to make the device wake up every 10 seconds and then back to sleep. When it wakes up, the LED is flashing.

My question is how to make the LED flashes for certain amount of time. For example from 7pm to 8 pm. After that the device should go to sleep again and wait for the next alarm triggered.

I was trying to use the while loop for that but the LED always flash and never go back to sleep :(

In your while loop, you never check the time again, so when the while loops hits, you will never leave it. You need to request the time again. Something like:

while ( now.minute()>0 && now.minute() < 30)
{
   digitalWrite(ledPin, HIGH);
   delay(100);
   digitalWrite(ledPin, LOW);
   delay(1000);
   now = rtc.now(); // check time again
}


Error while inputting EEPROM.read() and EEPROM.write() I am trying to store data in ATmega328 (Arduino Uno) using the following code using tinkercad:
#include <EEPROM.h>

void setup() {
  int addr, data=1;
  Serial.begin(9600);
  for (addr=0; addr<1023; addr++) {
    EEPROM.write(addr, data);
  }
  for (addr=0; addr<1023 ; addr++) {
    Serial.print(EEPROM.read(addr), DEC);
  }
}

When I simulate the code in the tinkercad, then i get the following error:
In function `main':
43: undefined reference to `loop'
 error: ld returned 1 exit status

Please help me where is the error in my code. I am not able to understand the error source.

Have you looked at any Arduino IDE example programs?
They all have a setup() and loop() function.
Apparently, Tinkercad is missing the loop() function in your code.
You can solve the issue by adding an empty void loop() { } after your void setup() { ... } code.


AnalogRead always 1023 on Arduino Due? Just using the Basic Example AnalogReadSerial.

// the setup routine runs once when you press reset:
  void setup()
{
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop()
{
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

I have a basic voltage divider set up between two 10K resistors from 5V to GND. I have verified with a DMM that the DC voltage at pin A0 is 2.5V. Grounding the A0 pin has no effect.

It also seems that enabling either ADC channel 7 (Arduino pin AD0) or enabling every channel, putting the ADC in free-running mode, and deliberately setting it to not sleep has no effect:

ADC->ADC_CHDR = 0;
ADC->ADC_CHER |= 0xFF;
ADC->ADC_MR |= 0b10000000;
ADC->ADC_MR &= 0b11011111;

Also, by running the sketch DigitalInputPullup, I can get the LED on pin 13 to toggle and serial communication to work as I tie the pin to ground, demonstrating that the board is being programmed properly.

I guess I'm just stumped. Should be the simplest thing in the world and it's just not working.

EDIT:
This is my attempt at manually controlling the ADC:

volatile unsigned long value;

void setup()
{
  //ADC setup
  ADC->ADC_WPMR &= 0xFFFE; //disable write protect
  ADC->ADC_CHER = 0b100; //Enable AD2     |
  ADC->ADC_MR &= 0b11111111000000001111111100000000;
  ADC->ADC_MR |= 0b00000000000100100000000000000000; //software trigger, hi res, no sleep, not free running
  ADC->ADC_IER = 0b100; //enable interrupt
  ADC->ADC_IMR = 0b100; //enable interrupt in mask

  ADC->ADC_CR |= 0b10; //start first conversion
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop()
{
  ADC->ADC_CR |= 0b10; //start conversion
  while (!(ADC->ADC_ISR & 0b100)); //wait for conversion to end

  for (int i = 0; i <= 15; i++)
 {
    value = ADC->ADC_CDR[i]; //read conversion data for all channels
    Serial.println(value);
 }

 Serial.println();
 Serial.println();
 Serial.println();

 delay(3000);
}

Just doesn't seem to be doing anything. ADC_CHSR (the ADC channel status register) shows channel 2 and only channel 2 enabled and conversions are starting and completing, yet now the conversion data is always 2048. Here's the serial output of all 15 channels, now in 12 bit mode:

0
0
4095
0
0
0
0
0
0
0
0
0
0
0
0
0

0
0
4095
0
0
0
0
0
0
0
0
0
0
0
0
0

You need to add this to your setup():

pinMode(A0, INPUT);

...to set the pin for reading.

Since you're reading an input that's already pulled up (in the middle of a voltage divider), that should be all. However, you can turn on the internal pull-up with:

digitalWrite(A0, HIGH);

...while the pin is in input mode.

More details here:

http://arduino.cc/en/Reference/PinMode

http://arduino.cc/en/Tutorial/AnalogInputPins


Fill an Array with Values I have a function in which I change the pinMode on many of my Arduino's pins based on a passed in mode. I first construct an array of bytes specifying each pin to be an input or an output and then I iterate through the array to set all the pins.

void pinout(byte mode) {
  switch(mode) {
    case 0: char pins[13] = {'O','O','I','I','O','I','I','I','I','O','I','I','O'}; break;
    case 1: char pins[13] = {'O','I','I','O','O','I','O','O','I','O','I','O','I'}; break;
  //etc..
  }
  for(byte i = 0; i <= 13; i++) {
    if(pins[i] == 'I') pinMode(i, INPUT);
    else pinMode(i, OUTPUT);
  }
}

However, since the array is defined inside the switch statement, I loose scope of the pins array when I move onto the for loop. I tried defining the pins[] outside of the switch statement, but then I am confused on how to populate it efficiently. These all threw errors when I tried to populate the variable inside the switch statement:

pins[0,1,2,3,...,12,13] = {...};
pins[13] = {...};
pins[] = {...};
pins = {...};

I know I could go through each entry individually, but this could be rather inefficient use of memory and computational power as I add more cases. Any ideas?

Since your values are all constant you can define them all as constant values and just select between them. The simplest way is to add an extra dimension to your arrays:

const char pins[2][13] =
    {'O','O','I','I','O','I','I','I','I','O','I','I','O'},
    {'O','I','I','O','O','I','O','O','I','O','I','O','I'}
};

for(byte i = 0; i < 13; i++) {
    if(pins[mode][i] == 'I') pinMode(i, INPUT);
    else pinMode(i, OUTPUT);
}

(Note: An array of size 13 has entries 0-12.)

However, that is very inefficient.  Since you only have two states, I and O, and there are only 13 entries, you can store each array as a single 16-bit value:

const uint16_t pins[2] = {
    0b0110111101100,
    0b1010100100110
};

for(byte i = 0; i < 13; i++) {
    if((pins[mode] & (1 << i)) pinMode(i, INPUT);
    else pinMode(i, OUTPUT);
}

(Note: the data is stored backwards - pin 0 is on the right, pin 12 on the left.)


How to pad an ascii number with leading zeros? I need to include a 3 digit ascii representation of message length number in the message header, but I am having difficulty trying to pad the number with leading '0' zeros in order to keep the number of 'length' digits needing to be appended always 3 even when the message length is only one or two digits long.

Addendum:
The problem, more specifically, is how to left-pad a char array containing the number representation.
I got as far as defining what and where, but I couldn't figure out how to shift the char[] contents right in order to insert the "0" at msglength[0].  (I tried using strcat, but that didn't work).

char msglength[4]          //(3 digits + nul)
for (int pad=1; pad<=3-strlen(msglength); pad++)
{
    // add a leading zero char to msglength, but that involves
    // somehow shifting all its contents to the right
}

This is the kind of situation where printf() comes handy:

printf("%03d", number);

prints the number in the format you described. Alas, printf() is not
part of the standard Arduino API. But you can have it, nonetheless, at
least on AVR-based Arduinos, as it is provided by the avr-libc, which is
always linked with all Arduino programs. Some setup is needed to tell
avr-libc about where is its “standard output”. We can use the macro
fdev_setup_stream() to tell it to just push the bytes through
Serial.write():

static int Serial_write(char c, FILE *) {
    if (c == '\n') Serial.write('\r');  // convert LF -> CRLF
    return Serial.write(c);
}

static FILE mystdout;

void setup() {
    Serial.begin(9600);
    stdout = &mystdout;
    fdev_setup_stream(stdout, Serial_write, NULL, _FDEV_SETUP_WRITE);
}

void loop() {
    static int count;
    printf("%03d and counting...\n", count++);
    delay(500);
}

C.f. the manual of avr-libc's
stdio.h
for details.

Pros of this method:

printf() has plenty of options to control the formatting of your
messages.
It's very standard C, understood by anyone having programmed in that
language.

Cons:

This can make your compiled program bigger than it would be if
sticking with the Arduino API.
It's not the “Arduino way”.


Use SD-Card module in combination with MKR GSM 1400 I have bought a SD Module with the following Pin-Names: VCC,GND,MOSO,MOSI,CS,SCK. I've found many tutorials on how to use it with the Arduino Uno. But haven't found any on how to wire it with the MKR GSM 1400. Most of these Pin Names are written on the Board itself, but the CS-port isn't marked. (VCC and GND are obvious). So is there any tutorial on how to use them together or any more specific documentation?

Here is a Picture of the SD-Adapter I am using :

You can free choose pins used by SPI master to select slaves, but if possible use the default expected by the library.

With MKR and other SAMD Arduino boards use the same default SPI slave select pins as for AVR boards, because same libraries are used.

Ethernet library has default SS pin 10 and SD library pin 4.


Using SIMCOM SIM800 as a Bluetooth SPP Client I just bought a SIM800 module for my Arduino project and I found that I supports Bluetooth too. I have already worked with HC-05 and my Android phone.

I tried to play with this module and able to connect it successfully with my Android mobile. I am able to make a call using it, accept a call, etc. But when I tried to send text data using it (in SPP mode), I ran into problem.

I have an app called Bluetooth Terminal in my mobile with which I use to communicate with my HC-05. But with SIM800, I can't connect.

I have read all the AT commands which are used to make a SPP connection. Here's a screenshot of the PuTTy terminal where I tried to make the connection:

As you can see in the image, whenever I try to call

  AT+BTGETPROF=1

It never returns to me. I also tried the command with my Bluetooth visible in the mobile, but still no result.

Whenever I try to run the command or

  AT+BTCONNECT=1,4

My SIM800 goes into state 2 and I have to manually reset it.

Can someone please help me with this problem? I just want to use my SIM800 as a SPP client/server so that I can exchange text data with my Android APP.

Thanks in advance.

By default i see that the Android handset i used did not have SPP profile enabled. You need to open a App which enables the SPP profile to be advertised. Then after that you can get that in AT+BTGETPROF list. I made a tutorial for this, Have a look here,

https://youtu.be/zdQb8r2xRK8

and

http://www.raviyp.com/embedded/215-sim800-series-bluetooth-at-commands


Is there any limitation with Arduino Nano serial communication distance? I am trying to build Project which communicate multiple Arduino Nanos. I wanted to understand if Arudino Nano is capable of doing that, while doing research I came across post where it says communication with nano can be done up to 2-3 meter, where as my goal is up to 30 meter.

Project - I am trying intercom system, I have 4 Ring button at main gate, when user press any one of those 4 the Arduino will understand it and send to one of the 4 Arduino sitting at other place. Each Arduino will read that message if its for them they will perform activity if not they will skip it.

My problem is I am in selection mode and want know if Arduino Nano can handle that, communication is not that complex. It will be just sending 2/3 value max during communication. As I saw post of distance limitation, I just want get inputs from community. If you have any similar examples of serial communication between multiple Arduino Nano please let me know, I found several but it might save my time if I find something more similar.

For that sort of difference you are better using RS-485 instead of UART.  UART is really only designed for short-distance communication.

Converting UART to RS-232 will give an improvement, but switching to RS-485 instead will give you the ability to create a multi-drop bus for connecting more than two Arduinos together over a long distance.

UART uses 5V logic level signalling (on the normal Arduinos - 3.3V on most 32-bit boards). It has a "weak drive" and is highly susceptible to induced noise over longer distances.
RS-232 uses ±10V "Non Return to Zero" signalling. This gives far greater immunity to noise and a stronger drive for greater distances.
RS-485 (and the associated peer-to-peer RS-422) use differential signalling. This gives the greatest immunity to noise over the longest distances.

In summary:

RS-232 can be used if you only want to connect two devices together in a low noise environment.
RS-422 can be used to connect two devices together in a high noise (industrial) environment.
RS-485 can be used to connect lots of devices together in a high noise environment.

For more information on how they work there are some good Wikipedia pages:

RS-232
RS-422
RS-485

For interfacing any of these to an Arduino you will need extra hardware ("Driver Chips"). For example:

RS-232: MAX232
RS-422: MAX1184
RS-485: MAX485

There is also "CAN", which is a more modern replacement for RS-485 and is used in many industrial and automotive environments. As this is a newer technology than RS-485 there are fewer resources available and "initial cost to entry" can be higher.


How do I segment Arduino program when line count is so large that code maintenance is difficult? I'm looking for the Arduino/C++ equivalent of COBOL's 'copy' statement.

I'm working on a program that is approaching 600 lines of code in the TopLevel.cpp source file.  This is hard to manage because I feel like I spend all my time scrolling up and down the source file.  The code in question does not easily lend itself to conversion to a class because it is sections of loop/main.  I've tried using xxx.h (for storage definitions) and yyy.cpp (for code sections).  Those approaches yield error messages, which I think are due to the different timings of the Arduino pre-processor and the compiler code that resolve the #include statements.

Thanks for the help.
--CVTBrakeman

p.s.
I wrote my first program in 1967; the language was GOTRAN on an IBM 1620.  For almost 50 years, I made my living designing/writing COBOL and SAS code on IBM mainframes.  Yes, Y2K was real and I survived it.

This is more like a general programming question than an Arduino
question but, anyway...

You don't need to write classes to sort your code into files. You just
need to think in term of independent pieces of functionality. Each of
those pieces would be implemented in a .cpp file, with the interface
declared in a .h file.

As an example, let's say your Arduino is controlling an hyperdrive.
Managing the dilithium plasma generator is one of those functionalities
that can be separated in its own files. The .h files declares everything
that is needed for using that functionality:

plasma_generator.h:

// Read the state of the plasma.
float plasma_density();
float plasma_temperature();

// Control the plasma.
void set_plasma_target_temperature(float target_temperature);
void ignite_plasma();
void turn_off_plasma();
void add_dilithium(float amount);

Then the .cpp file contains the implementation:

plasma_generator.cpp:

#include "plasma_generator.h"

// A "static" function is a function private to this module.
static float get_gauge_reading(int gauge_number)
{
    ...
}

// Implementation of a public function, described in the .h file.
float plasma_density()
{
    float raw_reading = get_gauge_reading(42);
    ...
}

...

In your main program (or even in other modules, if needed) you
#include the .h file and use the functionality defined therein.


Arduino buzzer code sequence not triggering I have a problem with my arduino buzzer:
the code should be doing the following:
I have a security system where in order to open the door you have to enter a 4 digit code from the remote. If the code is correct the door opens. if not you can try again.
You have 3 chances to try to enter the pin before an alarm goes on. here comes the problem: the alarms code triggers but the buzzer isn't making any sound.
here is the code for the alarm sound:
if (tryCount>=3) { // if the pin is wrong 3 times we sound an alarm
    Serial.println("got in alarm");
    while(true) {
        Serial.println("got in while");
        noTone(buzzer);
        tone(buzzer,100,300);
        delay(300);
        noTone(buzzer);
        tone(buzzer,1000,300);
        delay(300);
    }
}

here is the proof the alarm code triggers:

here is the full code:
https://create.arduino.cc/editor/mihimbc/8ec2fe30-d812-45cc-b0ae-850b437eb05b/preview
and here is the hardware schematics:

The problem was with the buzzer, somehow was a faulty buzzer, I've managed to replace it and the problem was solved.
Thanks everybody for your time trying to help me!


General Question about fast Serial Communication and Arduino I'm looking for a fast (and safe, in terms of stability) way to send sensor data from an Arduino UnoR3 in real time to a Computer (in my case a MacBook Pro) with a sample rate of at least 1kHz.

I tried following:

Sending sensor values with the related timestamp (in microseconds):
I use 7 bytes for each sample [1 Header byte, 2 bytes for the sensor value (10/(16)bit-Int), and 4 bytes for a 32-bit unsigned long (time in microseconds)] and send them right away.
On the receiving end i mainly use Processing (Im relatively new to Processing though): Reading the bytes in, converting them in integers and safe them in a file or plot them.

For sampling rates of 1sample/10ms my code runs smooth and i even can plot the data in "real-time".

For higher frequencies i ran into following problems:

If i want to plot things, my peripherals freeze and program stops after some time. I have no clue why... maybe serial buffer overflow??
If i just save the data in a text file (without plotting) it works but with a delay of around 20-30seconds on total sampling times of 10seconds (10000 samples).
Meaning that somewhere seems to be a bottleneck and i cant keep up with the sent samples from the Arduino.
Is it possible that the serial bus is the bottleneck here? How can i speed things up? (I'm working with a baudrate 115200bits/s and also 230400bits/s)

How can i improve this while still be able to process data in almost real-time (e.g plotting). Is this even possible or do you recommend logging the data in a text file first and then plot?

Will it helps to send the data in packages (10samles = 70bytes)?

I added a timestamp on each sample, since i observed some delay between the actual sensor measurement and the input on the receiving end. I thought that would allow me to plot and postprocess accurately in "real"-time (with a little delay). Any other ideas?

I would appreciate some input and advice!

Thanks in advance!

You are sending data at ~70kbps. Provided you use serial rate greater than this (115.2 kbps or faster on the Arduino) there should be no problem, assuming you samples are processed quickly enough. This seems to be the case.

Your problem seems to be on the Mac. With a quad core CPU on a fast multitasking machine this should not be an issue. If you are having problems this would be in how you are processing the data. I am not familiar with Processing but you could do this in any language. You need to separate the data logging from the processing and display task. This could be as simple as running a logger and piping the data into a display program.

This is not an Arduino issue (or even a Mac issue), you should ask on https://stackoverflow.com/. NOTE if you want help there you will need to give more detail of the code you are running in the Mac.


Low memory error using SD card I called HTTP web service on Arduino Uno, now i am trying to store the data in SD card. But as soon as i compile the program, it shows LOW MEMORY error and no data stored in SD card.
Any one can help?

Try Arduino mega. It has more memory 8 KB RAM, 256 KB flash memory.


Mega2560 has 2 Crystal Oscillator? Who knows this Mega2560 with two Crystal Oscillators: 12 000 MHz and 16 000 MHz? What is the use of them?

There are two devices on an Arduino board than need a clock source:

The ATMega328 / ATMega2560 main MCU (16MHz)
The USB interface.

The USB interface crystal speed depends on what device is used on your board. Genuine Arduino boards use an ATMega16U2 which uses a 16MHz crystal.  Cheap Chinese clones use a CH340G which takes a 12MHz crystal.

Note that normally it's one crystal and one ceramic resonator.  USB requires very precise timing, so a crystal is used for that. The main MCU doesn't need quite such precise timing, so a cheaper (and less accurate) ceramic resonator is used.


How to use potentiometer on one Arduino to control servo on another Arduino via WiFi? I want to connect a potentiometer on one Arduino (master side) and send the readings to another Arduino (client side) to run a servo motor. The communication between the two Arduinos should be via Wi-Fi using two ESP8266. Based on the changing values of potentiometer, the servo motor should run accordingly.

Is there any reference code? Or, if anybody has done this earlier, please share the link of your code.

(Yes, I only have links in my answer. And they tend to rot. But in this case it shouldn't be too hard to find those tutorials, nor is the content very specific. I also somewhat feel there should be some help to this person before his question gets closed)

Try to focus on one thing at a time.

Follow the steps below, they should be self explanatory. If you run into trouble, you can always create a question based on that particular problem.

Doing so, you'll learn much more about programming/Arduino as by copying code (and having no idea how to). Sooner or later you'll run into the problem that people will not give you "ready to use code".

Get an Arduino to read out a potentiometer. There are lots of tutorials about that.

https://www.arduino.cc/en/tutorial/potentiometer

Get an Arduino to run a servomotor

https://www.arduino.cc/en/Tutorial/Sweep

Combine these two.

https://www.arduino.cc/en/Tutorial/Knob

Make a wired link between two arduino's

http://robotic-controls.com/learn/arduino/arduino-arduino-serial-communication
https://www.arduino.cc/en/Tutorial/MasterWriter

Make the potentiometer control the servo over the wired connection.
Make a wireless link.
Port the wired link to the wireless communication.


SSD1306 allocation failed when adding a constant I am trying to get this code working:

#include <Button.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RTClib.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
RTC_DS1307 RTC;

// when I remove this part it works...
int mode = 1;
const String periodicSystem[60] = {
    "H", "He", "Li", "Be", "B", "C", "N", "O",
    "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S",
    "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr",
    "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge",
    "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb",
    "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn",
    "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd"
};
/////////////////////////////////////////////////////////////////////

Button button1(7);

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  RTC.begin();
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // This will reflect the time that your sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }

  display.display();
}

void loop() {
  DateTime now = RTC.now();
  if(button1.pressed()) {
      display.clearDisplay();
      display.setTextSize(1); // Draw 2X-scale text
      display.setTextColor(WHITE);
      display.setCursor(10, 0);
      display.print(now.second());
      display.display();
  }
}

Whenever I try to add the constant periodicSystem, I get the error SSD1306 allocation failed over Serial. The error also goes away when I remove the part with button1.pressed(). Basically I am not able to add the constant periodicSystem and read out a digital pin at the same time. To me it seems to be some sort of memory issue (I am only adding the constant, I am not doing anything else with it), but my IDE tells me I am only using 52% of the available storage. What am I doing wrong?

Here is my wiring (in reality I am using a 128x32 display, I didn't have the correct part for Fritzing; my display is labeled SDA, SCK, VCC, GND instead of SDA, SCK, VDD, GND; the RTC Module I am using is a DS1307 AT24C32 RTC Module):

Your display needs 624 bytes of RAM for its internal buffer (128 * ((32 + 7) / 8)). The periodicSystem array needs a massive 360 bytes of RAM just for the objects. That doesn't include the memory used to store the actual string data, which by my reckoning is 168 bytes.

So far we're up to 624+360+168 = 1152 bytes of a maximum of 2048.  Over half way and we haven't touched on the serial buffers or other objects that you're using.

An array (const or otherwise) of String objects is by far the least efficient way possible of storing constant string data on an Arduino. You're using 528 bytes of RAM to store what could be stored in 121 bytes of flash.

Personally I would store the data thus:

const char periodicSystem[] PROGMEM = "H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNd";

Each symbol consists of exactly two bytes, and the PROGMEM forces it to stay in flash and never be copied to RAM.

You can get the two bytes of each symbol with:

char b1 = pgm_read_byte(periodicSystem + (i * 2));
char b2 = pgm_read_byte(periodicSystem + (i * 2) + 1);

Then either print them separately, or combine them into a C string:

char symbol[3] = { b1, b2, 0 };

That will include the space character, of course. So you could remove that if you like:

if (symbol[1] == ' ') symbol[1] = 0;

Theoretically you could also change the spaces in the original data to be character 0 if you like - depending on what you do with it, it shouldn't cause any issues:

const char periodicSystem[] PROGMEM = "H\0HeLiBeB\0C\0N\0O\0F\0NeNaMgAlSiP\0S\0ClArK\0CaScTiV\0CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY\0ZrNbMoTcRuRhPdAgCdInSnSbTeI\0XeCsBaLaCePrNd";


Code is not working (Matrix keypad) I am new to Arduino. I am learning from Arduino Cookbook. I was using tinkercad.com for running my Arduino code. But it is not working.
The Serial monitor should show the key which I have pressed on the keypad.
I think there is some syntactical error in the code, I believe the connection is all right.
Any suggestion will be appreciated.
Please look into this:

const char keymap[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
 };
const int rpin[]={9,8,7,6};
const int cpin[]={5,4,3,2};
void setup()
{
  Serial.begin(9600);
  Serial.println("Program starting");//for debugging purpose and canbe removed later
  for(int i=0;i<4;i++)
  {
    pinMode(rpin[i],INPUT);
    digitalWrite(rpin[i],HIGH);
  }
  for(int j=0;j<4;j++)
  {
    pinMode(cpin[j],INPUT);
    digitalWrite(cpin[j],HIGH);
  }
}
void loop()
{
  char key=getkey();
  if(key!=0)
  {
   Serial.println(key);
  }
}
char getkey()
{
  char key=0;
  for(int i=0;i<4;i++)
  {
    digitalWrite(rpin[i],LOW);
    for(int j=0;j<4;j++)
    {
      if (digitalRead(cpin[j])==LOW)
      key=keymap[i][j];
    }
    digitalWrite(rpin[i],HIGH);
  }
  return key;
}

and the connection pic:

update 1:

Cited comment:

  Check pin modes. Should be INPUT_PULLUP and OUTPUT. Also, consider
  debouncing. – Mikael Patel

Please, try:

const char keymap[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
 };
const int rpin[]={9,8,7,6};
const int cpin[]={5,4,3,2};
void setup()
{
  Serial.begin(9600);
  Serial.println("Program starting");//for debugging purpose and canbe removed later
  for(int i=0;i<4;i++)
  {
//Should be INPUT_PULLUP and OUTPUT
    pinMode(rpin[i],OUTPUT);
    pinMode(cpin[i],INPUT_PULLUP);
  }
}
void loop()
{
  char key=getkey();
  if(key!=0)
  {
   Serial.println(key);
   delay(200);              // Also, consider debouncing.
  }
}
char getkey()
{
  char key=0;
  for(int i=0;i<4;i++)
  {
    digitalWrite(rpin[i],LOW);
    for(int j=0;j<4;j++)
    {
      if (digitalRead(cpin[j])==LOW)
      key=keymap[i][j];
    }
    digitalWrite(rpin[i],HIGH);
  }
  return key;
}


Fastest way to send serial commands and do something I am trying to send a lot of serial commands really fast. I basically need to change color of my LED strip many times per second (10 times per second should really be enough). If I do this over WiFi, it will eventually clutter up and make the ESP8266 unresponsive. I need to send the colors as hex, then convert them into usable values (HEX to RGB). Something tells me that's going to cost a lot of resources and the MCU is therefore spending a lot of time just converting the colors into RGB values. Here's a pseudo code example of what I am trying to achieve:

void loop() {
    if(Serial.available()) {
        if(Serial.read().first(8) == "0xABCDEF") {
            //0xABCDEF is basically my indicator saying "this is for individual LEDs"
            //Serial.read() can now be something like 0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000
            char* colors[] = Serial.read().split(" ");
            colorLED(colors);

        }
    }
}

void colorLED(colors) {
    for(i = 1; i < colors.length; i++) {
        strip.SetPixelColor(i, color[i]);
    }
}

I hope this example makes sense. I can send a serial command like 0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000. 5 colors in HEX.

My real question is: How do I take a lot of inputs like above (or another way) and turn them into strings, so I can convert them to RGB? Is there a better way to send commands (like pure RGB values? but remember I need to send many)?. Here is how I convert my colors into RGB:

//hexColor can be "FF0000"
int number = (int)strtol(&hexColor[0], NULL, 16);

int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;

Simple answer: don't.

Don't even consider strings in any form. Instead you want a state machine.

In pseudocode:

Start with an invalid count number (-1)
Read a character.
If that character is x then set your counter to 0.
Otherwise, if counter is 0 or more, convert the character to a number and place it into the right byte depending on the value of your counter
Increment counter
If counter is 6 then set your LED colours and set the counter to "invalid".
Return to start.

Or, in untested C:

static int8_t counter = -1;
static uint8_t r = 0;
static uint8_t g = 0;
static uint8_t b = 0;

if (Serial.available()) {
    char c = Serial.read();
    if (c == 'x') {
        counter = 0;
    } else {
        if (c > 0x39) c -= 7;
        uint8_t v = c & 0x0f;
        switch (counter) {
            case 0: r = v << 4; break;
            case 1: r |= v;
            case 2: g = v << 4; break;
            case 3: g |= v;
            case 4: b = v << 4; break;
            case 5: b |= v;
        }
        counter++;
        if (counter == 6) {
            counter = -1;
            analogWrite(3, r);
            analogWrite(5, g);
            analogWrite(6, b);
        }
    }
}

The "clever" bit that may confuse you is:

if (c > 0x39) c -= 7;
uint8_t v = c & 0x0f;

That is, if the character is greater than a "9" (character 0x39) then it should be a-f. Subtracting 7 from it converts ASCII HEX from 0123456789ABCDEF to 0123456789:;<=>?.  If you then mask it with 0x0F you end up with a number between 0 and 15, or 0-F in hex.

The rest just takes each nibble and places it into the right half of the right colour variable.


I need to change this code to start the section of code when the switch is on and not when the switch is released I have this section of code. It works fine and how I want it only, it executes when the button is released not when it is pressed. My application needs to execute this code when a switch is on. The issue is that it the vairable "fsrOnMillis" is updated constantly when the button is high. I have tried a few things but can't figure out the best way to get this to function how I want.

Hardware description:
Switch when turned on will provide 5V. When off 0V.
2 Led's one green and one red.

What I want to happen is when the switch is on the green led lights up and turns off. Then after a time 60,000 ms the red LED will light up to say that the process is complete.

What is happening is that when the switch is turned on nothing happens but when it is turned off the code executes. I want the process to execute once the switch is turned on.

if (digitalRead(BUTTON) == HIGH) {
  // update the time when button was pushed

  fsrOnMillis = currentMillis;
  greenReady = true;
  redReady = true;
 }

 // make sure this code isn't checked until after button has been let go
 if (greenReady) {
   //this is typical millis code here:
   if ((unsigned long)(currentMillis - fsrOnMillis) >= greenOnDelay ) {
     // okay, enough time has passed since the button was let go.
     analogWrite(greenLedPin, 153);
     // setup our next "state"
     greenState = true;
     // save when the greenLedPin turned on
     greenTurnedOnAt = currentMillis;
     // wait for next button press
     greenReady = false;
   }
 }

 // see if we are watching for the time to turn off greenLedPin
 if (greenState) {
   // okay, led on, check for now long
   if ((unsigned long)(currentMillis - greenTurnedOnAt) >= greenOffDelay) {
     greenState = false;
     analogWrite(greenLedPin, 0);
   }
 }

 if (redReady) {
   //this is typical millis code here:
   if ((unsigned long)(currentMillis - fsrOnMillis) >= redOnDelay) {
     // okay, enough time has passed since the button was let go.
     analogWrite(redLedPin, 153);
     // setup our next "state"
     redState = true;
     // save when the greenLedPin turned on
     redTurnedOnAt = currentMillis;
     // wait for next button press
     redReady = false;
   }
 }

 // see if we are watching for the time to turn off greenLedPin
 if (redState) {
   // okay, led on, check for now long
   if ((unsigned long)(currentMillis - redTurnedOnAt) >= redOffDelay) {
     redState = false;
     analogWrite(redLedPin, 0);
   }
 }

Any help is much appreciated.

You should provide a description of your hardware setup as part of your question, as well as a clearer statement of your problem.

Are you saying that your code is backwards, and is acting like the button is pressed when its not, and like it's been released when you press it?

You probably have your button set up as INPUT_PULLUP, and wired to connect the pin to ground. That's a pretty typical setup. In that case the button pin reads as LOW when it's pressed and HIGH when it's not pressed. Just changed your if statement to:

//                         vvv
if (digitalRead(BUTTON) == LOW)
//                         ^^^


How to run atmega328p at 8, 4 and 1 mhz? Instead of using the regular Arduino board I have purchased the atmega328p-pu along with this components:

22pf ceramic capacitor
10K resistor
16mhz crystal
47uF capacitor
3.3 Volts Power supply

The diagram looks like this:

Because the atmega328p chip that I purchased already comes loaded with arduino bootloader I can program this chip right away! This video explains in more detail how to upload the code to the chip. It is very simple.

The reason why I run my atmega328p chip with a 3.3V power supply is because of these reasons:

I have multiple sensors like the NRF24L01 that cannot take 5 volts.
I run this project of a 3.3 battery as well in order to save power.
I do not want to use voltage regulators as they are inefficient and they will waste my battery.
Everything works great.

Even though everything works great if I am running atmega328P at 16mhz @ 3.3V I am not following the specifications. In order to do things correct I will like to run my code at 8mhz so that I am in within the specs

Question

What is the correct way of running this project at 8mhz? If I change the 16mhz crystal for a 8mhz it runs at 8mhz but everything is half the speed. I have to divide all time related functions by 2. Moreover, I cannot upload new code if it has a 8mhz crystal. In order to upload new code I have to place the 16mhz crystal upload the code and then change the crystal again.

Can I still use my 16mhz crystal and run at 8mhz so that I do not have to keep replacing the crystal? I want my millis function and other time dependent functions to have the correct time. I do not want to have to divide everything by 2.

Do I have to burn a different bootloader for this to work? Where can I find a tutorial that can explain me all this?

There are tutorials on how to use the internal 8mhz crystal from the atmega328 chip but still want to use an external crystal as it is much more accurate

Edit

I just found  this link that explains how to do it. Edgar Bonet answer seems a lot simpler so I will stick to that.

If you run your MCU at 8 MHz, everything will run at this frequency: not
only the CPU core but also the timers, including Timer 0 which is used
for millis(), delay(), etc. So you will have to use a modified
version of the Arduino timing functions in order to cope with this clock
frequency.

Fortunately, such version already exists. Actually, it is even supported
by the standard Arduino core, since it supports the 3.3 V version
of the Arduino Pro Mini, which uses an ATmega328P clocked at 8 MHz.

I thus suggest you install an 8 MHz crystal, burn in the bootloader
for the 3.3 V Pro Mini, and tell your IDE that you are using that
board. In the Tools menu:

set board to "Arduino Pro or Pro Mini"
set processor to ""ATmega328P (3.3V, 8 MHz)"


Pro Micro board not responding to anything I just got a couple of Arduino Pro Micros for a custom keyboard build. Before testing them with the Arduino IDE, I tried to test them with qmk by shorting RST to GND to try and flash it. After a few seconds of holding RST, I got a single blink and nothing else, and qmk didn't seem to have detected the reset.
I've tried setting "Board" to "Arduino Micro" and "Arduino Pro or Pro Mini". I'm on Arch Linux and no matter which USB port is plugged in, the IDE only shows /dev/ttyS0). I tried uploading the "Blink" example, as well as "Burn Bootloader", but only got programmer is not responding like so:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         Using Port                    : /dev/ttyS0
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

It turns out I had to use the port ttyACM0 (and not ttyS0) which wasn't found at the time. The port was there the next day and I have no idea why it wasn't there before.
Also, I thought I had to press and hold RST for a couple of seconds to reset the Pro Micro, but I actually have to press it twice in a row.
I've managed to flash the firmware for my keyboard by double-pressing RST.


Trying to determine the phase difference between two square signals I have been looking for the phase difference between two square signals and this is the code:

#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
  //Serial.begin(9600);
  pinMode(2, INPUT);    //set pins 2 and 3 as inputs and 11 as output
  pinMode(3, INPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  cli();           // disable all interrupts
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);  //set up timer2 to generate a PWM
  TCCR2B = _BV(CS20);    //set prescalar value to 1
  //TCCR1A = 0;
  //TCCR1B = _BV(CS20);
  //TCCR1B |= (1 << CS12); //256 values
  TCNT2  = 0;
  sei();             //enable all interrupts

  attachInterrupt(digitalPinToInterrupt(2), t1_ISR, RISING);     //enable interrupt service routines on pins 2 and 3
  attachInterrupt(digitalPinToInterrupt(3), t2_ISR, RISING);

  //Serial.print(OCR2A);
  //Serial.print(OCR1A);

}

volatile uint8_t t1, t2;

void loop() {
  if (t2 == t1)
  {
    OCR2A = 0;
    OCR2B = 0;
  }
  //compare time that one signal goes high to time the other signal goes high
  else if (t2 > t1)
  {
    OCR2A = (t2 - t1); //output PWM based on phase difference on pin 11
    OCR2B = 0;
  }
  else if (t2 < t1)
  {
    OCR2B = (t1 - t2);  //output PWM on pin 11
    OCR2A = 0;
  }
}
}

void t1_ISR() {         //interrupt if signal on pin 2 goes high and store counter
  t1 = TCNT2;           //value to variable t1
}

void t2_ISR() {         //interrupt if signal on pin 3 goes high and store counter
  t2 = TCNT2;           //value to variable t2
}

I want to operate the input pulses at 40 kHz, how can I do this and read the difference of phase? I am using the Arduino Mega2560

There are a few things very wrong here.

First problem: you are clocking Timer 2 with the prescaler set to 1.
This means the timer will roll over every 256 CPU cycles. Your
input signal, on the other hand, has a period of 25 µs, which is
400 CPU cycles (I am assuming a 16 MHz Arduino). Unless you
know beforehand that the phase difference is within some window less
than 16 µs wide, your readings will be ambiguous.

You have to make sure the rollover period of your timer is larger than
the period of the input signal. This means either using a larger
prescaler (8 should do), which will decrease your phase resolution,
or using a 16-bit timer instead of an 8-bit timer.

Second problem: you are using a signed integer type for the timer
readings. This makes little sense. Worse: you are computing differences
like t2-t1, which can overflow. Signed integer overflow is undefined
behavior in C++, and
invoking it is always a bug.

You should declare t1 and t2 as unsigned, i.e. either
volatile uint8_t, or volatile uint16_t (if using a 16-bit timer).
Then you don't get overflows: you get instead a well-defined rollover
behavior.

Third problem: you are doing comparisons like if (t2 > t1). This,
again, makes no sense, if only because the timer is repeatedly
rolling-over to zero. You should instead just compute t2-t1 and work
your way from that.


need to compare if a byte is less than 80 hex I am using an infrared sensor called OTI301. In its data sheet it says that in order to obtain object temperature and ambient temperature values I need to extract the binary information from the sensor and use the binary information in given formulas. I have done all that but for some reason I am not getting the right values for the object temperature. The ambient temperature seems to work well but when I put a hot object, more than 320 F, the formula returns a random negative number. Also the the sensor can go up to 780 F so I know the temperature has not been capped. Please see pictures for important data sheet information, or here are the links for the complete data sheets
https://drive.google.com/file/d/1XMRDCNzY3fn0q6lkGejs5D-pqksfRuZ8/view?usp=sharing.
https://drive.google.com/file/d/1mmdkHkNbwC5VgQxGMrq07XolajNvgBkN/view?usp=sharing. Lastly, here is the part of the code where I extract the information and apply formulas.

     void loop()
 {
   if (Wire.read()) // On success, read() will return 1, on fail 0.
   {
     buttonState = digitalRead(button);
     //Serial.println(buttonState);
     Wire.beginTransmission(DEVICE_ADDRESS);
     Wire.write(0x80);  // readout command
     Wire.endTransmission(false);
     Wire.requestFrom(DEVICE_ADDRESS, 6); // request 6 bytes
     uint8_t data[6];
     for (int i = 0; i < 6; i++) {
         data[i] = Wire.read();
     }

      //Calculate Object Temperature
     if(data[5] < 0x80) {
       TA = (data[3]+ data[4]*256+data[5]*65536)/200;
     }
     else {
       TA = (((data[3]+ data[4]*256+data[5]*65536)) - 16777216) /200;
     }

     //Calculate Ambient Temperature
     if(data[2] < 0x80) {
       TA = (data[0]+ data[1]*256+data[2]*65536)/200;
      }
     else {
       TA = (((data[0]+ data[1]*256+data[2]*65536)) - 16777216) /200;
     }

The rules of integer arithmetics are tricky in C++. There are rules that
give the type of integer literals:

256 and 200 are of type int, which is the default type for
integer literals. On the Nano, this type is 16-bits, and covers the
range from −32,768 to +32,767.
65536 being too large for the int type, it is implicitly
considered a long int. This type is 32-bits on the Nano, and covers
roughly ±2.15×109.

Then there are rules for the types used in arithmetic operations. No
computation is ever done on a type smaller than int: anything smaller
is promoted to int. Then, if you combine two operands of different
types, the larger type “wins” and the compiler implicitly converts the
other operand to the larger type. Note that if two types have the same
bit size, the unsigned one is considered “larger”.

Let's go now through your formula, and see the types of the different
terms:

data[3]       = uint8_t
data[4]*256   = uint8_t * int → int
data[5]*65536 = uint8_t * (long int) → long int

Now you may see the problem. Your calculation will eventually overflow,
but the overflow is not in data[5]*65536, as one may naively expect.
What happens is than when the temperature reaches 163.84 °C (≈ 327 °F),
data[4] becomes 128, and data[4]*256 is 32,768, just too large for
an int. The result overflows to −128, hence the negative values you
see.

The simplest solution is to force 256 to be a long int, by appending
the L suffix to the number. Then the multiplication will be performed
with the long int type, and there will be no overflow:

TA = (data[3] + data[4]*256L + data[5]*65536) / 200;

On a final note, it is worth noting that the numbers 256, 65536 and
16777216 used in the formula are all powers of two. Even powers of 256.
You may notice that, save for the division by 200, what this formula
describes is the coding of an integer as a 24-bit, little-endian, two's
complement number. This format (two's complement little-endian) is
exactly what the Arduino uses internally for representing numbers. You
could then avoid all those calculations and get your result by just
telling the compiler that what those memory cells are actually holding
is a 24-bit integer:

float TA = *(__int24*)&data[3] / 200.0;

This works for both positive and negative temperatures, but it has the
drawback of breaking some C++ rules (aliasing rules), and using the
non-standard type __int24. A safest way to achieve the same is to
build a 32-bit integer by putting the bits in place using bitwise
operations. But note that then a sign-extension byte is needed to
convert the 24-bit number to 32 bits:

uint8_t sign_extension = data[5] & 0x80 ? 0xff : 0x00;
int32_t reading = (uint32_t) data[3] <<  0
                | (uint32_t) data[4] <<  8
                | (uint32_t) data[5] << 16
                | (uint32_t) sign_extension << 24;
float TA = reading / 200.0;


How to read CPU temperature into Arduino? I'm not sure about this and if it is possible. I need to read CPU (normal computer) into an Arduino. This could be possible (at least I think) by connecting some kind of sensor that can be placed between the heatsink and the CPU, where the thermal paste is placed. Or, the second option is to read values from the system somehow, or from the motherboard. I hope I'm not talking about stupid things. I need some advice about this.

Here is a simple way to send CPU temperature reading data via serial port, under Windows.

As answered in the question Batch-file get CPU temperature in °C and set as variable, it is possible to build batch file (*.BAT) to get the readings and output to console. I took following option and built the BAT file.

wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature

Now, to redirect the console to serial port, use > symbol. Try following and receive it in your Arduino or use serial port monitor to check (in my case it works):

mybatfile.bat > COM1

Alternatively, you can use

wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM1

inside your BAT file.

Next, we have to specify the serial configuration, make it EXE file so it can run under Administrative account. I used Advanced BAT to EXE converter. In the tool, specify the commands:

@echo off
mode COM1 BAUD=38400 PARITY=n DATA=8
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM1

Convert it to EXE using File->Build EXE...

And finally, you can create Scheduled Task to run your newly built EXE application periodically.

BTW, WMI is a powerful interface, it is possible to retrieve many other metrics and configuration data.


microstepping and pwm As per definition:

Micro stepping is a method of moving the stator plug of the stepper motor more smoothly than it is in the full or half step drive mode.The process of micro stepping helps in reducing the vibration and produces noiseless stepping as low as 0 Hz. It even make the step angle smaller and the positioning becomes much better.

Pulse-width modulation (PWM) is a modulation process or technique used in most communication systems for encoding the amplitude of a signal right into a pulse width or duration of another signal, usually a carrier signal, for transmission. Although PWM is also used in communications, its main purpose is actually to control the power that is supplied to various types of electrical devices, most especially to inertial loads such as AC/DC motors.

Which is better method to run a stepper motor with maximum possible speed..?

which can be used to run the motor at almost zero speed ..?

can we be able to rotate the motor at zero or less than Zero speed with PWM method..?

I want to rotate nema 17 stepper motor with microstepping or pwm whichever is suitable and rpm should be greater than what mentioned in the specifications. Can I do this with arduino and any driver..?

which driver would be most suitable to run the stepper at 1000 rpm or more..?

Which is better method to run a stepper motor with maximum possible speed..?

Microstepping

  which can be used to run the motor at almost zero speed ..?

Microstepping

  can we be able to rotate the motor at zero or less than Zero speed with PWM method..?

What is "less than" zero speed? Backwards? Turning through another dimension?  PWM cannot drive a stepper motor. That's like asking if you can download a cake through your suitcase. The concepts just don't match up.  Yes, there are ways of implementing microstepping using closely coupled phase controlled PWM signals, but the end result is microstepping.

A stepper motor requires coils to be activated in the right order and at the right time (and in some cases with the right polarity). PWM just generates a square wave with a set frequency and duty cycle.

To be clear, a single step of a stepper motor involves cycling through all the correct sequence of energising coils (often a sequence of 4 energisings). Microstepping is merely the act of stopping at different points within that single cycle to give a higher resolution that whole steps (usually 4 times the resolution). It is nothing magical or special.


ILI9341 backlight flickers when using USB power from Laptop I've developed a project using am ILI9341, ESP12F and Arduino. Everything works fine except a very annoying issue. The LCD flickers when I use the laptop's USB. But when I use a USB charger it's much better.
I use https://github.com/Bodmer/TFT_eSPI library for SPI driver and AMS1117 as regulator (with 1uf in the input, and 10uf in output).
I don't think the software has a problem because I don't refresh anything on the display (just draw something in the setup function, not in loop) and also it changes with different power sources. The problem is the backlight.
When I move the USB cable it goes crazier sometimes. I've checked it with many different cables and computers. Is this because of noise or something from the USB port? How can I fix this?
It's very important for me to be able to use the USB port as the power source.
Update
When I'm uploading the code to the ESP8266 (using TXD & RXI), the LCD doesn't flicker event a little bit! And immediately after finishing the upload, the LCD brightness decreases and starts flickering!
The circuit is pretty simple and LCD pins are connected directly as listed here

That happens because not all USB ports can supply more than 500mA of current.
When you use a charger's USB port, it is designed to provide more than 500mA of current(ex. 1-2amps in most chargers). Try using a USB port that can provide more than 500mA of current. Most PCs and Laptops will only supply 500mA at maximum unless specified so.

More information regarding USB power can be read here on Wikipedia.

Cheers!


Is it possible to change pin operation from output to input within the Arduino loop (event-driven)? Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?

I would like to change the operation of a couple of Arduino pins from input to output during execution of the Arduino loop in an event-driven way. Is this possible please?

Yes.

Just call pinMode([pin], [mode]) whenever you want to change from input to output or output to input.

How to decide when to do that is entirely up to you. You can do it any time you choose using any stimulus you like.


What does the datasheet information for a switch mean? I'm clueless when it comes to the information on datasheets for switches. When I see a datasheet for LEDs or servos, I'm used to seeing a fairly straightforward call out for the required volts and amps.

A project I'm working on now requires turning on an LED using a float switch like this one:
Water Level Switch

The max switching voltage and current values, and minimum voltage info is really throwing me. The minimum voltage, for instance, is 250v DC! Does a $5 switch really require 250 volts? I haven't been able to find many schematics where they are just using a switch like this without a pump or other hardware, but I seem to remember seeing someone run a switch like this with 5v pin. And I'm totally unsure what the current would be/if I need a resistor, etc.

A reed switch like this will not require any minimum voltage. It should work quite happily down to millivolt levels. If you want to switch on an LED from a 5V supply that is switched by the reed switch you will need a resistor that limits the current to no more than
20mA. The forward voltage drop over a red LED is around 2V so your resistor will drop 3V which means it needs to be at least about 150 ohms.


Sending textual and nontextual data simultaneously across a serial port I am currently using an Arduino Uno and creating an LCD simulator that works by sending LCD data through the hardware UART (serial interface). This LCD data is very short in length; in this case, it's 2 bytes. The LCD simulator has already been made, and it is capable of detecting these LCD packets on the serial port and using them to control the simulated LCD.

However, I don't want to disturb the other traffic passing through the serial port; in this case, it's just text. The problem is that most serial monitors are able to pick up the LCD packets, which aren't supposed to be printed out because they appear as gibberish.

For now, I'm prefixing these short LCD packets with two magic numbers for it to be detectable by the LCD simulator alongside non-LCD traffic, and perhaps removable by a modified serial monitor.

I thought about using ASCII control characters to inform regular terminals that following data must not be printed, but there does not seem to be a specific control character to "hide" text/data; the closest thing there is is the BS character. All other control characters seem to give an inconsistent result among terminals - i.e. ESC doesn't actually hide text with the Windows console host, but it does with mintty.

My goal is to not have to integrate my own serial monitor and force others to use it if there is traffic present that can only be read by the LCD simulator. I want to allow others to use their own terminals and serial monitors to exchange textual data with the Arduino while seamlessly having LCD packets being sent invisibly and "under the hood."

Is this possible? Can I mix different types of data across the same serial port? If not, what are my options, or am I essentially forced to "reinvent the wheel" by making my own protocol that can mix the two types of traffic?

The idea that sundry terminal programs can cleanly deal with binary data intended for your LCD simulator doesn't seem realistic.  Instead, look for a method to suppress the binary data when the Arduino isn't talking to an LCD simulator.

For example, during startup the Arduino could send some fixed text and a number to the host, and if the simulator is running, it would reply to the Arduino with some other fixed text and the 9's complement of the number.  If the Arduino doesn't get such a reply within a couple of seconds, it turns off LCD-simulation data transmission.


5V+ Voltage to the arduino analog If I connect a 12V / 12V+ battery to the arduino (uno) analog, will it be damaged ? What if I connect 230-240V to it ? Don't worry I haven't tried it yet. :D

Thanks in advance.

For the 12 V battery, let's assume it might get up to 15 to 20 V when charging, so we need a voltage divider to divide that down.

The zener diode is there to clamp the input to no more than 5.1 V in case of spikes or other damaging things on the input.

The voltage divider will divide down to 25% of the input, ie.

output = R2 / (R1 + R2) = 10 / (30 + 10) = 0.25

So now if you measure 5 V on the analog input you know you have 20 V on the battery. Thus you can scale your calculations appropriately.

(A more common value would be a 33 k resistor, in which case redo the calculation and scale accordingly).

For 240 V I strongly advise against trying something like that with bigger resistors. For one thing, 240 V RMS will have 240 * sqrt (2) = 340 V peak to peak. And that is both negative and positive.

A suitable approach would be to run through a small transformer, which will reduce the voltage and also isolate you from (almost) certain death.

In addition to that you would need to rectify the resulting voltage (say, 12 V) so that you don't put negative voltages into your input pin. And on top of that filter it so smooth out the peaks and troughs.