body:
I flashed the ESP-12E from AT firmware 2.0 (running ok) to NodeMCU (running ok). When I reflashed it back to the AT 2.0 it is stuck in endless loop on boot:

     ets Jan  8 2013,rst cause:2, boot mode:(3,6)

    load 0x40100000, len 2408, room 16
    tail 8
    chksum 0xe5
    load 0x3ffe8000, len 776, room 0
    tail 8
    chksum 0x84
    load 0x3ffe8310, len 632, room 0
    tail 8
    chksum 0xd8
    csum 0xd8

    2nd boot version : 1.6
      SPI Speed      : 40MHz
      SPI Mode       : QIO
      SPI Flash Size & Map: 8Mbit(512KB+512KB)
    no GPIO select!
    jump to run user1 @ 1000

    rf_cal[0] !=0x05,is 0xFF

I am sure I flashed it correctly, it was not my first flashing of AT firmware. Just to be sure:

    esp_init_data_default.bin -> 0x3fc000
    blank.bin -> 0x3fe000
    boot_v1.6.bin -> 0x0000
    user1.1024.new.2.bin -> 0x1000
    blank.bin -> 0x7e000

I can even reflash it to the NodeMCU firmware and it works, but reflashing to the AT firmware ends in the same endless loop again.

I suspect the problem is in initialization data, but I'm at my wit's end with it.

title: Endless loop on boot after reflashing ESP-12E with AT firmware

Answers: 1

body:
Full answer and writeup to the comments:

The error message is due to the bootloader trying to read the contents of its radio-frontend calibration data (hence the name `rf_cal`). It compares it with a magic number, `0x05`, but fails because it reads `0xFF` at that point. `0xff` is an indication that you read data from flash which was erased. After erasing a flash-sector, the data in it becomes `0xff 0xff 0xff..`. Hence it seems as if the bootloader is trying to access the data from the wrong address, thus only reading erased flash data. The RF-calibration data is stored in the file `esp_init_data_default.bin` and must be flashed to the correct address in order for the bootloader to be able to read it.

The [NodeMCU documentation][1]  tells us the needed address for `esp_init_data_default.bin` given the size of the flash of our ESP module:

[![flash addresses][2]][2]

The bootloader messages

    2nd boot version : 1.6
    SPI Speed      : 40MHz
    SPI Mode       : QIO
    SPI Flash Size & Map: 8Mbit(512KB+512KB)

indicate that the flashed firmware (or that what is overriden by `esptool.py`) uses the 8 MBit flash size. There should be two ways to fix this:

 - Put `esp_init_data_default.bin` to the address the 8Mbit (1 MByte) bootloader expects, which is `0xfc000`
 - Force the usage of the 32 MBit (4 MByte) Flash map by giving `esptool.py` the parameter `--flash_size 32m`. This makes `esptool.py` overwrite a few bytes in the firmware (at `0x000000`) to adapt the firmware.

By your comments, method one worked. If there are problems however with the flash or the firmware, consider also trying method 2.

  [1]: https://nodemcu.readthedocs.io/en/master/en/flash/#sdk-init-data
  [2]: https://i.stack.imgur.com/g7clM.png


body:
I have a weird problem. again. This time it's the PWM. I have used PWM before and I used to work the way I am doing it now. But now it just wont work. The `Fading` sketch from example works. When I compile a code with the similar code it doesn't work. Everything with respect to compilation is same.

The code that works:

    int ledPin = 3;    // LED connected to digital pin 9

    void setup() {
      // nothing happens in setup
    }

    void loop() {
      for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
        analogWrite(ledPin, fadeValue);
        delay(30);
      }
      for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
        analogWrite(ledPin, fadeValue);
        delay(30);
      }
    }

The code that doesn't work.

    #define FAN1 3
    #define FAN2 5

    void setup() {
      //EMPTY
    }

    void loop() {
      int speed1 = 25;
      int speed2 = 127;
      analogWrite(5, speed1);
      analogWrite(3, speed2);
      delay(10000);
    }

Why doesn't the second code work?

**EDIT 1:**

By not working I meant **No output** on *Second Code* and **Expected Output** on *First one*. Currently I'm using `ISIS` for simulation and `Oscilloscope` to view the output along with a `L239D` with motors attached.

In the first code the motor starts and stops as expected, with the expected PWM Waveform.

In second code, nothing. No waveform, no motor movement.

title: PWM doesn't work with my sketch

Answers: 1

body:
One omission from your code which might be causing the problems is the fact that you haven't set the pinMode. You need to set the pins as OUTPUT in setup()

    #efine FAN1 3
    #define FAN2 5

    void setup() {
     pinMode(FAN1, OUTPUT);
     pinMode(FAN2, OUTPUT);
    }

    void loop() {
      int speed1 = 127;
      int speed2 = 25;
      analogWrite(FAN1, speed1);
      analogWrite(FAN2, speed2);
      delay(10000);
    }

I am curious to know why you declared FAN1 and FAN2, but didn't use them - I'd recommend changing the analogWrite statements to use them instead of referring to the pin numbers directly.

Also, the way you're using the pin and speed means that you're using speed2 for FAN1 and vice versa, I've switched these in my example so FAN1 and speed1 go together.


body:
I am trying to change leds status via serial port screen. Here is my code but it's not reading anything from serial port screen. I got leds on D1 and D2 pins.

    void setup() {
    pinMode(5,OUTPUT);
    pinMode(4,OUTPUT);
    Serial.begin(115200);

    }

    void loop() {
    // put your main code here, to run repeatedly:
    int point = Serial.read();
     if(point == 1)
    {
    digitalWrite(5,!5);
    }
    else if(point == 2)
    {
     digitalWrite(4,!4);
    }

    }

title: How To Read Serial Data With NodeMCU

Answers: 1

body:
Your code isn't doing what you expect because of a few issues.  As echo_salik says you are only ever turning off the output pins.  If you want to toggle the values then its probably easiest to store the value in a bool and use that to control the LED.

I think - and I may be wrong - that you are pressing the one and two keys and expecting that to work.  When you press the 1 key `Serial.read()` will return 49 and 2 will return 50.  These are the ASCII values for the keys you are pressing.

Its advisable to test to see if there is any data available to read on the serial port.  `read()` will return -1 if there is no data.

    void loop()
    {
      if (Serial.available())
      {
        int point = Serial.read();
        switch (point)
        {
          case 1:
            digitalWrite(5,HIGH); // Not !5 use High and Low
            break;
          case 2:
            digitalWrite(4,HIGH);
            break;
          case 3:
            digitalWrite(5,LOW); // Not !5 use High and Low
            break;
          case 4:
            digitalWrite(5,LOW); // Not !5 use High and Low
            break;
        }  // End of switch
      }  // End of if
      delay(50);  // I have no idea why, but most programs of this sort have a delay in.  (Hope someone explains to me too)
    }  // End of function

(A switch statement is a more efficient way of doing a number of if elses)

One thing you might want to consider is the values you are checking against.  `Serial.read()` is returning a value between -1 and 255.  It is not returning the key you pressed.  If you want to change it to work with keys then you can do it by changing the case statements that are checking integers `case 1:` to ones that are checking characters i.e. `case '1':`.


body:
Below is an Arduino sketch for a basic animation, taken from the book *Beginning Arduino* by Michael McRoberts. Also, the connections have been shown. From what I have read elsewhere, this is the standard kind of code used to drive a LED dot matrix using the 595 shift registry, or the like (for example the MAX7219). Regarding the functioning of the code, I have two questions.

1. **For what percentage of the time will the LED stay lit?** In the `screenupdate()` there are no set delays. Hence, each row will stay lit only for the time it takes for the Arduino to execute the remaining loop and come back with the updated row values. How do we know for what time will the LEDs be lit, and hence predict their brightness, or for what can we do to set a particular value for this?

2. As I understand from the code, it works assuming that the ISR will fire as the code is running and will include all stages of the `led[]`. Although in this case it is not much significant, but how do we know that the ISR will fire including all the stages?If say we are updating each row of the matrix, to give a scroll effect, we would need the ISR to fire after each modification. How do we ensure this? If the ISR is too frequent, it may not let the code run. Or if it is too dispersed, the code may skip lines giving a jagged animation. Also, since the code would have some periodicity, is it not possible that some LED rows are always skipped? How do we determine the time of ISR firing perfect for the code or modify the code to ensure these do not happen(except trial and error)?

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

    #include <TimerOne.h>

    int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch)
    int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock)
    int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data)
    byte led[8]; // 8 element unsigned integer array to hold the sprite

    void setup() {
      // set the 3 digital pins to outputs
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      // Load the binary representation of the image into the array
      led[0] = B11111111;
      led[1] = B10000001;
      led[2] = B10111101;
      led[3] = B10100101;
      led[4] = B10100101;
      led[5] = B10111101;
      led[6] = B10000001;
      led[7] = B11111111;
      // set a timer of length 10000 microseconds (1/100th of a second)
      // and attach the screenUpdate function to the interrupt timer
      Timer1.initialize(10000);
      Timer1.attachInterrupt(screenUpdate);
    }

    // invert each row of the binary image and wait 1/4 second
    void loop() {
      for (int i = 0; i < 8; i++) {
        led[i] = ~led[i];
      }
      delay (250);
    }

    // Display the image
    void screenUpdate() {
      byte row = B10000000; // row 1
      for (byte k = 0; k < 8; k++) {
        shiftOut(dataPin, clockPin, LSBFIRST, led[k] ); // LED array
        shiftOut(dataPin, clockPin, LSBFIRST, ~row); // row binary number (active low)
        // latch low to high to output data
        digitalWrite(latchPin, LOW);
        digitalWrite(latchPin, HIGH);
        // bitshift right
        row = row >> 1;
      }
      // Turn all rows off until next interrupt
      shiftOut(dataPin, clockPin, LSBFIRST, 0);
      shiftOut(dataPin, clockPin, LSBFIRST, ~0);
      // latch low to high to output data
      digitalWrite(latchPin, LOW);
      digitalWrite(latchPin, HIGH);
    }

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

***ADDENDUM***

In the above code, I tried putting `Serial.println(micros())` in the `screenUpdate()` loop, but I git a very confusing results in which the time displayed seemed to increase and then decrease randomly. **I did not understand why**. Has it got to do something with ISRs? Sorry for the apparently clumsy question.

