message:
How to generate musical notes using an uno without using tone() function? Can anyone share the embedded c language code for it?

I also want to know how can we make it without functions like digitalwrite

body:
I made a 13 note piano-like (well, more organ-like) tones instrument here

https://forum.arduino.cc/index.php?topic=179761.0

Youtube clip of it in action

https://www.youtube.com/watch?v=4c8idXN4Pg0

Only 8 notes in the clip, that was all the buttons I had at the time.

I used a '1284P processor instead of '328P so it could have 13 inputs & 13 outputs, without jumping up to a 2560.

There is nothing wrong with using Direct Port Manipulation in the Arduino IDE environment. Arduino is just C++ with some things made easier for the user with functions, macros, etc.

Here's the code.

    /* Crossroads, 26 July 2013
     test for creating multiple simultaneous notes using micros()
     press a key, get a note. Use external analog mixer (summing op amp) for sound mixdown to single output to a speaker
     need a higher pin count device - this code is for '1284P - with specific pin mappings, not written for uC portability
     play 13 notes for now, C4 up to C5
     note info from http://www.sengpielaudio.com/calculator-notenames.htm
     Input keys: pin2=C4, 3=C#4, 30=D4, 8=D#4, 9=E5, 31=F5, 4=F5#, 5=G5, 6=G5#, 7=A5, 10=A5#, 11=B5, 12=C5
     Output notes: pin 16=C4, 17=C#4, 18=D4, 19=D#4, 20=E5, 21=F5, 22=F5#, 23=G5, 24=G5#, 25=A5, 26=A5#, 27=B5, 28=C5
     Ordering is funny due to Bobuino mapping, and having PortA output bits follow portD input bits, portC output bits follow portB input bits
     0,1 reserved for serial
     13,14,15,29, unused, maybe make 1 of 9 octave select? Piano has 7 full C to B octaves, 2 partials
     */
    // array of 1/2 period of the notes in microseconds
    // so a C8 note would be 119uS High, 119uS low for example
    unsigned long noteArray[] = {
      119, // C8, highest note - note 0
      127,134,142,150,159,169,179,190,201,213,225,239, // B7, A#7,A7, G#7, G7, F#7, F7, E7, D#7, D7, C#7, C7 - notes 1-12
      253,268,284,301,318,338,356,379,402,426,451,478, //  B6 down to C6 - notes 13-24
      506,536,568,602,638,676,716,758,804,851,902,965, // B5 down to C5 - notes 25-36
      1012,1073,1136,1204,1276,1351,1432,1517,1607,1703,1804,1911, // B4 down to C4 - notes 37-48
      2025,2145,2272,2408,2551,2703,2863,3034,3214,3405,3607,3822, // B3 down to C3 - notes 49-60
      4050,4290,4545,4816,5102,5405,5727,6067,6428,6810,7215,7645,  // B2 down to C2 - notes 61-72
      8099,8581,9091,9631,10204,10811,11454,12135,12856,13621,14431,15289,  //  B1 down to C1 - notes -73-84
      16198,17161,18182, // B0, A#0, A0 - 85-86-87
    };  // really need to flip this whole thing over so that 0 is lowest note & 87 is  highest
    byte keyArray[]={
      2,3,30,8,9,31,4,5,6,7,10,11,12,13,}; //Ports D2,D3,D4,D5,D6,D7,B0,B1,B2,B3,B4,B5,B6, added b7 - notes 48, 47,46,45,44,43,42,41,40,39,38,37,36
    byte outputArray[] = {
      14,15,16,17,18,19,22,23,24,25,26,27,28, 21,22,29}; // Ports A0,A1,A2,A3,A4,A5,C0,C1,C2,C3,C4,C5,C6, added a6, a7, c7
    // ports selected for consistency for bits used from input to output from D in to A out, and B in to C out
    byte keyActive[]= {
      0,0,0,0,0,0,0,0,0,0,0,0,0,}; // 1 indicates key is pressed
    //byte octaveSelect[] = {
    // 13,21,22,29}; // b7,a6,a7,c7 -  0 to 9 - future use
    // ATMEL ATMEGA1284P on Bobuino
    //
    //                       +---\/---+
    //           (D 4) PB0 1 |        | 40 PA0 (D 21) AI 7
    //           (D 5) PB1 2 |        | 39 PA1 (D 20) AI 6
    //      INT2 (D 6) PB2 3 |        | 38 PA2 (D 19) AI 5
    //       PWM (D 7) PB3 4 |        | 37 PA3 (D 18) AI 4
    //   PWM/SS (D 10) PB4 5 |        | 36 PA4 (D 17) AI 3
    //     MOSI (D 11) PB5 6 |        | 35 PA5 (D 16) AI 2
    // PWM/MISO (D 12) PB6 7 |        | 34 PA6 (D 15) AI 1
    //  PWM/SCK (D 13) PB7 8 |        | 33 PA7 (D 14) AI 0
    //                 RST 9 |        | 32 AREF
    //                VCC 10 |        | 31 GND
    //                GND 11 |        | 30 AVCC
    //              XTAL2 12 |        | 29 PC7 (D 29)
    //              XTAL1 13 |        | 28 PC6 (D 28)
    //      RX0 (D 0) PD0 14 |        | 27 PC5 (D 27) TDI
    //      TX0 (D 1) PD1 15 |        | 26 PC4 (D 26) TDO
    // INT0 RX1 (D 2) PD2 16 |        | 25 PC3 (D 25) TMS
    // INT1 TX1 (D 3) PD3 17 |        | 24 PC2 (D 24) TCK
    //     PWM (D 30) PD4 18 |        | 23 PC1 (D 23) SDA
    //      PWM (D 8) PD5 19 |        | 22 PC0 (D 22) SCL
    //      PWM (D 9) PD6 20 |        | 21 PD7 (D 31) PWM
    //                       +--------+
    //
    byte x;
    byte portDkeys;
    byte portBkeys;
    byte portAnotes;
    byte portCnotes;
    unsigned long currentTime;
    unsigned long changeTime[]= {
      0,0,0,0,0,0,0,0,0,0,0,0,0,}; // track when to flip output
    unsigned long duration;
    /* consistency check
     INDEX, NOTE, port In, port Out
     0, C4,       D2, A2           read 04 write 04 FB 1111 1011 Middle C
     1, C#4,      D3, A3           read 08 write 08 F7 1111 0111
     2, D4,       D4, A4           read 10 write 10 EF 1110 1111
     3, D#4,      D5, A5           read 20 write 20 DF 1101 1111
     4, E4,       D6, A6           read 40 write 40 BF 1011 1111
     5, F4,       D7, A7           read 80 write 80 7F 0111 1111
     6, F#4,      B0, C0           read 01 write 01 FE 1111 1110
     7, G4,       B1, C1           read 02 write 02 FD 1111 1101
     8, G#4,      B2, C2           read 04 write 04 FB 1111 1011
     9, A4,       B3, C3           read 08 write 08 F7 1111 0111  Concert A
     10, A#4,     B4, C4           read 10 write 10 EF 1110 1111
     11, B4,      B5, C5           read 20 write 20 DF 1101 1111
     12, C5,      B6, C6           read 40 write 40 BF 1011 1111
     */
    /*************/
    void setup(){
      //Serial.begin (115200); // for debug testing
      for (x=0; x<14; x=x+1){ // input pins with pullup
        pinMode(keyArray[x], INPUT);
        digitalWrite (keyArray[x], HIGH);
      }
      for (x=0; x<17; x=x+1){
        pinMode(outputArray[x], OUTPUT); // output pins
      }
      //  for (x=0; x<4; x=x+1){ // future use maybe
      //    pinMode(octaveSelect[x], INPUT); // input pins with pullups
      //    digitalWrite (octaveSelect[x], HIGH);
      //  }
    } // end setup

    /***********/
    void loop(){
      //Serial.print (" ");
      // if key is pressed, determine time for next transition
      // if key is not pressed, no transition, use AC coupling into summing op-amp for no output
      // idea is to allow multiple notes to be created simultaneoulsy. Can the reading & if's all be done fast enough?
      portDkeys = PIND; // Read the input keys - using direct port manipulation for speed
      portBkeys = PINB;
      currentTime = micros();

      // Didn't make this part of a larger loop/array lookup because that adds 12-15uS for each pass thru the loop

      /* Check if key for note C4 is pressed, key0  */

      if ((portDkeys & 0x04) == 0){ // key is pressed D2 -> A2
         if (keyActive[0]==0){
           keyActive[0] = 1;
           changeTime[0] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[0])>=noteArray[48]){ // time for a period toggle?
          changeTime[0] = changeTime[0] + noteArray[48];    // setup time for the next toggle
          PINA=0x04;  // write a 1 to PINx toggles an output bit - NickGammon to the rescue again!
        }
      }
      else{keyActive[0] = 0;}

      /* Check if key for note C#4 is pressed, key1  */

      if ((portDkeys & 0x08) == 0){ // key is pressed D3 -> A3
           if (keyActive[1]==0){
           keyActive[1] = 1;
           changeTime[1] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[1])>=noteArray[47]){
          changeTime[1] = changeTime[1] + noteArray[47];
          PINA = 0x08;
        }
      }
      else{keyActive[1] = 0;}

      /* Check if key for note D4 is pressed, key2  */

      if ((portDkeys & 0x10) == 0){ // key is pressed D4 -> A4
           if (keyActive[2]==0){
           keyActive[2] = 1;
           changeTime[2] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[2])>=noteArray[46]){
          changeTime[2] = changeTime[2] + noteArray[46];
          PINA = 0x10;
        }
      }
      else{keyActive[2] = 0;}

      /* Check if key for note D#4 is pressed, key3  */

      if ((portDkeys & 0x20) == 0){ // key is pressed D5 -> A5
           if (keyActive[3]==0){
           keyActive[3] = 1;
           changeTime[3] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[3])>=noteArray[45]){
          changeTime[3] = changeTime[3] + noteArray[45];
          PINA = 0x20;
        }
      }
      else{keyActive[3] = 0;}

      /* Check if key for note E4 is pressed, key4  */

      if ((portDkeys & 0x40) == 0){ // key is pressed D6 -> A6
           if (keyActive[4]==0){
           keyActive[4] = 1;
           changeTime[4] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[4])>=noteArray[44]){
          changeTime[4] = changeTime[4] + noteArray[44];
          PINA = 0x40;
        }
      }
      else{keyActive[4] = 0;}

      /* Check if key for note F4 is pressed, key5  */

      if ((portDkeys & 0x80) == 0){ // key is pressed D7 -> A7
           if (keyActive[5]==0){
           keyActive[5] = 1;
           changeTime[5] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[5])>=noteArray[43]){
          changeTime[5] = changeTime[5] + noteArray[43];
          PINA = 0x80;
        }
      }
      else{keyActive[5] = 0;}

      /*  Now Port B & Port C */
      /* Check if key for note F#4 is pressed, key6  */

      if ((portBkeys & 0x01) == 0){ // key is pressed B0 -> C0
           if (keyActive[6]==0){
           keyActive[6] = 1;
           changeTime[6] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[6])>=noteArray[42]){
          changeTime[6] = changeTime[6] + noteArray[42];
          PINC = 0x01;
        }
      }
      else{keyActive[6] = 0;}

      /* Check if key for note G4 is pressed, key7  */

      if ((portBkeys & 0x02) == 0){ // key is pressed B1 -> C1
           if (keyActive[7]==0){
           keyActive[7] = 1;
           changeTime[7] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[7])>=noteArray[41]){
          changeTime[7] = changeTime[7] + noteArray[41];
          PINC = 0x02;
        }
      }
      else{keyActive[7] = 0;}

      /* Check if key for note G#4 is pressed, key8  */

      if ((portBkeys & 0x04) == 0){ // key is pressed B2 -> C2
           if (keyActive[8]==0){
           keyActive[8] = 1;
           changeTime[8] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[8])>=noteArray[40]){
          changeTime[8] = changeTime[8] + noteArray[40];
          PINC = 0x04;
        }
      }
      else{keyActive[8] = 0;}

      /* Check if key for note A4 is pressed, key9  */

      if ((portBkeys & 0x08) == 0){ // key is pressed B3 -> C3
           if (keyActive[9]==0){
           keyActive[9] = 1;
           changeTime[9] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[9])>=noteArray[39]){
          changeTime[9] = changeTime[9] + noteArray[39];
          PINC = 0x08;
        }
      }
      else{keyActive[9] = 0;}

      /* Check if key for note A#4 is pressed, key10  */

      if ((portBkeys & 0x10) == 0){ // key is pressed B4 -> C4
           if (keyActive[10]==0){
           keyActive[10] = 1;
           changeTime[10] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[10])>=noteArray[38]){
          changeTime[10] = changeTime[10] + noteArray[38];
          PINC = 0x10;
        }
      }
      else{keyActive[10] = 0;}

      /* Check if key for note B4 is pressed, key11  */

      if ((portBkeys & 0x20) == 0){ // key is pressed B5 -> C5
           if (keyActive[11]==0){
           keyActive[11] = 1;
           changeTime[11] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[11])>=noteArray[37]){
          changeTime[11] = changeTime[11] + noteArray[37];
          PINC = 0x20;
        }
      }
      else{keyActive[11] = 0;}

      /* Check if key for note C5 is pressed, key12  */

      if ((portBkeys & 0x40) == 0){ // key is pressed B6 -> C6
           if (keyActive[12]==0){
           keyActive[12] = 1;
           changeTime[12] = currentTime;
         }
        // see if time to change hi to lo, or lo to hi
        if ( (currentTime - changeTime[12])>=noteArray[36]){
          changeTime[12] = changeTime[12] + noteArray[36];
          PINC = 0x40;
        }
      }
      else{keyActive[12] = 0;}

    } // end loop


