body:
TEENSY Boards have in the USB-MODE "**FLIGHTSIM**" direct access to the variables = **DATAREFS**
of X-PLANE 11.
You can use FLIGHTSIMINTEGER and FLIGHTSIMFLOAT but not a varible for CHARs like the ID of a waypoint
for example "IBZ" or "EDDF" .
I need to read the CHARs to use them in the Display of my FlightSimPanel.
ANY IDEA ?

title: How can TEENSY Microcontrollers read ASCI Variables from X-PLANE 11

Answers: 0


body: I am planing on making Arduino from scratch. I found many examples on internet, but they all need another Arduino for programming. How can I make Arduino with USB interface for programming and serial data transfer? Would I need something called FTDI? Basically I want same Arduino you can buy, just build it from separate parts.

title: DIY Arduino with USB port

Answers: 1

body:
There are two critical things that make an "Arduino". There is the hardware, and there is the bootloader.

The hardware is nothing special. It's just an MCU and the required minimal support hardware. What really makes it an Arduino is the bootloader which allows it to be programmed over the serial connection (via USB usually).

Without that bootloader the only way to program the MCU is over the hardware programming interface (typically ICSP for an AVR MCU), and for that you need some form of hardware programmer.

And of course that means the only way to put the bootloader onto the chip is to use a hardware programmer.

So you have two options:

1. Program the bootloader into the chip using a hardware programmer (which you can make with an Arduino), or
2. Buy an ATMega328P chip with the bootloader pre-programmed.

Once you have the bootloader installed then yes, you can program the chip over UART (through USB with a USB to UART adaptor such as an FT232).


body:
I was following [FREE Functions to draw graphs on OLED displays][1] on YouTube but mine OLED display doesn't support Adafruit_SSD1306 library,but it works on Adafruit_SH1106.h driver.

  [1]: https://www.youtube.com/watch?v=13PFOwcK3-I

The code that is shared with YouTube video

    /*

      This program provides functions to draw:
      1. horizontal bar graph
      2. vertical bar graph
      3. dial
      4. cartesian graph

      It requires an microcrontrioller Arduino, teensy and a 0.96 dispaly (1306 driver chip)

      display. sources
      https://www.amazon.com/Diymall-Yellow-Arduino-display.-Raspberry/dp/B00O2LLT30/ref=pd_lpo_vtph_147_bs_t_1?_encoding=UTF8&psc=1&refRID=BQAPE07SVJQNDKEVMTQZ
      https://www.amazon.com/dp/B06XRCQZRX/ref=sspa_dk_detail_0?psc=1&pd_rd_i=B06XRCQZRX&pd_rd_wg=aGuhK&pd_rd_r=1WJPXAG68XFSADGDPNZR&pd_rd_w=DAAsB

      Adafruit libraries
      https://github.com/adafruit/Adafruit-GFX-Library/archive/master.zip
      https://github.com/adafruit/Adafruit_SSD1306

      Revisions
      rev     date        author      description
      1       12-5-2017   kasprzak    initial creation

      Pin settings

      Arduino   device
      5V        Vin
      GND       GND
      A0        read an input voltage from a pot across Vcc and Gnd (just for demo purposes)
      A1
      A2
      A3
      A4        SDA on the display. or use dedicated pin on board if provided
      A5        SCL on the display. use dedicated pin on board if provided
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13

    */

    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>

    #define READ_PIN            A0
    #define OLED_RESET          A4
    #define LOGO16_GLCD_HEIGHT  16
    #define LOGO16_GLCD_WIDTH   16

    // create what ever variables you need
    double volts;
    double bvolts;
    double x, y;

    // these are a required variables for the graphing functions
    bool Redraw1 = true;
    bool Redraw2 = true;
    bool Redraw3 = true;
    bool Redraw4 = true;
    double ox , oy ;

    // create the display object
    Adafruit_SSD1306 display(OLED_RESET);

    void setup() {

      Serial.begin(9600);

      // initialize the display
      // note you may have to change the address
      // the most common are 0X3C and 0X3D

      display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
      // if you distribute your code, the adafruit license requires you show their splash screen
      // otherwise clear the video buffer memory then display
      display.display();
      //delay(2000);
      display.clearDisplay();
      display.display();

      // establish whatever pin reads you need
      pinMode(A0, INPUT);

    }

    unsigned long OldTime;
    unsigned long counter;

      void loop(void) {

      // read some values and convert to volts
      bvolts = analogRead(A0);
      volts = (bvolts  / 204.6 ) ;

      // draw any of the following, sorry for the crazy long arguement lists
      // note 0.96 isn't very big, so you can't show many graphs at the same time
      // also colors are hard coded
      // the display i use draws text at the top in yellow--we'll use that for drawing the title

      // call one of these functions
      DrawBarChartV(display, bvolts, 25,  60, 40, 40, 0, 1024 , 256, 0, "A0 (bits)", Redraw1);
      //  DrawBarChartH(display, volts, 10, 45, 100, 20, 0, 5, 1, 0, "A0 (volts)", Redraw2);
      //  DrawDial(display, volts, 65, 50, 25, 0, 5 , 1, 0, 200, "A0 (volts)", Redraw3);

      // for multiple graphs uncomment the next 2 lines
      //  DrawBarChartV(display, bvolts, 5,  60, 10, 40, 0, 1024 , 256, 0, "A0 (bits/volts)", Redraw1);
      //  DrawDial(display, volts, 90, 50, 25, 0, 5 , 1, 0, 200, "A0 (bits/volts)", Redraw3);

      // or show a cartesian style graph to plot values over time (or whatever)

        DrawCGraph(display, x++, bvolts, 30, 50, 75, 30, 0, 100, 25, 0, 1024, 512, 0, "Bits vs Seconds", Redraw4);
        if (x > 100) {
        while (1) {}
        }

      delay(1000);

      }

      /*
      This method will draw a vertical bar graph for single input
      it has a rather large arguement list and is as follows

      &d to pass the display object, mainly used if multiple displays are connected to the MCU
      curval = date to graph (must be between loval and hival)
      x = position of bar graph (lower left of bar)
      y = position of bar (lower left of bar
      w = width of bar graph
      h =  height of bar graph (does not need to be the same as the max scale)
      loval = lower value of the scale (can be negative)
      hival = upper value of the scale
      inc = scale division between loval and hival
      dig = format control to set number of digits to display. (not includeing the decimal)
      label = bottom lable text for the graph
      redraw = flag to redraw display. only on first pass (to reduce flickering)

    */

    void DrawBarChartV(Adafruit_SSD1306 &d, double curval, double x , double y , double w, double h , double loval , double hival , double inc , double dig, String label, bool &Redraw)
    {
      double stepval, my, level, i, data;

      if (Redraw) {
        Redraw = false;
        d.fillRect(0, 0,  127 , 14, SSD1306_WHITE);
        d.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
        d.setTextSize(1);
        d.setCursor(2, 4);
        d.println(label);
        // step val basically scales the hival and low val to the height
        // deducting a small value to eliminate round off errors
        // this val may need to be adjusted
        stepval = ( inc) * (double (h) / (double (hival - loval))) - .001;
        for (i = 0; i <= h; i += stepval) {
          my =  y - h + i;
          d.drawFastHLine(x + w + 1, my,  5, SSD1306_WHITE);
          // draw lables
          d.setTextSize(1);
          d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
          d.setCursor(x + w + 12, my - 3 );
          data = hival - ( i * (inc / stepval));
          d.print(data, dig);
        }
      }
      // compute level of bar graph that is scaled to the  height and the hi and low vals
      // this is needed to accompdate for +/- range
      level = (h * (((curval - loval) / (hival - loval))));
      // draw the bar graph
      // write a upper and lower bar to minimize flicker cause by blanking out bar and redraw on update
      d.drawRect(x, y - h, w, h, SSD1306_WHITE);
      d.fillRect(x, y - h, w, h - level,  SSD1306_BLACK);
      d.drawRect(x, y - h, w, h, SSD1306_WHITE);
      d.fillRect(x, y - level, w,  level, SSD1306_WHITE);
      // up until now print sends data to a video buffer NOT the screen
      // this call sends the data to the screen
      d.display();

    }

    /*
      This method will draw a horizontal bar graph for single input
      it has a rather large arguement list and is as follows

      &display to pass the display object, mainly used if multiple displays are connected to the MCU
      x = position of bar graph (upper left of bar)
      curval = date to graph (must be between loval and hival)
      y = position of bar (upper left of bar (add some vale to leave room for label)
      w = width of bar graph (does not need to be the same as the max scale)
      h =  height of bar graph
      loval = lower value of the scale (can be negative)
      hival = upper value of the scale
      inc = scale division between loval and hival
      dig = format control to set number of digits to display. (not includeing the decimal)
      label = bottom lable text for the graph
      redraw = flag to redraw display. only on first pass (to reduce flickering)
    */

    void DrawBarChartH(Adafruit_SSD1306 &d, double curval, double x , double y , double w, double h , double loval , double hival , double inc , double dig, String label, bool &Redraw)
    {
      double stepval, mx, level, i, data;

      if (Redraw) {
        Redraw = false;
        d.fillRect(0, 0,  127 , 16, SSD1306_WHITE);
        d.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
        d.setTextSize(1);
        d.setCursor(2, 4);
        d.println(label);
        // step val basically scales the hival and low val to the width
        stepval =  inc * (double (w) / (double (hival - loval))) - .00001;
        // draw the text
        for (i = 0; i <= w; i += stepval) {
          d.drawFastVLine(i + x , y ,  5, SSD1306_WHITE);
          // draw lables
          d.setTextSize(1);
          d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
          d.setCursor(i + x , y + 10);
          // addling a small value to eliminate round off errors
          // this val may need to be adjusted
          data =  ( i * (inc / stepval)) + loval + 0.00001;
          d.print(data, dig);
        }
      }
      // compute level of bar graph that is scaled to the width and the hi and low vals
      // this is needed to accompdate for +/- range capability
      // draw the bar graph
      // write a upper and lower bar to minimize flicker cause by blanking out bar and redraw on update
      level = (w * (((curval - loval) / (hival - loval))));
      d.fillRect(x + level, y - h, w - level, h,  SSD1306_BLACK);
      d.drawRect(x, y - h, w,  h, SSD1306_WHITE);
      d.fillRect(x, y - h, level,  h, SSD1306_WHITE);
      // up until now print sends data to a video buffer NOT the screen
      // this call sends the data to the screen
      d.display();

    }

    /*
      This method will draw a dial-type graph for single input
      it has a rather large arguement list and is as follows

      &display to pass the display object, mainly used if multiple displays are connected to the MCU
      curval = date to graph (must be between loval and hival)
      cx = center position of dial
      cy = center position of dial
      r = radius of the dial
      loval = lower value of the scale (can be negative)
      hival = upper value of the scale
      inc = scale division between loval and hival
      sa = sweep angle for the dials scale
      dig = format control to set number of digits to display. (not includeing the decimal)
      label = bottom lable text for the graph
      redraw = flag to redraw display. only on first pass (to reduce flickering)
    */

    void DrawDial(Adafruit_SSD1306 &d, double curval, int cx, int cy, int r, double loval , double hival , double inc, double dig, double sa, String label, bool &Redraw) {

      double ix, iy, ox, oy, tx, ty, lx, rx, ly, ry, i, Offset, stepval, data, angle;
      double degtorad = .0174532778;
      static double px = cx, py = cy, pix = cx, piy = cy, plx = cx, ply = cy, prx = cx, pry = cy;

      if (Redraw) {
        Redraw = false;
        // draw the dial only one time--this will minimize flicker
        d.fillRect(0, 0,  127 , 16, SSD1306_WHITE);
        d.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
        d.setTextSize(1);
        d.setCursor(2, 4);
        d.println(label);
        // center the scale about the vertical axis--and use this to offset the needle, and scale text
        Offset = (270 +  sa / 2) * degtorad;
        // find hte scale step value based on the hival low val and the scale sweep angle
        // deducting a small value to eliminate round off errors
        // this val may need to be adjusted
        stepval = ( inc) * (double (sa) / (double (hival - loval))) + .00;
        // draw the scale and numbers
        // note draw this each time to repaint where the needle was
        for (i = 0; i <= sa; i += stepval) {
          angle = ( i  * degtorad);
          angle = Offset - angle ;
          ox =  (r - 2) * cos(angle) + cx;
          oy =  (r - 2) * sin(angle) + cy;
          ix =  (r - 10) * cos(angle) + cx;
          iy =  (r - 10) * sin(angle) + cy;
          tx =  (r + 10) * cos(angle) + cx + 8;
          ty =  (r + 10) * sin(angle) + cy;
          d.drawLine(ox, oy, ix, iy, SSD1306_WHITE);
          d.setTextSize(1);
          d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
          d.setCursor(tx - 10, ty );
          data = hival - ( i * (inc / stepval)) ;
          d.println(data, dig);
        }
        for (i = 0; i <= sa; i ++) {
          angle = ( i  * degtorad);
          angle = Offset - angle ;
          ox =  (r - 2) * cos(angle) + cx;
          oy =  (r - 2) * sin(angle) + cy;
          d.drawPixel(ox, oy, SSD1306_WHITE);
        }
      }
      // compute and draw the needle
      angle = (sa * (1 - (((curval - loval) / (hival - loval)))));
      angle = angle * degtorad;
      angle = Offset - angle  ;
      ix =  (r - 10) * cos(angle) + cx;
      iy =  (r - 10) * sin(angle) + cy;
      // draw a triangle for the needle (compute and store 3 vertiticies)
      lx =  2 * cos(angle - 90 * degtorad) + cx;
      ly =  2 * sin(angle - 90 * degtorad) + cy;
      rx =  2 * cos(angle + 90 * degtorad) + cx;
      ry =  2 * sin(angle + 90 * degtorad) + cy;

      // blank out the old needle
      d.fillTriangle (pix, piy, plx, ply, prx, pry, SSD1306_BLACK);

      // then draw the new needle
      d.fillTriangle (ix, iy, lx, ly, rx, ry, SSD1306_WHITE);

      // draw a cute little dial center
      d.fillCircle(cx, cy, 3, SSD1306_WHITE);

      //save all current to old so the previous dial can be hidden
      pix = ix;
      piy = iy;
      plx = lx;
      ply = ly;
      prx = rx;
      pry = ry;
      // up until now print sends data to a video buffer NOT the screen
      // this call sends the data to the screen
      d.display();

    }

    /*

      function to draw a cartesian coordinate system and plot whatever data you want
      just pass x and y and the graph will be drawn huge arguement list

      &display to pass the display object, mainly used if multiple displays are connected to the MCU
      x = x data point
      y = y datapont
      gx = x graph location (lower left)
      gy = y graph location (lower left)
      w = width of graph
      h = height of graph
      xlo = lower bound of x axis
      xhi = upper bound of x asis
      xinc = division of x axis (distance not count)
      ylo = lower bound of y axis
      yhi = upper bound of y asis
      yinc = division of y axis (distance not count)
      title = title of graph
      &redraw = flag to redraw graph on fist call only

    */

    void DrawCGraph(Adafruit_SSD1306 &d, double x, double y, double gx, double gy, double w, double h, double xlo, double xhi, double xinc, double ylo, double yhi, double yinc, double dig, String title, boolean &Redraw) {

      double i;
      double temp;
      int rot, newrot;

      if (Redraw == true) {
        Redraw = false;
        d.fillRect(0, 0,  127 , 16, SSD1306_WHITE);
        d.setTextColor(SSD1306_BLACK, SSD1306_WHITE);
        d.setTextSize(1);
        d.setCursor(2, 4);
        d.println(title);
        ox = (x - xlo) * ( w) / (xhi - xlo) + gx;
        oy = (y - ylo) * (gy - h - gy) / (yhi - ylo) + gy;
        // draw y scale
        d.setTextSize(1);
        d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
        for ( i = ylo; i <= yhi; i += yinc) {
          // compute the transform
          // note my transform funcition is the same as the map function, except the map uses long and we need doubles
          temp =  (i - ylo) * (gy - h - gy) / (yhi - ylo) + gy;
          if (i == 0) {
            d.drawFastHLine(gx - 3, temp, w + 3, SSD1306_WHITE);
          }
          else {
            d.drawFastHLine(gx - 3, temp, 3, SSD1306_WHITE);
          }
          d.setCursor(gx - 27, temp - 3);
          d.println(i, dig);
        }
        // draw x scale
        for (i = xlo; i <= xhi; i += xinc) {
          // compute the transform
          d.setTextSize(1);
          d.setTextColor(SSD1306_WHITE, SSD1306_BLACK);
          temp =  (i - xlo) * ( w) / (xhi - xlo) + gx;
          if (i == 0) {
            d.drawFastVLine(temp, gy - h, h + 3, SSD1306_WHITE);
          }
          else {
            d.drawFastVLine(temp, gy, 3, SSD1306_WHITE);
          }
          d.setCursor(temp, gy + 6);
          d.println(i, dig);
        }
      }

      // graph drawn now plot the data
      // the entire plotting code are these few lines...

      x =  (x - xlo) * ( w) / (xhi - xlo) + gx;
      y =  (y - ylo) * (gy - h - gy) / (yhi - ylo) + gy;
      d.drawLine(ox, oy, x, y, SSD1306_WHITE);
      d.drawLine(ox, oy - 1, x, y - 1, SSD1306_WHITE);
      ox = x;
      oy = y;

      // up until now print sends data to a video buffer NOT the screen
      // this call sends the data to the screen
      d.display();

    }

    /////////////////////////////////////////////////////////

