message:
Communication between 2 Bluetooth modules

I successfully connected two Bluetooth modules, HC-05 and HC-06 like on this website:

http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link/

I have an Arduino Nano that's the slave (HC-06) and an Arduino Mega that is the master (HC - 05) and there's is the code for both of them:

**Reveiver - Master**

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11); // RX | TX
    String Data = "";
    void setup() {
        Serial.begin(9600);
        mySerial.begin(9600);
    }

    void loop(){
        while (mySerial.available()){
            Serial.println(mySerial.read())
        }
    }

**Sender - Slave**

    #include <SoftwareSerial.h>
    SoftwareSerial BTserial(11, 10); // RX | TX

    int c = 100;

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

    void loop(){
         BTserial.println(c);
    }

I tried

    BTserial.write(c)

and doesn't work either, I receive numbers like 245,255. And when I change the data that I'm sending the numbers are different, so I know that they are communicating, I think it's a variable problem, but I tried a bunch of codes of the internet that supposedly work, but it doesn't seem to work for this case.

body:
println prints the int variable c as string "100" with /r/n at the end. And you read it as bytes with read and print the bytes as numbers with new line at the end. So you get ascii values of 1, 0, 0, \r and \n.

use write() to write a byte to Bluetooth and to Serial Monitor


sender: user

message:
Why does Serial.print print only a value for 0-84 for a 100 integer array?

int a[100],i;
    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      for(i=0; i<100; i++) {
        a[i] = i;
        Serial.println(a[i]);
      }
      exit(0);
    }

sender: assistant

body:
It's because you're using `exit(0)`.  That turns off interrupts and goes into an infinite loop. However, serial printing is first placed into a buffer, and each character is then removed from that buffer in turn and sent out through the serial port.

That's all fine, up until the end when you use `exit(0);`, and what is left in the serial buffer to send never gets sent because interrupts are disabled.

There is never really any cause to use `exit()` on a microcontroller - after all, where can it "exit" to? There's no OS to exit to. So it does the next best thing which is as close to doing nothing as reasonably possible.

Instead, if you want to "stop" your program you should use a simple `while(1);` which will allow interrupts to still trigger.

Alternatively, if you really want to use `exit()`, you should `flush` the serial first:

    Serial.flush();

That function will block until the transmit buffer has been fully emptied by the interrupt and the last byte has left the UART's TX shift register.


message:
How to stop a loop when using attachInterrupt to catch the change of a button

This what the program does:

> There is 1 button to start/stop the engine, when the motor is running
> the green LED will go on, when stopped the red LED is on. The second
> button is used to change the direction of the DC-motor. When the
> temperature is above 20° the motor will stop and the servo motor will
> go to the position of the red LED. Otherwise the servo motor is in a
> neutral position. When the engine is running there a music playing that should sound as a car.

So what my problem is if I pressed the button to stop the DC-motor but the music is still playing it won't stop. I read something about a [break][1]. Can you combine this with the `attachInterrupt()`? I also found something called [`interrupts()` and `noInterrupts()`][2]. What do I need to so when I pressed the button the DC-Motor directly stops and the led turns red?

The init

    #include <Servo.h>
    #include "notebook.h";
    #include "themes.h";

    const int input1OfTheDCMotor = 9;
    const int input2OfTheDCMotor = 10;
    const int pwmInputOfTheDCMotor = 6;
    const int buttonToStartStopTheDcMotor = 2;
    const int buttonToShowToChangeTheDirectionOfTheDCMotor = 3;
    const int greenLed = 12;
    const int redLed = 8;
    const int tempSensor = A0;
    const int servoPin = 11;
    Servo servo;

    volatile byte stateOfTheButtonToStartStopTheDCMotor = LOW;
    bool isRunning = LOW;
    bool changeDirection = LOW;
    bool isEngineSoundsPlaying = HIGH;

The `setup()`

    void setup() {
      //Leds setup
      pinMode(greenLed, OUTPUT);
      pinMode(redLed, OUTPUT);
      digitalWrite(redLed, HIGH);
      //buttons
      pinMode(buttonToStartStopTheDcMotor, INPUT);
      pinMode(buttonToShowToChangeTheDirectionOfTheDCMotor, INPUT);
      //DC motor
      pinMode(input1OfTheDCMotor, OUTPUT);
      pinMode(input2OfTheDCMotor, OUTPUT);
      digitalWrite(input1OfTheDCMotor, LOW);
      digitalWrite(input2OfTheDCMotor, HIGH);
      //pwm signal
      pinMode(pwmInputOfTheDCMotor, OUTPUT);
      //Servo
      servo.attach(servoPin);
      //interrupts
      attachInterrupt(digitalPinToInterrupt(buttonToStartStopTheDcMotor), readTheChangeToStartStop, RISING );
      attachInterrupt(digitalPinToInterrupt(buttonToShowToChangeTheDirectionOfTheDCMotor), readTheChangeToChangeDirection, RISING );
    }

The `loop()`

    void loop() {
      int valueOfTheSensor = analogRead(tempSensor);
      float voltage = (valueOfTheSensor / 1024.0) * 5.0;
      float temp = (voltage -0.5) * 100;
      if (temp >= 20.00)
        isRunning = LOW;
      }
      changeTheStateOfTheLights(isRunning);
      startTheDCMotorAndStopIt(isRunning);
      changeTheDirectionOfTheDCMotor(changeDirection);
    }

The function `readTheChangeToStartStop()`:

    void readTheChangeToStartStop () {
      isRunning  = !isRunning;
      changeTheStatusOfTheEnginePlaying();
    }

The function `readTheChangeToChangeDirection()`:

    void readTheChangeToChangeDirection () {
      changeDirection = !changeDirection;
    }

The function `changeTheStatusOfTheEnginePlaying()`:

    void changeTheStatusOfTheEnginePlaying (){
      if (isRunning == HIGH){
        isEngineSoundsPlaying = HIGH;
      } else {
        isEngineSoundsPlaying = LOW;
      }
    }

The function `changeTheStateOfTheLights()`:

    void changeTheStateOfTheLights(bool stateOfLight) {
      digitalWrite(greenLed, stateOfLight);
      digitalWrite(redLed, !stateOfLight);
    }

The function `startTheDCMotorAndStopIt()`:

    void startTheDCMotorAndStopIt(bool isRunning){
      if (isRunning == HIGH) {
        digitalWrite(pwmInputOfTheDCMotor, HIGH);
        playCarMusicStart();
        changeToNeutral();
      } else {
        digitalWrite(pwmInputOfTheDCMotor, LOW);
        changeToRedLight();
      }
    }

The function `changeTheDirectionOfTheDCMotor()`:

    void changeTheDirectionOfTheDCMotor(bool changeDirection) {
      digitalWrite(input1OfTheDCMotor, changeDirection);
      digitalWrite(input2OfTheDCMotor, !changeDirection);
    }

The function `changeToRedLight()`:

    void changeToRedLight() {
      servo.write(0);
      delay(15);
    }

The function `changeToNeutral()`:

    void changeToNeutral() {
      servo.write(40);
      delay(15);
    }

The function `playCarMusicStart()`:

    void playCarMusicStart(){
      if (isEngineSoundsPlaying == HIGH) {
        for (int thisNote = 0; thisNote < (sizeof(carSounds_note)/sizeof(int)); thisNote++) {
          int noteDuration = 1000 / carsounds_duration[thisNote];
          tone(4, carSounds_note[thisNote], noteDuration);
          int pauseBetweenNotes = noteDuration * 2.70;
          delay(pauseBetweenNotes);
          noTone(4);
          isEngineSoundsPlaying = LOW;
        }
      }
    }

#Solution
##A big thanks to @ratchet freak

I need to change my `loop()` to this:

    void loop() {
      int valueOfTheSensor = analogRead(tempSensor);
      float voltage = (valueOfTheSensor / 1024.0) * 5.0;
      float temp = (voltage -0.5) * 100;
      if (temp >= 20.00) {
        isRunning = LOW;
      }
      changeTheStateOfTheLights(isRunning);
      startTheDCMotorAndStopIt(isRunning);
      changeTheDirectionOfTheDCMotor(changeDirection);

      playCarMusicStart();
    }

I also needed to change the `PlayCarMusicStart()`:

    void playCarMusicStart(){
      if (isEngineSoundsPlaying == HIGH && currentNote < (sizeof(carSounds_note)/sizeof(int))) {
          int noteDuration = 1000 / carsounds_duration[currentNote];
          tone(4, carSounds_note[currentNote], noteDuration);
          int pauseBetweenNotes = noteDuration * 2.70;
          delay(pauseBetweenNotes);
          noTone(4);
          currentNote++;
       } else {
          currentNote = 0;
       }
    }

And the least is to set the `isEngineSoundsPlaying` equal to `HIGH`, I changed the function `startTheDCMotorAndStopIt()` for:

    void startTheDCMotorAndStopIt(bool isRunning){
      if (isRunning == HIGH) {
        isEngineSoundsPlaying = HIGH;
        digitalWrite(pwmInputOfTheDCMotor, HIGH);
        changeToNeutral();
      } else {
        isEngineSoundsPlaying = LOW;
        digitalWrite(pwmInputOfTheDCMotor, LOW);
        changeToRedLight();
      }
    }

  [1]: https://www.arduino.cc/en/Reference.Break
  [2]: https://www.arduino.cc/reference/en/language/functions/interrupts/interrupts/

body:
The key will be to split up `playCarMusicStart` and instead create a `playCarMusicStep` that will do just one iteration of the loop and returns. Call it every time in `loop()` akin to blinkWithoutDelay.

In playCarMusicStart you then setup the playing state so it starts playing correctly.

And when you need to stop it you then stop the music by setting the correct variable.


message:
Comparing button presses to correct sequence

I am creating a memory game with the Arduino. It has four buttons, each for a different colored led. The leds will blink in a random sequence and either fail or add another light in the next sequence if the user presses the correct buttons. I have also attached an lcd screen to late implement a score tally.

Right now, the welcome lights display and the sound is working fine, but when the sequence starts, it will act as though I am pressing a button and proceed through the fail light method. I think the last method is causing this issue where I am comparing the button pressed to the sequence.

I would appreciate any help!

This is essentially my wiring just with different pins chosen:
[![enter image description here][1]][1]

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

body:
The problem might be that you do not debounce the buttons. When you press a button, there is somehwere between fully pressed and not pressed (or backwards) a state there it 'bounces', e.g. you get lots of state transitions, resulting in seeing a button pressed twice or many times instead of once.

Check the [debounce example][1] in the default Arduino Tutorial

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


body: I found that I did not need the pull down resistors for each button since I had declared the pinMode for each button to be INPUT_PULLUP. So instead of the schematic above, I took out the resistors for the buttons and instead wired one side of the buttons to ground.


message:
Arduino JSON foreach loop

I'm trying to extract values using ArduinoJson. The values aren't fixed, therefore I need to use the foreach loop.

I'm trying this, but I can't seem to use the values like I could with.

    root["0"]["value"].as<const char*>();

Here is my code.

    void loop(){
      int httpCode = http.GET();
      if(httpCode > 0) {
        // if Get request has processed
        if(httpCode == HTTP_CODE_OK) {
          payload = http.getString();
        }
        if(payload.length() > 0) {
          Serial.println(payload);
          JsonObject& root = jsonBuffer.parseObject(payload);
          if (!root.success()) {
            Serial.println("parseObject() failed");
            jsonBuffer.clear();
          } else {
            Serial.println("Data Fetched");
            for(JsonPair& node : root) {
              Serial.print("0 State: ");
              Serial.println(*node);
            }
            http.end();
          }
        } else {
          Serial.println("Payload Empty");
        }
      }
    }