I executed the following code (from the same book) out, which includes a MAX7219 driver (with the usual setup) and creates scrollable text. It worked perfectly well. And I just want to understand how this ISR and multiplexing go together, and how do we make sure the frequency is appropriate. More of an academic question rather than a practical one.

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

    #include <avr/pgmspace.h>
    #include <TimerOne.h>
    int DataPin = 2; // Pin 1 on MAX
    int LoadPin = 3; // Pin 12 on MAX
    int ClockPin = 4; // Pin 13 on MAX
    byte buffer[8];
    #define SCAN_LIMIT_REG 0x0B
    #define DECODE_MODE_REG 0x09
    #define SHUTDOWN_REG 0x0C
    #define INTENSITY_REG 0x0A
    static byte font[][8] PROGMEM = {
    // The printable ASCII characters only (32-126)
    }
    void clearDisplay() {
    for (byte x=0; x<8; x++) {
    buffer[x] = B00000000;
    }
    screenUpdate();
    }
    void initMAX7219() {
    pinMode(DataPin, OUTPUT);
    pinMode(LoadPin, OUTPUT);
    pinMode(ClockPin, OUTPUT);
    clearDisplay();
    writeData(SCAN_LIMIT_REG, B00000111); // scan limit set to 0:7
    writeData(DECODE_MODE_REG, B00000000); // decode mode off
    writeData(SHUTDOWN_REG, B00000001); // Set shutdown register to normal operation
    intensity(15); // Values 0 to 15 only (4 bit)
    }
    void intensity(int intensity) {
    writeData(INTENSITY_REG, intensity); //B0001010 is the Intensity Register
    }
    void writeData(byte msb, byte lsb) {
    digitalWrite(LoadPin, LOW); // set loadpin ready to receive data
    shiftOut(DataPin, ClockPin, MSBFIRST, (msb));
    shiftOut(DataPin, ClockPin, MSBFIRST, (lsb));
    digitalWrite(LoadPin, HIGH); // latch the data
    }
    void scroll(char myString[], int rate) {
    byte firstChrRow, secondChrRow;
    byte ledOutput;
    byte chrIndex = 0; // Initialise the string position index
    byte Char1, Char2;
    byte scrollBit = 0;
    byte strLength = 0;
    unsigned long time;
    unsigned long counter;
    while (myString[strLength]) { // Increment count till we reach the end of the string
    strLength++;}
    counter = millis();
    while (chrIndex < (strLength)) {
    time = millis();
    if (time > (counter + rate)) {
    Char1 = constrain(myString[chrIndex],32,126);
    Char2 = constrain(myString[chrIndex+1],32,126);
    for (byte y= 0; y<8; y++) {
    firstChrRow = pgm_read_byte(&font[Char1 - 32][y]);
    secondChrRow = (pgm_read_byte(&font[Char2 - 32][y])) << 1
    ledOutput = (firstChrRow << scrollBit)
    | (secondChrRow >> (8 - scrollBit) );
    buffer[y] = ledOutput;
    }
    scrollBit++;
    if (scrollBit > 6) {
    scrollBit = 0;
    chrIndex++;
    }
    counter = millis();
    }
    }
    }
    void screenUpdate() {
    for (byte row = 0; row < 8; row++) {
    writeData(row+1, buffer[row]);
    }
    }
    void setup() {
    initMAX7219();
    Timer1.initialize(10000); // initialize timer1 and set interrupt period
    Timer1.attachInterrupt(screenUpdate);
    Serial.begin(9600);
    }
    void loop() {
    clearDisplay();
    scroll(" BEGINNING ARDUINO ", 45);
    scroll(" Chapter 7 - LED Displays ", 45);
    scroll(" HELLO WORLD!!! :) ", 45);
    }

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

title: ISR and multiplexing- time required to execute the code in Arduino

Answers: 2

body:
I think the code is likely wrong.

the code is called every 10ms, each time refreshing all columns and all rows and then immediately overwriting them all. so you should just see a quick flicker.

the typical way to approach this is to have a static variable to remember the row (or column) to be lit, and then load up the corresponding data for that row + columns when the display routine is called.

blanking isn't necessary for hc595.

edit: 1/21/2017.

now that I have a little bit more time, I would just add to the comments above.

we know the issues, as outlined above. here is a confirmation of it, in a simulation.

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

I ran your original code on an arduino uno. U2 is the shift register connected to the led matrix's rows (active low), and U3 to the columns (active high).

two things are obvious:
1. the code is invoked every 10ms;
2. the code for the most part resets the display: other than when the code is updating all rows / columns (the first half of the screenUpdate()), rows are high (inactive) and the columns are low (inactive), thanks to the display being reset by the bottom of the screenUpdate() routine.

the net result is that you for the most part don't see anything being displayed on the led, other than very fast flickers.

here is the solution: rewrite screenUpdate(), as below:

    // Display the image - alternate routine
    void screenUpdate2(void) {
        static unsigned char row = 0; // start with row 0
        //for (byte k = 0; k < 8; k++) {
            shiftOut(dataPin, clockPin, LSBFIRST, led[row] ); // LED array
            shiftOut(dataPin, clockPin, LSBFIRST, ~(1<<row)); // row binary number (active low)
            // latch low to high to output data
            digitalWrite(latchPin, LOW);
            digitalWrite(latchPin, HIGH);
            // bitshift right
            //row = row >> 1;
            row = (row==7)?0:(row+1);
        //}
        // Turn all rows off until next interrupt
        //shiftOut(dataPin, clockPin, LSBFIRST, 0);
        //shiftOut(dataPin, clockPin, LSBFIRST, ~0);
        // latch low to high to output data
        //digitalWrite(latchPin, LOW);
        //digitalWrite(latchPin, HIGH);
    }

the updated routine, screenUpdate2(), utilizes a static variable, row, to remember the current row to be displayed. it shifts out the column data, and sets up the row to be activated, and then strikes out the display to the led matrix. after that, it updates row for the next invokation.

here is how it works in the simulation:
[![enter image description here][2]][2]

hope it helps.

post-it: if the main loop has good execution time (short, and fairly deterministic), you can run screenUpdate2() in the loop and it will work as well. running it through an interrupt provides better consistency.

edit: 1/21/2017 v2

short after posting the above, a couple sharp eyed individuals noticed that the output data seems to be flipped (more noticeable at 320ms in the simulation posted above). good catch.

that's due to the following lines in the main loop:

    for (int i=0; i<8; i++) {
        led[i]= ~led[i];
    }
    delay (250);

I'm not sure what its purpose was in the original code - creating a blinking effect? - but if you comment out those lines, you will see that the execution would be as you would have expected:

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

  [1]: https://i.stack.imgur.com/QvCYr.png
  [2]: https://i.stack.imgur.com/sbta2.png
  [3]: https://i.stack.imgur.com/LHqku.png

you will find that the values match exactly what's in the led[] array.

you can think of led[] as a ram display buffer that stores information to be displayed. all your application code needs to do is to manipulate / update it in the main loop. the display routine, when called by the timer isr, will update that for you periodically, in a fully transparent and carefree manner.

I tend to utilize this approach with a lot of things. Thus having a hook to a timer to execute a piece of code is a valuable tool for a programmer to have.

edit: 1/21/2017 v3

I was asked how long screenUpdate() and screenUpdate() will run on an arduino (16MIPS): screenUpdate() takes about 2.1ms to run, and screenUpdate2() about 0.2ms. those numbers will determine the upper-end of the display update frequency.

body:
*(In a comment the asker mentioned they're not sure of the "usual approach", so I've provided this answer to hopefully help clarify)*

Here is my code for using a single 595 to drive the columns, and hooking up the rows to the Arduino pins themselves. Here I demonstrate a clear delay in each row update, as well as another delay before the image changes. I hope this helps clear up your confusion, and I apologize for not have a 2 595 setup handy (though I have 2 595s so if this doesn't help you, I'd be more than happy to set it up...), but it should be easy to adapt for a second 595. This supports a variable amount of width and height.

I also answered this assuming you just want the dotmatrix display functioning correctly, and I didn't focus on ISR. On first glance I see no delay in the row updating on the ISR version, or a delay when setting the latch pin and the whole thing seems pretty confusing. Honestly I think it might work in a perfect universe but I'm not sure (it wouldn't, as the other answer said, you'll probably just maybe observe a flicker and one row being lit). If this isn't an X Y problem and you really need ISR, I can answer that too, it just seems like we're getting into a lot of questions at once here...

<!-- language: c -->

    // Pin connected to ST_CP of 74HC595
    const int latchPin = 8;
    // Pin connected to SH_CP of 74HC595
    const int clockPin = 12;
    // Pin connected to DS of 74HC595
    const int dataPin = 11;
    // The pin of the first row of your display
    const int row1Pin = 2; // WARNING: All future rows are assumed to be row1Pin + n
    // The amount of rows your display has
    const int HEIGHT = 3;
    // The amount of columns your display has
    const int WIDTH = 2;
    // The reset pin of 74HC595 (not required as it isn't used, but this pin is pulled low)
    const int resetPin = 9;
    // Variable used to keep track of currently lit up row
    int currentRow = 0;
    // Array of rows
    int rows[] = {0b11,
                  0b01,
                  0b11};
    unsigned long lastChange = 0;

    void setup() {
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(resetPin, OUTPUT);
      digitalWrite(resetPin, LOW);
    }

    /* I don't think this works, but it might with a much higher delay.
    void reset() {
      pinMode(resetPin, INPUT);
      delayMicroseconds(1);
      pinMode(resetPin, OUTPUT);
      digitalWrite(resetPin, LOW);
    }
    */

    // enableRow changes the currently enabled row for future calls, it also changes
    // the pinMode on the previous row to "INPUT", disabling all lights on that row.
    void enableRow(int row) {
      if (currentRow != 0) {
        pinMode(currentRow, INPUT);
      }
      currentRow = row;
    }

    // This is a quick function to test one single LED or row on your dotmatrix display (I should have documented this one better but pass an incremeneting number to it and you'll see what it does...).
    void lightOne(int pos) {
      enableRow(row1Pin + int(pos / (WIDTH+1)));
      shiftOut(dataPin, clockPin, MSBFIRST, 1 + pos % (WIDTH+1));
    }

    // This function draws the display stored in "rows".
    void displayRows() {
      for (int i = 0; i < HEIGHT; i++) {
        digitalWrite(latchPin, LOW);
        enableRow(row1Pin+i);
        // shift out the bits:
        shiftOut(dataPin, clockPin, MSBFIRST, rows[HEIGHT-i-1]);
        digitalWrite(latchPin, HIGH);
        pinMode(currentRow, OUTPUT);   // set the current row's pin as OUTPUT
        digitalWrite(currentRow, LOW); // output LOW on currentRow to complete light's circuit and display
        delay(3); // time in ms to hold each row lit
      }
    }

    void loop() {
      displayRows();
      if (lastChange+1000 /* 1000ms between changes */ < millis()) {
        for (int i = 0; i < HEIGHT; i++) {
          rows[i] = random(4);
        }
        lastChange = millis();
      }
    }