For my purpose of running this project in my OLED I replaced all SSD1306 keyword with SH1106. Except this project every other projects works on this OLED by replacing SSD1306 keyword with SH1106.

Getting this error in Ardunio IDE 'SH1106_WHITE' was not declared in this scope

    Arduino: 1.8.13 Hourly Build 2020/04/21 12:25 (Linux), Board: "Arduino Uno"

    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino: In function 'void DrawBarChartV(Adafruit_SH1106&, double, double, double, double, double, double, double, double, double, String, bool&)':
    sketch_oct07a:162:33: error: 'SH1106_WHITE' was not declared in this scope
         d.fillRect(0, 0,  127 , 14, SH1106_WHITE);
                                     ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:162:33: note: suggested alternative: 'SH1106_LCDWIDTH'
         d.fillRect(0, 0,  127 , 14, SH1106_WHITE);
                                     ^~~~~~~~~~~~
                                     SH1106_LCDWIDTH
    sketch_oct07a:163:20: error: 'SH1106_BLACK' was not declared in this scope
         d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                        ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:163:20: note: suggested alternative: 'SH1106_128_64'
         d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                        ^~~~~~~~~~~~
                        SH1106_128_64
    sketch_oct07a:187:30: error: 'SH1106_WHITE' was not declared in this scope
       d.drawRect(x, y - h, w, h, SH1106_WHITE);
                                  ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:187:30: note: suggested alternative: 'SH1106_LCDWIDTH'
       d.drawRect(x, y - h, w, h, SH1106_WHITE);
                                  ^~~~~~~~~~~~
                                  SH1106_LCDWIDTH
    sketch_oct07a:188:39: error: 'SH1106_BLACK' was not declared in this scope
       d.fillRect(x, y - h, w, h - level,  SH1106_BLACK);
                                           ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:188:39: note: suggested alternative: 'SH1106_128_64'
       d.fillRect(x, y - h, w, h - level,  SH1106_BLACK);
                                           ^~~~~~~~~~~~
                                           SH1106_128_64
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino: In function 'void DrawBarChartH(Adafruit_SH1106&, double, double, double, double, double, double, double, double, double, String, bool&)':
    sketch_oct07a:221:33: error: 'SH1106_WHITE' was not declared in this scope
         d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                     ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:221:33: note: suggested alternative: 'SH1106_LCDWIDTH'
         d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                     ^~~~~~~~~~~~
                                     SH1106_LCDWIDTH
    sketch_oct07a:222:20: error: 'SH1106_BLACK' was not declared in this scope
         d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                        ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:222:20: note: suggested alternative: 'SH1106_128_64'
         d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                        ^~~~~~~~~~~~
                        SH1106_128_64
    sketch_oct07a:246:47: error: 'SH1106_BLACK' was not declared in this scope
       d.fillRect(x + level, y - h, w - level, h,  SH1106_BLACK);
                                                   ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:246:47: note: suggested alternative: 'SH1106_128_64'
       d.fillRect(x + level, y - h, w - level, h,  SH1106_BLACK);
                                                   ^~~~~~~~~~~~
                                                   SH1106_128_64
    sketch_oct07a:247:31: error: 'SH1106_WHITE' was not declared in this scope
       d.drawRect(x, y - h, w,  h, SH1106_WHITE);
                                   ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:247:31: note: suggested alternative: 'SH1106_LCDWIDTH'
       d.drawRect(x, y - h, w,  h, SH1106_WHITE);
                                   ^~~~~~~~~~~~
                                   SH1106_LCDWIDTH
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino: In function 'void DrawDial(Adafruit_SH1106&, double, int, int, int, double, double, double, double, double, String, bool&)':
    sketch_oct07a:283:33: error: 'SH1106_WHITE' was not declared in this scope
         d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                     ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:283:33: note: suggested alternative: 'SH1106_LCDWIDTH'
         d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                     ^~~~~~~~~~~~
                                     SH1106_LCDWIDTH
    sketch_oct07a:284:20: error: 'SH1106_BLACK' was not declared in this scope
         d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                        ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:284:20: note: suggested alternative: 'SH1106_128_64'
         d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                        ^~~~~~~~~~~~
                        SH1106_128_64
    sketch_oct07a:333:49: error: 'SH1106_BLACK' was not declared in this scope
       d.fillTriangle (pix, piy, plx, ply, prx, pry, SH1106_BLACK);
                                                     ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:333:49: note: suggested alternative: 'SH1106_128_64'
       d.fillTriangle (pix, piy, plx, ply, prx, pry, SH1106_BLACK);
                                                     ^~~~~~~~~~~~
                                                     SH1106_128_64
    sketch_oct07a:336:43: error: 'SH1106_WHITE' was not declared in this scope
       d.fillTriangle (ix, iy, lx, ly, rx, ry, SH1106_WHITE);
                                               ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:336:43: note: suggested alternative: 'SH1106_LCDWIDTH'
       d.fillTriangle (ix, iy, lx, ly, rx, ry, SH1106_WHITE);
                                               ^~~~~~~~~~~~
                                               SH1106_LCDWIDTH
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino: In function 'void DrawCGraph(Adafruit_SH1106&, double, double, double, double, double, double, double, double, double, double, double, double, double, String, boolean&)':
    sketch_oct07a:388:33: error: 'SH1106_WHITE' was not declared in this scope
         d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                     ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:388:33: note: suggested alternative: 'SH1106_LCDWIDTH'
         d.fillRect(0, 0,  127 , 16, SH1106_WHITE);
                                     ^~~~~~~~~~~~
                                     SH1106_LCDWIDTH
    sketch_oct07a:389:20: error: 'SH1106_BLACK' was not declared in this scope
         d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                        ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:389:20: note: suggested alternative: 'SH1106_128_64'
         d.setTextColor(SH1106_BLACK, SH1106_WHITE);
                        ^~~~~~~~~~~~
                        SH1106_128_64
    sketch_oct07a:433:28: error: 'SH1106_WHITE' was not declared in this scope
       d.drawLine(ox, oy, x, y, SH1106_WHITE);
                                ^~~~~~~~~~~~
    /tmp/arduino_modified_sketch_953644/sketch_oct07a.ino:433:28: note: suggested alternative: 'SH1106_LCDWIDTH'
       d.drawLine(ox, oy, x, y, SH1106_WHITE);
                                ^~~~~~~~~~~~
                                SH1106_LCDWIDTH
    exit status 1
    'SH1106_WHITE' was not declared in this scope

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

