body:
only display this:

    ARDUMOTIVE
    ArduinoBased
    compassn.Compass
    Michalis Vas.

nothing else. I tried another Arduino Uno, Mega, Nano, but execute only set up. Display is working.No compiler errors.Sketch upload it with out errors!!
i found here https://www.instructables.com/id/Arduino-Digital-Magnetic-Compass-HMC5883L-2-displa/

Code is here.Thank you.

    `*          Ardumotive.com Project Corner
       Arduino digital magnetic Compass with two display modes
       using 3-Axis Digital Compass IC HMC5883L board
       Dev. Vasilakis Michalis / Ver. 1.0 / Date:17/3/2015      */

    //Include libraries
    #include <SPI.h>
    #include <Wire.h>
    #include <Button.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_PCD8544.h>
    #include <Adafruit_HMC5883_U.h>
    #include <Adafruit_Sensor.h>

    //Init Display (SCLK, DIN, D/C, CS, RST)
    Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);
    //Init HMC5883L sensor
    Adafruit_HMC5883_Unified compass = Adafruit_HMC5883_Unified(12345);

    //Constants
    const int lcdLight = 13; //BL pin of LCD to arduino pin 13 (BL = Back Light)
    Button buttonA = Button(2,HIGH); //Button to turn on/off display light
    Button buttonB = Button(8,HIGH); //Button for changing display mode
    // For 1st display mode:
    static unsigned char Leters[] = { 'N' , 'E' , 'S' , 'W' };
    const static unsigned char PROGMEM arrow_bmp[] ={B00100000, B00100000, B01110000, B01110000, B11111000,};
    // For 2nd display mode:
    int r = 24; // radius of compass rose
    int x0= 60; // x-origin
    int y0= 24; // y-origin

    //Variables
    int flag=0;//Store buttonA condition 0:1st display mode / 1: 2nd display mode
    int i=1;   //Store buttonB condition 1: light on / 0: light off

    void setup() {
      pinMode(lcdLight, OUTPUT); // lcd led
      compass.begin();
      Wire.begin();
      display.begin();
      display.setContrast(60);
      //Print a welcome message in startup for 6sec.//////////
      digitalWrite(lcdLight,HIGH);
      display.clearDisplay();   // clears the screen and buffer
      display.setTextColor(BLACK);
      display.setCursor(0,2);
      display.print("  ARDUMOTIVE  ");
      display.setCursor(0,13);
      display.print(" ArduinoBased ");
      display.setCursor(0,23);
      display.print(" compassn.Compass ");
      display.setCursor(0,33);
      display.print(" Michalis Vas.");
      display.display(); // show splashscreen
      digitalWrite(lcdLight,LOW);
      delay(6000);
      /////////////////////////////////////////////////////////
      display.clearDisplay();   // clears the screen and buffer
    }

    void loop() {

      //if buttonB is pressed, 'flag' will change between 0 and 1
        if(buttonB.isPressed()){
          delay(100);//small delay
        if(flag==0){ flag=1; }
        else{ flag=0; }
      }
      //if buttonA is pressed, 'i' will change between 0 and 1
      if(buttonA.isPressed()){
        if(i==0){ i=1; }
        else{ i=0; }
      }
      //if i is equal with 0, set display light on, else set display light off
        if (i==0){
      digitalWrite(lcdLight,HIGH);}
        else{
      digitalWrite(lcdLight,LOW);
       }
      //Reading and calculate degrees:   /////////////////////////////////////
      //Get new sensor value every time that loop starting again
      sensors_event_t event;
      compass.getEvent(&event);
      //Variable heading stores value in radians
      float heading = atan2(event.magnetic.y, event.magnetic.x);

      // Once you have your heading, you must then add your 'Declination Angle', which is the 'Error' of the compassnetic field in your location.
      // Find yours here: http://www.compassnetic-declination.com/
      // Mine is: -13* 2' W, which is ~13 Degrees, or (which we need) 0.22 radians
      float declinationAngle = 0.22;  //<--Change 0.22 with yours. If you can't find your declination juct delete those lines ;)
      heading += declinationAngle;
      // Correct for when signs are reversed.
      if(heading < 0)   heading += 2*PI;
      // Check for wrap due to addition of declination.
      if(heading > 2*PI)heading -= 2*PI;
      // Convert radians to degrees for readability.
      float headingDegrees = heading * 180/M_PI;
      //Convert float to int
      int angle=(int)headingDegrees;
      //////////////////////////////////////////////////////////////////////////

      display.clearDisplay(); // Just in case...

      //if flag is equal with 0 - 1st Display Mode
      if (flag==0){
      DrawRow(angle); //call DrawRow function
      display.drawBitmap(40, 24,  arrow_bmp, 5, 5, 1);
      display.drawLine(42, 0, 42, 24, BLACK);
      display.setCursor(32,34);
      display.print(angle);
      display.setTextSize(1);
      display.print("o");
      display.display();
      delay(500); //print new value every 0.5sec
      }

      //if flag is equal with 1 - 2nd Display Mode
      if (flag==1){
      // Calculation of compass needle on lcd pointing to the direction
      DrawCircle(angle); //call DrawCircle function
      // Display actual heading
      display.setTextSize(2);
      display.setTextColor(BLACK);
      display.setCursor(0,0);
      display.println(angle);

      display.setTextSize(1);
      display.setTextColor(BLACK);
      display.setCursor(x0-2,0);
      display.println("N");

      display.setTextSize(1);
      display.setTextColor(BLACK);
      display.setCursor((x0+r)-5,y0-3);
      display.println("E");

      display.setTextSize(1);
      display.setTextColor(BLACK);
      display.setCursor(x0-2,y0+r-8);
      display.println("S");

      display.setTextSize(1);
      display.setTextColor(BLACK);
      display.setCursor((x0-r)+5,y0-3);
      display.println("W");

      // Triangle for direction
      display.drawTriangle(0, 46, 20, 46, 10, 18, BLACK);
      display.fillTriangle (0, 46, 20, 46, 10, 18, BLACK);
      display.display();
      delay(500); //print new value every 0.5sec
      }
    }/// end of program

    ////////////      Functions    ////////////

    //Draw rows and print letters to display - 1st Display Mode
    void DrawRow(int angle) {

      display.drawLine(0, 0, 84, 0, BLACK);
      display.drawLine(0, 1, 84, 1, BLACK);

      display.drawLine(0, 22, 91, 22, BLACK);
      display.drawLine(0, 23, 95, 23, BLACK);

      display.setTextSize(2);
      display.setTextColor(BLACK);

      int start = 42 - angle / 3 ;
      if (start > 120) start += -120 ;

      int x = 0 ;
      int y = 18 ;
      for (int i=0; i<4; i++) {
          x = start + (i*30) -1;
          if (x>119) x += -120;
          display.drawPixel(x+1, y-2, 1);
          display.drawPixel(x, y, 1);
          display.drawPixel(x+1, y, 1);
          display.drawPixel(x+2, y, 1);
          display.drawPixel(x, y-1, 1);
          display.drawPixel(x+1, y-1, 1);
          display.drawPixel(x+2, y-1, 1);
          display.setCursor((x-4),(y-16));
          display.write(Leters[i]);
       }
      for (int i=0; i<24; i++) {
          x = start + (i*5) -1;
          if (x>119) x += -120;
          display.drawPixel(x+1, y+1, 1);
          display.drawPixel(x, y+2, 1);
          display.drawPixel(x+1, y+2, 1);
          display.drawPixel(x+2, y+2, 1);
          display.drawPixel(x, y+3, 1);
          display.drawPixel(x+1, y+3, 1);
          display.drawPixel(x+2, y+3, 1);
       };

      for (int i=0; i<8; i++) {
          x = start + (i*15)-1;
          if (x>119) x += -120;
          display.drawPixel(x+1, y-1, 1);

          display.drawPixel(x, y, 1);
          display.drawPixel(x+1, y, 1);
          display.drawPixel(x+2, y, 1);
          display.drawPixel(x, y+1, 1);
          display.drawPixel(x+1, y+1, 1);
          display.drawPixel(x+2, y+1, 1);

       };
    }

    ////Draw circle and print letters to display - 1st Display Mode
    void DrawCircle(int angle) {
      if (angle >= 0 && angle <=45) {    // 0-45 degrees
        int angle = angle/2;
        display.drawLine(x0, y0, x0+angle, y0-r, BLACK);
      }
      else if (angle >45 && angle <=90) {// 46-90 degrees
        int angle = (angle-44)/2 ;
        display.drawLine(x0, y0, x0+r, (y0-r)+angle, BLACK);
      }
      else if (angle >90 && angle <=135) {// 91-135 degrees
        int angle = (angle-90)/2;
        display.drawLine(x0, y0, x0+r, y0+angle, BLACK);
      }
      else if (angle >135 && angle <=180){// 136-180 degrees
        int angle = (angle-134)/2;
        display.drawLine(x0, y0, (x0+r)-angle, y0+r, BLACK);
      }
      else if (angle >180 && angle <=225){// 181-225 degrees
        int angle = (angle-178)/2;
        display.drawLine(x0, y0, x0-angle, y0+r, BLACK);
      }
      else if (angle >225 && angle <=270){// 226-270 degrees
        int angle = (angle-222)/2;
        display.drawLine(x0, y0, x0-r, (y0+r)-angle, BLACK);
      }
      else if (angle >270 && angle <=315){// 271-315 degrees
        int angle = (angle-270)/2;
        display.drawLine(x0, y0, x0-r, y0-angle, BLACK);
      }
      else if (angle >315 && angle <=360){// 316-360 degrees
        int angle = (angle-312)/2;
        display.drawLine(x0, y0, (x0-r)+angle, y0-r, BLACK);
      }
    }

title: Does not execute code on loop;only run code of set up

Answers: 0


body:
I bought some incremental rotary encoders online  https://www.bourns.com/docs/Product-Datasheets/PEC12R.pdf

The spec sheet for those suggests a filter circuit for the outputs of the encoder that looks like this:

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

Adding that filter reduces, but doesn't eliminate, spurious signals from the encoder. I wanted to avoid adding Schmitt triggers or other solid state components since I don't have a lot of room left on my proto board for an IC, but I'm beginning to think I will have to add something with hysteresis since any filter that reduces jitter will also slow the rise time/fall time for the output of the encoder and keep it in the "gray area" between LOW and HIGH for a digital signal for too long.

Is there a way to wire these encoders and/or software that lets you read from them with simple passive filtering and/or software rather than adding something like a latch or Schmitt trigger for debouncing?

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

title: Will a simple RC filter work with my mechanical rotary encoder, or do I need a Schmitt trigger?

Answers: 3

body:
The answer seems to be no. I added the RC filter suggested by the manufacturer and the results still jump around (The values sometimes increase by several steps at once, or decrease even when turning the decoder clockwise.)

I added a CMOS Schmitt trigger and it resolves the problem.

I really don't understand why that is, since apparently Arduino digital inputs have integrated Schmitt triggers. This thread from the Arduino forum discusses it at length:

http://forum.arduino.cc/index.php?topic=452599.15

The only thing I can think of is that the hysteresis band of the built-in Schmitt triggers is too narrow (2.08 - 2.63V at VCC of 5V and typical operating conditions) and the filtered voltage still bounces between those values.

I'm using a MC14584B Schmitt trigger that I had lying around, and it looks like it's hysteresis band is ≈2.1V to 2.7V (typical at 25°C) which is slightly wider and goes slightly higher than the hysteresis range of the Arduino itself.

The differences seem quite small though, so I'm confused as to why the Schmitt trigger eliminates the "bobbling" of values I'm seeing.

I could add delay based debouncing code to my Arduino program, but the decoder handler is written as an ISR and those are supposed to be as fast as possible, and the millis() function is supposed to be quite slow, making it difficult.

## EDIT:

I asked a related question regarding filter component values on the EE stack exchange, and somebody there pointed out that I should only be seeing "bounce" on one pin at a time, and that I should be able to reject spurious changes purely through software. I'm trying to do that now.

My new code looks like this:

    bool rotaryValueChanged = false;

    bool pinAHasChanged = false;
    bool pinBHasChanged = false;

    enum ChangeTypes {
      fallingA,
      changingA,
      changingAOrB
      };
    ChangeTypes changesToDetect = fallingA;

    void encode() {
      pinAHasChanged = true;
      //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
      //Fast equivalent to pinAState = digitalRead(rotaryPinA) == LOW
      bool pinAState = (PINE & (1 << 4)) == 0;
      bool pinBState = (PINE & (1 << 5)) == 0;
      //Ignore state changes to pinA unless pinB has changed since the last change.
      //Also only pay attention if this is a falling edge
      //or we're tracking both rising and falling edge changes
      if (pinBHasChanged && (pinAState == false || changesToDetect != fallingA)) {
        rotaryValue +=  (pinAState == pinBState) ? -1 : 1;
        rotaryValueChanged = true;
        pinBHasChanged = false;
      }
    }

    void encodePinB() {
      pinBHasChanged = true;

      //Unless we're counting 48 ticks/rotation, don't count PinB changes.
      if (changesToDetect != changingAOrB) {
        return;
      }
      //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
      bool pinAState = (PINE & (1 << 4)) == 0;
      bool pinBState = (PINE & (1 << 5)) == 0;

      //Ignore state changes to pinB unless pinA has changed since the last change
      if (pinAHasChanged) {
        rotaryValue +=  (pinAState != pinBState) ? -1 : 1;
        rotaryValueChanged = true;
      }
    }

    void setup() {
      attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, CHANGE);//FALLING
      attachInterrupt(digitalPinToInterrupt(rotaryPinB), encodePinB, CHANGE);
      //More setup code here...
    }

This code is written to handle 3 possible options:

  - Only falling edge state changes on pin A (12 steps/rotation)
  - Rising or falling changes on pin A (24 steps/rotation)
  - Rising or falling state changes on either pin (48 steps/rotation.)

The key part of this is to have interrupts on both pins. When one pin changes, its interrupt handler sets a "this pin changed" bool to true. In the ISR (Interrupt Service Routine) for the other pin, it only pays attention to a state change if the other pin has changed. That way, when Pin A changes states, if it bounces, the other pin should not bounce at the same time and so unless pin B has changed, I can simply ignore additional changes to Pin A and handle my debouncing in software, and without having to do timing delays which are too slow for an ISR.

However, the code above doesn't quite work. Sometimes I get bogus reverse rotation readings. If I'm rotating the encoder clockwise, the values I get increase one by one as expected, but occasionally decrement by 1 and then go back to incrementing.

What am I doing wrong?

Since the bouncing should only ever occur on one pin at a time, the above code **should** give correct readings from a bare rotary encoder without any hardware debouncing needed, but it doesn't.

My test case is only counting falling edge transitions for Pin A of my encoder, so picking up spurious counterclockwise rotation readings suggests that sometimes Pin B is changing state at the same time as pin B. That shouldn't happen, so I'm confused.

body:
First of all, I would question the usefulness of debouncing a rotary
encoder. I would expect to have contact bounce only when the contact is
transitioning from `HIGH` to `LOW` or vice-versa. At this transition
point, both the `HIGH` and `LOW` readings are in a sense correct. A
non-debounced reading should then display a rotary angle that briefly
changes back and forth between two _consecutive_ positions, with no
cumulative error.

I would suggest you forget about debouncing and just look at the state
changes. If you think you do need debouncing, handle it downstream, by
periodically querying the “raw” angle and updating the “debounced”
angle:

* if the raw angle is more than one unit apart from the debounced angle,
  bring this difference back to one unit.

* if the raw angle has not changed since a fixed count of milliseconds,
  then make the debounced angle equal to the raw angle.

Second point: you are not looking at the falling edged of input A, you
are looking at the rising edges. This is because `pinAState`
uses negative logic: it is `true` when the pin is `LOW`. It shouldn't
make a big difference though in terms of the logic of the code.

Third point: there is some flaw in your counting logic. I will not try
to analyze it in detail, as the whole debouncing concept you use does
not make sense to me, but only provide an example of how it can fail.
Let's assume the encoder is in the position where both inputs are `LOW`,
and you wiggle it a little bit so that each input, in turn, gives a
positive pulse, like this:

                    _       _       _       _       _       _
    input A      __/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____
                        _       _       _       _       _       _
    input B      ______/ \_____/ \_____/ \_____/ \_____/ \_____/ \_

    rotaryValue      0     |   1   |   2   |   3   |   4   |   5

Here, `rotaryValue` is incremented on each rising edge of input A, save
for the very first one. In this case, the expected behavior is for this
variable to stay, say, within [−1, +1].

body:
Having just chased a problem using a software based debounce for several days, what I'll add is that for the encoders I was using (green no-name Chinese ones), if you put 10mA though the contacts then the signal is a LOT better.   So change the 10k to 470 Ohms.

Or if using 3.3V use 330 Ohms.  Solved all my problems.


body: I want to make an IOT project using an Arduino nano and I need heart rate sensors. I I have a miband2. So, is it possible to connect them ?

title: Is it possible to connect miband2 and arduino nano (?)

Answers: 2

body:
To use BLE on Arduino, I tried google and found this [Article][1]:

Examples:

- HM-10 (HM-11) BLE Module
- BLE Nano
- BLE Mini
- BLE Shield v2.1
- RFduino
- Bluno series
- BLE WT51822-ABS
- Grove – BLE
- BLEduino

Chose one that fits best, and use it.

  [1]: https://developex.com/blog/best-modules-shields-and-boards-for-ble-usage-on-arduino/

body:
You need to connect as a central device.
I've had good luck with the adafruit nrf52 feather.  Also see: https://github.com/Freeyourgadget/Gadgetbridge for the protocol.


body: I was able to connect my HC-05, pair it with my phone, and I can see data in the Serial Bluetooth Terminal Android App.  But when I try to connect it to a certain application it says it cannot find it.  Can the application force a certain version of Bluetooth?  Am I missing something?  Thanks.

title: HC-05 bluetooth module

Answers: 1

body:
The HC-05 modules use bluetooth 2.0. Certain apps would only be compatible with bluetooth 4.0 devices (BLE - Bluetooth Low Energy), such as an HM10 or AT09.

It could be that your app requires the device to use v4.0+. Are you able to find, and pair with the device using your android's default bluetooth device scanning/pairing features?

Assuming that your app does not require v4.0+, have you removed the connection from 'en'/'ch_pd' to 3.3v? If that was still connected (which is a required connection to enter AT command mode), then your bt module would not be able to accept incoming pair requests etc.

hope this has helped. :)


body:
I have code that compiles correctly for an ATTINY85 board using the ARDUINO IDE but I don't have an ATTINY85 board. I have an Arduino Mega ATMEGA2560 and when I select this board in the Arduino IDE the code does not compile and throws this error message

 sketch_feb21a:216:3: error: 'GIMSK' was not declared in this scope

    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

    ^

 sketch_feb21a:216:16: error: 'PCIE' was not declared in this scope

    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

                 ^

 sketch_feb21a:217:3: error: 'PCMSK' was not declared in this scope

    PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin

    ^

 exit status 1
 'GIMSK' was not declared in this scope

Here is the code snippet that throws the error

 void sleep()
 {
   GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
   PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin
   ADCSRA &= ~_BV(ADEN);                   // ADC off
   set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

   MCUCR &= ~_BV(ISC01);
   MCUCR &= ~_BV(ISC00);       // Interrupt on rising edge
   sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
   sei();                                  // Enable interrupts
   sleep_cpu();                            // sleep

   cli();                                  // Disable interrupts
   PCMSK &= ~_BV(PCINT2);                  // Turn off PB3 as interrupt pin
   sleep_disable();                        // Clear SE bit
   ADCSRA |= _BV(ADEN);                    // ADC on

   sei();                                  // Enable interrupts
 }

 ISR(PCINT0_vect) {
    /*noInterrupts();
    while (digitalRead(BUTTON_PIN) == LOW);

    delay(50);
    while (digitalRead(BUTTON_PIN) == LOW);
    playTrack(1 + (curTrack++ % 2));
    delay(400);

    interrupts();*/

 }

title: Converting code for ATTINY85 to ATMEGA2560. Pin change interupts

Answers: 1

body:
Each processor has different registers, things that control stuff like interrupts, input and output. I would not expect code written for one processor, especially if it directly accesses the registers, to work on another processor.

You would need to look at the datasheet for the Atmega2560 and see how to control its pin change interrupts.


body:
I am doing a project on waste management. I have to separate waste majorly as metal, plastic and other materials. For that using Arduino Mega 2560. I have connected Inductive proximity sensor @ A0 (Anolog pin 1 of Arduino) & Capacitive proximity Sensor @ A1(analog pin 2 of Arduino). The two 5V DC motor which are to be used as actuators when the sensors sense the object.
I have given 12 V to the 2 sensors and I have directly connected the sensor's output pin with arduino.

If the Inductive sensor senses any metal object in the conveyor, the dc motor which is a actuator here has to rotate forward, wait sometime and to rotate reverse and stay until the next sense started.
The same for capacitive sensor.

But the problem was there is even though the sensor is not sensing the motor is running. The motor keeps on running forward, delayed and reverse. Please help me out for this, I don't know where I have done the mistake.

The program I have tried is here:

    #define motorpin1 4 \\dc motor's pin 1
    #define motorpin2 5 \\dc motor's pin 2
    #define motorpin3 6 \\dc motor's pin 3
    #define motorpin4 7 \\dc motor's pin 4

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(A0,INPUT);
      pinMode(A1,INPUT);
      pinMode(4,OUTPUT);
      pinMode(5,OUTPUT);
      pinMode(6,OUTPUT);
      pinMode(7,OUTPUT);
      pinMode(8,OUTPUT);
      pinMode(9,OUTPUT);

    }

    void loop() {
      // put your main code here, to run repeatedly:
    if((analogRead(A0)<400) && (analogRead(A0)>100)
    {
      digitalWrite(motorpin1,HIGH);
      digitalWrite(motorpin2,LOW);
      delay(5000);
      digitalWrite(motorpin1,LOW);
      digitalWrite(motorpin2,HIGH);
      delay(5000);
      digitalWrite(motorpin1,LOW);
      digitalWrite(motorpin1,LOW);

    }
    if((analogRead(A1)<400) && (analogRead(A1)>100)
    {
      digitalWrite(motorpin3,HIGH);
      digitalWrite(motorpin4,LOW);
      delay(5000);
      digitalWrite(motorpin3,LOW);
      digitalWrite(motorpin4,HIGH);
      delay(5000);
      digitalWrite(motorpin3,LOW);
      digitalWrite(motorpin4,LOW);

    }

title: Troubleshooting Program using sensors and actuators

Answers: 0


body:
I'm using an addressable 150 led strip and an Arduino Nano to control it, using `FastLed` library.

I'm tring do create a function `turn_on_leds`, which gets 4 parameters:

1) delay time for lighting a led in the loop, 2) direction ( not relevant for now), 3) color index for `colors` array , 4) brightness percentage.

**Problem #1**: a color array is defined to select from a preset definitions of colors ([Fastled reference][1], but when selecting `col_indx` =2, meaning `colors[2]`, leds are not lit in `Red` as they should, AND when setting `leds[i]=0xFF0000`, the right result is set.

**Problem #2**: at `loop` there is a for intended for raise bightness from 0 to 100, BUT the results are 0 for first iteration and 9 for all others.

Appreciate any HELP!!

Guy

Code:

    #include <FastLED.h>

    #define NUM_LEDS 10
    #define BRIGHTNESS  55
    #define DATA_PIN 7

    char *colors[] = {0x000000,0xFFFFFF,0xFF0000,0x008000,0x0000FF}; // black, white,r,g,b
    CRGB leds[NUM_LEDS];
    int t = 0;

    void setup() {
      Serial.begin(9600);
      FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
      //  FastLED.setBrightness(BRIGHTNESS);
    }

    void turn_leds_on(int del_1, bool dir_1, int col_indx, int bright_1) {
      if (dir_1 == true ) { // start to end
        for (int i = 0; i <= NUM_LEDS; i++) {
          leds[i] = 0xFF0000;//colors[col_indx];
          FastLED.setBrightness(bright_1*255/100);
          FastLED.show();
          delay(del_1);
        }
      }
    }

    void loop() {
      Serial.println(t);
      turn_leds_on(50, true, 2, 100);
      delay(1000);
      //  turn_leds_on(50, true, 0, t);
      //  delay(1000);

      if (t < 100 ) {
        t += 10;
      }
      else {
        t = 0;
      }
    }

  [1]: https://github.com/FastLED/FastLED/wiki/Pixel-reference

title: Define preset colors using FastLed library

Answers: 1

body:
Your `colors` array should be `CRGB` type, not `char *`.

    CRGB colors[] = {0x000000,0xFFFFFF,0xFF0000,0x008000,0x0000FF}; // black, white,r,g,b

For your second problem - you are overflowing the bounds of your LEDs array:

    for (int i = 0; i <= NUM_LEDS; i++) {
      leds[i] = 0xFF0000;//colors[col_indx];

You are going from 0 to 10 inclusive. That's 11 iterations. There is no such array slice as `leds[10]`, so the value you write to it ends up overwriting the next two bytes in memory - and those happen to be occupied by the variable `t`.


body:
I am a beginner with C++ but used to be good with BASIC (2 decades ago lol). I'm building a peristaltic metered doser that allows you to input desired mL on a 4x4 keypad and then when 'fill' button is pressed it doses the desired mLs through the peristaltic.

I'm still drafting/printing the peristaltic housing and all of that but in the meantime I want to get as much of the coding done as possible. It's still incomplete, but one of the functions I want the doser to have is a 'PRIME/FLUSH' button.

Originally I wanted the button to run the pump as long as the button is held down to prime the tubing with solution or flush the tubing with DI water. But I haven't had luck figuring out how to use a 4x4 button in momentary switch mode.

A workaround I had was to have the button be an on/off button. So press it once, pump turns on, press it again, pump turns off. Since the pump isn't printed yet I've been using the onboard LED as a tester for the coding (hence the LED_BUILTIN).

The issue, from my research I figured what I would need was an if/else statement. When the button is pressed (in this case the 'a' button), it reads the LED_BUILTIN status and if its HIGH it turns it off and if its LOW it turns it on.

But the 'if' part is working, it turns it on, but the 'else' part is not. When the LED is already on and the 'a' button is pressed, it stays on and doesn't rewrite to LOW.

Code below, any advice?

    #include <KeypadShield.h>

    KeypadShield keypad;

    #include <LiquidCrystal_I2C.h>
    #include <Wire.h>

    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    char Data[15];
    byte data_count = 0;

    int x;

    char customKey;

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);

      keypad.begin();
      lcd.begin(20,4);
        lcd.setCursor(4,0);
        lcd.print("Let's Fill!");
        lcd.setCursor(4,1);
        lcd.print("Designed by");
        lcd.setCursor(4,2);
        lcd.print("JP");
        lcd.setCursor(5,3);
        lcd.print("2019 v1.0");

        delay (2000);

        lcd.clear();

        lcd.setCursor(1,0);
        lcd.print("Enter volume in mL");
        lcd.setCursor(3,1);
        lcd.print("on keypad then");
        lcd.setCursor(5,2);
        lcd.print("press DONE");
        lcd.setCursor(0,3);
        lcd.print("mL:");
    }

    void softReset()
    {
    asm volatile ("  jmp 0");
    }

    void loop()
    {
        customKey = keypad.getNextKeypress();

        if (customKey)
        {
          if (customKey == 'a')
          {
            if (digitalRead(LED_BUILTIN == LOW))
            {
              digitalWrite(LED_BUILTIN, HIGH);
              lcd.clear();
              lcd.setCursor(5,1);
              lcd.print("FLUSHING");
            }
            else
            {
              digitalWrite(LED_BUILTIN, LOW);
              lcd.clear();
              lcd.setCursor(1,0);
              lcd.print("Enter volume in mL");
              lcd.setCursor(3,1);
              lcd.print("on keypad then");
              lcd.setCursor(5,2);
              lcd.print("press DONE");
              lcd.setCursor(0,3);
              lcd.print("mL:");
            }
          }

          if (customKey == 'd')
          {
           softReset();
          }

          if (customKey != 'p' && customKey != 'a' && customKey != 'b' && customKey != 'c' && customKey != 'd' && customKey != 's')
          {
            Data[data_count] = customKey; // store char into data array
            lcd.setCursor(data_count+3,4); // move cursor to show each new char
            lcd.print(Data[data_count]); // print char at said cursor
            data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
            x = atoi (Data); //convert string to integer 'x' for use in equations
          }

         if (customKey == 'p')
          {
           lcd.clear();
           lcd.setCursor(7,0);
            lcd.print(x);
            lcd.setCursor(Data[data_count]+13,0);
            lcd.print("mL");
            lcd.setCursor(0,1);
            lcd.print("FILL --> fill");
            lcd.setCursor(0,2);
            lcd.print("RESET --> change mL");
            lcd.setCursor(0,3);
            lcd.print("FLUSH --> finish");

          }
        }
    };

title: if/else on digitalRead not executing on 'else' portion

Answers: 1

body:
(Heh... before even seeing the code I guessed you'd done this...)

You are comparing a pin number, not the results of `digitalRead()`, and then passing the results of that comparison to `digitalRead()`:

    if (digitalRead(LED_BUILTIN == LOW))

It should read:

    if (digitalRead(LED_BUILTIN) == LOW)

Note the order of the brackets:  `LED_BUILTIN` is passed to `digitalRead()`, and then the result of calling that function is compared to the value `LOW`.


body:
I am powering 2 stepper motors with an L298N driver each (from a 9V 2A external power supply powered from the mains: https://www.amazon.co.uk/BERLS-Power-Adapter-Elegoo-Connectors/dp/B07GSM6YLX/ref=sr_1_5?ie=UTF8&qid=1550859082&sr=8-5&keywords=AC/DC+Power+Adapter+for+Arduino).

I am wondering how I can connect the driver 5V and GND pins to the power supply?

Thanks in advance!

title: Powering L298N drivers from mains power supply

Answers: 2

body: You would not connect the +5V lead to the power supply. Connect the ground between the driver, the Arduino, and the power supply. Connect the 9V from the power supply to the driver. Connect the logic lines from the Arduino to the inputs on the driver.

body:
You'll need another supply, or a step-down supply for the 5v; same ground for all.

Also H-bridges are really inefficient to drive steppers, you should get a dedicate stepper driver.


body:
I am unable to access elements of a 2D PROGMEM array from inside a loop. Please see the following example:

    const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
    const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
    const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
    const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

    const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

      Serial.println(pgm_read_byte(&(arr[0][0])));
      Serial.println(pgm_read_byte(&(arr[1][0])));
      Serial.println(pgm_read_byte(&(arr[2][0])));
      Serial.println(pgm_read_byte(&(arr[3][0])));
      for (int i = 0; i < 4; i++) {
        Serial.print(i);
        Serial.print(":");
        Serial.println(pgm_read_byte(&(arr[i][0])));
      }
      int j = 0;
      Serial.println(pgm_read_byte(&(arr[j][0])));
      j = 1;
      Serial.println(pgm_read_byte(&(arr[j][0])));
      j = 2;
      Serial.println(pgm_read_byte(&(arr[j][0])));
      j = 3;
      Serial.println(pgm_read_byte(&(arr[j][0])));
    }

    void loop() {

    }

The output is:

    97
    101
    106
    114
    0:12
    1:174
    2:12
    3:148
    97
    101
    106
    114

I verified and re-verified the syntax so many times. could not find anyone facing similar issue. I am at my wits end why it would not print correct values inside the loop. Any ideas?

EDIT: expected output is:

    97
    101
    106
    114
    0:97
    1:101
    2:106
    3:114
    97
    101
    106
    114

title: Accessing 2 dimensional array in PROGMEM inside loop

Answers: 2

body:
After going through link given by Juraj above again, I could make it work as follows:

    const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
    const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
    const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
    const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

    const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

      Serial.println(pgm_read_byte(&(arr[0][0])));
      Serial.println(pgm_read_byte(&(arr[1][0])));
      Serial.println(pgm_read_byte(&(arr[2][0])));
      Serial.println(pgm_read_byte(&(arr[3][0])));
      for (int i = 0; i < 4; i++) {
        Serial.print(i);
        Serial.print(":");
        Serial.println(pgm_read_byte_near(pgm_read_word(&(arr[i])) + 0));
      }
      int j = 0;
      Serial.println(pgm_read_byte(&(arr[j][0])));
      j = 1;
      Serial.println(pgm_read_byte(&(arr[j][0])));
      j = 2;
      Serial.println(pgm_read_byte(&(arr[j][0])));
      j = 3;
      Serial.println(pgm_read_byte(&(arr[j][0])));
    }

    void loop() {

    }

Now it shows the expected output and access from inside loop using variable index is possible. Thanks.

body:
    const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
    const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
    const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
    const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

    const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

      for (int i = 0; i < 4; i++) {
        Serial.print(i);
        Serial.print(':');
        for (int j = 0; j < 4; j++) {
          Serial.print((char) pgm_read_byte_near(pgm_read_word(arr + i) + j));
          Serial.print(',');
        }
        Serial.println();
      }
    }

    void loop() {

    }

output

    0:a,b,c,d,
    1:e,f,g,h,
    2:j,k,l,m,
    3:r,s,t,u,

at runtime the size of the arrays is unknown, so I print the first 4 items


body:
I have Arduino Genuino Uno and 'Extra PC' Debian Linux USB dongle. I can get board data S/N etc., but TX LED permanently lit and data showing on TX line with an oscilloscope. I get the following error message:

    avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
An error occurred while uploading the sketch.

Any body know how to create this device?

title: Arduino Genuino UNO

Answers: 0


body:
Sorry For my bad English.
I will start to make a mini conveyor (100 cm x 30 cm) with an Arduino Uno.

What is the best motor should I choose for my project ?
- Stepper Motor ?
- DC Motor ?
Etc.

Please help me, I am Newbie.

title: Choosing a motor for my project

Answers: 2

body:
 - If you want to control how much the conveyor moves and want to move it a fix distance then stop and move again stepper would be better as you know that each step is equivalent to a certain amount of displacement. Stepper have the disadvantage that is more complicated to control so you will need a special driver.
 - If you want the conveyor to move continuously at a approximately speed or moving approximately, then DC motor is a good option. It's easier to drive. But if you want the conveyor to go back and forward then you will need a H bridge for the DC motor(similar to the driver for the stepper motor). Also you can get very accurate positioning with a DC motor using a rotary encoder, but it requires a complex software to drive it properly.

body:
I second the suggestion that a stepper motor might be a more suitable drive mechanism.  There are a lot of stepper motors for sale on line for very low cost that can provide great accuracy.  They are an amazing value, probably because of so many robotics projects to supply.  Their native accuracy can be enhanced many times by use of what is called a "micro-step" driver.  The micro-step driver can transform a stepper motor that has 200 native steps per revolution to one that effectively has 2000 or more steps per revolution. I have found repeatability to be excellent.  They are used commonly to drive precision CNC machines.

And you are correct that if you don't need the fastest motion, a gear reduction can enhance accuracy even more.  There are small stepper motors with affixed gear boxes sold as sets.  Consider a size NEMA 17 stepper motor for a small and inexpensive, but well engineered, motor.

A coupled worm gear box has the advantage that it serves as a natural brake if there is any tendency for system weight to move the laser in certain positions, but gear reduction means that fast motion require higher motor rpm's.

The Accel_Stepper library has worked well for me in helping to get them to function smoothly.  It helps a lot to make it easy to integrate the stepper with Arduino, and it is fairly user-friendly.


body:
I looked around for solutions to my issue by searching on the forum and elsewhere and haven't seen similar issues - (https://arduino.stackexchange.com/search?page=2&tab=Relevance&q=MQTT ESP8266)

I am describing below what I am trying to achieve: (I am relatively new)

I would like to pass streaming joystick data from a "Remote Control" through MQTT to a "OnBoard" unit to drive my robot. Both the "Remote Control" and "OnBoard" units are NodeMCUs ESP8266.

I am able to separately send data from my Joystick to the MQTT broker and also separately read streaming data from the MQTT broker on any MQTT client. However, the moment I connect the "Remote Control" and the "OnBoard" Units to run their respective code, I keep receiving a Lost Connection to MQTT server error. I also observe this happens right after my Joystick ESP8266 connects.

I suspect this is related to one of the following -

 1. **0>>** I am doing something fundamentally wrong [Syntax, usage of libraries, logic?]
 2. connection parameters to the MQTT client [keep alive?, QoS?, delay?] b) there
 3. is something to with sequence of Sub & Pub?
 4. the version of ESP MQTT libraries i am using??
 5. this is not the best way to stream data to
    control devices? WebSockets?

I am copying my code for both units below:

**RemoteControl Unit**: [Joystick input is given through Serial]

    #include <PubSubClient.h>
    #include <EspMQTTClient.h>

    void onConnectionEstablished();

    EspMQTTClient client(
      "mywifi",           // Wifi ssid
      "somepwd!",           // Wifi password
      "iot.eclipse.org",  // MQTT broker ip
      1883,             // MQTT broker port
      "usr",            // MQTT username
      "mqttpass",       // MQTT password
      "test1",          // Client name
      onConnectionEstablished, // Connection established callback
      true,             // Enable web updater
      true              // Enable debug messages
    );

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

    void onConnectionEstablished()
    {
      Serial.println("Remote Connection Established");
    }

    void loop()
    {
      if (Serial.available() > 0) {
        Serial.println("Inside Serial");
        char bfr[101];
        memset(bfr,0,101);
        Serial.readBytesUntil('\n',bfr,100);
        client.publish("DriveChannel", bfr);
      }
      client.loop();
    }

**OnBoard Unit**:

    #include <PubSubClient.h>
    #include <EspMQTTClient.h>

    void onConnectionEstablished();

    EspMQTTClient client(
      "mywifi",           // Wifi ssid
      "somepwd!",         // Wifi password
      "iot.eclipse.org",  // MQTT broker ip
      1883,             // MQTT broker port
      "usr",            // MQTT username
      "mqttpass",       // MQTT password
      "test1",          // Client name
      onConnectionEstablished, // Connection established callback
      true,             // Enable web updater
      true              // Enable debug messages
    );

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

    void onConnectionEstablished()
    {
      client.subscribe("DriveChannel", [] (const String &payload)
      {
        Serial.print("In Connection payload---> ");
        Serial.println(payload);
      });
    }

    void loop()
    {
      delay(3000);
      client.loop();
    }

title: Real-time Pub/Sub thru MQTT between JoyStick and OnBoard Drive units [both ESP8266] - Connection issues

Answers: 0


body: It's an arduino board, model UNO R3. I have 3 5cmx10cm heating pad power required 5V DC up to 1A and can withstand up to 12V DC. These 3 heating pad are wired up onto arduino board with red wires connected to pin 8 pin 9 and pin 10 on the digital side of the arduino and the black wire connected to GND (ground). Lastly I have a toggle on and off switch connected to the arduino with the red wire attached to digital pin 2 and the black wire to 5V. The arduino uno R3 withstand 20voltage and the 5V heating pads can withstand 12V. I would like my 20V external power to heat up all 3 heating pads evenly, how can I do this? Is it possible? Thank you!

title: Distributing power evenly to multiple pins

Answers: 2

body:
Yes, of course it is possible.  But if all you need to do it to turn these heat pads on and off, an Arduino is perhaps not the most suitable technology.

But presuming these heat pads are a component of some more complex system that responds to other inputs or outputs to/from the Arduino, you will need a few more components.  You need to accomplish two things that the UNO R3 cannot accomplish by itself, because your heat pads are very much too large a load for your UNO to power directly.  (The power for a single LED bulb is about the most that you can draw from an output pin.)

 1.  You need to reduce your 20-V external power source down to something less than 12 volts to supply your heating pads.

 2.  You need to switch on and off up to 1 amp of current to flow to each of the three heating pads.  The UNO cannot do this directly.

There are a lot of ways to reduce your 20-volt supply down to less than 12 volts.  Some are much more efficient than others.  Probably the lowest cost efficient way is to use your 20-V source as the input a small DC to DC voltage down stepping converter.  These are available online from Chinese vendors for very low cost.  Just search for "DC-DC converter down".  A quick search finds one rated at 20 amps, with adjustable voltage output can be purchased for less than $10.  These are pretty efficient devices that don't waste the power that a simple voltage dropping resistor would waste.

Then you need either one or three 5-volt relays of some type to switch the power on to the heat pads.  The UNO pins output of 5-volts would not provide current to heat pads, put only enough current to energize the relay(s).  The relay(s) can be either solid state, or coil energized.  Just be sure the relay "contacts" are rated to handle well more than 1 amp if there are three of them, and more than 3-amps if only one.   An Arduino relay shield with four relays, each rated for 10 amps, can be purchased for less than $5.

If you only every want all three heat pads energized at the same time, you only need one relay, and one Arduino output to energize it.

The very simplest solution, if you only want all the pads heating simultaneously, would be to wire the three heat pads in series.  Then you could apply your 20-volts directly across all three heat pads, and you would not need any device to reduce your supply voltage.  Each heat pad would have 1/3 of 20 volts across it, which is well under their 12 volt tolerance.  And you would only need one relay.

body:
Can you state the full goal of the project? Are you supposed to be turning the heating pad on and off with the Arduino? (The rest of my answer assumes that that is what you want to do.)

You will need a source of DC power to drive the Arduino. (You can't power an Arduino with AC.)

You will need a 5V relay so you can turn off the power to the heating pad from a logic pin on the Arduino. There are various relay modules made to be controlled by microcontrollers like Arduinos. This one, for example: https://www.jameco.com/z/VMA406-Velleman-Arduino-Compatible-5V-Relay-Module_2255306.html?CID=GOOG&gclid=EAIaIQobChMIr9bSioLT4AIVkpOzCh3X7gqbEAQYBSABEgLf1PD_BwE

Then you will be able to rig the Arduino to turn the relay on and off. You'll wire the power for the heating pad through the relay. You will also need a way to lower the voltage of your power supply to the 5V - 12V range you mentioned. A 1:2 step-down transformer would be a good choice for that.


body:
I'm trying to use NRFlite library to facilitate a simple wireless remote incorporating a 3x4 keypad and nRF24L01 modules.  I have it all working well except for one programming puzzle.

All of the example NRFLite receiver sketches that I can find online show the entire main program loop within a while statement:
while (_radio.hasData())

Such as:

    void loop() {

    while (_radio.hasData())

    {

        _radio.readData(&_radioData); // Note how '&' must be placed in front of the variable name.

        String msg = "Radio ";

        msg += _radioData.FromRadioId;

        msg += ", ";

        msg += _radioData.OnTimeMillis;

        msg += " ms, ";

        msg += _radioData.FailedTxCount;

        msg += " Failed TX";

        Serial.println(msg); }}

But my sketch is obviously much more complicated than these examples.  I would like to pass the data received to a variable to use outside of this "while" loop to do a bunch of other stuff not related to the wireless remote.  However, whenever I try to do that, the conditional argument of this "while" function
"(_radio.hasData())"
seems to test as TRUE, and the old data just received is treated again as new data with each pass through the program loop.

How can I pass the data packet outside of the "while (_radio.hasData())" function and get it to subsequently ignore that last data packet received?

Looking at the cpp file, it seems as if perhaps just calling the function "_radio.readData(&_radioData)" is intended to do just that by reseting a "data received flag", which makes sense as a way to accomplish just what I need.  But it doesn't seem to work that way.  Here is that "_radio.readData(&_readData)" function from the .cpp file:

    void NRFLite::readData(void *data) {

    // Determine length of data in the RX FIFO buffer and read it.

    uint8_t dataLength;

    spiTransfer(READ_OPERATION, R_RX_PL_WID, &dataLength, 1);

    spiTransfer(READ_OPERATION, R_RX_PAYLOAD, data, dataLength);

    // Clear data received flag.

    uint8_t statusReg = readRegister(STATUS_NRF);

    if (statusReg & _BV(RX_DR))

    {

        writeRegister(STATUS_NRF, statusReg | _BV(RX_DR));
    }
    }

I would sure appreciate any suggestions, because otherwise, the NRFlite library seems very efficient for my simple need.

title: NRFlite Question

Answers: 0


body:
I'm following this [tutorial page][1] and I don't have a 10k ohm potentiometer on hand. Could I replace it with resistors to simulate a manual setting and replace the resistors to adjust to a new settings.

From what I was reading this pin is for contrast and I'm sure I could manually set the contrast once and be happy with it for quick prototyping. I'll be ordering a 10k ohm potentiometer on Monday.

  [1]: https://aibodoctor.com/arduino_lcd/

title: Trying to use an LCD 1602 to display, but I don't have a 10 KOhm potentiometer

Answers: 3

body:
Yes. All a potentiometer is, is two resistors end to end.  The "wiper" is the join between the two resistors.

It doesn't matter too much what value potentiometer (and hence what value resistors) you use, as long as it's "around" the 10kΩ mark (100kΩ should be fine, 50kΩ, 1kΩ etc - anything below 1kΩ may not work) - what matters is the ratio of the values of the resistor.

body:
Yes, you always can do that, depending on the resistors you have at hand, you can combine them to make e.g. 1 KOhm, 2 KOhm etc resistors.

Probably you need a linear potentiometer (which means halfway is 5 KOhm).

In a linear potentiometer, you can use the following resistance (made up by a single or a combination of resistors in series or parallel):

body:
Yes, but you need only one resistor to GND. The display has already one resistor inside the display. I forgot what the value should be and I don't have a display at hand right now, so you have to try which value is best.

In most examples with a LCD display, a potentiometer is used for the contrast. Not many people know that only a (variable) resistor to GND is needed.

With a fixed resistor, you are not able to quickly adjust the display when the temperature changes.


body:
I have been trying to figure out this MPU6050 for a bit but the RAW readings are confusing me. It seems to me that the accelerometer readings and the gyro readings are getting swapped... and I don't really see how.

Here is the code reading the raw data in:
```C
#include "Wire.h"