body:
I have three byte arrays. I first change their values during runtime and after that I want to combine them into one bigger 4th array.

    byte a1[] = { 0x01, 0x00, 0x01 };
    byte a2[] = { 0x00, 0x11, 0x01 };
    byte a3[] = { 0x11, 0x00, 0x01 };

    byte c1[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

I first tried this, but it did not compile.

    c1 = a1 + a2 + a3;

I also tried `strcat()` and I did got a error.

title: How can I concatenate multiple byte Arrays into one Array

Answers: 3

body:
    byte *src;
    byte *tgt;
    tgt=c1;
    src=a1;
    for (int i=0;i<3;i++) *(tgt++)=*(src++);
    src=a2;
    for (int i=0;i<3;i++) *(tgt++)=*(src++);
    src=a3;
    for (int i=0;i<3;i++) *(tgt++)=*(src++);

body:
You can do it like this

    byte c1[] = {0x01, 0x00, 0x01, 0x00, 0x11, 0x01,0x11, 0x00, 0x01 };
    byte *a1 = c1;
    byte *a2 = c1+3;
    byte *a3 = c1+6;

Note that This does not make a copy byt you can access the C1 and a1 a2 and a3 as you liked.

body:
You can concatenate with `memcpy`. You just need to set the pointer at the right place inside the `c1` array.

 memcpy(c1, a1, sizeof(a1));
 memcpy(c1+sizeof(a1), a2, sizeof(a2));
 memcpy(c1+sizeof(a1)+sizeof(a2), a3, sizeof(a3));


body:
I'm using [this][1] incremental rotary encoder with a rotating disc.

Here is my system:

[![enter image description here][2]][2]

I will explain the system briefly and above is the illustration for that:

The rotary encoder(blue) is attached/fixed to a larger disc(yellow) concentrically at its origin, so both the encoder and the disc rotate together the same angle.
The disc is rotating on a fixed plane(gray). The plane has a fixed point mark(red X) on its surface.
There is also a fixed red arrow on the disc.

Each time before the system is powered, I will manually rotate the disc such that its red arrow will be aligned to the red X mark on the surface.
This adjustment each time at the beginning will provide the reference point.

After this adjustment I want to output the actual angles via Arduino.

I tried the following example code from Arduino website:

    #define encoder0PinA  2
    #define encoder0PinB  4

    volatile unsigned int encoder0Pos = 0;

    void setup() {

      pinMode(encoder0PinA, INPUT);
      digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
      pinMode(encoder0PinB, INPUT);
      digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor

      attachInterrupt(0, doEncoder, CHANGE);  // encoder pin on interrupt 0 - pin 2
      Serial.begin (9600);
      Serial.println("start");                // a personal quirk

    }

    void loop(){
    // do some stuff here - the joy of interrupts is that they take care of themselves
    }

    void doEncoder() {
      /* If pinA and pinB are both high or both low, it is spinning
       * forward. If they're different, it's going backward.
       *
       * For more information on speeding up this process, see
       * [Reference/PortManipulation], specifically the PIND register.
       */
      if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
        encoder0Pos++;
      } else {
        encoder0Pos--;
      }

      Serial.println (encoder0Pos, DEC);
    }

    /* See this expanded function to get a better understanding of the
     * meanings of the four possible (pinA, pinB) value pairs:
     */
    void doEncoder_Expanded(){
      if (digitalRead(encoder0PinA) == HIGH) {   // found a low-to-high on channel A
        if (digitalRead(encoder0PinB) == LOW) {  // check channel B to see which way
                                                 // encoder is turning
          encoder0Pos = encoder0Pos - 1;         // CCW
        }
        else {
          encoder0Pos = encoder0Pos + 1;         // CW
        }
      }
      else                                        // found a high-to-low on channel A
      {
        if (digitalRead(encoder0PinB) == LOW) {   // check channel B to see which way
                                                  // encoder is turning
          encoder0Pos = encoder0Pos + 1;          // CW
        }
        else {
          encoder0Pos = encoder0Pos - 1;          // CCW
        }

      }
      Serial.println (encoder0Pos, DEC);          // debug - remember to comment out
                                                  // before final program run
      // you don't want serial slowing down your program if not needed
    }

But this code increases one count for each encoder tick at CW direction, and decreases one count for each tick at CCW direction.
It keeps increasing from zero to 65535 in CW and decrease from 65535 to 0 in CCW.
I want to translate this code such that I can output the angle in degrees.

My encoder says its ppr is 15 and 30 ticks. This code increase/decrease one count for each tick.

Any idea how to extract the angle from this setup? (It doesn't have to use the specific code I provided.)

  [1]: http://au.rs-online.com/web/p/mechanical-rotary-encoders/6234300/
  [2]: https://i.stack.imgur.com/Z1VHk.png

title: Problem to convert rotary encoder output to angle

Answers: 2

body:
Gerben's comment is mostly right. The shortest way to adapt the behavior of that sketch to your setup is by multiplying the result by 24 (not 12, since it is 15 pulses - 30 dents, but each channel varies 15 times) and then making the modulo:

    if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
     encoder0Pos += 24;
    } else {
     encoder0Pos -= 24;
    }
    encoder0Pos = encoder0Pos % 360;

BUT... the code you posted has some problems.

 1. "The joy of interrupts is that they take care of themselves" is true, but relying on interrupts always has some drawbacks you MUST take into account. Mainly you are blocking the rest of the program (screwing up the timings for instance). I prefer to use the interrupts only when strictly needed (and this is not the case)
 2. You are performing a potentially long function (serial interaction) into an interrupt. Totally wrong
 3. You are using HALF the steps you can potentially use (since you are checking only one input, you are ignoring half the transitions).

To fix these, I propose you to rewrite the program to check in the loop the buttons status. Then, since they are mechanical switches, I'm going to use the Bounce2 library to debounce the inputs.

This, alongside with solving the previous 3 points, will also allow you to use any arbitrary pin on the board.

    #include <Bounce2.h>

    #define encoder0PinA  2
    #define encoder0PinB  4
    #define STEP_SIZE 12

    byte encoder0Pos = 0;

    Bounce debouncerA = Bounce();
    Bounce debouncerB = Bounce();

    void setup()
    {
     debouncerA.attach(encoder0PinA, INPUT_PULLUP);
     debouncerA.interval(5); // interval in ms
     debouncerB.attach(encoder0PinB, INPUT_PULLUP);
     debouncerB.interval(5); // interval in ms

     Serial.begin (9600);
     Serial.println("start");                // a personal quirk

    }

    void loop()
    {
     // Read the status of the inputs
     debouncerA.update();
     debouncerB.update();

     int8_t EncVariation = 0;

     if (debouncerA.rose())
     { // if input A changed from low to high, it was CW if B is high too
      EncVariation = (debouncerB.read()) ? 1 : -1;
     }
     else if (debouncerA.fell())
     { // if input A changed from high to low, it was CW if B is low too
      EncVariation = (debouncerB.read()) ? -1 : 1;
     }
     else if (debouncerB.rose())
     { // if input B changed from low to high, it was CCW if A is high too
      EncVariation = (debouncerA.read()) ? -1 : 1;
     }
     else if (debouncerB.fell())
     { // if input B changed from high to low, it was CCW if B is low too
      EncVariation = (debouncerA.read()) ? 1 : -1;
     }

     if (EncVariation != 0)
     {
      encoder0Pos = (encoder0Pos + EncVariation * STEP_SIZE) % 360;

      Serial.println (encoder0Pos, DEC);
     }
    }

Disclaimer: I haven't tested this, but I'm pretty confident this will work.

