message:
Accelstepper run stepper backward

**Update:**

Below I implemented how I understood your suggestions. And it still does only turn in one direction (forward). Curiously if I entered M_DEST in the stepperOneForward() function it turned forward very long but smooth. The code below made it rotate as usual very jittery. Is this the acceleration part and if so how can I change that ? Ideally I would be able to tell the stepper go to position X and return to start and that in constant speed.

     #include <AccelStepper.h>

    const int stepPin = 5;
    const int dirPin = 4;
    const int enPin = 12;

    unsigned int DEST = 800;
    unsigned int M_DEST = -800;
    unsigned int SPD = 1600;
    unsigned int ACCEL = 800;

    AccelStepper stepper1(1,stepPin,dirPin);

    void setup() {

      pinMode(stepPin,OUTPUT);
      pinMode(dirPin,OUTPUT);
      pinMode(enPin,OUTPUT);

      stepper1.setEnablePin(enPin);
      stepper1.setPinsInverted(false, false, true);
      Serial.begin(9600);  // Start Serial
    }

    void loop() {

    stepperOneForward();
    Serial.println("Stepper1 turned forward.");
    delay(1000);
    stepperOneBackward();
    Serial.println("Stepper1 turned backward.");
    }

    void stepperOneForward() {

      stepper1.enableOutputs();
      stepper1.setMaxSpeed(SPD);
      stepper1.setAcceleration(ACCEL);
      stepper1.move(DEST);
      if (DEST > 0) {
        while ( stepper1.distanceToGo() > 0) {
          stepper1.run();
          }
      //stepper1.disableOutputs();
      }
     }

     void stepperOneBackward() {

      stepper1.enableOutputs();
      stepper1.setMaxSpeed(SPD);
      stepper1.setAcceleration(ACCEL);
      stepper1.move(M_DEST);
      if (M_DEST < 0) {
        while ( stepper1.distanceToGo() > 0) {
          stepper1.run();
          }
      //stepper1.disableOutputs();
      }
     }

I have multiple steppers that I would like to run forward until they hit a microswitch and backwards to the initial position. But to simplify things I would like to control one stepper going forward and then backward. The code below always just turns clockwise.

I tried to set the dirPin to low, which did not work.
I tried to reverse the `setMaxSpeed` (by putting a minus in front of it).
I found the "enum AccelStepper::Direction" class in Accelstepper that did not explain how to to set `DIRECTION_CCW` or `DIRECTION_CW`.

What I would like to achieve is control these steppers so they move smoothly forward, wait and then backwards. This should be very easy, but has frustrated me now for too long. I would use any library at this point that can do this and control more than 1 stepper.

The SPD and ACCEL values are so high because I use microstepping (6400 is a full cycle).

    #include <AccelStepper.h>

    const int stepPin = 5;
    const int dirPin = 4;
    const int enPin = 12;

    unsigned int DEST = 6400;
    unsigned int SPD = 1600;
    unsigned int ACCEL = 800;

    void setup() {

      pinMode(stepPin,OUTPUT);
      pinMode(dirPin,OUTPUT);
      pinMode(enPin,OUTPUT);
      Serial.begin(9600);  // Start Serial
    }

    void loop() {

    stepperOneForward();
    Serial.println("Stepper1 turned forward.");
    stepperOneBackward();
    Serial.println("Stepper1 turned backward.");
    }

    void stepperOneForward() {

      AccelStepper stepper1(1,stepPin,dirPin);
      digitalWrite(enPin,LOW);
      stepper1.setMaxSpeed(SPD);
      stepper1.setAcceleration(ACCEL);
      stepper1.move(DEST);
      if (DEST > 0) {
        while ( stepper1.distanceToGo() > 0) {
          stepper1.run();
          }
      digitalWrite(enPin,HIGH);
      }
     }

     void stepperOneBackward() {

      AccelStepper stepper1(1,stepPin,dirPin);
      digitalWrite(enPin,LOW);
      stepper1.setMaxSpeed(-SPD);
      stepper1.setAcceleration(ACCEL);
      stepper1.move(DEST);
      if (DEST < 0) {
        while ( stepper1.distanceToGo() > 0) {
          stepper1.run();
          }
      digitalWrite(enPin,HIGH);
      }
     }

body:
First, you are creating/destroying the `AccelStepper stepper1()` object at every call. This is not right, as the library can no longer keep track of the stepper position and state.

The stepper object should be created in the global scope (that is, outside of `setup()` or `loop()`).

Second, you can call `stepper1.setEnablePin(enPin)` and `stepper1.setPinsInverted(false, false, true)` after you create the object to have the AccelStepper library control the enable pin and to set the enable pin to operate active-low. Then the driver is enabled or disabled with calls to `stepper1.enableOutputs()` and `stepper1.disableOutputs()`. In practice, you would not disable the driver except for power saving, as the stepper can no longer hold it's position when the outputs are not enabled. It will lose it's position.

Third, do not set the speed to a negative value. The direction of the stepper is determined by the library based on the current position and the desired end position. When the library is created, the position is zero. You can set the new position in several ways:

- `stepper1.move()`: Set the target position **relative to the current position**. This means to go *backwards* you pass this function a negative value. It will add this (negative) number to the internal target position, and then `run()` will work to get it there.

- `stepper1.moveTo()`: Set a new absolute position. If you initially set the position to 100 and move there, then set it to 50, the stepper will run in reverse to be able to reach position 50. If you start in position 0 and run to 50, it will run forward. If you start at 0 and set to -50, it will run in reverse to get there, and so on.


sender: user

message:
Why does a 4 digit 7 segment cathode display wired to an Arduino not need to be connected to ground?

As a circuit neophyte I thought for a circuit to conduct current it had to be grounded.  [![See wiring diagram][1]][1]

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

sender: assistant

body:
The Uno is grounded. Current flows *into* the A-G and DP pins (that is: D2, D3, D4, D5, D6, D6, D8, and D9 on the Uno) when one of those pins is `LOW` and one of the display's digit pins is also low.

There is one "Common" pin for each of the 4 digits, labeled D1, D2, D3, and D4 on the display. Those common pins are connected to the Anodes (positive pin) of all segments in the specified digit. When 5V is applied to the base of the transistor, the NPN transistor is off. When 0V is applied to the base of the NPN transistor, current flows from the 5V source, through the transistor, and into the Anode of the digit.

When a segment pin (A-G, DP) is `HIGH`, it is at 5V. The Anode is also at 5V, so no current flows. When a segment pin in `LOW`, it s at 0V, and current flows from the Anode to Ground through the segment pin into the Uno.

This kind of display is meant to be multiplexed by digit. To light the first digit, The D1 transistor is turned on, and the segments to light up are set to `LOW`. All other transistors are off. Then, the first digit transistor is turned off and the 2nd digit transistor is turned on, and the segment pins are re-adjusted so that the desired output on the 2nd digit is displayed. Each digit is only on for a fraction of a second, but they are rotated through all 4 so quickly, that it gives the appearance of all 4 digits being on at the same time, without requiring 8x4=32 IO pins. Multiplexing means you only need 8+4=12 IO pins.

Search "multiplexed common anode 7-segment display" for more info.


body:
Current limit resistors are needed, one for each segment (A-G, DP) to avoid burning out the LEDs or uC IO pins:

    (5V - Vce of transistor - Vf of the LED)/current = resistor value

So making some assumptions:

    Vce = 0.7V in saturation (full on)

    Vf = 2.5V (approx. for Red, check your datasheet)

    10mA (so not blinding bright to start)

Then

    (5V - 0.7V - 2.5V)/.01 = 180 ohm


message:
Do all pins of Arduino Uno output 5V?

I am currently working on a project which uses PIR motion sensor and 5V relay.
Since you might be familiar that both the motion sensor and the relay requires a 5V connection.

My problem is, I don't want messy connections (parallel and series) and want to use any other pin for power and ground.

Also, can you suggest which resistor I might require for the motion sensor and relay?

Thanks for any help.

body:
You might get away with powering a PIR sensor from a logic line. Check the specs. If it draws less ≤20mA you'd be fine. If you nee to drive more current than that you can use a CMOS TTL Driver or a properly selected N-channel MOSFET. Adafruit sells [**these**][1], for example.

A relay is another matter. If you this is one of those optically isolated relays and all you're driving is the optioisolator then you might get away with that too if you only need ≤20mA. If you're looking to actually power the relay coils with your Arduino, forget it. it's a bad idea to even have the relay driven from the 5V line on the Arduino. Relays take quite a bit of current, and their load is quite "dirty" and likely to cause problems.

As to "which resistor I might require for the motion sensor & relay", I'm not sure what you mean. You shouldn't need any resistors. If the relay draws more current than the Arduino can supply, a current limiting resistor might protect the Arduino from damage but the relay won't work correctly.

What resistors are you referring to?

  [1]: https://www.adafruit.com/product/355?gclid=EAIaIQobChMI-LDGxsy84AIVx4WzCh1_vQNFEAQYASABEgK4ofD_BwE


message:
Wemos D1 mini not being shown when connected to macbook

I have multiple Wemos d1 mini lying around, but can't seem to get them connected to my macbook, to they do not show up in my /dev/tty?

I tried updating the driver, both using home-brew and installing the driver manually -  as suggested here

https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

but nothing seem to work?
I tried different cables? no way to connect to it?

body: All of the cables I tried don't have a data line


message:
Multiple .ino files in the same sketch

Yeah yeah, I know people ask this type of thing a lot, but I couldn't find an answer _anywhere_.

I understand that you can have multiple `.ino` files in one sketch, but I don't just want functions and variables separated, _I want functionality_.

I am writing a Braille program for the NodeMCU -- It takes a message from a served website and moves servos to emulate the appropriate Braille. I want to have 2 files: one to serve the website and get input from it (`website.ino`), and the other one to manipulate the servos(`braille.ino`). The only problem is, I can't figure out where to declare/attach the servos.

I plan to have a list of servos in `braille.ino` that will be looped over with each servo being set to a different value. If I declare them  in `website.ino` (my "main" file, ie, with a `setup` and `loop`), I will have to pass them to my `braille` function every time. On the other hand, if I choose to declare them as globals in my `braille.ino`, where would I attach them? Can I have _another_ `setup` in `braille.ino`?

body:
What isn't obvious is that with Arduino, you can have normal C and C++ files in the same directory as the `.ino` file. These can have functions and variables inside them, and Arduino will link them into the main program too. You only need one `.ino` file - all the rest can be in modules with a `.c` or `.cpp` (for C++) extension.

That way, you can group "helper" functions in different files by category - for example, a `BrailleServo.c` file. These contain the functions and variables for just that category.

If you haven't programmed native C/C++:

* Put the functions and variables in the `BrailleServo.c` file, and then *repeat* the functions' header in the `BrailleServo.h` file.
* Inside the `BrailleServo.c` file, at the top, put the following line:

        #include "BrailleServo.h"
Note the quotes (`" "`), not angle brackets (`< >`)
* Inside the `.ino` file, put the same `#include` line. That tells the module that "there are other functions elsewhere, and these are their definitions".

The only problem? Getting the silly Arduino environment to let you add `.c` and `.h` files to that directory. You could just use Notepad, but there's a trick (if you're using Windows):

 1. Choose `File`|`Open…`
 2. Right-click the pane with the files in it, and choose `New >`|`Text Document`
 3. Give it a complete name, and make sure you replace the `.txt` part of the name too with `.c` or `.h`. You may get the "If you change the extension, the file may be unusable" warning - just click `OK`.
 4. Select the new (blank) file in the file pane, and a new tab will appear.