I am new to this field. Any help will be appreciated.

title: OLED 'SH1106_WHITE' was not declared in this scope

Answers: 1

body:
In the Adafruit_SH1106.h header file, `SH1106_WHITE` and `SH1106_BLACK` are defined simply as `WHITE` and `BLACK` respectively.
So instead of writing `SH1106_WHITE` try replacing it `WHITE` and `SH1106_BLACK` as `BLACK` respectively.

Eg:-  `fillRect(0, 0,  127 , 14, WHITE);`


body:
I am trying to simulate a 12V LED strip as per [this tutorial.][1] However the schematic I tried to make on EasyEDA looks quite different from the images on the website. I wanted to know if what I did is correct.

[![A1, A2, A3 are the pins connected to the Arduino][2]][2]

[![As compared to this...][3]][3]

  [1]: https://learn.adafruit.com/rgb-led-strips/usage
  [2]: https://i.stack.imgur.com/iPMug.png
  [3]: https://i.stack.imgur.com/EZb6x.png

title: Is this LED Strip Schematic correct?

Answers: 1

body:
Schematic and wiring diagram are not the same. They seem to use different RGB LEDs. The wiring diagram has **common anode** RGB LEDs, while your schematic uses a **common cathode** RGB LED. The difference is, which side of the LED gets switched.

In the common anode configuration, all anodes (positive lead) of the individual color LEDs are connected together, while the cathodes (negative leads) are brought out, so that you can switch them via the MOSFETs. That means, that the MOSTFETs are connected between the strips color component pins and ground.

In the common cathode configuration, all cathodes (negative lead) of the individual color LEDs are connected together, while the anodes (positive leads) are brought out for you to switch them. In this case, the MOSFETs are connected between the strips color component pins and Vcc.

---

Besides that, you should be careful with providing 12V at Vin of an Arduino Uno. While it is possible, you can very fast get the linear voltage regulator to overheat, when providing 12V. It dissipates the excess voltage (so 7V, to get it to 5V down) as heat. The voltage regulator is not cooled, so you might run into this issue, with the wiring diagram. It depends on your much current you draw from the regulator.


body:
I'm using this ADC with a load cell for weight measurement, I had 4 strain gauges and mounted them on a cantilever structure that I made out of acrylic sheet, used calibration program from here: https://github.com/olkal/HX711_ADC/blob/master/examples/Calibration/Calibration.ino,

followed the steps but it gave ```calibration factor as 0.00``` and the output was ```NaN``` or ```inf``` . I used another program from here: https://github.com/queuetue/Q2-HX711-Arduino-Library/tree/master/examples/simple_scale and the output was just hovering around ```83868```. So I thought that the mounting was the problem and used a load cell (green label, CZL 601) with the above and found the same results by doing the above.

Then I thought maybe the ADC is at fault , measured the power output from Arduino to the board and it was around 5 V , but when I measured between the ```E+``` and ```E-``` , I got ```0 V```. Since it is the excitation voltage to the bridge, it should be around 5V too right?

Is this the right way of checking the board?

P.S. I measured the four wires of the load cell and connected the opp. ends of the bridge to the E+ , E- , A+ , A- (order doesn't matter here right? connected the pairs that showed the rated resistance to E's and A's separately)

Here's a [pic][1] of the connections

Between White and green wire the Resistance is 350 ohm
Between Bk( connected in the board ) and the red it is 408 ohm
Between White and red it was 263 ohm
Between white and bk it is 320 ohm

Between bk(not connected in the board) and all others it is around 1 MOhm (so ignored that)
  [1]: https://photos.app.goo.gl/4HEmZaN1EwZ7Mjur7

title: How to find out if HX711(amplifier and 24-bit ADC) is damaged or not?

Answers: 1

body:
Looking closely at the photo of your setup I can see that you haven't soldered the header to the breakout board. Whilst there are headers available that don't require soldering, and ways of making header connections that don't require soldering, this isn't either of those.

Without solder the connection to the board will be intermittent at best and non-existent in general.


body:
`sim.println("AT+CMGS=\"+91xxxxxxxxxx\"\r");`

I don't want to write this. I want to write mobile number on serial monitor in Arduino and on that number, i want to send message. how can I do?

title: Send message to multiple number

Answers: 0


body:
i wonder where to find out the PIN names for the Az Delivery ESP32 DevKitC V2.
There is a pin out graphic, but it does not say how the Pin addresses are:
https://cdn.shopify.com/s/files/1/1509/1638/files/ESP_-_32_NodeMCU_Developmentboard_Pinout_Diagram.jpg?4479111012146266271

I thought maybe it's just the number of the GPIOs but that's wrong. In the first example script only PIN 1 was named as the address for the board intern LED.

title: Az Delivery ESP32 DevKitC V2 PIN names/number

Answers: 1

body:
ESP32 boards don't use "names" for their IO pins. There is a direct 1:1 mapping between the internal "GPIO" number and the pin number.

To do something with pin G21 on the board you use pin number 21. To do something with pin G14 you use pin number 14.

By all accounts that board differs from other ESP32 devkits in that the LED is on GPIO1 rather than the normal GPIO0 that all the other boards use. I suspect that this is the source of your confusion.


body:
The following circuit is a simplified version of a more complex system. For testing purposes, the 555 Timer was added to serve as a test signal source with frequencies set by the resistors in series. Each arbitrary signal is indicated by a push button and the Arduino needs to be able to distinguish what button has been pushed. Unfortunately, there can only be 3 buttons and more cannot be added. This is where the problem occurs. How can you reliably indicate which push button has been pressed without interfering with the arbitrary waveform?

At first, my original thought was to have the Arduino sample the signal based on that sample the Arduino would be able to tell which button is pressed.

When button 1 in the pink is pushed the Arduino receives a takes the following
 sample of the signal.

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

    843
    848
    849
    849
    849
    849
       // Time 0 when button is pushed
    532
    414
    500
    373
    463
    346
    425
    370
    386
    476
    346
    442
    642
    788
Moving the input
[![enter image description here][3]][3]

        // At t = 0 the Serial Monitor reads zero
        998
        998
        998
        998
        998
        0
        0
        0
        0
        0
        998
        0
        0
        0
        0
        0
        0
        0
        0
        0
        998
        0
        0
        0
        0
        998
        0
        0
        0
        998
        998
        998
        0
        998
        0
        0
        0
        998
        0
        0
        0
        0

Moving the analog input does not make it any easier to distinguish which button was being pushed. Which is why I decided to ask the community on how to deal with this. I have tried using a relay and simply hard coding all of the cases but the result is a system is not very robust and is vulnerable to easily break over time.

  [1]: https://www.tinkercad.com/things/eB13vkkJXJT
  [2]: https://i.stack.imgur.com/DSbgc.png
  [3]: https://i.stack.imgur.com/2eAJa.png
  [4]: http://yaab-arduino.blogspot.com/2015/02/fast-sampling-from-analog-input.html

title: Dealing with a Signal Source

Answers: 2

body:
There's an easy way to achieve reading multiple pushbuttons using single analog input.

All you need to do is create some voltage dividers at different voltages which can be read using analogRead. The last resistor,R6, in the diagram below ensures that the pin reads 0 when no push-button is pressed (i.e pull-down resistor).
In the diagram below, connect Vcc to 5V on the Arduino.

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

Try it out, you should be able to get well spaced out values for different push buttons!

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

body:
After a day or two of working on this problem, I have found that it is best to avoid using the analog pins and stay away from directly interfacing with the 555 Timer. This is a simplified version of a more complex circuit and the 555 Timer represents some arbitrary signal source. For example, on mobile radio, you push a button to send out a certain frequency. That is the concept here only the frequencies cannot be adjusted yet. Now that it has been clarified that the 555 Timer has been placed in the circuit for debugging purposes here is the best solution I have found to this problem. First, I have found that it is doable to read in from the analog pin on the Arduino but not easy. This leaves a lot of room for error being that the waveform is arbitrary with some random frequency. Therefore, I have opted to use the digital pins on the Arduino.
[![Revised Circuit][1]][1]
by using the digital pins I have now only have to worry about whether the button is high or low. Then NPN transistors were used to act as switches once the button is pushed. The diodes then were added to maintain a steady voltage across the base of the transistor. For testing purposes, the LCD was removed and replaced by an LED. As far as the code is concerned it is nothing extraordinary or complex as shown below. Therefore, I believe this may be the best way to go about solving this problem.

    const int D_pin10 = 10;
    const int D_pin9 = 9;
    const int D_pin8 = 8;
    int led = 13;
    void setup()
    {
      pinMode(D_pin10 , INPUT); // pin 10 is an input
      pinMode(D_pin9 , INPUT); // pin 10 is an input
      pinMode(D_pin8, INPUT); // pin 10 is an input
      pinMode(led, OUTPUT);
    }

    void loop()
    {
      int High_Low10 =0;
      int High_Low9 =0;
      int High_Low8 =0;

      High_Low10 = digitalRead(D_pin10);
      High_Low9 = digitalRead(D_pin9);
      High_Low8 = digitalRead(D_pin8);

      if(High_Low10 == HIGH)
      {
        digitalWrite(led, HIGH);
      }
      else if(High_Low9 == HIGH)
      {
        digitalWrite(led, HIGH);
      }
      else if(High_Low8 == HIGH)
      {
        digitalWrite(led, HIGH);
      }
      else
      {
        digitalWrite(led, LOW);
      }
      delay(1000);
    }

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


body: Is it safe to use LiFe PO4 batteries in a 18650 Battery Shield (sometimes called Lithium-Battery Shield)?

title: Can I use LiFe PO4 batteries in a 18650 battery shield?

Answers: 1

body:
In my opinion it is NOT SAFE, if your 18650 Battery Shield also charges the battery.
Anyhow some pages state that it is possible to charge LiFePo4 batteries with 4.2V instead of the recommended 3.65V. https://www.powerstream.com/lithium-phosphate-charge-voltage.htm

LiFePo4 batteries have a smaller energy density and therefore capacity. Thus those are not as explosive as Li-Ion batteries. But you are risking damaging the battery and shorten its lifespan.


body:
I am new so please be nice :)

I am trying to upload the Blinky example to my Arduino Nano BLE 33 but I get this error message from the Arduino IDE:

    No device found on ttyACM0
    Set binary mode
    Send auto-baud
    An error occurred while uploading the sketch
    Set binary mode