I highly suggest you to use the Bounce2 library, since it also has many helper functions which shorten the code a lot. See [here](https://github.com/thomasfredericks/Bounce2) for instructions on how to get and use it. I'm just a happy user of this library, and I'm not linked in any way to the author ;)

body:
As noted in a comment, treating the numbers modulo 360° will put results into the range you want.

Note, however, that you can (and should) avoid use of `long` arithmetic by taking the pulse count modulo 30 *before* multiplying by 12°.

To compensate for the reference point adjustment, have the program set your tick count to correspond to 0° when the arrows align.  If you set the base count to some value that's a multiple of 30, say 120, and store it in an unsigned byte, the code would look like so:

    angle = 12*(count0);

Since the base count 120 is a multiple of 30, it falls out automatically when the modulus is taken.  To make this work in the long run, you would set the encoder count to 120 whenever the arrows align (or to `(current0)+120` if required to adjust it at other times).

If your base count were 0 instead of 120 and the count an unsigned integer instead of a byte, when the rotor goes CCW the modulus counts would have 15 extra counts.  For example, a count of 0 correctly converts to 0°, but a count of 65535 is 15 modulo 30, so converts to 180° instead of 348°.

Note, there is no need to debounce rotary encoder inputs if a proper state machine is used; and debouncing slows processing to the point that ticks will be lost.  See [my answer to question 32572](https://arduino.stackexchange.com/a/32582/3917) which includes code for reading several encoders active at once.


body:
I want to make my alarm clock “smart”. I'm very new to this stuff, that is, the hardware side. The programming shouldn't present too many problems.

I’m currently experimenting with a simulator (http://circuits.io) and want to start with controlling the alarm’s buzzer with my Arduino.

I did some reading on transistors and this is what I came up with:

I’ve turned pin D3 to high and hooked it up to the base of a NPN transistor. I’m trying to run 1.5V through the transistor, but nothing happens. Any thoughts?

[![Circuit that I came up with.][1]][1]

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

title: How can I switch a 1.5V buzzer with my Arduino?

Answers: 1

body: You simply need to ground the circuit. In row E on your breadboard just under where you connect the - of the battery, connect that to the ground pin on the UNO. This causes the buzzer to start working.


body:
I am having a problem with an Arduino Mega 2560.

Everything works fine, the ultrasonic sensors work fine, and the other LEDs work fine. Although there is 2 LEDs who do not work right and when I do `analogWrite()`, they actually do `digitalWrite()`. I have tried to attach these two LEDs to a potentiometer (potentiometer works fine, values are tested) but it always does `digitalWrite()` not `analogWrite()`.

I have tested the LEDs and potentiometer on an Arduino Uno in PWM pins and analog pin and yes it does work very well.

Please mind that these LEDs are attached to analog pins. Why is this? Because I do not have anymore PWM pins available to use and so I have to use analog pins. No way I can rearrange this.

Here is part of the code (only part otherwise it's too long, most of my pins are taken):

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

    //Leds//

    int led = A4;
    int ledUV = A3;

    //Potentiometer//

    int potReading;
    int potPin = A2;
    int lightDim;

    void setup(){

     Serial.begin(9600);

     pinMode(led, OUTPUT);
     pinMode(ledUV, OUTPUT);

     pinMode(potPin, INPUT);

    }

    void loop(){

     potReading = analogRead(potPin);
     lightDim = (255./1023.)*potReading;

     analogWrite(led, lightDim);
    //  analogWrite(ledUV, lightDim);
    // Serial.println("pot: ");
    // Serial.println(potReading);
    // Serial.println(" ");
     Serial.println("dim: ");
     Serial.println(lightDim);
    // analogWrite(led, 255);
    // analogWrite(ledUV, 255);

    }

title: Analog output doesn't work for just 2 LEDs [Arduino Mega]

Answers: 2

body:
Analog pins an only *read* analog values, not *write* them.

`analogWrite()` is a deceptive name. It should really be `PWMWrite()` since all it does is PWM. And that, of course, needs PWM pins.

body:
Reference: [`analogWrite()`][1]

The pins 2 - 13 and 44 - 46 are the PWM pins for `analogWrite()`.

That means you have 15 PWM pins. Did you use them all?

You could add a module with more PWM outputs. Search for: Arduino 16 channel PWM

The Arduino Mega does not have analog outputs, only digital PWM outputs.

  [1]: https://www.arduino.cc/en/Reference/analogWrite


body:
So I have four Electronic Speed Controllers (ESC's), each connected to a motor. I am building a drone with an Arduino UNO board as my flight controller. For convenience, I have soldered the signal wires on each of the four ESC's onto the bottom of the Arduino where the Arduino's pin headers are soldered on. The serial ground pins on the ESC's are soldered to the ground pins on the Arduino.

The ESC's I am using can be found [here.][1]

In order to change settings on my ESC's, I am trying to use this [Turnigy USB linker][2] to connected to the BLHeli software on my computer.
The linker has a signal and a ground wire for Serial Communication, as well as a positive wire (I think this is just to fit the connector on ESC's with a BEC, but mine are OPTO, and have none). To connect the USB Linker to an ESC, I should be able to plug it into appropriate female pin headers on the Arduino using some breadboard-type jumper cables.

At least that's what I thought...

Whenever I try to connect to an ESC with the BLHeli software, I get a message:
*Please Connect ESC and power up or cycle power.*

Earlier, I was able to make the connection and change the settings on my ESC's when they weren't connected to the Arduino board, but now that they are soldered and hot-glued on there, they won't work. So the question is: **What is the Arduino doing to the Serial connection, and how can I fix it without desoldering my ESC's whenever I need to change some settings?**

Now before you ask:

 - Yes, the ESC is powered up and connected to a motor. It gives me a happy beeping sound.
 - Yes, I definitely have the signal and ground wires connected correctly. I have been trying to figure this out for days, and have even tried switching them.
 - The Arduino is turned off when I try to connect an ESC to the USB Linker.
 - Only one ESC is powered on at a time.

Maybe the Arduino has some kind of protection circuit for the IC that is messing up the signal, or maybe the ESC's have something similar that's messing it up too, because some of the ground wires are connected together. I'm going to have a very difficult time figuring this out myself, so hopefully someone out there has an idea of what's going on.

Thanks for any help you have to offer.

-- Ember

  [1]: https://hobbyking.com/en_us/multistar-mini-blheli-multi-30a-opto.html
  [2]: https://hobbyking.com/en_us/turnigy-multistar-usb-blheli-programmer-for-v2-multistar-esc.html

title: Flash an ESC Through Serial USB without Arduino Interrupting the Signal

Answers: 2

body:
I can offer general advice without reference to specific implementations.

By driving the Arduino pins when it is powered off you are potentially exceeding it's maximum rated specifications for voltage on any ping, and possibly for current into a pin, and you risk damaging it.
When the Arduino is powered down its Vdd pin and power supply rail will be at about 0.0 volts and will be loaded to ground by power supply capacitors and various other items connected to Vdd - including the OUTPUT of the Vdd voltage regulator in many cases.
Each Arduino pin is connected to the Vdd rail by a body / protection diode. To drive the pin high you must also raise Vdd to high-1 diode drop and must drive the Vdd rail load from your signal line via the body diode.
If your programmer has the ability to do this there is a reasonable chance that you may damage the body diode. For extra points, a very capable signal input MIGHT damage the Arduino's voltage regulator and possibly other on board devices - but I'd think that to be unlikely.

The technically best solution is to disconnect the Arduino's relevant pins when programming. As you obviously would rather not do that, then ...

**Probable solution:** If you power on the Arduino and run a program which ensures that the relevant pins are set to input mode then it should work as required. IF the Arduino default program sets the relevant pins to inputs then just powering it on should suffice, but odds are that the serial port pins are not both configured as inputs.
If the Arduino has a USB to serial port IC or other devices connected to the pins in question then you will need to also ensure that they do not load the pin excessively and that they will not be damaged by programming signals. eg if you were trying to drive the Arduinos serial RX_in pin which was connected to the TX_out pin of a USB-Serial IC then the programmer would be attempting to drive the USB-serial output pin and this must be dealt with in some way.

**Checklist:**

- Is there something else connected to this pin.

If so

- What state is it in during ESC programming

- Will it be damaged by programming

- Will it affect programming.

- What action is thus needed.

body:
As far as I can tell, it is not possible to program a Turnigy Multistar ESC while it is connected in parallel to any pins on an Arduino. Whether the Arduino is off, or the pins are set to input, output, HIGH, or LOW, the signal is disrupted somehow.

**Solution:** Don't do what I did and solder the ESC's to your Arduino unless you want to de-solder them to change settings. Sticking some wires into the Arduino's pin headers will not make a strong connection, so I would recommend *soldering some sort of strong JST connectors to the pins on the Arduino.*

Hope this all helped, and good luck,

-- Ember


body: I'm about to buy two ESP8266 modules. I want them to use as an auto deauth device. The first module will monitor my WiFi router's packet transmission. If a certain device receive loads of packets from my router (which hogs my network) the second module will deauth that device or flood "forged" packets. There will be a threshold so a simple web browsing will not trigger the deauth process from the second module. Btw. My router doesn't support traffic shaping & QoS. Only a different kind of QoS (DHCP & IPP/TOS) which is useless because my ISP doesn't support it.

title: ESP8266 as WiFi monitor

Answers: 1

body:
You're going to face significant challenges with this.

The ESP Arduino API doesn't let you run in promiscuous mode (which you'd need in order to see other people's traffic), and the APIs are all set up for you to create nice well-behaved traffic, not spoofed packets.

I strongly suspect the hardware can do it, but you're going to be making significant changes to the IP stack.  The code is all open, so you're free to dig in and see what you can do (I've done a similar thing myself, as I needed some lower-level information than was made available in the API).

So feasibility is determine by your skill level (C, C++ and IP stack and protocols) and available time.

Something like a Raspberry Pi Zero and a suitable USB wifi dongle would probably be a quicker path at similar cost, as there are Linux tools to do a lot of this stuff.


body:
I am currently developing some basic led board using Arduino Uno R3. Basically,
the LEDs are connected in parallel so that 5V DC supply can light up about 3 LED. Each LED has its resistor and its connected to 3 Arduino digital pin where I ground it by using digitalWrite(pins, LOW). Each ground on the schematic is the Arduino digitalWrite(LOW). My question is where should the negative of the 5V should be connected?

Also, if I wanted to measure the voltage of the LED, where should I connect my probe so that analogRead() can read the voltage?

Thanks and sorry if my explanation is not correct since it's my first time using this site.

<!-- 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/dYrCg.png)

<!-- End schematic -->

title: 5V power supply negative terminal connection

Answers: 1

body:
The Arduino common, normally referred to as ground, although it is usually only accidentally grounded through external connection. In general **ALL** connections should have a common "ground".

You can not measure voltage across the LED given the circuit you have listed. (You could read the voltage at both ends and subtract.)

If you swap the LED and resistor you can get an approximation of the LED voltage (actually LED + Arduino pin) from the junction of LED and resistor.


body:
    #include <Stepper.h>
    #define STEPS_PER_MOTOR_REVOLUTION 32
    #define STEPS_PER_OUTPUT_REVOLUTION 32 * 480  //2048
    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);
    int Steps2Take;
    int dirpin=8;
    int steppin=9;
    int buttonApin=2;
    int buttonBpin=3;

    void setup() {
      pinMode(dirpin,OUTPUT);
      pinMode(steppin,OUTPUT);
      pinMode(buttonApin,INPUT);
      pinMode(buttonBpin,INPUT);
    }

    void loop() {
      int valA=digitalRead(buttonApin);
      int valB=digitalRead(buttonBpin);
      if(valA==HIGH) {
        digitalWrite(steppin,HIGH);
        digitalWrite(dirpin,LOW);
        small_stepper.step(40000);
        delay(1000);
      }
      if(valB==HIGH) {
        digitalWrite(steppin,HIGH);
        digitalWrite(dirpin,LOW);
        small_stepper.step(-40000);
        delay(1000);
      }
      if((valA==LOW)&&(valB==LOW)) {
        digitalWrite(steppin,HIGH);
        digitalWrite(dirpin,LOW);
        small_stepper.step(0);
      }
    }

Here I have written this code to rotate stepper motor. When the input on digital pin 2 becomes high, then the motor should rotate clockwise. When the digital pin 3 becomes high, it should rotate in a different direction. When the input on both pins is low, the motor should not move.

But with this code the motor is moving continuously even if you apply high input to digital pins.

Please suggest how to fix this problem. For input signal I am taking signal from relays: if relay is in on condition, it should give a high signal and vice versa.

title: Stepper motor is not working according to code

Answers: 3

body:
Disclaimer: I've never used this library.  The following is my thoughts from looking at the code.

[This example][1] seems to do basically what you want.  It doesn't seem to be necessary to do any `digitalWrite`s yourself - you just need to call call `.step(x)`.

There also doesn't seem to be any need to anything in the "do nothing" case - you don't need to tell it not to step, as far as I can see.

I couldn't work out why you were stepping 40000 steps at a time.  I've changed it to 1.  You can change it back if I missed something.

Also note I've used `else if` so that if both inputs are high, the motor doesn't go forward AND backwards.  Maybe that's the behaviour you want, and if not, again, you can change it.

    #include <Stepper.h>
    #define STEPS_PER_MOTOR_REVOLUTION 32
    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);
    int buttonApin=2;
    int buttonBpin=3;

    void setup()
    {
        pinMode(buttonApin,INPUT);
        pinMode(buttonBpin,INPUT);
    }

    void loop()
    {
        int valA=digitalRead(buttonApin);
        int valB=digitalRead(buttonBpin);
        if(valA==HIGH)
        {
            small_stepper.step(1);
            delay(1000);
        }
        else if(valB==HIGH)
        {
            small_stepper.step(-1);
            delay(1000);
        }
    }

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

body:
Does the relay actually connect the pin to ground when it is off?  Or does it leave the input floating?  If it leaves it floating then you should use a pull-down resistor to make sure the pin actually sees ground and not stray interference.

If you can rewire the relays you can use an active low configuration and save the resistor since the Arduino has built-in pullup resistors.

body:
  I think its better to use count function .. you need to test yor stepepr motor first ..here the code to test .. i hope its will help :)

    #define IN1  50
    #define IN2  51
    #define IN3  52
    #define IN4  53
    int Steps = 4096; //4096(full rotation 360 degree )
    int cstep = 0;

    void setup()
    {
      Serial.begin(9600);
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(IN3, OUTPUT);
      pinMode(IN4, OUTPUT);

     Serial.println("Enter character for control option:");
     Serial.println("h : anticlockwise");
     Serial.println("i : clockwise");
     }

     void loop()
    {

       if (Serial.available()>0)
       switch(Serial.read())
     {
       case 'h':
       Serial.println("anticlockwise");
       for(int x=0;x<Steps;x++)
    {

         step1();
         delayMicroseconds(1000);
    }
      break;

       case 'i':
       Serial.println("clockwise");
         for(int x=0;x<Steps;x++)
       {

           step2();
           delayMicroseconds(900);
       }

       //delay(1000);
        break;

      }

      }

       void step1()
      {
        //stepp
        switch(cstep)
     {
       case 0:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
     break;
     case 1:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, HIGH);
     break;
     case 2:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
     break;
     case 3:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
     break;
     case 4:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 5:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 6:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 7:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
     break;
     default:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     }

     cstep=cstep+1;
     if(cstep==8)
      {cstep=0;}
     }

      void step2()
    {
    //stepp
    switch(cstep)
    {
     case 0:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
     break;
     case 1:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
     break;
     case 2:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 3:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 4:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;
     case 5:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
     break;
     case 6:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
     break;
     case 7:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, HIGH);
     break;
     default:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
     break;

     }

      cstep=cstep+1;
     if(cstep==8)
     {
      cstep=0;
      //Serial.println("habis");

      }
     }


body:
for logging of environmental data, I am using a MicroSD card adapter (no brand name, eBay, China) and a 4GB Intenso SD card. I want to read data and write it to the SD card once every 10 minutes. Power consumption needs to be as low as possible.

Between the measurement points, I switch off the power supply to my sensor and SD card adapter using an NPN transistor (BC547B, 2N3904, 2SC945) and put my controller to sleep using [jeelib][1]. Everything works fine!

*But* I realized, that even during sleep, still 1mA of current is drawn. This disappears, when I remove the SCK connection between the Arduino and the SD controller. Doesn't sound like a lot, but for my purposes, it's a major concern (when SCK is removed, I'm around 6µA during sleep).

**Is it possible to switch the SCK signal off during sleep to save that last bit of power?**

In case it matters, I am using the SdFat library to write to SD. Initialization is done before each write. I figured, this would be necessary because of the poweroff of 10 minutes. Here's the function:

    #include <SdFat.h>
    const int chipSelect = 10;
    String outfilename = "Bienen.log";

[...]

    int writeToFile(String outfilename, String writestring) {

      SdFat SD;
      if (!SD.begin(chipSelect)) {
    #ifdef DEBUG
        Serial.println("Card failed, or not present");
        error_signal();
    #endif
      } else {
    #ifdef DEBUG
        Serial.println("card initialized.");
    #endif
      }

    File outfile = SD.open(outfilename.c_str(), FILE_WRITE);
    #ifdef DEBUG
      Serial.println(outfile);
    #endif
      if (outfile) {
        outfile.println(writestring);
        outfile.close();
    #ifdef DEBUG
        Serial.println("Wrote successfully.");
        ok_signal();
    #endif
        return 0;
      } else {
    #ifdef DEBUG
        Serial.println("Writing failed.");
        error_signal();
    #endif
        return 1;
      }
    }

ok_signal() and error_signal() are merely functions to flash an LED.

**EDIT:**
Thanks for your reply! I tried the code snippets

    SPCR &= ~_BV(SPE)
and

    SPCR |= _BV(SPE)

at the appropriate places, although I did not understand them. There was, however, no change in power consumption - SCK still seems to run.

I could not adapt the physical changes detailed in the suggested wordpress article, as the adapter there is quite different from [my microSD adapter][2], and I know too little about hardware to adapt the author's suggestions. It looks and sounds quite promising though ...

Thanks for your time! Any help is greatly appreciated!

  [1]: http://jeelabs.org/2011/12/13/developing-a-low-power-sketch/ "jeelib"
  [2]: http://robojax.com/products/images/ELE_SDCARDUI_176.jpg

title: Disable SCK temporarily to save power

Answers: 1

body:
Re-visiting the issue, I have found a simple answer:

I set the SPI pins as outputs and inputs respectively:

    const int chipSelect = 10;
    const int MOSIPin = 11;
    const int MISOPin = 12;
    const int SCKPin = 13;

and

      pinMode(chipSelect, OUTPUT);
      pinMode(MOSIPin, OUTPUT);
      pinMode(MISOPin, INPUT);
      pinMode(SCKPin, OUTPUT);

Now, before I power down my machine, I do the following:

      SPI.end();
      digitalWrite(SCKPin, HIGH);
      digitalWrite(chipSelect, HIGH);
      digitalWrite(MOSIPin, HIGH);

Now, the drawn current drops from 1mA to roughly 0,02mA, which is satisfactoy for me!

Thanks for reading!


body:
I have an Arduino Uno and an ESP8266, connected over serial through ESP8266 pin GPIO_2 (which is set as RX over espsoftwareserial) and 11 on Uno (which is set as TX over SoftwareSerial). I am trying to send data in this format:

 **<0.000000:0.000000:0.000000:0.000000:0.000000:0.000000:24.50:24.50:1.49>**

It is < char then number with six floats, separator :, and again... 9 times

I am using:

 - [espsoftwareserial library][1]
 - [Original SoftwareSerial library][2]

Arduino UNO code:

    SoftwareSerial ARD_ESP(10, 11); // RX, TX

    totalVolume[0] = 0.000000;
    totalVolume[1] = 0.000000;
    totalVolume[2] = 0.000000;
    flowRate[0] = 0.000000;
    flowRate[1] = 0.000000;
    flowRate[2] = 0.000000;
    float temperature_cold_value = 24.50;
    float temperature_hot_value = 24.50;
    float propane_gas_value = 1.49;

    void setup()
    {
       ARD_ESP.begin(57600);
       Serial.begin(9600);
    }
    void loop()
    {
    if (millis() - previousMillis_esp_post > 5000 && run_state_metering == 1)
         {
              ARD_ESP.print("<");
              ARD_ESP.print(totalVolume[0],6);
              ARD_ESP.print(":");
              ARD_ESP.print(totalVolume[1],6);
              ARD_ESP.print(":");
              ARD_ESP.print(totalVolume[2],6);
              ARD_ESP.print(":");
              ARD_ESP.print(flowRate[0],6);
              ARD_ESP.print(":");
              ARD_ESP.print(flowRate[1],6);
              ARD_ESP.print(":");
              ARD_ESP.print(flowRate[2],6);
              ARD_ESP.print(":");
              ARD_ESP.print(temperature_cold_value,2);
              ARD_ESP.print(":");
              ARD_ESP.print(temperature_hot_value,2);
              ARD_ESP.print(":");
              ARD_ESP.print(propane_gas_value,2);
              ARD_ESP.print(">");

              Serial.print("<");
              Serial.print(totalVolume[0],6);
              Serial.print(":");
              Serial.print(totalVolume[1],6);
              Serial.print(":");
              Serial.print(totalVolume[2],6);
              Serial.print(":");
              Serial.print(flowRate[0],6);
              Serial.print(":");
              Serial.print(flowRate[1],6);
              Serial.print(":");
              Serial.print(flowRate[2],6);
              Serial.print(":");
              Serial.print(temperature_cold_value,2);
              Serial.print(":");
              Serial.print(temperature_hot_value,2);
              Serial.print(":");
              Serial.print(propane_gas_value,2);
              Serial.print(">");
              Serial.print("");

              previousMillis_esp_post = millis();
         }

   ESP8266 code: (it's programmed with Arduino IDE)

    #include <ESP8266WiFi.h>
    #include <SoftwareSerial.h>
    #include <string.h>

    SoftwareSerial ARD_ESP(2, SW_SERIAL_UNUSED_PIN);

    const byte numChars = 32;
    char receivedChars[numChars];
    boolean newData = false;

    String sensor_1_total_volume;
    String sensor_2_total_volume;
    String sensor_1_flow_rate;
    String sensor_2_flow_rate;
    String temperature_cold_value;
    String temperature_hot_value;
    String propane_butane_gas_value;
    String mereni_token = "xxxxx";

    void setup() {

      Serial.begin(115200);
      ARD_ESP.begin(57600);
      delay(10);
    }

    void loop() {

      recvWithStartEndMarkers();
      showNewData();

      sensor_1_total_volume = getValue(receivedChars, ':', 0);
      sensor_2_total_volume = getValue(receivedChars, ':', 1);
      sensor_1_flow_rate = getValue(receivedChars, ':', 2);
      sensor_2_flow_rate = getValue(receivedChars, ':', 3);
      temperature_cold_value = getValue(receivedChars, ':', 4);
      temperature_hot_value = getValue(receivedChars, ':', 5);
      propane_butane_gas_value = getValue(receivedChars, ':', 6);

    }

    void recvWithStartEndMarkers() {
        static boolean recvInProgress = false;
        static byte ndx = 0;
        char startMarker = '<';
        char endMarker = '>';
        char rc;

        while (ARD_ESP.available() > 0 && newData == false) {
            rc = ARD_ESP.read();

            if (recvInProgress == true) {
                if (rc != endMarker) {
                    receivedChars[ndx] = rc;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars - 1;
                    }
                }
                else {
                    receivedChars[ndx] = '\0'; // terminate the string
                    recvInProgress = false;
                    ndx = 0;
                    newData = true;
                }
            }

            else if (rc == startMarker) {
                recvInProgress = true;
            }
        }
    }

    void showNewData() {
        if (newData == true) {
            Serial.print("This arrived: (unparsed)");
            Serial.println(receivedChars);
            Serial.println("DATA sensors: (parsed)");
            Serial.println(sensor_1_total_volume);
            Serial.println(sensor_2_total_volume);
            Serial.println(sensor_1_flow_rate);
            Serial.println(sensor_2_flow_rate);
            Serial.println(temperature_cold_value);
            Serial.println(temperature_hot_value);
            Serial.println(propane_butane_gas_value);
            Serial.println(mereni_token);
            newData = false;
        }
    }

    String getValue(String data, char separator, int index)
    {
        int found = 0;
        int strIndex[] = { 0, -1 };
        int maxIndex = data.length() - 1;

        for (int i = 0; i <= maxIndex && found <= index; i++) {
            if (data.charAt(i) == separator || i == maxIndex) {
                found++;
                strIndex[0] = strIndex[1] + 1;
                strIndex[1] = (i == maxIndex) ? i+1 : i;
            }
        }
        return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
    }

It works fine, but ESP receive only three values, another 6 does not.
I have tried to change bitrate to 57600, but thats not help.
I think that there is a problem with speed or waiting for full data.

Can you help me ? Many Thanks.

Here is the output from ESP:

    This arrived: (unparsed)0.000000:0.000000:0.000000:0.00
    DATA sensors: (parsed)
    0.000000
    0.000000
    0.000000
    0.004

    xxxx

  [1]: https://github.com/plerup/espsoftwareserial
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerialConstructor

title: Arduino to ESP8266 (SoftwareSerial) communication, does not receive full data

Answers: 1

body:
You are sending number+'.'+6 float +separator = 9 char at least.

You are sending 9x this, 81 char at least. Plus '<>' and maybe some more chars...

And you store it in 32 char long buffer. Somehow it does not fit all inside, who knows why?  :(

As you can see, you got like 32 chars only of the full transmission. Try to set `numChars` to something like 100 and try again. See, if it is better.

(Also I would use pattern

          ARD_ESP.print("<");
          Serial.print("<");
          ARD_ESP.print(totalVolume[0],6);
          Serial.print(totalVolume[0],6);
          ARD_ESP.print(":");
          Serial.print(":");

to leave the ESP more time to process stored data, but it is probabelly not problem now)


body: What would be minimal schematic for ATMega328P in order to have communication over ethernet? So I'm not asking about attaching existing shields to existing Arduino board, but just for bare minimum of ATMega328P and ethernet on one board, so basically like minimal version of Arduino Yun.

title: Minimal ATmega328p Ethernet Configuration

Answers: 0


body:
I have a [LED 24 button remote][1] with a few broken buttons and I want to simulate all the buttons with an esp8266 using an [IR remote library][2].

  [1]: http://is.alicdn.com/img/pb/557/412/430/430412557_545.jpg
  [2]: https://github.com/markszabo/IRremoteESP8266

I would like to know if someone can help me translate the LIRC config file with all the functional buttons to an ESP lib command.
I have 2 lircd.conf files of the same remote (everything worked on a raspberry) and I'm using the same circuit on an ESP8266 (wemos d1 mini pin D5 and D6).

lircd.conf 1

    begin remote

      name  lumina
      bits           16
      flags SPACE_ENC|CONST_LENGTH
      eps            30
      aeps          100

      header       8860  4530
      one           508  1724
      zero          508   607
      ptrail        508
      repeat       8863  2301
      pre_data_bits   16
      pre_data       0xFF
      gap          107224
      toggle_bit_mask 0x0

          begin codes
              PWR_ON                   0xB04F
              PWR_OFF                  0xF807
              LI_LOW                   0xB847
              LI_HI                    0x906F
              R                        0x9867
              G                        0xD827
              B                        0x8877
              W                        0xA857
              R1                       0xE817
              R2                       0x02FD
              B4                       0xF00F
              G1                       0x48B7
              B1                       0x6897
              FLASH                    0xB24D
              STROBE                   0x00FF
              FADE                     0x58A7
              SMOOTH                   0x30CF
              G2                       0x32CD
              R3                       0x50AF
              R4                       0x38C7
              G3                       0x7887
              G4                       0x28D7
              B2                       0x20DF
              B3                       0x708F
          end codes

    end remote

lircd.conf 2

    begin remote

      name  lumina
      bits           16
      flags SPACE_ENC|CONST_LENGTH
      eps            30
      aeps          100

      header       8861  4525
      one           515  1718
      zero          515   600
      ptrail        516
      repeat       8865  2291
      pre_data_bits   16
      pre_data       0xFF
      gap          107235
      toggle_bit_mask 0x0

          begin codes
              B1                       0x6897
              PWR_ON                   0xB04F
              PWR_OFF                  0xF807
              LI_LOW                   0xB847
              LI_HI                    0x906F
              R                        0x9867
              G                        0xD827
              B                        0x8877
              W                        0xA857
              R1                       0x9867
          end codes

    end remote

Output from a few buttons read from the esp using the IRremoteESP8266 library .

    F0C41643
    4039382595
    Unknown encoding: F0C41643 (32 bits)
    Raw (68): 8850 -4550 550 -650 550 -650 550 -650 500 -650 550 -600 550 -650 550 -650 550 -600 550 -1750 550 -1750 500 -1750 500 -1750 550 -1750 500 -1750 550 -1750 550 -1750 500 -1750 500 -650 500 -1750 550 -1750 550 -650 550 -650 500 -650 550 -650 550 -650 550 -1750 550 -650 500 -600 550 -1750 500 -1750 550 -1750 550 -1750 500
    ------------------

    A3C8EDDB
    2747854299
    Unknown encoding: A3C8EDDB (32 bits)
    Raw (68): 8900 -4550 550 -650 550 -600 550 -650 550 -650 550 -600 550 -650 550 -600 550 -600 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -600 550 -600 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -1750 550 -1750 550
    ------------------

    86B0E697
    2259740311
    Unknown encoding: 86B0E697 (32 bits)
    Raw (68): 8900 -4550 550 -600 550 -650 550 -650 550 -600 550 -600 550 -650 550 -600 550 -600 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -600 550 -1750 550 -1750 550 -600 550 -600 550 -650 550 -650 550 -600 550 -1750 550 -600 550 -650 550 -1750 550 -1750 550 -1750 550
    ------------------

    A3C8EDDB
    2747854299
    Unknown encoding: A3C8EDDB (32 bits)
    Raw (68): 8900 -4550 550 -650 550 -600 550 -650 550 -600 550 -650 500 -650 550 -600 550 -650 550 -1750 550 -1750 500 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -600 550 -650 500 -650 550 -1750 550 -650 500 -1750 550 -650 550 -1750 550 -1750 550 -1750 500

title: Convert LIRC config file to Arduino IR remote command

Answers: 1

body: Looks like is just plain NEC IR protocol. So use something like `irsend.sendNEC(0xB04F, 16)` for POWER_ON.


body:
I am trying to make something so when I press the button it sets the position of the servo to 50 and then when I press it again, it sets it to 150. The button is momentary not a toggle switch. This is what I have come up with so far. I would also like to account for button bounce. Hope someone can help. Thanks in advance!

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo

    // variables will change:
    int pos = 0; // variable to store the servo position
    int buttonState = 0; // variable for reading the pushbutton status
    int button_mode = 1; // Variable for the button's current state.
    // button_mode = 1 when the button is up, and 0 when the button is pressed.
    // This variable is 'static' and persists because it is declared outside a function.

    void setup() {
      myservo.attach(8); // attaches the servo on pin 9 to the servo object
      Serial.begin(9600); // Initialize the Serial port at 9600 baud.
      pinMode(9,INPUT); // Set Digital pin 9 to an input so it can monitor the button.
    }

    void loop() {
      buttonState = digitalRead(9);
      if ((digitalRead(9) == LOW) && (button_mode == 1)) {
        // Check Digital pin 9 to see if it's pressed.
        pos = 150; //set servo position variable to 150
        myservo.write(pos); //set servo postion to 'pos'
        delay(1000); // wait 1 second
        button_mode = 0; // Button was up before, but is pressed now. Set the button to pressed
        Serial.println("Button has been pressed."); // and report that to the serial monitor.
      } else if ((digitalRead(9) == HIGH) && (button_mode == 0)) {
        pos = 50;
        myservo.write(pos);
        delay(1000);
        button_mode = 1; // Button was down before, but is released now. Set the button to
        Serial.println("Button has been released"); // released and report that to the serial monitor.
      }
      delay(100); //small delay to account for button bounce
    }

title: How can I make this button toggle the position of a servo?

Answers: 2

body:
Do something like this:

    int angles[2] = {0,180}
    bool state = 0;

then:

    if(button == PRESSED)
      state = !state;

finnally, to control the servo:

    Servo.write(angles[state]);

body:
The code is not well structured. Here is what I would do:

    if (button_pressed()) { //test to see if button is pressed
      button_state +=1; //increment button
      if (button_stat & 0x01) {//if lsb set
        myservo.write(SERVO_POS1); //set servo position 1
      } else {
        myservo.write(SERVO_POS2); //set servo position 2
      }
    }

You can debounce if you wish in button_pressed().


body:
I wrote the following code. The idea is to execute some AT command on my ESP-01 module. The problem is that first command is execute without problem, the second sometimes but the reply on AT+GMR is the following:
    AT

    OK
    AT+GMR

    AT version:1.1/0.0(May 11 3016 18:09:57)
    SDK version:1.5.ar.0
    AR)�WS�TZ�j
    C�j�L�AZCA�O�C�

    FINE

The problem is that, after some thing that I don't understand, the formatting (maybe the baud change?) gone wrong. Then the reply of the following commands became unreadable. Any idea why it happens?

    #include <SoftwareSerial.h>
    #define DEBUG true
    SoftwareSerial wifi(2,3);

    void setup() {
       Serial.begin(115200);
       wifi.begin(115200);
       sendCommand("AT\r\n", 2000);
       sendCommand("AT+GMR\r\n",2000);
       sendCommand("AT+CWMODE=2\r\n", 2000);
       sendCommand("AT\r\n", 2000);
       Serial.print("\n\nFINE");
    }

    void loop() {}

    String sendCommand(String cmd, int timeout){
       wifi.print(cmd);
       return readSerial(timeout);
     }

     String readSerial(int timeout){
       long int time = millis();
       String res = "";
       while( (time+timeout) > millis() ){
            while(wifi.available()){
              char c = wifi.read();
               res += c;
            }
        }
        if(DEBUG)
           Serial.print(res);

        return res;
     }

title: Serial.print start prints unreadable character without any reason

Answers: 2

body: The problem was about high baud for SoftwareSerial. Changing it to 9600 the problem disappears.

body:
[![ esp connections][1]][1]

Take a look at the connections check the all the connections properly i also had the same problem

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


body:
So I have been experimenting with keyboard inputs and I think I may have accidentally put a loop in my code that never actually ends the keyboard input thus not allowing me to upload any sketches to fix the problem.

Here is the error code I got when I tried to upload a blank into the qduino:

    Arduino: 1.8.1 (Windows Store 1.8.1.0) (Windows 10), Board: "Qduino Mini"

    Build options changed, rebuilding all
    Sketch uses 4136 bytes (14%) of program storage space. Maximum is 28672 bytes.
    Global variables use 148 bytes (5%) of dynamic memory, leaving 2412 bytes for local variables. Maximum is 2560 bytes.
    An error occurred while uploading the sketch
    processing.app.SerialException: Error opening serial port 'COM11'.
     at processing.app.Serial.<init>(Serial.java:125)
     at processing.app.Serial.<init>(Serial.java:66)
     at processing.app.SerialMonitor$3.<init>(SerialMonitor.java:93)
     at processing.app.SerialMonitor.open(SerialMonitor.java:93)
     at processing.app.AbstractMonitor.resume(AbstractMonitor.java:110)
     at processing.app.Editor.resumeOrCloseSerialMonitor(Editor.java:2240)
     at processing.app.Editor.access$2400(Editor.java:77)
     at processing.app.Editor$DefaultExportAppHandler.run(Editor.java:2315)
     at java.lang.Thread.run(Thread.java:745)
    Caused by: jssc.SerialPortException: Port name - COM11; Method name - openPort(); Exception type - Port busy.
     at jssc.SerialPort.openPort(SerialPort.java:164)
     at processing.app.Serial.<init>(Serial.java:114)
     ... 8 more
    Error opening serial port 'COM11'.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

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

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

title: Qduino Mini bricked?

Answers: 1

body: Ok strange, just after posting this the qduino decided to flash a different light on me so I try to upload again and it works... So apperantly just by keeping the qduino connected for some time it will start to work again...


body:
Using a knockoff Arduino Nano (pinout seems to be the same), I would like to record data to an external SD card. I have everything hooked up (correctly I think) but I continue to fail to initialize the card using `SD.begin()`.

Here's a snippet of code that I'm running to do this:

    //Wire and MS5803_I2C libraries for communicating with the pressure sensor.

    #include <Wire.h>
    #include <SparkFun_MS5803_I2C.h>
    // For the SD card reader.
    #include <SPI.h>
    #include <SD.h>

    const int chipSelect = 4;

    void setup(void) {
      Serial.begin(9600); // Set baud rate.
      pinMode(10, OUTPUT); // Set data output pin for the SD card reader.
      digitalWrite(10, HIGH);
     // see if the card is present and can be initialized:
     if (!SD.begin(10)) {
       Serial.println("Card failed, or not present");
       // don't do anything more:
       return;
     }
     Serial.println("card initialized.");
      delay(500);  // Wait half a second before continuing.
    }

    void loop(void) {
      Serial.println("Hello Library!");
      delay(100000);
    }

Here's the Nano pinout:

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

And a picture of the circuit.

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/qLIni.png
  [2]: https://i.stack.imgur.com/Msdv5.jpg

title: Failing to write to SD card using SD.h

Answers: 2

body:
The Sparkfun pressure sensor has a 3.3V chip and a SD memory card is also 3.3V. Your Arduino Nano is probably a 5V board. How did you connect those to the board ?

When your Nano board is 5V, you need a SD module with a level shifter for the signals.

To make it work, test either the SD or the sensor and try to make it work. When testing the SD, don't connect the sensor and don't even include the sensor library.

body:
Is it my eyes or there's nothing connected to D4...?

    const int chipSelect = 4;

Your chipSelect/CS pin seems connected to D10.


body:
Scenario:  The Uno is being powered by USB for programming, and the HC-12 wireless communications module is wired correctly.  But it will not work.

In reading through the web literature, it is mentioned that to use the HC-12 in the high-power (100 mW) mode requires a power supply in excess of what the laptop's USB port will provide.

I am finding nothing on Stackexchange that addresses this issue.

So the question is, how do I get the power to run the Uno with the HC-12?  I need to be able to periodically update the programming and test it while that auxiliary power is applied, and need to know it is safe to do so.

title: How can i provide enough power on an UNO to use the HC-12 wireless module?

Answers: 1

body:
There two options I have found that work well.

First is a simple wall-wart that provides 12 Volts to a barrel connector, like for a CCTV camera.

Or, if I want to run the Uno from a separate higher-amperage USB charging port I have found that there are "USB A Male to CCTV male" cables that work.

Doing the latter means the Uno is running at 5V instead of utilizing the on-board regulator to drop a higher-voltage input, which only matters if your circuit expects to find more than 5 Volts on the Vin pin (although that is not supposed to be an output pin, of course).

Through thorough experimentation I've proven that both methods work.

The best part is that the Uno can easily tolerate having both CCTV-style power and also being plugged into the laptop for programming and testing (like using the serial monitor).

Lesson learned:  The HC-12 simply will not work without auxiliary power, and it is safe to provide such power while also plugging the serial port into a laptop.


body:
I'm trying to use the arduino DUE board as a  AVR Programmer. My target device is atmega328p. After uploading the ArduinoISP into the DUE Board. I've tried to let a pin toggle using the following code:

    #define F_CPU 10000000
    #include <avr/io.h>
    #include <util/delay.h>

    int main (){
     DDRD |= (1<< PD7);
     for(;;){
      PORTD ^= (1<< PD7);
      _delay_ms(1000);
     }
     return 0;
    }

I want to use the internal oscillator and based [this example ][1] I've adjust the makefile:

    DEVICE     = atmega328p
    CLOCK      = 8000000
    PROGRAMMER = -c arduino -P COM10 -b 19200
    OBJECTS    = main.o
    FUSES      = -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

the problem that I have is that when run :

    make flash
I get the following :

[![enter image description here][2]][2]

and yes the port COM10 is definitely correct.

does anyone have a suggestion how to solve this ?

thanks in advance !

  [1]: https://gist.github.com/holachek/3304890
  [2]: https://i.stack.imgur.com/bFDr5.png

title: Trouble while using Arduino DUE as programmer

Answers: 1

body:
There error you have is from *avrdude* failing to get a communication link established to the 'programmer' (which manipulates the target.)

Here is a link that may help with the connection

[Stk500 error][1]

Here is another relative link that may help

[Arduino ISP on DUE][2]

Best of luck.

  [1]: https://arduino.stackexchange.com/questions/17/avrdude-stk500-getsync-not-in-sync-resp-0x00-aka-some-dude-named-avr-won
  [2]: https://petervanhoyweghen.wordpress.com/2013/06/11/arduinoisp-on-the-due/


body:
I am using a Pro Mini to read analog values and to send them via serial.

Goal of the sketch is to stream these values to Serial as fast as possible, to obtain a steady stream of at least 1000 readings per second. For this reason I reduced the ADC prescaler and I increased serial speed.

I tested sending binary values with Serial.write and it works (it's the fastest), I tested Serial.print (it's the slowest), and I tested an [optimised conversion integer-to-string][1] (found on StackOverflow) in association with Serial.write.

This optimised conversion is faster than Serial.print (it would allow me to send the full strings within the given timeframe), but it gives me wrong values. I cannot understand why it happens, the code looks fine to my not-so-expert eye.

A correct stream as sent by Serial.print would be (spaces added for clarity):

    3075 \t 2800 \t 4132 \n

"Wrong values" means that the last value gets repeated for all the three columns:

    4132 \t 4132 \t 4132 \n

What is the issue in my code regarding the int2str conversion?

Since I cannot get one measurement taken and sent every 500 us, I would like to use the optimised routine to get plaintext readings at 1000 us intervals.

The source code follows. I cut out the function slimADC because it was tested as working, while I left all the 3 methods for sending data via serial: binary, optimised, Serial.print.

    #include <digitalWriteFast.h>

    volatile unsigned long previousMicros, currentMicros;

    #define SAMPLES 8
    volatile unsigned int valuesX;
    volatile unsigned int valuesY;
    volatile unsigned int valuesZ;

    char* x;
    char* y;
    char* z;

    void setup() {
    // set pins, ADC prescaler and initialise ADC
      pinModeFast(A0, INPUT);
      pinModeFast(A1, INPUT);
      pinModeFast(A2, INPUT);
      ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear bits
      ADCSRA |= bit (ADPS0) | bit (ADPS2);  // 32: 32 us per ADC
      slimADC(0);
      slimADC(0);

    // initialise Serial
      Serial.begin(250000);
      Serial.write("\n");
      Serial.write("\n");
      previousMicros = 0;
    }

    void loop() {
      currentMicros = micros();
      if ((currentMicros - previousMicros) < 1000) { return; }
      previousMicros = currentMicros;

    // ADC readings, repeated SAMPLES times
      valuesX = 0;
      valuesY = 0;
      valuesZ = 0;
      for (uint8_t i = 1; i < SAMPLES; i++) {  // 8*3*32=768 us
        valuesX += slimADC(0);
        valuesY += slimADC(1);
        valuesZ += slimADC(2);
      }

    // SERIAL TRANSMISSION

    // fastest
    //  Serial.write(valuesX / 256);
    //  Serial.write(valuesX % 256);
    //  Serial.write("\t");
    //  Serial.write(valuesY / 256);
    //  Serial.write(valuesY % 256);
    //  Serial.write("\t");
    //  Serial.write(valuesZ / 256);
    //  Serial.write(valuesZ % 256);
    //  Serial.write("\n");

    // good
      x = int2str( valuesX );
      y = int2str( valuesY );
      z = int2str( valuesZ );
      Serial.write(x);
      Serial.write("\t");
      Serial.write(y);
      Serial.write("\t");
      Serial.write(z);
      Serial.write("\n");

    // slowest
    //  Serial.print(valuesX);
    //  Serial.print("\t");
    //  Serial.print(valuesY);
    //  Serial.print("\t");
    //  Serial.print(valuesZ);
    //  Serial.print("\n");
    }

    static int slimADC(uint8_t pin) { ... }

    char _int2str[7];
    char* int2str( register int i ) {
      register unsigned char L = 1;
      register char c;
      register boolean m = false;
      register char b;  // lower-byte of i
      // negative
      if ( i < 0 ) {
        _int2str[ 0 ] = '-';
        i = -i;
      }
      else L = 0;
      // ten-thousands
      if( i > 9999 ) {
        c = i < 20000 ? 1
          : i < 30000 ? 2
          : 3;
        _int2str[ L++ ] = c + 48;
        i -= c * 10000;
        m = true;
      }
      // thousands
      if( i > 999 ) {
        c = i < 5000
          ? ( i < 3000
              ? ( i < 2000 ? 1 : 2 )
              :   i < 4000 ? 3 : 4
            )
          : i < 8000
            ? ( i < 6000
                ? 5
                : i < 7000 ? 6 : 7
              )
            : i < 9000 ? 8 : 9;
        _int2str[ L++ ] = c + 48;
        i -= c * 1000;
        m = true;
      }
      else if( m ) _int2str[ L++ ] = '0';
      // hundreds
      if( i > 99 ) {
        c = i < 500
          ? ( i < 300
              ? ( i < 200 ? 1 : 2 )
              :   i < 400 ? 3 : 4
            )
          : i < 800
            ? ( i < 600
                ? 5
                : i < 700 ? 6 : 7
              )
            : i < 900 ? 8 : 9;
        _int2str[ L++ ] = c + 48;
        i -= c * 100;
        m = true;
      }
      else if( m ) _int2str[ L++ ] = '0';
      // decades (check on lower byte to optimize code)
      b = char( i );
      if( b > 9 ) {
        c = b < 50
          ? ( b < 30
              ? ( b < 20 ? 1 : 2 )
              :   b < 40 ? 3 : 4
            )
          : b < 80
            ? ( i < 60
                ? 5
                : i < 70 ? 6 : 7
              )
            : i < 90 ? 8 : 9;
        _int2str[ L++ ] = c + 48;
        b -= c * 10;
        m = true;
      }
      else if( m ) _int2str[ L++ ] = '0';
      // last digit
      _int2str[ L++ ] = b + 48;
      // null terminator
      _int2str[ L ] = 0;
      return _int2str;
    }

**Appendix**

The bare ADC conversions take about 768 us.

With binary data I am sending via serial 3x uint16_t plus one end of line and two tabs, meaning 9 characters per reading. At 250 kbps 8N1 the minimum time required is 324 us. Using RealTerm (for Win) I can see that I get a stram of 9k chars/s, as expected.

With Serial.print I am sending 4x string[4] (readings are always between 1000 and 9999), plus tabs and newline, meaning 15 bytes per reading. RealTerm however gives me an incoming stream of 11-12k chars/s, therefore Serial.print is too slow.

The optimised int-to-string function (even without modifying it to avoid checking for negative and for >9999, not needed in my case) still sends 15 bytes per reading, and RealTerm also shows me an actual stream of 15k chars/s, as expected.

  [1]: https://stackoverflow.com/a/20567753/2131851

title: Why is integer-to-string not working in this sketch?

Answers: 1

body:
it took me a while and i'm still not 100% sure if I got you right. I think you have two questions:

> 1) how to speed up the entire execution?

the serial routines will be your biggest bottleneck. I would suggest that a) you speed up the baud rate; and b) you try to use a tx interrupt here.

