body:
    #include <TimeLib.h>
    #include <Wire.h>
    #include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

    #define PIN_SCE   7
    #define PIN_RESET 6
    #define PIN_DC    5
    #define PIN_SDIN  11
    #define PIN_SCLK  13

    #define LCD_COMMAND    LOW
    #define LCD_DATA     HIGH

    #define LCD_X     84
    #define LCD_Y     48

    String now_time;
    char printTime;

    void gotoXY(int x, int y) {
      LCDWrite(0, 0x80 | x);  // Column.
      LCDWrite(0, 0x40 | y);  // Row.  ?
    }

    //This takes a large array of bits and sends them to the LCD
    void LCDBitmap(char my_array[]){
      for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
        LCDWrite(LCD_DATA, my_array[index]);
    }

    //This function takes in a character, looks it up in the font table/array
    //And writes it to the screen
    //Each character is 8 bits tall and 5 bits wide. We pad one blank column of
    //pixels on each side of the character for readability.
    void LCDCharacter(char character) {
      LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding

      for (int index = 0 ; index < 5 ; index++)
        LCDWrite(LCD_DATA, ASCII[character - 0x20][index]);
        //0x20 is the ASCII character for Space (' '). The font table starts with this character

      LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding
    }

    //Given a string of characters, one by one is passed to the LCD
    void LCDString(char *characters) {
      while (*characters)
        LCDCharacter(*characters++);
    }

    //Clears the LCD by writing zeros to the entire screen
    void LCDClear(void) {
      for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
        LCDWrite(LCD_DATA, 0x00);

      gotoXY(0, 0); //After we clear the display, return to the home position
    }

    //This sends the magical commands to the PCD8544
    void LCDInit(void) {

      //Configure control pins
      pinMode(PIN_SCE, OUTPUT);
      pinMode(PIN_RESET, OUTPUT);
      pinMode(PIN_DC, OUTPUT);
      pinMode(PIN_SDIN, OUTPUT);
      pinMode(PIN_SCLK, OUTPUT);

      //Reset the LCD to a known state
      digitalWrite(PIN_RESET, LOW);
      digitalWrite(PIN_RESET, HIGH);

      LCDWrite(LCD_COMMAND, 0x21); //Tell LCD that extended commands follow
      LCDWrite(LCD_COMMAND, 0xAF); //Set LCD Vop (Contrast): Try 0xB1(good @ 3.3V) or 0xBF if your display is too dark
      LCDWrite(LCD_COMMAND, 0x04); //Set Temp coefficent
      LCDWrite(LCD_COMMAND, 0x14); //LCD bias mode 1:48: Try 0x13 or 0x14

      LCDWrite(LCD_COMMAND, 0x20); //We must send 0x20 before modifying the display control mode
      LCDWrite(LCD_COMMAND, 0x0C); //Set display control, normal mode. 0x0D for inverse
    }

    //There are two memory banks in the LCD, data/RAM and commands. This
    //function sets the DC pin high or low depending, and then sends
    //the data byte
    void LCDWrite(byte data_or_command, byte data) {
      digitalWrite(PIN_DC, data_or_command); //Tell the LCD that we are writing either to data or a command

      //Send the data
      digitalWrite(PIN_SCE, LOW);
      shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
      digitalWrite(PIN_SCE, HIGH);
    }

    void setup(void) {
       LCDInit();
       LCDClear();
       Serial.begin(9600);
       while (!Serial) ; // Needed for Leonardo only
       setSyncProvider(RTC.get);   // the function to get the time from the RTC
       if (timeStatus() != timeSet)
         Serial.println("Unable to sync with the RTC");
       else{
         Serial.println("RTC has set the system time");
          digitalClockDisplay();
       }
    }

    void loop(void) {
      if(timeStatus() == timeSet)
      {
        delay(1000);
        digitalClockDisplay();
      }
    }
    void digitalClockDisplay(){
      // digital clock display of the time
      if(minute() < 10)
      {
        now_time = String(hour()) + ":0" + String(minute());
      }
      else if(minute() >= 10){
        now_time = String(hour()) + ":" + String(minute());
      }
      Serial.println(now_time);
       LCDClear();
       LCDString("Time: ");
       for(int i = 0; i <= now_time.length()-1; i++)
       {
          printTime = now_time.charAt(i);
          LCDString(printTime);
       }

    }

    void printDigits(int digits){
      // utility function for digital clock display: prints preceding colon and leading 0
      LCDString(":");
      if(digits < 10)
        LCDString('0');
      LCDString(digits);
    }

When I run the code the time will display perfectly on the Serial Monitor but when I connect it to my Nokia LCD screen the words "Time: " will appear along with some random characters. Anyone know why this is?

title: Time displays on serial monitor but not my LCD

Answers: 1

body:
I assume you are writing now_time one Char at a time because the LCD library does not accept the String object as input? LCDString assumes you will pass a C-style string -- that is a pointer to an array of char. When you pass in one character, it's not a pointer to a C-style string, but the LCDString function is assuming that it's a pointer to some bit of memory elsewhere.

Try not sending one Char at a time, but:

    LCDString(now_time.c_str());