> Note that 3. above assumes that you've told Windows File Explorer to NOT hide the extensions of known file types. I always do that - if you haven't, you'll need to. With:
>
>  * **Windows 10**:
>    In any folder's `View` tab, tick the `File name extensions` checkbox;
>  * **Windows 7**:
>    In `Control Panel` | `Appearance and Personalization` | `Folder Options`' `View` tab, **un**tick `Hide extensions for known file types`

---

Here are three examples:

`BrailleServo.h`

    //
    // BrailleServo.h
    //

    // Call this function once in setup()
    void BrailleInit();

    // This function activates the six servos to form the passed-in pattern.
    void BrailleShow(byte pattern);

`BrailleServo.c`

    //
    // BrailleServo.c
    //

    #include "BrailleServo.h"

    // The number of servos
    const byte NumServos = 6;

    // These are the pins for the six servos
    const byte servo[NumServos] = { 3, 4, 6, 7, 9, 10 };

    // This initialises the six servos
    void BrailleInit() {
       for (byte i=0; i<NumServos; ++i) {
          pinMode(servo[i], OUTPUT);
          // Do what else you need to do with servo[i]
       } // for
    } // BrailleInit()

    // This is how to use the six servos to form the passed-in pattern
    void BrailleShow(byte pattern) {
       // … Complicated code here …
    } // BrailleShow(pattern)

`Main.ino`

    //
    // Main.ino
    //

    #include "BrailleServo.h"

    void setup() {
       BrailleInit();
       // Other stuff
    } // setup()

    void loop() {
       BrailleShow('A');
       delay(1000);
       BrailleShow('B');
       delay(1000);
    } // loop()

Incidentally, for ideas you may want to check out [my answer][1] to a more generic Braille question.

  [1]: https://arduino.stackexchange.com/a/29480/22924


body:
It is important to know that the tabs/ino files are concatenate into one by the builder. The order of the concatenation is the same as the order of tabs in IDE. First is the main ino file with the same name as the project. The rest of the files is concatenated in alphabetical order.

The concatenated ino file determines the visibility of variables. All ino files 'see' the variables in the main ino file, but variables in other ino files are visible only in ino file with names later in alphabetical order.

For functions the builder generates function prototypes to the beginning of the resulting cpp file, so as usual all functions are visible everywhere in all ino files.

One way to work with additional tabs is group is to write xySetup() and xyLoop() functions in the xy.ino file and then call this functions from the main setup() and loop(). [My main Arduino project][1] is created this way, so it is a big and complex example of this approach.

To illustrate, this is the resulting cpp file entering the cpp part of the build toolchain (scroll it to end):

    #include "Arduino.h"
    #define I2C_ADC121         0x50
    #include <Wire.h>
    extern const unsigned long EVENTS_SAVE_INTERVAL_SEC;
    extern const char eventLabels[];
    extern const char* eventLongLabels[];
    extern const char* eventLongLabels[];
    #define EVENTS_FILENAME "EVENTS.DAT"
    #include <Grove_LED_Bar.h>
    #include <StreamLib.h>
    #include <TimeLib.h>
    #include <MemoryFree.h>
    #include <UIPEthernet.h>
    #define ETHERNET
    #include <ArduinoOTA.h>
    #include <SD.h>
    #define FS SD
    #define Serial SerialUSB
    #include "consts.h"
    #define BLYNK_PRINT Serial
    #define BLYNK_NO_BUILTIN // Blynk doesn't handle pins
    #include <BlynkSimpleUIPEthernet.h>
    #include <RTCZero.h>
    #define STATS_FILENAME "STATS.DAT"

    void balboaSetup() ;
    void balboaReset() ;
    void balboaLoop() ;
    void battSettLoop() ;
    boolean battSettRead(FormattedPrint& out) ;
    const char* bit2s(int value, byte mask) ;
    int battSettControl(boolean chargeControlOn, boolean dischargeControlOn) ;
    int battSettSetLimit(byte reg, int limit) ;
    void beeperLoop() ;
    void alarmSound() ;
    void beep() ;
    void beeperTone(int freq, uint32_t time) ;
    void blynkSetup() ;
    void blynkLoop() ;
    void updateWidgets() ;
    void buttonSetup() ;
    void buttonLoop() ;
    void csvLogSetup() ;
    void csvLogLoop() ;
    void csvLogPrintJson(FormattedPrint& out) ;
    void elsensSetup() ;
    void elsensLoop() ;
    boolean elsensCheckPump() ;
    byte overheatedSecondsLeft() ;
    int readElSens() ;
    unsigned short elsensAnalogRead() ;
    void eventsSetup() ;
    void eventsLoop() ;
    void eventsWrite(int newEvent, int value1, int value2) ;
    boolean eventsSaved() ;
    void eventsSave() ;
    byte eventsRealCount() ;
    void eventsPrint(FormattedPrint& stream) ;
    void eventsPrint(FormattedPrint& s, int ix) ;
    void eventsPrintJson(FormattedPrint& stream) ;
    void eventsPrintJson(FormattedPrint& stream, int ix) ;
    void eventsBlynk() ;
    int eventsCompare(const void * elem1, const void * elem2) ;
    void ledBarSetup() ;
    void ledBarLoop() ;
    void manualRunLoop() ;
    byte manualRunMinutesLeft() ;
    void modbusSetup() ;
    boolean modbusLoop() ;
    void modbusClearData() ;
    boolean requestSymoRTC() ;
    boolean requestInverter() ;
    boolean requestMeter() ;
    boolean requestBattery() ;
    boolean modbusError(int err) ;
    int modbusRequest(byte uid, unsigned int addr, byte len, short *regs) ;
    int modbusWriteSingle(unsigned int address, int val) ;
    int modbusConnection() ;
    void pilotLoop() ;
    unsigned short power2pwm(int power) ;
    void setup() ;
    void loop() ;
    void shutdown() ;
    void handleSuspendAndOff() ;
    void clearData() ;
    boolean handleAlarm() ;
    boolean restHours() ;
    boolean turnMainRelayOn() ;
    boolean networkConnected() ;
    void statsSetup() ;
    void statsLoop() ;
    int statsEvalCurrentPower() ;
    void statsAddMilliwats() ;
    void statsSave() ;
    int statsConsumedPowerToday() ;
    void statsPrint(FormattedPrint& out) ;
    void statsPrint(FormattedPrint& out, const char *label, Stats &stats) ;
    void statsPrintJson(FormattedPrint& out) ;
    void statusLedSetup() ;
    void statusLedLopp() ;
    void statusLedShortBlink() ;
    void susCalibLoop() ;
    void telnetSetup() ;
    void telnetLoop(boolean log) ;
    void valvesBackSetup() ;
    void valvesBackReset() ;
    void valvesBackLoop() ;
    void valvesBackStart(int v) ;
    boolean valvesBackExecuted() ;
    unsigned short valvesBackTempSensRead() ;
    void watchdogSetup() ;
    void watchdogLoop() ;
    void WDT_Handler(void) ;
    void webServerSetup() ;
    void webServerLoop() ;
    void webServerRestRequest(char cmd, ChunkedPrint& chunked) ;
    void webServerServeFile(const char *fn, BufferedPrint& bp) ;
    void printValuesJson(FormattedPrint& client) ;
    void printAlarmJson(FormattedPrint& client) ;
    const char* getContentType(const char* ext);
    void wemoLoop() ;
    boolean wemoPowerUsage() ;
    int wemoRequest(const char* service, const char* action, const char* param, const char* value, char* response, size_t size) ;

    #include "Regulator.ino"

    #include "Balboa.ino"
    #include "BattSett.ino"
    #include "Beeper.ino"
    #include "Blynk.ino"
    #include "Button.ino"
    #include "CsvLog.ino"
    #include "ElSens.ino"
    #include "Events.ino"
    #include "LedBar.ino"
    #include "ManualRun.ino"
    #include "Modbus.ino"
    #include "PowerPilot.ino"
    #include "Stats.ino"
    #include "StatusLed.ino"
    #include "SusCalib.ino"
    #include "Telnet.ino"
    #include "ValvesBack.ino"
    #include "Watchdog.ino"
    #include "WebServer.ino"
    #include "WemoInsight.ino"

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


message:
Using Sleep AND LowPower.h

I am trying to set up the low power module for an instance case,
I have installed the low power library but when I am using the
line

    LowPower.powerDown (SlEEP_5S, ADC_OFF, BOD_OFF) ;

It is throwing an error stating that the 'SLEEP' was not declared in the scope.
Any suggestion for that ? Do I have to include a library for sleep too ?

    #include "LowPower.h"
      /// DON' t worry about the setup and loop, i have defined all those.