sender: user

sender: assistant

body:
Yes, that's easy enough to do. I wrote a library to do that, as described [here](http://www.gammon.com.au/forum/?id=11504&reply=11#reply11).

Basically you could make a class like this:

    class TonePlayer
      {
      // addresses of output ports - NULL if not applicable
      volatile byte * const timerRegA_;
      volatile byte * const timerRegB_;
      volatile byte * const timerOCRH_;
      volatile byte * const timerOCRL_;
      volatile byte * const timerTCNTH_;
      volatile byte * const timerTCNTL_;

      public:
        // constructor
        TonePlayer (
              // ports
              volatile byte & timerRegA,
              volatile byte & timerRegB,
              volatile byte & timerOCRH,
              volatile byte & timerOCRL,
              volatile byte & timerTCNTH,
              volatile byte & timerTCNTL)
           :
             timerRegA_  (&timerRegA),
             timerRegB_  (&timerRegB),
             timerOCRH_  (&timerOCRH),
             timerOCRL_  (&timerOCRL),
             timerTCNTH_ (&timerTCNTH),
             timerTCNTL_ (&timerTCNTH)
      { }

        void tone (const unsigned int Hz);
        void noTone ();

      };  // end of TonePlayer

Then implement the two functions like this:

    void TonePlayer::tone (const unsigned int Hz)
    {
      // it takes two toggles for one "cycle"
      unsigned long ocr = F_CPU / Hz / 2;
      byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

      // too large? prescale it
      if (ocr > 0xFFFF)
        {
        prescaler |= _BV (CS11);    // now prescaler of 64
        ocr /= 64;
        }

      // stop timer
      *timerRegA_ = 0;
      *timerRegB_ = 0;

      // reset counter
      *timerTCNTH_ = 0;
      *timerTCNTL_ = 0;

      // what to count up to
      *timerOCRH_ = highByte (ocr);
      *timerOCRL_ = lowByte (ocr);

      *timerRegA_ = _BV (COM1A0);             // toggle output pin
      *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
      }  // end of TonePlayer::tone

    void TonePlayer::noTone ()
      {
      // stop timer
      *timerRegA_ = 0;
      *timerRegB_ = 0;
      } // end of TonePlayer::noTone

And now call it:

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

    void setup()
      {
      pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

      tone1.tone (220);  // 220 Hz
      delay (500);
      tone1.noTone ();

      tone1.tone (440);
      delay (500);
      tone1.noTone ();

      tone1.tone (880);
      delay (500);
      tone1.noTone ();
      }

    void loop() { }

In this example you plug your speaker into D9 (digital pin 9) on your Uno, with the other pin going to ground. Since this plays tones using the hardware timers you can do other things in your loop without affecting the tones.


message:
Increasing speed of Vl6180x Sensors

I have 5x vl6180x pololu ToF sensors. I have managed to hook up all of the sensors to the arduino via I2C by making each sensor startup at different times and when they do, changing their addresses, but while I can quite easily read them, they take a very long time, 50ms - 300ms. I'm using the [Pololu VL6180x library][1] and when I've investigated the library, I couldn't find any delays in the code. I have also tried to change the clock rate of I2C to 400kHz, but that didn't seem to affect the speed. The datasheet of the sensors says that a sensor might take ~63ms to respond, but is there any way to make it faster? If not, can I read the sensors with the AtTiny13A and send the data from each chip to arduino? Which protocol should i use to communicate with them, if i want to read their measured distance?

Ps. I'm making a robot which needs to move fast and react quickly to each sensor. (11 of sensors in total, none, except ToF are I2C)

  [1]: https://github.com/pololu/vl6180x-arduino

body:
You can use `startRangeContinuous` and `readRangeContinuous` to have the sensor continuously measuring the distance, negating the need to wait for the sensor to do a measurement.

Using `readRangeSingle` will start a single measurement, and this function will just sit there waiting for the measurement to be done, after which it will return the result.


message:
Spi based pin expander for Arduino

I don't have enough pins on my Esp32 board. I would like to use a pin expander. All the ones I could find online only use i2c. Are there ones available that use SPI?

 I would like send pwm signals to the pin expander outputs. Is that possible?

body: Here you go https://www.microchip.com/wwwproducts/en/MCP23S17. Found it. I am gonna leave this here in case anyone needs it.


message:
How can I rewrite Arduino Code using SPI library into C++?

The issue is that I have code using an Arduino library and need to convert it into C++ so I can use it with a raspberry pi on ROS (Robot operating system). Does anyone know the best way to change it over or know of good resources?

I know that Arduino is essentially C++ but I am uncertain about how to make Arduino libraries into C++.

body:
The sometimes-called "Arduino Language" is C++, but with some upfront work - primarily supplying file inclusions - done for you if you don't.

The Arduino compiler is a GNU C++ compiler. If you write or supply standard C++ to the Arduino IDE, it will compile it.


body:
The Arduino compiler is a GNU C++ compiler HOWEVER there is no c runtime library (which is not part of the compiler).

Probably more significant to the question is that the Arduino compiler supplies support for the ATMEL hardware. This is incompatible with the Raspberry Pi.

The Arduino is a real time microcontroller and has unrestricted access to its hardware, the Pi usually runs a multi-tasking OS, the hardware is not directly accessible from user space, so many tasks need to be written differently; often this means relying on a OS supplied kernel driver.

Any practicable Arduino program would require extensive changes to work on the Raspberry Pi. The effort involved is likely to be more than writing a Raspberry Pi program from scratch.


message:
Problems with Serial.read()

void loop()
    {
      if (sensor.begin() == true)
      {
        Serial.print("Current Conversion Mode: ");
        Serial.println(sensor.getConversionMode());
        Serial.println("Enter your mode of Conversion (number 0 - 3): ");
        while (Serial.available() == 0); // Waits for the user input
        mode = Serial.read(); // Reads the input string from serial port
        Serial.print("Number recieved: ");
        Serial.println(mode);
        delay(500);
        if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
        {
          sensor.setConversionMode(mode);
          Serial.println();
          delay(500);
        }
        else
        {
          Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
        }
        delay(1000);
      }
      else // Runs when the device was unable to setup properly
      {
        Serial.println("Device failed to setup");
      }
    }