Any idea what I could try?

I am running the Arduino IDE as superuser in Manjaro (latest versions of everything). If you need any more information please feel free to ask.

Full IDE output:

    Sketch uses 77820 bytes (7%) of program storage space. Maximum is 983040 bytes.
    Global variables use 42192 bytes (16%) of dynamic memory, leaving 219952 bytes for local variables. Maximum is 262144 bytes.
    Forcing reset using 1200bps open/close on port /dev/ttyACM0
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
    Uploading using selected port: /dev/ttyACM0
    /root/.arduino15/packages/arduino/tools/bossac/1.9.1-arduino1/bossac -d --port=ttyACM0 -U -i -e -w /tmp/arduino_build_408944/Blink.ino.bin -R
    No device found on ttyACM0
    Set binary mode
    Send auto-baud
    An error occurred while uploading the sketch
    Set binary mode

title: Can not upload to Arduino Nano BLE 33

Answers: 1

body: It appears you are using Linux. In order to communicate you must establish yourself as being allowed to use it, that is the dial out function. "sudo usermod -a -G dialout <username>" should work but you need to log out then back in before it takes effect. After that you are all set.


body: I am making a project with 3 arduinos (2 slave, 1 master) and I want to know can I use the mpu6050 since it uses the I2c communication.

title: Can I use The mpu6050 with this?

Answers: 2

body: You can but keep the I2C wires less then about 30cm. If they are going to be further apart consider something like RS485 or CAN. Are you sure you need three?

body: Yes, but only from the master. You have one I2C bus with three slave devices on it - two arduinos and one mpu6050.


body:
I am using KDE Neon and have downloaded the Arduino IDE via the Snap store. It worked well with the ESP8266 and other Arduions. But when I tried to upload a simple sketch or an example sketch to my Digispark, I get an error message. I have selected the right Board and the micronucleus programmer. I have also installed libusb. But I always get the following error message:

/home/myusername/snap/arduino/41/.arduino15/packages/digistump/tools/micronucleus/2.0a4/micronucleus: error while loading shared libraries: libusb-0.1.so.4: cannot open shared object file: No such file or directory

title: Digispark uploading not working in KDE Neon (Linux)

Answers: 1