This set of code is in

      void Loop()
        ...
        else
        {
           LowPower.powerDown (SLEEP_10S, ADC_OFF, BOD_OFF) ;

body:
There is no 5 or 10 second sleep. You can't just arbitrarily choose how long to sleep for. The watchdog timer only has specific periods (defined by dividing the clock by a set amount) that it can sleep for:

    enum period_t
    {
     SLEEP_15MS,
     SLEEP_30MS,
     SLEEP_60MS,
     SLEEP_120MS,
     SLEEP_250MS,
     SLEEP_500MS,
     SLEEP_1S,
     SLEEP_2S,
     SLEEP_4S,
     SLEEP_8S,
     SLEEP_FOREVER
    };

To sleep for 5 seconds you would need to sleep first for 4 seconds, then wake up, and then sleep for a further 1 second after that. For 10 seconds sleep for 8 seconds followed by 2 seconds.

Note that they aren't exact values, however, since the watchdog oscillator is very crude and varies wildly in frequency with both temperature and power supply voltage.


message:
Transmit/Receive data Nodemcu(V3) + Bluetooth Module HC-05

I am trying to communicate with the HC-05 Bluetooth module for quite long time now, but with no success.

I am using the Nodemcu(V3) ESP8266 module.

I connect the HC-05 to Nodemcu in following sequence:

    HC-05             Nodemcu
    -----             -----------
    RX       -->      Pin 1 (Tx)
    TX       -->      Pin 3 (RX)
    Vcc      -->      +3.3V
    GND      -->      GND

For starters, i want to check if my Nodemcu is communicating properly with my HC-05 module.

I have written the following code to read the response of AT commands:

    #include <SoftwareSerial.h>
    SoftwareSerial BTserial(3, 1); // RX | TX
    char Bluetooth_Name = ' ';

    void setup()
    {
        // Arduino IDE serial monitor
        Serial.begin(115200);

        // HC-05 default serial speed for AT mode is 38400
        BTserial.begin(38400);

        // Wait for hardware to initialize
        delay(1000);

        // Print debug string
    }

    void loop()
    {

       // Keep reading from HC-05 and send to Arduino Serial Monitor
       if (BTserial.available())
       {
          reading = BTserial.read();
          Serial.println(reading);
       }

       // Keep reading from Arduino Serial Monitor and send to HC-05
       if (Serial.available())
       {
          reading = Serial.read();
          BTserial.write(reading);
       }
    }
However, i do not get response for any AT command at all. The serial monitor just shows blank.

***Thanks in advance***

EDIT:- I connected the "EN" pin on the HC-05 to Vcc. Now, the led on the HC-05 blinks slowly, which means that the HC-05 is configured in command mode. However, i am still not able to receive the response for any AT commands. I have also selected "Both NL & CR" in the serial monitor, configured the baud rate correctly and double-checked the hardware connections.

Everything seems to be correct except that i don't get response for the AT commands.

Please help!!!

body:
I changed the line

    SoftwareSerial BTserial(3, 1); // RX, TX

to

    SoftwareSerial BTserial(D4, D3); // RX, TX

And got it to work!


body:
I had the exact same problem and got it to work doing these changes:

I had to add this under my library include statements

```
#ifndef D5
#if defined(ESP8266)
#define D5 (14)
#define D6 (12)
#define D7 (13)
#define D8 (15)
#define TX (1)
#endif
#endif
```

and changed

`SoftwareSerial BTserial(3, 1); // RX, TX`

to

`SoftwareSerial BTserial(D5,D6);`

I used D5 and D6 on my esp8266 instead of D1 and D3 but shouldn't matter


message:
Arduino for loop

I am a beginner in Arduino programming. This is my program for 5 LEDs and 1 Button. The LEDs are supposed to light before I press the button. But the LEDs start immediately, even without pressing the button. How is it possible?

    int sw7=7;
    int timer=500;
    int start=0;
    int stopp=100;
    void setup()
    {
      for (int opin=1;opin<6;opin++)
      {
        pinMode(opin,OUTPUT);
        pinMode(sw7,INPUT);
      }
    }

    void loop()
    {
      if (digitalRead (sw7)==LOW)
      {
        while (start<=stopp);
      }
      {
        for (int opin=1;opin<=5;opin++)
        {
          digitalWrite(opin,HIGH);
          delay(timer);
          digitalWrite(opin,LOW);
         }
      }
    }

body:
This is a sketch according to your requirements:

``` C
// pin mapping
int pin_map[] = {
  1,  // 0: led in pin 1
  2,  // 1: led in pin 2
  3,  // 2: led in pin 3
  4,  // 3: led in pin 4
  5,  // 4: led in pin 5
  7   // 5: button (pull-up)
};

int timeout_ms = 500;
int blink_ms = 100;

void setup()
{
  // setup pins
  for (int opin = 0; opin < 5; opin++) pinMode(pin_map[opin], OUTPUT);
  pinMode(pin_map[5], INPUT_PULLUP);

  // wait for activation
  while (millis() < timeout_ms)
  {
    // activate by button (off:pull-up on:GND)
    if (digitalRead (pin_map[5]) == LOW) break;
  }
}

void loop()
{
  for (int opin = 0; opin < 5; opin++)
  {
    // toggle LED
    int pin = pin_map[opin];
    pinMode(pin, !digitalRead(pin));
  }

  delay(blink_ms);
}
```

You will need avoid delay() usage if you need asynchronous tasks. Probably, you should study C language and practice with some hundred of sketchs to improve your code skills.


body:
Several things:

You need to explicitly set your output pins to `LOW` in your setup method.

The code to set the sw7 to input should not be inside the loop.

You should probably connect your switch between sw7 and ground and use `INPUT_PULLUP` mode (in `INPUT_PULLUP` mode the line is connected to +5V through a "pull-up resistor" so that it reads HIGH until you press the button, and then it reads LOW. If you don't use either an input pull-up or pull-down resistor then the input tends to "float" and give bad readings.)

You say "The LEDs are supposed to light before I press the button. But the LEDs start immediately, even without pressing the button."

I'm not sure what you mean. What do you want to happen, exactly? Do you want the LEDs to be lit steadily, and then turn off or flash when you press the button?

The code below will turn off all the LEDs initially, then toggle between off and flashing on each (debounced) button press. Switch the value of `idleLEDState` to HIGH if you want the LEDs to be lit when they are not flashing.

    #define flashDelay 50 //Delay between on and off state for LEDs
    #define switchBounceDelay 100

    uint8_t idleLEDState = LOW; //Change to HIGH
                                //if you want the LEDs to be lit when not flashing
    bool flashLEDs = false;
    bool ledsOn = false;
    unsigned long nextFlashTime = 0;
    unsigned long nextSwitchCheckTime = 0;

    void setup() {
      pinMode(sw7, INPUT_PULLUP); //Connect the switch between sw7 and ground
      for (int opin=1;opin<6;opin++)
      {
        pinMode(opin,OUTPUT);
        digitalWrite(opin, idleLEDState);
      }
    }

    void loop() {

      //If it's time to check the switch, and it's being pulled LOW, toggle flashLEDs
      if (mills() > nextSwitchCheckTime && digitalRead(sw7) == LOW) {
        flashLEDs = !flashLEDs;
        nextSwitchCheckTime = millis() + switchBounceDelay;
      }

      if (!flashLEDs) {
        //IF we're not supposed to flash the LEDs, set them to their idle state
        for (int opin=1;opin<6;opin++) {
            digitalWrite(opin, idleLEDState);
         }
      } else if millis() > nextFlashTime {
        nextTime = millis() + flashDelay;
        ledsOn = !ledsOn;
        for (int opin=1;opin<6;opin++) {
            uint8_t newState = ledsOn ? HIGH : LOW;
            digitalWrite(opin, newState);
         }
    }

I banged out the code above in the Stack Exchange editor. It likely contains a few typos. Please exert some effort to fix it and adapt it to your needs before posting back "Your code didn't work. I got error XYZ."


message:
Replace digitalWrite with a selective bitwise operation

I have the following code with digitalWrite I aim to write with bitwise operation only.
No portability concerns here whatsoever. (for atmega328p here)

    #define DATAOUT 11//MOSI
    byte commandbits = B11000000;
    for (int i = 7; i >= 3; i--) {
        digitalWrite(DATAOUT, commandbits & (1 << i));
    }

I came up with something like this below which works.

    #define DATAOUT 11//MOSI
    byte commandbits = B11000000;
    for (int i = 7; i >= 3; i--) {
        PORTB = (PORTB &(~(1<<3))) | (((commandbits &(1 << i))>>i) << 3);
    }

Is this the most concise way. Is there a way to simplify it?

body:
Personally I'd expand it out a little:

    if (commandbits & (1 << i)) {
        PORTB |= (1<<3);
    } else {
        PORTB &= ~(1<<3);
    }

It's far more readable, and there are less shifts to mess around with. Plus the AVR has bit set and bit clear operations which that will make use of, especially since it's now using literal values. You could actually replace those values with literals:

    if (commandbits & (1 << i)) {
        PORTB |= 0x08;
    } else {
        PORTB &= 0xF7;
    }


body:
If you like both portability, readability and performance there are a few libraries (for instance [Arduino-GPIO][1]):

    #include "GPIO.h"

    GPIO<BOARD::D11> data;

    // Setup
    data.output();

    // Manual loop unrolling for speed. Could ask the compiler to do this
    // Member function write()
    data.write(commandbits & 0x80);
    data.write(commandbits & 0x40);
    data.write(commandbits & 0x20);
    data.write(commandbits & 0x10);
    data.write(commandbits & 0x08);

    // Or using the assignment operator
    data = commandbits & 0x80;
    data = commandbits & 0x40;
    data = commandbits & 0x20;
    data = commandbits & 0x10;
    data = commandbits & 0x08;

And it is as fast as manually written direct port access.

  [1]: https://github.com/mikaelpatel/Arduino-GPIO


message:
Arduino Uno: external power supply +5V and serial communication with pc over USB

I have connected to my Arduino Uno outputs relay module. Relay module has 16 relays (5VDC) which are controlled by transoptors pins (HIGH from Arduino = specific relay is off).

Link to relay module (lang: polish): https://botland.com.pl/pl/przekazniki/6940-modul-przekaznikow-16-kanalow-z-optoizolacja-styki-7a240vac-cewka-5v.html?search_query=modul+przekazniko&results=75 (SRD-05VDC-SL-C relays).

Arduino is supplied by +5V pin and GND pins with external power supply MDR-5-10. Relay module is supplied with the same power supply.

I control Arduino from PC using serial communication over USB (I send a command eg. 1;1;1;1;1;1;, then 6 outputs goes to HIGH). And now there is a problem. When I disconnect relay module control pins from Arduino outputs everything works fine. But when it is connected, I get serial com. error "device not found" (after some switches: sometimes it works for about 20 output switches, sometimes for 1 output switch) and I have to open serial communication again. Probably error appears only when I'm switching outputs.

I think the problem is because my external power supply +5V drops for a while when switching and then Arduino switches to +5V from USB (which doesn't drop), which has not enough power and then error occurs.

Am I right? Any suggestions to fix the problem?

**EDIT #1:**
Thank you for help. Answers:

@**Jot**, after disconnecting +5V Arduino pin, but with connected relay module, I get serial error immediately with first relay switch. If i dosconnect both +5V pin and relay module control pin, my application works fine.
My wires: external power supply - Arduino: 0,5 mm2; Arduino - relay module control pins: 23 AWG (~0,25 mm2); external power supply - relay module +5V and GND: 1,5 mm2. It flows through relays: 24VDC <30W or 230VAC ~20mA.

@**CrossRoads**, no I use A0-A4 and Q3-Q12 (for relay module: Q3-Q7, Q9-Q11, Q13).

@**Duncan C**: Currently, I use only 9 relays, other control pins are disconnected and off. Here - http://botland.com.pl/index.php?controller=attachment&id_attachment=244 (power consumption per relay - 0,36W 5VDC) - you can see relay datasheet. Relays are isolated from Arduino with opto-isolators (signal HIGH from Arduino = relay is off).
I never switch them all at once. In specific function I never use more then 5 relays together.

@**Majenko**, thank you, I'll give it a try in Tuesday!

Further informations:

1. *Probably* problems occur more often when I connect wires to relays pins (I use them all as NO: 7x 30W 24VDC - coils, 2x 230VAC ~20mA - contactor).
2. Serial communication error can occur during both reading or writing to serial.

body:
I have a similar rig using a 4-channel optically isolated relay, but I use different power supplies for the Arduino and for the relay. (It works perfectly.) My guess is that the relays are causing the voltage on your arduino to droop when they switch on. I suggest using separate power supplies.

As @Majenko suggests, you might try adding a filtering cap (capacitor) between +5V and ground very near the Arduino. The cap should slow the drop in voltage to the Arduino long enough for the power supply to recover, but separate power supplies is the surest fix.


message:
ESP8266 Flash - Maximize SPIFFS size

the board i use has **1MB Flash Size**. My program however downloads 512K+ of data for processing.

Arduino Options i see are:

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

Ideally i would like to use 1MB of SPIFFS, is this even possible?

I don't use OTA, and compile with:

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

  [1]: https://i.stack.imgur.com/2XQog.png
  [2]: https://i.stack.imgur.com/WTkse.png

To minimise the footprint of the main sketch.

Thanks in advance.

body:
No.

Even if you don't use OTA, your program is stored in flash. If you have 1MB of flash, there's no way you can use all 1MB for SPIFFS; that would leave no space for your program.

Here's [a page showing how flash is divided up in an Arduino environment][1].

Even if you eliminate space for OTA images and the EEPROM, the Arduino environment will still reserve space for the sketch itself and for its wifi config and possibly a little more data.

You can never use 100% of the flash storage for SPIFFS.

  [1]: https://esp8266.github.io/Arduino/versions/2.0.0/doc/filesystem.html


message:
How ro re-enable 32u4 USB controller after sleep mode?

I've run into quite the problem with my 32u4, I can't get it to reconnect to the computer upon wakeup from a sleep mode!

So I have an Arduino Pro Micro featuring the 32u4, and I'm also designing a project with a standalone 32u4 (I'm using the Pro Micro as a test platform before I begin building my project). It is a battery operated device with a soft-start, so I need power consumption to be a miniscule as possible (hence the sleep modes).

After learning about the registers and brushing up on some binary, putting the chip to sleep was fairly straight forward, however, I cannot get the USB interface internal to the 32u4 to 'wake back up' or reconnect to the computer. I've attached my code below. I also tested this code on my Arduino Nano and it works just fine, however with added USB features of the 32u4, I cannot get it to reconnect to the computer, and I have to reset the chip a million times to get the IDE to finally recognise it and upload something else to it.

Here is my lovely code below. All it does it upon startup, go sleep, and when interrupt on pin 2 goes low, wake the chip back up and run the blink sketch. It goes to sleep, and wakes up and runs the sketch, it just won't ever reconnect to my computer, until I do a hardware reset.

    int btn1Pin = 2;
    int led1 = 9;

    // these are the 'standard' register configurations
    byte _SMCR = 0; // disable sleep mode
    byte _ADCSRA = 0b10000111; // re-enable ADC

    int interval = 500;
    int ledState = true;
    unsigned long ct1 = 0;
    unsigned long pt1 = 0;

    void setup()
    {
      pinMode(led1, OUTPUT);
      attachInterrupt(digitalPinToInterrupt(btn1Pin), wakeUp, FALLING);
      sleep();
    }

    void loop()
    {
      ct1 = millis(); // blink something so I know you're working
      if (ct1 - pt1 >= interval)
       {
         digitalWrite(led1, ledState);
         ledState = !ledState;
         pt1 = ct1;
       }
    }

    void wakeUp()
    {
      SMCR = _SMCR; // disable sleep mode
      ADCSRA = _ADCSRA; // re-enable ADC
    }

    void sleep()
    {
      ADCSRA &= ~(1 << 7); // disable ADC
      SMCR |= ( 1<<2 );    // power down mode
      SMCR |= 1;           // enable sleep
      __asm__ __volatile__("sleep"); // hypnotist snaps fingers, chip is out cold!
    }

----------

**Inside AJ's brain (more research):**
[32u4 Datasheet for quick reference][1]

I added a quick led turn on in the wakeUp() ISR to ensure it was actually getting executed, and indeed it was.

The description of the USBCON register (Page 267 - 21.13.1) claims that clearing bit 7 disables and resets the USB controller. I tried another iteration of code where in sleep() I cleared bit 7, hoping that reset the controller, and in wakeUp() I set the bit to turn it back on after reset, but that didn't work. In fact, it gave me a really tough time when trying to reprogram (even though I KNOW that the wakeUp() ISR is executing and the bit had to have been reset).

After some more reading, I saw (Page 262 - 21.7.2) says that in power down mode (the sleep mode I'm using),  *"the oscillator is stopped and halts all the clocks (CPU and peripherals). The USB controller 'wakes
up' when:*

 - *the WAKEUPI interrupt is triggered*
 - *the VBUSTI interrupt is triggered."*

Okay so this makes sense, in power down mode the USB controller is stopped due to the lack of an oscillator, cool! I understand that to mean I need to trigger one of those interrupts to re-enable the USB controller. So I searched around for the first interrupt "WAKEUPI", and it appears this bit is set by hardware (Page 282), I'm guessing this means when you plug in the USB cable? I wrote a sketch to read that register, and it returned with 00010000, so I'm assumed the above statement is true. It also says setting it with software has no effect, so I left this one to explore the next interrupt, VBUSTI, which seems to be part of the automatic USB plug in detection based off of the VBUS pad. Maybe something here needs to be changed but I can't tell.

Page 266 - 21.12 talks about software USB operating modes, and the last one is "Resuming the USB interface." The 4 bullets provide to wake up are as such:

 - Enable PLL
 - Wait PLL lock
 - Unfreeze USB clock
 - Clear Resume information

I tried to do all of the above by adding this code to the wakeUp() ISR. It still didn't work :(. I know it's brutal and ISRs should be as short as possible but I gave it a go anyways.

      PLLCSR = _PLLCSR; // enable PLL clock
      var = bitRead(PLLCSR, 0);
      while (var != 1) {} // wait for clock to lock

      USBCON = _USBCON; // unfreeze USB clock
      UDINT = 0; // clear resume flag
Maybe I'm making all of this more complicated than it needs to be, I don't know! I can't get this thing to reconnect.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf

body:
You're making it too hard on yourself.

There is a method to re-start the USB, but it only works if the USB has been properly stopped - and the method that is supposed to do that is empty.

This is a little sketch that works on my Leonardo:

    #include <LowPower.h>

    void setup() {
    }

    void loop() {
     USBCON = 0;
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

     USBDevice.attach();

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

     delay(10000);
     digitalWrite(13, LOW);
    }

It disables the USB (`USBCON = 0;`), sleeps for 8 seconds, then starts the USB up again from scratch (`USBDevice.attach();`).  10 seconds later it sleeps again.

At the computer end, you get (on Linux):

    [1242489.000014] usb 2-1.5.2: Product: USB IO Board
    [1242489.000015] usb 2-1.5.2: Manufacturer: Arduino LLC
    [1242489.000316] cdc_acm 2-1.5.2:1.0: ttyACM0: USB ACM device
    [1242498.631563] usb 2-1.5.2: USB disconnect, device number 69
    [1242507.068078] usb 2-1.5.2: new full-speed USB device number 70 using ehci-pci
    [1242507.199628] usb 2-1.5.2: New USB device found, idVendor=2341, idProduct=0036
    [1242507.199630] usb 2-1.5.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [1242507.199631] usb 2-1.5.2: Product: USB IO Board
    [1242507.199633] usb 2-1.5.2: Manufacturer: Arduino LLC
    [1242507.200256] cdc_acm 2-1.5.2:1.0: ttyACM0: USB ACM device
    [1242517.063425] usb 2-1.5.2: USB disconnect, device number 70
    [1242525.495729] usb 2-1.5.2: new full-speed USB device number 71 using ehci-pci
    [1242525.627634] usb 2-1.5.2: New USB device found, idVendor=2341, idProduct=0036
    .... etc ....


message:
Can I read using an analog pin on an arduino Mega whether or not there is a high (5v) voltage on a wire from another board's digital pin?

I am making a peer-to-peer network of initiating devices and a common hub, which controls most of the hardware. It sends a number over `Serial` to Mega's `Serial1` (Mega's `Serial` is used for communicating to the computer), but as a fallback it initiates a general alarm by sending a 5v signal (using `digitalWrite(pin, HIGH)`) to the main board. In order to complete the circuit and get the read, how would I do this?

Thanks!

body:
Yes of course you can. Better to use `digitalRead()` than `analogRead()` however.

You just need to tie the grounds of the 2 Arduinos together, and set up the pin on the Arduino you want to sense the input as INPUT or INPUT_PULLUP. Then do a digitalRead on the pin. It will return `LOW` if the other Arduino is setting the pin LOW, and `HIGH` if the other Arduino is setting it HIGH.

And, as Juraj points out in their comment, CMOS devices like Arduinos respond to voltage, not current. Their inputs are capacitive. They react to a voltage potential, not current. (When you initially change a CMOS input from one state to another a small amount of current flows in to change the state of the capacitor and after that the only current that flows is a **very** tiny amount of leakage current through the capacitor on the input.)


message:
sensor for illegal parking detection

I want to create a system that will detect illegal parking. I will place the sensor s to specific locations and when a car parks there the system will send a message to local authorities. My question is if a PIR is the suitable sensor for this project.

thanks in advance.

body:
Don't get discouraged, there are many ways to do this, but I would rate a PIR as being one of the worst options because even a bird or a squirrel could set it off. Plus, once the car has stopped you can't detect it's presence anymore with a PIR sensor, it has to be moving. I would recommend either using something like a webcam and OpenCV for this or if you're set on using an Arduino and physical sensors, multiple laser or multiple ultrasonic sensors placed 5-10 feet apart so that they both have to trip at once for positive detection of a vehicle instead of something else. You're going to have to spend some time experimenting and tuning. If you want something very reliable and you own the place, you could always do what the public street works does and cut a loop into the pavement and install a large steel cable and use inductance, but that may be overkill. ;)

Some other ideas:

 - Paint a pattern on the ground using high contrast paint and detect
   when the pattern is completely covered.  Maybe there is something you
   can do with IR reflective paint and use a camera with no IR filter,
   this way you could make a pattern invisible to the eyes.

 - A carbon monoxide detector - Detects dinosaur powered vehicles, but
   is nice to the environmentally conscious.

About a decade ago now I [created my own parking detection using a Raspberry Pi and a webcam][1] and some Perl code I wrote (non-opencv). I basically just detected the shadow contrast under the car and it worked very well. Originally I tried detecting red colors in the tail lights, but this was more troublesome due to other lighting in the environment. Especially at night. In my case, I didn't have direct access to set up physical sensors and lasers would have been too intrusive, so visual analysis made sense.

  [1]: https://www.youtube.com/watch?v=lDOcIEK5rx0


message:
Keep motor moving

I have a problem on how to keep my stepper motor moving when button is released. It should only stop moving if I press the button again.

For now, stepper motor  is only moving IF the button is constantly pressed.

    //Constants won't change. They're used here to set pin numbers:
    const int buttonPin = 4;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin
    const int dirPin = 8;        // the number of the motor direction pin
    const int stepPin = 9;         // the number of the motor step pin

    //Variables will change:
    boolean flag = true;
    int buttonState = 0;         // variable for reading the pushbutton status
    int distance = 0;

    void setup() {
      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);
      pinMode(dirPin, OUTPUT);  //YELLOW
      pinMode(stepPin, OUTPUT); //ORANGE

      digitalWrite(buttonPin, LOW);
      digitalWrite(dirPin, HIGH);
      digitalWrite(stepPin, HIGH);
    }

    void loop() {
      buttonState = digitalRead(buttonPin); // Read the state of the pushbutton

      if (digitalRead(buttonPin) == LOW) {  // If pushbutton is pressed, buttonState is HIGH:
        digitalWrite(ledPin, HIGH);
        digitalWrite(dirPin, LOW);          // LOW=FORWARD DIRECTION
        digitalWrite(stepPin, HIGH);        // stepPin = MOTOR ON/OFF
        delayMicroseconds(100);
        digitalWrite(stepPin, LOW);
        delayMicroseconds(100);
        distance++;
        if(distance > 21000){
          distance = 0;
          delay (3000);
          reverse();
        }
      }

      if (digitalRead(buttonPin) == HIGH){ // turn LED off:
        digitalWrite(ledPin, LOW);
        digitalWrite(dirPin, LOW);  //LOW = FORWARD DIRECTION
        digitalWrite(stepPin, LOW); //stepPin = MOTOR ON/OFF
        delayMicroseconds(100);
        digitalWrite(stepPin, LOW);
        delayMicroseconds(100);
      }
    }

    void reverse() {
      digitalWrite(dirPin,HIGH); //HIGH = REVERSE DIRECTION
      digitalWrite(stepPin,HIGH);
      delayMicroseconds(100);
      digitalWrite(stepPin,LOW);
      delayMicroseconds(100);
      distance++;
        if(distance > 21000){
          distance = 0;
          delay(3000);
          return;
        }
      reverse();
    }

body:
N.b. your code is unreadable, so I won't attempt to debug your program, but I will present some pseudo-code that could help.

> It should only stop moving if I press the button again ... [as of] now, [the] stepper motor is only moving IF the button is constantly pressed.

So what you need to do is save the state of your Motor, (MOVING, STOPPED, etc.) and base your code on that state.

You will also need to de-bounce your switch.

Your loop will have to:

 - Read & de-bounce the switch
 - Update the state based on switch
 - Run the stepper based on state

pseudo-code:

    // include libraries etc.
    #include <Stepper.h>

    // set up your buttons pins etc.
    int button = <pin>;
    Stepper = step(...); // pins etc.

    void setup()
    {
       // do setup stuff...
    }

    enum MOTORSTATES {
      STOPPED = 1,
      FORWARD = 2,
    }

    MOTORSTATES state = STOPPED;

    // forward declare your functions
    bool isPressedDebounce(int pin);
    void doStep(Stepper&, MOTORSTATES);
    MOTORSTATES changeState(MOTORSTATES);

    // loop is now simple
    void loop()
    {
      if(isPressedDebounce(button))
        state = changeState(state);

      doStep(step, state);
    }

    // because we have broken our problem into pieces
    bool isPressedDebounce(int pin)
    {
      // proccess and de-bounce the switch
      // implementation left as exercise for reader
    }

    void doStep(Stepper& step, MOTORSTATES state)
    {
      // based on the state move the stepper
      // implementation left as exercise for reader
      switch(state)
      {
        case STOPPED:
          // DO IT
          break;
        case FORWARD:
          // DO IT
          break;
      }
    }

    MOTORSTATES changeState(MOTORSTATES state)
    {
      // n.b. I used this pattern because it is the beginning of a state machine!
      switch(state)
      {
        case STOPPED:
          return FORWARD;
          break;
        case FORWARD:
          return STOPPED;
          break;
      }
    }

I structured the pseudo code such that it contains a simple state machine, and can be easily extended. State machine code is very useful for programming Arduinos!


body:
There are two issues:

1. You SHOULD pull-up or pull-down the input pin when using pushbutton.
2. You should detect the "press" and "release" event.

Two above issues are mentioned [in this tutorial][1]

  [1]: https://arduinogetstarted.com/tutorials/arduino-button


message:
Reading a monochromatic bitmap with Arduino for plotting

Complete newbie here.

I am following this thread:
https://arduino.stackexchange.com/questions/19795/how-to-read-bitmap-image-on-arduino

Specifically the third reply from : frarugi87 in my attempt to plot a monochromatic bitmap image with a plotter device.
Basically: bitmap>SD card board>arduino uno> plotted image

I attempted to modify their code to work with monochromatic bitmaps and removed the print to file function:

        // MODIFIED CODE FROM BELOW CONTRIBUTOR

        // (c) Michael Schoeffler 2016, http://www.mschoeffler.de

        #include <SD.h> //Load SD library
        int chipSelect = 4; //chip select pin for the MicroSD Card Adapter
        File file; // file object that is used to read and write data

    int32_t readNbytesInt(File *p_file, int position, byte nBytes)  // FUNCTION WHICH READS A DETERMINED AMMOUNT OF BYTES INTO A SINGLE VARIABLE
    {
        if (nBytes > 4)
            return 0;

        p_file->seek(position);

        int32_t weight = 1;
        int32_t result = 0;
        for (; nBytes; nBytes--)
        {
            result += weight * p_file->read();
            weight <<= 8;
        }
        return result;
    }

        void setup() {
          Serial.begin(9600); // start serial connection to print out debug messages and data

          pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode
          if (!SD.begin(chipSelect)) { // Initialize SD card
            Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
          }

          if (SD.exists("bitmap.bmp")) { // if "bitmap.bmp" exists, say so
            Serial.println("Found The Bitmap File.");

          }

          file = SD.open("bitmap.bmp", FILE_READ);   // open the file to an object for reading

          // DETERMINE HOW LARGE THE BITMAP FILE IS
          int howmany;
          howmany = file.available();
          Serial.println(howmany);    // print the how large the file is

          // DETERMINE STARTING IMAGE ARRAY LOCATION IN THE BITMAP FILE
          int32_t dataStartingOffset = readNbytesInt(&file, 0x0A, 4);
          Serial.println("The starting location in the fiile is...");
          Serial.println(dataStartingOffset);

          // DETERMINE THE IMAGE HEIGHT AND WIDTH
          int32_t imgwidth = readNbytesInt(&file, 0x12, 4);
          Serial.println("The image width is the following pixels:");
          Serial.println(imgwidth);
          int32_t imgheight = readNbytesInt(&file, 0x16, 4);
          Serial.println(imgheight);

          // MODIFIED CODE. DOES THE COLOR DEPTH LOCATION WORK IN THE BITMAP AND DOES IT GIVE CORRECT INFO ABOUT THE FILE?
          int16_t pixelsize = readNbytesInt(&file, 0X1C, 2);
          if (pixelsize != 24)
          {
            Serial.println("This image is most definitely not 24 bpp");
            Serial.println(" it is actually a depth of :");
            Serial.println(pixelsize);

          }

           file.seek(dataStartingOffset);   //skip bitmap header and go directly to the image data array.

         /*  for(int32_t i = 0; i < imgheight; i ++) {
            for (int32_t j = 0; j < imgwidth; j ++) {
                B = file.read();
                Serial.println("height and width location from bottom");
                Serial.println(i);
                Serial.println(j);
                Serial.println("B");
                Serial.println(B);
            }
            Serial.println("height advance");
        }

    */
          int B;

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

                B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

            B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

                B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

                B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

          B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

            B = file.read();
          Serial.println(B, BIN);
          B = file.read();
          Serial.println(B, BIN);

        file.close();

        Serial.println("done write");

        }

But when I read a 16x16 monochromatic bitmap: see below

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

At what I assume is the color table starting location (given by dataStartingOffset variable).
I get strings two bytes of correct color information, followed by two bytes of just...zeros.
Is this a bitmap formatting thing?

Serial output for 16x16 bitmap looks like this:(only up to 9 of the 16 lines starting from the bottom)

> Found The Bitmap File. 126 The starting location in the file is... 62
> The image width is the following pixels: 16 16 This image is most
> definitely not 24 bpp  it is actually a depth of : 1 1111111 11111110
> 0 0 11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0
> 11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0
> 11111111 11111111 0 0 1111111 11111110 0 0 done write

And when I try to read a bitmap that is around 200 x 200 pixels, I get very strange height and width numbers that are negative and my above code does not work at all!
Does a 16x16 bitmap have different byte structure formatting than a 200x200?

Any help is appreciated. Again, I am a complete newbie here. I am just trying to figure out how to read a bitmap.

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

body:
Bitmap files (.BMP) have to have a row size that is a multiple of 4 bytes. Any extra space in a row has to be padded with 0.

Since your rows are 16 pixels wide that equates to 2 bytes. That's not a multiple of 4, so it is padded with to bytes of 0 to make it a multiple of 4.

Your code needs to take that into account and know that if it hasn't read a multiple of 4 bytes then to read enough "dummy" bytes to get to the start of the next row.

Also, note that BMP files are the only files in the known universe where the image data is stored upside down (starting lower-left corner instead of upper-left corner).


message:
Use 2 DHT22 AND PASS THE DATA TO SD Error File data does not exsist

anyone can help me please to fix this error when I try to compilate says File does not exsist. It would be great if anyone can post the entirely code.

Link of code below if anyone can help me please:

   https://create.arduino.cc/editor/Jawad2001/5ea57339-7ca1-4f8d-ab00-f4f1aa639209/preview

error: expected')' before 'f'

Sorry I'm new at this sorry for the annoyances.

Thanks For all your Help.

body:
Here are several things I can see from your code that cause most of the error messages.

**1)** You declare

    File data_txt;
    File data2_txt;

but you later use `data_file` and `data_file2`. This is why you see the "not declared in this scope" errors.

**2)** You do not properly define the functions `getData()` and `getData2()`. You start with the definition of `getData2()` inside the function `getData()`.
First finish the function `getData()` by closing all brackets you opened and then define the function `getData2()`, like this:

    void getData() {
    //the code of getData() goes here....
    }

    void getData2() {
    //the code of getData2() goes here....
    }