Please avoid any missing brackets. Thanks in advance.

    [{"state": true, "value": 10}, {"state": false, "value": 8}, {"state": false, "value": 5}, {"state": false, "value": 13}]

body:
I found another way around the solution.

Idk if this is helpful to anyone but the problem was that I had an unknown number of nodes I wanted to loop through, Example of the json format above.

    void loop(){
    int httpCode = http.GET();
      if(httpCode > 0) {
        // if Get request has processed
        if(httpCode == HTTP_CODE_OK) {
              payload = http.getString();
          }
          if(payload.length() > 0){
              JsonArray& nodes = jsonBuffer.parseArray(payload);
              if (!nodes.success()) {
                Serial.println("parseObject() failed");
                jsonBuffer.clear();
              }else{
                int node_length = nodes.size();
                for(int i=0; i<node_length;i++){
                  Serial.printf("node-%i\nValue : ",i );
                  String value = nodes[i]["value"].as<const char*>();
                  String state = nodes[i]["state"].as<const char*>();
                  Serial.println(value);
                  Serial.print("State : ");
                  Serial.println(state);
                }
                http.end();
            }
        }else{
          Serial.println("Payload Empty");
        }
      }

      jsonBuffer.clear();
      delay(8000);
    }


message:
STM32 VGA Output - don't understand why lines are jagged

I am using "blue-pill" STM32F103C8 (http://wiki.stm32duino.com/index.php?title=Blue_Pill) to create VGA output. I am connecting PB6 to VSync, PB0 to HSync, and PA0 to red using 278 Ohm resistor.

I don't understand why the lines are "jagged", like in the picture: [![enter image description here][1]][1]

I would appreciate any input.

By the way, my real code is more complex and can display 256x192 with 64 colors. Since this board has 20K memory, I am using separate areas for pixels and colors, like Sinclair ZX (https://en.wikipedia.org/wiki/ZX_Spectrum_graphic_modes).

This is my code:

    // interrupt handlers
    void EndVBackPorch();
    void ShockAbsorber();

    volatile uint8 *GPIO_ODR;
    volatile int vflag = 0; /* When 1, can draw on the screen */

    void setup()
    {
      pinMode(PB6, PWM); // VSync
      pinMode(PB0, PWM); // HSync

      // PA0..PA5 set to OUTPUT with max speed 50 MHz
      GPIOA->regs->CRL = 0x88333333;
      GPIO_ODR = (volatile uint8_t *)&GPIOA->regs->ODR;

      // 640 x 480 @ 60 Hz (Standard, pixel clock frequency 25.17 MHz)
      //InitHSync(false, 2287, 275, 400);
      //InitVSync(false, 525, 2, 35 + 48);

      // 640 x 480 @ 60 Hz (non-standard, pixel clock frequency 24.0 MHz)
      InitHSync(true, 2376, 264, 370);
      InitVSync(true, 505, 5, 10 + 74);
    }

    void loop()
    {
        // Everything happens in the interrupts
    }

    void InitVSync(
      bool isNegative,
      int wholeFrame,
      int syncPulse,
      int startDraw)
    {
      HardwareTimer timerVSync(4);

      timerVSync.pause();
      timerVSync.setPrescaleFactor(1);
      timerVSync.setOverflow(wholeFrame); /* Vertical lines */

      // VSync on pin PB6
      timer_oc_set_mode(timerVSync.c_dev(), TIMER_CH1,
                isNegative ? TIMER_OC_MODE_PWM_2 : TIMER_OC_MODE_PWM_1, TIMER_OC_PE);
      timerVSync.setCompare(TIMER_CH1, syncPulse);

      timerVSync.setChannelMode(TIMER_CH4, TIMER_OUTPUT_COMPARE);
      timerVSync.setCompare(TIMER_CH4, startDraw);
      timerVSync.attachInterrupt(TIMER_CH4, EndVBackPorch);

      // Slave mode Gated, triggered by TIM3
      timerVSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_SMS);
      timerVSync.c_dev()->regs.adv->SMCR |= ((uint16_t)TIMER_SMCR_SMS_GATED);
      timerVSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_TS);
      timerVSync.c_dev()->regs.adv->SMCR |= (uint16_t)TIMER_SMCR_TS_ITR2;

      //nvic_irq_set_priority(NVIC_TIMER4, 1);

      timerVSync.refresh();
      timerVSync.resume();
    }

    void InitHSync(
      bool isNegative,
      int wholeLine,
      int syncPulse,
      int startDraw)
    {
      HardwareTimer timerShockAbsorber(2);
      timerShockAbsorber.pause();
      timerShockAbsorber.setPrescaleFactor(1);
      timerShockAbsorber.setOverflow(wholeLine);

      timerShockAbsorber.setChannelMode(TIMER_CH1, TIMER_OUTPUT_COMPARE);
      timerShockAbsorber.setCompare(TIMER_CH1, 0);

      timerShockAbsorber.setChannelMode(TIMER_CH2, TIMER_OUTPUT_COMPARE);
      timerShockAbsorber.setCompare(TIMER_CH2, startDraw - 12);
      timerShockAbsorber.attachInterrupt(TIMER_CH2, ShockAbsorber);

      // Master mode, TIM_TRGOSource_Enable
      bitSet(timerShockAbsorber.c_dev()->regs.adv->SMCR, TIMER_SMCR_MSM_BIT);
      timerShockAbsorber.setMasterModeTrGo(TIMER_CR2_MMS_ENABLE);

      timerShockAbsorber.refresh();

      HardwareTimer timerHSync(3);
      timerHSync.pause();
      timerHSync.setPrescaleFactor(1);
      timerHSync.setOverflow(wholeLine);

      // HSYNC on pin PB0
      timer_oc_set_mode(timerHSync.c_dev(), TIMER_CH3,
                isNegative ? TIMER_OC_MODE_PWM_2 : TIMER_OC_MODE_PWM_1, TIMER_OC_PE);
      timerHSync.setCompare(TIMER_CH3, syncPulse);

      timerHSync.setChannelMode(TIMER_CH4, TIMER_OUTPUT_COMPARE);
      timerHSync.setCompare(TIMER_CH4, startDraw);
      timerHSync.attachInterrupt(TIMER_CH4, Draw);

      // Slave mode Trigger, triggered by TIM2
      timerHSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_SMS);
      timerHSync.c_dev()->regs.adv->SMCR |= ((uint16_t)TIMER_SMCR_SMS_TRIGGER);
      timerHSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_TS);
      timerHSync.c_dev()->regs.adv->SMCR |= (uint16_t)TIMER_SMCR_TS_ITR1;

      // Master mode, TIM_TRGOSource_Update
      bitSet(timerHSync.c_dev()->regs.adv->SMCR, TIMER_SMCR_MSM_BIT);
      timerHSync.setMasterModeTrGo(TIMER_CR2_MMS_UPDATE);

      nvic_irq_set_priority(NVIC_TIMER3, 0);

      timerHSync.refresh();

      // Starts timerHSync as well
      timerShockAbsorber.resume();
    }

    void EndVBackPorch()
    {
      vflag = 1;
    }

    void ShockAbsorber()
    {
      // Wait for interrupt
      __asm__ volatile("wfi \n\t" :::);
    }

    void Draw()
    {
      if (!vflag)
      {
        return;
      }

      noInterrupts();

      __asm__ volatile(

        "  mov r0, #3        \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  strb r0, [%[odr]] \n\t"
        "  mov r0, #0        \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  strb r0, [%[odr]] \n\t"
        "  mov r0, #3        \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  strb r0, [%[odr]] \n\t"
        "  mov r0, #0        \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  strb r0, [%[odr]] \n\t"
        "  mov r0, #3        \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  strb r0, [%[odr]] \n\t"
        "  mov r0, #0        \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  nop               \n\t"
        "  strb r0, [%[odr]] \n\t"

        :
        : [odr] "r"(GPIO_ODR)
        : "r0");

      interrupts();
    }

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