body:
I had the same problem when using the snap package of the Arduino IDE. I solved the problem by installing the Arduino IDE from the official web page: [https://www.arduino.cc/en/software][1]

  [1]: https://www.arduino.cc/en/software

You might have to run the Arduino IDE with sudo or better add a custom udev rule in case you now get following assertion error:

> 'micronucleus_connect: Assertion `res >= 4' failed.'

Solving the assertion error is further described in following post: https://digistump.com/board/index.php?topic=106.0


body:
I am using Twilio for sending SMS in my project. I am measuring temperatures and if the temperature is too high, an SMS is sent. In my code I also have a read and a push to Firebase Realtime Database. In this case (where there is only one read and one push) everything works fine and the message is sent. However, after adding another set to Firebase the SMS is not sent. The error I get is  "Last SSL error was: Unable to allocate memory for SSL structures and buffers". I also added the command, which prints the free heap just before the message is sent and it prints that I still have 24000 free heap. In other cases, where I did not set values to Firebase, my free heap was also 24000 and the message was sent properly. Do you have any suggestions how to solve this problem?

Here's my code:
```
#include <ESP8266WiFi.h>
#include <FirebaseESP8266.h>
#include "OneWire.h"
#include "DallasTemperature.h"
#include "twilio.hpp"
#include <ESP8266WebServer.h>
#include <WiFiManager.h>

#define FIREBASE_HOST "***"
#define FIREBASE_AUTH "***"
const char* account_sid = "***";
const char* auth_token = "***";
FirebaseData firebaseData1;
FirebaseData firebaseData2;
FirebaseJson tms;
FirebaseJsonArray arr;
String path = "/Test/Stream";
int sms = 0;
String c;
int b;

#define WIFI_SSID "***"
#define WIFI_PASSWORD "***"

const char fingerprint[] = "BC B0 1A 32 80 5D E6 E4 A2 29 66 2B 08 C8 E0 4C 45 29 3F D0";
String to_number    = "***";
String from_number = "***";
String message_body    = "Hello from Twilio and the ESP8266!";
String master_number    = "***";
String media_url = "";
Twilio *twilio;
ESP8266WebServer twilio_server(8000);
const char* host = "api.twilio.com";
const int   httpsPort = 443;
WiFiClientSecure client;

#if USE_SOFTWARE_SERIAL == 1
#include <SoftwareSerial.h>
extern SoftwareSerial swSer(14, 4, false, 256);
#else
#define swSer Serial
#endif

#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float temp1 = 0;

unsigned long sendDataPrevMillis = 0;

void printResult(FirebaseData &data);
void printResult(StreamData &data);
void streamCallback(StreamData data)
{
  Serial.println("Stream Data1 available...");
  Serial.println("STREAM PATH: " + data.streamPath());
  Serial.println("EVENT PATH: " + data.dataPath());
  Serial.println("DATA TYPE: " + data.dataType());
  Serial.println("EVENT TYPE: " + data.eventType());
  Serial.print("VALUE: ");
  printResult(data);
  Serial.println();
}
void streamTimeoutCallback(bool timeout)
{
  if (timeout)
  {
    Serial.println();
    Serial.println("Stream timeout, resume streaming...");
    Serial.println();
  }
}
void setup()
{
  Serial.begin(115200);
  WiFiManager wm;
  bool res;
  res = wm.autoConnect("AutoConnectAP", "password");
  if (!res) {
    Serial.println("Failed to connect");
  }
  else {
    Serial.println("connected");
  }
  twilio = new Twilio(account_sid, auth_token, fingerprint);
  twilio_server.begin();
  sensors.begin();
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

  firebaseData1.setBSSLBufferSize(1024, 1024);
  firebaseData1.setResponseSize(1024);
  firebaseData2.setBSSLBufferSize(1024, 1024);
  firebaseData2.setResponseSize(1024);
  if (!Firebase.beginStream(firebaseData1, path))
  {
    Serial.println("------------------------------------");
    Serial.println("Can't begin stream connection...");
    Serial.println("REASON: " + firebaseData1.errorReason());
    Serial.println("------------------------------------");
    Serial.println();
  }
  Firebase.setStreamCallback(firebaseData1, streamCallback, streamTimeoutCallback);
}

void loop()
{
  if (millis() - sendDataPrevMillis > 5000)
  {
    sendDataPrevMillis = millis();

    sensors.requestTemperatures();
    temp1 = sensors.getTempCByIndex(0);
    Serial.print("");

    tms.set(".sv", "timestamp");
    Serial.print("FIRST HEAP");
    Serial.println(ESP.getFreeHeap());
    firebaseData2.pauseFirebase(false);

    if (Firebase.getString(firebaseData2, "002/alarm")) {
      if (firebaseData2.dataType() == "string") {
        Serial.println(firebaseData2.stringData());
      }
    } else {
      Serial.println(firebaseData2.errorReason());
    }

    int myInt = firebaseData2.stringData().toInt();
    firebaseData2.clear();

    Serial.println("HEAP BEFORE SET");
    Serial.println(ESP.getFreeHeap());
    if (temp1 < myInt) {
      if (Firebase.setInt(firebaseData2, "/serial/sms", sms))
      {
        printResult(firebaseData2);
      }
      else {
        Serial.print(firebaseData2.errorReason());
      }
    }
    firebaseData2.clear();

    if (temp1 > myInt) {
      firebaseData2.clear();
      Serial.print("HEAP BEFORE SENDING MESSAGE");
      Serial.println(ESP.getFreeHeap());
      String response;
      bool success = twilio->send_message(
                       to_number,
                       from_number,
                       message_body,
                       response,
                       media_url
                     );
     if (!client.connect(host, httpsPort)) {
    Serial.println("- Connection failed.");
    char buf[200];
                int err = client.getLastSSLError(buf, 199);

                buf[199] = '\0';

                Serial.println("Last SSL error was:");

                Serial.println(buf);

                Serial.print("ERRCODE: ");
                Serial.println(err);
     }
    }
    else {
      firebaseData2.clear();
    }
    Serial.print("HEAP BEFORE PUSH");
    Serial.println(ESP.getFreeHeap());
    delay(0);
    arr.clear();
    arr.set("/[0]", temp1);
    arr.set("/[1]", tms);
    firebaseData2.pauseFirebase(false);
    if (Firebase.push(firebaseData2, path + "/Int", arr))
    {
      //      Serial.println("PASSED");
      //      Serial.println("PATH: " + firebaseData2.dataPath());
      //      Serial.println("TYPE: " + firebaseData2.dataType());
      //      Serial.print("VALUE: ");
      //      printResult(firebaseData2);
      //      Serial.println("------------------------------------");
      //      Serial.println();
    }
    else
    {
      //      Serial.println("FAILED");
      //      Serial.println("REASON: " + firebaseData2.errorReason());
      //      Serial.println("------------------------------------");
      //      Serial.println();
    }
    firebaseData2.pauseFirebase(true);
    firebaseData1.pauseFirebase(true);
    firebaseData1.clear();
    firebaseData2.clear();
    Serial.print("LAST HEAP");
    Serial.println(ESP.getFreeHeap());
  }
}

//Helper function for printing the response/received data
void printResult(FirebaseData &data)
{
  if (data.dataType() == "int")
    Serial.println(data.intData());
  else if (data.dataType() == "float")
    Serial.println(data.floatData(), 5);
  else if (data.dataType() == "double")
    printf("%.9lf\n", data.doubleData());
  else if (data.dataType() == "boolean")
    Serial.println(data.boolData() == 1 ? "true" : "false");
  else if (data.dataType() == "string")
    Serial.println(data.stringData());
  else if (data.dataType() == "json")
  {
    Serial.println();
    FirebaseJson &json = data.jsonObject();
    //Print all object data
    Serial.println("Pretty printed JSON data:");
    String jsonStr;
    json.toString(jsonStr, true);
    Serial.println(jsonStr);
    Serial.println();
    Serial.println("Iterate JSON data:");
    Serial.println();
    size_t len = json.iteratorBegin();
    String key, value = "";
    int type = 0;
    for (size_t i = 0; i < len; i++)
    {
      json.iteratorGet(i, type, key, value);
      Serial.print(i);
      Serial.print(", ");
      Serial.print("Type: ");
      Serial.print(type == FirebaseJson::JSON_OBJECT ? "object" : "array");
      if (type == FirebaseJson::JSON_OBJECT)
      {
        Serial.print(", Key: ");
        Serial.print(key);
      }
      Serial.print(", Value: ");
      Serial.println(value);
    }
    json.iteratorEnd();
  }
  else if (data.dataType() == "array")
  {
    Serial.println();
    //get array data from FirebaseData using FirebaseJsonArray object
    FirebaseJsonArray &arr = data.jsonArray();
    //Print all array values
    Serial.println("Pretty printed Array:");
    String arrStr;
    arr.toString(arrStr, true);
    Serial.println(arrStr);
    Serial.println();
    Serial.println("Iterate array values:");
    Serial.println();
    for (size_t i = 0; i < arr.size(); i++)
    {
      Serial.print(i);
      Serial.print(", Value: ");
      FirebaseJsonData &jsonData = data.jsonData();
      //Get the result data from FirebaseJsonArray object
      arr.get(jsonData, i);
      if (jsonData.typeNum == FirebaseJson::JSON_BOOL)
        Serial.println(jsonData.boolValue ? "true" : "false");
      else if (jsonData.typeNum == FirebaseJson::JSON_INT)
        Serial.println(jsonData.intValue);
      else if (jsonData.typeNum == FirebaseJson::JSON_FLOAT)
        Serial.println(jsonData.floatValue);
      else if (jsonData.typeNum == FirebaseJson::JSON_DOUBLE)
        printf("%.9lf\n", jsonData.doubleValue);
      else if (jsonData.typeNum == FirebaseJson::JSON_STRING ||
               jsonData.typeNum == FirebaseJson::JSON_NULL ||
               jsonData.typeNum == FirebaseJson::JSON_OBJECT ||
               jsonData.typeNum == FirebaseJson::JSON_ARRAY)
        Serial.println(jsonData.stringValue);
    }
  }
  else
  {
    Serial.println(data.payload());
  }
}
//Helper function for printing the response/received stream data
void printResult(StreamData &data)
{
  if (data.dataType() == "int")
    Serial.println(data.intData());
  else if (data.dataType() == "float")
    Serial.println(data.floatData(), 5);
  else if (data.dataType() == "double")
    printf("%.9lf\n", data.doubleData());
  else if (data.dataType() == "boolean")
    Serial.println(data.boolData() == 1 ? "true" : "false");
  else if (data.dataType() == "string" || data.dataType() == "null")
    Serial.println(data.stringData());
  else if (data.dataType() == "json")
  {
    Serial.println();
    FirebaseJson *json = data.jsonObjectPtr();
    //Print all object data
    Serial.println("Pretty printed JSON data:");
    String jsonStr;
    json->toString(jsonStr, true);
    Serial.println(jsonStr);
    Serial.println();
    Serial.println("Iterate JSON data:");
    Serial.println();
    size_t len = json->iteratorBegin();
    String key, value = "";
    int type = 0;
    for (size_t i = 0; i < len; i++)
    {
      json->iteratorGet(i, type, key, value);
      Serial.print(i);
      Serial.print(", ");
      Serial.print("Type: ");
      Serial.print(type == FirebaseJson::JSON_OBJECT ? "object" : "array");
      if (type == FirebaseJson::JSON_OBJECT)
      {
        Serial.print(", Key: ");
        Serial.print(key);
      }
      Serial.print(", Value: ");
      Serial.println(value);
    }
    json->iteratorEnd();
  }
  else if (data.dataType() == "array")
  {
    Serial.println();
    //get array data from FirebaseData using FirebaseJsonArray object
    FirebaseJsonArray *arr = data.jsonArrayPtr();
    //Print all array values
    Serial.println("Pretty printed Array:");
    String arrStr;
    arr->toString(arrStr, true);
    Serial.println(arrStr);
    Serial.println();
    Serial.println("Iterate array values:");
    Serial.println();
    for (size_t i = 0; i < arr->size(); i++)
    {
      Serial.print(i);
      Serial.print(", Value: ");
      FirebaseJsonData *jsonData = data.jsonDataPtr();
      //Get the result data from FirebaseJsonArray object
      arr->get(*jsonData, i);
      if (jsonData->typeNum == FirebaseJson::JSON_BOOL)
        Serial.println(jsonData->boolValue ? "true" : "false");
      else if (jsonData->typeNum == FirebaseJson::JSON_INT)
        Serial.println(jsonData->intValue);
      else if (jsonData->typeNum == FirebaseJson::JSON_FLOAT)
        Serial.println(jsonData->floatValue);
      else if (jsonData->typeNum == FirebaseJson::JSON_DOUBLE)
        printf("%.9lf\n", jsonData->doubleValue);
      else if (jsonData->typeNum == FirebaseJson::JSON_STRING ||
               jsonData->typeNum == FirebaseJson::JSON_NULL ||
               jsonData->typeNum == FirebaseJson::JSON_OBJECT ||
               jsonData->typeNum == FirebaseJson::JSON_ARRAY)
        Serial.println(jsonData->stringValue);
    }
  }
}
```

Thanks for your help in advance!

title: Can't send Twilio SMS using Nodemcu esp8266

Answers: 0


body:
I want to read 2 separate voltage readings by AD7705 ADC and send the data to Arduino(Master). What is the correct program flow should I implement to get dual-channel operation working. How data will be sent to master when both the channels are converting the voltage.

Thanks in Advance.

title: Dual Channel Reading with 16 bit AD7705(SPI)

Answers: 0


body:
I have this little AtTiny45 which I'm loading a program with Arduino as ISP.

My goal to use this chip along with a op amp, a piezo buzzer and a press button, and have it automatically sleep between uses.

I intend to use 2 3V pill batteries in parallel (specifically [CR2032](https://www.amazon.ca/Maxell-CR2032-Lithium-Batteries-Version/dp/B07VH3VRCJ/ref=sxts_sxwds-bia-wc-drs-ajax1_0?cv_ct_cx=CR2032&dchild=1&keywords=CR2032&pd_rd_i=B07VH3VRCJ&pd_rd_r=dc117175-f9aa-4cd5-8c64-d6edb19fd43f&pd_rd_w=4dUsA&pd_rd_wg=ck2Vq&pf_rd_p=23dc26fa-d34b-4922-8a43-bae5e960ed0f&pf_rd_r=0402J9JTYWJM0114SW3C&psc=1&qid=1602134636&sr=1-1-25b07e09-600a-4f0d-816e-b06387f8bcf1 "Amazon Link") if this makes a difference) as the power source, so here are my two questions:

 - Can 2 3V pill batteries in parallel power a small application that will produce audible sound?
 - How long could these batteries last *--based on constant use--* **if someone used this item for an hour per day**?

title: Arduino IDE on Attiny45: What kind of power does a chip need?

Answers: 0


body:
This piece of code was taken from AMIS30543- Arduino library,
```c++
void init(uint8_t slaveSelectPin) {
    ssPin = slaveSelectPin;
    digitalWrite(ssPin, HIGH);
    pinMode(ssPin, OUTPUT);
}
```

Facts I know

 - digitalWrite - makes the pin to the corresponding voltage level
 - pinMode - makes the pin either input or output
 - ssPin is active low pin usually.

So I was wondering before setting the pinDirection why the pin is made HIGH, Then immediately after that the pinDirection was declared as OUTPUT

Also I know , if a pin was made HIGH and on the next line if the direction of the same is set as  INPUT will bring the internal pull up resistor in action .

So what am I missing here. More over in Arduino does the order of pinMode/digitalWrite matter.? if So what is the meaning of this particular lines of code [Github link to the library][1]

  [1]: https://github.com/pololu/amis-30543-arduino/blob/master/AMIS30543.h

title: AMIS30543 - Library code | Order of pinDirection and pinOut

Answers: 2

body:
The library is doing this to make sure, that the pin will never go low during initialization.

Imagine doing it the other way round:

    pinMode(ssPin, OUTPUT);
    digitalWrite(ssPin, HIGH);

If the corresponding PORT bit is set to zero (LOW) previously (which is also the standard after reset/power cycle), the pin will go LOW for a very short time, until `digitalWrite()` sets it HIGH again. That LOW time is short, but it might needlessly activate the slave. If you first use `digitalWrite(ssPin, HIGH)`, you activate the internal pullup (as standard mode after reset/power cycle is INPUT) and set the corresponding PORT bit to 1. Thus, when you now change the pin mode, the pin is HIGH immediately, without ever going to LOW in between.

Internally the Arduino uses 3 SFRs (Special Function Registers), which are directly connected to the IO hardware of the pins. The `DDR` register of each port controls the "pin mode" aka direction of the pin (input or output). The `PORT` register controls the output value (HIGH or LOW; or turning the pullup resistor on or off in input mode). The `PIN` register reflects the current state of the pin (for reading it). In this case the double function of the `PORT` register is important, as it activates the internal pullup resistor, when set while in input mode.

body:
This initialization will work with [spi communication][1] for PIC32 microchip too?

  [1]: https://911electronic.com/spi-communication-how-spi-works/


body:
I am trying to sense the temperature using the LM70 temperature sensor with an Arduino Mega. As you can see in the Datasheet, it uses the SPI protocol. I have made the following connections (VSSOP-8 Package):
- SI/O pin --> Pin 50 Arduino Mega.
- SC pin --> Pin 52 Arduino Mega.
- CS pin --> Pin 53 Arduino Mega.
- V+ pin --> 3.3V Arduino Mega.
- GND pin --> GND Arduino Mega.

My code does not work (it does not print the right temperature), and I think it can be for two reasons:
1. I am not reading correctly the information from the sensor. It sends 16 bits, from which the 11 first bits store the data for the temperature.
2. I am not calculating the temperature in the right way.

This is my code:

    // the sensor communicates using SPI, so include the library:
    #include <SPI.h>

    void setup() {
      pinMode(51,OUTPUT); //MOSI
      pinMode(50,INPUT); //MISO
      pinMode(52,OUTPUT); //CLOCK PIN
      digitalWrite(53,HIGH); //slave select stays high. When we set this to low, the sensor will start to send data.
      SPI.begin();
      Serial.begin(9600);

      //time to set up
      delay(500);
    }

    void loop() {
        //enable Slave
        digitalWrite(A0,LOW); //Enable communication with slave
        delay(500); //wait for conversion

        int val = SPI.transfer(0x00); // read from sensor
        Serial.println(val); //display reading on serial monitor
        int temperature = val * 0.25;
        Serial.println(temperature); //display temperature on serial monitor

        //disable Slave
        digitalWrite(53,HIGH); //set to High again
    }

Please, if you see something wrong in my code, let me know.
Thank you in advance.

title: Using LM70 temperature sensor with Arduino

Answers: 2

body:
There are several things that are not doing correctly. This is not a complete answer but to provide you some directions on how to get it right.

1) `A0` is pin 54, it is not `SS` which is pin 53;

2) On how to use the SPI library properly, I would suggest that you read my blog on [SPI](https://www.e-tinkers.com/2020/03/do-you-know-arduino-spi-and-arduino-spi-library/), it will also help you to get the data out of data sheet that you need for SPI programming. Based on the timing diagram on the data sheet, you will need to configure the SPI as `SPI_MODE2`;

3) LM70 SI/O pin is used as both MOSI and MISO, you will need to connect MOSI to SI/O via a 10k resistor, and connect SI/O direct to MISO, this information is available in the data sheet;

4) LM70's temperature data is in [Two's complement format](https://en.wikipedia.org/wiki/Two's_complement), To convert it, it needs a little bit work. It is then need to shift down/right using [bitshift](https://www.arduino.cc/en/pmwiki.php?n=Reference/Bitshift) operator by 5 bits to get ride of the first 5-bits, before finally multiply by 0.25C as per data sheet.

```
int value = 0x4b1f;  //value from SPI, temp = 125 degree C
int mask = 0x8000;   // mask for MSB
int temp = (-(value & mask) + (value & ~mask)) >> 5;
Serial.print("Temp");
Serial.println(temp*.25);
```
Read all links that I provided to understand the subjects and give it a try. Good luck!

body:
Your problem lies here:

```
    int val = SPI.transfer(0x00); // read from sensor
    Serial.println(val); //display reading on serial monitor
    int temperature = val * 0.25;
```

And it's a twofold problem.

First:

```
int val = SPI.transfer(0x00);
```

That only reads the first 8 bits of the data. To get all 16 bits you have to do two transfers and then combine them together with bitshifting:

```
int bh = SPI.transfer(0x00);
int bl = SPI.transfer(0x00);
int val = (bh << 8) | bl;
```

That then gives you a value that is right-aligned. you then need to shift it to the left the right number of bits and "sign extend" it to keep it negative if needed.  If you're not interested in the fractional part then it's as simple as:

```
val >>= 7;
if (val & 0x0100) {
    val |= 0xFE00;
}
```
Now... what does that all mean?  Well, assume it's currently 25°C. From the datasheet we can see that would give us a reading of `0000 1100 1001 1111` (note there is a typo in the datasheet saying that is 0b9f in hex when in fact it's 0c9f).