**3)** I assume you want to write to `data_file` in `getData()` and to `data_file2` in `getData2()`?! Nevertheless, you also use `data_file` in `getData2()`.

**Update after your edit:**

Regarding the compilation error, you do not open a curly bracket

**{**

after `getData2()`.

However, there are several other issues that will lead to problems, even if it finally does compile without problems.


message:
Stuck Arduino Relay?

I am looking for a relay that stays on (NC=Normally Closed), and when I send a new signal switches to off (NO=Normally Open).

So the relay doesn't consume any power while being in a specific position.

Do you guys know any type?

Thanks :)

body:
Finally, I found it!

Google Image:
https://www.google.com/search?biw=1974&bih=1050&tbm=isch&sxsrf=ACYBGNSImNFTI2vRTPD5bbjE-eRkJUzdow:1571311366907&sa=1&ei=Bk-oXcSJN5K78gKG4brgCw&q=HFD2/005&oq=HFD2/005&gs_l=img.3..0j0i24l6.1135292.1138931..1139132...0.0..0.80.289.4......0....1..gws-wiz-img.......0i5i30j0i30.yfdL1Ivd0sU&ved=0ahUKEwjEpOz-lqPlAhWSnVwKHYawDrwQ4dUDCAc&uact=5

Aliexpress:
https://www.aliexpress.com/item/32988578668.html?spm=2114.13010708.0.0.57a64c4dkzjFcM