> 2) why isn't the int2str() routine working?

because int2str() stores the converted string in a buffer (_int2str[]), which is subsequently destroyed by conversions. so for it to work, you should do something like this:

      serial.write(int2str(x)); serial.write("\t");
      serial.write(int2str(y)); serial.write("\t");
      serial.write(int2str(z)); serial.write("\n");

BTW, int2str() can be written a lot better than it is now.

edit: to add an alternate int2str() implementaton.

    //positive and negative numbers
    //int is 16-bit type
    char *int2str2(int i) {
     static char _int2str[7];
     unsigned char tmp, str_len=0;  //converted string starts at _int2str[0]

     //process the sign
     if (i&0x8000/*<0*/) {
       _int2str[str_len++]='-';   //insert leading '-'
       i=-i;        //make the number positive
     };

     //convert the next position (10,000)
     tmp = 0;       //reset tmp
     while (i >= 10000) {
       i-=10000;       //decrement i
       tmp+=1;       //increment counter
     }
     _int2str[str_len++] = tmp + '0'; //form the msb

     //convert the next position (1,000)
     tmp = 0;       //reset tmp
     while (i >= 1000) {
       i-=1000;       //decrement i
       tmp+=1;       //increment counter
     }
     _int2str[str_len++] = tmp + '0'; //form the msb

     //convert the next position (100)
     tmp = 0;       //reset tmp
     while (i >= 100) {
       i-=100;       //decrement i
       tmp+=1;       //increment counter
     }
     _int2str[str_len++] = tmp + '0'; //form the msb

     //convert the next position (10)
     tmp = 0;       //reset tmp
     while (i >= 10) {
       i-=10;       //decrement i
       tmp+=1;       //increment counter
     }
     _int2str[str_len++] = tmp + '0'; //form the msb

     //convert the lsb
     //tmp = 0;       //reset tmp
     //while (i >= 100000ul) {
     //  i-=100000ul;      //decrement i
     //  tmp+=1;       //increment counter
     //}
     tmp = i;
     _int2str[str_len++] = tmp + '0'; //form the msb

     return _int2str;
    }