I'm currently using the SparkFun red board to run this code on. I have been trying to get this to read from the serial monitor to take an input to send to the library I wrote to change the value of the conversion mode register of a temperature sensor. When I run the code, I can only have it run once correctly, then it jumps directly to the else statement for the inputs, saying that 0-3 was not an input. I tried the other methods that people have suggested  from this website and the Arduino forums but none of them have worked for me yet. I'm not sure if adding more delays would help - that was one of the most common suggestion I found for this specific issue and it wasn't that consistent. Please help! Thanks.

body:
Using a slightly modified version of your sketch, I receive the following output in the serial monitor when I enter the number 2.

> Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
Number recieved: 2

> Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
Number recieved:

> Conversion mode unsuccessfully set - Please enter a number 0 - 3
Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
Number recieved:

> Conversion mode unsuccessfully set - Please enter a number 0 - 3
Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):

If you change `mode` to an `int` then retest, you'll see the second and third "Number recieved" are 10 and 13. That would be the New Line and Carriage Return characters. When you send data via the serial monitor, do you have "No Line Ending" selected or something else?

Here is a test sketch:

    char mode;

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

    void loop()
    {
      if (true)
      {
        Serial.print("Current Conversion Mode: ");
        //Serial.println(sensor.getConversionMode());
        Serial.println("Enter your mode of Conversion (number 0 - 3): ");
        while (Serial.available() == 0); // Waits for the user input
        mode = Serial.read(); // Reads the input string from serial port
        Serial.print("Number recieved: ");
        Serial.println(mode);
        delay(500);
        if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
        {
          //sensor.setConversionMode(mode);
          Serial.println();
          delay(500);
        }
        else
        {
          Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
        }
        delay(1000);
      }
      else // Runs when the device was unable to setup properly
      {
        Serial.println("Device failed to setup");
      }
    }


message:
Include guards vs #pragma once

Is there any particular reason why `#pragma once` doesn't seem to be used in Arduino code? Is this just because it's not a well-known feature, or is there some overriding reason to use `#ifndef XXX_H`/`#define XXX_H`/`#endif`?

body:
`#pragma once` operates on the absolute filename of a file. Include guards work on the content of the file.

If you have multiple copies of the same library (maybe one library has some parts of another included in it - it happens...) `#pragma once` would have no hope of working right.

Add to that the fact that the Arduino IDE copies some files around the place when building and `'#pragma once` is pretty much screwed.

Include guards work regardless. So sensible people use include guards and shun `#pragma once`.


message:
Is there an alternative to soldering to connect boards?

I know that shields are usually soldered to headers so they can be attached to the board with the Arduino. I have a tremor, which makes soldering impossible. **Are there ways of connecting PCBs without soldering?**

If a concrete example would be helpful, I would like to connect the [Adafruit WINC1500 WiFi Shield][1] to a [SparkFun RedBoard][2].

  [1]: https://www.adafruit.com/product/3653
  [2]: https://www.sparkfun.com/products/13975

body:
Yes, there are ways. There is a system called "Press Fit" where the pins have a bulge in one end of them. This grips the inside of the holes in place of soldering.