message:
How to initialize digital output pin as low

I need to define a pin as output for relay module but when i do it in setup section, relay is activated (low - 0) automatically then i deactivated immediately with coding `digitalWrite(pin, 1)` but this issue results the relay is activated then deactivated within miliseconds. But I want to know that is it possible to define a pin as output but low in default.

    void setup(){
      pinMode(pin,OUTPUT);
      digitalWrite(pin,1);
    }

    void loop(){
      if(start_relay){
        digitalWrite(pin, 0);
      }
    }

body:
As fas as I know, by default digital pins are set as inputs. Arduino has internally only pull-up resistors, which you can use in that way:

    digitalWrite(pinOut[i], HIGH);
in first setup() line (without `pinMode(pinOut[i], OUTPUT);`).

If you need LOW state on start-up (pull-down resistors), you have to use an external resistor.


body:
If you have a relay that is activated by a LOW or ground path, and is deactivated
by an open circuit or HIGH signal applied, then you could try switching the pinMode
to act as the HIGH or open circuit.

    const byte pin = 2;

    void setup(){

      // Define the pin as INPUT_PULLUP until you are ready to use it.
      pinMode(pin, INPUT_PULLUP);

    }

    void loop(){

      delay(1000);

      // Activate the relay. Supplying a low impedance
      // path to ground turns the relay on.
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);

      delay(1000);

      // Deactivate the relay.
      pinMode(pin, INPUT_PULLUP);

      // Using digitalWrite(pin, HIGH); is an alternative to using
      // pinMode(pin, INPUT_PULLUP); If your relay module is the
      // same as the one shown below, then it doesn't matter which
      // method you choose.

    }

I'm not sure which relay module you are using, but if it is the same as this type, using INPUT_PULLUP will work.

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

As Edgar Bonet mentions in his comment to kot's answer, using `pinMode(pin, INPUT_PULLUP);` is clearer than using `digitalWrite(pin, HIGH);`.