body:
I found a similar issue when I developed [code to display on a VGA monitor](http://www.gammon.com.au/forum/?id=11608).

The reason for the slight jitter is that when an interrupt fires, it can't stop in the middle of an instruction. So there are potentially one or two extra clock cycles before the interrupt is processed.

Those clock cycles would account for the slight jaggedness on the right. The way to avoid that is to go to sleep between horizontal lines (idle sleep mode). This wakes up instantly, but the important thing is it wakes up at the start of an instruction cycle, so you don't get a one or two cycle delay.

I can't see any sleeping in your code, and I'm not sure if your STM32F103C8 would compensate for that, but certainly it is worth trying.

I can't see a "main" loop, presumably it doesn't do much until an interrupt fires.

My main loop is this:

    void loop()
      {
      // sleep to ensure we start up in a predictable way
      sleep_mode ();
      doOneScanLine ();
     }  // end of loop

Note the sleep which ensures that it starts the drawing at the same time each time (of course the interrupt will take time, but at least it takes the same time every scan line).


message:
How to use use 2 or more HC-SR04 sensors as one single sensor?

I'm new to Arduino and this is my problem. I need to track an object in a room. For now I have placed 3 sensors on the edges of each axis (x, y, z), where the x axis will the line between the east and the west walls of the room, the y axis will be the north and south walls of the room, and the z axis will be the ceiling of the room.

I have written code to get the output as x, y, z coordinates. But since the HC-SR04 has no horizontal range it can only track objects in its line of sight. Due to this I'm not able to fulfil my requirements. So I thought if I could couple up an array of HC-SR04s together to work as one sensor I can get more horizontal range.

Is this possible using an Arduino Uno R3? If it's possible, please guide me through it.

body:
You can try attaching your HC-SR04 sensor to a servo, then you will have a range of detecting an object in 180 degree span.

 [![Sample][1]][1]

Of course you will have to make modifications to fit your purpose. Using three ultrasonic sensors with each of them having their own servo of 180 degree range will surely increase accuracy. To get started visit [here][2].
Hope this was what you were looking for.

(Image credits: Dejan Nedelkovski)

  [1]: https://i.stack.imgur.com/5Wt1F.jpg
  [2]: https://howtomechatronics.com/projects/arduino-radar-project/


message:
MQ135 Gas Sensor Calibration

I have bought a MQ135 gas sensor. I have read online from multiple sources that a calibration/warm-up period of between 12-24hrs is required for the sensor to give its most accurate readings. I currently have it attached to one of my UNO's just spitting out Analog readings to the Serial monitor and seems (just after an hour!) to have settled at a reading of 50 which it has stayed at now for a period of around 20 minutes. My questions surrounding this process really are:

1. What is the point in doing this process if when a project that uses this sensor is powered off for some number of hours? Will you have to let it warm-up/calibrate again before having faith in the readings?
2. How do I actually identify PPM for a gas such as C02? Is there some form of constant that I should be comparing the reading obtained to or something similar?

body: By my opinion, it is impossible to calibrate these solid electrolyte based sensors. I achieved best results when I measured the CO2 level in 5 minute intervals, by heating the sensor for 100 seconds. I cant remember these times precisely, but by heating and allowing it to cool down I was able to get quite reliable results. But then I realized that the sensor is getting some offset. If you want to do a two-point calibration, you can put it to fresh air, it should read [about 0.04%](https://www.quora.com/What-is-the-percentage-of-CO2-in-the-atmosphere), or you can breathe directly to the sensor for a short while and it [shoud read 4%](https://sciencing.com/chemical-composition-exhaled-air-human-lungs-11795.html). But I highly recommend using [NDIR CO2 sensor](https://www.co2meter.com/blogs/news/6010192-how-does-an-ndir-co2-sensor-work), those are used in home air monitoring devices.


message:
Creating public instance of class in another class's initialization

I'm using several TM1637 displays to create timers, so I decided to make a Timer class. Every time I initialize an instance of the Timer class, I want it to create an instance of the TM1637Display class. So I started out with this, but the display object can't be accessed from within updateDisplay.

    class Timer {
    public:
        Timer(uint8_t CLK, uint8_t DIO) {
            TM1637Display display(CLK, DIO);
            ...
        }
        void updateDisplay() {
            ...
            display.setSegments(displayData);
        }
    }

And if I do this I get the compile time error `In constructor 'Timer::Timer(uint8_t, uint8_t)': src\main.cpp:16:37: error: no matching function for call to 'TM1637Display::TM1637Display()'`

        TM1637Display display;
        Timer(uint8_t CLK, uint8_t DIO) {
            display(CLK, DIO);
            ...
        }

What should I try? Maybe make an empty pointer before the display instance is created with a public scope, assign the pointer to the display instance, then hand the updateDisplay function the pointer? That seems really convoluted.

body:
As it's now in the first example, it's local variable in Timer constructor.

In the second one you have to use member initializer list in constructor as there is no default constructor in your display class.

    class Timer {
    public:
        Timer(uint8_t CLK, uint8_t DIO)
        : display(CLK, DIO) // constructor's initializer list
        {
            ...
        }
        void updateDisplay() {
            ...
            display.setSegments(displayData);
        }

        // member variable:
        TM1637Display display;
    }


message:
Run python in Windows OS installed in micro SD card which is read by Arduino microcontroller board

I have a python code which runs in my computer with Windows operating system. The code reads some images as input, extends some cognitive services apis from Microsoft azure and finally give an audio output. I would like to run this code on an independent device, for which I am thinking to have a motherboard like Arduino (I can use raspberry pi, but it's a small project and I don't want to invest that much). However being an amateur in this genre, I have some questions and would really like if someone could help.

 I want the system to have an independent processing power, with the operating system loaded in a micro SD card. I do not want to connect  Arduino with my pc and run the code from there. It will not make any sense since the PC/laptop is already able to do the work, what would I need Arduino for?

Can someone please tell me if it is possible to have an operating system installed in a micro SD card (bootable) and have it inserted in the Arduino board so that I can run the python code within the SD card?

body:
With some Arduino boards, yes.  You want a board like the Yun (unfortunately retired now, but there are probably others similar) which has a MIPS SoC on it that runs Linux (specifically OpenWRT).  The OS is installed into the SoC, but there is an SD card slot that will allow you to read your code.

An alternative is a Yun shield (available from third parties, such as the [Dragino Yun Shield](http://www.dragino.com/products/yunshield/item/86-yun-shield.html)).  This turns any Uno-like Arduino into a Yun.   Of course, you can run it without any Arduino attached if you so wish to wire it manually.

However, with all these, you're getting into the price bracket of a Raspberry Pi, so you may as well do it properly and just get a Raspberry.


message:
Flashing ATmega8U2 using another Arduino

I have an Anduino Uno R1 and the ATmega8U2 on. It does not respond correctly. How can I use another Arduino Uno R3 in order to reinstall the correct firmware? What I want to avoid it to solder the resistor because I am not very good with the soldering iron.

As fas as I understand there are some pins close to the AREF pin that can be used in order to attach a programmer. Also how can I temporally attach them without the need of a soldering iron? On the R1 the pins are just some exposed metal. How can I connect to them?

Also, if I load into the other Arduino the programmer, then how can I load the firmware using GNU/Linux into the ATmega8U2?

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

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

body:
There is an official guide. [Arduino as ISP and Arduino Bootloaders][1]

But you need to add the 2x3 ISP pin header since some of the signals isn't available on D0-D13 or any other pins.

  [1]: https://www.arduino.cc/en/tutorial/arduinoISP


message:
SIM900 and Mega 2560 not sending SMS

I just bought a SIM900 Arduino shield from AZDelivery. I only have a Mega 2560 board, thus I am trying to use this although most examples (like the tutorial from AZDelivery) are with the Uno board. I am using the SIM card from my mobile phone, not having any PIN. [This][1] is the Arduino library I am using.

1. I didn't flash anything on the SIM900 board prior to testing, because in the instructions from AZDelivery Ebook this was not mentioned.

2. My NetLight LED is blinking constantly (1 blink per second) I guess it is not finding the mobile network.

3. At the momemt, I only have a 1A supply, though I've already ordered a new one with 2A. Could this be the reason for point 2? Does the board need 2A to log into the network?

4. Asuming it would log into the network, the AZDelivery Instruction Sketch/Example is using "SoftwareSerial.h" due to its compatibility to the Uno board. Since I am using a Mega board, can I just use D30 and D31 and set them as Rx and Tx using the SoftwareSerial library?

5. Can you give me a link to an up-to-date library and/or example for SIM900 working with the Mega 2560 Rev3 and Arduino 1.8.4?

I hope you can help me getting started with the SIM900 module.

  [1]: https://github.com/MarcoMartines/GSM-GPRS-GPS-Shield library

body:
I was just able to send an SMS (even with the 1A supply). Here the answers to my questions.

 1. No, it is not necessary to flash the SIM900 board
 2. I was not connected, because I didn't insert the SIM card properly on the shield.
 3. No it does not necessarily need 2A for logging into network and obviously not for sending SMS though there might be reasons for the board consuming 2A during SMS sending, e.g. bad network connection.
 4. If you want to use Sotware Serial, you need certain digital lines allowing software interrupts. In the case of the **MEGA board**, e.g. D10, D11 or for the **UNO** D7,D8.
 5. I was using [this tutorial][1] to get communication via SoftwareSerial working. Afterwards I added the code for sending SMS.

I hope I can help some others who are looking for a low level description of how to get started with MEGA and SIM900.

  [1]: http://hotresistor.blogspot.de/2015/02/interfacing-simcom-sim900-with-arduino.html


message:
Check if servo is connected to arduino

#include <Servo.h>

    Servo esc;

    void setup(void) {
      esc.attach(7, 1000, 2000);

      if (esc.attached()) {
        // this always runs
        // even if there's no servo connected to pin 7
      }
    }

I've written code kind of like the above.

The problem is that after using `Servo.attach` the method `Servo.attached` always returns true, even if there's nothing in the pin that I've attached to.

How can I check if the pin, in this case `7`, actually has a wire in it?

body:
You cannot check, if a servo or a wire is physically connected to the pin, without extra effort. The Servo library uses Timer interrupts to create a PWM signal for the servo on the used pin. For this the pin is configured as OUTPUT and cannot measure anything except of the value, that was written to it. In most servo motors the PWM input is high impedance, so that the current draw from the PWM pin is very low.

To solve your problem you have 2 possibilities:

 1. Use a special connector, that has 2 extra pins with a mechanical switch, which gets closed, when the connector is put together. (The same principle as in SD card holders)
 2. Measure the current, that the servo uses through it's power supply pins, with a suitable circuit.


message:
Arduino Uno R1 I soldered resistor but I cannot DFU program atmega8u2

I have an Arduino R1 board (the very first one) and I managed to solder the resistor into Arduino's Atmega8u2 (I went to a specialist in order to do that). Then I reset atmega8u2 and by wiring the pins mentioned in: https://www.arduino.cc/en/Hacking/DFUProgramming8U2

I can confirm it via this message over my GNU/Linux machine by running `dmesg`:

    [ 1544.679504] usb 1-6: new full-speed USB device number 42 using xhci_hcd
    [ 1544.808341] usb 1-6: New USB device found, idVendor=03eb, idProduct=2ff7
    [ 1544.808350] usb 1-6: New USB device strings: Mfr=0, Product=1, SerialNumber=0
    [ 1544.808356] usb 1-6: Product: Arduino Uno DFU

I also to confirm that I run `lsusb` and I got the following result:

    Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 001 Device 002: ID 248a:8367
    Bus 001 Device 058: ID 03eb:2ff7 Atmel Corp.
    Bus 001 Device 003: ID 058f:6362 Alcor Micro Corp. Flash Card Reader/Writer
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Further indicating to me that arduino is in DFU mode over my ubuntu 16.04 machine. Also I further verify via `dfu-util -l` command:

    Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
    Copyright 2010-2014 Tormod Volden and Stefan Schmidt
    This program is Free Software and has ABSOLUTELY NO WARRANTY
    Please report bugs to dfu-util@lists.gnumonks.org

    Found DFU: [03eb:2ff7] ver=0000, devnum=63, cfg=1, intf=0, alt=0, name="UNKNOWN", serial="UNKNOWN"

The I try to run:

`sudo dfu-programmer atmega8u2 erase`

But for some reason I get the following error:
`dfu-programmer: no device present.`

Do you know why I get this error and how I can fix it?

# Edit 1
I installed the latest version of dfu-programmer and compiled from source via https://sourceforge.net/projects/dfu-programmer/files/dfu-programmer/0.7.2/ but still I get the error. I also tried to compile it with `libusb-1.0.0`

# Edit2

I also tried [this](https://github.com/swinman/dfu-programmer/tree/libusb_no_device) version with `libusb-1.0.0` but still the same error occurs.

# Edit 3
As many suggest I tried to do multiple times but still I get this error.

# Edit 4

I also used `dfu-util` and I try to insert the data into the atmega8u2 via:

     sudo dfu-util -d 03eb:2ff7 -D ./Arduino-usbserial-uno.hex -R

But I get the error:

    dfu-util 0.8

    Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
    Copyright 2010-2014 Tormod Volden and Stefan Schmidt
    This program is Free Software and has ABSOLUTELY NO WARRANTY
    Please report bugs to dfu-util@lists.gnumonks.org

    dfu-util: Invalid DFU suffix signature
    dfu-util: A valid DFU suffix will be required in a future dfu-util release!!!
    Opening DFU capable USB device...
    ID 03eb:2ff7
    Run-time device DFU version 0100
    Claiming USB DFU Interface...
    Setting Alternate Setting #0 ...
    Determining device status: state = dfuIDLE, status = 0
    dfuIDLE, continuing
    DFU mode device DFU version 0100
    Device returned transfer size 3072
    Copying data from PC to DFU device
    Download    [                         ]   0%            0 bytesdfu-util: Error during download
    dfu-util: can't detach
    Resetting USB to switch back to runtime mode

body:
According to https://gebloggendings.wordpress.com/category/elektronik/arduino/ it is sometimes not to assume that the `atmega8u2` is always the correct value in my case was the `at90usb82` resulting into using the following command sequence:

    sudo dfu-programmer at90usb82 erase
    # Flashing the arduino provided .hex
    sudo dfu-programmer at90usb82 /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/Arduino-usbserial-uno.hex
    # reset the board
    sudo dfu-programmer at90usb82 reset

Further information you can find into:

* https://forum.arduino.cc/index.php?topic=53443.0
* https://forum.arduino.cc/index.php?topic=542854.0


message:
How does Peggy2 drive rows with 74HC154 Decoder?

Trying to program Evil Mad Scientist's Peggy 2 board without their Library.
The board drives a LED Matrix with

 - Source  74HC154 Decoder
 - Sink    STP16CPSO5  LED Sink Driver

[Schematic][1]

What has me confused is the 74HC154 Outputs can only have one output set to Low at at time. See table below. This means all but one row is "on". Isn't this backwards?  Shouldn't all outputs be low except one that is high?  Selecting what row you want on, rather than selecting what row you want off.  It looks more like the 74HC154 is a Sink.  Thanks.

[![Output Table for 74HC154][2]][2]

  [1]: https://bcdn.evilmadscientist.com/source/p2leschem.pdf
  [2]: https://i.stack.imgur.com/EfVhj.jpg

body:
If you look into the datasheet of 74HC154, you can see that each output has an Active Low State. Also in the schematic, the leds row part use a pnp transistor (see page two). As so, they will be active if the input is low.

> This means all but one row is "on". Isn't this backwards?

Since they are PNP, the only active row is the one with Low value and the current of that row is sink through the selected column(s) in the STP16CPS05


message:
How can I connect an Arduino / ESP8266 to an Azure MySQL database?

I am currently trying to connect an ESP8266 to my Azure MySQL database via WiFi, but have not yet been successful.

I have tried a bunch of guides, but no luck and I'm running out of ideas. I have made a connection to an IoT Hub in Azure but could not forward the messages to the MySQL database in the cloud. I managed to get it stored in a blob datatype but had so many issues with it that I kinda scratched that idea.

Last thing I tried was trying to implement the example from
https://github.com/ChuckBell/MySQL_Connector_Arduino
more specifically the 'connect_wifi' example. I was unable to find the ip of my azure server so i tried using some of the code from the 'connect_by_hostname' but no luck there.

I'm new to Arduino and cloud in general so any help is appreciated.

body:
Not sure how you would directly connect with an C++ embedded file. One way you could achieve this is by creating a computer application and connect to the machine via Bluetooth.

    {Arduino}
    * Intake information
    * Process into commands
    * Push through software serial ----(Blue Tooth-----> { PC or MAC}
                                                        *Create C# or Swift App
                                                        *Intake information via COM-PORT
                                                        *Prepare SQL command with serial data
                                                        *Push to database server

This may of not of been the method you were looking for, but it's a way I found around the issue when working with Azure Databases and Arduino Micro-Controllers. An alternative is going to Raspberry Pi which has a little more resources to deal with server functions.

Hope this helps.


message:
don't save on tab

Ok, I made some changes to the code and I wish they would see it.

At the moment the program has a bug, it is not saving the contents of the txt file to the table, can someone give some lights?

    #include <LiquidCrystal.h>
    #include <SPI.h>
    #include <SD.h>

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    // define some values used by the panel and buttons
    int lcd_key     = 0;
    int adc_key_in  = 0;
    int x = 1;
    String files, memo, memo1;
    int sizef = 0;
    int sizef1 = 0;
    int sizef2 = 0;
    int y=0;
    int z=1;
    int d=0;
    int u=0;
    int r=0;
    int l=0;
    int indice_objetos=0;

    struct objeto_celeste_s {
      char nome[20];
      float ar;
      float dec;
      };
    typedef struct objeto_celeste_s objeto_celeste;

    void rightfunction (int rate){
     char cmd[] = {'P',2,16,36,rate,0,0,0};

      for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
        Serial1.print(cmd[i]);

    }

    void leftfunction (int rate){
     char cmd[] = {'P',2,16,37,rate,0,0,0};

      for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
        Serial1.print(cmd[i]);

    }

    void upfunction (int rate){
     char cmd[] = {'P',2,17,36,rate,0,0,0};

      for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
        Serial1.print(cmd[i]);
    }

    void downfunction (int rate){
     char cmd[] = {'P',2,17,37,rate,0,0,0};

      for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
        Serial1.print(cmd[i]);
    }

    File file;

    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5

    char * list[]={"1.Modo Normal    ","2.Modo Teste    "};

    // read the buttons
    int read_LCD_buttons()
    {

    adc_key_in = analogRead(0);
    if (adc_key_in > 1000) return btnNONE;
    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 250)  return btnUP;
    if (adc_key_in < 400)  return btnDOWN;
    if (adc_key_in < 450)  return btnLEFT;
    if (adc_key_in < 650)  return btnSELECT;

    return btnNONE;  // when all others fail, return this...
    }

    void setup() {

     Serial.begin(9600);
     Serial1.begin(9600);
     while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
     }
     Serial.println ("Welcome!");
     Serial.println ("Efectue o alinhamento do telescópio, depois carregue no botão UP.");
     lcd.begin (16,2);
     lcd.setCursor (0,0);
     lcd.print ("Efectue alinham.");
     lcd.setCursor (0,1);
     lcd.print ("E carregue UP");
     delay (1000);

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }
    }

    void loop() {

    lcd_key = read_LCD_buttons();  // read the buttons

     switch (lcd_key)  // depending on which button was pushed, we perform an action
     {
       case btnRIGHT:
         if (z==0){
          rightfunction (9);
          Serial.println ("Andar para a direita a uma velocidade de 9.");
          z=1;
          r=1;
          break;
         }

         if (r==1){
          rightfunction (0);
          Serial.println ("Parar de andar para a direita.");
          z=0;
          r==0;
          break;
         }

       case btnLEFT:
         if (z==0){
          leftfunction (9);
          Serial.println ("Andar para a esquerda a uma velocidade de 9");
          z=1;
          l=1;
          break;
         }

         if (l==1){
          leftfunction (0);
          Serial.println ("Parar de andar para a esquerda.");
          z=0;
          l=0;
          break;
         }

       case btnUP:
          if (z==0){
           upfunction (9);
           Serial.println ("Andar para cima a uma velocidade de 9");
           z=1;
           u=1;
           break;
         }

          if (u==1){
           upfunction (0);
           Serial.println ("Parar de andar para cima.");
           z=0;
           u=0;
           break;
         }

          if(x==1){
            x--;
            lcd.clear ();
            lcd.setCursor(0,0);
            lcd.print(">");
            lcd.println(list[0]);
            lcd.setCursor(0,1);
            lcd.print (" ");
            lcd.println(list[1]);
            break;
          }
       case btnDOWN:
          if (z==0){
           downfunction (9);
           Serial.println ("Andar para baixo a uma velocidade de 9.");
           z=1;
           d=1;
           break;
          }

          if (d==1){
           downfunction (0);
           Serial.println ("Parar de andar para baixo.");
           z=0;
           d=0;
           break;
          }

          if(x==0){
            x++;
            lcd.clear ();
            lcd.setCursor(0,0);
            lcd.print(">");
            lcd.println(list[1]);
            lcd.setCursor(0,1);
            lcd.println("                ");
            break;
          }

       case btnSELECT:
        if (x==2){
          Serial.println ("Bem-vindo ao Modo Manual.");
          lcd.clear ();
          lcd.print ("Modo Manual");
          lcd.setCursor (0,1);
          lcd.print ("Reset p/mod GoTo");
          Serial.println ("Pressione os botões UP, DOWN, RIGHT ou LEFT no arduíno para controlar o telescópio.");
          z=0;
          break;
        }

        if (x==0){
        lcd.clear ();
        lcd.print ("Modo Normal");
        Serial.println ("Selecionou o modo normal!");
        delay (1000);
        if (SD.exists("objectos.txt")) {
        Serial.println("O ficheiro 'objetos' foi encontrado!");
        lcd.clear ();
        lcd.setCursor (0,0);
        lcd.print ("Modo Normal");
        delay (1000);

        file = SD.open("objectos.txt", FILE_READ);
        if (file) {
        while (file.available()) {
         String line = file.readStringUntil('\n');
         sizef++;
        }
        } else {//se houver erro a abrir o ficheiro
         Serial.println("Erro a abrir o ficheiro 'objectos.txt'.");
        }
         Serial.print ("Contados ");
         Serial.print (sizef);
         Serial.println (" objetos no ficheiro objectos.txt.");

         objeto_celeste *tab =(objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));

         if (tab==NULL){
          lcd.clear ();
          lcd.print ("Erro a alocar memoria");
          Serial.println ("Erro a alocar memória");
          while (1){ };

         }else{

          Serial.print ("Memória alocada para ");
          Serial.print (sizef);
          Serial.println (" objectos.");
          lcd.setCursor (0,1);
          lcd.print ("Alocados ");
          lcd.print (sizef);
          lcd.print (" obj");
          }

          file.close();

        char * line1 =(char*) malloc(sizeof(String));

        file = SD.open("objectos.txt", FILE_READ);

        if (file) {
         Serial.println ("Carregando informação para a memória:");

         while (file.available()) {

         char c = file.read ();

         if (c=='\n'){

         char * justafun = strtok (line1," "); //divide em tokens

         while (justafun !=NULL){

          switch (indice_objetos) {
              case 1:
                tab[sizef2].ar = atof(justafun); //to float

                indice_objetos++;
                break;
              case 2:
                tab[sizef2].dec = atof(justafun);

                sizef2++;
                indice_objetos=0;
                break;
              case 0:
                strcpy(tab[sizef2].nome, justafun); //this one is a string
                indice_objetos++;
                break;
          }
          justafun = strtok (NULL, " ");
          }

          if (line1==NULL){
          Serial.print ("Falhou na linha ");
          Serial.println (sizef2);

         }else{
           line1="";
        }
       }else{
         sprintf(line1, "%s%c", line1, char(c));
         }
        }
       }
      file.close ();

      delay (1500);

      if (Serial1.available()) {
       int inByte = 'V';
       Serial1.write (inByte);
       int inByte1 = 'e';
       Serial1.write (inByte1);
      }

    delay (1000);

    Serial.println ("Tabela ordenada alfabeticamente:");

     x=2;
     delay (1000);
     lcd.clear ();
     Serial.println ("Modo GoTo. Para entrar em Modo Manual pressione o botão select.");
     lcd.print ("Modo GoTo");
     lcd.setCursor (0,1);
     lcd.print ("Slct p/Modo Man.");

     }else {

        Serial.println ("O ficheiro 'objetos' não existe.");
        lcd.clear ();
        lcd.print ("Erro nao encontrado");
        delay (2000);
        while(1) { };
      }
     }

        if (x==1){
          lcd.clear ();
          lcd.print ("Modo Teste");
          Serial.println ("Selecionou o modo teste!");
          delay (2000);

          if (SD.exists("teste.txt")) {
          Serial.println("O ficheiro 'teste.txt' foi encontrado!");
          lcd.clear ();
          lcd.setCursor (0,0);
          lcd.print ("Modo Teste");
          lcd.setCursor (0,1);
          lcd.print ("Ficheiro encontrado");
          delay (2000);

          file = SD.open("teste.txt", FILE_READ);

          if (file) {
          while (file.available()) {//ler o ficheiro
          String line = file.readStringUntil('\n');
          sizef++;
         }

          files = "Contados " + String (sizef) + " objetos no ficheiro teste.txt.";
          Serial.println (files);
          objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
          memo = "Alocados " + String (sizef) + " obj  ";
          memo1= "Memória alocada para " + String (sizef) + " objetos.";

          if (tab==NULL){
            lcd.clear ();
            lcd.print ("Erro alocar memoria");
            Serial.println ("Erro a alocar memória");
            while (1){ };

          }else{

            Serial.println (memo1);
            lcd.setCursor (0,1);
            lcd.print (memo);
          }

          file.close();

         } else {//se houver erro a abrir o ficheiro
          Serial.println("Erro a abrir o ficheiro 'teste.txt'.");
         }

        }else {
          Serial.println ("O ficheiro 'teste.txt' não foi encontrado.");
          lcd.clear ();
          lcd.print ("Erro nao encontrado");
          delay (2000);
          while(1) { };
        }
       }
         break;

       case btnNONE:
          break;
     }
     delay (200);
    }

This is the content of txt.

P.S. I know the "Ar" section is wrong, it's just for test purposes.

    Syrius 6.45 -16.42
    Deneb 20.41 +45.16
    Capella 5.16 +45.59
    Rigel 5.14 -8.12
    Vega 18.36 +38.47
    Alnitak 05.40 -01.56

body:
Maybe I have found your problem:

Before reading the file you are allocating memory with `malloc()` and creating a pointer `line1` to it. `malloc()` takes the number of bytes to allocate as a parameter. Here you use `sizeof(String)`, which would give you the size of a new String object. But the point of the String object is, that is dynamically allocates the memory for the string of characters. So the created buffer `line1` is most likely to small for your text. You have to allocate the buffer with the maximum number of characters of all lines.

But you should consider, that using `malloc()` or any other dynamic memory allocation is dangerous on microcontrollers, which don't have much RAM. If you are doing it to often you get heap fragmentation, essentially making swiss cheese of your heap. If possible you should use a statically declared array or at least allocate memory only once during the lifecycle of your program.


message:
Arduino Uno board with male header pins

I am currently working on a project that would greatly benefit from an arduino uno board with male headers soldered on instead of the female connectors. My question is hence extremely simple, yet I was not able to find an answer myself. Are there uno formfactor boards out there, with male header pins. I have found versions without headers for other boards, but not for the uno. Since I have already designed and 3d printed an enclosure that fits the uno and want to lower the overall height this seems like the easiest way to achieve this.

body: I often unsolder the female connectors to solder wires directly. I would simply unsolder then and solder male headers in their place.


message:
How to deal with unusual neopixel grid

I have built a custom installation in my home with 896 WS2812 LED driven by an ArduinoMega 2560 and powered by several rails just fine. However, the installation is arranged in a checkerboard-like pattern. There are 14 panels with 8 strips of 8 LED each (64 LED per panel), The strips are soldered in zigzag pattern within a panel, and the tiles are connected via leads in a "column progressive" fashion.

Hooking this up and running it works well but I'm trying to deal with the unusual pattern I've created, and having a hard time scaling with my current solution. I am worried that my solution is not very graceful and will use up a lot of unnecessary RAM. I am currently using Adafruit's NeoMatrix library.

My solution is to "fake" like I have many more pixels and use the `setRemapFunction()` to throw these fake grid points away. But as I continue to add fake pixels, I assume the overhead RAM is set aside for them and I will max out before getting done. I have 896 real pixels total, but at this rate I'll be declaring that I have 1,792. This is my attempt to deal with the offset, and is a work in progress. This is utilizing about half of my total grid so far:

    const int16_t grid[] = {
    0,  15,  16,  31,  32,  47,  48,  63,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 256, 271, 272, 287, 288, 303, 304, 319,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    1,  14,  17,  30,  33,  46,  49,  62,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 257, 270, 273, 286, 289, 302, 305, 318,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    2,  13,  18,  29,  34,  45,  50,  61,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 258, 269, 274, 285, 290, 301, 306, 317,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    3,  12,  19,  28,  35,  44,  51,  60,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 259, 268, 275, 284, 291, 300, 307, 316,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    4,  11,  20,  27,  36,  43,  52,  59,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 260, 267, 276, 283, 292, 299, 308, 315,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    5,  10,  21,  26,  37,  42,  53,  58,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 261, 266, 277, 282, 293, 298, 309, 314,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    6,   9,  22,  25,  38,  41,  54,  57,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 262, 265, 278, 281, 294, 297, 310, 313,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    7,   8,  23,  24,  39,  40,  55,  56,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 263, 264, 279, 280, 295, 296, 311, 312,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,

    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 128, 143, 144, 159, 160, 175, 176, 191,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 384, 399, 400, 415, 416, 431, 432, 447,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 129, 142, 145, 158, 161, 174, 177, 190,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 385, 398, 401, 414, 417, 430, 433, 446,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 130, 141, 146, 157, 162, 173, 178, 189,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 386, 397, 402, 413, 418, 429, 434, 445,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 131, 140, 147, 156, 163, 172, 179, 188,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 387, 396, 403, 412, 419, 428, 435, 444,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 132, 139, 148, 155, 164, 171, 180, 187,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 388, 395, 404, 411, 420, 427, 436, 443,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 133, 138, 149, 154, 165, 170, 181, 186,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 389, 394, 405, 410, 421, 426, 437, 442,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 134, 137, 150, 153, 166, 169, 182, 185,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 390, 393, 406, 409, 422, 425, 438, 441,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 135, 136, 151, 152, 167, 168, 183, 184,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 391, 392, 407, 408, 423, 424, 439, 440,

    64,  79,  80,  95,  96, 111, 112, 127,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 320, 335, 336, 351, 352, 367, 368, 383,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    65,  78,  81,  94,  97, 110, 113, 126,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 321, 334, 337, 350, 353, 366, 369, 382,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    66,  77,  82,  93,  98, 109, 114, 125,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 322, 333, 338, 349, 354, 365, 370, 381,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    67,  76,  83,  92,  99, 108, 115, 124,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 323, 332, 339, 348, 355, 364, 371, 380,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    68,  75,  84,  91, 100, 107, 116, 123,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 324, 331, 340, 347, 356, 363, 372, 379,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    69,  74,  85,  90, 101, 106, 117, 122,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 325, 330, 341, 346, 357, 362, 373, 378,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    70,  73,  86,  89, 102, 105, 118, 121,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 326, 329, 342, 345, 358, 361, 374, 377,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
    71,  72,  87,  88, 103, 104, 119, 120,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 327, 328, 343, 344, 359, 360, 375, 376,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,

    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 192, 207, 208, 223, 224, 239, 240, 255,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 448, 463, 464, 479, 480, 495, 496, 511,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 193, 206, 209, 222, 225, 238, 241, 254,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 449, 462, 465, 478, 481, 494, 497, 510,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 194, 205, 210, 221, 226, 237, 242, 253,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 450, 461, 466, 477, 482, 493, 498, 509,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 195, 204, 211, 220, 227, 236, 243, 252,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 451, 460, 467, 476, 483, 492, 499, 508,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 196, 203, 212, 219, 228, 235, 244, 251,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 452, 459, 468, 475, 484, 491, 500, 507,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 197, 202, 213, 218, 229, 234, 245, 250,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 453, 458, 469, 474, 485, 490, 501, 506,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 198, 201, 214, 217, 230, 233, 246, 249,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 454, 457, 470, 473, 486, 489, 502, 505,
    -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 199, 200, 215, 216, 231, 232, 247, 248,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 455, 456, 471, 472, 487, 488, 503, 504,

    };

I am using this like so:

    #define PIN 6

    #define WIDTH 32 // So far. Will be 56 when I finish creating array.
    #define HEIGHT 32

    /**
     * Setup the lightwall matrix.
     *
     * Each panel is 8x8 pixels. There are 7 columns and 2 rows,
     * but they are arranged in a checkerboard pattern.
     */
    Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(WIDTH, HEIGHT,PIN,
      NEO_MATRIX_TOP     + NEO_MATRIX_LEFT +
      NEO_MATRIX_COLUMNS + NEO_MATRIX_ZIGZAG,
      NEO_GRBW           + NEO_KHZ800
    );

    uint16_t remapXY(uint16_t x, uint16_t y) {
      y = y * WIDTH + x;
      return grid[y];
    }

    void setup() {
      matrix.setRemapFunction(remapXY);
      matrix.begin();
    }

So the `remapXY()` returns the correct key of the array, thus the reason for the crazy array pasted above. And that array is only halfway complete (tediously typing it out!)

But so far it is working. I have a pacman animation (not pictured) scrolling across the screen and being "off screen" for a believable  amount of time. That is the whole point of this madness. But am I going about it all wrong? Attached is also a picture of the full visible matrix for visual aid.

[![lightwall][1]][1]

Starting from the upper left corner is panel 1, then lower left panel 2. Next column top is panel 3, bottom panel 4. And so on.

So will I need more RAM in order for this to be performant? Or is there a better way to code my way out of this problem? I have a lot of animations and ambient effects planned, not all of which will strictly require this offset.

Is there another way to "mask" or delay some pixels off screen temporarily based on where they should be? Only to put them back where they belong afterward?

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

body:
break it down into blocks to determine the upper left corner of any 8x8 grid

    const int16_t grid[8][8] = {
           {0,  15,  16,  31,  32,  47,  48,  63},
           {1,  14,  17,  30,  33,  46,  49,  62},
           {2,  13,  18,  29,  34,  45,  50,  61},
           {3,  12,  19,  28,  35,  44,  51,  60},
           {4,  11,  20,  27,  36,  43,  52,  59},
           {5,  10,  21,  26,  37,  42,  53,  58},
           {6,   9,  22,  25,  38,  41,  54,  57},
           {7,   8,  23,  24,  39,  40,  55,  56}
    };

    const int16_t block[7][4] = {
           { 0,  -1,   4,  -1,   8,  -1,  12},
           {-1,   2,  -1,   6,  -1,  10,  -1},
           { 1,  -1,   5,  -1,   9,  -1,  13},
           {-1,   3,  -1,   7,  -1,  11,  -1}
    };

    blockNumber = block[x/8][y/8];

    // some checking for the -1 value

    pixelNumber = blockNumber * 64 + grid[x%8][y%8]

    //


body:
This indeed looks awesome!

I suggest getting rid of the big `grid` array, and instead generate the
mapping programmatically. Given that it is very regular, the mapping can
be computed instead of stored:

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

    uint16_t remapXY(uint16_t x, uint16_t y) {

        // Compute panel position and offset of pixel within that panel.
        uint8_t pannel_x = x / 8;
        uint8_t offset_x = x % 8;
        uint8_t pannel_y = y / 8;
        uint8_t offset_y = y % 8;

        // Is this a missing panel?
        if ((pannel_x + pannel_y) & 1)
            return -1;

        // Compute panel number.
        uint8_t pannel = pannel_y / 2 + pannel_x * 2;

        // LED index within the panel.
        uint8_t led = 8 * offset_x;

        if (offset_x & 1)  // numbered bottom to top
            led += 7 - offset_y;
        else               // numbered top to bottom
            led += offset_y;

        return pannel * 64 + led;
    }

I hope this will save enough memory to make the whole thing work.


message:
Small Arduino with Bluetooth HID interface

I am trying to create a bluetooth gamepad for my phone.

I saw this:

https://www.amazon.com/DFRobot-Beetle-BLE-Arduino-Bluetooth/dp/B014KQHEH6/ref=cm_cr_arp_d_product_top?ie=UTF8

It says its bluetooth HID, but there are some conflicting comments saying it is serial over bluetooth. Is there something similar in a small form factor with an hid bluetooth module that I can use?

body:
Based on the fact that the controller you mentioned has a [TI CC2540 Bluetooth processor](http://www.ti.com/product/CC2540), I have found a few webpages with information about HID capabilities in the CC2540. Based this the CC2540 should support HID.

[Some example code.](https://github.com/rampadc/cc254x-hidKbdM)
[Question on the TI forums, with a link to example code.](http://e2e.ti.com/support/wireless_connectivity/bluetooth_low_energy/f/538/p/120371/430649)


message:
Does the ESP8266 somehow remember wifi access data?

Today I did some tinkering with an ESP8266, trying out OTA and writing a webserver. To find an error, I reduced the sketch to just the following lines:

    #include <ESP8266WebServer.h>

    ESP8266WebServer server(80);

    void setup() {
      Serial.begin(115200);
      server.on("/", []() {
        Serial.println("Sending response...");
        server.send(200, "text/plain", "Hi there!");
      });
      server.begin();
    }

    void loop() {
      server.handleClient();
    }

Notice that there is no code to connect to a Wifi network. However, the chip still connects to my local, WPA2-secured, network on every boot. I can ping the chip, my browser can get the "Hi there!" message via http, the Serial message gets printed.

How is this possible? Does the ESP8266 somehow retain the Wifi information, maybe because of some old OTA data that was not completely overwritten?

I'm using platformio. Here's my entire platformio.ini:

    [env:d1_mini]
    platform = espressif8266
    board = d1_mini
    framework = arduino

I posted the compile and upload log here: https://pastebin.com/BtGrFZiu

body:
Yes, normally the last WiFi credentials will be saved in flash and the ESP8266 loads this data on bootup and reconnect to the last known WiFi. See https://github.com/esp8266/Arduino/issues/2843#issuecomment-334250100:

>the SDK stores some info, including the wifi credentials, in a sector of the flash.
>
>That sector is kept between flashings to allow for a quick startup after update. On boot, before your sketch is executed, the SDK will retrieve the wifi credentials and attempt a quick connection.

This behaviour can be controlled by using the function `WiFi.setAutoConnect(autoConnect)` as documented in https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/station-class.rst#setautoconnect. This in turn calls the Espressif SDK function `wifi_station_set_auto_connect` ([API reference][1])

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

In short: This is normal behaviour. If you want to make sure that your ESP8266 does not connect to any WiFi unless you tell it do it explicitly, call `WiFi.setAutoConnect(autoConnect)` at the beginning.

Edit: From within the firmware code, you can use `system_restore`. The documentation says that it would reset WiFi related data. This should destroy previous settings. The function can be included from https://github.com/esp8266/Arduino/blob/master/tools/sdk/include/user_interface.h within Arduino-ESP8266. I have not tried this myself nor can I say that it actually erases security-critical information from flash though.

[![abc][3]][3]

Or, as you also have found out, hard-erasing the entire flash will purge the WiFi data with absolute certainty. This can be achieved by using `esptool.py` with the `erase_flash` option, e.g. `python esptool.py -p COM6 erase_flash`. Then you can flash the new firmware which will not use previous WiFi settings (but will probably open up the default access point again).

Then there's also [`ESP.eraseConfig`][4] which erases only the relevant flash sectors.

  [1]: https://www.espressif.com/sites/default/files/documentation/2c-esp8266_non_os_sdk_api_reference_en.pdf
  [2]: https://i.stack.imgur.com/pET2B.png
  [3]: https://i.stack.imgur.com/u59VU.png
  [4]: https://github.com/esp8266/Arduino/blob/master/cores/esp8266/Esp.cpp#L426


message:
When RFID tag is removed

After rewriting and getting a good grip on what I have got in my sketch so far, I need some assistance.

So in my sketch I can play an MP3 track with a certain tag, but when that tag is removed I can't  start the fading out process.

So for all that helped on previous ones, where I just mashed a lot of code together and hoped for the best, this one should start to have some good foundations to build on.

But I'm stuck on the part that's commented out.

//rfid

    #include <SPI.h>
    #include <MFRC522.h>
    #define RST_PIN         9  // reset pin 9
    #define SS_PIN          10 // sda pin 10
    MFRC522 rfid(SS_PIN, RST_PIN); // Create MFRC522 instance

    // = 0001.mp3    8C DE 63 A9   uid's for me to relate to mp3 tracks.
    // = 0002.mp3    0A 97 F3 16 /
    // = 0003.mp3    3A 5F DE 16

    //mp3 player
    #include<SoftwareSerial.h>
    int mp3Pin[2] = { 5, 4 }; //Rx/Rx

    // For the checksum to the mp3
    #define startByte 0x7E
    #define endByte 0xEF
    #define versionByte 0xFF
    #define dataLength 0x06
    #define infoReq 0x01

    SoftwareSerial mp3(mp3Pin[0], mp3Pin[1]); // Rx, Tx

    void setup() {
      Serial.begin(9600); // Initialize serial communications with the PC
      SPI.begin(); // Init SPI bus
      rfid.PCD_Init(); // Init MFRC522
      rfid.PCD_DumpVersionToSerial(); // Print version of RFID

      //Mp3
      mp3.begin(9600); // Init mp3
      delay(1000);
      sendMP3Command(0x3F, 0, 0); // Send request for initialization parameters
      sendMP3Command(0x06, 0, 20); // Vol set to 30
      sendMP3Command(0x07, 0, 0); // EQ = pop
    }

    void loop() {
      // Look for new cards
      if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()) {
        //In new card found and new serial
        /*printHex(rfid.uid.uidByte, rfid.uid.size); // Print the Hex uid &
          Serial.println(); // use to get new uids.*/
        {
          String content = "";
          byte letter;
          for (byte i = 0; i < rfid.uid.size; i++) {
            content.concat(String(rfid.uid.uidByte[i] < 0x10 ? " 0" : " "));
            content.concat(String(rfid.uid.uidByte[i], HEX));
          }
          content.toUpperCase();
          if (content.substring(1) == "0A 97 F3 16") {
            //change here the UID of the card/cards that you want to give access
            //Serial.println("hello World");
            Serial.println("0002.mp3");
            sendMP3Command(0x03, 0, 0002); // Play track 0002.mp3
            sendMP3Command(0x19, 0, 0); // Loop track playing
            delay(30);
          }
          /*else !rfid.PICC_IsNewCardPresent();{
            sendMP3Command(0x06, 0, 28); // Reduce vol by 2 and fade out
            delay(30);
            sendMP3Command(0x06, 0, 26);
            delay(30);
            sendMP3Command(0x06, 0, 24);
            delay(30);
            sendMP3Command(0x06, 0, 22);
            delay(30);
            sendMP3Command(0x06, 0, 20);
            delay(30);
            sendMP3Command(0x06, 0, 18);
            delay(30);
            sendMP3Command(0x06, 0, 16);
            delay(30);
            sendMP3Command(0x06, 0, 14);
            delay(30);
            sendMP3Command(0x06, 0, 12);
            delay(30);
            sendMP3Command(0x06, 0, 10);
            delay(30);
            sendMP3Command(0x06, 0, 8);
            delay(30);
            sendMP3Command(0x06, 0, 6);
            delay(30);
            sendMP3Command(0x06, 0, 4);
            delay(30);
            sendMP3Command(0x06, 0, 2);
            delay(30);
            sendMP3Command(0x06, 0, 0);
            //sendMP3Command(0x16, 0, 0); // Stop
            delay(500); // Change value if you want to read cards faster
            }*/
        }
        // Halt PICC
        rfid.PICC_HaltA();
        // Stop encryption on PCD
        rfid.PCD_StopCrypto1();
      }
    }

    void sendMP3Command(byte Command, byte Param1, byte Param2) {
      // Calculate the checksum
      unsigned int checkSum = -(versionByte + dataLength + Command + infoReq + Param1 + Param2);
      // Construct the command line
      byte commandBuffer[10] = { startByte, versionByte, dataLength, Command, infoReq, Param1, Param2, highByte(checkSum), lowByte(checkSum), endByte };
      for (int cnt = 0; cnt < 10; cnt++) {
        mp3.write(commandBuffer[cnt]);
      } // Delay needed between successive commands delay(30); }
      /*   // Print the Hex uid & use to get new uids.
        void printHex(byte * buffer, byte bufferSize) {
        for (byte i = 0; i < bufferSize; i++) {
          Serial.print(buffer[i] < 0x10 ? " 0" : " ");
          Serial.print(buffer[i], HEX);
        }
        }*/

body:
Basically, you have written this code:

    void loop()
    {
      // Look for new cards
      if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial())
      {
        {
          // ...
          if (content.substring(1) == "0A 97 F3 16")
          {
            // play
          } else
          {
            // stop
          }
        }
        // ...
      }
    }

Try something like this:

    bool playing = false;

    void loop()
    {
      // Look for new cards
      if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial())
      {
        // ...
        if (content.substring(1) == "0A 97 F3 16")
        {
          // play
          playing = true;
        }
        // ...
      }
      if (playing && !anyCardPresent())
      {
        // stop
        playing = false;
      }
    }

and for the implementation od anyCardPresent refer to this [discussion](https://github.com/miguelbalboa/rfid/issues/188) - if more consecutive calls of PICC_ReadCardSerial fail, you can consider this as card being removed


message:
Do prototypes need to follow the order of the functions?

I define prototypes prior to calling the functions.

Does the order of the prototypes have to match the order of the functions in the code?

I'd like to sort the prototypes alphabetically, while I wouldn't care in which order they appear in the code.

I am after common or best practice.

body:
There is no specific best practice in this regard.

The rest of this answer is primarily opinion based, and hence off topic for this site.

If you have classes it's common, but in no way required, universal or "bad" not to do, to group the public, private and protected methods together.

Really, group them in a way which makes sense for your program - related functions together. If you have so many methods / functions that they need a lot of organizing, split them into groups of related functionality - using classes or whatever.


body:
> Does the order of the prototypes have to match the order of the functions in the code?

No.

> I'd like to sort the prototypes alphabetically, while I wouldn't care in which order they appear in the code.

You can do that. It would make the prototype easier to find, I suppose, however most editors these days have search functions.

> I am after common or best practice.

Because the Arduino IDE automatically generates function prototypes the common practice is not to use them at all.

If you want to know best practice **in general** I suggest you ask on [Stack Overflow](https://stackoverflow.com/).

---

Years ago I programmed Burroughs Medium Systems in BPL (Burroughs Programming Language), a language similar to Algol (which Pascal looks a bit like).

In BPL you could not use a function or variable which had not been previously defined. Thus, the "main" function would always appear at the end of the source file. Major functions (called by the main function) would therefore precede it, and minor functions would appear earlier again. Thus you could tell the hierarchy of function calls, roughly, by the order in which the functions appeared.

In C (and C++) you don't need function prototypes if you have all your code in a single file, and if you follow that convention. Put the main code at the end and the things it calls before them. You only need function prototypes then in unusual cases where A might call B but B might call A.


message:
Use SD Card while Pin 11 is being used for PWM

On Arduino Uno Rev3, I just ran the [`speaker_pcm`][1] demo that used TIMER1 and TIMER2 to generate a PWM wave. However, this means that the Pins 3, 9, 10 and 11 can not be used anymore; according to the documentation:

<!-- language: lang-none -->

    Takes over Timer 1 (16-bit) for the 8000 Hz timer. This breaks PWM
    (analogWrite()) for Arduino pins 9 and 10. Takes Timer 2 (8-bit)
    for the pulse width modulation, breaking PWM for pins 11 & 3.

I wanted to change the program such that the WAV data was read from a SD card. However, this is what [documentation][2] for `SD.h` library says:

<!-- language: lang-none -->

    The communication between the microcontroller and the SD card uses SPI,
    which takes place on digital pins 11, 12, and 13 (on most Arduino boards)

This means both the `SD.h` and `speaker_pcm` want to use pin 11, and the requirement to use these pins is dictated by the hardware. I am guessing that this clash will create problems.

Is there any way I can make this work? Can I switch between SD card reading and Audio playing somehow (essentially multiplexing in software)? Or will this collision of pin usage not be a problem?

  [1]: https://playground.arduino.cc/Code/PCMAudio
  [2]: https://www.arduino.cc/en/Reference/SDCardNotes

body:
The program you link to does _not_ take over pins 3, 9, 10 and 11, it
takes over Timer 1 and Timer 2, which are used to provide PWM capability
on those pins. This means you cannot do `analogWrite()` on those pins
anymore, but you still can use them for other purposes, including SPI
access to an SD card.

Note, however, this line of code:

    int speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2

This of course will conflict the SPI port using pin 11 as MOSI. You can
fix this conflict simply by setting `speakerPin` to 3 instead of 11.


message:
Variables not saving

I'm trying to write web server code. However, I am having trouble with part of it.

Currently, to get it to save a bool variable I have it use a pin, as when I ran the code without it, after the page refreshes it resets the variable to its original value.

How do I get it to save the variable in this code without it using the pin?

    digitalWrite (equalPin, server.arg("equal").toInt());
    char equalText[80];
    if(equalState) {
      strcpy(equalText, "priority is equal. Deactivate");
      equalState = false;
    } else {
      strcpy(equalText, "priority is not equal. Activate");
      equalState = true;
    }
    equalState = digitalRead(equalPin);

I also have several over copies of this for different pages but if I change 1 of them they all change and reset after 10 seconds.

The code follows the example on [this site][1].

  [1]: https://42bots.com/tutorials/esp8266-example-wi-fi-access-point-web-server-static-ip-remote-control/

body:
same code snippet without using pin

    char equalText[80];

    if (equalState){
      strcpy(equalText, "priority is equal. Deactivate");
      equalState = false;
    }
    else {
      strcpy(equalText, "priority is not equal. Activate");
      equalState = true;
    }
    equalState = server.arg("equal").toInt();

but it does not make much sense to set the value if you already switched the state based on it's previous value


message:
Save Leading Zero HEX into String RFID RC522 Arduino

I'm using RC522 to read RFID card. All is until if the HEX leading by 0 then i can't save it into String. But if i print it to Serial all is well. Here is my code:

    #include <SPI.h>
    #include <MFRC522.h>
    #include <stdlib.h>

    #define RST_PIN         9
    #define SS_PIN          10

    String inStringHex = "";

    MFRC522 mfrc522(SS_PIN, RST_PIN);

    void setup() {
      Serial.begin(9600);
      SPI.begin();
      mfrc522.PCD_Init();
    }

    void loop() {
      // Look for new cards
      if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial())
      {
        //Serial.print("Card UID:");
        for (byte i = 0; i < 4; i++) {
          Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
          Serial.print(mfrc522.uid.uidByte[i], HEX);
          inStringHex += String(mfrc522.uid.uidByte[i], HEX);
        }

        Serial.println();
        Serial.println(F("Hex normal"));
        Serial.print(inStringHex);
        Serial.println();
        Serial.println();

        inStringHex = "";
        delay(5000);
      }
    }

Here is what displayed in serial monitor:
[![enter image description here][1]][1]

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

What i want is the String under "Hex normal" would be "04292e5a" not "4292e5a"

Please anyone help me.
Thank You.

body:
`String(mfrc522.uid.uidByte[i], HEX)` means you want to convert number into hexadecimal string repesentation, if you pass 4 as input parameter, it will convert it into "4", not "04". You need to apply similar approach as you have used when printing the value through UART. For example:

    if (String(mfrc522.uid.uidByte[i] < 0x10)
      inStringHex += " ";
    inStringHex += String(mfrc522.uid.uidByte[i], HEX);

Personally, I would recommend switching from Strings into static buffers (because arduino has too small memory to use dynamic allocation and there could be issue with running out of memory due to memory fragmentation):

    char id[16];
    sprintf(id, "xxxx", mfrc522.uid.uidByte[0], mfrc522.uid.uidByte[1], mfrc522.uid.uidByte[2], mfrc522.uid.uidByte[3]);


body:
you can try ;

    for (byte i=0; i < uidLength; i++)
    {
      Serial.print(uid[i] < 0x10 ? " 0" : "");
      Serial.print(uid[i], HEX);
      if (uid[i] < 0x10) inStringHex += "0";
          inStringHex += String(uid[i], HEX);
    } Serial.println(); Serial.println(inStringHex);


message:
3.3v Arduino I2C communication with motor controller powered at ~6v

I am trying to just use the voltage from 4 Alkaline AA batteries in series (6v nominal) to power a motor with the [TI drv8830 IC][1].

My question is, will this circuit (specifically just pulling the sda and scl pins to 3.3v) work reliably?   The datasheet says at maximum of 6.8v vcc the chip will still recognize 3.3v i2c lines (minimum 3.13V at that vcc voltage) but will the varying voltage of the battery cause the communication to be unstable?   There is a 10uf capacitor between vbat and gnd (not shown).

[![][2]][2]

  [1]: http://www.ti.com/lit/ds/symlink/drv8830.pdf
  [2]: https://i.stack.imgur.com/fcDmA.png

body:
> will the varying voltage of the battery cause the communication to be unstable?

No. As the battery voltage drops the input HIGH threshold (which is a function of VCC) also drops. If anything as the battery voltage drops the communication becomes *more* stable.

Since I2C is an *open drain* protocol the voltage makes no different for sending data - that voltage is set by the pull-up resistors to 3.3V.


message:
Arduino + Solenoid Lock

I was trying to use a [solenoid lock][1] alongside the arduino, using a 12V 2A DC adapter, TIP120, and a diode.

The circuit looks something like [this][2]. However, the lock isn't going in automatically (it requires a push).

I've tested the circuit using a multimeter, and the output given by the transistor, is indeed 12V, however, when connected to the lock, the potential difference is around 8V. I don't know if that's normal, but the lock isn't going in on it's own.

Can anyone help me with this issue?

  [1]: https://www.amazon.in/Segolike-Luggage-Electric-Solenoid-Assembly/dp/B06Y2JYYKJ?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=ddf05c16-60ff-4b8c-9c06-ade37716a043
  [2]: http://playground.arduino.cc/uploads/Learning/solenoid_driver.pdf

body: It sounds like your 12 volt adaptor is not powerful enough to operate the lock solenoid. If you power up the solenoid **only** and **directly** using the adaptor it should work. If it doesn't, you'll need a more powerful adaptor. If it does work, then the problem is somewhere in your driver circuit or Arduino sketch.


message:
Can I connect more than one IR receiver to an Arduino Uno?

I want to use `#include <IRremote.h>` to receive information from an infrared remote control. It works perfectly with one IR receiver.

But I want to put three or four IR receivers:

    IRrecv irrecv6(pin6);
    IRrecv irrecv7(pin7);
    IRrecv irrecv8(pin8);
    IRrecv irrecv9(pin9);
    IRrecv irrecv10(pin10);

And:

    void setup() {
      Serial.begin(9600);
      irrecv6.enableIRIn(); // Start the receiver
      irrecv7.enableIRIn(); // Start the receiver
      irrecv8.enableIRIn(); // Start the receiver
      irrecv9.enableIRIn(); // Start the receiver
      irrecv10.enableIRIn(); // Start the receiver
    }

Inside the loop function, I am checking each pin to see if there is any data received. But only the last pin (which means pin 10 above) is receiving the data and others are not.

body: That library only supports one IR receiver at a time. Try [this fork](https://github.com/Neco777/Arduino-IRremote) that seems to have added multiple receivers support.


body: Just add some delay between irrecv.decode()s and everything will work just fine.


message:
Understanding USBHID_DESC report

Recently Ran the USBHID_DESC program on my Arduino Uno with a USB hub attached to my joystick. I wanted to be able to program my joystick to integrate with my project. Circuits@Home developed the code and have 2 articles dealing with understanding the report. But they are very sparse with details and only have a single example to go off of. Many of the fields that I got returned are not described at all in the tutorial. Further more, attempting to dig through the official documentation from USB.org itself has been extremely overwhelming. I don't really know how to start. Can anyone help me interpret the data fields for this controller?

This is the data that I recieved from the serial monitor:

>Start
>0000: 05 01 09 04 A1 01 09 01 A1 00 09 30 09 31 09 32
>0010: 09 BB 15 80 25 7F 46 FF 00 66 00 00 66 00 00 75
>0020: 08 95 04 81 02 C0 09 39 15 01 25 08 35 00 46 3B
>0030: 01 65 14 75 04 95 01 81 02 05 09 19 01 29 04 15
>0040: 00 25 01 75 01 95 04 81 02 95 08 81 01 05 08 09
>0050: 43 15 00 26 FF 00 35 00 46 FF 00 75 08 95 04 91
>0060: 82 55 00 65 00 55 00 65 00 55 00 C0
>Usage Page Gen Desktop Ctrls(01)
>Usage Game Pad
>Collection Application
>Usage Pointer
>Collection Physical
>Usage X
>Usage Y
>Usage Z
>Usage Undef
>Logical Min(80)
>Logical Max(7F)
>Physical Max(FF00)
>Unit(0000)
>Unit(0000)
>Report Size(08)
>Report Count(04)
>Input(00000010)
>End Collection
>Usage Hat Switch
>Logical Min(01)
>Logical Max(08)
>Physical Min(00)
>Physical Max(3B01)
>Unit(14)
>Report Size(04)
>Report Count(01)
>Input(00000010)
>Usage Page Button(09)
>Usage Min(01)
>Usage Max(04)
>Logical Min(00)
>Logical Max(01)
>Report Size(01)
>Report Count(04)
>Input(00000010)
>Report Count(08)
>Input(00000001)
>Usage Page LEDs(08)
>Usage Slow Blk On Time
>Logical Min(00)
>Logical Max(FF00)
>Physical Min(00)
>Physical Max(FF00)
>Report Size(08)
>Report Count(04)
>Output(10000010)
>Unit Exp(00)
>Unit(00)
>Unit Exp(00)
>Unit(00)
>Unit Exp(00)
>End Collection Game Pad Pointer X Y Z Undef(00)(00)(7F)(00)
>Hat Switch(00)
>Btn0001
>(00) Btn0002
>(00) Btn0003
>(00) Btn0004
>(00)
>(00)(00)(00)(00)(00)(00)(00)(00)
>Slow Blk On Time

body:
It's pretty easy to follow if you indent and break it up right.  Let me add some annotation too:

    Usage Page Gen Desktop Ctrls(01)  // Usages describe what the
    Usage Game Pad                    // following data is used for.
    Collection Application
        Usage Pointer        // Use the settings for a physical
        Collection Physical  // pointing device
            Usage X       // It has four axes -
            Usage Y       // X, Y, Z and some other undefined axis.
            Usage Z
            Usage Undef
            Logical Min(80) // Output the values 0x80 to 0x7F, which when
            Logical Max(7F) // interpeted as signed bytes is -128 to 127.
            Physical Max(FF00) // The input has a range 0 to 255
            Unit(0000)
            Unit(0000)
            Report Size(08)  // The report value is 8 bits long,
            Report Count(04) // and there are 4 of them (one per axis)
            Input(00000010)  // This ends this "input" section.
        End Collection

        Usage Hat Switch // Describing a HAT Switch now.
        Logical Min(01)  // Interpret it as a value between 1 and 8
        Logical Max(08)
        Physical Min(00) // The input to it is between 0 and 0x3B01.
        Physical Max(3B01) // Not sure that value is interpreted properly.
        Unit(14)
        Report Size(04)  // The report has 4 bits in it,
        Report Count(01) // and there is just one of them.
        Input(00000010)  // And end the input section.

        Usage Page Button(09)  // Next come the buttons.
        Usage Min(01)      // These are basically button numbers
        Usage Max(04)      // - there's 4 buttons, 1 through 4.
        Logical Min(00)    // A button is either off (0)
        Logical Max(01)    // or on (1).
        Report Size(01)    // And can only have one state, so size 1.
        Report Count(04)   // There's 4 buttons, so 4 reports.
        Input(00000010)    // And end the input.

        Report Count(08)   // This is a special one. It keeps the settings
        Input(00000001)    // from before (the haven't been changed), but
                           // is just a dummy one to pad out the data to
                           // the right size. Alignment is key.

        Usage Page LEDs(08)    // Now we have 4 LEDs with an
        Usage Slow Blk On Time // 8-bit PWM value. 0-FF which doesn't
        Logical Min(00)        // need interpreting, so 0=0 and FF=FF.
        Logical Max(FF00)
        Physical Min(00)
        Physical Max(FF00)
        Report Size(08)    // As I said, 8 bit,
        Report Count(04)   // and there's 4 of them.
        Output(10000010)   // And it's output.

        Unit Exp(00)   // Now there seems to be a bit of junk.
        Unit(00)
        Unit Exp(00)
        Unit(00)
        Unit Exp(00)
    End Collection Game Pad // And the end.

So interpreting that, you get a report sent to you that has:

    Byte     Function
    0        X Axis 0-255 which you map to -128 to 127
    1        Y Axis 0-255 which you map to -128 to 127
    2        Z Axis 0-255 which you map to -128 to 127
    3        Another Axis 0-255 which you map to -128 to 127
    4        Upper 4 bits buttons, lower 4 bits HAT direction
    5        Padding byte to make ita multiple of 16 bits long

And you can send a 4 byte report where:

    Byte     Function
    0        LED 1 PWM
    1        LED 2 PWM
    2        LED 3 PWM
    4        LED 4 PWM

Those "LEDs" could be force feedback motors or vibrators.

Also I suspect there is maybe a small amount of corruption or mis-interpretation of multi-byte values in the output.


message:
How to use a DC buck converter to regulate Uno R3 input voltage?

I have had a rough time trying to understand why this isn't working correctly. Quick background: I set up a system to pop open car doors using touch sensors. I heard that powering the Arduino Uno R3 straight off the car battery is not a good idea, so I bought a buck converter. I wired it up and calibrated the output on the converter for 5V. When I hooked it up to the Arduino (via the barrel jack), I experienced some odd effects. The output pins and the 5v power pins were only getting 3.5V.  I had to adjust the buck converter up to about over 7V in order to get 5v on the Uno.

Then the sensors started acting oddly. Auto triggering and alternately not working. Anyone know what I am doing wrong?

Converter I bought:  https://www.amazon.com/gp/product/B0159W0UL2/ref=oh_aui_detailpage_o07_s00?ie=UTF8&psc=1

body:
The barrel jack needs 9-12 V, the internal voltage regulator of the Arduino will reduce this to 5 V.

Since you only supply 5 V, there is a loss in the internal voltage regulator why you probably get only 3.5 V.

And after applying 7 V, probably some (sub) system gets less than the necessary voltage, or there are occasional 'downspikes' lower than 5 V.

The default adapter that you use for supplying voltage to the Uno, also is 9V-12V. Also, check the polarity.

See the following link for more info:

[What adapter][1]

  [1]: http://playground.arduino.cc/Learning/WhatAdapter


body: If you are getting a clean 5v from the buck converter, you can/should run that directly to the 5v pin on the Arduino. Using the barrel jack(at 7-12V) still uses the on board linear(inefficient) Regulator to produce the 5v the board needs. You will want to ensure you are outputing a clean 5v during all phases of the car being on/off/startup.


message:
Making a distance sensor for human interaction

I want to make a sensor that senses a person between 1.5 m and 0.2 m, connected to an LED that is on 100% at 0.2 m and 1% at 1.5 m and gradually scales.

Is an ultrasonic sensor the best sensor to use here?

body:
Most arduino compatible ultrasonic sensors should work perfectly for your use case. You would just have to program the arduino then but I am going to assume that you know how to do that.

Here is a link to the one that I personally use: https://www.amazon.com/HC-SR04-Ultrasonic-Distance-MEGA2560-ElecRight/dp/B01MA4O5G5/ref=sr_1_3?ie=UTF8&qid=1524520770&sr=8-3&keywords=ultrasonic+sensor


message:
What's the newest way to use C++ stdlibs in Arduino 1.8.2?

(My Arduino version is 1.8.2.)

 For example,if I want to `#include` `<vector>` or `<string>`, `<iostream>`, `<memory>` etc, the compiler always complains that such libs are not found.

So what's the newest/most efficient way to use C++ libs in Arduino 1.8.2?

body:
Most Arduino Core don't include the Standard C++ Library, that's why headers like `<vector>` and `<string>` are missing.
This decision makes a lot of sense because the STL relies heavily on heap allocation, which would ruin the little RAM of the microcontroller.

If you're looking for an alternative to the STL, you might check out the [ETL, the Embedded Template Library.](https://www.etlcpp.com/). However, the code will not be the same because all the containers of the ETL have a fixed capacity. Here is a string for example:

    etl::string<32> s = "hello world";

In practice, I never saw a project using the ETL. Most projects use the standard Arduino classes (`String`, `Stream`, `Print`...) and [learn to live with their flaws](https://cpp4arduino.com/2018/11/21/eight-tips-to-use-the-string-class-efficiently.html). Since there are no generic container classes in the Arduino core, the common usage is to use plain old C arrays.


message:
Teensy 2.0 with MCP23017-E

I've recently bought two more MCP23017-E's for a project, but after hooking them up to my Teensy 2.0 I couldn't get them to react to anything. Suspecting faulty hardware, I hooked them up to an old LCP1114, and got them running just fine. I've tried porting the code I used, which still gave no result.

I'm using the following code:

    #include "Wire.h"
    const byte device=0b01000000; //default addrress of IO chip

    const byte IODIRA=0x00;
    const byte IODIRB=0x01;

    const byte GPIOA=0x12; //IO pins, port A
    const byte GPIOB=0x13; //IO pins, port B
    const byte OLATA=0x14;//O pins A
    const byte OLATB=0x15;//O pins B

    const byte GPPUA=0x0C; //pull up resistors ,port A
    const byte GPPUB=0x0D; //pull up resistors ,port B

    char iCounter = 0;

    void setup() {
      Wire.begin();
      seti2cbyte(device,IODIRA,0x00);
      seti2cbyte(device,IODIRB,0xFF);
      seti2cbyte(device,GPPUB,0xFF);  //enable pull-up resistors on port B
    }

    byte geti2cbyte(byte address, byte ptr) {
      Wire.beginTransmission(address);
      Wire.write(ptr);
      Wire.endTransmission();
      Wire.requestFrom(address, 1); // request one byte of data from MCP20317
      byte inputs=Wire.read();
      return inputs;
    }

    void seti2cbyte(byte address, byte ptr, byte value) {
      Wire.beginTransmission(address);
      Wire.write(ptr); // set MCP23017 memory pointer to GPPUA address
      Wire.write(value); // enable pull up resistors
      Wire.endTransmission();
    }

    void loop() {
      seti2cbyte(device,OLATA,iCounter);
      byte port_b = geti2cbyte(device,GPIOB); //get status of pins 21-28
      Serial.print(iCounter++);Serial.println(port_b);
      delay(500);
    }

I don't see a blinking LED, and port_b stays at 255 (or -1 I figured after reading the Wire.cpp)

I've tried different methods, even running SPI myself (setting pins high and low manually). The only difference I see is that the Teensy 2.0 is 5V, and the LCP1114 runs at 3.3V. The data sheet for the MCP23017-E states that it is also rated for 5V though.

Why does it seem like my MCP23017-E's won't work at 5V, while the data sheet states they should?

[MCP23017-E datasheet][1]

> • Operating Voltage:
> - 1.8V to 5.5V @ -40°C to +85°C
> - 2.7V to 5.5V @ -40°C to +85°C
> - 4.5V to 5.5V @ -40°C to +125°C

[![Overview][2]][2]
[![Close-up of Teensy. Yes, I did plug in the USB cable while testing.][3]][3]

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/20001952C.pdf
  [2]: https://i.stack.imgur.com/6daFC.jpg
  [3]: https://i.stack.imgur.com/6MNTK.jpg

body:
You have the wrong device address. You've included the R/W bit in the address, which you shouldn't.  An I2C address is only 7 bits, not 8.  Drop one bit:

    const byte device=0b0100000; //default addrress of IO chip


message:
Fio Keyboard program out of control, how to reset?

My question involves a Sparkfun Fio v3, similar to the Arduino Fio.

I had a student who was testing his understanding of the Keyboard library.  He uploaded a sketch that continuously sends output, emulating a keyboard, saying "Hello!If you're reading this, then you did things right!" (I don't have his code, unfortunately, so I can't post it.)

So, now, whenever I connect it via the USB, I can't upload a new sketch because the Serial channel is clogged with this output.  (Error Message: "avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00" and so on)

I've tried putting the cursor inside the header comment in 'Blink', so that the new characters that are being spammed to my code are all inside a comment, and this makes it possible to compile, but it won't sync and upload.  I've tried burning a new bootloader, and this fails as well (Message: "Error while burning bootloader.").

It seems to me that the only way to get this device back is to reset the memory without connecting to a computer, but I can't find any way to do this.

Is there any way to rescue this device?

body:
Hehe... This is a fun one to try and get out of. The normal way is to reflash the bootloader...

If it's the same as the Leonardo you get about 8 seconds after a reset while just the bootloader runs before it starts to spam everything with text. So you can try:

1. Open notepad or something similar
2. Plug in the board
3. Press *and hold* the RESET button (or connect the RESET pin to GND with wire)
4. Open the IDE and load Blink.ino

Now the tricky bit.  If the correct serial port isn't selected, you need to, within the space of 8 seconds:

1. Release the reset button.
2. Let the PC enumerate the device
3. Open the serial ports menu and select the right port
4. Press *and hold* the RESET button again.

Now you can program it, in a similar way:

1. Press UPLOAD in the IDE.
2. Just *before* it finishes compiling (turn on verbose output can help you time it better) release the RESET button.

If you timed it right the bootloader should run and accept the new program *before* the existing sketch runs and starts spamming everything.


body:
Majenko's suggestion should work - the bootloader should give you a few seconds in which to upload the new sketch, although timing it can be critical.

If that fails, you can reburn the bootloader which will erase the existing sketch. I have a [sketch which uploads various bootloaders](http://www.gammon.com.au/bootloader), the ATmega32U4 being one of them.

Judging by [the schematic](https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Fio_v31.pdf) and also a photo of the board, you would need to solder on a 6-pin header (circled).

[![Fio photo][1]][1]

Then run 6 wires as described on my page above to another Arduino (see "Wiring for Leonardo") and burn the bootloader. That only takes a couple of seconds. You could make up a suitable cable with a 6-pin socket to make it easier next time a student does the same thing. :)

This will definitely work (if you get the wiring right) because it uses ICSP programming, which means the sketch on the board doesn't have a chance to run. In fact the programming is not via the USB interface at all.

The bootloader uploading starts with a chip erase, which therefore removes any existing sketches.

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