const int MPU_ADDR = 0x68; // I2C address of the MPU-6050.
const int ACCEL_XOUT_H = 0x3B; // starting register: high byte to accelerometer X High

int16_t accelerometer_x, accelerometer_y, accelerometer_z; // variables for accelerometer raw data
int16_t gyro_x, gyro_y, gyro_z; // variables for gyro raw data
int16_t temperature; // variables for temperature data

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
  Wire.write(0x6B); // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
}

void loop() {
  Wire.beginTransmission(MPU_ADDR);
  Wire.write(ACCEL_XOUT_H); // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false); // connection is kept active.
  Wire.requestFrom(MPU_ADDR, 7*2, true); // request a total of 7*2=14 registers

  // Read high byte, shift up one byte then OR with low byte
  accelerometer_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L)
  accelerometer_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x3D (ACCEL_YOUT_H) and 0x3E (ACCEL_YOUT_L)
  accelerometer_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x3F (ACCEL_ZOUT_H) and 0x40 (ACCEL_ZOUT_L)
  temperature = Wire.read()<<8 | Wire.read(); // reading registers: 0x41 (TEMP_OUT_H) and 0x42 (TEMP_OUT_L)
  gyro_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x43 (GYRO_XOUT_H) and 0x44 (GYRO_XOUT_L)
  gyro_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x45 (GYRO_YOUT_H) and 0x46 (GYRO_YOUT_L)
  gyro_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x47 (GYRO_ZOUT_H) and 0x48 (GYRO_ZOUT_L)

  // print out data
  Serial.print(""); Serial.print(accelerometer_x, DEC);
  Serial.print("|"); Serial.print(accelerometer_y, DEC);
  Serial.print("|"); Serial.print(accelerometer_z, DEC);
  Serial.print("|"); Serial.print(temperature/340.00+36.53, DEC);
  Serial.print("|"); Serial.print(gyro_x, DEC);
  Serial.print("|"); Serial.print(gyro_y, DEC);
  Serial.print("|"); Serial.print(gyro_z, DEC);
  // the following equation was taken from the documentation [MPU-6000/MPU-6050 Register Map and Description, p.30]

  Serial.println();

  // delay
  delay(100);
}
```

I am expecting some pipe-delimited data in the format:
`'aX|aY|aZ|T|gX|gY|gZ'`

and indeed looking at the serial data that is what I thought I had:
```
%matplotlib notebook
import serial
from collections import deque
import pandas as pd
import matplotlib.pyplot as plt
ser= serial.Serial('COM6', 115200, timeout=2.5)
ser.readline()
```
gives me a good line of data: `b'4008|-1792|18376|26.3182334899|-1084|274|-380\r\n'`

This certainly looks plausible -- but I was confused by why the accelerometer values were so high at rest... maybe that is just how it is. But when I moved things around I was more and more confused - I have to see this. So I plotted all the values in Jupyter/matplotlib and it made sense -- the first three numbers are not accelerometer data but gyro data:

```
fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()