This code does 2 things:

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

First it sets the pin to INPUT_PULLUP, then it sets it to VCC (for lack of a better term). If you connect a modern LED with a 1k ohm resistor to pin 2, and use this sketch, you can see the LED "dimly" lit for 5 seconds, then it is "brightly" lit.

    const byte pin = 2;

    void setup() {

      // pre-set output value to HIGH
      // The internal pull up resistor is now connected to the pin.
      digitalWrite(pin,HIGH);

      // Wait for 5 seconds.
      delay(5000);

      // set to output, it will be HIGH
      // The pin is now connected to VCC (for lack of a better term).
      pinMode(pin,OUTPUT);

    }

    void loop(){}

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


body:
There are two solutions:

 1. Use the pin as a open-collector pin as in the answer of VE7JRO.
    Switch the pin between input (high) and output with low. I prefer
    to use the INPUT_PULLUP.
 2. Write the output value before setting the pinMode.

All the microcontrollers of the AVR family (ATtiny and ATmega chips) allow to set the output value before setting the pin as output. This will enable the pullup resistor, but when it is done in the right order, that is fine.

Because this is a common way to use the microcontrollers and processors, the Arduino libraries allow to use that. The Arduino libraries for the SAMD processors (Arduino Zero, M0 and MKR) are written to allow that as well.

    void setup() {
      digitalWrite(pin,HIGH);     // pre-set output value to HIGH
      pinMode(pin,OUTPUT);        // set to output, it will be HIGH
    }

    void loop() {
      digitalWrite(pin,LOW);
      delay(1000);
      digitalWrite(pin,HIGH);
      delay(1000);
    }

When the relay module has floating inputs (as far as I know they do not) then you need extra hardware to pull the signal high with a pullup resistor to keep the relays disabled during reset.


message:
attiny85 reset itself instead of wakeup procedure

I have a [digispark attiny85](https://paradisetronic.com/en/arduino/tiny85-board-attiny85-microusb-digispark-arduino-ide-compatible), and I am using SLEEP_MODE_PWR_DOWN to sleep, and wake-up with external interrupt on pin2. I am trying to count number of interrupts received with the code below.

Problem is on every LOW signal on pin2, attiny85 reset (restart) itself instead of processor wake-up and continue where it left. I can identify this by seeing led blink 3 times(_as in setup()_) on every LOW signal.

Is there a limitation on this hardware? **How can I only wake-up from sleep and not reset?** I appreciate if you direct me an example.

```
#include <avr/interrupt.h>
#include <avr/sleep.h>

//modified from http://playground.arduino.cc/Learning/arduinoSleepCode

int ledPin = 0;            // LED connected to digital pin 0
int interruptPin = 1;      // LED to show the action of a interrupt
int wakePin = 2;            // active LOW, ground this pin momentary to wake up
unsigned int counter = 0;

void setup(){
  pinMode(ledPin, OUTPUT);         // sets the digital pin as output
  pinMode(interruptPin, OUTPUT);   // sets the digital pin as output
  pinMode(wakePin, INPUT_PULLUP);        // sets the digital pin as input
  digitalWrite(wakePin, HIGH);
  counter = 0;
  //do some blinks so we can identify boot & loop
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
}

void sleepNow(){

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();                          // enables the sleep bit in the mcucr register so sleep is possible
    attachInterrupt(0, wakeUpNow, LOW);     // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
    digitalWrite(interruptPin, LOW);

    sleep_mode();                          // here the device is actually put to sleep!!

    sleep_disable();                       // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);                    // disables interrupton pin 3 so the wakeUpNow code will not be executed during normal running time.
    delay(250);                           // wait 2 sec. so humans can notice the interrupt LED to show the interrupt is handled
    digitalWrite (interruptPin, HIGH);       // turn off the interrupt LED

}

void wakeUpNow(){        // here the interrupt is handled after wakeup

  //execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
 digitalWrite(interruptPin, HIGH);
}

void loop(){
   digitalWrite(interruptPin, HIGH);
  //digitalWrite(ledPin, HIGH);            // sets the LED on
  counter++;
  delay(5000);                           // waits for a second
  sleepNow();                      // sleep function called here
}
```

body:
I found this, I can confirm it is working. on digispark attiny85.

```
void sleepTillChg() {  // 0.02ma drain while sleeping here
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT0);                   // Use PB0 (was PB3) as interrupt pin
    // Turn off unnecessary peripherals
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    ACSR |= _BV(ACD); // Disable analog comparator

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep ... Zzzz

    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT0);                  // Turn off PB0 (was PB3) as interrupt pin
    sleep_disable();                        // Clear SE bit
    sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
    // This is called when the interrupt occurs, but we don't need to do anything in it
}
```

credits should go
https://www.instructables.com/id/3-Minute-Game-Timer/


message:
Servo Motors PWM pins, Arduino Uno

I wanted to understand how people are connecting a servo motor to pins without PWM, so I went searching and I read that the Servo library uses the timer1 of pin 9 and pin 10 to be able to use other pins.

I would like to ask some questions about this.

1. Could I connect a servo motor on pin 12 by emulation of the library, and another servo on pin 9, another on pin 10 and another on pin 11 at the same time?

2. Or using the Servo library the PWM in pin 9 and 10 stops working?
3. I could then through library emulation connect one servo on pin 7, another on 8, another on 12 and another on 13 ?
4. 4 emulations at the same time?

body:
Have you read the [Servo library page](https://www.arduino.cc/en/Reference/Servo)?

The library support upto 12 servos outputs. You can use any pin you want.

The library disables analogWrite() (PWM) functionality on pins 9 and 10.


body:
For those looking for more information on PWM in arduino, a must see page is this one:
[http://www.righto.com/2009/07/secrets-of-arduino-pwm.html][1]. Once you read it you may undestand, what is software and hardware PWM and which are the limitations.

To do the software PWM the servo library takes over one of the three arduino's timers. So pin 9,10 are not available to analoWrite() anymore, resting Timer0 (pins 5,6) and Timer2 (pins 11,3).

Note that internally arduino must use Timer0 to its timing functions (such as delay(), milis(), etc).

So to answer your question:

1) Yes, you can since the library is managing your timers it may allocate fine (as software emulation though).

2) Yes and No. It works for the library itself but may be not at disposal for other libraries or for your code. Example: if you want use it along with RH_ASK (radio frequency library) you have an conflict of timer usage and may be needed to change the config of one of them to move to another Timer.

3) Yes.

4) Yes (you can get all 20 pins working as PWM if you want. [SoftPWM][2] library does that).

Best regards,

gl

  [1]: http://www.righto.com/2009/07/secrets-of-arduino-pwm.html
  [2]: https://code.google.com/archive/p/rogue-code/wikis/SoftPWMLibraryDocumentation.wiki


message:
Set Low Power Level or Enable Pin of stepper driver, so stepper does not get hot

I am using the code below with this stepper shield:

https://www.dfrobot.com/wiki/index.php/Stepper_Motor_Shield_For_Arduino(DRV8825)_SKU:DRI0023

Everything works, but tends to get hot (62.3 Celsius) while holding in idle position. What I understood so far, to reduce the temperature I can:

1. Set enable pin only when I need to turn the motor, but loose my position.

2. I can use what the driver manual describes as low level. Which I did not entirely understand.

If I set the enable pin to low by doing `digitalWrite(M1en,LOW);` do I put the stepper in low power mode or do I switch off the power to the stepper ?

3. I could only enable the stepper (if by setting it to LOW or HIGH I enable, disable) when I need it. Which would be the best as I understood it.

Where in my code below would I have to add the digitalWrite LOW,HIGH to achieve this ? Or do I need to just set it LOW (for low power mode).

4. Or is there a much better way I don't know about.

Code:

    const int dirPin = 4;
    const int stepPin = 5;
    const int M1en = 12;

    int speed = 200;    // desired speed in steps per second
    int steps = 0;      // the number of steps to make

    void setup()
    {
      pinMode(dirPin, OUTPUT);
      pinMode(stepPin, OUTPUT);
      digitalWrite(M1en,LOW);// Low Level Enable
      Serial.begin(9600);
    }

    void loop()
    {
      if ( Serial.available()) {
        char ch = Serial.read();

        if(isDigit(ch)){             // is ch a number?
          steps = steps * 10 + ch - '0';        // yes, accumulate the value
        }
        else if(ch == '+'){
          step(steps);
          steps = 0;
        }
        else if(ch == '-'){
          step(-steps);
          steps = 0;
        }
        else if(ch == 's'){
          speed = steps;
          Serial.print("Setting speed to ");
          Serial.println(steps);
          steps = 0;
        }
      }
    }

    void step(int steps)
    {
      int stepDelay = 1000 / speed;  //delay in ms for speed given as steps per sec
      int stepsLeft;

      // determine direction based on whether steps_to_mode is + or -
      if (steps > 0)
      {
        digitalWrite(dirPin, HIGH);
        stepsLeft = steps;
      }
      if (steps < 0)
      {
        digitalWrite(dirPin, LOW);
        stepsLeft = -steps;
      }
      // decrement the number of steps, moving one step each time
      while(stepsLeft > 0)
      {
        digitalWrite(stepPin,HIGH);
        delayMicroseconds(1);
        digitalWrite(stepPin,LOW);
        delay(stepDelay);
        stepsLeft--;      // decrement the steps left
      }
    }

body:
The product page you gave has a link to the [DRV8825 datasheet][1].

Reading this, it is clear that the enable pin(s) comlpetely disable the H-Bridge that drives the motor coils. This **is** low power mode. It'd doesn't mean low, but non-zero holding current. The driver only supports enabled and disabled.

If your steppers are getting hot, perhaps the current being supplied by the driver is too high. The maximum drive current is set by the current-sense resistors attached to the driver chip. These may not be easy to change. To decrease the maximum current, you increase the current-sense resistor.

The product page notes that the shield has the current set at 1.6A per coil.

  [1]: https://github.com/Arduinolibrary/DFRobot_Stepper_Motor_Driver_DRV8825/raw/master/Datasheet_DRV8825.pdf


message:
Arduino Python to Serial command

I am trying to send commands via serial from Python to Arduino with the code below.

If I save this code in a dedicated python file "Stepper.py" (Python2.7 on Mac OSX) , the code runs successfully but nothing happens (the code does not trigger a motor connected to Arduino).

If I start terminal and run the same code from the interactive shell it works as expected.

How can I run it via a dedicated file ?

    import serial
    import time

    ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
    ser.write("200+")
    time.sleep(1)
    print ser.read()

body:
Majenkos comment (above) solved the problem:

"You need to wait after opening the serial port for the board to finish resetting and the bootloader to run and exit before you can send any commands."

    import serial
    import time

    ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
    time.sleep(1)
    ser.write("200+")
    print ser.read()


message:
Arduino button and led

Program below is my program for my button and LED, but it's not functioning the way I want it too. The LED is supposed to light up before I press switch 9, but it is lighting up immediately.

    const int sw9=9;
    const int sw10=10;
    const int sw11=11;
    const int sw12=12;
    const int sw13=13;
    int timer=250;
    int s=0;
    void setup()
    {
      for (int opin=1;opin<=8;opin++)
    {
      pinMode(opin,OUTPUT);
      pinMode(sw9,INPUT_PULLUP);
      pinMode(sw10,INPUT);
      pinMode(sw11,INPUT);
      pinMode(sw12,INPUT);
      pinMode(sw13,INPUT);
    }
    }
    void loop(){
    {
    while (s==0)

    for (int opin=1;opin<=8;opin++)
    {
    digitalWrite(opin,HIGH);
    delay(timer);
    digitalWrite(opin,LOW);
    if(digitalRead(sw9)==LOW);
    }

    {
    s=1;
    delay(timer);
    }
    }
    while(s==1)
    for (int opin=1;opin<=8;opin++)
    {
    digitalWrite(opin,LOW);
    if(digitalRead(sw9)==HIGH);
    }
    }