Let's do those operations - first the bit shift:

```
Dec   Hex   Bin
3231  0C9F  0000110010011111 >> 7
25    0019  0000000000011001
```

Then we look to see if bit 8 is set or not (bit 8 was the most significant bit). If it is then we OR it with bits 9-15 also set. This "sign extends" it.

Let's take a look at -25°C from the datasheet:

```
Dec   Hex  Bin
-3169 f39f 1111001110011111 >> 7      Shift right 7 bits
487   01e7 0000000111100111 & 0x0100  And with 8th bit
256   0100 0000000100000000           Result is not 0 so is true

"Or" the shifted value with 0xFE00:

487   01e7 0000000111100111 or
65024 fe00 1111111000000000 =
-25   ffe7 1111111111100111
```


body:
Edit: Took some advice from below but it still doesn't work. I think it probably blocking code but please tell me how I could fix it to send a the valid infrared signal, NOTE: I wouldn't actually code it like this I am just trying to learn and understand how to do it and then make it better after:

    uint8_t Status;
    uint8_t Counter;
    const uint32_t Code[] = {4507,4507,573,1694,573,1694,573,1694,573,573,573,573,573,573,573,573,573,573,573,1694,573,1694,573,1694,573,573,573,573,573,573,573,573,573,573,573,573,573,1694,573,573,573,573,573,573,573,573,573,573,573,573,573,1694,573,573,573,1694,573,1694,573,1694,573,1694,573,1694,573,1694,573,46560};

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

    void loop() {
      while(Counter<70) {
        if (Status=1) {
            digitalWrite(4, HIGH);
            Status=3;
            while(Status=3) {
              delayMicroseconds(26);
              digitalWrite(4, HIGH);
              delayMicroseconds(26);
              digitalWrite(4, LOW);
            }
            delayMicroseconds(Code[Counter]);
            Status=2;
            Counter++;
        } else {
          if (Status=2) {
            digitalWrite(4, LOW);
            Status=0;
            while(Status=0) {
              delayMicroseconds(26);
              digitalWrite(4, HIGH);
              delayMicroseconds(26);
              digitalWrite(4, LOW);
            }
            delayMicroseconds(Code[Counter]);
            Status=1;
            Counter++;
          }
        }
      }
    }

title: Infrared sending not working slight misconfiguration?

Answers: 1

body:
There are two basic things wrong here - one with your understanding of the timings, and the other with your understanding of how IR communication works.

First the timings - those are both ON *and* OFF timings. You don't just turn on for a defined length of time - you turn on for a defined length of time *and then turn off for another defined length of time*.

So for the timings in your code `4507,4507,573,1694,573,...etc...` you would:

* Turn on
* Wait 4507us
* Turn off
* Wait 4507us
* Turn on
* Wait 573us
* Turn off
* Wait 1694us
* Turn on
* Wait 573us
* ... etc ...

You have no "off" time in your code, only ever on times.

Secondly is your understanding of IR communications. It does not involve turning an LED on or off for defined times. It's not as simple as that. Instead you are controlling the *modulation* of an LED.  When the LED of an IR remote control is "on" it's not just turned on - it's rapidly turning on and off. The receiver looks for the presence or absence of this rapid turning on and off light. This is the "carrier frequency" of the signal and must match what the receiver is looking for.

Typically this is between 30kHz and 50kHz depending on the receiver.

So you need some way of generating that rapid on-off signal. Normally this is done using PWM by the IR libraries and switching between 0% and 50% duty cycle for the off and on periods of the signal you want to send.

So it's far simpler to just use a library that does all this underlying work for you.


body:
Is it possible to build an serial-adapter with digispark board?
Like: Embedded System with 2-wire RS-485 Port connect to my digispark board. Digispark Board is connected via USB to my Computer (running Linux tty or Windows COM Putty Interface)

I also own a Raspberry Pi. I'm very new at this thing, so maybe there is a way to convert the RS485 signals to monitoring my devices with my computer?

title: Building RS485 serial to USB adapter with digispark

Answers: 2

body: There are some good books available to help. There is the Raspberry Pi cookbook and the Arduino cookbook. These will take you from the very beginning to the point where you can make your own designs and they will work.

body:
I would steer you away from using something that has a chip with neither a USART nor USB hardware for the purposes of making something like that. The ATTiny85 that's on the Digispark has USI (Universal Serial Interface), which is really more of a USART construction kit. The USB support it has is bitbanged and somewhat unreliable.

If you do go in this direction and want a small Arduino type board like Digispark, the "Beetle" ATMega32u4 based boards are a better choice.  It has a native USB interface, and a proper USART to hook to an RS-485 driver.

The chip also has a bootloader section; it is difficult to corrupt your own sketch.  It also has more memory, not that you necessarily need it.


body:
Before you close this saying it's not related to programming. It is related to programming since i'm using it and asking about libraries.