fig.show()
fig.canvas.draw()

ser.reset_input_buffer()
ser.readline()
data = deque(maxlen = 100)
try:
    while True:
        line_of_data = [float(x.strip()) for x in (ser.readline().decode("utf-8")).split("|")]
        data.append(line_of_data)
        ax.clear()
        for n in range(7):
            ax.plot([x[n] for x in data], label='x['+str(n)+']')
        ax.legend(loc='upper left')
        fig.canvas.draw()
except KeyboardInter
```
[![plot of mpu6050 data][1]][1]

I slowly turned the robot chassis and the x[0] and x[2] (should have labeled those better) values changed and then held their values as I held the rotation. This is what I expected to see from the gyroX and gyroZ (the MPU6050 is at the top of the chassis so as I rotate the body about the wheels the X axis changes the most but the Z does as well).

I don't see how the code could be swapping to two sets of data. I have looked at a number of other examples of reading the raw values and their numbers look similar to mine (i.e. they show the first three values as rather large, and the last three as rather small).

When the MPU is not moving I would expect the accelerometer values to be small.

Do I just not understand how the MPU6050 is working or am I somehow swapping the values in my code?

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

title: MPU6050 Acc and Gyro readings swapped

Answers: 0


body:
I am having a byte array let us say

    byte arr[7]={123456};

How to compare this array with a list of of other array like this for example

    byte  buffers[5][7] = {123456,654321,987654,456789,765432};

if this method is wrong how can I declare that ?

title: Comparing byte array with multi-dimensional array

Answers: 1

body:
    byte arr[7]={123456};

sets arr[0] = 64 - which is 123456 % 256 - and arr[1-6] are left at 0

And you also only want 6 (not 7) values - so the code would be

    byte arr[6]={1,2,3,4,5,6}; // this is how to initialise an array
    byte  buffers[5][6] = {{1,2,3,4,5,6},{6,5,4,3,2,1},{9,8,7,6,5,4},{4,5,6,7,8,9},{7,6,5,4,3,2}}; // this is how to initialise a 2d array

    void setup() {
      Serial.begin(74880);
      delay(100);
      // this code will find a match, the vlaue of `i` will be the matched index
      int i;
      int j;
      for(i = 0; i < 5; i++) {
        for(j = 0; j < 6; j ++) {
          if(arr[j] != buffers[i][j]) {
            break;
          }
        }
        if(j == 6) {
          break;
        }
      }
      if (i < 5) {
        Serial.print("Found at index ");
        Serial.println(i);
      }

    }


body:
[![blood glucose breakout board][1]][1]

I am trying to output analog voltage (400 mV) using Arduino Nano PWM pins. Is it okay to directly connect (using jumper wires) the PWM pins to the Vin+ of the INA219 current sensor?

I badly need it for my graduation project. Thanks for the help.

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

title: Outputting 400 mV using Arduino Nano PWM pin

Answers: 2

body:
PWM pins don't output analog voltages. They output pulses of 5V. You then need to average the output in order to get an actual analog voltage out of it. You should be able to use a capacitor and resistor to average out the voltage of the PWM pin, making a [low-pass filter][1]. You won't get exactly to 400mV. If I remember correctly the PWM pin has a value of 0 - 255, and 1/255 is 0.0196 V after a good low-pass filter, or 19.6 mV, so `analogWrite(pin,20)` should get close to the 400mV you want.

Another option would be to use a voltage divider to the output to get the output you want. That way you can use the full range of `analogWrite()` in producing the 400 mV and smaller voltages, thus gaining precision. Then again, if all you want is a fixed 0 or 400mV you could accomplish that with a digital output pin and a fixed voltage divider - no need for PWM.

  [1]: https://en.wikipedia.org/wiki/Low-pass_filter

body:
Of course it's possible !

Duncan you made a little error of 10^2 ;)

5V / 1023 = 0.004887.. = 4.88mV

For 400mV you got 400/4.88 = 81.9.

So in the arduino a value of 82 (0-1023) will send you an output of 400.16mV after beeing redressed by a RC filter.


body:
I have a long code written in Arduino101 that works fine. I use a prepared function (connected to a library) in my code that I have not written it. My input to this function is an array. In 99.9999..% of the time, the function works great. However, it might stops due to an unknown reason, maybe because of my wrong input. This causes the program to stop.
My question is: how to bypass this function if it fails for any reason? Something like 'on error' function in normal programming.

Thanks a lot in advance,

title: Bypass a function error

Answers: 1

body:
If your function is crashing then there is no way to recover. Arduinos are unprotected real mode devices. If your code does something invalid, your program crashes and the device will likely either hang or restart.

You need to debug your function, or find the invalid data you are passing into it.


body:
I am working on my final assignment. The problem is I want to make a prototype tool, with 2 string compare. If I send data "OK DISC DISCLOSED: 341513DB689AOK RSSI: -056 OK NAME: CarBT1 OK DISCE" will be parsed and bring up data "CarBT1 OK DISCE" if the data is correct then the LED will turn on, but my program isn't working? does anyone know the problem?

    String dataIn;
    String dt[10];
    int i;
    boolean parsing=false;
    const int pinLED = 8;
    String readString;

    void setup (){
      Serial.begin(9600);
      pinMode(pinLED, OUTPUT);
      Serial.print("Sketch:   ");   Serial.println(__FILE__);
      Serial.print("Uploaded: ");   Serial.println(__DATE__);
      Serial.println(" ");
      while(!Serial){
        ;
      }
    }

    void loop (){
      if(Serial.available()>0) {
      char inChar = (char)Serial.read();
      dataIn += inChar;
      if (inChar == '\n'){
      parsing = true;
      }
    }
    if(parsing){
      parsingData();
      parsing=false;
      dataIn="";
    }
    while(Serial.available()){
      delay(3);
      char c =  Serial.read();
      readString += c;
    }
    readString.trim();
      if(readString.length()>0){
        if(readString == "CarBT1 OK+DISCE"){
          digitalWrite(pinLED, HIGH);
          Serial.println("Switching On");
       }
      if(readString == "off"){
          digitalWrite(pinLED, LOW);
          Serial.println("Switching Off");
       }
    readString = "";
     }
    }

    void parsingData(){
    int j=0;
    Serial.print("data masuk : ");
    Serial.print(dataIn);
    Serial.print("\n");
    dt[j]="";
    for(i=1;i<dataIn.length();i++){
      if ((dataIn[i] == ':') || (dataIn[i] == ':')){
      j++;
      dt[j]="";
    }
      else{
      dt[j] = dt[j] + dataIn[i];
      }
     }
    }
    Serial.print("data 1 : ");
    Serial.print(dt[0]);
    Serial.print("\n");
    Serial.print("data 2 : ");
    Serial.print(dt[1]);
    Serial.print("\n");
    Serial.print("data 3 : ");
    Serial.print(dt[2]);
    Serial.print("\n\n");
    Serial.print("data 4 : ");
    Serial.print(dt[3]);
    Serial.print("\n\n");
    }

title: Parsing Data and Comparing two string in arduino

Answers: 1

body:
I think that the biggest problem that you are encountering is that reading a line from serial is not as straightforward as you would like. I don't have a quick and easy solution for you, but there is much on this issue that you can look at.

You have two serial read while loops. The first exits as soon as there are no characters to read (even though some may be on the way). When "\n" is read, you set parsing but it does not mean that \n is removed from dataIn.

The second serial read while loop is using a delay(3) after detecting that a character is available, but that character could have arrived after the first read and be the only character in the buffer, for example.

I suspect that the reason that your String comparison does not work is simply because the Strings are not equal.

Your String looks like something read from an HM-10/11 or something similar. I have had some success reading those transmissions by doing the following:

Make sure the serial buffer is empty. When a character is available, read it into your building String, but continue looking for characters that are available for a set amount of time (maybe a couple of seconds). Continue looking for characters until the time has elapsed and not as soon as there are no characters available (because more may be coming). Alternatively, keep building the string until you recognize the "DISCE" marking the end of that transmission.

A problem, however, is that, in my experience, if it is a very long line (that can occur when there are many devices out there), you will never get that "DISCE". I assumed that this was a firmware issue.

Hope it helps.


body:
This is Arduino RC control car, the sketch tested good in a small motor, but burned two 60A drivers when put into 24V,500W motors, need help to find out whats wrong?

    #include <VirtualWire.h>

    //motor A connected between A01 and A02
    //motor B connected between B01 and B02

    int STBY = 2; //standby  // mod: was 10 --2 ??

    int count;

    //Motor A
    int PWMA = 9; //Speed control   // need mod: was 3 change into 9
    int AIN1 = 8; //Direction  // was 9
    int AIN2 = 7; //Direction

    //Motor B
    int PWMB = 10; //Speed control   // need mod: was 5 change into 10
    int BIN1 = 5; //Direction   // was 6
    int BIN2 = 4; //Direction   ///was 16 put into p7 cause of Arduino uno no p16.

    const boolean FORWARD = HIGH;
    const boolean REVERSE = LOW;

    float speed_Max = 252; //pwm usually goes from was:0-255 ////0-255 changed into 0-252

    float speed_Min = 0;
    float analogInput_Max = 1023;
    float analogInput_Min = 0;
    float analogInput_Middle_X = 515;//ideally it would be analogInput_Max / 2
    float analogInput_Middle_Y = 495;//ideally it would be analogInput_Max / 2
    float deadBand = 0;
    float middleMax = (analogInput_Max / 2) + deadBand;
    float middleMin = (analogInput_Max / 2) - deadBand;
    boolean pastDirection = FORWARD;

    void setup()
    {
      // Configure Timer 2 for PWM @ 14 kHz.
      TCCR2A = 0;           // undo the configuration done by...
      TCCR2B = 0;           // ...the Arduino core library
      TCNT2  = 0;           // reset timer

      TCCR2A = _BV(COM2A1)  // non-inverted PWM on ch. A
               | _BV(COM2B1)  // same on ch; B
               | _BV(WGM20);  // mode 10: ph. correct PWM, TOP = ICR1

          TCCR2B = (TCCR2B & 0b11111000) | 0x01; //3.92116 [kHz] //** use this code got 3.9khz but joystick works not too good
        {

        Serial.begin(9600);  // Debugging only
        Serial.println("setup"); //Prints "Setup" to the serial monitor

        vw_set_rx_pin(6);       //Sets pin D12 as the RX Pin
        vw_set_ptt_inverted(true); // Required for DR3100
        vw_setup(2000);      // Bits per sec
        vw_rx_start();       // Start the receiver PLL running

        pinMode(23, OUTPUT); //Relay one ////M1 added 2 was 2 -- 4
        pinMode(25, OUTPUT); //Relay two
        pinMode(27, OUTPUT); //Relay four
        pinMode(29, OUTPUT); //Relay five
        pinMode(31, OUTPUT); //Relay sex
        pinMode(33, OUTPUT); //Relay seven
        pinMode(35, OUTPUT); //Relay eight
        pinMode(37, OUTPUT); //Relay three
        pinMode(39, OUTPUT); //Relay three
        pinMode(41, OUTPUT); //Relay eight
        pinMode(43, OUTPUT); //Relay three
        pinMode(45, OUTPUT); //Relay three

        digitalWrite(23, HIGH);
        digitalWrite(25, HIGH);
        digitalWrite(27, HIGH);
        digitalWrite(29, HIGH);
        digitalWrite(31, HIGH);
        digitalWrite(33, HIGH);
        digitalWrite(35, HIGH);
        digitalWrite(37, HIGH);
        digitalWrite(39, HIGH);
        digitalWrite(41, HIGH);
        digitalWrite(43, HIGH);
        digitalWrite(45, HIGH);
         }

      pinMode(STBY, OUTPUT); //// pin: the number of the pin whose mode you wish to set; mode: INPUT, OUTPUT, or INPUT_PULLUP.

      pinMode(PWMA, OUTPUT);
      pinMode(AIN1, OUTPUT);
      pinMode(AIN2, OUTPUT);

      pinMode(PWMB, OUTPUT);
      pinMode(BIN1, OUTPUT);
      pinMode(BIN2, OUTPUT);
    }

    void loop() {

    button(); //// disable 'button', no work. remove '//' enable, button works good
    joystick(); //// disable 'joystick', no work. remove '//' enable, joystick works good, but no motor control yet

     }

    void joystick() {

      uint8_t buf[VW_MAX_MESSAGE_LEN]; // This declares a variable array. instead of 7 variables buf1, buf2 etc...
      uint8_t buflen = VW_MAX_MESSAGE_LEN;
      if (vw_get_message(buf, &buflen)) // Non-blocking
      {
        int i;
        int column = 0;
        String message;
        int commands[30];
        // Message with a good checksum received, dump it.
        for (i = 0; i < buflen; i++)
        {
          //DEBUG:
          //Serial.print(char(buf[i]));

          if (char(buf[i]) == '|') {
            commands[column] = message.toInt();
            message = "";
            column++;
          } else {
            message += char(buf[i]);
          }
        }

        //one more time to capture the last value since the message does not end with |
        commands[column] = message.toInt();

        // DEBUG
        //    Serial.print("X: ");
        //    Serial.print(commands[0]);
        //    Serial.print(" Y: ");
        //    Serial.println(commands[1]);

         motorControl(commands[0], commands[1]);

      }

    }

    void move(int motor, int speed, boolean direction) {
      digitalWrite(STBY, HIGH); //disable standby

       if (motor == 1) {
        digitalWrite(AIN1, direction);
        digitalWrite(AIN2, !direction);
        analogWrite(PWMA, speed);
      } else {
        digitalWrite(BIN1, !direction);
        digitalWrite(BIN2, direction);
        analogWrite(PWMB, speed);
      }
    }

    void motorControl(float x, float y) {
      boolean currentDirection = y >= analogInput_Middle_Y;

        //map(value, fromLow, fromHigh, toLow, toHigh);
      if (currentDirection == REVERSE) {
        y = map(y, analogInput_Middle_Y, analogInput_Min, speed_Min, speed_Max) ;
      } else {
        y = map(y, analogInput_Middle_Y, analogInput_Max, speed_Min, speed_Max);
      }

      int subtractFromLeft = map(x, analogInput_Middle_X, analogInput_Min, speed_Min, y);
      int subtractFromRight = map(x, analogInput_Middle_X, analogInput_Max, speed_Min, y);

      if (subtractFromRight < 0) {
        subtractFromRight = 0;
      }

      if (subtractFromLeft < 0) {
        subtractFromLeft = 0;
      }

      int Throttle_RIGHT = y - subtractFromRight;
      int Throttle_LEFT = y - subtractFromLeft;

      boolean currentDirection_LEFT = currentDirection;
      boolean currentDirection_RIGHT = currentDirection;

      if (Throttle_LEFT < 1 && Throttle_RIGHT > 1) {
        currentDirection_LEFT = !currentDirection;
        Throttle_LEFT = Throttle_RIGHT;
      }

      if (Throttle_RIGHT < 1 && Throttle_LEFT > 1) {
        currentDirection_RIGHT = !currentDirection;
        Throttle_RIGHT = Throttle_LEFT;
      }

      move(1, Throttle_LEFT, currentDirection_LEFT);
      move(2, Throttle_RIGHT, currentDirection_RIGHT);

      }

    void button()
    {
      uint8_t buf[VW_MAX_MESSAGE_LEN];
      uint8_t buflen = VW_MAX_MESSAGE_LEN;
      if (vw_get_message(buf, &buflen)) // Non-blocking
      {
        int i;
        digitalWrite(13, true);  // Flash a light to show received good message
        // Message with a good checksum received, dump it.
        Serial.print("Got: ");

        for (i = 0; i < buflen; i++)
        {
          int c = (buf[i]);
          Serial.print(c);
          Serial.print(" ");
          if (c == 65 ) {
            digitalWrite(23, !digitalRead(23));  //// A--RELAY A1
          }

          if (c == 66 ) {
            digitalWrite(25, !digitalRead(25));  //// B--RELAY A2
          }

          if (c == 67 ) {
            digitalWrite(27, !digitalRead(27)); //// C--RELAY B1
          }

          if (c == 68 ) {
            digitalWrite(29, !digitalRead(29)); //// D--RELAY B2
          }
    /*
          if (c == 69 ) {
            digitalWrite(37, !digitalRead(37)); //// E--
          }

          if (c == 70 ) {
            digitalWrite(39, !digitalRead(39)); //// F--
          }
    */
          if (c == 71 ) {
            digitalWrite(31, !digitalRead(31)); //// G--RELAY C1
          }

          if (c == 72 ) {
            digitalWrite(33, !digitalRead(33));  //// H -- RELAY C2
          }

          if (c == 73 ) {
            digitalWrite(43, !digitalRead(43));  //// I --
          }

           if (c == 74 ) {
            digitalWrite(35, !digitalRead(35));  //// J --
          }

           if (c == 75 ) {
            digitalWrite(37, !digitalRead(37));  //// K --
          }

          if (c == 76 ) {
            digitalWrite(39, !digitalRead(39));  //// L --
          }
          if (c == 77 ) {
            digitalWrite(41, !digitalRead(41));  //// M --
          }
          if (c == 78 ) {
            digitalWrite(35, !digitalRead(35));  //// N --
          }

        }
        count++;
        // Serial.print(count);
        Serial.println("");
        digitalWrite(13, false);
      }
    }

My new driver is came, I just scare to use it, heard that DC motor will draw upto 300A at the start, what should I do to reduce the start current?

title: The sketch burned two H Bridges, need help to find out how to modify

Answers: 1

body:
As you wrote in comment you use this H bridge:

https://www.ebay.com/itm/60A-DC-Motor-Driver-Module-High-Power-motor-Speed-Control-Dual-Channel-H-bridge/122479397950

The description how to use it is clear:
[![h-bridge features][1]][1]

But the listing doesn't say what will happen when you set state of `A1,A2=1.1` to that H-bridge.

When you set value of `A1,A2=1.1` to a unprotected (cheap) H-Bridge you get a direct short to ground through 2 transistors burning them instantly

[![H-Bridge and electricity path for 1,1][2]][2]

Your code actually does not protect against that:

       if (motor == 1) {
        digitalWrite(AIN1, direction);
        digitalWrite(AIN2, !direction);
        analogWrite(PWMA, speed);
      } else {
        digitalWrite(BIN1, !direction);
        digitalWrite(BIN2, direction);
        analogWrite(PWMB, speed);
      }
    }

If previous value of direction is 0 (`A1,A2=0,1`) and you want to set direction to 1 (`A1,A2=1,0`) when arduino runs the line `digitalWrite(AIN1, direction);` for few cycles you actually end up with `A1,A2=1,1` and MOSFETs go bye bye.

Try setting AIN1, AIN2 (or BIN1, BIN2) to 0 before adjusting the direction

       if (motor == 1) {
        digitalWrite(AIN1, LOW);
        digitalWrite(AIN2, LOW);

        digitalWrite(AIN1, direction);
        digitalWrite(AIN2, !direction);
        analogWrite(PWMA, speed);
      } else {
        digitalWrite(BIN1, LOW);
        digitalWrite(BIN2, LOW);

        digitalWrite(BIN1, !direction);
        digitalWrite(BIN2, direction);
        analogWrite(PWMB, speed);
      }
    }

This way you are guaranteed that you always have at least one `0` there.

**EDIT:**

You wrote that the module contains IR2103s it should protect you from the problem I described above. (But my suggested fix is not dangerous so you can use it just in case)

There is another possibility. Maybe the rapidly changing of the direction induces high voltage spikes in the motor, and that burns the circuit. Do you see any power diodes there? Look at the image I pasted above it has 4 diodes that should safely discharge those spikes. Make sure your code does not change direction every few milliseconds.

  [1]: https://i.stack.imgur.com/s5fTz.png
  [2]: https://i.stack.imgur.com/YQiz5.png


body:
I'm using digiKeyboard library to type to a powershell, but I need to type a backslash (a lot of them), but I can't figure it out.

I have been looking for the solution for about 3 hours and I still can't find it.
Please let me know how to make a backslash work.

The powershell command that I want to execute:

cmd /C "start /MIN powershell iwr -Uri https://tinyurl.com/WjnAU6 -OutFile c:\windows\temp\b.jpg;sp 'HKCU:Control Panel\Desktop' WallPaper 'c:\windows\temp\b.jpg';$a=1;do{RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True;sleep 1}while($a++-le59)"

It just changes the wallpaper with a downloaded image, try in on your friend.

title: DigiKeyboard - type a backslash (\)

Answers: 1

body:
To include `\` in a string so it can be printed you have to escape it.  `\` is itself the escape character, so doubling it up "escapes the escape character" so it is interpreted as a normal character.

So to print `"c:\windows"` you would actually have to type `"c:\\windows"` and the `\\` gets changed by the compiler into just `\`


body: OV7670 image sensor, small volume, low operating voltage, providing all functions of a single chip of VGA camera and image processor. so I am using and ESP8266 to connect to internet and stream the video from the OV7670 on a web, can I do so?

title: Can I use ESP8266 and OV7670 to video stream on a web?

Answers: 0


body:
The common useage of the OTA library for this MCU is to have it connect to a network, and to then use a computer on that network to upload firmware across that network. Due to <strike>either issues with PlatformIO (my IDE of choice right now) or</strike> my router (administrated by my ISP) blocking discovery (mDNS does NOT work here either way, and getting the IP is very hard as a result*), I would like to use the SoftAP class to make an access point that I can connect to directly when uploading firmware.

However, I have attempted this, and it *does* work IF I specify an IP address. This is a bit more convenient, but it *fails* if I try using mDNS again (via upload_port = myesp8266.local). (As an aside, this means that OTA over SoftAP does work, at least to this degree. I'm sure some will find this useful.)

Has anyone else confirmed either of these issues? I understand that they may be unrelated (since problem one is (Network || PIO) and the second is (PIO || SoftAP) as the cause), but any information as to why this might fail in both cases would be useful.

**So, for the first case, can someone who uses that IDE and has an ESP8266 board test if mDNS works with the IDE?
For the second, assuming that mDNS *does* work with the IDE in the first case (and it's thus the MCU's fault), can anyone determine why the SoftAP class either halts or fails to work with mDNS?**

This will really help my abilities to easily get firmware onto the board, and also tell me if I need to get a new router that allows mDNS (if it's not PlatformIO in the first case).

*Since the ISP administrates the router, I am unable to log in and view the IP addresses currently connected. My only option is printing it via UART, which renders this pointless, or attaching a OLED or LCD screen to every single device I build, or get a new router, which is its own issue right now. I've now run the web server test again, and not only does OTA not work with mDNS, but apparently I can't access it at all unless I know its actual IP address.

title: OTA mDNS issues with ESP8266 and PlatformIO?

Answers: 0


body:
Hello i am using ESP8266 to control my 220v AC ceiling fan.

I am able to do that easily with a 5v 10A relay module.

But i want to know is there any module to control the fan speed as well? i have checked many videos on YouTube but couldnt understand how can i do that. I just got one thing that it will require Pulse Width Modulation to control it.

Thank you!

title: Control Fan Speed Using ESP8266

Answers: 0


body:
I'm trying to build a smart Keychain using Arduino uno wifi(org, so Im using it like it's Arduino uno), ESP8266-01 And neo6m GPS device.

My esp8266 wasn't new, and it came without AT firmware. I flashed it so it could have AT commands but it's not completely working.

Anyway, the flash is using 115200 baud and I'd like to use serial monitor to communicate it using arduino(and blynk app).
Is there a way could I do it without flashing the esp for 9600 baud rate?

Thanks!

title: Using ESP8266-01 via Arduino(no flash) without AT commands(using serial monitor)

Answers: 1

body:
Arduino Uno WiFi Dev Ed has the on-board esp8266 wired to additional Serial interface (I2C to Serial adapter). With [UnoWiFiDevEdSerial1][1] library you can use the on-board esp8266 and have Serial free for Serial Monitor and sketch upload. The EspProxy tool enables upload to the on-board esp8266 over the ATmega (passing bytes between Serial and Serial1).
I am the author of the UnoWiFiDevEdSerial1 library.

  [1]: https://github.com/jandrassy/UnoWiFiDevEdSerial1


body:
I'm writing an Arduino library to communicate with an I2C device, and I'm wondering what the best way is to declare all the register addresses so as to save memory.

Using `#defines`:

    #define REGISTER_MOTOR_1_MODE 0x44
    #define REGISTER_MOTOR_2_MODE 0x47