A number of companies make them, such as [TE Connectivity](https://www.te.com/usa-en/products/connectors/automotive-connectors/intersection/press-fit-connections.html) and [Positronic](https://www.connectpositronic.com/en/press-fit-connectors/).

Of course, these depend on the holes being just the right size, and finding the right connectors could be tricky... so... your mileage may vary.

But nothing is better than getting someone to solder the pins for you. You could teach one of your younger relatives to solder, for example...


body:
Boards with headers can be connected using jumper wires or hookup wire. If there are no headers then I don't think you will be able to get a reliable connection without soldering.

The RedBoard you linked to uses headers, so you should be able to use jumpers with it, but I suspect you are out of luck with the WiFi shield. You'll probably either need to find a version that is built using headers or ask/hire somebody to solder headers onto it for you.

As for the center portion of the shield you should probably just skip that part and use a breadboard, which uses jumpers or hook-up wires.


body:
Sparkfun has a lot of sensor boards that use their [Qwiic Connect System](https://www.sparkfun.com/qwiic). Those you can just plug in, and even chain together, with their cables with JST connectors.

Adafruit has their [Flora](https://www.adafruit.com/category/92) like of products. Mostly tailored to wearables, but with their large connector pads, you can easily connect the board to the sensors wit [alligator clips](https://www.adafruit.com/product/1592).


message:
My webswerver works fine when there is only 1 servo used/defined in my code

I am trying to make a webserver which controls my 3 servos for a robotic arm. When I define and use 1 servo it is nice and quick, but whereas if I use more than 1 the webserver is very slow and barely loads. Someone please help.

I will post the code below. With this code the webserver is very slow:

    #include <Ethernet.h>
    #include <SPI.h>
    #include <Servo.h>
    String readString;
    Servo robotservo1;
    Servo robotservo2;

    byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x29, 0xAF };
    byte ip []={10,1,1,121};// check back of your shield
       // when the shield connected the serioal monitor will display the ip address
    EthernetServer server(80);

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
     Ethernet.begin(mac, ip);
    server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());// prints my IP address, so you can copy paste in browsr

    robotservo1.attach(9);
    robotservo2.attach(10);

    robotservo1.write(45);
    robotservo2.write(45);

    }

    void loop() {
      // put your main code here, to run repeatedly:
    EthernetClient client = server.available();
    if (client) {
    if (client.connected()){
      if (client.available()) {
      char c = client.read();
      if (readString.length() < 100) {
              readString += c;
            }
      if (c == '\n') {
              Serial.println(readString);
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println();
              client.println("<hmtl>");
              client.println("");
    client.println("<title>Ethernet shield, hopefully works</title>");
    client.println("");
    client.println("<title>");
    client.println("Control the robotic arm using the buttons below");
    client.println("</title>");
    client.println("");
    client.println("");
    client.println("<meta http-equiv=\"refresh\" content=\"4\">");
    client.println("");
    client.println("Control the robotic arm by pressing the buttons below!!!");
    client.println("");
    client.println("");
    client.println("
");
    client.println("Servo 1 or Base");
    client.println("
");
    client.println("<FORM>");
    client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?baseserv0\'>");
    client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?baseserv45\'>");
    client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?baseserv90\'>");
    client.println("</FORM>");
    client.println("
");

    client.println("
");
    client.println("Servo 2 or Elbow");
    client.println("
");
    client.println("<FORM>");
    client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?elbowserv0\'>");
    client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?elbowserv45\'>");
    client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?elbowserv90\'>");
    client.println("</FORM>");
    client.println("
");

    client.println("
");
    client.println("Servo 3 or Shoulder");
    client.println("
");
    client.println("<FORM>");
    client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?shoulderserv0\'>");
    client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?shoulderserv45\'>");
    client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?shoulderserv90\'>");
    client.println("</FORM>");
    client.println("
");

    client.println("");
    client.println("");
    client.println("");

     delay(1);

      if(readString.indexOf("?baseserv0") >0)
                {
                  robotservo1.write(0);
                }

              else{
                if(readString.indexOf("?baseserv45") >0)
                {
                  robotservo1.write(45);
                }

              else{
                if(readString.indexOf("?baseserv90") >0)
                {
                  robotservo1.write(90);
                }

      }

    }

      if(readString.indexOf("?baseserv0") >0)
                {
                  robotservo2.write(0);
                }

              else{
                if(readString.indexOf("?elbowserv45") >0)
                {
                  robotservo2.write(45);
                }

              else{
                if(readString.indexOf("?elbowserv90") >0)
                {
                  robotservo2.write(90);
                }

      }

    }

      readString="";
              client.stop();
      }}}}}

body:
I have no Ethernet board so I couldn't test the timings, but when I compiled your code for an Uno, I got a low free-memory warning; that 83% of memory was used and stability problems could occur. That's the compiler telling you that your code might not run right. It may very well be the reason your server was slow. The largest user of data-memory (SRAM) is the text in your client.print() statements.

I put that text into program-memory (Flash, of which there is over 10x as much!) which got the SRAM use down to 29%! Try running that and see if it won't behave a little bit better:

    #include <Ethernet.h>
    #include <SPI.h>
    #include <Servo.h>
    String readString;
    Servo robotservo1;
    Servo robotservo2;

    byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x29, 0xAF };
    byte ip [] = {10, 1, 1, 121}; // check back of your shield
    // when the shield connected the serioal monitor will display the ip address
    EthernetServer server(80);

    void setup() {
       // put your setup code here, to run once:
       Serial.begin(9600);
       Ethernet.begin(mac, ip);
       server.begin();
       Serial.print("server is at ");
       Serial.println(Ethernet.localIP());// prints my IP address, so you can copy paste in browsr

       robotservo1.attach(9);
       robotservo2.attach(10);

       robotservo1.write(45);
       robotservo2.write(45);

    }

    void loop() {
       // put your main code here, to run repeatedly:
       EthernetClient client = server.available();
       if (client) {
          if (client.connected()) {
             if (client.available()) {
                char c = client.read();
                if (readString.length() < 100) {
                   readString += c;
                }
                if (c == '\n') {
                   Serial.println(readString);
                   client.println(F("HTTP/1.1 200 OK"));
                   client.println(F("Content-Type: text/html"));
                   client.println();
                   client.println(F("<hmtl>"));
                   client.println(F(""));
                   client.println(F("<title>Ethernet shield, hopefully works</title>"));
                   client.println(F(""));
                   client.println(F("<title>"));
                   client.println(F("Control the robotic arm using the buttons below"));
                   client.println(F("</title>"));
                   client.println(F(""));
                   client.println(F(""));
                   client.println(F("<meta http-equiv=\")refresh\" content=\"4\">"));
                   client.println(F(""));
                   client.println(F("Control the robotic arm by pressing the buttons below!!!"));
                   client.println(F(""));
                   client.println(F(""));
                   client.println(F("
"));
                   client.println(F("Servo 1 or Base"));
                   client.println(F("
"));
                   client.println(F("<FORM>"));
                   client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?baseserv0\'>"));
                   client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?baseserv45\'>"));
                   client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?baseserv90\'>"));
                   client.println(F("</FORM>"));
                   client.println(F("
"));

                   client.println(F("
"));
                   client.println(F("Servo 2 or Elbow"));
                   client.println(F("
"));
                   client.println(F("<FORM>"));
                   client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?elbowserv0\'>"));
                   client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?elbowserv45\'>"));
                   client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?elbowserv90\'>"));
                   client.println(F("</FORM>"));
                   client.println(F("
"));

                   client.println(F("
"));
                   client.println(F("Servo 3 or Shoulder"));
                   client.println(F("
"));
                   client.println(F("<FORM>"));
                   client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?shoulderserv0\'>"));
                   client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?shoulderserv45\'>"));
                   client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?shoulderserv90\'>"));
                   client.println(F("</FORM>"));
                   client.println(F("
"));

                   client.println(F(""));
                   client.println(F(""));
                   client.println(F(""));

                   delay(1);

                   if (readString.indexOf("?baseserv0") > 0)
                   {
                      robotservo1.write(0);
                   }

                   else {
                      if (readString.indexOf("?baseserv45") > 0)
                      {
                         robotservo1.write(45);
                      }

                      else {
                         if (readString.indexOf("?baseserv90") > 0)
                         {
                            robotservo1.write(90);
                         }

                      }

                   }

                   if (readString.indexOf("?baseserv0") > 0)
                   {
                      robotservo2.write(0);
                   }

                   else {
                      if (readString.indexOf("?elbowserv45") > 0)
                      {
                         robotservo2.write(45);
                      }

                      else {
                         if (readString.indexOf("?elbowserv90") > 0)
                         {
                            robotservo2.write(90);
                         }

                      }

                   }

                   readString = "";
                   client.stop();
                }
             }
          }
       }
    }


message:
Can I solder wall cord directly to servo?

I have a servo which requires 7.4v and a wall power cord which says the output is 7.4v but the connector does not fit that of the servo. Is it safe to snip off the end of the wall cord and solder the internal wires directly to the servo?

body:
First choice: Attach compatible, polarized connectors to both pigtails.

Alternatively, you can solder it up but the result is certainly less convenient to use. I like [heat-shrink tubing][1] for insulating wire-to-wire solder joints, one over each solder joint and a third, slightly larger one over both. (My favorite way to screw this up is to forget to push all three shrink tubes over the wires **before** I solder the joints. :)

  [1]: https://www.lowes.com/pl/Heat-shrink-tubing-Electrical-testers-tools-Electrical/4294722456


message:
About ATmega32 event system

From my reading on internet i found that the Event system allows peripherals to trigger each other without involving the CPU...does the event system is software or hardware?also does ATmega32 support it? also can any one give me a real application for event system?

body:
The ATmega32 has a coupe of peripheral-to-peripheral communication
features that are in some way similar to the Event System:

* You can use the analog comparator to trigger an input capture on
  Timer 1.
* You can use the analog comparator, external interrupt 0, Timer 0, or
  Timer 1 to trigger a conversion on the ADC.

These are the only ones I know about. As you can see, it's a very
limited functionality. From what I read, the Event System looks like a
generalization of this idea. You have many peripherals that can trigger
events (event emitters), many that can be triggered by such events
(event receivers), and you can connect any event emitter to any event
receiver. You thus have much more flexibility than the very limited
peripheral-to-peripheral communication facilities provided by the
ATmega32.

The configuration of the event system (emitter to receiver connections)
is performed by your software. However, once the connection is
established, the peripheral-to-peripheral communication is entirely
hardware, and does not depend on the CPU.


body:
The 'old' ATmega 8 bit microcontrollers don't have an event system peripheral. The new "megaAVR 0 series" has an event system. Atmega 4809 on Arduino Uno WiFi Rev2 and on Nano Every is "megaAVR 0-series". The event system of the new ATmegas is similar to SAMD event system I know.

ARM MCUs for example SAMD by Atmel/Microchip used in Arduino Zero and MKR have an event system. Event system is a MCU peripheral. It enables direct communication between peripherals without the involvement of the CPU of the MCU.

The MCU peripherals are what makes the MCU a MCU. Examples of peripherals are GPIO pins, external interrupts, timers, SERCOM, watchdog...

To give you an example of use of the event system. To perform AC phase cutting with a Triac the Triac must be pulsed at right time after zero crossing. (It turns off self at next zero crossing.) To achieve this with MCU, the MCU must sense the input from the zero crossing detection circuit, then start timing the requested off time, then start a pulse to triac's gate and then stop the pulse.

It can be implemented with an external interrupt function for zero crossing, which starts a timer to generate a pulse on a wave output pin.

On ARM MCU it is possible to setup the event system to start the timer on external interrupt over an event, without an interrupt function. Then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals.

After setting up the zero crossing detector input pin for external interrupt without interrupt function and setting up the timer to execute one-shot pulse, the event system will re-trigger the timer on external interrupt.

a simple Arduino SAMD lib for a Triac/ZC module (in development):

    #ifndef _TRIAC_LIB_
    #define _TRIAC_LIB_

    namespace Triac {

    const unsigned long AC_WAVE_MICROS = 10000; // at 50 Hz
    const int TIMER_PRESCALER = 8;
    const unsigned long PULSE_PERIOD = ((F_CPU / 1000000) * 200) / TIMER_PRESCALER;

    Tcc* TCC;

    void syncTCC() {
      while (TCC->SYNCBUSY.reg & TCC_SYNCBUSY_MASK);
    }

    void zeroCrossing() {
    }

    void setup(byte zcPin, byte triacPin) {

      // setup the external interrupt
      attachInterrupt(zcPin, zeroCrossing, RISING);
      uint8_t ulExtInt = g_APinDescription[zcPin].ulExtInt;
      EIC->EVCTRL.reg |= (1 << ulExtInt);// enable event
      EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT(1 << ulExtInt); // turn-off interrupt

      const PinDescription& pinDesc = g_APinDescription[triacPin]; // Arduino pin description
      TCC = (Tcc*) GetTC(pinDesc.ulPWMChannel);
      uint8_t tcChannel = GetTCChannelNumber(pinDesc.ulPWMChannel);

      // setup the pin as TCC wave out pin
      PORT->Group[pinDesc.ulPort].PINCFG[pinDesc.ulPin].bit.PMUXEN = 1;
      PORT->Group[pinDesc.ulPort].PMUX[pinDesc.ulPin >> 1].reg |= PORT_PMUX_PMUXE_F;

      // setup the timer

      REG_GCLK_CLKCTRL = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TCC0_TCC1)); // assign clock
      while ( GCLK->STATUS.bit.SYNCBUSY == 1 );

      TCC->CTRLA.bit.SWRST = 1; // reset timer
      syncTCC();
      TCC->WAVE.reg |= TCC_WAVE_WAVEGEN_NPWM; // normal PWM as wave output mode
      syncTCC();
      TCC->CTRLBSET.reg = TCC_CTRLBSET_ONESHOT | TCC_CTRLBSET_DIR; //one shot and count down
      syncTCC();

      TCC->PER.reg = ((F_CPU / 1000000) * AC_WAVE_MICROS) / TIMER_PRESCALER; // initial value of period (triac off)
      syncTCC();
      TCC->CC[tcChannel].reg = PULSE_PERIOD; // pin on at compare match and off at 0 (timer counts down)
      syncTCC();

      TCC->EVCTRL.reg |= TCC_EVCTRL_TCEI0 | TCC_EVCTRL_EVACT0_RETRIGGER; // retrigger on event
      syncTCC();
      TCC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV8 | TCC_CTRLA_ENABLE; // set prescaler and enable
      syncTCC();

      // event system
      PM->APBCMASK.reg |= PM_APBCMASK_EVSYS; // power it on
      GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(EVSYS_GCLK_ID_0) | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN(0); // assign a clock
      while (GCLK->STATUS.bit.SYNCBUSY);

      EVSYS->CTRL.bit.SWRST = 1; // reset
      while(EVSYS->CTRL.bit.SWRST);

      EVSYS->USER.reg = EVSYS_ID_USER_TCC0_EV_0 | EVSYS_USER_CHANNEL(1); // set user TCC0 event 0 on channel 0
      EVSYS->CHANNEL.reg = EVSYS_CHANNEL_CHANNEL(0) | EVSYS_CHANNEL_PATH_ASYNCHRONOUS | // channel 0 is async
          EVSYS_CHANNEL_EDGSEL_FALLING_EDGE | EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_0 + ulExtInt); // source is ext.interrupt
      while (!EVSYS->CHSTATUS.bit.USRRDY0);
    }

    /*
     * r is from interval <0.0, 1.0>
     */
    void setPeriod(float r) {
      unsigned long period = ((F_CPU / 1000000) * ((1.0 - r) * AC_WAVE_MICROS)) / TIMER_PRESCALER;
      TCC->PER.reg = period + PULSE_PERIOD;
      syncTCC();
    }

    }
    #endif

[other SAMD example][1]

  [1]: https://martinvb.com/wp/as5030-magnetic-encoder-capturing-a-pwm-signal-with-an-atsamd21/


message:
How to rotate a servo motor on a specific angle?

I am trying to rotate a top on a specific angle after every 1 second. For example: 1 degree/second. I have two question:

 1. Can I achieve this with servo motors?
 2. If not, what motor should I use?

I know this question has very little description. I am mainly a programming guy. I don't much about arduino stuff. It's actually a hobby project for me.

Thanks in advance.

body: You can rotate the servo motor per degree, but it has it's limitations, it only has 0-180 degrees of movement. If you need to rotate beyond that, I would recommend using Stepper motors, they can be very precise, but they don't have a potentiometer, like a servo does, so, after resetting the system, the motor won't comeback to the starting position.


body:
The kind people who have written the Arduino libraries include [software drivers for servo control][1].  These drivers abstract the hardware from the programmer of the sketch software (the sketch is application software you write in C or C++).  It is unnecessary to understand the driver in detail.  However the servo driver software (likely written in C++) can been examined [here][2].

To move a normal servo to a particular position, make a call to the Arduino Servo Driver using the [function write(angle)][3] passing an angle value from 0 to 180.  The value is an approximation of degrees and the value type is of type integer.

In the above links you will find [this example][4] of sweeping the servo motor across its range:

    /* Sweep
     by BARRAGAN <http://barraganstudio.com>
     This example code is in the public domain.

     modified 8 Nov 2013
     by Scott Fitzgerald
     http://www.arduino.cc/en/Tutorial/Sweep
    */

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

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

Proceed to that page for more details including a schmatic (diagram) of how the servo is connected to an Arduino Uno board.

  [1]: https://www.arduino.cc/en/Reference/Servo
  [2]: https://github.com/arduino-libraries/Servo
  [3]: https://www.arduino.cc/en/Reference/ServoWrite
  [4]: https://www.arduino.cc/en/Tutorial/Sweep


message:
Arduino DUE- flash space for user

I need for my project to save only 32bit in non-volatile storage.
What is the easiest/cheapest way to do that in Arduino DUE?

ArduinoDUE is Atmel SAM3X8E so according to the attached table (from Atmel DS)

[![Can I use this NFC SRAM space as non-volatile memory?][1]][1]

In the chip I have 4KB of NFC SRAM. NFC = Nand Flash Controller, so I have 4KB of internal flash in the internal SRAM?

Thanks,

  [1]: https://i.stack.imgur.com/m7s9g.jpg

body:
It looks like there's at least one library out there to emulate EEPROM functionality in the DUE using Flash.

https://github.com/sebnil/DueFlashStorage


message:
Why am only hearing noise or no sound?

Alright, there is something missing in the question, **I was able to hear one sound of the files** and the others apply to the question I asked and that is why I am wondering. what is happening!

Here is the code:

   <!-- language: c -->

    #include <SD.h>                      // need to include the SD library
    #define SD_ChipSelectPin 4  //using digital pin 4 on arduino nano 328, can use other pins
    #include <TMRpcm.h>           //  also need to include this library...
    #include <SPI.h>

    TMRpcm tmrpcm;   // create an object for use in this sketch

    void setup(){

      tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc

      Serial.begin(9600);
      if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
        Serial.println("SD fail");
        return;   // don't do anything more if not
      }
      tmrpcm.play("music.mp3"); //the sound file "music" will play each time the arduino powers up, or is reset
    }

    void loop(){

      if(Serial.available()){

        if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback

          /* These are spkean Numbers */

         // tmrpcm.play("1-24bit.wav");
         // tmrpcm.play("1-16bit.wav");
         // tmrpcm.play("200-insane.mp3");
         // tmrpcm.play("music.mp3")       // Strangely this is the working perfectly with good sound
         // tmrpcm.play("200-standard.mp3");
            tmrpcm.play("200.wav");        // from https://evolution.voxeo.com/library/audio/prompts/numbers/index.jsp
        }
      }

    }

Everything is good when I play this `tmrpcm.play("music.mp3");` but the others I hear aliens sounds expect this `tmrpcm.play("200.wav");` which I can hear the number two hundred but I feel the sound is 4-bit depth which very noisy. The files used in the code are [**here**][1]

For clarification previously, I thought it was amplifying issues which then I had to used **LM386** but the sound was the same noise with `tmrpcm.play("200.wav");` and later when I tried this `tmrpcm.play("music.mp3");` I was shocked it worked perfectly like what I need it to be!  so I was curious I removed the **LM386** and played this `tmrpcm.play("music.mp3");` again and worked alright just maybe less volume.

  [1]: https://github.com/noajm/Audio-For-Arduino

body:
As @Juraj mentioned it was solved by changing the setting and I was able easily to play the sound when I matched the setting to this file:

[![enter image description here][1]][1]

So, I could not create one from scratch matches above setting but I was able to convert existing sound through this [site][2]
which allowed me to convert with desire setting and here finally the exiting sound has matched the setting:

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/DWG6x.png
  [2]: https://www.online-convert.com/
  [3]: https://i.stack.imgur.com/aJJOY.png


message:
LED not blinking when using a transistor

I want to control an led using a transistor. The led gets it‘s power from an external 5v dc power supply.

For the transistor I use an 1kΩ base resistor. The transistor is a BC547C (npn). The datashet is available [here][1].
The led is red (3mm), draws 20mA of current and needs 2V.

I‘ve got a very simple Arduino sketch and wiring setup:

**Code:**

    #define ledPin 6

    void setup() {
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      digitalWrite(ledPin, HIGH);
      delay(1000);
      digitalWrite(ledPin, LOW);
      delay(1000);
    }

**Wiring diagram:**

[![wiring diagram][2]][2]

**Problem:**

1. The led is not blinking but shining at full power constantly.
2. Disconnecting `ledPin 6` from the Arduino (to mimic `digitalWrite(ledPin, LOW)`) still lets the led shine, just not as bright. The LED should be off in that case, not just dimmed to 50% brightness.

**What I tried so far:**

1. I tried using different base resistors. I tried 2kΩ, 3kΩ, 2.5kΩ, 470Ω, 1.5kΩ. The behavior did not change.
2. I tried using different leds. Same behavior. LEDs are shining constantly, not blinking, and are dimmed when disconnecting `pin 6`.
3. I used another BC547C to see if the first one was broken. It wasn’t. I still got the same behavior.
4. Connecting the led directly to the Arduino without the transistor and external power supply let’s the led blink exactly how it was defined in code.

Any ideas?
I several-times-checked the wiring in my setup. It should not be the problem.

  [1]: https://produktinfo.conrad.com/datenblaetter/125000-149999/140539-da-01-ml-TRANSISTOR_BC547C_TO_92_de_en.pdf
  [2]: https://i.stack.imgur.com/GE4E9.jpg

body:
Without a common reference (ground) between the Arduino power supply and the external power-supply, again, you have a floating base, as you can't know what the Arduino's 5v output (or local ground) looks like to the external circuit.

Connect the two grounds. That should correct the LED brightness with respect to the Arduino output pin level. Then, if you need the external circuit to behave in a specific way when the base is disconnected from the Arduino, add a 10K resistor from the transistor base to the external +5 if you want the LED to be on, or to ground, if you want it to be off. Again, I'm guessing at both the pullup/pulldown value (but 10K should be in the ballpark) and the switching sense ('On' or 'Off' for base at +5), but from the expectation state in your point (2.), I think I have it right.

Update: But see @EdgarBonet's comment to me about BJT's. I'd still avoid leaving an input floating as a matter of practice, but it seems not relevant in your circuit.


message:
Does LabVIEW Linx affect the communication speed with Arduino?

I am using LabVIEW to connect to Arduino Mega. I control a logic gate to switch the current On/Off and at the same time there is an I2C connection with a sensor. It came to my attention that the sensor time resolution is very low and I cannot get enough data points from the sensor (I know that the sensor is capable of much better resolutions). My question, is this a problem inherent to LabVIEW and Linx module or my program in LabVIEW? Should I turn to coding with Arduino programming language or C?
note! My reason for using LabVIEW is that I need to sync timing of data aqcuisition with another device which is connected through another VISA port.

body:
For specific timing requirements, my recommendation is to write your own Arduino code.

The Linx module deploys its own `ino` program to the Arduino and uses serial IO to send it commands and receive data from it. Open [NI I/O Trace](https://knowledge.ni.com/KnowledgeArticleDetails?id=kA00Z000000PAr6SAG&l=en-US) to observe that traffic.


message:
Arduino wrap or subclass print() to work with multiple Serial

I am writing an Arduino program that uses Bluetooth on `Serial1` to print text to a Bluetooth terninal on an Android phone and also normal `Serial` to print text to the serial monitor on a laptop. I would like to wrap the `Serial.print()` and `Serial.println()` functions so that they work with either or both `Serial` and `Serial1`. For example the code below works fine depending on the values of the global variables. But this only works for single chars, but `print()` and `println()` can take a very wide variety of datatypes. If I also define overloading functions for int and String types it works fine, but that is a very verbose and maybe fragile solution, it also ignores the optional inputs to the underlying functions. What is the proper way to do this ?

    void print(char x) {
      if (g_use_Serial)
        Serial.print(x);
      if (g_use_Serial1)
        Serial1.print(x);
    }

    void println(char x) {
      if (g_use_Serial)
        Serial.println(x);
      if (g_use_Serial1)
        Serial1.println(x);
    }

---------------

I have implemented the solution suggested and it works nearly perfectly. There seems to be a problem with the new line characters on the bluetooth (`Serial1`) connection.

The code is:

    class DualPrint : public Print
    {
    public:
        DualPrint() : use_Serial(false), use_Serial1(false) {}
        virtual size_t write(uint8_t c) {
            if (use_Serial) Serial.write(c);
            if (use_Serial1) Serial1.write(c);
            return 1;
        }
        bool use_Serial, use_Serial1;
    } out;

    void setup()  {
      Serial.begin(9600);
      Serial1.begin(9600);
      delay(1000);
    }

    void loop() {

      out.use_Serial = true;
      out.print("Printed to USB only.\n");
      out.use_Serial1 = true;
      out.print("Printed to both USB and BT.\n");
      out.use_Serial = false;
      out.print("Printed to BT only.\n");
      out.use_Serial1 = false;

      delay(3000);
    }

The output on the USB Serial monitor is as expected:

    Printed to USB only.
    Printed to both USB and BT.
    Printed to USB only.
    Printed to both USB and BT.

The output on the Bluetooth terminal is not as expected, the new lines are not in the right position:

    Printed to both USB and BT.Pri
    nted to BT only.
    Printed to both USB and BT.Pr
    inted to BT only.
    Printed to both USB and BT.Pr
    inted to BT only.
    Printed to both USB and BT.Pr
    inted to BT only.

Any suggestions on how to fix this. Are there other function members that need to be re-implemented to make this work properly?

Many thanks for high quality answers so far.

body:
You can create a class derived from `Print` that forwards its output to
either or both `Serial` and `Serial1`. The only method you need to
implement for this to work is `write(uint8_t)`:

<!-- language-all: lang-c++ -->

    class DualPrint : public Print
    {
    public:
        DualPrint() : use_Serial(false), use_Serial1(false) {}
        virtual size_t write(uint8_t c) {
            if (use_Serial) Serial.write(c);
            if (use_Serial1) Serial1.write(c);
            return 1;
        }
        bool use_Serial, use_Serial1;
    } out;

You would use it like this:

    out.use_Serial = true;
    out.println("Printed to Serial only");
    out.use_Serial1 = true;
    out.println("Printed to both Serial and Serial1");
    out.use_Serial = false;
    out.println("Printed to Serial1 only");

Note that with this approach, unlike yours, printing number will format
them as text only once, and the underlying `Serial` and `Serial1` will
only handle the resulting characters.

------------------------------------------------------------------------

**Edit**: To answer the question in OP's comment, the construct

    class ClassName
    {
        ...definition...
    } classInstace;

is a shotcut for

    class ClassName
    {
        ...definition...
    };
    ClassName classInstace;

A very similar construct exists in plain C:

    struct struct_name {
        ...the struct fields...
    } struct_instance;


message:
Sending data through esp8266 using arduino

I'm trying to send GPS data using esp8266 using Arduino board. I've used neo-6m receiver and esp8266-01 module. Below is my program using AT commands. The program is successfully compiled and loaded to the Arduino board, but the only output it gives on serial monitor is a simple begin. None of the AT commands are being executed. Not even the module connects to wi-fi. I can't point the error in my code. Please help me find the possible error.
Thank you

<!-- language-all: lang-cpp -->
```

#include <TinyGPS++.h>
#include <SoftwareSerial.h>

TinyGPSPlus gps;

String ssid = "JioFi_244DB1D";

String password = "q52fq74c9s";

SoftwareSerial esp(6,7);

SoftwareSerial ss(8,9);

char Lat[12], Lon[12], alt[12],ch;

byte NOS;

byte l;

String webpage;

void reset(){

  esp.println("AT+RST");

  delay(1000);

  if(esp.find("OK"))

    Serial.println("Module Reset");

    }

    void ConnectWifi(){

      esp.println("AT+CIPMUX=1");

      esp.println("AT+CWMODE=1");

      String cmd = "AT+CWJAP=\""+ssid+"\",\""+password+"\"";

      esp.println(cmd);

      delay(4000);

      if(esp.find("OK"))

      Serial.println("Connected!");

      else {

        ConnectWifi();

        Serial.println("Connecting..");

        }

      }

void setup(){

  esp.begin(9600);

  Serial.begin(9600);

    Serial.println("begin");

  reset();

  ConnectWifi();

  esp.println("AT+CIFSR");

  while(esp.available()>0){

  if(esp.find("STAIP"))

  {Serial.println("IP Address:");

  while(esp.available()>0)

  {ch=esp.read();

  Serial.print(ch);}

  }}}

void loop() {

    ss.listen();

    delay(2000);

    while(ss.available()>0)

    {

    gps.encode(ss.read());

    {

      if(gps.location.isValid()){

           // dtostrf(gps.location.lat(),1,6,Lat);

      //dtostrf(gps.location.lng(),1,6,Lon);

      webpage = "<!DOCTYPE html><html><body><form method = \"post\" action =\"http://localhost/php/esppost.php\"><label for = \"latitude\">Latitude:<\label><input type=number id = \"latitude\" name= \"latitude\" readonly value=";

        //                L = Lat.length();

      l= webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lat(),6);

      esp.print("\">");

      delay(500);

      webpage = "<Label for = \"Longitude\">Longitude:</Label><input type = \"number\" id = \"Longitude\" name = \"Longitude\" readonly value =\"";
      l=webpage.length();

      //L = Lon.length();

      esp.println("AT+CIPSEND=0,");

                        esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lng(),6);

      esp.print("\">");

      }

      else

      webpage="Location Invalid";

      l=webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(l+2);

      esp.println(webpage);

      delay(500);

      if(gps.altitude.isValid()){

      dtostrf(gps.altitude.meters(),1,6,alt);

      webpage = "<label for=\"Altitude\">Altitude:<\label><input type = number id=\"Altitude\" name=\"Altitude\" readonly value=";

      l=webpage.length();

      //L= alt.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+2);

      esp.println(webpage);

      esp.print(gps.altitude.meters(),6);

      esp.print("\">");

      }

     if(gps.satellites.isValid()){

        NOS= gps.satellites.value();

        webpage= "<lable for = \"NOS \"> Number of Satellites:<\label><input type=number id=NOS name= NOS readonly value =";

        l= webpage.length();

        esp.println("AT+CIPSEND=0,");

        esp.print(2+l+22);

        esp.println(webpage);

        esp.print(gps.satellites.value());

        esp.print("></body></html>");

        delay(500);

     }}

    esp.println("AT+CIPCLOSE");

      }
}
```

body:
SoftwareSerial can't listen on two instances. There is a `.listen()` function to switch between SoftwareSerial instances.

The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.

You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.

You could use the RX pin of Uno to receive data from GPS module over hardware Serial.


message:
Locate devices that can move among multiple connections

I don’t know if this is even doable, but the idea is to have a large board with many (500+) locations where I objects can connect, each object having a single LED, and be able to illuminate the LED on any object, no matter where it is connected on the board.  So the requirement is that the objects can be moved to any of the connections on the board and and that the board can have any number if it’s connections occupied.

It seems obvious that each object would have to be able to identify itself and that each connection would have to be able to supply both a signal both ways and and provide power to light the LED.  On the code side, I’d need to be able to iterate through the connections and identify the desired object by some unique identifier and send a signal to turn the LED on and off.  I’m a .Net developer with little knowledge of electronics, but I’m willing to learn if it’s possible to do this.  I haven’t been able to find any arduino examples similar enough to provide some idea of where to start.  I don’t know if this is something that can even be done with Arduino or what components would be required if it is possible.

I’d appreciate any guidance on how this could be done or even suggestions as to what might be a better approach toward finding the guidance necessary to build this.

body:
Your question is awfully vague.

There is a protocol called I2C that's commonly used for microcontrollers. It's a serial bus that has a data line, a clock line, power, and ground. That might meet your needs.

Each device on an I2C bus is supposed to have a unique address. You send commands to it using that address, and it doesn't matter where it is located physically.

I2C is designed to be a chain, and each device has 2 connectors that pass the connection on to the next device on the chain.

I2C also uses a byte address, so you could only have 255 unique devices.


message:
Arduino RS485 shield to RS485 temperature & humidity sensor

I’m try to get data from rs485 is not work please advise to me.

    1. Try to connect PC usb485 to DY-MD02 is work.
        Send command “AUTO” or “READ”

    2. Try to Arduino rs485 shield to DY-MD02 is not work.
        Send command “AUTO”
my code

''''

    char command[4] = {'A', 'U', 'T', 'O'};

    int n = sizeof(command)/sizeof(command[0]);   // Number of elements in an array

    String incoming = "";   // for incoming serial string data

    void setup()

    {

          // initialize serial ports
          Serial.begin(9600);
          pinMode(EN,OUTPUT);
          digitalWrite(EN,HIGH); //Enable high, RS485 shield waiting to transmit data
          Serial.write(command,n); //Test send command Auto,Read to RS485
          delay(500);
    }

    void loop()

    {

          String temp;
          digitalWrite(EN,LOW); //Enable low, RS485 shield waiting to receive data

          while(Serial.available() > 0 )
          {
              temp=Serial.read();
              Serial.println(temp);
              delay(1000); //Delay for some time, waiting for data transmitted
          }

    }

''''

----------
if change code to = ***Serial.readString()*** not show anything.

please help me
Thank

[![XY-MD02][1]][1]

[![PC USB485 is OK][2]][2]

[![Data][3]][3]

  [1]: https://i.stack.imgur.com/UTPVs.jpg
  [2]: https://i.stack.imgur.com/hmTYe.png
  [3]: https://i.stack.imgur.com/Xd1JQ.png

---

to Juraj

Maker tell me can connect with Arduino uno and send manual to me.

see in attach file.

[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]

  [1]: https://i.stack.imgur.com/0eNHG.jpg
  [2]: https://i.stack.imgur.com/qVQhy.jpg
  [3]: https://i.stack.imgur.com/QkixI.jpg
  [4]: https://i.stack.imgur.com/36RbV.jpg
  [5]: https://i.stack.imgur.com/LhCWp.jpg

body:
i'm tray change this code to readStringUntil, is OK

    if(Serial.available() > 0)
      {
        temp = Serial.readStringUntil('\n');
        Serial.println(temp);
        delay(1000); //Delay for some time, waiting for data transmitted
      }

Thank all for help me
^^


body:
I will suggest try to use [Modbus Master][1] library it will help you get the data from sensor. The issue with the code is you are only sending the command but while interfacing with modbus there is a packet/ frame which you need to form and then send it the packet/frame format is in the below diagram[![Modbus Packet][2]][2]

I will prefer use an Arduino Mega or other arduino which have more than 1 Serial port for communication. I also faced a similar issue but it was resolved after digging a little bit you can have a look at the issue [here][3]

  [1]: https://github.com/4-20ma/ModbusMaster
  [2]: https://i.stack.imgur.com/0hxCz.jpg
  [3]: https://arduino.stackexchange.com/questions/78648/read-internal-registers-of-rs485?


message:
Creating WebServer ip:port on esp8266 module

I creating Clever House with wifi. For this I'm using ESP8266 as module connected to Arduino. They communicate with SoftwareSerial. And there's a problem with global webserver on ESP8266. That I think to do it I must do this:

1.Create Webserver on another port(Neither 80 nor 443) Or Host will be in this model: https://ip:port/

2.Open port forwarding for port.

3.Almost done.

So how can I do it with AT commands?

body:
As @Juraj mentioned, [martyncurrey.com/arduino-esp8266-web-server][1] , I need to start server with command: `AT+CIPSERVER=1,5000`, IP is IP of the esp8266 and reserve it on router or use the AT command to set static IP.

  [1]: https://martyncurrey.com/arduino-esp8266-web-server


message:
Run a loop for only 60 secondes

How do run a code on arduino for only 60 secondes and than shut it down? I know I have to use the millis() function, but I do not know how to it in my code. Sorry if it looks unclear, but I only need to know how to program the millis() function. This is my first code so I have no experience.

    int main(void)
    {
    pin_mode(A13,INPUT);
    pin_mode(A12,INPUT);
    pin_mode(A11,INPUT);
    pin_mode(A10,INPUT);
    pin_mode(A15,INPUT);
    pin_mode(D0,OUTPUT);
    pin_mode(D1,OUTPUT);
    pin_mode(D2,OUTPUT);
    pin_mode(D3,OUTPUT);

    while (1)
    {
     int potmeter1 = read_analog_pin(A13);
     if (potmeter1 >= 1000 && potmeter1 < 1100){
     gen_pwm(D0, 1000, 100);

      int potmeter2 = read_analog_pin(A12);
      if (potmeter2 >= 2000 && potmeter2 < 2050){
      gen_pwm(D1, 1000, 100);

       int potmeter3 = read_analog_pin(A11);
       if (potmeter3 >= 500 && potmeter3 < 525){
        gen_pwm(D2, 1000, 100);

         int potmeter4 = read_analog_pin(A10);
         if (potmeter4 >= 3500 && potmeter4 < 3510){
          gen_pwm(D3, 1000, 100);

     {
      int lichtsensor = read_analog_pin(A15);
      if (lichtsensor >= 2000 && lichtsensor < 3500 && potmeter1 >= 1000 && potmeter1 < 1100 && potmeter2 >= 2000 && potmeter2 < 2050 && potmeter3 >= 500 && potmeter3 < 525 && potmeter4 >= 3500 && potmeter4 < 3510){
       gen_pwm(D0, 1000, 100);
       gen_pwm(D1, 1000, 100);
       gen_pwm(D2, 1000, 100);
       gen_pwm(D3, 1000, 100);
       _delay_ms(250);
       gen_pwm(D0, 1000, 0);
       gen_pwm(D1, 1000, 0);
       gen_pwm(D2, 1000, 0);
       gen_pwm(D3, 1000, 0);
       _delay_ms(250);

      }
     }
        }else{
        gen_pwm(D3, 1000, 0);
        }
       }else{
       gen_pwm(D3, 1000, 0);
       gen_pwm(D2, 1000, 0);
       }
      }else{
      gen_pwm(D3, 1000, 0);
      gen_pwm(D2, 1000, 0);
      gen_pwm(D1, 1000, 0);
      }
     }else{
     gen_pwm(D3, 1000, 0);
     gen_pwm(D2, 1000, 0);
     gen_pwm(D1, 1000, 0);
     gen_pwm(D0, 1000, 0);
     }

        }
       }

I have merged my program with your program and I have added the `#include "Arduino.h"`. The `millis()` function is colored now and works. My code still won't stop at 60 secondes, did I do something wrong?

    #include "hva-xmega.h"
    #include "Arduino.h"

    unsigned long EndTime;

    void setup()
    {
     pin_mode(A13,INPUT);
     pin_mode(A12,INPUT);
     pin_mode(A11,INPUT);
     pin_mode(A10,INPUT);
     pin_mode(A15,INPUT);
     pin_mode(D0,OUTPUT);
     pin_mode(D1,OUTPUT);
     pin_mode(D2,OUTPUT);
     pin_mode(D3,OUTPUT);

     EndTime = millis() + (60*1000L);
    }

    void loop() {
     if( millis() < EndTime ){

    while (1)
    {
     int potmeter1 = read_analog_pin(A13);
     if (potmeter1 >= 1000 && potmeter1 < 1100){
      gen_pwm(D0, 1000, 100);

      int potmeter2 = read_analog_pin(A12);
      if (potmeter2 >= 2000 && potmeter2 < 2050){
       gen_pwm(D1, 1000, 100);

       int potmeter3 = read_analog_pin(A11);
       if (potmeter3 >= 500 && potmeter3 < 525){
        gen_pwm(D2, 1000, 100);

        int potmeter4 = read_analog_pin(A10);
        if (potmeter4 >= 3500 && potmeter4 < 3510){
         gen_pwm(D3, 1000, 100);

         {
          int lichtsensor = read_analog_pin(A15);
          if (lichtsensor >= 2000 && lichtsensor < 3500 && potmeter1 >= 1000 && potmeter1 < 1100 && potmeter2 >= 2000 && potmeter2 < 2050 && potmeter3 >= 500 && potmeter3 < 525 && potmeter4 >= 3500 && potmeter4 < 3510){
           gen_pwm(D0, 1000, 100);
           gen_pwm(D1, 1000, 100);
           gen_pwm(D2, 1000, 100);
           gen_pwm(D3, 1000, 100);
           _delay_ms(250);
           gen_pwm(D0, 1000, 0);
           gen_pwm(D1, 1000, 0);
           gen_pwm(D2, 1000, 0);
           gen_pwm(D3, 1000, 0);
           _delay_ms(250);

          }
         }
         }else{
         gen_pwm(D3, 1000, 0);
        }
        }else{
        gen_pwm(D3, 1000, 0);
        gen_pwm(D2, 1000, 0);
       }
       }else{
       gen_pwm(D3, 1000, 0);
       gen_pwm(D2, 1000, 0);
       gen_pwm(D1, 1000, 0);
      }
      }else{
      gen_pwm(D3, 1000, 0);
      gen_pwm(D2, 1000, 0);
      gen_pwm(D1, 1000, 0);
      gen_pwm(D0, 1000, 0);
       }
      }
     }
    }
     else {
      // Time is up! Hang here
      for(;;)
      ;      // infinite loop here stops further processing
     }
     }

body:
Note that in an Arduino environment, `main()` is already provided for you. It calls your function `void setup(void){ ... }` once, then loops forever, calling your function `void loop(void){ ... }`. Either function may be empty but both must be present.

Without going into the specifics of your code, here is a program that fits the Arduino conventions, and will execute some procedure for 60 seconds, then hang, doing nothing:

    unsigned long EndTime;

    void setup()
    {
       // Any setup code you need goes here.

       EndTime = millis() + (60*1000L);
    }

    void loop() {
       if( millis() < EndTime ){
          // Do your processing here
       }
       else {
          // Time is up! Hang here
          for(;;)
             ;      // infinite loop here stops further processing
       }
    }

> My setup codes are the pin_modes right? and everything below is my
> processing?

Update:

Correct - Put pin modes and anything else that needs to be done once, at the beginning of the run in setup(). Everything else goes in loop().
Or if you're more comfortable writing your entire program starting with main() (as we do in other environments than Arduino), you can use the setup() function exactly as you would use main(), and leave loop() empty. The idea of a loop function is that embedded programs are typically not meant to end as long as the device has power. There are instances when this isn't strictly true and you seem to have one example.

> I have
> to remove the int main(void) from my code when I use your code right?

Correct - the Arduino environment provides a main() function, so writing your own - within that environment - would result in a multiple-definition error.

Update 2:

"WProgram.h" is obsolete. Instead, use: `#include <Arduino.h>`. There is no function called `elapsedMillis()`, just `millis()`. You won't need an include statement for it, or any of the other standard or common stuff: Serial I/O, digital I/O, analog I/O, pin definitions for specific boards, etc. 'Arduino.h' pulls in all that stuff. Your university should have add a description of the proprietary board to the Arduino's board description file.

(But if you/they are not using standard Arduino libraries, board descriptions, etc., then there is a lot of behind-the-scenes "housekeeping" you may be responsible for. That isn't something we can know; you may have to ask those kinds of questions of others more familiar with your university's programming environment. I think it is unlikely they would abandon the existing/working resources, but it's something to keep in mind.)


message:
External Interrupt Pins on Nano Clones

Long time lurker, first time poster here.

Do the cheap Arduino Nano clones [such as this one][1] have external interrupt pins?

For example, the original Nano has pins 2 and 3 usable for interrupts. Do clones tend to incorporate this feature? If so, can anyone recommend one which does?

I'm planning on using an encoder for my next project and want to make sure I can use interrupts so my code doesn't skip over encoder counts.

Thank you!

  [1]: https://www.amazon.com/Keywish-Arduino-ATmega328P-Moudle-Compatible/dp/B07D12TWNZ/ref=sr_1_2_sspa?keywords=arduino nano&qid=1560102722&s=gateway&sr=8-2-spons&psc=1

body:
I understand your doubt. In a world where Uno WiFi i not Uno it is better to ask. And the Wawgat boards which are named Uno but use a different 8-bit MCU are a trap too.

The Nano in your link has Atmega 328p and interrupts are a feature of the MCU. There is no reason for the clone manufacturer to not use the standard Nano pinout as specified in Open Hardware Nano schematics. Then the board is compatible with Arduino Nano as defined in Arduino AVR boards package.

The clones usually use a cheaper chip for USB. You will maybe need to install a driver for the CH340.

In a few days Nano Every will be available and I expect clones of it in a short time because it is a very simple board. It will use the ATmega 4809 and Arduino advertises exact pin compatibility with old Nano. But I expect in details problems similar to Uno WiFi R2 versus classic Uno problems. One of the problems could be the mapping of interrupt pins.

And later this year Nano 33 will be released. It is a Nano format board with SAMD or nRF52 MCU so 3.3 V (the 33 in name).


message:
LED array flashes once before being lit

I've built this simple Arduino controlled led-array. The Arduino sets a 5v pin on a relay to connect the high current power supply to a led array.
However, just before the led array is being fully turned on I'm getting this fast flash of the led array. I really would like to have the led working in an "on/off" manner.

[![Scheme][1]][1]

  [1]: https://i.stack.imgur.com/lbGAG.png

I remember that working with some motors one have to use capcitator in parallel because of resistence drop. Is it also the case with led array? And if it is why so, and why a capcitator would help?

Thank you very much.

body:
As Wendall says in his comment, you probably have an issue with the power-on state of your logic pins before the Arduino finishes booting up.

In addition to that, you should **not** drive a relay directly from an Arduino logic pin, for a couple of reasons:

 1. It can't provide enough current to drive a relay coil.
 2. The relay emits a strong surge of reverse current when you switch it off. This will likely destroy the logic pin you are using to drive the relay, or it might even destroy the whole Arduino board.

For these reasons you should drive the relay using a transistor, and you should put a properly sized diode wired across the relay coil backwards from the flow of current when the relay is energized. The diode bleeds off the reverse current from the relay coil.


message:
Unexpected results when creating 32-bit int from byte array

I'm having problems creating a 32-bit integer from a 4-byte array. In the following complete, minimal, and verifiable example, converting a byte array containing `0x00, 0x04, 0x04F, 0x45` results in `4F45` (expected result would be `44F45`). I must be overlooking something fundamental here.... can anyone see where I went wrong?

    void setup()
    {
        Serial.begin(9600);
        while(!Serial);
    }

    void loop()
    {
        uint8_t bytes[4] = {0x00, 0x04, 0x4F, 0x45}; //00044F45
        int32_t theInt = byteArrayToInt32(bytes);
        Serial.println(theInt, HEX); //Print 4F45
        delay(250);
    }

    uint32_t byteArrayToInt32(uint8_t* bytes)
    {
        uint32_t i = 0;
        i |= bytes[0] << 24;
        i |= bytes[1] << 16;
        i |= bytes[2] << 8;
        i |= bytes[3];
        return i;
    }

body:
The problem is that you are trying to shift `uint8_t` more than 8 bits and then `OR` it with `int32_t`.

You have to `cast` the `uint8_t` to `int32_t` before doing the shift.

    void setup()
    {
        Serial.begin(9600);
        while(!Serial);
    }

    void loop()
    {
        uint8_t bytes[4] = { 0x00, 0x04, 0x4F, 0x45}; //00044F45
        int32_t theInt = byteArrayToInt32(bytes);
        Serial.println(theInt, HEX); //Print 4F45
        delay(1000);
    }

    int32_t byteArrayToInt32(uint8_t* bytes)
    {
        int32_t i = 0;
        i |= (int32_t) bytes[0] << 24;
        i |= (int32_t) bytes[1] << 16;
        i |= (int32_t) bytes[2] <<  8;
        i |= (int32_t) bytes[3];
        return i;
    }


message:
Start / end events using milis

I want to start a relay, have it run for 3 seconds, stop for 10 seconds, repeat.

I can't use delay, because I have a motor driver starting / stopping every 100 milis.

So I put together this code, but it does not work. Any help appreciated.

There's a 500ms delay to stop too much debugging info.

Also for some reason, tenSecondsBool switches to true as soon as you run the code.

    unsigned long threeSeconds=3000; // the time we need to wait
    unsigned long threeSecondsMillis=0; // millis() returns an unsigned long.
    unsigned long fourSeconds=7000; // the time we need to wait
    unsigned long fourSecondsMillis=0; // millis() returns an unsigned long.

    unsigned long previousMillis=0; // millis() returns an unsigned long.
    bool ledState = false; // state variable for the LED
    bool led2State = false; // state variable for the LED
    unsigned long tenSecondMilis=0; // millis() returns an unsigned long.
    unsigned long tenSeconds=10000; // the time we need to wait

    unsigned long paliGasiMilis=0; // millis() returns an unsigned long.
    unsigned long paliGasi=1000; // the time we need to wait

    unsigned long ventMilis=0; // millis() returns an unsigned long.
    unsigned long ventInt=100; // the time we need to wait

    bool threeSecondBool = false;
    bool tenSecondBool = false;

    int Fin1 = D7;

    #define enA D1
    #define in1 D2
    #define in2 D3
    #define button 4

    int rotDirection = 0;
    int pressed = false;

    void setup() {
      Serial.begin(9600); // send and receive at 9600 baud
      pinMode(enA, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(button, INPUT);
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      pinMode(Fin1, OUTPUT);
      digitalWrite(Fin1, HIGH);
      threeSecondBool = false;
      tenSecondBool = false;
    }

    void loop() {

     unsigned long currentMillis = millis(); // grab current time

     if ((unsigned long)(currentMillis - tenSecondMilis) >= tenSeconds) {
        Serial.print("---------------\n");
        Serial.print("10 second end\n");
        Serial.print("---------------\n");
        tenSecondBool = true;
        tenSecondMilis = millis();
    }

    Serial.print("10 second bool = ");
    Serial.print(tenSecondBool);
    Serial.print("\n");
    Serial.print("3 second bool = ");
    Serial.print(threeSecondBool);
    Serial.print("\n");

     if (tenSecondBool) {
      if ((unsigned long)(currentMillis - threeSecondsMillis) >= threeSeconds) {
       Serial.print("---------------\n");
       Serial.print("3 second end\n");
       Serial.print("---------------\n");
       threeSecondBool = true;
       threeSecondsMillis = millis();
      }
     }

    if (!tenSecondBool && threeSecondBool){
      Serial.print("Both triggered!\n");
      digitalWrite(Fin1, HIGH);
    }

    if (!tenSecondBool && !threeSecondBool){
      Serial.print("Both triggered!\n");
      digitalWrite(Fin1, HIGH);
    }

    if (tenSecondBool && threeSecondBool){
      threeSecondBool = false;
      tenSecondBool = false;
      digitalWrite(Fin1, LOW);
    }

    delay(500);

      if ((unsigned long)(currentMillis - ventMilis) >= ventInt) {
        digitalWrite(in1, HIGH);
        digitalWrite(in2, LOW);
        ventMilis = millis();
      } else {
        digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
      }

    }

body:
Your code is somewhat confusing, probably because it has too many
variables. For doing what you describe, the program only needs to
remember two things:

 * is the relay in the ON state or in the OFF state?
 * when was the last time the relay changed state?

These can be represented as follows:

<!-- language-all: lang-c++ -->

    bool relay_is_on = false;
    unsigned long last_relay_change = 0;

Then, I recommend you use descriptive names for your variables and
constants. Calling a constant `threeSeconds` is not useful. It has no
added value over just typing `3000`. Having the constant named
`RELAY_ON_TIME` makes it a lot clearer what it is intended for. It is a
common convention to name the constants with all caps to make them stand
out relative to variables:

    const uint8_t RELAY_PIN = ...;
    const unsigned long RELAY_ON_TIME  =  3000;  //  3 s ON
    const unsigned long RELAY_OFF_TIME = 10000;  // 10 s OFF

With this in place, periodically switching the relay on and off can be
achieved as follows:

    void loop()
    {
        unsigned long now = millis();
        if (relay_is_on && now - last_relay_change >= RELAY_ON_TIME) {
            // Turn off.
            digitalWrite(RELAY_PIN, LOW);
            relay_is_on = false;
            last_relay_change = now;
        }
        if (!relay_is_on && now - last_relay_change >= RELAY_OFF_TIME) {
            // Turn on.
            digitalWrite(RELAY_PIN, HIGH);
            relay_is_on = true;
            last_relay_change = now;
        }
    }


body:
If you want a timer with millis with different intervals, then you can change the interval.

I use the [Blink Without Delay][1] to start with, and I borrow the 'relay_is_on' from the answer by Edgar Bonet.

    unsigned long previousMillis;
    unsigned long interval;
    bool relay_is_on;

    void loop() {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        if (relay_is_on) {
          // Relay was on, now turn it off.
          interval = 10000;
          digitalWrite (relayPin, LOW);
          relay_is_on = false;
        } else {
          // Relay was off, now turn it on.
          interval = 3000;
          digitalWrite (relayPin, HIGH);
          relay_is_on = true;
        }
      }
    }

The global variables can be set to a value to start with (for example 3000 for the interval) or they can be set in the setup() function. You have to choose what you want to start with. For example one second or one minute delay before it starts is also possible.

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


message:
How does the dual 5V and 3.3V output on the Uno R3 work exactly?

I'm constructing a circuit that needs both voltage supplies (for 3.3V RFID and 5V relay, GPS and screen) but the Uno is physically too big so I need to use a nano or mini pro, both of which I can only get in 5V. I understand how to use a regulator to drop 5V to 3.3V for the RFID-IC power but I keep seeing instructions to use a level shifter between the IC outputs and arduino input pins. I was just wondering if the Uno has a built-in level shifter for all pins or some other method as the I/O pins do not have specified voltages or uses.

Thanks for your time.

body:
You can get pro-mini in 3.3V, but this has little to do with your problem.

The nano runs on 5V, but has an on-board regulator which supplies 3.3V power, although the logic I/O is 5V.

Level shifters can be used to perform logic level translation, but are not always needed.

The output of a 3.3V logic circuit will drive the INPUT of a 5V logic circuit (technically this is marginal, but works in practice).

5V logic outputs can be connected to 3.3V inputs with a simple voltage divider (you can use level shifter or other methods). Without some means of limiting voltage there is a risk of damaging the 3.3V logic.

Without more detail of exactly what you are planning it is not possible to be more precise.


body:
Pins of the UNO/Nano/Mini/Mega board are connected to GPIO pins of the MCU without any additional circuit. The ATmega MCU running at 5 V will sense 3.3 V as HIGH because of the threshold level to convert voltage to logic state.

ATmega will read the pin HIGH from 0.6 * Vcc, so at 5 V Vcc the threshold is 3 V.

Sources:

 - [Schematics of Arduino Uno][1]
 - [Datasheet of ATmega328p][2] (28.2 DC Characteristics)

  [1]: https://content.arduino.cc/assets/UNO-TH_Rev3e_sch.pdf
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


body:
There are no built-in level shifters on the Uno; it doesn't need them. Uno's 3.3v pin is merely a convenience for supplying a low-current 3.3v device but there is no provision made for level shifting if/when that is necessary.

Genuine Uno's can deliver a *max* of 150mA to the 3.3v pin, so plan your current-budget conservatively. In my dual-voltage designs (2 voltage rails on a board with 3.3v & 5v parts), I reduce the "raw" 5v with a 3.3v regulator (typically an LM1117-3.3 part) rather than drawing it off of the regulated 5v power. (I put "raw" in quotes because I usually supply the board with a pre-regulated 5 volts (USB or wall-wart).

For I/O levels, a 3.3v part's HIGH level is within the range of what Uno will read as HIGH. In the other direction, Uno's HIGH level is too high for a 3.3v part and needs to be shifted down to 3.3v. If there are only one or two such signals (Uno -> 3.3v device), a voltage divider circuit would be less expensive and use less board space than a level-shifter. The level-shifter board would be an extra purchase but it is a quick and dirty solution if you have the space for it.