What are the common types of communication protocols and their libraries? Theres WiFi which uses esp8266 etc. Zigbee which can be used with XBee, Bluetooth which can be used with esp32 and others.
What are a list of wireless protocols and chips and libraries for those wireless communications? (This list will be compiled by multiple people hopefully so its okay if you don't know the library or chip but protocol is good) thank you and hopefully no take down <3

title: What wireless protocols can be used with arduino?

Answers: 1

body:
Arduino allows you to connect external peripherals (via I2C, SPI, UART, I/O) and shields.

It'll be impossible to list them all, as you can even make your own; but here an overview of the most common I can think off:

 - WiFi
 - Bluetooth
 - LoRa
 - Zigbee
 - Z-wave
 - RF (433mhz)
 - InfraRed
 - GSM/LTE

It'll be a trade-off between signal range, power usage, delay and bandwidth.

Do note that your question in this way is quite broad. If you want to use this to start your own wireless proejct, you can follow these steps (, but do note that we expect one to do some research/tests himself before posting a question):

 1. Find a tranmission layer applicable for your project based on requirements.
 2. Find Arduino compatible hardware (if none found; make your own or find another transmission layer / adjust requirements)
 3. Find libraries/examples of this hardware being used with Arduino.
 4. Buy the hardware (this is not step 1!)
 5. Use the found sources and make your project reality.


body:
[![enter image description here][1]][1]Hi,

I'm designing a custom board with the ATMEGA32U4, with a GPS receiver and LoRa radio and it is powered from a LiPo battery. Since I'll need to make hundreds of this board later on, I'd like to program them over USB. I started out from the Arduino Pro Micro schematic and I use an 8MHz crystal. I'm able to make use of the factory default USB bootloader and upload Arduino sketches using the dfu-programmer in **Linux**. My first problem was that the blink example didn't really blink at 0.5Hz rate(delay(1000) wasn't 1sec), but much-much slower. No worries, reduce the delay a little bit. However, when I want to communicate with the GPS, the from the transmitted signal, I can see that the baud rate is not correct. I suspect that the clock settings are not correct. I read that these can be changed with the help of fuses, but as far as I know, they cannot be modified using only USB , I need a programmer for that, which I'd like to avoid.
(Correct me if I'm wrong here)

So my question is, how do I set up the MCU correctly, so that it runs from the 8MHz external or 8MHz internal clock using only USB? Is it even possible?

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

title: Clocking issues while programming ATMEGA32U4-AU via USB bootloader

Answers: 0


body:
I have an ESP32 application that uses a web server as a user interface. For auditing and debugging during development I use Serial; however, that is impractical in the installed system. So, I decided to use Telnet (TCP/IP) to monitor what is happening when Serial is impractical.

The issue is that once a TCP/IP session has been established, when a HTTP request is received, the TCP/IP session is aborted.

I have reproduced the issue in a minimal sketch here:

```
#include "Arduino.h"
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

WiFiClient telnetClient;
WebServer server(80);
WiFiServer telnetServer(23);

void telnetPrint(const char* text)
{
  if (telnetClient)
  {
    telnetClient.print(text);
  }
}

void telnetPrintln(const char *text)
{
  telnetPrint(text);
  telnetPrint("\r\n");
}

void _print(const char* text)
{
  Serial.print(text);
  telnetPrint(text);
}

void _println(const char* text)
{
  Serial.println(text);
  telnetPrintln(text);
}

void _println(IPAddress myIP)
{
  char rgIPTxt[32];
  sprintf(rgIPTxt,"%u.%u.%u.%u",myIP[0],myIP[1],myIP[2],myIP[3]);
  _println(rgIPTxt);
}

const char *rootFmt="\
<html>\
  <head>\
    <title>Test</title>\
  </head>\
  <body>\
    <h1>Test</h1>\
    <div>\
      <h2>Heap size=%d<br><br>\
    </div>\
  </body>\
</html>\
";

char rootMessage[1024];

void updateRootMessage()
{
  _println("updateRoot");
  snprintf(rootMessage, sizeof(rootMessage), rootFmt,
           heap_caps_get_free_size(MALLOC_CAP_8BIT)
           );
}

void handleRoot()
{
  _println("Entered handleRoot");
  updateRootMessage();
  server.send(200, "text/html", rootMessage);
  _println("Leaving handleRoot");
}

void wifiSTASetup(const char*ssid, const char*password)
{
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);
  telnetServer.begin();
  telnetClient=telnetServer.available();
  _println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    _print(".");
  }
  _println("");
  _print("Connected to ");
  _println(ssid);
  _print("IP address: ");
  _println(WiFi.localIP());
  server.on("/", handleRoot);
  server.begin();
}

#define BAND    915E6

void setup()
{
  Serial.begin(115200);
  wifiSTASetup("your ssid", "your password");
}

void loop()
{
  server.handleClient();
  if (!telnetClient)
  {
    telnetClient=telnetServer.available();
    if (telnetClient)
    {
      _println("telnetClient obtained");
    }
  }

}
```

title: ESP32 HTTP Server request interrupts Telnet session

Answers: 0


body:
I'm working on a simple ADC project, the goal is to adjust the on/off of the LEDs according to the binary reading (1-on,0-off). I've tried this with 8 bit, and it works as intended. But on 10 bit, two of the LEDs with representation of 2^8 and 2^9 won't turn on even though the reading on the serial monitor is 1023 (should be 1111111111 -all LEDs on). I wonder if there's anything wrong with my code or circuit?
(I'm totally new to arduino, sorry for the noobness)
-I'm using Arduino UNO R3, the details are shown in the image[![enter image description here][1]][1]

    void setup(){
      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(4, OUTPUT);

      Serial.begin(9600);
    }

    void loop(){
      int sensorValue = analogRead(A0);
      Serial.print("Decimal=");
      Serial.print(sensorValue);
      Serial.print("\tBinary=");
      Serial.println(sensorValue,BIN);

      if(sensorValue>=0&&sensorValue<=1023){
        digitalWrite(4,(sensorValue&1));
        digitalWrite(5,(sensorValue&2));
        digitalWrite(6,(sensorValue&4));
        digitalWrite(7,(sensorValue&8));
        digitalWrite(8,(sensorValue&16));
        digitalWrite(9,(sensorValue&32));
        digitalWrite(10,(sensorValue&64));
        digitalWrite(11,(sensorValue&128));
        digitalWrite(12,(sensorValue&256));
        digitalWrite(13,(sensorValue&512));
      }
      delay(20);
    }

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

title: Arduino binary LED 10 bit display

Answers: 2

body:
Seems, digitalWrite does not take any `int` != 0 as HIGH

Rather consider supplying a boolean (one byte value)

       digitalWrite(12,(sensorValue&256)==256);
       digitalWrite(12,(sensorValue>>8)&1);
or similar

body:
According to [the official documentation][doc], the second parameter of
`digitalWrite()` should be either `HIGH` or `LOW`. Thus, in order to be
compliant with the published API, you are supposed to write:

```c++
digitalWrite(12, sensorValue&256 ? HIGH : LOW);
```

In practice, `digitalWrite()` interprets any non-zero value as `HIGH`.
However, [its prototype][proto] is:

```c++
void digitalWrite(uint8_t pin, uint8_t val);
```

Both parameters have the type `uint8_t`, which means “8-bit unsigned
integer”. If you provide a value that doesn't fit in 8 bits, the
implicit cast to `uint8_t` will reduce it modulo 28. Thus,
both 256 and 512 become zero through the implicit cast.

[doc]: https://www.arduino.cc/reference/en/language/functions/digital-io/digitalwrite/
[proto]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/Arduino.h#L135


body:
I'm using this working library to extract H2 & Alcohol in PPM from sensors.

UPDATE
I read the readme file and used the example shown.
But this gives me an error.

This is the code:

      //Include the library
    #include <MQUnifiedsensor.h>
    /************************Hardware Related Macros************************************/
    #define         Board                   ("Arduino UNO")
    #define         Pin                     (A4)  //Analog input 4 of your arduino
    /***********************Software Related Macros************************************/
    #define         Type                    ("MQ-4") //MQ4
    #define         Voltage_Resolution      (5)
    #define         ADC_Bit_Resolution      (10) // For arduino UNO/MEGA/NANO
    #define         RatioMQ4CleanAir        (4.4) //RS / R0 = 60 ppm
    /*****************************Globals***********************************************/
    //Declare Sensor
    MQUnifiedsensor MQ4(Board, Voltage_Resolution, ADC_Bit_Resolution, Pin, Type);
    // Setup
    MQ4.setRegressionMethod("Exponential"); //_PPM =  a*ratio^b
    MQ4.setA(1012.7); MQ4.setB(-2.786); // Configurate the ecuation values to get CH4 concentration
    MQ4.setR0(3.86018237); // Value getted on calibration
    // Loop
    MQ4.init();
    MQ4.update();
    float ppmCH4 = MQ4.readSensor();

And the error:

Arduino: 1.8.13 (Mac OS X), Board: "WeMos D1 R1, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), v2 Lower Memory, Disabled, None, Only Sketch, 921600"

MQ4:17:1: error: 'MQ4' does not name a type
 MQ4.setRegressionMethod("Exponential"); //_PPM =  a*ratio^b
 ^
MQ4:18:1: error: 'MQ4' does not name a type
 MQ4.setA(1012.7); MQ4.setB(-2.786); // Configurate the ecuation values to get CH4 concentration
 ^
MQ4:18:19: error: 'MQ4' does not name a type
 MQ4.setA(1012.7); MQ4.setB(-2.786); // Configurate the ecuation values to get CH4 concentration
                   ^
MQ4:19:1: error: 'MQ4' does not name a type
 MQ4.setR0(3.86018237); // Value getted on calibration
 ^
MQ4:21:1: error: 'MQ4' does not name a type
 MQ4.init();
 ^
MQ4:22:1: error: 'MQ4' does not name a type
 MQ4.update();
 ^
exit status 1
'MQ4' does not name a type

title: Need PPM out of MQ4 sensor

Answers: 0


body:
I'm trying to create an IMU unit using MPU-6050 unit.

I've got 100k data records, and this is the result:

[![Gyro x,y,z readings][1]][1]

It seems to me that's a kind of offset in gx. Why?

[![Accel x,y,z][3]][3]

Why I'm getting this kind of drifting in acz?

This is the setup code:

    void setup_mpu_6050_registers(){

      //Activate the MPU-6050

      //Start communicating with the MPU-6050
      Wire.beginTransmission(0x68);
      //Send the requested starting register
      Wire.write(0x6B);
      //Set the requested starting register
      Wire.write(0x00);
      //End the transmission
      Wire.endTransmission();

      //Configure the accelerometer (+/-8g)

      //Start communicating with the MPU-6050
      Wire.beginTransmission(0x68);
      //Send the requested starting register
      Wire.write(0x1C);
      //Set the requested starting register
      Wire.write(0x10);
      //End the transmission
      Wire.endTransmission();

      //Configure the gyro (500dps full scale)

      //Start communicating with the MPU-6050
      Wire.beginTransmission(0x68);
      //Send the requested starting register
      Wire.write(0x1B);
      //Set the requested starting register
      Wire.write(0x08);
      //End the transmission
      Wire.endTransmission();

    }

And this is the reading code:

    void read_mpu_6050_data(){

      //Read the raw gyro and accelerometer data

      //Start communicating with the MPU-6050
      Wire.beginTransmission(0x68);
      //Send the requested starting register
      Wire.write(0x3B);
      //End the transmission
      Wire.endTransmission();
      //Request 14 bytes from the MPU-6050
      Wire.requestFrom(0x68,14);
      //Wait until all the bytes are received
      while(Wire.available() < 14);

      //Following statements left shift 8 bits, then bitwise OR.
      //Turns two 8-bit values into one 16-bit value
      myData.msecs = millis();
      myData.acc_x = Wire.read()<<8|Wire.read();
      myData.acc_y = Wire.read()<<8|Wire.read();
      myData.acc_z = Wire.read()<<8|Wire.read();
      myData.temp = Wire.read()<<8|Wire.read();
      myData.gyro_x = Wire.read()<<8|Wire.read();
      myData.gyro_y = Wire.read()<<8|Wire.read();
      myData.gyro_z = Wire.read()<<8|Wire.read();
    }

The structure that stores data is:

    struct datastore {
       long msecs;
       int acc_x, acc_y, acc_z;
       int temp;
       int gyro_x, gyro_y, gyro_z;
    };

Then I save data in the card:

    logFile.write((const uint8_t *)&myData, sizeof(myData));

  [1]: https://i.stack.imgur.com/KCqkc.png
  [2]: https://i.stack.imgur.com/DqMQ3.png
  [3]: https://i.stack.imgur.com/1g4fn.png

title: Getting some strange data from an MPU-6050

Answers: 0


body:
I'm a newcomer to Arduino, trying to read analog values from a circuit with a photoresistor. I believe I am using a 1-ohm resistor

The problem I am having is that my photoresistor does not seem to be working, or my circuit is wrong. When I run the below code on my Nano, my Serial monitor constantly prints 1023. When I cover the photoresistor completely with my finger, the value dips down to 900-950, but then jumps back up to 1023. It dips down to 900-950 again, and jumps back to 1023. This happens continuously.

Here is my code:

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

void loop()
{
  int value = analogRead(A0);
  Serial.println(value);
  delay(20);
}
```

Here is an image of the circuit I am using. In my case, I am using a Nano instead of Uno.

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

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

I ran the above code on the virtual circuit above, and it works as expected. However, on my physical device, the phenomenon I explained above occurs.

Is there something wrong with my circuit? Could it be an issue with my photoresistor?

title: Photoresistor help

Answers: 1

body:
If you pealed the backing off the bread board you will find that you have plugged in your green, red and photo resistor wires into one piece of metal.  This means they are shorted together and as such do not work as you might expect.

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

Also, be aware that [photo resistor or cadmium sulfide cells][2] are slow to react to changes in light.  Sometimes taking about a second to fully change to a new resistance.  If you need a faster response consider using a photo diode or photo transistor.

  [1]: https://i.stack.imgur.com/yB9UT.jpg
  [2]: https://en.wikipedia.org/wiki/Photoresistor


body:
I am very new to arduino, so new that it is my first board. I keep running into this error

`avrdude: stk500_recv(): programmer is not responding`

`avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00`

I have searched the internet for hours, tried solutions from almost every StackExchange question related to this topic, and even Reddit posts but none of those have been able to help me. All my settings are as they are supposed to be. Both the correct board and serial port are selected but it still keeps giving me this error:

`System wide configuration file is "/home/rahat/Desktop/Arduino/arduino-1.8.13/hardware/tools/avr/etc/avrdude.conf"`

`User configuration file is "/home/rahat/.avrduderc"`

`User configuration file does not exist or is not a regular file, skipping`

       ` Using Port                    : /dev/ttyS4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200`
`
avrdude: stk500_recv(): programmer is not responding` <br>`
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00`

Also my operating system is **Ubuntu 20.04 LTS**

title: My code is not uploading to Arduino Uno, Please help!

Answers: 1

body:
First of all find out on which port the Arduino is connected by running the command : ```dmesg | grep tty```. You should get ```[82893.921017] usb 1-1: cp210x converter now attached to ttyXXX``` with the ```ttyXXX``` COM port.
Then check if the port is visible ```Tools->Port```. If the port is not visible then you have a permission issue.


body:
please I need help with the arduino BMP280 breakout board I got from  AliExpress. I’m pretty new to the arduino world, I need it for my rocket datalogger, I downloaded the adafruit BMP280 library but I don’t know how or where to change the data rate and what does the “default standby time” mean in the library sensor code? I want to get at least 10-20points of data per second as the rocket will be traveling very fast. Can someone please help me with a solution, or if there’s another library that solves my problem. I’m really stuck. Also, I don’t want my code to stop while waiting for temp, pressure and altitude values and also get the altitude before launch so that I can now the approximate height of the rocket above see level. Any help would be appreciated.

Details
Connection type: 12c
Application : Water rocket altimeter/datalogger and flightcomputer.

Brand: Unknown
Microcontroller: Arduino Nano

title: How to use a non-adafruit BMP280 sensor for continuous data outflow

Answers: 0


body:
I am a beginner trying to activate 2 sets of 3 air pistons sequentially by going through the YouTube Tutorials... Help, please, pretty please?? :-)

There are 3 sets of 2 pistons, each set working in opposition.
So I have P1/P2, P3/P4, and P5/P6, each set working in opposition to squeeze at the center sequentially -
Initial state at turn-on/Reset must be:
```
// Step 1 Run Once:
P1 Down/P2 Up  // Move simultaneously (joining at the center) and HOLD in position -
P2 Up/P3 Down  // Move simultaneously and HOLD -
P5 Up/P6 Down  // Move simultaneously and HOLD -
// Wait for Start button -
```
I need to start/stop the sequencing with a toggle push-button -
I have reed-switch sensors that will give me a set of two TRANSIENT contact closure for each piston moving to the Up and Down positions -

Once started, the sequence needs to be as follows:
```
// Loop until Reset button is pushed -
// STEP 2: -
P1 Down/P2 Up (HOLD) // Old Initial State, unchanged -
P3 Down/P4 Up (MOVE) // Piston 3 moves Down/Piston 4 moves Up and HOLDS -
P5 Up/P6 Down (HOLD) // Still Old Initial State, unchanged -
```
// PROBLEM:  P3 Down AND P4 Sensors only give me a TRANSIENT closure:  These two transients MUST occur to initiate Step 3, but  they are not always exactly synched together, so my initial try by putting them in series fails... -
// I need to use that set of contact closures to trigger the next command: -
```
// Step 3: -
// The transient closures of P3 Down/P4 Up Sensors is the trigger needed for -
P5 Down/P6 Up (MOVE) // P5 moves Down/P6 moves Up and HOLD -
P1 Up/P2 Down (MOVE) // P1 moves Up/P2 moves Down and HOLD -
P3 Down/P4 Up (HOLD)  // P3/P4 HOLD -

// Back to Step 2 until the Reset button is pushed -
```
I can send you my attempt at coding for this, but it does not work unless the two sensors close simultaneously, which only happens in simulation...  ARGH..  :-(

Can someone send me a piece of code that will work for this, please?
I would really, really appreciate that...  Very frustrated right now!
You can email me at XXXXXXX.XXXX@XXXXX.XXX or text/call at (XXX)XXX-XXXX
Thanks either way.
Sincerely,
Michael

PS:  I tried to wire for a separate toggle switching for each sensor, but I run out of pins on my Arduino UNO R3... Looking into it via YouTube https://www.youtube.com/watch?v=cAT07gy4DII "Increase the digital outputs on an Arduino (PART 1 & 2)" but that is way more complex...  Trying to wade my way through that now...

title: Sequencing air pistons proble - Help please?

Answers: 1

body:
> it does not work unless the two sensors close simultaneously

If I understand correctly, the problem is that when your Arduino detects
the second transient signal, the first one is not active anymore, and
your program doesn't remember it has already seen that first signal.

Your Arduino has memory. Thousands of bits of memory! So it can remember
quite a few things. The solution to your problem is to simply make use
of that memory. When you detect a signal that should be useful for a
future decision, take note, store it in a variable. In order for the
variable to be remembered across calls of the function where you set it,
it has to be global. Or, better yet, `static` local.

Here is how that could look like in code:

```c++
// A `static' variable is a variable that remembers its state across
// calls of the function. A global variable would do the same, but
// code is usually clearer when variables are defined close to where
// they are used. A `bool' (for "boolean") is a variable that can only
// be either `true' or `false'.
static bool P5_is_up, P6_is_down;

// If the sensor tells us that the P5 piston went all the way up, take
// note of the fact and remember it.
if (digitalRead(P5_up_sensor) == LOW)
    P5_is_up = true;

// Same for P6 going down.
if (digitalRead(P6_down_sensor) == LOW)
    P6_is_down = true;

// If both pistons finished their travel, we can move to the next
// step. `&&' means "and".
if (P5_is_up && P6_is_down)
    goto_step_3();
```

You will need to reset those variables to `false` at the appropriate
time. The example code above doesn't show that as it only deals with the
logic for deciding when it is time to start step 3.

You will probably end up with many of these variables, and lots of
repetitive code. So you will need to structure your program in order to
avoid excessive repetition. But that is not your immediate problem. For
now, try to make the logic work for a single step transition. Once you
get the logic right, you can worry about generalizing the logic to any
transition.


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

I'm trying to make a type of Arduino alarm clock, which when the time I inputed is equals to the current time, a servo will turn on my lights. It basically consists of a Keypad, an RTC DS1307 and a TM1637 seven segment display. The basic idea is that the RTC module would print time to the display until I decide to write something on the keypad, which would clear the time on the display to let me write the alarm. My problem is that the display manages to both show time on the display and write to the display but this only works on separate code, not together.

The keypad has a '\*' and '#' character, when i decide to write the time i want the lights to turn on, after writing it i press the '\*' character to save that time and then the idea would be to compare the time written and the present time, if i press '#', then all would be canceled and the RTC module would continue to show the time on the display. (i have not manage to advance that much due to my error on not being able to clear the display when i want to write on the keypad)

```
#include "Arduino.h"

// KEYPAD
#include "Keypad.h"

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

//define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

char customKey;

byte rowPins[ROWS] = {12, 11, 10, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

// DISPLAY
#include "SevenSegmentTM1637.h"
#include "SevenSegmentExtended.h"

const byte PIN_CLK = 4;   // define CLK pin (any digital pin)
const byte PIN_DIO = 5;   // define DIO pin (any digital pin)
SevenSegmentExtended      display(PIN_CLK, PIN_DIO);

// RTC

#include <Wire.h>
#include <TimeLib.h>
#include <DS1307RTC.h>

void setup(){
    Serial.begin(9600);         // initializes the Serial connection @ 9600 baud
    display.init();
    display.setBacklight(100);  // set the brightness to 10 %
    display.print("ON");      // display INIT on the display
    delay(1000);                // wait 1000 ms
    display.clear();
}

// OTROS

#define digit 4

byte data_count = 0;
char Data[digit];

void loop(){

    tmElements_t tm; // CLOCK

    display.setColonOn(true);
    customKey = customKeypad.getKey();

    if (RTC.read(tm)) {
        display.printTime(tm.Hour, tm.Minute, true);
    }

    if (customKey) { // ACTIVATE KEYPAD

        display.clear();

        if (customKey == '*') { // IF *
            display.blink();

            if (Data[data_count] < 3) {
                error();
            }

        } else if (customKey == '#') { // IF #
            display.blink();
            display.setColonOn(false);
            display.clear();
            clearData();
        } else { // WRITE ON DISPLAY

            Data[data_count] = customKey;
            display.setCursor(0,data_count);
            display.print(Data[data_count]);

            if (data_count < 4) {
                data_count++;
            } else {
                error();
            }
        } // END DISPLAY WRITE

    } // END KEYPAD IF

} // END LOOP

void error() { // DISPLAY ERROR AND DELETE DATA
    display.clear();
    display.setColonOn(false);
    display.print("ERR");
    delay(1000);
    display.clear();
    clearData();
}

void clearData() { // CLEAR DATA
    while (data_count != 0) {
        Data[data_count--] = 0;
    }
}
```

This are the libraries i'm using if it helps:
https://github.com/bremme/arduino-tm1637,
https://github.com/PaulStoffregen/DS1307RTC and the
Keypad library from Arduino library manager

Hope I made myself clear with my problem, english is not my first language, if you want more clarification then let me know!

That is basically what i've got, i'm sorry if the post is too long, i have been struggling with this problem for two days and i don't know how to proceed. Hope you all can help. Thanks!

title: Help in personal alarm clock project, cant write time on seven segment display

Answers: 1

body:
I think your problem is here:

> ```c++
> if (RTC.read(tm)) {
>     display.printTime(tm.Hour, tm.Minute, true);
> }
> ```

This code displays the current time, and it runs on every single loop
iteration. This is visibly not what you want. Your project should have
at least two distinct operational modes: “display the current time” and
“allow the user to input data”. You need a variable to remember which is
the current mode, e.g.

```c++
enum { MODE_DISPLAY_TIME, MODE_DATA_INPUT } mode;
```

You need to precisely define the events that make your program switch
modes, and code specific behaviors for each mode. For example:

```c++
if (mode == MODE_DISPLAY_TIME) {
    if (RTC.read(tm)) {
        display.printTime(tm.Hour, tm.Minute, true);
    }
} else if (mode == MODE_DATA_INPUT) {
    // Handle user input.
}
```

This general approach is called a “finite state machine”. You can read
more about it in [this blog article by Majenko][fsm].

[fsm]: https://majenko.co.uk/blog/finite-state-machine


body:
I am looking for a microcontroller that is small (like a attiny10) which is the smallest one I could find.
Requirements I need: analogRead on 1 pin, 7 pins for analogWrite to micro leds so in total 10 pins (ground, power, analogRead, analogWrite). It's circuitry has to be basic no adding extra things like a crystal oscillator etc.. This will allow me to send a certain code to the recieving pin and then the microcontroller decide which led to turn on.

title: Smallest microcontroller?

Answers: 2

body:
I don't know whether it's really the smallest you can find but... The
[ATtiny84][] has an ADC, more digital pins than you need, and is
available in 3 mm packages (UFBGA and VQFN). There is also an
[Arduino-compatible core][core] available for it.

[ATtiny84]: https://www.microchip.com/wwwproducts/en/ATtiny84
[core]: https://github.com/SpenceKonde/ATTinyCore

body:
I made a Arduino develop board with [ATtiny3217](https://www.e-tinkers.com/2020/07/arduino-compatible-development-board-with-attiny3217/), it has a 24-pin VQFN form factor, but as powerful as ATmega328p, with no external crystal and capable running at 20MHz.

If this is not suitable for you, look into the new [tinyAVR family](https://www.microchip.com/design-centers/8-bit/avr-mcus/device-selection), they are the new generation of ATtiny with more functionalities than the older ATtiny family with the smaller footprint.


body:
We have an Arduino Nano connected to 4 small (0.5") common-anode 7-segment displays and 2 large (3") common-anode 7-segment displays. We are trying to multiplex the displays. The larger one requires more power than the smaller one (9V) which the shift register cannot supply.

Therefore, we have supplied 9V to the open drain outputs of the shift register that are connected to the larger displays with a pull-up resistor (390ohm). However, more power (7.5V) goes to the resistor than the display (1.5V).

They are connected like in the [ShiftDisplay library's schematic][1], with a pull-up resistor added according to [this link on open drain][2].

How do we use the open drain outputs logic to supply power to the display?

The data sheet of the big 7-segment display can be [found here][3]. Each display requires 160mA of continuous current.

  [1]: https://github.com/MiguelPynto/ShiftDisplay
  [2]: https://forum.digikey.com/t/what-does-open-drain-mean/716
  [3]: https://cdn.reignofcomputer.com/images/1637378503422487352_5cab8653-2a2f-4dfb-8d5a-1ee1585e736e.png

title: TPIC6B595 Output Unable to Allow Supplied Power to 7-segment Display

Answers: 2

body:
You are getting confused. The pullup resistor is only needed on open drain when you are using it to generate logic levels. It turns the OD output into an RTL output.

You don't want that.

Instead you want your open drain outputs to act like a low-side switch transistor - which is infact what they are.

You can do that by simply placing your LEDs in *series* with your "pullup" resistor, thus:

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

<!-- End schematic -->

I have only shown two elements there (everything inside the dashed box is inside the shift register), but you can see now how when an output is "on" the transistor conducts, and the current flows through the LED, through the resistor, through the transistor, and down to ground.

Your resistor value is then calculated as simply

        9 - Vfled
    R = ---------
          Iled

For 20mA and a 2V forward voltage that comes out as 350Ω - so your 390Ω resistors are perfectly fine.

body: Can you use different resistors for each display group? If so that will solve your problem along with what Majenko said.


body:
I am using the DMP example code to get yaw pitch roll values, mainly I am interested in pitch value for building a self balancing robot. I am trying to display the pitch values on an OLED screen but I am getting FIFO overflow error which is resulting in delayed sampling and sometimes erratic values.

I tried adding a mpu.resetFIFO() after updating the OLED, but its causing a very slow sampling of the sensor.

I am keen on changing the Arduino Uno for a Teensy board(prolly teensy LC). My main concerns are will changing the processor help? Teensy LC runs @48Mhz compared to Arduino Uno which runs @16Mhz.

Also I went through this link which I found as a probable solution but wasn't able to do it
https://www.i2cdevlib.com/forums/topic/27-fifo-overflow/#comment-99

would be great if someone could guide me as to how do I do this?

title: FIFO overflow with DMP on MPU6050 and OLED

Answers: 0