here is what I would use. I benchmark against yours, converting numbers from 0 to 32767. total cycle count for yours is 10.5 million and 7.0 million for mine. Now, the actual performance will depend on a lot of factors, like your chips, compilers (I used IAR AVR), and optimization settings, to name a few.

Note: the routine was written as a generic one. if you are only converting 10-bit numbers (from a 10-bit adc for example), it can be greatly simplified, and execution time greatly shortened: <160K cumulative cycles converting numbers from 0 to 1023.


body:
Hi I have a program that does not work right as I aspect:

    v = tempC;
    h = tempC * 10;
    h = h % 10;
    memset(stempCA, 0, sizeof(stempCA));
    sprintf(stempCA, "%+.2d.%d", v, h);

it works fine on positive temperature "+11.22"
but not for negative values : "-02.-1"

where is my mistake?
 thanx

title: LCD displays wrong temperature

Answers: 1

body:
I think, that -1=-1, not 9 as you would like. I use

    if (tempC<0) {print'-';tempC=-tempC;};
    print tempC as usual for positive numbers


body:
I'm not sure if this is a dumb question, but here goes  :

I am developing an Android app that uses a custom Bluetooth device as a companion. I'm using an HC05 module to interface the device with my app. What I need is a way for me to distinguish my HC05 module from, say, some other HC05 module that might be in range.