Or using `static const`:

    static const uint8_t REGISTER_MOTOR_1_MODE = 0x44;
    static const uint8_t REGISTER_MOTOR_2_MODE = 0x47;

(Obviously I have more than just two registers I need to declare, but I thought two would illustrate the point just fine)

title: Memory usage: #define vs. static const for uint8_t

Answers: 3

body:
You'll find no noticeable difference memory-wise between the two.

The only real difference is that the `const` method also imposes a type to the value, which can be useful for function overloading or mathematical operations.

body:
A `#define` is a preprocessor macro. As Gerben says in his comment, it's just an automated find-and-replace.

If you use it to hold things like C string constants, e.g. `#define ERROR_STRING "You messed up, bud!"` it could actually cause your program to take more memory, since that same string literal will be duplicated every time you reference it. In that case a static const would be both type-safe AND reduce memory usage.

body:
Theoretically both approaches should consume the same amount of space and will probably result in the same code.

---

However, rather than that meaning "pick any one", what that actually means is that you should turn your attention to other factors when deciding which one to use.

As a rule of thumb you should generally avoid macros because they don't respect scoping rules due to how they work.
This can lead to some serious problems in certain cases.
See [Why are preprocessor macros evil and what are the alternatives?](https://stackoverflow.com/q/14041453).

---

However, I'd like to point out a third option: `constexpr`.
```cpp
constexpr uint8_t motorMode1Register = 0x44;
```
`constexpr` implies `const` and is a better expression of the intent that the value should be capable of being evaluated at compile time.
`constexpr` literally means "this is a constant expression and thus can be evaluated at compile time".
As a result of this, `constexpr` variables can be used in situations where other variables cannot, such as template parameters.

See [Constexpr vs Macros](https://stackoverflow.com/q/42388077).


body:
I just received a Nucleo F401RE and can't get my sketch to work on it because the compiler says Serial1 is not defined.
My sketch uses multiple serials because I need to use the usb serial monitor while also communicating to another device on a different serial port.

Here is a screenshot of the flags I selected.

[![compiling flags][1]][1]

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

According to the F401 specs it has at least 6 different serials, so the real question is: is there an easy way to use Serial1 and so on straight out of the box in the Arduino IDE?

I'm quite new and unexperienced to this field, so please excuse me if this question is too trivial.

title: STM32 Nucleo F401RE in Arduino IDE - how to enable more than 1 Serial?

Answers: 1

body:
Frederic Pillon on Github has been very helpful and suggested me the solution, which is to define the serial via:

    HardwareSerial Serial1(PA10, PA9);

instead of just giving Serial1 for granted as you would do on a regular Arduino mega


body:
I want to use serial plotter feature of Arduino by using DHT11 as humidity sensor at a time. But I'm getting problem as plotter is not loading by the code I have. Please help me what is the problem because of which serial plotter is not loading.

Here is the Code I wrote:-

    #include <dht.h>
    #define dht_apin0 A0 // Analog Pin sensor is connected to

    dht DHT0;

    void setup() {

      Serial.begin(9600);
      delay(500);//Delay to let system boot
      Serial.println("DHT11 Humidity Sensor\n");
      delay(1000);//Wait before accessing Sensor

    }//end "setup()"

    void loop(){
      //Start of Program

        DHT0.read11(dht_apin0);

        Serial.print("Current humidity = ");
        Serial.print(DHT0.humidity);
        Serial.print("%  ");

        delay(5000);//Wait 5 seconds before accessing sensor again.

      //Fastest should be once every two seconds.

    }// end loop()

title: Serial plotter isn't displaying my supplied data

Answers: 1

body:
You can't send arbitrary information (percent signs, text etc) to the plotter. The plotter *only* understands numeric values. You have to separate these number values from each other with commas, then do a `println` in your last value:

```
Serial.print(percent);
Serial.print(F(","));
Serial.print(tankPercent(depth));
Serial.print(F(","));
Serial.print(litres);
Serial.print(F(","));
Serial.println(tankLitres(depth));
```

In your case, it'd be simply:

    Serial.println(DHT0.humidity);

You can go a bit further if you want to switch between either serial output, or serial plotter. In one case, I just set a constant variable for graph or plain data, then have a function for each (my above `Serial` statements are actually within a function called `displayGraph()`). The data function would be something like you had originally, example:

```

void displayData(float depth, float percent, float litres){

  // water level depth (inches)

  Serial.print(F("current missing inches: "));
  Serial.println(mixtureDistance());

  // cubic inches

  Serial.print(F("total cubic inches: "));
  Serial.println(TANK_TOTAL_CUBIC_INCHES);

  Serial.print(F("current cubic inches: "));
  Serial.println(tankCurrentCubicInches(depth));

  // litres

  Serial.print(F("total litres: "));
  Serial.println(TANK_TOTAL_LITRES);

  // ... etc
}
```

I also have projects where I use a switch that if on, sets a flag to output in serial graph format, and if off, uses the serial data routine.

Then, in your sketch `loop()`, you'd do something like:

    graph
      ? displayGraph(depth, percent, litres)
      : displayData(depth, percent, litres);

...or a bit more verbose rather than using the tertiary operator:

    if (graph){
      displayGraph(...);
    }
    else {
      displayData(...);
    }

Here's a Q&D serial plotter example of my `displayGraph()` function above. In the top-right corner of the image, the four colours represent the four pieces of data I'm sending in, in order:

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

In my case, those represent the exponential moving average of the percentage of how full a liquid tank is, the second is the raw data I'm building that average on, third is the exponential moving average of how many litres are remaining in the tank, and lastly, again, the raw data for that average.

The sharp movements are simply me slapping the tank to get some variable and unstable readings for example purposes.

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


body:
If I follow this example using my Arduino Uno https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor

(using the 3.3V code example at the bottom of the page), I get reasonable temperatures from the readings over serial.

However, if I try this w/ a LoLin NodeMCU V3 (same circuit layout), my readings seem to be consistently higher than what I get running essentially the same code on the Uno. (Only difference in code is omission of analogReference(EXTERNAL), as the Node V3 appears to run on 3.3V as standard )

I'm fairly new to the whole electronics thing, so any pointers are much appreciated...

Circuit is:

          ----- |---------------- GND on breadboard with jumper to MCU
         | TMP36|---------------- AD0 pin on MCU
          ----- |---------------- breadboard power w/ 3.3V jumper to MCU

title: NodeMCU V3 - Troubleshooting basic TMP36 circuit

Answers: 0


body:
I'm trying to use an ATMega328 board to control a board of a broken UPS device. I replaced all the internals of the UPS by custom components, so the only things which remain are the chassis and the front board.

On this board, there are five buttons, and three LEDs.

[![][1]][1]

All those components are connected to the ground, each one through its own resistor. By connecting the different pins to the ground and to analog pins of the ATMega328 board, I can successfully detect when the buttons are pressed.

[![][2]][2]

Things, however, get tricky when I want to turn the LEDs on. They have their anode connected to the ground (through a 47Ω resistor), and their cathode connected to a dedicated pin. This means that if I apply voltage to this pin, the LED remains off.

The LED, however, turns on if I connect the ground to a 5V pin on ATMega328 board and the cathode pin to the ground of the ATMega328 board. However, connecting the ground to 5V makes it impossible to read the state of the buttons (or should I wire them somehow specifically?)

Therefore, **how do I feed negative current from the ATMega328 board?**

There is [a similar question][3] on this subject, but while the author wants to “understand the underlying electronics of the arduino and microcontrollers in general,” I, instead, just want to know how to make it work. Reading the answers from the linked question, I have an impression that this is possible, but they don't explain *how* to do it.

  [1]: https://i.stack.imgur.com/PxLIX.jpg
  [2]: https://i.stack.imgur.com/0tD2X.jpg
  [3]: https://arduino.stackexchange.com/q/4356/45493

title: How do I provide a negative current?

Answers: 2

body:
If the LEDs turn on when you apply 5V to *ground* then what you have identified as GND on the board is actually VCC.
There is no such thing as *negative current*: current is either **sourced** or **sinked**, depending if it’s exiting or entering into a node.

The diodes (LED) are one way valves, so you have a clear current direction: once that is established, identifying a button press can work either triggering when it gets LOW or when it gets HIGH, in other words that can be easily reversed.

If previously you where detecting a button press with `digitalRead(BTN_PIN) == HIGH` then just switch to `digitalRead(BTN_PIN) == LOW` and you have your solution.

body:
The answer by Roberto Lo Giacco was helpful, but I still had hard time understanding what is happening and how should I wire the boards properly. Since others may encounter similar problems, I'll explain the solution in my own words.

Note that [an answer to a similar question][1] helped me as well.

---

When a digital pin is set to high with `digitalWrite(LED_PIN, HIGH);`, it's similar (probably not in electrical terms, but at least in terms of interface) to connecting to 5V what was previously connected to the pin.

Similarly, `digitalWrite(LED_PIN, LOW);` is similar to connecting to GND what was previously connected to the pin.

This means that when the LED is connected as usual, cathode to the GND and anode (through a resistor) to a digital pin:

 - `digitalWrite(LED_PIN, HIGH);` turns the LED on, and:
 - `digitalWrite(LED_PIN, LOW);` turns it off.

Now, if the cathode is connected to the digital pin, the anode (through a resistor) can be connected to 5V. In this situation:

 - `digitalWrite(LED_PIN, HIGH);` turns the LED off.
 - `digitalWrite(LED_PIN, LOW);` turns it on.

On the photo in my question, the black wire is connected to GND. Instead, it should be connected to 5V. Other wires remain unchanged.

When it comes to the buttons, in order to determine whether the button is pressed or not, I was doing this:

    if (analogRead(ESC_PIN) == 0) {
        // The ESC button is pressed.
    }

When the button wasn't pressed, the values from `analogRead` were quite random, ranging from 50 to 250, or something like that. A zero value would indicate that the button was pressed.

With the new wiring (5V instead of GND), the new values from `analogRead` range from 350 to 900 when the button is not pressed. When the button is down, the value becomes 1023. Therefore, the new condition is simply:

    if (analogRead(ESC_PIN) == 1023) {
        // The ESC button is pressed.
    }

  [1]: https://arduino.stackexchange.com/a/46398/45493


body:
I am currently trying to learn about SPI and how it works on the Arduino. I want to wire a MAX7219 chip to it to drive an 8x8 LED matrix with. Normally, I would assume the wiring from Arduino to MAX7219 goes:

- PIN 10 SS -> CS
- PIN 11 MOSI -> DIN
- PIN 13 SCK -> CLK

And indeed, [this answer][1] confirms my assumption.
However, after going through some other resources and guides I found some confusing and conflicting information about how the pins on the two devices should be connected.

For instance, the documentation that came with my Arduino kit has this schematic.

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

[This tutorial][3] I found has the same wiring.

[![enter image description here][4]][4]

Most surprisingly, [this tutorial][5] doesn't even use the SPI pins at all.

[![enter image description here][6]][6]

What perplexes me the most is the sentence

> The VCC and GND of the module go to the 5V and GND pins of the Arduino and the three other pins, DIN, CLK and CS go to any digital pin of the Arduino board.

Is this true? If yes, then what is the point of the SPI pins at all? Why are the pins wired in so many different configurations?
I am really confused by this.

  [1]: https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino
  [2]: https://i.stack.imgur.com/NoDiw.png
  [3]: https://www.brainy-bits.com/how-to-control-max7219-led-matrix/
  [4]: https://i.stack.imgur.com/gEU5b.png
  [5]: https://howtomechatronics.com/tutorials/arduino/8x8-led-matrix-max7219-tutorial-scrolling-text-android-control-via-bluetooth/
  [6]: https://i.stack.imgur.com/01fNR.png

title: SPI Wiring Confusion

Answers: 3

body:
SPI is a communication protocol, you can take advantage of some hardware optimizations by using the pins where that hardware is available or you can do everything *by hand* using any pin you like, with the disadvantage of a bigger and slower firmware.
In certain situations, like in the presence of a shield or a library already using those pins, the SPI pins might be unavailable and you have to resort to a software solution (aka *bitbang*, as you manipulate bits to generate the proper signals), otherwise use of the hardware SPI pins is strongly advised.

body:
> For instance, the documentation that came with my Arduino kit has this schematic.

Pins 10 through to 13 are standard SPI pins on the Uno.

* 10 (SS)
* 11 (MOSI)
* 12 (MISO)
* 13 (SCK)

I have a tutorial [here](http://www.gammon.com.au/spi). I also have a Stack Exchange [reference question and answer](https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino/16349#16349) about SPI.

---

> Most surprisingly, this tutorial doesn't even use the SPI pins at all.

It is certainly possible to "bit bang" SPI and in some cases this is desirable, for example if you have something like an SD card interface, and also want to use SPI for a display. On the page I linked, specifically at [this post](http://www.gammon.com.au/forum/?id=10892&reply=6#reply6) I describe how to bit-bang SPI.

---

> What perplexes me the most is the sentence
>
> The VCC and GND of the module go to the 5V and GND pins of the Arduino and the three other pins, DIN, CLK and CS go to any digital pin of the Arduino board.

For bit-banged SPI, yes you can use any pins.

---

> Is this true? If yes, then what is the point of the SPI pins at all?

The hardware SPI is faster and easier, and you can do other things while SPI is sending/receiving but with bit-banging it is much more timing-dependent.

body:
This video shows a project I did with a Duemilanove, 4 MAX7219s driving 4 8x8 LED matrices, and powered via 7.5V power supply.  https://www.youtube.com/watch?v=hwYqgyMc5S4

With a 9V supply, the 5V regulator overheated and shut down after some number of minutes. With 7.5V, there was no problem.

The SPI and power pins, 5V, Gnd, SCK, MOSI, go to all devices, and each chip has its own SS pin (I didn't want to deal with sending out a bunch of NOP commands to feed data thru daisy-chained chips).  Data to all 4 devices is refreshed as fast as 50mS, any faster and the display got too hard to read. I think I only used SPI at 4 MHz too, I have done other projects with SCK at 8 MHz, that can send out data really fast.


body:
We are trying to burn bootloader into ATMega328P-AU SMD. We have taken the reference of the **[link][1]** and did the same. We checked wire connections and all looks fine and we tried with two chip with two separate boards and we got same result.

But we tried many times and got the same error as follows,

Could someone help us on this?

        /data/install/arduino-1.8.8/hardware/tools/avr/bin/avrdude -C/data/install/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyUSB0 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

    avrdude: Version 6.3-20171130
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/data/install/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/home/sankar/.avrduderc"

             Using Port                    : /dev/ttyUSB0
             Using Programmer              : arduino
             Overriding Baud Rate          : 19200
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x15
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x15
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x02

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
             Hardware Version: 4238814
             Firmware Version: 24405360.0
             Topcard         : STK502
             Vtarget         : 1.8 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x10

    avrdude done.  Thank you.

    Error while burning bootloader.

  [1]: http://www.electronoobs.com/eng_arduino_tut6.php

title: ATMega328 AU bootloader burning issue using Nano

Answers: 0