body:
    if(digitalRead(sw9)==LOW);

    if(digitalRead(sw9)==HIGH);

Both of these have the effect of "read the switch and then do nothing"

Change them to

    if(digitalRead(sw9)==HIGH){
    // do intended action
    }


message:
Why does a delay make my stepper stop? And why does the break command raise an error?

I am using a stepper motor for a project that I want it to stop. I tried *for loops*, *while*, and an *if statement*. All of these were placed inside the *void loop*, because it raised an error.

My code with the if loop:

    //This program does about 1 rotation or 4100 steps. The program should be able to stop the stepper motor after it does one rotation.
    int Pin1 = 8;
    int Pin2 = 9;
    int Pin3 = 10;
    int Pin4 = 11;
    int _step = 0;
    int _on = 4100;
    int _switches = 0;
    boolean direct = false;
    void setup() {
      pinMode (Pin1, OUTPUT);
      pinMode (Pin2, OUTPUT);
      pinMode (Pin3, OUTPUT);
      pinMode (Pin4, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      if (_on > 0) {
        switch(_step)
        {
          case 0:
            digitalWrite (Pin1, LOW);
            digitalWrite (Pin2, LOW);
            digitalWrite (Pin3, LOW);
            digitalWrite (Pin4, HIGH);
          break;
          case 1:
            digitalWrite (Pin1, LOW);
            digitalWrite (Pin2, LOW);
            digitalWrite (Pin3, HIGH);
            digitalWrite (Pin4, HIGH);
          break;
          case 2:
            digitalWrite (Pin1, LOW);
            digitalWrite (Pin2, LOW);
            digitalWrite (Pin3, HIGH);
            digitalWrite (Pin4, LOW);
          break;
          case 3:
            digitalWrite (Pin1, LOW);
            digitalWrite (Pin2, HIGH);
            digitalWrite (Pin3, HIGH);
            digitalWrite (Pin4, LOW);
          break;
          case 4:
            digitalWrite (Pin1, LOW);
            digitalWrite (Pin2, HIGH);
            digitalWrite (Pin3, LOW);
            digitalWrite (Pin4, LOW);
          break;
          case 5:
            digitalWrite (Pin1, HIGH);
            digitalWrite (Pin2, HIGH);
            digitalWrite (Pin3, LOW);
            digitalWrite (Pin4, LOW);
          break;
          case 6:
            digitalWrite (Pin1, HIGH);
            digitalWrite (Pin2, LOW);
            digitalWrite (Pin3, LOW);
            digitalWrite (Pin4, LOW);
          break;
          case 7:
            digitalWrite (Pin1, HIGH);
            digitalWrite (Pin2, LOW);
            digitalWrite (Pin3, LOW);
            digitalWrite (Pin4, HIGH);
          break;
          case 8:
            digitalWrite (Pin1, LOW);
            digitalWrite (Pin2, LOW);
            digitalWrite (Pin3, LOW);
            digitalWrite (Pin4, LOW);
          break;
        }

        if(direct == false) {
          _step++;
          _switches++;
          direct = false;
        }else{
          _step--;
          _switches--;
          direct = true;
        }

        Serial.println(_switches);

        if(_step>7) {
          _step=0;
        }

        if(_step<0) {
          _step=7;
        }
        _on--;
        delay(1); // This solves it.
      }
      break; //This raises an error when used with for loop.
    }

Can anyone help on why the delay makes it stop? And why the break command raises and error?

Arduino UNO. 5 wire stepper.

body:
> ... why the break command raises and error?

Because you are using it wrong! break will end a loop, and is used in the switch...case statements. Read the documentation for [break][1] if you need to know more

> I have fixed it, the delay at the end fixes it for some reason. I don’t know why though.

You haven't really fixed it if you don't know why. It seems that you are trying to directly control a 5 wire stepper, i assume your pins must drive a transistor or something as the arduino pins themselves will not work.

The reason it works is because the stepper takes time to energize and move, if you don't wait long enough it won't work, your serial.print must be long enough, as the delay(1) should produce a 1ms delay which is too short.

You are driving your stepper wrong, you have the code setup for a half-step control, but you have 9 states, state 8 in not needed.

you are duplicating effort you don't need with both _steps and _switches, they always have the same value.

you can do better on your code as well:

    int dir = 1
    int c = 0

    // in loop
    c += dir

    if (c > max)
    {
      dir *= -1
      c = max
    }

    if (c < min)
    {
      dir *= -1
      c = min
    }

With this you don't have to check the direction to modify your variables.

  [1]: https://en.cppreference.com/w/cpp/language/break


body:
In simple terms: break() literally breaks out of the immediate loop it is in. Since you were in no loop [void loop() is not your usual loop functions, it's just Arduino-for keep repeating whatever is inside infinitely. You could use a for/while loop in setup() for how many ever times you want it to run and then use break().] delay(time in ms), as the name says just pauses the Arduino like a brainfart for how much ever time you put as the parameter. You could check out this [link][1] in the future for information of inbuilt functions and other language-related doubts.

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


message:
How to subtract the current analog value from previous one

I pretty new to the Arduino. I am working on project that find the power by reading your

body:
I think you need something like the following :

    int lastTime;

    void loop(){
      int thisTime = analogRead(A1);
      int diff = thisTime - lastTime;
      lastTime = thisTime;
      Serial.println(diff);
    }


message:
Arduino max power supply limit

What is the maximum current that can be supplied to an Arduino Mega board before frying/breaking?

Basically i have several components connected to my board which draw a total current of 1.6A (which i calculated through a table), and thinking of using a 9V 2A power supply. I know that the arduino voltage limit is 7-12V but just wondering about the current as I can't find it on the datasheets?

Thanks in advance!

body:
1A coming in thru the barrel jack connecor, then you risk blowing the 1A rated reverse polarity protection diode. The 5V regulator will overheat at high currents above 7.5V. The chip itself can have 800mA put thru if if properly cooled and the IO limits of current per port are respected.

So 1.6A, no way.


body:
Your question isn't clear. Are you talking about drawing regulated 5V from the Arduino power supply? I believe the built-in regulator has a hard limit if 1A total output, but how much you can draw from it will depend on various factors (mostly how much waste heat it generates. If you drive it from 9V it will generate quite a bit of heat, since a linear regulator simply dissipates the excess voltage as heat. Better to use a 7V supply)

You won't be able to draw 1.6A of 5V from the Arduino. You should probably get a separate 2A 5V regulated power supply for your external components. Again though, your question isn't very clear so I'm not sure I'm answering what you're asking.


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

From the [ATmega328P datasheet][2].

  [1]: https://i.stack.imgur.com/nLAlB.png
  [2]: http://www.atmel.com/Images/doc8161.pdf


message:
NodeMCU display temperature and control LED from an autorefresh web page

I'm totaly new to Arduino, I'm using ESP2866 NodeMCU and dht22 to display temperature and humidity in a web page, it is autorefresh (using AJAX) and it works perfectly, I wanted to add 2 buttons to it so I can control 2 Leds but when I tried that I couldn't control them and even the values of temperature and humidity stopped refreshing. Can you tell me what is wrong in the code ? here it is :

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>
    #include "DHT.h"
    #define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

     /*Put your SSID & Password*/
     const char* ssid = "xxx";  // Enter SSID here
     const char* password = "xxx";  //Enter Password here

      ESP8266WebServer server(80);

     // DHT Sensor
     uint8_t DHTPin = D6;

      // Initialize DHT sensor.
      DHT dht(DHTPin, DHTTYPE);

      float Temperature;
      float Humidity;
      float reading;
      float percentage;
      // Auxiliar variables to store the current output state
      String output5State = "off";
      String output4State = "off";

     // Assign output variables to GPIO pins
     const int output5 = 5;
     const int output4 = 4;
     void setup() {
     Serial.begin(115200);
     delay(100);

     pinMode(DHTPin, INPUT);
     dht.begin();

    // Initialize the output variables as outputs
      pinMode(output5, OUTPUT);
     pinMode(output4, OUTPUT);
     // Set outputs to LOW
     digitalWrite(output5, LOW);
     digitalWrite(output4, LOW);
     Serial.println("Connecting to ");
     Serial.println(ssid);

    //connect to your local wi-fi network
    WiFi.begin(ssid, password);

    //check wi-fi is connected to wi-fi network
    while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected..!");
    Serial.print("Got IP: ");  Serial.println(WiFi.localIP());

    server.on("/", handle_OnConnect);
    server.onNotFound(handle_NotFound);

    server.begin();
    Serial.println("HTTP server started");

    }
    void loop() {

    server.handleClient();
    }

    void handle_OnConnect() {

    Temperature = dht.readTemperature(); // Gets the values of the temperature
    Humidity = dht.readHumidity(); // Gets the values of the humidity

    //Serial.println(reading);
    String header=SendHTML( Temperature,Humidity,percentage);

    server.send(200, "text/html",header);
    // turns the GPIOs on and off
            if (header.indexOf("GET /5/on") >= 0) {
              Serial.println("GPIO 5 on");
              output5State = "on";
              digitalWrite(output5, HIGH);
            } else if (header.indexOf("GET /5/off") >= 0) {
              Serial.println("GPIO 5 off");
              output5State = "off";
              digitalWrite(output5, LOW);
            } else if (header.indexOf("GET /4/on") >= 0) {
              Serial.println("GPIO 4 on");
              output4State = "on";
              digitalWrite(output4, HIGH);
            } else if (header.indexOf("GET /4/off") >= 0) {
              Serial.println("GPIO 4 off");
              output4State = "off";
              digitalWrite(output4, LOW);
            }

          }

       void handle_NotFound(){
       server.send(404, "text/plain", "Not found");
        }

       String SendHTML(float TempCstat,float Humiditystat, float  percentage){
        String ptr = "<!DOCTYPE html> \n";
        ptr +="<meta name=\"viewport\" content=\"width=device-width,
        initial-scale=1.0, user-scalable=no\">\n";
        // ptr +="<meta http-equiv=\"refresh\" content=\"2\" >\n";
       ptr +="<link href=\"https://fonts.googleapis.com/css?
        family=Open+Sans:300,400,600\" rel=\"stylesheet\">\n";
        ptr +="<title>ESP8266 Weather Report</title>\n";
        ptr +="\n";
         ptr +="\n";

         ptr +="\n";
         ptr +="\n";

         ptr +="
\n";

         ptr +="
ESP8266 Weather Report
\n";
         ptr +="
\n";
         ptr +="
\n";
         ptr +="<svg version=\"1.1\" id=\"Layer_1\"
         xmlns=\"http://www.w3.org/2000/svg\"
         xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n";
         ptr +="width=\"9.915px\" height=\"22px\" viewBox=\"0 0 9.915 22\"
         enable-background=\"new 0 0 9.915 22\" xml:space=\"preserve\">\n";
          ptr +="<path fill=\"#FFFFFF\" d=\"M3.498,0.53c0.377-0.331,0.877-
          0.501,1.374-0.527C5.697-0.04,6.522,0.421,6.924,1.142\n";
          ptr+=
           "c0.237,0.399,0.315,0.871,0.311,1.33C7.229,5.856,7.245,9.24,7.227,
            12.625c1.019,0.539,1.855,1.424,2.301,2.491\n";
          ptr +="c0.491,1.163,0.518,2.514,0.062,3.693c-0.414,1.102-1.24,2.038-
          2.276,2.594c-1.056,0.583-2.331,0.743-3.501,0.463\n";
          ptr +="c-1.417-0.323-2.659-1.314-3.3-2.617C0.014,18.26-
          0.115,17.104,0.1,16.022c0.296-1.443,1.274-2.717,2.58-3.394\n";
          ptr +="c0.013-3.44,0-6.881,0.007-
          10.322C2.674,1.634,2.974,0.955,3.498,0.53z\"/>\n";
          ptr +="</svg>\n";
          ptr +="
\n";
          ptr +="
Temperature
\n";
          ptr +="
";
          ptr +=(int)TempCstat;
          ptr +="°C
\n";
          ptr +="
\n";
          ptr +="
\n";
          ptr +="
\n";
          ptr +="<svg version=\"1.1\" id=\"Layer_2\"
          xmlns=\"http://www.w3.org/2000/svg\"
          xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n\";
          width=\"12px\" height=\"17.955px\" viewBox=\"0 0 13 17.955\" enable-
          background=\"new 0 0 13 17.955\" xml:space=\"preserve\">\n";
          ptr +="<path fill=\"#FFFFFF\"
         d=\"M1.819,6.217C3.139,4.064,6.5,0,6.5,0s3.363,4.064,4.681,6.217c1.793,
          2.926,2.133,5.05,1.571,7.057\n";
         ptr +="c-0.438,1.574-2.264,4.681-6.252,4.681c-3.988,0-5.813-3.107-
         6.252-4.681C-0.313,11.267,0.026,9.143,1.819,6.217\"></path>\n";
         ptr +="</svg>\n";
         ptr +="
\n";
         ptr +="
Humidity
\n";
         ptr +="
";
         ptr +=(int)Humiditystat;
         ptr +="%
\n";
         ptr +="
\n";

        //Buttons

         ptr +="
\n";
         ptr +="
Button
\n";
         ptr +="
";
         ptr +="
<button class=\"button\">ON</button>

";
         // If the output5State is off, it displays the ON button
            if (output5State=="off") {
              ptr +="
<button class=\"button\">ON</button>

";
            } else {
              ptr +="
<button class=\"button
            button2\">OFF</button>
";
            }
             // If the output4State is off, it displays the ON button
            if (output4State=="off") {
              ptr +="
<button class=\"button\">ON</button>

";
            } else {
              ptr +="
<button class=\"button
              button2\">OFF</button>
";
              }
               ptr +="%
\n";
               ptr +="
\n";
               ptr +="
\n";
               ptr +="\n";
               ptr +="\n";
               return ptr;
              }

body:
Write handlers for different URLs
```
server.on("/5/on", led5On);
server.on("/5/off", led5off);
```
do you get the concept?

or you could write one handler `server.on("/setLED", setLED);`, if you would send `"/setLED?num=5&state=on"`. and then in `setLED` function get the parameters values as

```
String num = sever.arg("num");
String state = sever.arg("state");
```

see the SimpleAuthentication example


message:
Sending char arry via nRF24L01

I am trying to send a char array using Arduino Uno board and nRF24L01 modules

Here is the code for both transmitter and receiver:

     #include <SPI.h> //~ #include <TMRh20nRF24L01.h> //~ #include <TMRh20RF24.h>
     #include <nRF24L01.h>
     #include <RF24.h>

     #define CE_PIN   9
     #define CSN_PIN 10

     // NOTE: the "LL" at the end of the constant is "LongLong" type //
     These are the IDs of each of the slaves const uint64_t slaveID[2] =
     {0xE8E8F0F0E1LL, 0xE8E8F0F0E2LL} ;

     RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

     char
    > dataToSend[64]="e7665072be018b6b58ea9e40cf38553d6dc293cda4c9d94cda6e91ca61b3a073";

     unsigned long currentMillis; unsigned long prevMillis; unsigned long
    > txIntervalMillis = 1000; int txVal = 0; float ackMessg[2]={1,2}; byte
     ackMessgLen = 4; // NB this 4 is the number of bytes in the 2 ints
     that will be recieved

     void setup() {

        Serial.begin(9600);
         Serial.println("Track Control Starting");
         radio.begin();
         radio.setDataRate( RF24_250KBPS );
         radio.enableAckPayload();
         radio.setRetries(3,5); // delay, count }

     //====================

     void loop() {

         currentMillis = millis();
         if (currentMillis - prevMillis >= txIntervalMillis) {

         radio.openWritingPipe(slaveID[0]); // calls the first slave
                                             // there could be a FOR loop to call several slaves in turn

         bool rslt;
         rslt = radio.write( dataToSend, sizeof(dataToSend) );
         Serial.print("\nRSLT (1 = success) ");
         Serial.println(rslt);
         Serial.print("Data Sent ");
         Serial.print(dataToSend[0]);
         Serial.print("  ");
         Serial.println(dataToSend[1]);
         if ( radio.isAckPayloadAvailable() ) {
             radio.read(ackMessg,ackMessgLen);
            Serial.print("Acknowledge received: ");
            Serial.print(ackMessg[0]);

>      #include <SPI.h>
>      #include <nRF24L01.h>
>      #include <RF24.h>
>
>
>      #define CE_PIN   9
>      #define CSN_PIN 10
>
>      // NOTE: the "LL" at the end of the constant is "LongLong" type
>
>      const uint64_t   deviceID = 0xE8E8F0F0E1LL; // Define the ID for this slave
>
>     int valChange = 1;
>
>      RF24 radio(CE_PIN, CSN_PIN);
>
>      char  dataReceived[64];
>      int ackData[2] = {12,23};
>
>      void setup() {
>
>          Serial.begin(9600);
>          delay(1000);
>          Serial.println("Hand Controller Starting");
>          radio.begin();
>          radio.setDataRate( RF24_250KBPS );
>          radio.openReadingPipe(1,deviceID);
>          radio.enableAckPayload();
>          radio.writeAckPayload(1, ackData, sizeof(ackData));
>          radio.startListening();
>      }
>
>      void loop() {
>
>          if ( radio.available() ) {
>              radio.read( dataReceived, sizeof(dataReceived) );
>               for (int x = 0; x <64; x++) {
>            //if (dataReceived[x] < 16) {
>            //  Serial.write('0');
>          // }
>            Serial.print(dataReceived[x]);}
>            Serial.println();
>              radio.writeAckPayload(1, ackData, sizeof(ackData));
>
>              ackData[0] += valChange; // this just increments so you can see that new data is being sent
>          }
>     }

And here is the output that I get

> Hand Controller Starting
>
> e7665072be018b6b58ea9e40cf38553d

body:
TX code

    #include "sha256.h"
    #include <Arduino.h>
    #include "./printf.h"

    #include <SPI.h>
    //~ #include <TMRh20nRF24L01.h>
    //~ #include <TMRh20RF24.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    #define CE_PIN   9
    #define CSN_PIN 10

    // NOTE: the "LL" at the end of the constant is "LongLong" type
    // These are the IDs of each of the slaves
    const uint64_t slaveID = 0xE8E8F0F0E1L  ;

    RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

    unsigned long currentMillis;
    unsigned long prevMillis;
    unsigned long txIntervalMillis = 1000;
    int txVal = 0;
    int ackMessg[6];
    byte ackMessgLen = 4;

    uint8_t* hash;
    uint8_t copy[32];
    void printHash(uint8_t* hash) {
      int i;
      for (i=0; i<32; i++) {
        Serial.print("0123456789abcdef"[hash[i]>>4]);
        Serial.print("0123456789abcdef"[hash[i]&0xf]);
          copy[i]=hash[i];
      }
      Serial.println();
    }

    void setup() {
      printf_begin();

      uint32_t a;
      unsigned long ms;

      Serial.begin(9600);

      radio.begin();
        radio.setDataRate( RF24_2MBPS );
        radio.enableAckPayload();
        radio.setRetries(3,5); // delay, count

      // SHA tests
      Serial.println("Test: FIPS 180-2 B.1");
      Serial.println("Expect:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
      Serial.print("Result:");
      ms = micros();
      Sha256.init();
      Sha256.print("abc");
      printHash(Sha256.result());
      Serial.println();
      for(int x=0;x<32;x++)
            {   Serial.print(copy[x]);
                Serial.print(" ");
                                      }
                Serial.println();

      Serial.print(" Hash took : ");
      Serial.print((micros() - ms));
      Serial.println(" micros");
      Serial.println();

      }

    void loop() {

      currentMillis = millis();
        if (currentMillis - prevMillis >= txIntervalMillis) {

        radio.openWritingPipe(slaveID);
        bool rslt,rsltt;
        rslt = radio.write( copy, 32 );

        if ( radio.isAckPayloadAvailable() ) {
            radio.read(ackMessg,ackMessgLen);
            Serial.print("Acknowledge received: ");
            Serial.print(ackMessg[0]);
            Serial.print("  ");
            Serial.println(ackMessg[1]);
        }
        prevMillis = millis();
     }

    }

Rx code

    // HandController - the slave or the receiver

        // http://tmrh20.github.io/RF24/

        //~ - CONNECTIONS: nRF24L01 Modules See:
        //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
        //~ 1 - GND
        //~ 2 - VCC 3.3V !!! NOT 5V
        //~ 3 - CE to Arduino pin 9
        //~ 4 - CSN to Arduino pin 10
        //~ 5 - SCK to Arduino pin 13
        //~ 6 - MOSI to Arduino pin 11
        //~ 7 - MISO to Arduino pin 12
        //~ 8 - UNUSED

    #include <SPI.h>
    //~ #include <TMRh20nRF24L01.h>
    //~ #include <TMRh20RF24.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    #define CE_PIN   9
    #define CSN_PIN 10

    // NOTE: the "LL" at the end of the constant is "LongLong" type

    const uint64_t   deviceID[2] ={ 0xE8E8F0F0E1LL,0xE8E8F0F0E1LL}; // Define the ID for slaves

    int valChange = 1;

    RF24 radio(CE_PIN, CSN_PIN);
    RF24 radioo(CE_PIN, CSN_PIN);
    uint8_t  dataReceived[32];

    int ackData[2] = {12,23};

    void setup() {

        Serial.begin(9600);
        Serial.println("Hand Controller Starting");
        radio.begin();
        radio.setDataRate( RF24_2MBPS );
        radio.openReadingPipe(1,deviceID[1]);
        radio.enableAckPayload();
        radio.writeAckPayload(1, ackData, sizeof(ackData));
        radio.startListening();

    }

    void loop() {

     unsigned long startTimer = millis();

        if ( radio.available() ) {
            radio.read( dataReceived, sizeof(dataReceived) );
            radio.writeAckPayload(1, ackData, sizeof(ackData));
            Serial.println();
            //Serial.println(startTimer);
            Serial.println();
            for(int x=0;x<32;x++)
            {Serial.print(dataReceived[x]);
            Serial.print(" ");}}
            ackData[0] += valChange; // this just increments so you can see that new data is being sent

        }

it is fully working now with both outputs on the same size