The obvious way of doing this would be to set the device name in a certain format. But I was wondering if there was a more better approach to this.

On searching, I found that UUID's are used for a similar purpose (i.e. service discovery), but I couldn't find any further info. Is it at all possible to set a custom UUID for the HC05 module so that I can filter devices in my Android app based on that?

title: How to setup HC05 Module to be distinguishable

Answers: 2

body:
As frarugi87 recommended in the comments, you need to change the device's name. Changing the device name will allow you to identify it by a custom name that you come up with. To do this you need to use something called AT Commands. Here is a guide that contains many of the system parameters that you can check and change via AT Commands: http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/?ALLSTEPS

Here is a brief summary about how to change the device name, quoted from the above Instructable:

First switch the device into command mode

> For the HC-05 module to switch to AT command mode, the HC-05 pin 34
> (often referred to as the Key pin) needs to pulled HIGH but in a
> certain order of events explained below. When the HC-05 enters the AT
> command mode, it will communicate at 38400 baud rate. Follow these
> steps in the stated order to switch to the HC-05 to AT command mode.
>
> 1. Wire the HC-05 and Arduino Uno per instructions.
> 2. BEFORE YOU CONNECT THE ARDUINO TO THE USB remove the VCC (power) red wire from the HC-05 so it's not getting any power from the
> Arduino. All other wires are still connected.
> 3. Now connect the Arduino Uno to the USB cable extended from your PC.
> 4. Make sure the HC-05 module is NOT PAIRED with any other Bluetooth device.
> 5. Re-connect the Arduino Uno 5V wire to the HC-05's VCC (5V power) pin.
> 6. The HC-05 LED will blink on and off at about 2 second intervals. Now the HC-05 is in AT command mode ready to accept commands to change
> configuration and settings.
> 7. To test if everything is wired correctly,  open the Serial Monitor from the 8. Arduino IDE and type "AT" and click SEND. You should see
> an "OK" If you don't see an "OK" check your wiring.