body:
I have written a code that displays a number into a seven segment display without manually setting the Arduino pins HIGH/LOW for each number. Now, my problem is how can I display a number larger than 9? This is my code and it works for only 1 digit number: (The seven segment display truth table is inverted because I'm using common anode 7seg)

    #define SEG_A 2
    #define SEG_B 3
    #define SEG_C 4
    #define SEG_D 5
    #define SEG_E 6
    #define SEG_F 7
    #define SEG_G 8
    #define DEC_P 12

    #define SET1 9 // [!][!][x]
    #define SET2 10// [!][x][!]
    #define SET3 11// [x][!][!]

    struct segmentmap {
      uint8_t num;
      const int segment[7];
    };

    const struct segmentmap segments[] = {
      // n   A  B  C  D  E  F  G
      {0, {0, 0, 0, 0, 0, 0, 1}},
      {1, {1, 0, 0, 1, 1, 1, 1}},
      {2, {0, 0, 1, 0, 0, 1, 0}},
      {3, {0, 0, 0, 0, 1, 1, 0}},
      {4, {1, 0, 0, 1, 1, 0, 0}},
      {5, {0, 1, 0, 0, 1, 0, 0}},
      {6, {0, 1, 0, 0, 0, 0, 0}},
      {7, {0, 0, 0, 1, 1, 1, 1}},
      {8, {0, 0, 0, 0, 0, 0, 0}},
      {9, {0, 0, 0, 1, 1, 0, 0}}
    };

    void setup() {
      Serial.begin(9600);
      for (int x = 2; x <= 8; x++) {
        pinMode(x, OUTPUT);
        Serial.print("Segment pin: ");
        Serial.print(x);
        Serial.println(" is set to OUTPUT mode.");
        digitalWrite(x, HIGH);
      }
      pinMode(DEC_P, OUTPUT);
      pinMode(SET1, OUTPUT);
      pinMode(SET2, OUTPUT);
      pinMode(SET3, OUTPUT);
      digitalWrite(SET1, 1);
    }
    int x = 0;
    void loop() {
      if (x > 9) {
        x = 0;
      }
      updateDisplay(x);
      delay(1000);
      x++;
    }

    void updateDisplay(int input) {
      for (int x = 0; x <= 9; x++) {
        //Serial.println(segments[x].num);
        if (segments[x].num == input) {
          Serial.println(segments[x].segment[0]);
          ////////////Simplify this part//////////////
          digitalWrite(SEG_A, segments[x].segment[0]);
          digitalWrite(SEG_B, segments[x].segment[1]);
          digitalWrite(SEG_C, segments[x].segment[2]);
          digitalWrite(SEG_D, segments[x].segment[3]);
          digitalWrite(SEG_E, segments[x].segment[4]);
          digitalWrite(SEG_F, segments[x].segment[5]);
          digitalWrite(SEG_G, segments[x].segment[6]);
          ////////////////////////////////////////////
          //Multiplex here?//
        }
      }
    }

title: Seven segment display multiplexing

Answers: 2

body:
> my problem is how can I display a number larger than 9?

your first problem can be solved by pulling down / up, depending on your led configuration, the right digit pins.

your second problem would be to write your code so that it is actually usable. think about a generic module where digit / segment pins can be user defined and the routine is called periodically update the segments / digits to display the content in a buffer.

body:
It looks like you are using a 3 digit common anode display.
If your code currently works, fixed to display something on digit 0, then you could get it working for all 3 digits by adding/updating the following:

    // globals:
    byte display_buffer[3] ;  // representation of the display which you can change in loop()
    byte anode_map[3] = { 9, 10, 11 } ;  // anode pins

    void loop() {
      if (millis() % 5 == 0 ) updateDisplay();  // every 5mS - better to use a timer
      if ( millis() % 1000 == 0) {  // every second
        if (x > 9) {
          x = 0;
        }
        display_buffer[0] = x ;  // just for testing
        display_buffer[1] = (x + 11) % 10 ;
        display_buffer[2] = (x + 12) % 10 ;
        x++;
      }
    }

    void updateDisplay() {
       // called every x Ms preferably with a timer
       // selects next item from display_buffer_ptr and displays it
       //
       static byte display_buffer_ptr ;
       display_buffer_ptr ++ ;
       if ( byte display_buffer_ptr > 2 ) display_buffer_ptr = 0 ;
       int input = display_buffer[display_buffer_ptr] ;
       for ( int i = 0 ; i < 3 ; i++ ) {
           digitalWrite( anode_map[i], ( i == display_buffer_ptr ) ) ;  set current anode HIGH, rest LOW
       }
       // rest of your code to display the value of input

    }

This is not the most elegant solution but involves minimal changes to your code.
It is more usual to use an array of byte for the mapping digits to segments.
You may have to optimise the switching of the anodes to stop ghosting.


body:
I have a very inconvenient problem with a web server I'm writing for a Arduino Mega 2560 with a W5100 Ethernet Shield (with the "official" Ethernet lib). I wrote the server code and it works like a charm, BUT there is a condition, when the server won't accept all the TCP handshakes and resets the TCP connections:
When I load a big webpage, the browser (Firefox and Chrome too) asks for the .htm first, then collects the links in the file and request them all simultaneously and that's when I got the problem:

The server gets multiple TCP connections but it only accepts the first, then dumps all the others (by TCP reset). After that the client sends them again and the problem starts again: the server accepts the first and drops the others. And so on, for example if the browser needs 3 files, it will take ~9 seconds, because of the retransmission delay. (3 + 6 seconds) Eventually the webpage will load, but a 10 second delay is not acceptable.
Is there any way to cache the requests on the Ethernet Shield or to tell the browser to wait a bit between requests or any other way, to wait a bit for the Arduino to finish the previous request?

Snippet for the server, Wireshark and Chrome network data: https://gist.github.com/anonymous/181f359b70d69e4470931204c4ec175c

Thanks for the help!

G.

title: Ethernet Shield - Multiple simultaneous connections cause TCP reset

Answers: 1

body:
*I have received a request from the OP to move this to Network Engineering because it got no answers. I'm going to decline this for the moment because I doubt they will be familiar with the Arduino Ethernet shields.*

---

The low-cost shields have a known limit on the number of connections they can handle simultaneously (no doubt limited by available RAM). From the page [Arduino Ethernet Shield 2](https://www.arduino.cc/en/Main/ArduinoEthernetShield) we learn:

> It supports up to eight simultaneous socket connections.

You don't seem to be getting that, which makes me wonder if it is a code issue. It might help to post your code. If you make code that "blocks" while handling the first connection you may not accept the other ones in a timely way, leading to a reset.

Please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).

I did a post about [a tiny web server for the Arduino](http://www.gammon.com.au/forum/?id=12942) which uses a state machine to handle incoming data without blocking.

---

You may also be able to help yourself by using the HTTP header that requests that the connection be kept open, eg.

    Connection: keep-alive

That might stop the client opening new connections in quick succession.


body:
I'm looking to toggle a pin on and off in a fast and timing-sensitive manner, and I'm wondering if the Arduino Uno has any built in "buffers" that would be able to hold a set of values and send them sequentially to the output pin at high speed, separately from the rest of the loop. I could then refill the buffer with the next set to be outputted, and so on.
Is this even possible? If anyone has any documentation on what's involved, I'd really appreciate some links (or tips!) :) thanks

title: Buffering output stream

Answers: 2

body:
The closest thing to what you describe is DMA (Direct Memory Access). The Arduino doesn't have DMA. More powerful microcontrollers often do, but not little 8 bit ones.

The closest you could do is to use a timer interrupt to run a small function periodically which reads the next value from an array and sets the pin to that state.

The [TimerOne or TimerThree](http://playground.arduino.cc/Code/Timer1) libraries can be of help to you here.

body:
For most Arduino devices, using the USART in SPI mode is about the most effective way to generate a hardware-timed stream of bits out of one pin.  For background, see §21, “USART in SPI Mode”, in the ATmega328 data sheet.  For some example code and exposition, see [ATmega Arduino USART in SPI Master Mode MSPIM,
Posted on February 17, 2015 by feilipu](https://feilipu.me/2015/02/17/avr-atmega-usart-spi-mspim/).

Ordinary SPI output on most Arduinos is single-buffered, hence subject to occasional delay if other interrupts get in the way of the SPIF-SPIE-SPDR interrupt handler.  However, the USART-in-SPI-mode method double-buffers output as well as input, allowing continuous data output.  That is, one can generate a continuous stream of bits clocked out at whatever rate one selects.

The [Arduino Due](https://www.arduino.cc/en/Main/arduinoBoardDue) is based on the Atmel SAM3X8E ARM Cortex-M3 CPU, a 32-bit ARM core microcontroller.  It supports DMA (direct memory access) and one can find webpages, eg [arduino.cc topic 219291](http://forum.arduino.cc/index.php?topic=219291.0), describing waveform generation using DMA and the 12-bit DAC (digital to analog converter) on the Due.  More notably, the Arduino software compatible [Teensy 3](https://www.pjrc.com/teensy/) series uses Cortex-M4 and M4F chips on boards running at 48, 72, 120, and 180 MHz, probably more suitable for elaborate waveform generation than are the Due or Zero.


body:
Is it safe to use PROGMEM variable like dynamically allocated memory (a pointer to PROGMEM variable which is out of scope).

I need this so I can generate a variable size (before compilation), constant values, lookup array stored in flash.

Working example:

    class Ex_class {
      public:
        Ex_class(int table_size, int value_range) {
          int flash_table[table_size + 1] PROGMEM;
          _ex_table = flash_table;
          for (int i = 0; i <= table_size; i++) {
            _ex_table[i] = random(value_range);
          }
        }

        int get_value(int index) const { return _ex_table[index]; }

      private:
        int* _ex_table;
    };

    void setup() {
      randomSeed(analogRead(0));
      Serial.begin(9600);
      Ex_class ex_object(5, 50);
      for (int i = 0; i <= 5; i++) {
        Serial.print(i); Serial.print(": "); Serial.println(ex_object.get_value(i));
      }
    }

    void loop() {}

title: Using PROGMEM in constructor

Answers: 1

body:
The closest I could get to what you are trying to do is this:

    template <size_t table_size> struct Ex_class {
      int get_value(int index) const {
        return pgm_read_word(&_ex_table[index]);
      }
      int _ex_table[table_size];
    };

    void setup() {
      Serial.begin(9600);
      static PROGMEM const Ex_class<5> ex_object = {1, 2, 3, 4, 5};
      for (int i = 0; i < 5; i++) {
        Serial.print(i);
        Serial.print(": ");
        Serial.println(ex_object.get_value(i));
      }
    }

    void loop() {}

`avr-nm` and `avr-objdump` confirmed that the object lives indeed in the
text section of the program. Please note that:

* The object is `PROGMEM const`. It would make no sense to try to put in
  PROGMEM anything that is not constant.

* The object is allocated statically. It can be either a global or a
  static local, but not an automatic local like in your example.

* I am using [aggregate initialization][] here. I know no other way to
  statically initialize an array of variable length. If you have an
  idea, I would be interested to know though.

[aggregate initialization]: http://en.cppreference.com/w/cpp/language/aggregate_initialization


body:
I've received an Arduino Uno today only. I have zero experience prior to Arduino boards or any other micro controller. I followed every step very carefully from the setting up guide for Linux based OS, but I still can't connect the board with my Ubuntu 16.04 PC. After googling the problem I found that the device must show up as `ttyACM*` but I don't see any such device in `/dev`. Its also not listed under the command `lsusb` but the LED's on the board are working properly. The ON LED is turned on when I connect it with my PC and the inbuilt LED starts to blink.

This is what the IDE displays:

[![Arduino IDE][1]][1]

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

title: Unable to connect Arduino Uno to Ubuntu 16.04

Answers: 1

body:
You may have to add yourself to the dialout group in Ubuntu so that your user account can access the serial ports.

Then, in the Arduino IDE, the Tools->Port menu should show you options. Right now, the screenshot you gave shows that it's set for COM1, which is a Windows-style serial port naming and definitely won't work on Ubuntu.


body:
I want to send numeric value from matlab to arduino but code is not working.

Matlab code is as:

    doi = 3 ;
    arduino=serial('COM5','BaudRate',9600); % create serial communication object
    fopen(arduino); % initiate arduino communication
    fprintf(arduino, '%s', char(doi)); % send answer variable content to arduino
    fclose(arduino);

Arduino code is as:

      int solenoidPin = 13; //This is the output pin on the Arduino
    int doi;

    void setup()
    {
      Serial.begin(9600);
      //pinMode(13, OUTPUT);
      pinMode(solenoidPin, OUTPUT); //Sets that pin as an output
    }
    void loop()
    {

      if(Serial.available()>0)
      {

        doi = Serial.read();
        //Serial.println(doi);
        //Serial.println("\n");
        //doi = doi - 48;
       if (doi == 1)
       {
        //Serial.println(1);
        digitalWrite(solenoidPin, HIGH); //Switch Solenoid ON
        delay(1000); //Wait .15 Second
         digitalWrite(solenoidPin, LOW);
        }
      else if (doi == 2)
        {
         //Serial.println(2);
        digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
        delay(2000); //Wait .165 Second
        digitalWrite(solenoidPin, LOW);
        }
      else
        {
          //Serial.println(3);
          digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
          delay(3000); //Wait .180 Second
          digitalWrite(solenoidPin, LOW);
        }

      }
    }

 I used str2num(doi) also instead of `fprintf(arduino, '%s', char(doi))` but no output.

Please give suggestion to correct this.

Thanks.

title: Sending values from Matlab to arduino using serial communication

Answers: 2

body:
You send a string of ASCII characters representing a number in human readable format.

You then read one of those characters that represents a single digit and then try and use it as if it were a number.

Instead you need to read the whole string of numbers (which means having some way of knowing where the end of the numbers are in the stream of characters that arrive) and then interpret it back into a number again.

body:
fopen(arduino); takes some time to initialize the serial connection so you should use pause(2); after fopen(arduino); and in fprintf() send doi as interger i.e. fprintf(arduino, '%i', doi);. Suppose the doi is 1 then code would be as

    doi = 1;
    arduino=serial('COM5','BaudRate',9600); % create serial communication object
    fopen(arduino); % initiate arduino communication
    pause(2);
    fprintf(arduino, '%i', doi); % send answer variable content to arduino
    fclose(arduino);

Another modification required in arduino program as

    doi = doi - 48;

Uncomment this line inside if(Serial.available()>0) block.


body:
I'm building a project that has 2 motors. What I want to do is:
When button is pressed (hold down through RF controller) then:

1. Run motor A on pwm at 50 for 1 second
2. Run motor B on pwm at 255 for 1 second

After that first second

3. Run motor A on pwm at 255 until button is released
4. Stop motor B.

And when I hit the button again the whole thing repeats. Here is my rough code but it doesn't work that way. What it does is if I pressed the button in the first second since start up off the Arduino it does the first task. If I press it again it does the second task.

I have looked and tried through a lot of examples of blink without delay and multitasking. But I still can't get it working.

Here is my code:

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include <elapsedMillis.h>

    // Motor 1
    int dir1PinA = 4;
    int dir2PinA = 5;
    int speedPinA = 3; // Needs to be a PWM pin to be able to control motor speed

    // Motor 2
    int dir1PinB = 7;
    int dir2PinB = 8;
    int speedPinB = 6; // Needs to be a PWM pin to be able to control motor speed

    int msg[1];
    RF24 radio(9,10);
    const uint64_t pipe = 0xE8E8F0F0E1LL;

    unsigned long previousMillis = 0;
    long OnTime1 = 500;
    long OnTime2 = 10000;

    void setup(){
     Serial.begin(9600);
     radio.begin();
     radio.openReadingPipe(1,pipe);
     radio.startListening();

     pinMode(dir1PinA,OUTPUT);
     pinMode(dir2PinA,OUTPUT);
     pinMode(speedPinA,OUTPUT);

     pinMode(dir1PinB,OUTPUT);
     pinMode(dir2PinB,OUTPUT);
     pinMode(speedPinB,OUTPUT);

     }
     void CandPush()
     {
              analogWrite(speedPinA, 50);//Sets speed variable via PWM
              digitalWrite(dir1PinA, HIGH);
              digitalWrite(dir2PinA, LOW);
              analogWrite(speedPinB, 255);//Sets speed variable via PWM
              digitalWrite(dir1PinB, LOW);
              digitalWrite(dir2PinB, HIGH);

     }
     void CandStop()
     {
              analogWrite(speedPinA, 255);//Sets speed variable via PWM
              digitalWrite(dir1PinA, HIGH);
              digitalWrite(dir2PinA, LOW);
              analogWrite(speedPinB, 0);//Sets speed variable via PWM
              digitalWrite(dir1PinB, LOW);
              digitalWrite(dir2PinB, LOW);

     }
     void Home()
     {
              analogWrite(speedPinA, 0);//Sets speed variable via PWM
              digitalWrite(dir1PinA, LOW);
              digitalWrite(dir2PinA, LOW);
              analogWrite(speedPinB, 255);//Sets speed variable via PWM
              digitalWrite(dir1PinB, HIGH);
              digitalWrite(dir2PinB, LOW);

     }
     void loop(){

     if (radio.available()){
        bool done = false;
        while (!done){
        done = radio.read(msg, 1);
        Serial.println(msg[0]);
        if (msg[0] == 111)
        {
          unsigned long currentMillis = millis();
          CandPush();
          if(currentMillis - previousMillis >= OnTime1)
          {
            CandStop();
            previousMillis = currentMillis;
          }

        }
     }
     }

     else
     {
      Home();
      Serial.println("Nothing");
     }
     }

title: Carry out two consecutive tasks when a button is pressed

Answers: 1

body:
I assume pressing the button results in msg[0] == 111 every time you do the radio.read (i.e. it will continue sending that while the button is held).  If so, the first issue I see is that after 500ms has elapsed, you will call CandStop(), and then it will loop back and immediately call CandPush(), essentially cancelling the second state.

I think you should create a state variable and state machine, so for example it does a different operation when/while the button is pressed depending on whether it is in the 'home', 'push', or 'stop' state.  In the first ('home') state it is waiting for the button to be pressed, in the second ('push') state it is waiting for the time to elapse, and in the third ('stop') state it is only waiting for the button to be released.  It would also allow you to avoid repeatedly calling CandPush() and Home() when it only needs to be called once (when the button is pressed).

EDIT:
I am adding the code below.  This hasn't been tested so there may be some bugs but it should give an idea of what I mean.  It could probably also be optimized somewhat, but I tried to make it do what I think you wanted it to do based on the code you attached.

There are parts in there that I doubt work as you wanted, aside from the button handling, for example how Home() is called whenever there is no radio available and how nothing appears to happen when the button is released.

Should the Home() call really set B to full output?  I added a call to StopAll which I assumed you would use to stop A and B when the button is released.

Also radio.read doesn't return anything, so done = radio.read(...) is pointless.

    // State machine states
    enum {
        STATE_INIT,
     STATE_HOME,
     STATE_PUSH,
     STATE_STOP
    };

    unsigned long previousMillis;
    bool buttonPressed = false;
    bool radioAvailable = false;
    int state = STATE_INIT;

    void loop()
    {
     //Check for new radio input every cycle
     if (radio.available()) {
      radio.read(msg, 1);
      buttonPressed = (bool) (msg[0] == 111);
      radioAvailable = true;
     } else {
      radioAvailable = false;
     }

     //State machine
     switch (state) {
     case STATE_INIT:
      //first cycle after boot-up, add any desired initialization
      //wait here until the first time the radio is available
      if (radioAvailable) {
       state = STATE_HOME;
      }
      break;

     case STATE_HOME:  //Wait for button to be pressed
      if (radioAvailable) {
       if (buttonPressed) {
        //button was pressed, reset timer and move to PUSH state
        previousMillis = millis();
        CandPush();
        Serial.println("STATE_PUSH");
        state = STATE_PUSH;
       }
      } else {
       //no radio input, go to HOME state
       Home();
       Serial.println("STATE_HOME");
       state = STATE_HOME;
      }
      break;

     case STATE_PUSH:  //Wait for timer to elapse
      if (millis() - previousMillis >= OnTime1) {
       //OnTime1 has elapsed, move to STOP state
       CandStop();
       Serial.println("STATE_STOP");
       state = STATE_STOP;
      }
      break;

     case STATE_STOP:  //Wait for button to be released
      if (radioAvailable) {
       if (!buttonPressed) {
        //button was released, stop all motors?
        StopAll();
        state = STATE_HOME;
       } //else still waiting for button to be released
      } else {
       //no radio input, go to HOME state
       Home();
       Serial.println("STATE_HOME");
       state = STATE_HOME;
      }
      break;
     }
    }


body:
So I recently bought a ESP8266 chip, it requires 3V3 and a large current( around 210mA max which is more than that can be supplied by an arduino uno at least). I managed to connect it to my arduino uno and got it to operate in standby mode, but Wifi mode wouldn't work because it requires more power.

After reading multiple online articles, I've decided to construct my own power supply. I'm planning on hooking 3 AAA batteries in series(4V5) and then use resistors(of small values to decrease power loss) to construct a voltage divide which powers the chip.

My concern is that I have not seen a single person doing this online and this seems like a straight forward thing to do, which makes me worried. Did I miss something? Is my plan feasible?

title: Powering ESP8266EX with batteries and a voltage divider

Answers: 1

body:
There's a good reason why you can't do this.

When you power something like an ESP, the current it consumes will vary over time, as it does different things. For the purposes of current consumption, you could model the device as a resistor  whose resistance varies (greatly) over time. When it's in sleep mode with the radio off, it might be a 10k resistor. When it's active with the radio on full power, maybe a 30ohm resistor.

A potential divider divides voltage according to the ratio of the resistances. You are talking about putting your ESP in parallel with one of the resistors. Putting two resistors in parallel creates a new resistor with a resistance lower than either of the two.

If you want to calculate the resistance of two parallel resistors, it's R = (R1 x R2) / (R1 + R2).

What values would you choose for the resistors in the potential divider?  You'd have to go for values much lower than 15ohm in order for the 'resistance' of the ESP not to greatly affect the behavior of the divider - say 5ohm in total. This would mean your divider alone would draw a current of 1A from a 5v supply.

Fortunately, voltage regulators and buck converters are easily and very cheaply available. I recently bought a pack of five 3.3v regulator modules from China, delivered for less than £2.

Alternatively, you can create a reasonably stable supply from a reference voltage with just a single NPN transistor, but I don't know offhand whether it would be good enough for this application.


body:
I bought an ultrasonic distance sensor seen here: http://arduinobasics.blogspot.co.uk/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html?m=1. As per the wiring diagram I connect it to the ground and 5V pins on my Arduino Nano which is powered via USB.

As soon as I connect the 5V to the sensor it shorts and the lights on the Arduino go out and my laptop says 'usb surge too much power being drawn'. Do I need to add a resistor to the circuit? It all works fine and I get a result when the sensor is connected to the 3V3 pin but it does not ping properly.

I have tried using an external power supply via a breakout board as well as usb mains plug but both still short. Any help would be much appreciated!

title: Connecting a sensor to the 5V pin shorts Arduino Nano

Answers: 0


body:
So I have an Arduino Nano that I think might have gone bad. The Vin and ground pins are shorting (I'm checking continuity with a multimeter). But it only shorts when:

 - The Arduino has power
 - The red lead of the multimeter is on ground and the black is on Vin (not the other way around)

I've tried checking with the leads both ways (red to ground as well as red to vin) while both on and off, and with two different multimeters, one of which is brand new. Completely at a loss for words because this isn't really how physics is supposed to work (continuity shouldn't depend on lead orientation from the multimeter or whether the circuit is powered, right?). Any insight would be appreciated. Do I have a bad board?

title: Vin and Ground pins shorting only under specific conditions

Answers: 3

body: It is not clear from your question what you are measuring with the multimeter (volts, ohms, amps etc.) but if you are using the ohms scale when your Nano device is not connected to the power, your multimeter charging capacitors on the board and reversing the leads will then cause a discharge through the multimeter, maybe giving a reading which leads you to believe there is a short circuit.

body:
Also if you have this setup and set it to measure Amp, then it will effectively shortcut the leads with as small resistace as mutltimeter can.

Also check, if those connectors (usually crocodiles) cannot touch something they should not (each other mainly)

body:
> But it only shorts when: The Arduino has power

You **must not** use a continuity checker or ohm meter on a powered circuit.

Not only will it not work, you risk damaging the meter.

It's also not necessarily safe to use such a meter on an unpowered active electronic circuit like an IC or eval board, as the meter must apply a small amount of power to the circuit to make a measurement - how much power varies between meters and settings, and how much a circuit can tolerate in an unintended way depends on things like polarity and the state of other parts of the circuit.  However, it is common practice to do so - especially for example when there's a fear that the device might already be damaged.


body: Using an Arduino Mega, I currently control two stepper motors that never operate at the same time and never will. I am using two EasyDriver stepper control boards with two separate power sources. I was wondering if I could go down to just one stepper control board, one power source but somehow switch the 4 input wires from one motor to another when I need to turn a specific motor. Is there a switch I can control with Arduino where I can plug in 8 wires and say "ok, use the 4 left most wires" or "switch to the right most 4 wires". Does that exist or is that more complicated than what I currently have?

title: Driving two stepper motors using one stepper motor driver

Answers: 1

body:
If we call the motor leads A1, A2, B1, B2 on each motor and control, you could tie the two motor A1's to A1 on the control, and motor B1's to B1 on control.  Then wire a DPDT relay as below.  (Coil not shown.)  Note, DPDT relays are about $4 on ebay, with labels like “DR21A01 DC 5V DPDT Relay Module Polarity reversal switch Board for Arduino UNO”.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/ddiJ2.png)

<!-- End schematic -->

Since you have equipment in place and working, it might not be worthwhile to change your setup.  However, even without adding a relay, you probably can power both motor controls and motors with a single power supply, ie could use one instead of two power supplies.  The current draw when a stepper motor is idle is a small fraction (eg 10-20%) of the high current drawn when the motor steps.  If you don't have power attached to a stepper motor, there is only its cogging resistance to keep it from turning; it does not take a large torque to turn an unpowered stepper motor.  If that's a concern, the DPDT relay approach might be unsuitable.


body:
I'm very new to Arduino and I am making a code for a pedometer.  I have a lot of variables and I have used "int" multiple times, but I just came across a code with "float".
Now because my coding background is next to none, I don't really understand the concept of a float and when it's appropriate to use one.
Could someone please give me an explanation.
Thanks!

title: When is it necessary to use "float" instead of "int"?

Answers: 6

body:
"int" means integer. It's either one whole number (forgive me, mathematicians, for the sloppy definition!) or the next or previous.

A "float" is a floating-point number - that is, a number and part of a number.

3 is an int

3.14 is a float

If you need to store/represent a value that can be between integers, you could use a float.

Floats use more RAM than integers, and there is a limit to the precision they can represent. Don't use a float unless you have a need.

body:
An [integer][1] is a [whole or natural number][2].  Computers use integers for counting and comparisons.  Computers can count precisely using integers and comparisons of two integers can be absolutely true or false.

To make a [float or floating-point number][3], a computer uses two integer numbers.  It uses one integer as the mantissa and the other as the exponent.  Computers use floats for calculations involving very large, very small or fractional values.  In other words the set of [real numbers][4].  Computers can not count very well using floats.  Computer can not even compare two floats very well. That is to say, you may get different results from different computers when testing if two different floats are the same or not. This is due to [rounding error][5].

Consider that the set of real numbers between 0 and 1 to be infinite.  However, intuitively, we know computers can not keep track of an infinite number of unique values between 0 and 1.  After all, computers use a float to do this and a float has a finite number of bits in it's mantissa and exponent.  The difference, if any, between the actual real number from, say, a calculation and the next possible float value is commonly referred to as the roundoff error.  In a program, a difference, for example, in the order of operation is enough to cause different roundoff errors to occur resulting in two slightly different float value results.

Rounding errors are what we end up with for allowing float values to grow very large or very small or to contain factional amounts.  Fortunately, floats are exactly what we need when computers are asked to calculate very large, very small or fractional numbers.

In embedded programming we rarely use floats.  They take up more of our limited RAM space than integers.  And it is rare that we need to calculate very large or very small numbers.  Usually, in embedded programming, we are counting events or measuring sensors.  Usually integers are preferred or are sufficient for our purposes.

Addressing your specific application (pedometer):

It is anticipated you would prefer to track distances in miles.  And it is practical to assume a good pedometer displays factional miles.  You can use floats to calculate this value.  A rigorous programmer would [cast][6] their integers as floats when mixing them in equations to make it clear to the compiler what is desired.

  [1]: https://en.wikipedia.org/wiki/Integer
  [2]: https://en.wikipedia.org/wiki/Natural_number
  [3]: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
  [4]: https://en.wikipedia.org/wiki/Real_number
  [5]: https://en.wikipedia.org/wiki/Round-off_error
  [6]: https://www.arduino.cc/en/Reference/Cast

body:
There are much more details on both data types, but to keep it easy, just a rough explanation:

**`integer`** data types only allow a range from -2,147,483,648 to 2,147,483,647 with 4 Bytes of memory per variable.

If your results exceed that numbers, an over- or underflow will occur. If you don't take care, bad things can happen.

And you can only use whole numbers, there is no decimal point.

**`float`** instead allows you to do your calculations directly typing decimal values (like 1.25, 3.14, ...), just like you do on paper.

Plus: You usually don't have to care for range checks, because that data type covers a huge value range (-3.4028235E+38 to 3.4028235E+38 with also only 4 Bytes of memory per variable!

So why not use `float` by default?

One big drawback is that handling this number format requires a special piece of hardware ("Floating Point Unit", FPU) to be efficient.

If your microcontroller doesn't have an FPU (and the small Arduinos don't have one), every calculation using `float` operands requires to call certain functions which use some rules to convert your `float` operands into `integer` data types, do the calculation on `integer` basis and convert the result back to `float`.

This consumes some memory and a lot of CPU cycles, which can slow down calculation speed to about 1/10 compared to using an FPU.

There are some other issues which make working with `float` a little bit tricky, so if your calculation can be done using `integer`, use this instead.

"And what if i *need* decimal numbers?"

You can't type 3.14 in `integer`, but you can multiply it to a value big enough to consider enough decimal places for your application. You just have to define the factor and  imagine the decimal point.
For instance, multiply your values by 1000, then 3.14 * 1.256 = 3.94384 becomes 3140 * 1256 = 3943840 internally.

body:
> When is it necessary to use “float” instead of “int”?

IMHO **in Arduino world it is never necessary to use float** ; well unless you want to do something very fancy like building a space ship route calculation with Arduino. In which case you will have someone on your team who understands the problem in full detail who can decide it is better to use float for some calculations.

> How do I deal with behind the comma numbers?

As integers does not allow you to work behind the coma and you won't use float you may wonder how to work with pi (3.1415..radians). In most cases you will only work with a specific number of digits behind the comma. Lets say you want 3 digits behind the comma. In this case you simply work with milli radians instead of radians ( 3145 milli radians=3.145 radians; [For the Americans it might be time to look at the metric system for a better understanding][1])
Because of this change in "base value", no more floats are needed to calculate.  There are 3 drawbacks:

 - when out-putting information formatting may be needed/desired to
   convert to a user "base value".
 - when in-putting information formatting may be needed/desired to
   convert to a user "base value".
 - When using methods that use float conversions are needed
In and output are normally very small in arduino. The Serial.print() is probably the biggest thing.
If you need to use a method like cos() you do as follows:
long result=DECIMALDIGITS*cos((float)corner/DECIMALDIGITS);
Where DECIMALDIGITS= (float)10^numdigits;

As type I advice to use long on a 8 bitter as int (-32,768 to 32,767) is very likely to get out of range.

**More background behind the dirty details of float**
It is pretty obvious that float supports behind the comma values, but what are the disadvantage of float?

 - float is CPU/RAM intensive
 - float introduces a rounding problem.
 - multiple types int/float can cause casting issues

Lets go through the disadvantages one by one:
**float is CPU/RAM intensive**
IMHO In many Arduino projects there is plenty of CPU/RAM left so I don't think this is a real issue.
To prove this point look at how many Arduino projects contain a delay(x00) in the loop; so if things go to slow simply decrease this number to release some CPU cycles ;-).

**float introduces a rounding problem.**
*When using floats A * B / A does not guarantee to be equal to B!!!* It will be close but ...
This is my main argument to avoid floats. Sooner or later this will hit you and you'll have a hard time finding out why. (I speak from experience here)
Basically 0.1 can not be represented 100% exactly in float. So in float 0.1+0.2 is not equal to 0.3!!!

**multiple types int/float can cause casting issues**
In C/C++ it is pretty hard to predict the casting that will happen in a formula like:

    float z;
    byte r;
    uint32 t;
    ...
    int a=z*r/t*1.5;

I consider myself very experienced in C/C++ and I always convert code like this into something like

    float z;
    byte r;
    uint32 t;
    ...
    byte rfloat=r;
    uint32 tfloat=t;
    int a=(int)(z*rfloat/tfloat*1.5);

I prefer not to explain this to a newbie Arduino user :-s.
More in depth details can be found at [floating-point-gui.de][2]

  [1]: https://en.wikipedia.org/wiki/Metric_system#Decimal_multiples
  [2]: http://floating-point-gui.de/

body:
> I'm very new to Arduino and I am making a code for a pedometer.

others have answered the difference between float and int.

but your project offers an interesting challenge in that it covers a wide range: the pedometer likely counts in miles and have to keep track of total steps, which the increments are done in single steps - much shorter than miles.

what you could do instead of using floats is to use multi-byte types. for example, a 32-bit/4-byte type can support 2 million miles; you can add additional msb to it to create a proprietary data type. a 5-byte type for example would support 5 million miles, and a 128 billion miles for a 6-byte type.

you will need to create your own math routines -> not difficult at all.

the point is that float is a simple solution to simple problems only.

body:
`int` stands for **Integer**
and `float` stands for **floating point** number.
For more reference check this out https://www.arduino.cc/reference/en/language/variables/data-types/float/


body:
I have been doing a lot of researching ever since Christmas when I got the Arduino Uno. Anyways, I want to build a 4 leg spider robot using 2 Arduino's. I had a lot of problems on coming up with how to do it, and I think I got it. What I want to be answered is this question, is my circuit good to go and will not fry anything? Anyways, I needed 12 servos. Only 6 pins on 1 Arduino has PWM. So I thought to use 2 Arduino's to communicate through the HC-06 blue-tooth. Power was another problem. I discovered that double AA batteries have an impressive 7 amps on my multi-meter. However, to much for the Arduino. That is why it is only supplying servos and not going directly to the Arduino. A 9v will do that. Anyways, I can't give you guys the schematic as it is to big of a file. However, I will explain the circuit in words. One Arduino is master and the other is slave. These steps go to both master and slave unless stated.

1. 6 servos on master and 6 on slave. Power is going to 4 double AA batteries in series. This supply is not connected to the board except the ground wire. This is a battery holder with switch already on it. All PWM pin's are in use for servos.

2. 9 volt battery going to the Vin pin. I will incorporate a switch.
3. Fan with positive and negative only. Positive goes to the 9 volt battery. Ground goes to ground pin on Arduino.

4. Bluetooth module with VCC going to 3.3v pin. Ground to ground pin. TXD going to the RX pin. RXD going to TX pin.

5. For master Uno only. Distance sensor with Trig going to A5 pin and echo to A4 pin. Ground going to ground pin. VCC going to 5v pin.

6. 2 led's in circuit with 220 ohm resistor. I will use pin 4 and 2. Ground goes to ground pin.

That is the setup. I am in college where soldering is banned. So I am including a fan, like you saw, to cool down the breadboard. Let me know if you think that will work. I could not find a good schematic online for this robot, so I made one. Please let me know if you have any questions. Anyways, please tell me if there are any flaws and thank you so much for your time and effort.

Edit 1:
@gilhad
I did not know about I2C, if that is easier than blue-tooth, then I will get that. Thanks for that input. This way I don't have to use 2 blue-tooth modules. Most of the robot is running in series, not parrel.

Also, I said 4 AA batteries and not 2. If I had 2 in series, then that is 3v only, so that is why I am going for 4 in series for a total of 6v, with amps being the same as with one battery. This will supply 7 Amps. I tested it with my multi-meter. The servo motors are going to need 1 amp of power at max. I have 7. I will probably be using 4 servos at one time. So that is 4 amps. It will run for about an hour. That is fine by me.  This 4 AA battery is not connected to the arduino. There are 2 power sources per arduino. The other one is a single 9v battery, that one is going directly to the arduino, the Vin pin to be clear. If it is going to reset, could I do something in the programming to account for that like a time delay that is short?

 I do not want to mess with my breadboards, that is why I am using a fan to cool them. Will that work?

The power source will not be moving all the servos at once, sorry that I did not include that.

Edit 2:

@killer rabbit

I guess I did not want to get a mega because I have 3 Uno's already, but I see they're pretty cheap online. I will ponder this idea of yours. I looked at my schematic and determine this would eliminate the 2 blue-tooth modules, 1 power source, 1 fan, and 2 leds along with their resistor. I think it would also eliminate an extra switch. Programming would be easier to because I don't have to worry about blue-tooth communication. I had no idea what to do for that one. So maybe I will get a Arduino mega.

The reason I am not using RC battery is because they're kinda heavy and SG90 servos are kinda small. I was worried about torque.  Li-ion is not to heavy, but I was worried about power. The ones you gave me though, look like that might work. There is 2 problems though. First, I can't use 2 of these batteries in series because that is 7.4 volts when the servos I am using is at max 7.2 volts. I would have to reduce voltage somehow, I have no idea how to wire that into the circuit. Problem 2 is that if I wire is parrel, that is 6 amps, which is fine, but only 3.7 volts. The motors can run on that, but that is on the low end. Will torque be less?

About the third paragraph, there is limits on the amount of current an Arduino can take. I looked them up. It is about 2 amps for the Vin pin I think or that might be the DC jack, one of the two.

I am using 2 Arduino, so that is why the blue-tooth was necessary. However, if I go with the mega, it will eliminate both of them. I forgot to mention for the distance sensor, I am using ultra sonic one. That is my fault for not mentioning that.

The reason I need 12 servos is because I am using 4 servos at the base, one for each leg to control direction of leg for steering. Then I have 4 legs, each using 2 servo motors to make the leg kick out and in. So 4 + 2(4)=12.

Yes, I would be using, if 2 Arduino, wireless communications, that is why the blue-tooth module. About the schematics, the picture is too big, so that is why I can't upload it. So sorry about that. I did try, believe me.

title: Arduino Uno-Spider Robot Plan

Answers: 2

body:
There are multiple points where you should reconsider your plans:
First of all, do not use multiple Arduino Unos, it's just a pain in the arse to make them work synchronously, instead use (for example) a single Arduino Mega 2560 which has 14 PWM outputs and still cheap as dirt.

I'm not sure about the life length of the AA batteries, I might consider using Li-Po (something from an RC shop, or something) or Li-ion (18650 is very popular and cheap) batteries. The Arduinos can take basically anything from 9 to 6 volts (and 5 from the USB), so you have a bit of freedom there.

A bit of electrical stuff: High available current is not a problem for the Arduino, it takes as much as it needs, so as long as you are in the voltage range of the board, you won't have any problems. Less amperage however is a problem, so be sure your battery can provide enough current!

You probably won't need cooling, there are no devices in your spider that would require more than a heatsink, if at all. But soldering is very recommended, I urge you to reconsider about that.

The Bluetooth module becomes unnecessary by going with a single Arduino.
For distance sensor I recommend an ultrasound one, those are really (ridiculously) cheap and simple to use. (HC-SR04 is very popular for example and there are tons of tutorials for it)

LED's are okay, most people don't think about the resistors, but those are important!

A question: Why do you need 12 servos?

That's all I got in the first round, feel free to share more info and I'll try to help you with your planing. I highly recommend you to share the schematics with us so we can help you to improve it!

Edit: I almost forgot: do you intend to use some kind of connection to the spider, like Bluetooth or Wi-Fi?

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

As far as batteries go, I'd recommend at least 6 volts, so you can use the Arduino's barrel connector. You may use 2 serial Li-ion batteries and a buck converter, but I believe you'll do fine without it, your servos will handle the extra 0.2 volts.

About the current limits: Your Arduino can supply around maximum 500 mA from all it's pins, and 40mA from a single pin, BUT it won't be a problem, because you do not connect the servos' VCC (+) and GND (-) pins to the Arduino, instead you hook them up to the battery directly. You only connect the SIGNAL pins to your Arduino which draw less then 10 mA.

For the communication with the spider I'd recommend a Wi-Fi module and UDP, as the protocol for the communication.

G.

body:
For connecting 2 Arduinos use some wires - I2C works good for me, but Serial is also good. Anyway you probabely will came to problem with interrupts and many tasks running in paralel, or the spider be slow - you choose not so easy target (but reacheble).

As for bateries - Arduino need constant power, than it takes as much current as it needs (if it is aviable), so no problem in 2 AA for Arduino.

You would need a lot of servos - they are, what takes energy - even if 2AA can give a lot for short time, this will not last long. Also giving high current means voltage drops (as for cable and mainly internal batery resistence), so if you feed arduino from the same source, it can reset every time, when too much servos try to move/stang agains gravity.

 Different source for Arduino is good idea, as the CPU will last longer, then those actuators and could shutdown properly (not let move just one leg or so). Also the electrical interference from servos would be much less this way. (There are other ways, more complicated to do that).

Breadbourd can be stripped the bottom plastic and have it exchange for more thinner double-size tape, then be put on large alluminium (or other heat-conducting) plate for better cooling too.

Arduino cannot move all those servos from its source, think about alimitation currrent per pin and per arduino itself - you may need some other IC/transistors to power it properly on each servo and the servo power should go direct from bateries, not via Arduino. Connect just grounds.


body:
I have used by Arduino countless times over the past few years and only after installing an update to Mac OS Sierra did the device stop showing up under the Serial Ports. Now only tty-bluetooth shows up no others. I have looked a countless threads where people suggest installing drivers or uninstalling drivers or rebooting. I have tried everything but still no device shows up.

I switched to my Windows partition using Bootcamp and lo and behold it works perfectly there but not in Mac OS. I would still like to use Mac OS to programme my Arduino. If anyone has any suggestions I would be very grateful!

title: Arduino Nano not visible in Serial Ports (Mac OS)

Answers: 1

body:
Is it an original Nano or a clone?

The original Nano uses FTDI's FT232 ship, whereas clones use the CG340 USB-to-TTL chip. The former works fine straight away Mac OS Sierra, whereas the latter needs a driver.

The CG340 driver doesn't work under Mac OS Sierra. Fortunately, someone patched the driver and made it [available at GitHub][1]. There you'll also find some troubleshooting instructions that can help (hopefully).

From Adrian Mihalko's repository at GitHub:

----------

ch340g-ch34g-ch34x-mac-os-x-driver
==================================

Latest **macOS Sierra**-compatible driver for devices using the CH340G, CH34G or CH34X chipset. This chipset is used in several Arduino-clones.

Introduction
------------

Version 1.3 (2016-09-27) of the [OEM driver][2] for the CH34x chipset currently causes a kernel panic (a.k.a. *crash*) when installed on **macOS Sierra.** To resolve this issue, please download and install the driver in this repo.

Installation
------------

- Remove the old driver by issuing one of the following commands (depending on your installation):
  - `sudo rm -rf /System/Library/Extensions/usb.kext`
  - `sudo rm -rf /Library/Extensions/usbserial.kext`
- Restart your Mac.
- Double-click on the `CH34x_Install_V1.3.pkg` file.
- Restart your Mac.
- Plug in your device. It should now be listed under the `/dev` directory. Examples:
 - `/dev/cu.wchusbserial1410`
 - `/dev/cu.wchusbserial1420`

Troubleshooting
---------------

If, and only if, the device is not recognized after the installation (or you cannot install the driver), please disable *System Integrity Protection*:

- Reboot your Mac into *Recovery Mode* by restarting your computer and holding down `Command+R` until the Apple logo appears on screen.
- Open the Terminal (Applications > Utilities > Terminal).
- In the Terminal window, type in `csrutil enable --without kext` (or to fully disable: `csrutil disable`) and press Enter.
- Restart your Mac.

Please share this page!

Regards,
Adrian Mihalko

  [1]: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
  [2]: http://www.wch.cn/download/CH341SER_MAC_ZIP.html


body: I'm building an IoT power usage monitor in which the data is logged using a RTC and an SD card module and a web app hosted on an ESP8266 gives access to this data. My question is can I use the exact same code (with libraries like "ESP8266.h") on a standalone ATmega programmed using Arduino as ISP?

title: Can I port a project built on Arduino Uno to a standalone ATmega328 using the exact same code?

Answers: 3

body:
You can run any code on an ATMEGA328P that you can run on an Arduino Uno. For maximum compatibility, you would configure the ATMEGA328P with a 16Mhz crystal/resonator.
There are instructions for using an Arduino Uno as an ISP for programming other devices, many of which require a Uno with a DIP version of the ATMEGA chip which can be removed.
What you cannot do is directly run code for an ESP8266 on an ATMEGA328P.

body:
Yes, it might work. But as a minimum you should check that the following is mapped between the two in a compatible way:

 1. Pinout and configuration of pins. ESP8266 allows INPUT_PULLDOWN in some pins, whereas ATmega328 doesn't.
 2. Use of timers and interrupts. ESP8266 accepts "true" interrupts on all I/O pins, whereas ATmega328 only accepts them in 2 pins (although you can use Pin Change Interrupts (PCIx), which are far less powerful than "true" External Interrupts (INTx)). Also, ESP8266 accepts HIGH level interrupts, whereas ATmega328 doesn't (even on INT-capable pins).
 3. Use of specific ESP8266 libraries which won't work at all on an ATmega328

The Arduino library ports for ESP8266 may work as expected out of the box, it may require minor tweaks, or it may require a major revamp of key code fragments. It's difficult to say without seeing the code.

body:
Almost all of my projects are roll-your-own-duinos with Atmega 328p chips, with code generated for an "Arduino/Genuino Uno" board. Many of them use an ESP8266-01 board as a WiFi interface. I either run the entire board at 3.3v or use a daughter-board that interfaces the ESP to a 5v environment.

If you're porting code from an actual Arduino Uno, there is nothing to do except to make sure your pinouts are the same between the Arduino and the RYO-duino. Otherwise, make all your pin definitions constants and group them together in such a way (e.g. with #ifdef / #else / #endif) that you can easily enable one or the other group just before you compile.

Update:

> There's a bit more required, for example, the clock rate needs to
> match or the timing will be off ...

I did gloss over the power & clock since the question hadn't asked about departures from the Uno's design. But yes, a RYO will need a compatible power supply and a matching clock rate, to be able to assume an arbitrary sketch could be run on it successfully. To make the RYO look like an UNO, it will need 5v power and a 16 MHz crystal, just as the Uno design provides.

If a RYO is designed be other than like an Uno, considering power source, clock rate, fuse options, DIP instead of an SMT, then there is nothing to support the supposition that a port from an Uno could succeed *without* modifying the code for those differences.


body:
I am currently using relay module, but I am facing a problem that, when Arduino pins are LOW then all relay are going HIGH, so I want to use this code so that when arduino starts all pins are getting HIGH, and also can be control with char data/switch(data)/case break;/,

    Here is my code:

    setup() {
      if(conditionIsTrue) {
        aGroup::setup();
      } else {
        bGroup::setup();
      }
    }

    loop() {
      if(conditionIsTrue) {
        aGroup::loop();
      } else {
        bGroup::loop();
      }
    }

    namespace aGroup {
    setup() {

     pinMode(ledPinA, OUTPUT);
        pinMode(ledPinB, OUTPUT);
        pinMode(ledPinC, OUTPUT);
        pinMode(ledPinD, OUTPUT);
        pinMode(ledPinE, OUTPUT);
        pinMode(ledPinF, OUTPUT);
        pinMode(ledPinG, OUTPUT);
        pinMode(ledPinH, OUTPUT);
        pinMode(ledPinI, OUTPUT);
        pinMode(ledPinJ, OUTPUT);
        pinMode(ledPinK, OUTPUT);
        pinMode(ledPinL, OUTPUT);

    }

    loop() {

      digitalWrite(ledPinA, HIGH);
      digitalWrite(ledPinB, HIGH);
      digitalWrite(ledPinC, HIGH);
      digitalWrite(ledPinD, HIGH);
      digitalWrite(ledPinE, HIGH);
      digitalWrite(ledPinF, HIGH);
      digitalWrite(ledPinG, HIGH);
      digitalWrite(ledPinH, HIGH);
      digitalWrite(ledPinI, HIGH);
      digitalWrite(ledPinJ, HIGH);
      digitalWrite(ledPinK, HIGH);
      digitalWrite(ledPinL, HIGH);

    }
    }

    namespace bGroup {
    setup() {
      Serial.begin(9600);
        pinMode(ledPinA, OUTPUT);
        pinMode(ledPinB, OUTPUT);
        pinMode(ledPinC, OUTPUT);
        pinMode(ledPinD, OUTPUT);
        pinMode(ledPinE, OUTPUT);
        pinMode(ledPinF, OUTPUT);
        pinMode(ledPinG, OUTPUT);
        pinMode(ledPinH, OUTPUT);
        pinMode(ledPinI, OUTPUT);
        pinMode(ledPinJ, OUTPUT);
        pinMode(ledPinK, OUTPUT);
        pinMode(ledPinL, OUTPUT);

    }

    loop() {

      char data = Serial.read();
        switch(data)
        {
            case 'A': digitalWrite(ledPinA, HIGH);break;
            case 'B': digitalWrite(ledPinA, LOW);break;

            case 'C': digitalWrite(ledPinB, HIGH);break;
            case 'D': digitalWrite(ledPinB, LOW);break;

            case 'E': digitalWrite(ledPinC, HIGH);break;
            case 'F': digitalWrite(ledPinC, LOW);break;

            case 'G': digitalWrite(ledPinD, HIGH);break;
            case 'H': digitalWrite(ledPinD, LOW);break;

            case 'I': digitalWrite(ledPinE, HIGH);break;
            case 'J': digitalWrite(ledPinE, LOW);break;

            case 'K': digitalWrite(ledPinF, HIGH);break;
            case 'L': digitalWrite(ledPinF, LOW);break;

            case 'M': digitalWrite(ledPinG, HIGH);break;
            case 'N': digitalWrite(ledPinG, LOW);break;

            case 'O': digitalWrite(ledPinH, HIGH);break;
            case 'P': digitalWrite(ledPinH, LOW);break;

            case 'Q': digitalWrite(ledPinI, HIGH);break;
            case 'R': digitalWrite(ledPinI, LOW);break;

            case 'S': digitalWrite(ledPinJ, HIGH);break;
            case 'T': digitalWrite(ledPinJ, LOW);break;

            case 'U': digitalWrite(ledPinK, HIGH);break;
            case 'V': digitalWrite(ledPinK, LOW);break;

            case 'W': digitalWrite(ledPinL, HIGH);break;
            case 'X': digitalWrite(ledPinL, LOW);break;

        }

    }
    }

But this isn't work, Please help me.

title: How to use to two different programs into one stkech

Answers: 1

body:
In first place, you have to declare the functions setup and loop as `void setup()` and `void loop()`.

If you want your output pins to be high when Arduino starts then you should do that in your setup function, instead of doing it in the loop:

    void setup() {

      Serial.begin(9600);

      // Step 1: configure pins as outputs
      pinMode(ledPinA, OUTPUT);
      pinMode(ledPinB, OUTPUT);
      pinMode(ledPinC, OUTPUT);
      pinMode(ledPinD, OUTPUT);
      pinMode(ledPinE, OUTPUT);
      pinMode(ledPinF, OUTPUT);
      pinMode(ledPinG, OUTPUT);
      pinMode(ledPinH, OUTPUT);
      pinMode(ledPinI, OUTPUT);
      pinMode(ledPinJ, OUTPUT);
      pinMode(ledPinK, OUTPUT);
      pinMode(ledPinL, OUTPUT);

      // Step 2: initialize pins to output HIGH
      digitalWrite(ledPinA, HIGH);
      digitalWrite(ledPinB, HIGH);
      digitalWrite(ledPinC, HIGH);
      digitalWrite(ledPinD, HIGH);
      digitalWrite(ledPinE, HIGH);
      digitalWrite(ledPinF, HIGH);
      digitalWrite(ledPinG, HIGH);
      digitalWrite(ledPinH, HIGH);
      digitalWrite(ledPinI, HIGH);
      digitalWrite(ledPinJ, HIGH);
      digitalWrite(ledPinK, HIGH);
      digitalWrite(ledPinL, HIGH);
    }

Also, you can't declare a variable and assign to it the value of a function other than an object constructor. Furthermore, you should check if there's data available before trying to read it. So you have replace the following sentence:

    char data = Serial.read();

With something like this:

    char data = 0;
    if (Serial.available() > 0) {
        data = Serial.read();
        // do your stuff
    }

This should do the trick.

Last but not least: I don't know why you're using two `namespace`s. The `aGroup` looks useless to me. On top of that, I fail to see where in your code do you declare, initialise and update the `conditionIsTrue` variable. The same goes for all those `ledPinX` variables. Is there more code that you're not showing here? Is your code failing at runtime, or doesn't even compile?


body: what is a servo motor shield in arduino? what is the key purpose for using it? I'm newbie in arduino and I've seen some briefings in websites which I couldn't understand, can somebody elaborate it to me?

title: Motor shields in arduino

Answers: 2

body:
Servos require power and PWM. Servo shields come in two main forms:

1. Simple distribution
2. Active control

The first kind just provides convenient 3-pin headers to the Ardino's PWM pins, and sometimes a dedicated power supply for powering the servos. They're simple and cheap, but can only provide as many servo ports as the Arduino has PWM pins.

[The second kind](https://www.adafruit.com/product/1411), more expensive, has a PWM chip on it to provide many more PWM pins than the Arduino can natively provide. Again there is sometimes a power supply as well, along with the convenient 3-pin headers. You usually interface with this kind using either I2C or SPI.  These are the ones people usually mean when they talk about a servo shield - a shield designed for powering and controlling many more servos than an Arduino by itself can manage.

Servo Motor Shields should not be confused with Motor Shields, which provide a number of H-Bridge drivers for powering and controlling (both the speed and direction) of a brushed DC motor.

body:
The dumb ones are basically distributors of power for the servo motors.
There are more clever boards that offer the control of multiple servos (usually 10+) by communicating with the Arduino via some higher-than-PWM-level control (Like I2C) thus taking less pins from the Arduino than a dumb servo shield.
Both kinds usually require a power supply to power the servos.

G.


body:
I recently ordered an HC-06 Bluetooth module for my Arduino Uno, and after watching [this video](https://www.youtube.com/watch?v=F6E5mP70jaw&t=1s), and many others, I still have been having many issues figuring out how to get it to work, and some questions for how the code receives and reads serial data from my phone.

1. I assume this wiring is correct, right?
 - Rx  > Tx
 - Tx  > Rx
 - Gnd > Gnd
 - Vcc > 3.3V

2. When I sent a command over the Bluetooth terminal app I have, the serial monitor displays that command over and over, I assume that is correct also?

3. How do I read the serial input? I've been using

        if(Serial.available() > 0)
                phoneInput = (char) Serial.read();
and then displaying the value of phoneInput to the serial monitor, but for some reason I can't seem to have it control anything properly (in this case an LED)

4. What datatype is the Serial.read() returning to my variable before I cast char on to it?

5. I get errors uploading the code to the board (avrdude: stk500_recv(): programmer is not responding), until I remove the pin connected to the Rx on the arduino, is there a cleaner solution to uploading the board without unplugging wires?

title: Issues using HC-06 Bluetooth module with arduino

Answers: 1

body:
> I assume this wiring is correct, right?
>
>     Rx > Tx
>     Tx > Rx
>     Gnd > Gnd
>     Vcc > 3.3V

Almost. The Arduino's TX should be reduced to 3.3V using a 10k/20k potential divider.

> How do I read the serial input? I've been using
>
>     if(Serial.available() > 0)
>            phoneInput = (char) Serial.read();

You should read and digest [this](https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/).

> What datatype is the Serial.read() returning to my variable before I cast char on to it?

An integer. It holds either 0-255 representing the ASCII code for a character, or -1 if there is nothing in the buffer to read.

> I get errors uploading the code to the board (avrdude: stk500_recv(): programmer is not responding), until I remove the pin connected to the Rx on the arduino, is there a cleaner solution to uploading the board without unplugging wires?

That will be because you are using pins 0/1 to communicate with the bluetooth which you can't do because those are used to communicate with the PC.


body:
I am using arduino mega for my application .  Board works well for a week , from yesterday it  is not programming at all , it shows me some error like timeout . What could be the problem kindly  help me to solve this.

 avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
    Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
    Copyright (c) 2007-2014 Joerg Wunsch

    System wide configuration file is "C:\Program Files\Arduino\hardware\tools\avr/etc/avrdude.conf"

    Using Port                    : COM20
    Using Programmer              : wiring
    Overriding Baud Rate          : 115200
 avrdude: ser_open(): can't open device "\\.\COM20": The system cannot find the file specified.

 Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
 avrdude: ser_drain(): read error: The handle is invalid.

 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: ser_send(): write error: sorry no info avail
 avrdude: stk500_send(): failed to send command to serial port
 avrdude: ser_recv(): read error: The handle is invalid.

 avrdude: stk500v2_ReceiveMessage(): timeout
 avrdude: stk500v2_getsync(): timeout communicating with programmer

 avrdude done.  Thank you.

title: Unable to program Arduino mega2560?

Answers: 1

body: Com 20 is not configured with your arduino. Go to the arduino program and I think it is on the tools tab or the one next to it. There should be a port label and it says which com port to use. Then go to device manager, then ports. Then go to properties on the port that has arduino and change that to the port the arduino program said. It should work then. This topic has been solved many times.


body:
I guess I just fried my second DUE in a week. The first I didn't really see what happened, but I couldn't upload any sketches, even if the computer could recognize it, and the SAM would get really hot.

Now, I had it powered by a 12V External supply, through a regulator bringing it down to 9V, and in the exact moment I plugged the USB, with power still on, I got a lot of smoke, smelling of fried electronics :p. Afterwards, I have the same symptoms as I had in the other boards: Green and orange LEDs on, chip very hot, computer recognizing it as a Arduino DUE but not being able to upload any sketches.

What just happened?

title: Did I fry my DUE by powering it from a external source and USB at the same time? If so, why?

Answers: 2

body:
As Majenko said you should check these voltages.

Arduino DUE uses the LM2734Y DC/DC converter and according to datasheet it works up to 20V so there is no need to use your 9V regulator.

Also on DUE there is comparator which should turns off a USB power supply when external power supply is used. Look for 2 transistors on board (FDN340P) called T1 and T2. There both are turning on/off power from USB source. Also check them. There can be also problem with all components around USB power. For more info check [Arduino] schematic.

[Arduino]: https://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf

body:
If it was the same sketch involved in the destruction of both it may be a good idea to check to make sure the sketch that is involved as well to make sure there are no logical shorts to ground or other pins. [Rugged-Circuits][1] has a list of some common ways the Arduino can get shorted. It is showing the Uno but I am sure all similar rules apply with the exception of total power requirements and other differences between the boards.

  [1]: https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/


body:
I have two arduinos that I would like to use to communicate with two xbees. I programmed both xbees with the xbee explorer breakout boards in XCTU, and got them to communicate on XCTU. They are XB24Cs, with the Zigbee function set, both on the same PAN ID, one as a Coordinator and one as a router, not on API mode. When I put the router on an xbee shield on an arduino, I run a program on the arduino that should allow me to communcate both ways, However I can send something through the serial and have it show up on the XCTU, but anything typed in XCTU will not show up in arduino. The arduino shield is the sainsmart xbee pro shield, and I tried it both with the jumpers in USB and XBee mode, however I can only ever upload first when it is on USB mode. How can I make communication possible from the computer to the arduino?

Here is my arduino code:

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

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

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

    void loop() {
     Serial.println("test");
     delay(1000);
      if(Xbee.available()){
        Serial.println(Xbee.read());
      }
      if(Serial.available()){
        Xbee.write(Serial.read());
      }
    }

title: Xbee can send from arduino to XCTU, but not the other way around

Answers: 0


body:
The code below was taken online and was written for the Arduino Uno. I know C++ however I am a beginner with Arduino so I don't understand this compatibility issue or how to fix it. I am very thankful for any help. Here is part of the code - the variable declarations: (I can upload the entire code if that would be more helpful).

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

    ISR(PCINT0_vect) {
      current_time = micros();
      //Channel 1=========================================
      if(PINB & B00000001) { //Is input 8 high?
        if(last_channel_1 == 0) { //Input 8 changed from 0 to 1.
          last_channel_1 = 1; //Remember current input state.
          timer_1 = current_time; //Set timer_1 to current_time.
        }
      } else if(last_channel_1 == 1) { //Input 8 is not high and changed from 1 to 0.
        last_channel_1 = 0; //Remember current input state.
        receiver_input[1] = current_time - timer_1; //Channel 1 is current_time - timer_1.
      }
      //Channel 2=========================================
      if(PINB & B00000010 ) { //Is input 9 high?
        if(last_channel_2 == 0) { //Input 9 changed from 0 to 1.
          last_channel_2 = 1; //Remember current input state.
          timer_2 = current_time; //Set timer_2 to current_time.
        }
      } else if(last_channel_2 == 1) { //Input 9 is not high and changed from 1 to 0.
        last_channel_2 = 0; //Remember current input state.
        receiver_input[2] = current_time - timer_2; //Channel 2 is current_time - timer_2.
      }
      //Channel 3=========================================
      if(PINB & B00000100 ) { //Is input 10 high?
        if(last_channel_3 == 0) { //Input 10 changed from 0 to 1.
          last_channel_3 = 1; //Remember current input state.
          timer_3 = current_time; //Set timer_3 to current_time.
        }
      } else if(last_channel_3 == 1) { //Input 10 is not high and changed from 1 to 0.
        last_channel_3 = 0; //Remember current input state.
        receiver_input[3] = current_time - timer_3; //Channel 3 is current_time - timer_3.
      }
      //Channel 4=========================================
      if(PINB & B00001000 ) { //Is input 11 high?
        if(last_channel_4 == 0) { //Input 11 changed from 0 to 1.
          last_channel_4 = 1; //Remember current input state.
          timer_4 = current_time; //Set timer_4 to current_time.
        }
      } else if(last_channel_4 == 1) { //Input 11 is not high and changed from 1 to 0.
        last_channel_4 = 0; //Remember current input state.
        receiver_input[4] = current_time - timer_4; //Channel 4 is current_time - timer_4.
      }
    }

    void set_gyro_registers() {
      //Set up the MPU-6050
      if(eeprom_data[31] == 1) {
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search.
        Wire.write(0x6B); //We want to write to the PWR_MGMT_1 register (6B hex)
        Wire.write(0x00); //Set the register bits as 00000000 to activate the gyro
        Wire.endTransmission(); //End the transmission with the gyro.
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search.
        Wire.write(0x1B); //We want to write to the GYRO_CONFIG register (1B hex)
        Wire.write(0x08); //Set the register bits as 00001000 (500dps full scale)
        Wire.endTransmission(); //End the transmission with the gyro
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search.
        Wire.write(0x1C); //We want to write to the ACCEL_CONFIG register (1A hex)
        Wire.write(0x10); //Set the register bits as 00010000 (+/- 8g full scale range)
        Wire.endTransmission(); //End the transmission with the gyro
        //Let's perform a random register check to see if the values are written correct
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search
        Wire.write(0x1B); //Start reading @ register 0x1B
        Wire.endTransmission(); //End the transmission
        Wire.requestFrom(gyro_address, 1); //Request 1 bytes from the gyro
        while(Wire.available() < 1); //Wait until the 6 bytes are received
        if(Wire.read() != 0x08) { //Check if the value is 0x08
          digitalWrite(12,HIGH); //Turn on the warning led
          while(1)delay(10); //Stay in this loop for ever
        }
        Wire.beginTransmission(gyro_address); //Start communication with the address found during search
        Wire.write(0x1A); //We want to write to the CONFIG register (1A hex)
        Wire.write(0x03); //Set the register bits as 00000011 (Set Digital Low Pass Filter to ~43Hz)
        Wire.endTransmission(); //End the transmission with the gyro
      }

title: Why won't this code work on an Arduino Mega 2560 (It works on an Arduino Uno)?

Answers: 2

body:
As no preview is available at the given links (for [YMFC-AL_setup.ino](https://drive.google.com/file/d/0B5tJTKkHim16NFZUenB6elZEbDA/view) and [YMFC-AL_Flight_controller.ino](https://drive.google.com/file/d/0B5tJTKkHim16VDFhdHhNUDVOcTA/view) at drive.google.com) and I don't want to download the code to my system, I haven't looked at the whole program; however, from the code included in the question, it's clear that it uses direct IO rather than Arduino API IO.

Direct IO expressions like `PINB & B00000001` [see Edit 1, Note 1] affect differently-numbered digital pins on the Mega than on the Uno or Nano.  (Or, more generally, on boards based on ATmega256x vs ATmega328x or 168x vs ATmega32U4 or 16U4.)

On the Arduino Nano and Uno, PB0–PB5 are assigned to Arduino digital pins 8–13.

On the Arduino Micro with 32U4, PB0–PB3 are not assigned to Arduino digital pins; they connect to SS, SCK, MOSI, MISO, while PB4–PB7 are assigned to Arduino digital pins 8–11.

On the Arduino Mega2560 with  ATmega2560,  PB0–PB3 are assigned to Arduino digital pins 53, 52, 51, 50 respectively, and PB4–PB7 are assigned to 10–13.

Summary:  To adapt direct IO code written for an Uno to a Mega, you may need to change ports and pins numbers.  Just moving wires around to corresponding pins may or may not fix problems; if the code uses a mix of direct IO and API IO (with `digitalWrite()` etc.) the code may need to be changed as well.  For example, in `setup()` it might use API pin identifiers, and in ISRs might use direct IO, an approach that will malfunction when transferring code to a differently-mapped board.

Note, see [numerous excellent pinout diagrams](http://www.pighixxx.com/test/pinoutspg/) at pighixxx.com.

*Edit 1:*

Note 1:  In a file called `binary.h`, the Arduino IDE's programming environment defines a set of 510 constants whose names consist of a `B` followed by from 1 to 8 zeroes and ones, with values equal to corresponding binary numbers.  The value of the expression `PINB & B00000001` is equal to the low-order bit (PB0) of input register PINB.    The value of `PINB & B00001000` is 8 (ie, 1<<3) if PB3 is high, and is 0 if PB3 is low.  Typically, these binary constants are used as *bit masks* for bit operations (AND &, OR |, XOR ^).

Note 2:  When including code in a stackexchange question or answer, first paste the code into the question or answer editing box; then in that editing box, highlight the code and press ctrl-k.  (Alternately, highlight the code and click the `{}` icon in the toolbar at the top of the editing box.)

Rather large sections of code can be pasted into questions and answers.  Generally, paste in at least enough to be compilable and exhibit the problem.  If any variable or procedure definitions, `#include` lines, etc., are left out, people may have to play guessing games to answer the question, and that's generally undesirable as it wastes time and does not elicit good answers.

body: The sketch uses I2C to communicate with the Gyro / Accelerometer. On a Uno these pins are A4 (SDA) and A5 (SCL). On a Mega these pins are 20 (SDA) and 21 (SCL).


body:
Im having a little problem with my code. here i called a function to make a test, if it passed it goes back and continue if it doesn't it goes to main loop.

    void loop()
    {

        if (call == 1)
        {
            funca();
        }
        print("waiting..");
    }
     void funca()
        {
            gsmtest();
            print("calling..")
        }
     void gsmtest()
        {
            if (test==1)
                 {
                print("test ok");
                 }
            else
                  {
                    print("error");
                    loop();
                  }
        }
here is a simple example, if u press call, the code goes to funca which make a call to gsmtest. if test goes ok it print "calling.." if not it print "error" and goes back to loop. for some reasons here if test failed, it print error and than goes to loop after that it print "calling.." (continuing funca which i want to abort it if test goes wrong) .

title: Call function and not came back

Answers: 1

body:
You're overflowing your stack due to infinite recursion.

By explicitly calling `loop()` you are breaking the whole call stack system. You effectively have:

    loop() ->
      funca() ->
        gsmtest() ->
          loop() ->
            funca() ->
              gsmtest() ->
                etc...

Instead of>

    loop() ->
        funca() ->
            gsmtest()
        <-
    <-

Instead of calling `loop()` you should use `return;` to "return" back to where the function was called from.

For example:

    void loop() {
     if (call == 1) {
      funca();
     }
     print("waiting..");
    }

    void funca() {
     if (!gsmtest()) return;
     print("calling..")
    }

    bool gsmtest() {
     if (test == 1) {
      print("test ok");
     } else {
      print("error");
      return false;
     }
        return true;
    }


body:
So I made this circuit + a momentary push button on D2 and GND: [![enter image description here][1]][1]

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

Because I don't use a real arduino, I use the RAW port to act like the +5V port. It all worked with a single LED without the npn transistor. Now, with the transistor, the strip of LED's doesn't turn off anymore when I hit the button. The code:

     #include <SoftwareSerial.h>

      #include <Keyboard.h>

      boolean toggle = false;
      int inPin = 2;
      int outPin = 3;

      int state = HIGH;
      int ledOn;
      int reading;
      int previous = LOW;

      long time = 0;
      long debounce = 200;

      void setup() {
        // make pin 2 an input and turn on the
        // pullup resistor so it goes high unless
        // connected to ground:
        pinMode(inPin, INPUT_PULLUP);
        pinMode(outPin, OUTPUT);
        Keyboard.begin();
      }

      void loop()
      {
        reading = digitalRead(inPin);
        ledOn = digitalRead(outPin);

        // if the input just went from LOW and HIGH and we've waited long enough
        // to ignore any noise on the circuit, toggle the output pin and remember
        // the time
        if ((reading == LOW) and (ledOn == LOW)) {
          state = HIGH;
          Keyboard.press((char) 128);
          Keyboard.press('r');
          delay(50);
          Keyboard.releaseAll();
          delay(200);
        }

        if ((reading == LOW) and (ledOn == HIGH)) {
          state = LOW;
          Keyboard.press((char) 32);
          delay(10);
          Keyboard.releaseAll();
          delay(100);
          Keyboard.press((char) 177);
          delay(10);
          Keyboard.releaseAll();
          delay(200);

          time = millis();
        }

        digitalWrite(outPin, state);

        previous = reading;
      }

title: Why is D3 not activating?

Answers: 2

body:
You need to adjust the value of Rc, the collector current limiting resistor. When replacing the single LED with a strip of N LEDs of the same kind, you have increased N times the current required (that's why you need to use a BJT, because the Arduino I/O pins won't supply that much current). So, you need a new value for that resistor, let's call it Rc', much lower: Rc' = Rc/N. Otherwise, the old value may limit the current far below of what the LEDs need to light up.

But that's not all. You also need to add 2 resistors:

 1. Rb: a current limiting resistor between D3 and the BJT base. Its value should be in the range 330 - 2200 Ohm. The higher the current draw of the LED strip, the lower the value of Rb should be.
 2. Rpd: a pull-down resistor between the BJT base and ground to avoid it floating while D3 is not initialised as `OUTPUT`. Make it at least 20x the value of Rb.

All this should be enough to make it work.

body:
Looks like Eric has beaten me to it with his answer, which is more thorough than mine, but I'll explain why the base resistor works anyway.

Your code relies on reading the level of a pin set to output.  It will only switch off the output if that output is already reading "high".

If you don't have a resistor on the base, then a pretty high current will flow from base to emitter.  This will pull the level of the output down below the threshold for "high", even if it's being driven.  (It also might blow the output, but I guess you have been lucky.)

It's unusual, even if perhaps not "wrong", to read the value of an output.  I'd use a global or static variable to hold the on/off state, rather than reading it.


body:
I am using an Arduino Uno with GSM shield, trying to read some SMS. Here is my code.
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(7, 8);

    char incoming_char=0;

    void setup()
    {
      Serial.begin(19200); // for serial monitor
      SIM900.begin(19200); // for GSM shield
      SIM900power();  // turn on shield
      delay(20000);  // give time to log on to network.

      SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
      delay(100);
      SIM900.print("AT+CNMI=2,2,0,0,0\r");

      delay(100);
    }

    void loop()
    {
      // Now we simply display any text that the GSM shield sends out on the serial monitor
      if(SIM900.available() >0)
      {
        incoming_char=SIM900.read(); //Get the character from the cellular serial port.
        Serial.print(incoming_char); //Print the incoming character to the terminal.
      }
    }

My issue is: am testing sending this sms to the shield

> A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z

but somehow am not getting all the info, why?

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

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

title: GSM serial get event or read the whole input?

Answers: 0


body:
My board.

![Arduino Board](https://i.stack.imgur.com/z9L5V.jpg)

I think I have it wired correctly (the lights aren't, but the board is).

I've read through the first few Google results to no avail.

My sample code to test the chip:

    // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    void setup () {
      while (!Serial); // for Leonardo/Micro/Zero

      Serial.begin(57600);
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
         rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      }
        }

    void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));

    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println();
    delay(3000);
    }

Serial output:

    `RTC is NOT running!
    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

    2165/165/165 (Tuesday) 165:165:85
     since midnight 1/1/1970 = 1551138385s = 17952d
     now + 7d + 30s: 2019/3/5 12:16:31

title: DS1307RTC Outputting cryptic 165/165/2165 date. What are some possible fixes?

Answers: 10

body:
Your picure shows also another device on the bread board. Remove that and ensure that:

Uno Ground --> 1307 Ground

Uno 5Volt --> 1307 +5v

Uno A4 --> 1307 Data

Uno A5 --> 1307 Clock

If the 1307 has a power led indicator, it should be lit.

If that still does not work, then in the code, comment this line out:

    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

and uncomment this line to set the 1307 with a specific time stamp:

    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));

body:
Had the same issue, however, my RTC was 1302 (not 1307) and yours seems to be as well, please check.
If it's 1302, use this library:
https://github.com/msparks/arduino-ds1302

Also, make sure you connect pins like this:

 1. Arduino Pin 7 goes to CLK
 2. Arduino Pin 6 goes to DAT
 3. Arduino Pin 5 goes to RST
 4. Arduino 5+ goes to VCC
 5. Arduino GND goes to GND

body:
Put in the following line in void setup():

    Wire.begin();

(Assuming Wire library has been included.)
This will set up the I2C connection between the Master (Arduino) and the Slave (RTC).

For more generic use, the syntax is: Wire.begin(address);

The complete code is:

    void setup () {
      Wire.begin();
      Serial.begin(9600);
      //rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // UNCOMMENT TO SET TIME & DATE TO THAT AT COMPILATION.
      //rtc.adjust(DateTime(2017, 8, 31, 14, 45, 14 )); // UNCOMMENT TO SET TIME & DATE MANUALLY. (YEAR, MONTH, DAY, 24-HOUR, MINUTE, SECOND)

    }

body:
On the DS3231 seems like the device can get unsynchronized with the microcontroller. Not sure if the same problem with DS1307 I think worth trying.
My [complete solution][1] on stackoverflow for the same question

> The I2C interface is accessible whenever either VCC or VBAT is at a
> valid level. If a microcontroller connected to the DS3231 resets
> because of a loss of VCC or other event, it is possible that the
> microcontroller and DS3231 I2C communications could become
> unsynchronized, e.g., the microcontroller resets while reading data
> from the DS3231. When the microcontroller resets, the DS3231 I2C
> interface may be placed into a known state by toggling SCL until SDA
> is observed to be at a high level. At that point the microcontroller
> should pull SDA low while SCL is high, generating a START condition.

  [1]: https://stackoverflow.com/a/47027763/1976512

body:
I can verify that the 1302 does not work with the 1307 library.  Very different chips.  No I2C on the 1302.  I'm trying to setup an autosync with the 1302 by studying how the 1307 does it... not having a lot of success.
I did it once before, and it is driving me bonkers that I can't figure it out again.

body:
I had the same "165" problem.  Very intermittent.  Turns out that I was drawing too much power from the Arduino rails for the circuit I was controlling.  I was being lazy by not powering it independently when I started.  Nick Gannon on arduino.cc showed where the 165 came from and solved my problem.  He included the bcd math.
https://forum.arduino.cc/index.php?topic=184908.0

body: I had the same exact issue and discovered that the Tiny RTC 1307 board.  I found that the board I had was operating at 3.3v.  Once I moved the board to a 3.3v pin on my Arduino Nano.

body:
I had the same problem 165/165.

I change the Crystal 32 kHz which solved my problem.

body:
I had same issue.
Put in setup `rtc.begin();`

body:
With the Arduino Due, the 165 problem came up intermittently with a knock off DS3231 (compatible with 1307 supposedly).  Tried switching to a different RTC but it didn't help.  Switching to an Arduino Mega 2560 seems to have resolved it.  The Mega 2560 is a lot slower so maybe it was a clock speed issue?  In any case, it was useful for resolving the intermittent issue.

That said, if you always get 165:165 it means your Arduino is not communicating with your RTC.  This is a different problem and won't be solved by switching Arduinos.


body:
I'm trying to find the I2C address of an IMU plugged into my Arduino using the code from this URL: http://playground.arduino.cc/Main/I2cScanner.  However, the program stalls at this stage:

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

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

Why could this be happening?

title: Scanning for I2C addresses

Answers: 1

body:
When the I2C scanner stops, it halts in the function Wire.endTransmission. The cause is a hardware problem of the I2C bus. For example the SDA or SCL are shortcut to something or pull-up resistors are missing (as already mentioned by TisteAndii) or the sensor module is not powered.

I assume that the IMU module has already pull-up resistors for SDA and SCL on the module. Which IMU module is it ? How did you connect it ? Do you have other I2C modules to test the I2C bus ?