Next run this program on your Arduino

    /*

    AUTHOR: Hazim Bitar (techbitar)
    DATE: Aug 29, 2013
    LICENSE: Public domain (use at your own risk)
    CONTACT: techbitar at gmail dot com (techbitar.com)

    */

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup()
    {
      pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(9, HIGH);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
      BTSerial.begin(38400);  // HC-05 default speed in AT command more
    }

    void loop()
    {

      // Keep reading from HC-05 and send to Arduino Serial Monitor
      if (BTSerial.available())
        Serial.write(BTSerial.read());

      // Keep reading from Arduino Serial Monitor and send to HC-05
      if (Serial.available())
        BTSerial.write(Serial.read());
    }

Finally (the quotes aren't part of the command)

> To change device name from the default HC-05 to let's say MYBLUE
> enter: "AT+NAME=MYBLUE"

body:
Your options are:

 1. As you guessed, you could set the name with `AT+NAME=`, and only use the names matching some pattern. It would work if you're only user so you just want to ignore other BT devices, but is problematic if you're having multiple independent users (each with its different set of *HC05*s) who might be in range (you could set different pattern for each user, though).

 2. build a database of addresses (read-only with `AT+ADDR?`), and only access those devices that are belonging to that user. It would avoid problem above with multiple users, but would require some logistics on your part (for example, when you sell user the app and HC05s, in the registration process you'll need to assign exactly which HC05 address that user my access. Or you might want to allow user to pick which devices are his, by having him specify specify PIN for pairing set with `AT+PSWD=`)

 3. third way is to [use custom Inquire Access Code][1] instead of [GIAC][2] so only that set of devices is scanned. HC05 [allows setting it][3] with `AT+IAC=`. However, as it is more complex and nonstandard that (2), and you'd probably still need to registration to differentiate which user is allowed which IAC, I'd recommend you do (2) instead.

  [1]: https://stackoverflow.com/q/4827343/2600099
  [2]: https://www.bluetooth.com/specifications/assigned-numbers/baseband
  [3]: http://elecfreaks.com/store/download/datasheet/Bluetooth/HC-0305 serail module AT commamd set 201104 revised.pdf


body:
I am working on comparing autopilots like [Ardupilot][1], [CC3D][2], [KK2.1.5][3]. The comparision is about system reactions/behaviors that it gives during flight. For this purpose, I need to read the PWM duty cycle (like osilascopes - the PWM frequency can be vary from 50 to 430 Hz) values from autopilot card. There are 4 command input PWMs and 4 esc control PWMs for a typical quadrotor. **I have to read 8 duty cycle values with digital/analog input pins.** How do I measure duty cycle of 8 PWM signals?  Also, is digital or analogue measurement precise and faster?

*Note about **attachInterrupt** command: According to [arduino.cc][4] AtMega328 series have **2** interrupts, Arduino ATmega 2560 series have **7** interrupts.*

  [1]: http://ardupilot.org/
  [2]: http://www.dronetrest.com/t/cc3d-flight-controller-guide/830
  [3]: https://www.google.com.tr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjN7ubm7dfRAhVnIpoKHfF9DDQQFggZMAA&url=https://www.rcgroups.com/forums/showatt.php?attachmentid=6646802&d=1396466493&usg=AFQjCNG_tmyH1Ppv2sy7WixUytnVCPFHDA&sig2=pgugQ4brDIwro2KgWw1ziQ&bvm=bv.144224172,d.bGs
  [4]: https://www.arduino.cc/en/Reference/attachInterrupt

title: Arduino read PWM duty cycle value with input (analog / digital)

Answers: 2

body:
if done in analog, run the pwm through a lpf and perform an adc on the output;

if done in digital, use a timer's capture function, or use external interrupt / pin change interrupt to capture the timing off a time base.

body:
The code shown in [my answer to question 18183](https://arduino.stackexchange.com/a/18221/3917), “Read RC receiver channels using Interrupt instead of PulseIn”. That answer has code to read four channels of RC PWM.  It can easily be adapted to work with eight channels.  It has an ISR that runs when selected pins change.  It sorts out which channel(s) changed, and stores the value of `micros()` at each change.

Also see [my answer to question 19106](https://arduino.stackexchange.com/a/19109/3917), “Can external interrupts be OR'd together on the '328 (Uno)?”  That answer includes a sketch for generating appropriate ISR code.  [My answer to question 32572](https://arduino.stackexchange.com/a/32582/3917), “How to detect the direction of a rotary encoder?”, shows another instance.

Digital input, as used in the code mentioned above, takes under  <strike>a microsecond</strike> ten microseconds in the ISR.  As noted in dannyf's comment, unrolling the `for` loop and (where possible) using constants instead of variables can reduce the in-ISR time to 3.4 μs.  Note, ISR entry and exit still add several microseconds.

10-bit analog input, on the other hand, will take around 104 microseconds per reading, a time comparable to some of the pulse widths you'll be measuring.  So it isn't fast enough.  If degraded ADC accuracy is acceptable, decreasing the ADC-clock scale factor as explained in [a webpage at microsmart.co.za](http://www.microsmart.co.za/technical/2014/03/01/advanced-arduino-adc/) can get AD conversion time down to 20 μs.  This is around three times as long as digital input takes, so rather slow.