body:
I'm working on Python and nodeMCU with websocket connection.

So, I send a string from Python to nodeMCU and nodeMCU collects the string and decodes to set values to a stepper motor. Initial code worked fine before updating with stepper motor code. Now it triggers watchdog resets.

Here's my full code:-

```
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AccelStepper.h>

// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver:
#define dirPin 8  // clk+
#define stepPin 9  // cw+
#define motorInterfaceType 1

AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);

const char ssid[] PROGMEM ="PencoNetwork2";    //change it to your wifi SSID
const char password[] PROGMEM ="Penco1234567890";    //change it to your wifi password

AsyncWebServer server(80);
AsyncWebSocket ws("/test");

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println(WiFi.localIP());

  ws.onEvent(onWsEvent);
  server.addHandler(&ws);

  server.begin();

}

void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){

  if(type == WS_EVT_CONNECT){

    Serial.println("Websocket client connection received");

  } else if(type == WS_EVT_DISCONNECT){
    Serial.println("Client disconnected");

  } else if(type == WS_EVT_DATA){

    Serial.println("Data received: ");

    for(int i=0; i < len; i++) {
//          Serial.print((char) data[i]);
           String data_String = (String) data[i];

          int commaIndex = data_String.indexOf(',');
          int secondCommaIndex = data_String.indexOf(',', commaIndex+1);
          String firstValue = data_String.substring(0, commaIndex);
          String secondValue = data_String.substring(commaIndex+1, secondCommaIndex);
          String thirdValue = data_String.substring(secondCommaIndex+1); //To the end of the string

          int mDist = firstValue.toInt();
          int mspeed = secondValue.toInt();
          int mAccel = thirdValue.toInt();

          stepper.setMaxSpeed(mspeed);
          stepper.setAcceleration(mAccel);

          stepper.moveTo(mDist);
          stepper.runToPosition();
          delay(1000);
          stepper.moveTo(0);
          stepper.runToPosition();
          delay(1000);

    }

//    Serial.println();
  }
}

void loop(){

  }

 ```

It would be a great help pointing out my mistakes.

title: wdt reset cause:4, boot mode:(3,6)

Answers: 1

body:
You're calling `delay()` in the `onWsEvent()` callback. The [ESPAsyncWebServer][1] documentation specifically says not to do that in the '**Important things to remember'** section:

> You can not use yield or delay or any function that uses them inside the callbacks

When you call `delay()` or loop inside an async web server callback, you block its event task from doing any other processing. This can interfere with a variety of housekeeping functions that HTTP, TCP and the Arduino Core need to perform. In general you should do as little as possible during a callback and return as quickly as possible.

The correct way to structure this code is to set a flag in the callback and inspection the flag and do the work in `loop()`.

For instance,
```
AsyncWebServer server(80);
AsyncWebSocket ws("/test");

boolean flag_move_stepper = false;

void setup(){
```

and

```
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){

  if(type == WS_EVT_CONNECT){

    Serial.println("Websocket client connection received");

  } else if(type == WS_EVT_DISCONNECT){
    Serial.println("Client disconnected");

  } else if(type == WS_EVT_DATA){
    flag_move_stepper = true;

    // you'll need to rewrite this code to share variables with `loop()` and do the work there
```

and

```
void loop(){
  if(flag_move_stepper) {
    flag_move_stepper = false;

    // do the work formerly in onWsEvent() here
  }

}
```

You'll need to make the variables you stored data in in the event handler available to `loop()` and move the stepper code there for this to work.

  [1]: https://github.com/me-no-dev/ESPAsyncWebServer


body:
I am using Arduino Nano to test a code that will be ported on an ATTiny chip, which will need to perform operations at a frequency near clock maximum, calling for a *very* succinct coding.

**My goal: to streamline coding for two different chips in one file with the least repetitions and operations possible.**

Specifically, I have a pin

    #ifdef TIMSK0 //Nano vs atTiny
    const byte  wavePin  = 5,
                waveBit  = B100000;
          byte *wavePort = &PORTD;
    #define NANO
    #else
    const byte  wavePin  = 0,
                waveBit  = PB1;
          byte *wavePort = &PORTB;
    #endif

Notice the pointer? It works, but I have the impression this may not be the most efficient option, as it adds an operation (by looking up the reference). I have also planned to do constantly check which chip we are loading it in this fashion

    #ifdef NANO
      PORTD
    #else
      PORTB
    #endif
      |=   waveBit *  waveOn);
    #ifdef NANO
      PORTD
    #else
      PORTB
    #endif
      &= ~(waveBit * !waveOn));

But again, while this may be perfectly fine in operations, it hurts the eyes and is rather repetitive.

Is there a way to create a direct access to a port?

title: Port manipulation: Coding for two chips

Answers: 0


body:
I have written a code that detects an incoming pulse (square) of 7.875 kHz to trigger the output High for the entire duration of pulse, and trigger the output low if the pulse is off or not detected.

**CODE**

    // Define pins
    volatile int pulse1 = 2;    //incoming pulse 1 on pin 2

    const int ledPin = 13;   //output to trigger LED

    void setup() {

      pinMode(pulse1, INPUT);

      pinMode(ledPin, OUTPUT);

      // Timer Setup

      TCCR1A = 0;               // set entire TCCR1A register to 0
      TCCR1B = 0;               // same for TCCR1B
      TCNT1  = 65282;           // initialize counter value
      TCCR1B |= (1<<CS10);      // set prescaler to 8 bit
      TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt

    }
    ISR(TIMER1_OVF_Vect){
      TCNT1 = 65282;
      attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV2, FALLING);
      }

    void loop() {
      attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV1, RISING);

    }

    // Interrupt routines

    void ISR_UV1(){
      digitalWrite(ledPin, HIGH);      // Send high signal
    }

    void ISR_UV2(){
      digitalWrite(ledPin, LOW);      // Send low signal
    }

Is it the correct approach, or am I doing it wrong. One last thing that is bothering me is, every time I connect a wire (not connected to anything) to the input pin 2, it sends a high signal, and keeps the signal high until the Arduino is reset.
The pulse is a square wave 50% duty cycle generated by a device. I dont need to measure it or count it. I am just using it as a trigger to send a HIGH signal when it occurs. So it stays on (occurs) for 25ms & turns off during which its freq. is 7.875MHz & then it is repeated by the device according to the device parameters. I am aware it is a very short pulse but for the purpose of project nothing else can be used as the trigger

Any help will be appreciated.

title: Detecting an incoming 7.875 kHz pulse to use as trigger

Answers: 2

body:
I don't think, that your current approach will work. The logic seems flawed to me (though I cannot know, how exactly this code is embedded in your actual code) and the frequency is that high, that it will be difficult for the microcontroller to do much between the different interrupt triggers.

I would suggest 2 different approaches, based on the actual needs:

1. You can build a demodulator, which just gives you a high value, when your signal is there, and a low one, if it is not. Here you would need extra components.

2. You could feed the signal into one of the timers as clock source. Then the timer counts the pulses (actually twice the pulses, since the timer increments on every edge, rising or falling). You can use the overflow interrupt to get the value out of it. Lets say you use Timer 1 for the signal and still have Timer 0 for doing the Arduino time stuff (`delay()`, `millis()`, `micros()`). Then you can write an ISR for the Timer1 overflow interrupt. In there you take the current time and subtract the time of the last interrupt. Then you get the time, that it took the timer to overflow. Since you know, how many pulses are needed to overflow the timer, you now know the average frequency. If it is in the needed range, you set a simple single byte flag variable (be sure to declare it as `volatile`). You can tune the time for the average for example with the prescaler.

    In your main code you can then check for the flag being set and do stuff accordingly. Reset the flag, if you have done stuff, and save a timestamp. Check in your main code, if a specific time has passed since your last timestamp. If yes, that means, that the signal is lost. There you can act accordingly

body:
So i figured out what the problem was, I had to detach interrupts in the interrupt routines not in my main code. So basically these changes:

    void loop() {
      digitalWrite(ledPin, LOW);
      attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV1, CHANGING);

    }

& in the Interrupt routines:

    digitalWrite(ledPin, HIGH);      // Send high or Low dpending on the routine
    detachInterrupt(digitalPinToInterrupt(pulse1));

& basically this works like a charm, & there are still issues with the timer, but that will be solved in my main code with another sensor.


body:
I am making a project where I need to communicate between two devices that are about 300-500 meters apart and might experience a lot of RF interference and obstacles. So I thought for initial testing the nRF24L01 modules will be good knowing that they are advertised at 500m. When I did a range test, I got only 10 meters and that too with no obstacles in between! This module seems to be the only choice I have so any suggestions on how to increase range will help immensely.

Stats:

nRF24L01+ module with PCB antennae and a socket adapter board.
I am using the nRFLite library and am transmitting at 2MBPS and have tried multiple channels!

title: nRF24L01 only getting 10 meters range!

Answers: 0


body:
I am facing issue in using 2 Serial communication device with Arduino uno. I am trying to use ESP8266, Neo 6M GPS module with Arduino UNO, but only one of device is working at a time. Is there any solution available to make this work? When I comment processGPS() and uncomment TCP related API and vice-versa then either of the device working. Any idea how we can make work both?

My code:

    // This is a demo example using a public http server for testing both GET and POST requests

    #include <Arduino.h>
    #include <LiteESP8266Client.h>
    #include "TinyGPS++.h"
    #include "SoftwareSerial.h"

    #define PACKET_MTU 500    // Standard network MTU is 500 bytes

    LiteESP8266 radio;

    const char ssid[] PROGMEM = "xyz";    //change it to your wifi SSID
    const char password[] PROGMEM = "xyz";    //change it to your wifi password
    const char host[] PROGMEM = "192.168.0.156";
    const int port = 8080;

    const char http_get_request[] PROGMEM = "GET /getLedStatus HTTP/1.1\r\n";
    const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
    const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
    const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
    const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
    const char http_content_length_header[] PROGMEM = "Content-Length: ";
    const char success[] PROGMEM = "success";
    const char failed[] PROGMEM = "failed";
    const char CRLF[] PROGMEM = "\r\n";
    const char error_data_null[] PROGMEM = "Error: data came back null.";
    const int ledPin=11;
    // Choose two Arduino pins to use for software serial
    int RXPin = 5;
    int TXPin = 4;

    int GPSBaud = 9600;

    // Create a TinyGPS++ object
    TinyGPSPlus gps;

    // Create a software serial port called "gpsSerial"
    SoftwareSerial gpsSerial(RXPin, TXPin);

    void setupStationMode() {
      Serial.print(F("Setup station mode... "));
      if (radio.set_station_mode()) {
        Serial.println(F("success"));
      } else {
        Serial.println(F("failed"));
      }
    }

    void joinAP() {
      Serial.print(F("Join AP "));
      Serial.print(F("... "));
      if (radio.connect_to_ap(ssid, password)) {
        Serial.println(F("Success"));
      } else {
        Serial.println(F("Failed"));
      }
    }

    boolean establishTcpConnect() {
      Serial.print(F("Establish TCP Connection... "));
      if (radio.connect_progmem(host, port)) {
        Serial.println(F("Success"));
        return true;
      } else {
        Serial.println(F("Failed"));
        return false;
      }
    }

    void readHttpPacketAndProcessLEDStatus() {
      char *data;
      while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
        if (data) {
          Serial.println(F("Response Received..."));
          Serial.println(data);
          if(strstr(data, "ON") != NULL) {
            digitalWrite(ledPin, HIGH);
          }else{
            digitalWrite(ledPin, LOW);
          }
          free(data);//Mandatory
        } else {
          Serial.println(error_data_null);
        }
      }
    }

    void httpGetLedStatus() {
      Serial.println(F("Sending GET request... "));
      radio.send_progmem(http_get_request);
      radio.send_progmem(http_useragent);
      radio.send_progmem(http_host);
      radio.send_progmem(http_close_connection);
    }
    void setupGPS(){
      // Start the software serial port at the GPS's default baud
      gpsSerial.begin(GPSBaud);
      Serial.println("GPS Start");//Just show to the monitor that the sketch has started
    }
    void setup() {
      delay(2000);
      pinMode(ledPin, OUTPUT);
      radio.begin(9600,2,3);
      Serial.begin(9600);
      while (!Serial) {};
      //setupStationMode();
      //joinAP();
      setupGPS();
    }
    void displayInfo()
    {
      if (gps.location.isValid())
      {
        Serial.print("Latitude: ");
        Serial.println(gps.location.lat(), 6);
        Serial.print("Longitude: ");
        Serial.println(gps.location.lng(), 6);
        Serial.print("Altitude: ");
        Serial.println(gps.altitude.meters());
        Serial.println("Speed MPH:");
        Serial.println(gps.speed.mph());
      }
      else
      {
        Serial.println("Location: Not Available");
      }

      Serial.print("Date: ");
      if (gps.date.isValid())
      {
        Serial.print(gps.date.month());
        Serial.print("/");
        Serial.print(gps.date.day());
        Serial.print("/");
        Serial.println(gps.date.year());
      }
      else
      {
        Serial.println("Not Available");
      }

      Serial.print("Time: ");
      if (gps.time.isValid())
      {
        if (gps.time.hour() < 10) Serial.print(F("0"));
        Serial.print(gps.time.hour());
        Serial.print(":");
        if (gps.time.minute() < 10) Serial.print(F("0"));
        Serial.print(gps.time.minute());
        Serial.print(":");
        if (gps.time.second() < 10) Serial.print(F("0"));
        Serial.print(gps.time.second());
        Serial.print(".");
        if (gps.time.centisecond() < 10) Serial.print(F("0"));
        Serial.println(gps.time.centisecond());
      }
      else
      {
        Serial.println("Not Available");
      }

      Serial.println();
      Serial.println();
      delay(1000);
    }
    void processGps(){
       // This sketch displays information every time a new sentence is correctly encoded.
      if (gpsSerial.available() > 0)
        if (gps.encode(gpsSerial.read()))
          displayInfo();
    }
    void loop() {
      /*if(establishTcpConnect()){
        httpGetLedStatus();
        readHttpPacketAndProcessLEDStatus();
      }*/
      processGps();
      }

title: Arduino ESP8266 GPS integration issue

Answers: 1

body:
As mentioned by StarCat and romkey, SoftwareSerial only allows one connection at a time.

There are two potential solutions to this in my opinion, but each requires some new hardware.

### Solution 1 - Replace Arduino Uno with an STM32 Blue Pill
STM32 Blue Pill has more than one hardware serial interfaces, so that you don't even need the SoftwareSerial, in fact, the `LiteESP8266Client.h` will auto detect if a STM32 is used or an AVR-based Arduino is used to decide whether to use `HardwareSerial` or `SoftwareSerial`, see [here](https://github.com/e-tinkers/LiteESP8266Client/blob/master/src/LiteESP8266Client.h#L30-L49).

Pros:
- Minimum code change. You be able to use what you have written so far and continue to use ESP-01 as a WiFi-shield;

Cons:
- A little bit extra works to setup STM32duino Core for Arduino and requires either a SWDI programmer or USB-serial programmer.

Read [this](https://www.e-tinkers.com/2020/01/getting-started-with-stm32-and-things-you-need-to-be-aware-of/) for getting started with STM32 and the things need to be aware of.

### Solution 2 - Replace both Arduino Uno and ESP-01 with an ESP8266 Dev Board
Instead of using an ESP-01 as a WiFi shield,  get an ESP12-based development board as an Arduino to replace both the Arduino Uno and ESP-01. In this case, you run Arduino sketch directly on the board and replace the AT firmware with Arduino bootloader.

Pros:
- Integrated Arduino Uno with ESP wireless functionality into one hardware.

Cons:
- Need complete re-write of your application.

[ESP8266 Arduino github](https://github.com/esp8266/Arduino) should have sufficient information for getting started.


body:
Currently, I've worked on code for controlling stepper motor with pushbuttons. So, basically, I have to press two push button to run forward and backwards.
but the problem is when I press the 1st pushbutton it detects that pushbutton and run motor CW or CCW,  That means it cannot detect the press of another pushbutton to make it counterclockwise.

I realize that the program isn't detecting the second push button after pressing 1st one.
Tried different options to make it work. but failed.

any suggestions?

Here's my code for reference:-

```

#include <AccelStepper.h>

const int button1Pin = A2 ;
const int button2Pin = A1;

int button1State = 0;
int button2State = 0;

boolean flag1 = 0;
boolean flag2 = 0;

AccelStepper stepper = AccelStepper(1, 8, 9);
void setup()
{
   pinMode(button1Pin, INPUT);
   pinMode(button2Pin, INPUT);

   Serial.begin(9600);
}

void loop()
{

      int sensorReading = analogRead(A0);
      int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
      button1State = digitalRead(button1Pin);
      button2State = digitalRead(button2Pin);

     stepper.setMaxSpeed(2000);
     stepper.setSpeed(motorSpeed);

     if (button1State == HIGH)
       {

        stepper.setSpeed(motorSpeed);
        Serial.print("ok");
        stepper.runSpeed();

       }

  if (button2State == HIGH)
       {

        Serial.print("ok2");
        stepper.setSpeed(-motorSpeed);
        stepper.runSpeed();

      }
}
```

Another problem is in this current code, it cannot detect the potentiometer input inside the if ( button state ) {} loop.

it would be a great help pointing out my mistakes.

title: Continuous push button detection in for Stepper control

Answers: 1

body:
I implemented your code here on a UNO using 2 pushbuttons (with the stepper motor functions commented out) and it seems to work fine.  When I press button1 I get a lot of "ok" printouts for as long as the button is held down. When I press button2, the same thing happens except with "ok2" instead of "ok".

Here's the code I used:

    /*
        Name:       TwoPushButtonTest.ino
        Created: 9/28/2020 2:36:07 PM
        Author:     FRANKNEWXPS15\Frank
    */

    //#include <AccelStepper.h>

    const int button1Pin = A2;
    const int button2Pin = A1;

    int button1State = 0;
    int button2State = 0;

    boolean flag1 = 0;
    boolean flag2 = 0;

    //AccelStepper stepper = AccelStepper(1, 8, 9);
    void setup()
    {
      pinMode(button1Pin, INPUT);
      pinMode(button2Pin, INPUT);

      Serial.begin(115200);
    }

    void loop()
    {

      //int sensorReading = analogRead(A0);
      //int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
      button1State = digitalRead(button1Pin);
      button2State = digitalRead(button2Pin);

      //stepper.setMaxSpeed(2000);
      //stepper.setSpeed(motorSpeed);

      if (button1State == HIGH)
      {

        Serial.print("ok");
        //stepper.setSpeed(motorSpeed);
        //stepper.runSpeed();

      }

      if (button2State == HIGH)
      {

        Serial.print("ok2");
        //stepper.setSpeed(-motorSpeed);
        //stepper.runSpeed();

      }
    }

and here's the wiring diagram:

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

Note the two 10K pull-down resistors.  If these are not present, then the A2/A3 inputs are indeterminate whenever the buttons are in the 'disconnected' state, and anything can happen.

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


body:
After reviewing similar topics I've decided to ask this question below in the Security Stackexchange forum about 11 days ago.
https://security.stackexchange.com/questions/235423/is-arduino-mega-hackable-over-the-air

*No one gave an answer yet, perhaps I was wrong about the medium that's why I am also posting the question here.*

I am collecting data (by reading input registers) from a machine by RS-485 protocol and Arduino Mega 2560 hardware.

I am also sending this data from Arduino Mega to a NodeMCU which is connected to the internet over WiFi.

I made 100% sure that no physical interference can be performed on the hardware I setup.

But since this machine, I collect data from is controllable (by writing holding registers) over RS-485 (I've tested it) I have to make sure that Arduino's software cannot be changed/re-programmed/flashed over the air by someone.

There is no other device than NodeMCU which is open to the Internet and can be the source of vulnerability. And the only physical connections between Arduino & NodeMCU ar TX3+RX3 pins and power+ground pins.

I do not really care if the data or WiFi password or cloud server credentials are stolen. The only thing I care about is that Arduino is not flashed over the air which can ultimately damage the machine I am taking data from. Do you think this setup is safe regarding the information I present to you?

title: Is Arduino Mega Hackable Over The Air

Answers: 1

body:
1. the bootloader doens't listen on RX/TX3.
2. to start the bootloader reset is required
3. to communicate with the bootloader a serial programmer must have STK500 protocol or a telnet bridge for avrdude, which your NodeMCU sketch doesn't have

If your NodeMCU sketch has OTA, then the sketch could be updated to an avrdude telnet bridge. then reset would be needed to activate the bootloader. If your NodeMCU doesn't have a wire to Mega reset pin or you don't have a command in your Mega sketch to activate the reset, some serial overload of your Mega sketch could be a way.

But all this doesn't have an effect because the bootloader only listens at RX0


body:
As a hobbyist I code in a variety of arduino's and in Digispark's (Attiny 85 and 167).

But I'm doing a project with space contraints, so I'd need to use just the MCU directly over my pcb.

Apart from a voltage regulator (to get the VIn to 5V or 3.3V) do I need extra components to mount the MCU to my PCB?

DO I need crystals, capacitors, etc? Or the MCUs (mostly AtMega 32u4 and Attiny85 and Attiny167) have it all what's needed inside them?

I'll program the MCU before soldering on to the PCB, so there's no need for USB or programming stuff or leds.

Thanks!

title: Is extra hardware and components needed to connect the bare MCU directly to a PCB, without a shield?

Answers: 1

body:
> DO I need crystals, capacitors, etc? Or the MCUs (mostly AtMega 32u4 and Attiny85 and Attiny167) have it all what's needed inside them?

You don't need a crystal if you use the internal clock of the MCU (which means setting the fuses right and compiling your code to expect the right clock frequency). However if you are using a direct USB interface (such as for the ATMega32U4) then you will need a crystal as the precise timing is required for USB to operate.

You will need capacitors. Decoupling capacitors on all the power pins are not optional and must be included.

You will need a pullup resistor on the RESET pin unless you have set the fuse to disable the RESET pin (not advisable since it will prevent ICSP programming in the future - but can be useful for low pin-count chips).


body:
Hy,
Here I using 10 DS2413 to control gpios, it works very well with arduino ,I read the 10 ic address and store it in a 2D array, I want to control the individual IC using their address .Here all works well. My problem is the Ic address are not store in arrange wise manner. For ex, I have 10 IC's, Each IC's have unique address, The address of first IC1 is store in arr1, address of ic2 is arr2 and address of ic3 is store in arr3..... what i need is If i Swap the IC1 and IC2 the address of IC2 is store in arr1 and IC1 address is store in arr2.

title: DS2413 One Wire IC read and store the addresses of individual IC's

Answers: 1

body:
The OneWire system has no concept of the arrangement of the bus. All it knows is the addresses, and it always searches for those addresses in a pre-defined order.

No matter what arrangement you have on the bus the devices will always be found in the same order.

You can think of it akin to a teacher taking the register in class. They call out the names in alphabetical order and the pupils answer (if they are there). All it tells the teacher is who is there and who isn't. It doesn't give them any information about where in the class the pupil is sat.

You can read more about how the address searching is done [here](https://www.maximintegrated.com/en/design/technical-documents/app-notes/1/187.html).


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

Okay, so I am making a jewelry box for my niece that will spin a necklace holder with a stepper motor, play an audio file and turn on LED lights. I am using an Arduino MEGA 2560.

The flow is this:

1. **ringDoor open and necklaceDoor closed:** LED on, stepper spin, audio plays.
1. **ringDoor closed and necklaceDoor open:** LED on and audio plays, no stepper
motor.
1. **Both doors closed:** Everything off or off after delay.
1. **Both doors open:** LED on and music plays, no stepper motor.

My issue is that with the doorLatch open, the audio plays as it should. No issues, but if I only open doorLatch2, no audio plays. If I open doorLatch and then doorLatch2, audio will play. If I open in reverse, no audio will play. I have tried adding an `if` statement by itself with an "or" in the loop section to check for either door open and I cannot put it in the setup section because that just continuously plays with latches open or closed. I currently have it to where music plays with doorLatch open. The extremely strange portion to me is that if I put the tmrpcm.play in the first else statement, the audio will play after opening and closing doorLatch2.

So what I would like is for audio to play and loop as long as either door is open. PLEASE HELP! WHAT AM I DOING WRONG?!?!?!?!?!

Code:

    #include <SD.h>
    #include <TMRpcm.h>
    TMRpcm tmrpcm;

    #include <Stepper.h>
    const int stepsPerRevolution = 2048;
    const int doorLatch=2;   //Ring door
    const int doorLatch2=6;  //Necklace door
    const int relayPower=13; //Turn relay on

    Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

    void setup() {
      Serial.begin(9600);
      Serial.print("\nInitializing SD card...");

      // set this to your card type and cs pin
      if (!SD.begin(53)) {
        Serial.println("failed!");
        return;
      }
      Serial.println("done.");

      tmrpcm.speakerPin = 46;

      myStepper.setSpeed(5);
      pinMode(doorLatch,INPUT);
      pinMode(doorLatch2,INPUT);
      pinMode(relayPower,OUTPUT);
      digitalWrite(doorLatch,HIGH);
      digitalWrite(doorLatch2,HIGH);

    }

    void loop() {

      if ((digitalRead(doorLatch)==HIGH)&&(digitalRead(doorLatch2)==HIGH)) {
        //ring door and necklace door is closed
        digitalWrite(relayPower,LOW);

      }
      else {
        //ring door is open, lights on, stepper motor spinning, music playing
        digitalWrite(relayPower,HIGH);

      }

      if ((digitalRead(doorLatch2)==HIGH)&&(digitalRead(doorLatch)==LOW)) {
        //ring door open and necklace door closed

        digitalWrite(relayPower,HIGH);

        myStepper.step(stepsPerRevolution);
        delay(500);
        myStepper.step(-stepsPerRevolution);
        delay(500);

      }
      else {
        tmrpcm.play("music.wav");
      }
    }
****NEW CODE, NEW PROBLEM, but closer******Updated names and notes for easier following*****
New problem is if I open the necklaceDoor first, nothing happens. I have to open the ringDoor first. That turns everything on. Then with the necklaceDoor open, the stepper motor will turn off and the lights and music will continue to play. But I want to be able to open the necklaceDoor first and play the music with the lights. I do not want it to matter which one is opened first. I also realized that if I can get an or statement to work within an and statement I could do away with the fourth if statement completely. Both ringDoor open and necklaceDoor open, as well as ringDoor closed and necklaceDoor open have the same outcome.
Now if I switch the door states in the third if statement, I get necklaceDoor only plays audio after closed(original problem) but if both doors are open and then ringDoor is closed, the music will shut off after the stepper timer is done and then start again after necklaceDoor is closed?!?!?!?

    #include <SD.h>
    #include <TMRpcm.h>
    #include <Stepper.h>
    TMRpcm tmrpcm;

    const int stepsPerRevolution = 2048;   //Number of pulses per revolution
    const int ringDoor=2;                  //Ring door
    const int necklaceDoor=7;              //Necklace door
    const int relayPower=22;               //Turn relay on

    Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

    void setup() {
      Serial.begin(9600);                         //Start connection with computer

      if (!SD.begin(53))                         //Chip pin on card
      {
        Serial.println("failed!");                //SD card did not read
        return;
      }

      tmrpcm.speakerPin = 46;                      //Speaker output pin
      myStepper.setSpeed(5);                       //Stepper speed
      pinMode(ringDoor,INPUT);                     //Check state of ring door magnetic switch, NO
      pinMode(necklaceDoor,INPUT);                 //Check state of necklace door magnetic switch, NO
      pinMode(relayPower,OUTPUT);                  //Relay enable for 12V LED
      digitalWrite(ringDoor,HIGH);                 //Make door closed read high on start up
      digitalWrite(necklaceDoor,HIGH);             //Make door closed read high on start up
      digitalWrite(relayPower,LOW);                //Make relay off on start up
    }

    void loop() {

      if ((digitalRead(ringDoor)==HIGH)&&(digitalRead(necklaceDoor)==HIGH))
      {                                                                                //ring door and necklace door is closed, everything is off
        digitalWrite(relayPower,LOW);
      }

      if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
      {                                                                                //ring door is open and necklace door is closed, lights on, stepper motor spinning, music playing
        digitalWrite(relayPower,HIGH);
        tmrpcm.play("music.wav");
        myStepper.step(stepsPerRevolution);
        delay(500);
        myStepper.step(-stepsPerRevolution);
        delay(500);
      }

      if ((digitalRead(ringDoor)==HIGH)&&(digitalRead(necklaceDoor)==LOW))
      {                                                                                //ring door closed and necklace door open, lights on, stepper motor off, music playing
        digitalWrite(relayPower,HIGH);
        tmrpcm.play("music.wav");
      }

      if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==LOW))
      {                                                                                //ring door and necklace door open, lights on, stepper motor off, music playing
        digitalWrite(relayPower,HIGH);
        tmrpcm.play("music.wav");
      }
    }

*****Please and thank you to any and all who help. It is greatly appreciated*****

title: Mega 2560 does not play audio file when I want. It plays when the first condition is met, but not the other

Answers: 1

body:
Your code doesn't match your desired output. You say you want to:

    doorLatch open and doorLatch2 closed: LED on, stepper spin, audio plays.
    doorLatch closed and doorLatch2: LED on and audio plays, no stepper motor.
    Both latches closed: Everything off or off after delay.
    Both latches open: LED on and music plays, no stepper motor.

Note that both latches open and and doorLatch closed  DoorLatch2 open result in the same state: LED on and audio plays, no stepper motor.

Your code says

    if doorLatch & doorLatch2 are both closed (high)

        relayPower = low (off)

    else

        relayPower = HIGH (on). This in ALL cases other than both latches HIGH

Next, a second if statement:

    if doorLatch2 == HIGH && doorLatch == LOW
         relayPower = HIGH (on)
         step motor back and forth
    else
         play sound

So you play the sound if doorlatch2 is low or doorLatch is high

You turn off the relay if doorLatch & doorLatch2 are both closed (high)

You turn on the relay if doorLatch is low or doorlatch2 is low.

    void loop() {
       int latchState digitalRead(doorLatch);
       int latch2state = digitalRead(doorLatch2);
       if (latchState = LOW && latch2Sate == HIGH) {        //0 - 1
          //turn on led
          //spin stepper
          //play audio
       } else if (latchState = HIGH && latch2Sate == LOW) { //1 - 0
          //Turn LED on
          //play audio
          //turn off stepper
       } else if (latchState = HIGH && latch2Sate == HIGH) {//1 - 1
         //turn everything off (after delay?)
       } else if (latchState = LOW && latch2Sate == LOW {   //0 - 0
         //LED on
         //play music
         //turn off stepper
       }
    }


body:
I have two boards, Uno and ESP32 and my goal is to send data from the Uno to the ESP. I made a voltage divider so my ESP doesn't get fried and I use the communication only in **ONE** way, strictly UNO -> ESP32. I use PIN 9 from my UNO to send data and RX2 (16) from my ESP to receive the data. How ever, I get errors and can't make it work.

This is my Uno code:

    #include <SoftwareSerial.h>

    SoftwareSerial softPort(-1, 9);

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

    void loop() {
    softPort.print("100");
    delay(2000);

    }

and my ESP code:

    #include <SoftwareSerial.h>

    #define RXD2 16
    #define TXD2 -1

    SoftwareSerial Serial2(RXD2, TXD2); // RX, TX

    void setup() {
    Serial.begin(115200);
    Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);

    }

    void loop() {
    Serial.println("Data received:");
    Serial.println(Serial2.read());
    delay(200);

    }
I'm getting an error that says

> no matching function for call to 'SoftwareSerial::begin(int, int, int, int)'

title: Uno - ESP32 SoftwareSerial communication won't work

Answers: 1

body:
On the ESP32 you would *never* use SoftwareSerial except under *exceptional* circumstances.

The ESP32 has three hardware UARTs that can be mapped to *any* pin combination on the board.

The general usage is:

```
HardwareSerial Serial2(1); // Use UART channel 1

void setup() {
    Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
}
```

UARTs are numbered 0-2 where 0 is pre-assigned to the TX/RX (USB connection) pins and is used for debugging and programming.  UARTs 1 and 2 are not normally assigned to anywhere and you can use them as you see fit.


body:
I'm trying to create a small battery powered alarm clock using an Arduino MKRZero and a generic SH1106-controlled, 128x64 pixel oled.

I started out just dumping all code into a single file named `Clock.ino`. As the code got bigger, I started to split out functionality into separate classes. This went fine for timekeeping and alarms, but when I tried to do the same for the display functionality, I ran into an issue.

Now I wanted to split out my display code into a separate class. The working code before the refactor looks a bit like this:

`Clock.ino`
-----------
```c++
//Display stuff
#include <U8x8lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);

void setup(void) {
  u8x8.begin();
}

void print_clock([...]) {
  [...]
  u8x8.setCursor(0,3);
  u8x8.print("23:59:59");
  [...]
}

void loop(void) {
  [...]

  // Main clock
  print_clock(clk.datetime);

  [...]
}
```

I tried to split it out like this:

`Clock.ino`
-----------
```c++
#include "Display.h"

Display disp;

void setup(void) {}

void loop(void) {
  [...]

  // Main clock
  disp.print_clock([...]);

  [...]
}
```

`Display.cpp`
-------------
```c++
#include "Display.h"

Display::Display() {
  this->u8x8.begin();
}

void Display::print_clock([...]) {
  [...]
  this->u8x8.setCursor(0,3);
  this->u8x8.print("23:59:59");
  [...]
}
```

`Display.h`
-----------
```C++
//Display stuff
#include <U8x8lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif

class Display {
  public:
    Display();
    void print_clock([...]);
  private:
    U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
}
```

That didn't work, gave me a whole list of errors, all similar to these:

```
  5 In file included from /home/simon/Arduino/libraries/U8g2/src/U8x8lib.h:45:0,
  6                  from sketch/Display.h:9,
  7                  from sketch/Display.cpp:1:
  8 /home/simon/Arduino/libraries/U8g2/src/clib/u8x8.h:323:23: error: expected identifier before numeric c    \>onstant
  9  #define U8X8_PIN_NONE 255
 10                        ^
 11 sketch/Display.h:26:55: note: in expansion of macro 'U8X8_PIN_NONE'
 12      U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
 13                                                        ^~~~~~~~~~~~~
 14 /home/simon/Arduino/libraries/U8g2/src/clib/u8x8.h:323:23: error: expected ',' or '...' before numeric    \> constant
 15  #define U8X8_PIN_NONE 255
 16                        ^
 17 sketch/Display.h:26:55: note: in expansion of macro 'U8X8_PIN_NONE'
 18      U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
 19                                                        ^~~~~~~~~~~~~
 20 sketch/Display.cpp: In constructor 'Display::Display()':
 21 Display.cpp:8:9: error: invalid use of member function 'U8X8_SH1106_128X64_NONAME_HW_I2C Display::u8x8    \>(int)' (did you forget the '()' ?)
 22    this->u8x8.begin();
 23    ~~~~~~^~~~
```

So I tried rewriting it in such a way that the `u8xu` var is global like it was before, defining it in `Display.cpp` and getting rid of the `this->` before the `u8x8.` method calls in the `Display::` methods. That didn't work either. It compiles, but my display stays blank and the arduino gets stuck (does not interface with serial anymore until I hard-reset it).

At some point I rewrote the code such that I passes on the variable to the Constructur for `Display`, but I think I completely botched that as I couldn't get it to compile.

so, main question: **how do I instantiate an object inside my class, so it becomes available as a private variable?**

If anyone wants to look at the full code, it's right here:
https://github.com/ffective/wake-up/tree/master/Clock

The latest commit is the way of splitting up I described last: using a global variable. The previous commit is the working code with all Display methods just globally in `Clock.ino`. Unfortunately I didn't save my attempts for putting it as a private variable.

title: How to properly put a u8g2 handle in a class

Answers: 2

body:
You need to create a "blank" object in your class and then instantiate it in your constructor initializer list:

```
class Display {
    private:
        U8X8_SH1106_128X64_NONAME_HW_I2C u8x8;

    public:
        Display() : u8x8(U8X8_PIN_NONE) {}
        void print_clock([...]);
};
```

The object in `private` is not instantiated until the constructor is called by the calling of the `Display()` constructor.

From then on you can use `u8x8.whatever()` as you would normally.

body:
First errors aren't much helpful, but the last one about member function explains it all. You are not creating member variable of that type, you are trying to create member function (with invalid parameter list) that returns `U8X8_SH1106_128X64_NONAME_HW_I2C` value.

This code is perfectly valid:

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

    class Display {
      public:
        Display() { u8x8.begin(); }

        // you can also use different initializer for u8x8 object (default one is never executed in this case):
        Display(uint8_t resetPin) : u8x8{resetPin} { u8x8.begin(); }

      private:
        U8X8_SH1106_128X64_NONAME_HW_I2C u8x8 { U8X8_PIN_NONE };
    };

and in the sketch:

    // creating instance:
    Display disp{ 5 };

    // or with default constructor and reset pin value
    Display disp2;


body:
I am trying to write a function to store the date and time data from an RTC module. I have used char arrays to implement the function. I get "*declaration of 'varDay' as array of references*" error upon compilation.

I am still learning about char arrays and manipulating them so may be I am making a very obvious mistake. Could you please explain what I am doing wrong?

    #include <RTClib.h>

    RTC_DS3231 rtc;

    void setup() {
      Serial.begin(115200);
    #ifndef ESP8266
      while (!Serial); // wait for serial port to connect. Needed for native USB
    #endif

      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        Serial.flush();
        abort();
      }

      if (rtc.lostPower()) {
        Serial.println("RTC lost power, let's set the time!");
        // When time needs to be set on a new device, or after a power loss, the
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
      }

    }

    void loop() {
      unsigned long newTime = millis();
      static unsigned long oldTime = 0;

      char varYear [] = "1234";
      char varMonth [] = "00";
      char varDay [] = "00";
      char varHour [] = "00";
      char varMinute [] = "00";
      char varSecond [] = "00";
      unsigned int varEpoch;
      char varDate [] = "123456789";
      char varTime [] = "12345678";
      char dash [] = "-";
      char colon [] = ":";

      if (newTime - oldTime >= 60000) {
        oldTime = newTime;

        getDate(varDay, varMonth, varYear, varDate, dash, colon);
      }

    }
    void getDate (char &varDay[3], char &varMonth[3], char &varYear[5], char &varDate[11], char &dash[2], char &colon[2]) {

      DateTime now = rtc.now();
      strcpy (varDay, now.day());
      strcpy (varMonth, now.month());
      strcpy (varYear, now.year());

      strcat (varDate, varDay) ;
      strcat (varDate, dash);
      strcat (varDate, varMonth);
      strcat (varDate, dash);
      strcat (varDate, varYear)

      Serial.println(varDate);
    }

title: declaration of 'varDay' as array of references error

Answers: 1

body:
`char &varDay[3]` is an array of 3 references to type char, not a reference to type char of size 3.

Instead just pass a pointer:

```
void getDate (char *varDay, char *varMonth, char *varYear, char *varDate, char *dash[2], char *colon[2]) {
```

Also:

```
strcpy (varDay, now.day());
strcpy (varMonth, now.month());
strcpy (varYear, now.year());
```

That won't work. You can't copy a number into a string. now.day() etc need converting to a string first.

It would be better to format your string with snprintf:

```
snprintf(varDate, 11, "d-d-d", now.day(), now.month(), now.year());
```


body:
I am building my own board with integrated pressure sensor.
(microcontroller is 3V3 logic)

I want to know which parts do i need. In datasheet there are only 2 capacitors but on breakout board there are also 4 resistors.

Also in datasheet are 2 100 nF capacitors and on breakout board are 1uF and 0,1uF.

schematics from datasheet:
[![enter image description here][1]][1]

breakout board schematics:

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

  [1]: https://i.stack.imgur.com/OVdBW.png
  [2]: https://i.stack.imgur.com/IXFyK.png

title: Connecting BMP280 sensor to microcontroller

Answers: 1

body:
The capacitors are just decoupling capacitors. The value is not that critical. 100nF are good values to use.  On the breakout they have used just one pair of decoupling capacitors but use that pair for both power pins. The datasheet has one decoupling capacitor for each pin. You can do it either way. Personally I'd do it the datasheet way, but for a small board it really doesn't make much difference.

The resistors are a different matter. The BMP280 can work in a number of communication modes, and which mode you have it in dictates what resistors are needed.

R1 is used to place it into I2C mode. R4 is used to set the I2C address. R2 and R3 are the pullup resistors on the I2C bus. They aren't really part of the BMP280 circuit, but part of any I2C circuit in general.

R1 and R4 could be replaced by direct connections to VCC and GND respectively, but by having resistors gives you the ability to override them and use SPI instead of I2C should you wish it.


body:
I have created a curcuit which reads the analog pin 3 auf the arduino nano and does other things dependant on the returned value. However I have problems regarding the analogRead() function. Whenever I use a piece of wire to short the "Analog_UpDownHorn_Signal" and do it fast paced so that the arduino reads 0V and 5V repeatedly the serial communication stops. Sometimes it resumes. Sometimes it doesn't and when it does the value is always 1023.

I have managed to reduce the problem to the following 2 lines of code, which leads me to believe its my curcuit or a bug in the functions used. Before the arduino gets stuck it sometimes puts out random '?' or other wierd characters on the serial monitor.

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

void loop()
{
  Serial.println(analogRead(A3));
}
```

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

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

title: printing the analogRead() functions result crashes Arduino

Answers: 2

body:
The capacitor you have is rather large on the Analogue input, normally at this position it would be for debounce. Try something in the range of 100nF. Another idea would be to increase R8 to 10k.

[https://www.g7smy.co.uk/2015/09/multiple-buttons-on-one-pin-with-an-arduino/][1]

  [1]: https://www.g7smy.co.uk/2015/09/multiple-buttons-on-one-pin-with-an-arduino/

body:
I have fixed the issue by connecting the two grounds on the opposite site of the arduino nano with a thick solder connection on the bottom side of my perfboard. Seems like it really had to do with the big capacitance an the rapid discharge when shorting it to ground.

Maybe it had a "charge pump" like effect  with decoupling cap and the debouncing cap, because those are on the same side of the board.

To further avoid this problem i will not short the cap an discharge it through a low ohm resistor. Furthermore i could lower the capacitance as it was stated before and up the resistor values.


body:
LE: I'm almost certain that the problem is noise from the DC motor. I tried with a spare motor laying around and it had no problem, even if it had no capacitor on it's leads. So I tried adding all kinds of capacitors on the present motors, no improvement. I guess I'll search for another wireless solution.

So I want to build a remote controlled car using a cheap 433MhZ receiver and [transmitter][1]. I am using [this][2] motor driver. I send the values from the joystick to the receiver and based on that I control the motor's direction. The problem is that when I use PWM (or digitalWrite) the receive data code completely freezes (my guess is receiver fault). Other code in the program works so the only problem is in the communication department. I don't think it's a software problem because when I pull out the PWM pin to the motor driver, code starts running again.
I tried with another driver (TB6612FNG), I tried another receiver, I tried another library for 433MhZ (VirtualWire), I tried using SoftPWM library, I tried using a 220 Ohm resistor in series with the PWM signal, nothing works. I put a LED on the PWM pin, no problem.

I'm using two 3.7V lithium batteries as power. The receiver gets 5V directly from arduino. I also tried using a voltage divider to power the receiver directly from the batteries.

Here's the code, it's the last version that uses RCSwitch library for comms, I send the values from the joystick as 8 byte, read the respective bits and based on them I control the motors. Now it has a workaround that if the receive code is not in use, after a period it stops the motors, gets the data, starts motors again, but this is not acceptable.

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

bool up1, down1;
byte recData;

int AIN1 = 10;
int AIN2 = 9;
int BIN1 = 5;
int BIN2 = 6;
unsigned long resetTime;
unsigned long period = 3000;

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
    pinMode(AIN1, OUTPUT);
    pinMode(BIN1, OUTPUT);
    pinMode(AIN2, OUTPUT);
    pinMode(BIN2, OUTPUT);
}

void loop() {
      resetTime++;
  if (mySwitch.available()) {
    recData = mySwitch.getReceivedValue();
    Serial.println("Received ");
    mySwitch.resetAvailable();
    resetTime = 0;
  }
  if (resetTime > period)
      recData = 0;
   up1 = bitRead(recData, 7);
   down1 = bitRead(recData, 6);
  /*Serial.print(currentMillis);
  Serial.print("  ");
  Serial.print(recData);
  Serial.print("  ");
  Serial.print(up1);
  Serial.print("  ");
  Serial.println(down1);*/
  if (up1) {
      analogWrite(AIN1, 255);
      analogWrite(AIN2, 0);
      analogWrite(BIN1, 255);
      analogWrite(BIN2, 0);
    }
    else if (down1) {
      analogWrite(AIN1, 0);
      analogWrite(AIN2, 255);
      analogWrite(BIN1, 0);
      analogWrite(BIN2, 255);
    }
    else {
      analogWrite(AIN1, 0);
      analogWrite(AIN2, 0);
      analogWrite(BIN1, 0);
      analogWrite(BIN2, 0);
    }

}

  [1]: https://www.banggood.com/SRX882-433MHz-Superheterodyne-Receiver-Module-Board-For-ASK-Transmitter-Module-p-1410507.html?utm_source=google&utm_medium=cpc_fashion&utm_content=lucas&utm_campaign=snew-ele-outdoor-all&ad_id=445748584540&gclid=Cj0KCQjwg8n5BRCdARIsALxKb95hI2zQdwbsVlx69RWm-t_pkxSXKX5wkOq8bubjJi03uwW1Emzr04oaAmcSEALw_wcB&cur_warehouse=CN
  [2]: https://www.banggood.com/Dual-Channel-L298N-DC-Motor-Driver-Board-PWM-Speed-Dual-H-Bridge-Stepper-Module-p-1162946.html?cur_warehouse=CN&rmmds=buy

title: RF433MhZ - PWM with a motor driver freezes the code

Answers: 0


body: I found https://wiki.dfrobot.com/Gravity__MOSFET_Power_Controller_SKU__DFR0457 this board for a non-Arduino project and it does not list the pinout of the JST-PH 2.0 header but it does show it connected to an Arduino so I was hoping people familiar with the Arduino could figure out based on that.

title: What's the pinout of the Gravity MOSFET power controller board?

Answers: 0


body:
I want to power my board using a 9v battery. I also want to power a component in my circuit from the same power source (9v battery) but ONLY when my board sends a signal (say from D1 pin).

What component allows me to restrict power this way? I don't want to activate the component through signal, but actually power it after the signal is sent.

title: What component do I need (power)

Answers: 0


body:
I wrote this code, but it doesn't work (what I want is that the program choose a random color and turn on or off an RGB led) I use transistors to turn the led strip on or off and analogWrite(pin, random(0, 255) doesn't work
```
int red = 11;
int green = 10;
int blue = 9;

int color = 1;
int stat = 1;

void setup() {
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
}

void loop() {
  color = random(1, 3);
  stat = random(0, 1);

  if (color == 1 and stat == 0) {
    digitalWrite(red, LOW);
  }

  if (color == 1 and stat == 1) {
    digitalWrite(red, HIGH);
  }

  if (color == 2 and stat == 0) {
    digitalWrite(green, LOW);
  }

  if (color == 2 and stat == 1) {
    digitalWrite(green, HIGH);
  }

  if (color == 3 and stat == 0) {
    digitalWrite(blue, LOW);
  }

  if (color == 3 and stat == 1) {
    digitalWrite(blue, HIGH);
  }

  delay(1000);

}
```

title: Why my code isn't working?

Answers: 1

body:
From Arduino reference: [random](https://www.arduino.cc/reference/en/language/functions/random-numbers/random/)

In short:

> **Syntax**
>
> random(max)
>
> random(min, max)
>
> **Parameters**
>
> min: lower bound of the random value, inclusive (optional).
>
> max: upper bound of the random value, exclusive.
>
> **Returns**
>
> A random number between min and max-1. Data type: long.

Basically your first random returns values {1,2} and second one is even better {0}


body:
I'm using a sim800C module and an Arduino Uno. I want the code to send back an SMS to a number which sends it the password. So, if the sim module receives 'abcd' I want it to send back an SMS, saying 'ok'. Where I'm stuck is actually storing the read SMS. Since I need to check the SMS with a pre-defined password, I need to store the SMS the module received somehow. Please help ? Here's the code so far:

    #include <SoftwareSerial.h>
    SoftwareSerial sim(10, 11);
    int _timeout;
    String _buffer;
    String number = "+000000000000"; //-> change with your number
    String incoming;

    void setup() {
      //delay(7000); //delay for 7 seconds to make sure the modules get the signal
      Serial.begin(9600);
      _buffer.reserve(50);
      Serial.println("System Started...");
      sim.begin(9600);
      delay(1000);
      Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
    }

    void loop() {
      char inChar[5];
      if (Serial.available() > 0)
        switch (Serial.read())
        {
          case 's':
            SendMessage();
            break;
          case 'r':
            RecieveMessage();
            break;
        }
    // this is where the sim module spits back the received SMS to the serial monitor. How do I store it ?
      if (sim.available() > 0) {
        Serial.write(sim.read());

      }
    }

    void SendMessage()
    {
      //Serial.println ("Sending Message");
      sim.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
      delay(1000);
      //Serial.println ("Set SMS Number");
      sim.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
      delay(1000);
      String SMS = "GPS-cordinates";
      sim.println(SMS);
      delay(100);
      sim.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
      _buffer = _readSerial();
    }

    void RecieveMessage()
    {
      Serial.println ("SIM800C Read an SMS");
      delay (1000);
      sim.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
      Serial.write ("Unread Message done");
    }

    String _readSerial() {
      _timeout = 0;
      while  (!sim.available() && _timeout < 12000  )
      {
        delay(13);
        _timeout++;
      }
      if (sim.available()) {
        return sim.readString();
      }
    }

title: Help with reading and storing data from sim module

Answers: 0


body:
I want to read the [TCD1304][1] linear CCD sensor with an ESP32 and I'm facing some problems. As a first "warm-up" and to get familiar with this sensor I tried to generate the sensors input signals using a timer interrupt and bitbanging, but soon I found out that the resulting signals were way to slow and I didn't get any useful readings.

The signals involved are:
  - SH (shift gate): determines the integration time
  - ICG (integration clear gate): used to transfer pixel values to the shift register
  - ΦM: (master clock): self-explanatory
  - OS: output signal

[![Timing chart of  the TCD1304][2]][2]

The timing of those signals seems to be quite critical (see diagram below) and need to be quite fast - supported master clock frequency ist 0.8-4MHz and an analog measurement has to be done after every 4th clock pulse (0.2-1MHz).

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

Right now I'm pretty lost and I believe that this task requires some progamming techniques that I'm not familiar with so far.

Basically, my question is:

**What is the best way to generate those signals and how do I read the ADC at that high sampling rate/accurate in timing?**

I have some ideas, but - as I said - I probably lack the required skills, so it's hard for me to decide which approach I should take:

1) Using a single timer and direct port manipulation:
This would be easy to implement, but my assumption is that the interrupts will fire much too frequently to handle the ISR (which would be more or less complex, even if I refactorize my current test code). Especially reading the ADC will take too much time, I guess.

2) using the ESP's I2S-ADC:
I have no experience with I2S. From what I understand it is good for reading the ADC with a high frequency, but it is typically used for periodic sampling. In my case I would need the readings to be aligned with the control signals and I don't know if that is possible/convenient with I2S-ADC.

3) using ADC-DMA:
@esben Rossel has a done great work providing a framwork for STM32s and the TCD1304 in which he uses DMA for readout. I have never used direct memory access, but I feel this is a promising approach. Unfortunately, the [documentation of the ADC][4] only covers the ADC-RTC mode while there is no information about how to use the ADC-DMA mode. If DMA is the way to go I appreciate any hints on how I can get started with DMA programming on the ESP32.

In the latter cases 2) and 3) I would still need to generate the driving pulses in a "CPU-friendly" manner, probably hardware PWM (?), while the analog reading has to be triggered at every fourth clock pulse.

**Would I use one timer for each signal and if yes, how would I ensure that the signals have the correct phase offset? Also, how can I trigger the analog measurement after every 4th clock pulse?**

[1]: https://toshiba.semicon-storage.com/info/docget.jsp?did=13703&prodName=TCD1304DG
  [2]: https://i.stack.imgur.com/Oxc9h.png
  [3]: https://i.stack.imgur.com/PBy77.png
  [4]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html

title: Reading TCD1304 linear CCD Sensor

Answers: 0


body:
I would like to push two values at the same time (to the same node) from arduino to firebase. I tried to create an array and push the array to firebase, however, that is not working.

Here are the two values that I'm pushing, but I would like to push them to the same unique key:
```
temp1 = sensors.getTempCByIndex(0);
 StaticJsonBuffer<50> jsonBuffer;
JsonObject& timeStampObject = jsonBuffer.createObject();
timeStampObject[".sv"] = "timestamp";

Firebase.push("Sensors/20/temperatures/001", temp1);
Firebase.push("Sensors/20/temperatures/001", timeStampObject);
```
[How it should look like in Firebase][1]

Thanks in advance!

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

title: How to push two values to the same key from Arduino to Firebase

Answers: 1

body:
@hcheung thanks for your help! It solved the problem. This is my code now:

    StaticJsonBuffer<256> jsonBuffer;
    JsonArray& array = jsonBuffer.createArray();
    array.add(timeStampObject);
    array.add(temp1);
    Firebase.push("Sensors", array);


body:
Lately I've been struggling with Serial communication between Uno and ESP32. I'm trying to send a simple string (In my case "100") from my Uno to my ESP32. I made a voltage divider and I'm using `HardwareSerial Serial2(1)` for the Serial reading on the ESP32's side. On my Uno's side, I use Pin 9 for sending data a.k.a Pin 9 goes to the voltage divider and links with RX2 (GPIO16) on my ESP32, like in the picture below. [![picture][1]][1]

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

My Uno code is:

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

    void loop() {
    Serial.print("100");
    delay(2000);
    }

and on the other side, ESP32's code:

    #define RXD2 16
    #define TXD2 -1

    HardwareSerial Serial2(1); // Use UART channel 1

    void setup() {
    Serial.begin(9600);
    Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
    }

    void loop() {
    if(Serial2.available() >= 1){
    Serial.print(Serial2.read());
    }
    else {
    Serial.print("Not sending");
    }
    delay(2000);
    }
I'm not receiving the data and I get "Not sending" all the time.
My question is: Should I use TX pin from my Uno instead of pin 9? Or there's something wrong with my code?

Thank you in advance

title: Arduino UNO not sending serial data to ESP32

Answers: 0


body:
I am recieving SD card failuer and I did everything I could.

I use the correct SPI pins;

```
CS > 10
MOSI > 11
MISO > 12
SCK > 13
VCC > 5v
GND > GND
```

I did format my SD card to FAT32

I did write;

```
pinMode(csPin, OUTPUT);
digitalWrite(csPin, HIGH);
```

and I did add a blank file to sd card.

pls make harambe live ;-;

here is my code;

```arduino
#include <pcmConfig.h>
#include <pcmRF.h>
#include <TMRpcm.h>
#include <SD.h>
#define sd_pin 10
TMRpcm tmr;

int speaker_pin = 3;
int trig_pin = 8;
int echo_pin = 9;
int buzzer_pin = 6;
long cm;
long lecture_echo;

void setup()
{
  Serial.begin(9600);
  Serial.println("active");

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

  if(!SD.begin(sd_pin)){
    Serial.println("harambe is dead");
    return;
  }
  else{
    Serial.println("harambe is alive");
  }

  tmr.speakerPin = speaker_pin;

  pinMode(echo_pin, INPUT);
  digitalWrite(trig_pin, LOW);
  pinMode(trig_pin, OUTPUT);

  pinMode(buzzer_pin, OUTPUT);

}

void loop()
{
  digitalWrite(trig_pin, HIGH);
  delay(100);
  digitalWrite(trig_pin, LOW);

  lecture_echo = pulseIn(echo_pin, HIGH);
  cm = lecture_echo / 58;

  Serial.println(cm);
  delay(500);

  if(cm < 4)
    {

    }
  else
    {
      tmr.setVolume(5);
      tmr.play("test");
    }
}

```

title: Arduino SD card module failure

Answers: 0


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

    #include <ESP8266WiFi.h>
    const char *SSID = "mr_lazy_boei";
    const char *pass  = "usalusal";

    WiFiClient client;

    // Relay pin number
    int ignition=2;
    int self=0;

    //   Return RSSI(Received Signal Strength Indicator) or 0 if target SSID not found
    int32_t getRSSI(const char* target_ssid) {
     byte available_networks = WiFi.scanNetworks();

     for (int network = 0; network < available_networks; network++) {
       if (WiFi.SSID(network).compareTo(target_ssid) == 0) {     //stringOne.compareTo(stringTwo) < 0
         return WiFi.RSSI(network);
       }

     }
     return 0;
    }

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

     Serial.println("Connecting to ");
     Serial.println(SSID);

     WiFi.begin(SSID,pass);
     while(WiFi.status() !=WL_CONNECTED)
     {
       delay(500);
       Serial.print(".");
     }
     Serial.println("");
     Serial.println("WiFi connected");

    pinMode(ignition,OUTPUT);
    pinMode(self,OUTPUT);
    }

    void loop(){

    int32_t rssi = getRSSI(SSID);

     // For debugging purpose only
     Serial.print("Signal strength: ");
     Serial.print(rssi);
     Serial.println("dBm");

     if (rssi > (-55) && rssi != 0) // if rssi is greater then -55 dbm or it's 0 dbm, then the light will turn
     {
       digitalWrite(ignition, LOW);
       Serial.println("ON");
    }
    else

    {
     digitalWrite(ignition,HIGH);
     Serial.println("OFF");
    }
    if (rssi > (-55) &&rssi !=0)
    {
     digitalWrite(self,LOW);
     delay(750);
     digitalWrite(self,HIGH);
     Serial.println("SELF OFF");

    }

    }

Above is my code written. As you can see, I have two variables: `ignition` and `self`. `ignition` works the way I want, but the `self` variable turns on and and then off. That is correct. But it again turns on because of `void loop()`.

Let me explain further:

If wifi signal is strong the `ignition` should turn on and the `self` should turn on for less than a second and then turn off. It should not turn on again. When the signal goes weak the `ignition` turns off. Again, when signal gets strong the `ignition` turns on and I need `self` to turn on for not even a second and turn off.

I tried my best getting that. I tried moving it to `void setup()`, but that just works when I power up the device. After that it doesn't turn on or off. Please kindly help me. I know here I am having very talented brothers who would help me out on this issue.

title: Wifi strength Automation . Help. Noobie here

Answers: 1

body:
You need to design your program using a Finite State Machine.

First start off by defining each *state* that your program can be in, and what is allowed to happen in each of those states.

For example:

1. **IDLE**

The only thing that is allowed to happen here is detecting the RSSI and deciding whether or not to start the engine.

2. **IGNITION**

The RSSI has got strong enough and you want to start the car. The only thing you want to do is turn on the ignition and wait a moment. Nothing more.

3. **CRANK**

Once you've waited a moment you can crank the engine. That means turning on the starter motor and waiting a moment.

4. **RUNNING**

Now the engine has started you can release the starter motor and leave the engine to idle. It's now that you want to start watching the RSSI gain.

5. **STOP**

The RSSI has dropped below your threshold, so now you can stop the engine.

6. **IDLE**

Now the engine's stopped you can go back to the start and idle looking for the RSSI to get high enough again.

These are all the *states* of a *Finite State Machine*. You move from state to state depending on different *inputs* or *triggers*.  One input is your RSSI value - or more strictly your RSSI value being above or below a threshold.  Another input is (less obviously) time. Waiting for some time to pass.

So you start in state 1. In that state all your program is doing is watching the RSSI. When that rises you move to state 2. At that point it performs whatever actions are needed (turn on the ignition) and record the time. When enough time has elapsed you move on to state 3, and do the same.

It could actually be simplified by compressing states 2 and 3 together:

* Turn on ignition
* Delay
* Turn on starter motor
* Delay
* Turn off starter motor
* Delay
* Move to next state

You could then increase the complexity again a little (while increasing the safety) by adding extra steps when you're watching the RSSI. You can then check to see if the RSSI has been above (or below) the threshold for a certain amount of time before moving on to the next step:

1. IDLE - watching RSSI
   * If RSSI rises above threshold go to state 2.
   * Else stay in state 1
2. Record the time and keep watching the RSSI
   * If RSSI drops below threshold: Go back to 1.
   * If Enough time has passed: Go to state 3.
   * Else stay in state 2
3. Start the engine.
   * Go to state 4
4. RUNNING - watching RSSI
   * If RSSI falls below threshold go to state 5.
5. Record the time and keep watching the RSSI
   * If the RSSI rises above threshold: Go back to 4
   * If enough time has passed: go to state 6.
   * Else stay in state 5.
6. Stop the engine.
   * Go to state 1.

... etc ...


body: I've connected a strand of WS2811 to a 5V power supply and an Arduino Uno and no matter what I do the lights are always red. I'm using the fast led library and for some reason, the WS2811 lights are only red.

title: WS2811 lights only turn red

Answers: 1

body: I had this same issue, turns out I had 12v WS2811's. Changing power supply fixed it for me!


body:
I am using the NRF24L01 module to communicate between multiple Arduinos. For this example I will have a master transmiter (tx) Arduino and a salve receiver (rx) Arduino to illustrative better my problem.

**Master (Tx) code:**

    #include <nRF24L01.h>
    #include <RF24.h>
    #include <SPI.h>

    RF24 radio(9, 10); // NRF24L01 used SPI pins + Pin 9 and 10

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

     radio.begin();
     radio.openWritingPipe(27);
     radio.stopListening();
    }

    void loop() {
        char buf[32];
        buf[0] = 123;

        auto res = radio.write(buf, sizeof(buf));
        if (res) {
      Serial.println("worked");
     }
     else {
      Serial.println("** error **");
            delay(1000);
     }

        delay(700); // wait 700 ms

    }

**Slave (Rx) Code**

    #include <nRF24L01.h>
    #include <RF24.h>
    #include <SPI.h>

    RF24 radio(9, 10); // NRF24L01 used SPI pins + Pin 9 and 10

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

     radio.begin();
     radio.openReadingPipe(1, 27);
     radio.startListening();
    }

    void codeThatMakesMasterAckStopWorking()
    {
        // Code that will be changed
    }

    void loop() {

        if (radio.available()) {
           char buf[32];
           radio.read(buf, 32);
           Serial.println("received data");
           codeThatMakesMasterAckStopWorking();

        }

    }

If I execute this code it works great just as it is. The master (tx) always gets an acknowledgment every time it sends data. Also the range of the NRF24L01 works great. **The problem occurs when the slave sends data becoming a transmitter instead of a receiver**. In other words if I replace the method `codeThatMakesMasterAckStopWorking` with:

    void codeThatMakesMasterAckStopWorking()
    {
        radio.stopListening();
        radio.openWritingPipe(1234); // send to some other node that is not master
        char buf[32];
     radio.write(buf, 32);
     radio.startListening();
    }

The master (Tx) is able to send the data because the slave prints the message `"received data"` but without acknowledgment. The master keeps printing `** error **` even though the slave is receiving the data. I been doing a lot of tests and this are my findings:

    // does not work (master stops receiving acknowledgment and prints '** error **')
    void codeThatMakesMasterAckStopWorking()
    {
        radio.stopListening();
        delay(200);
     radio.startListening();
    }

    // works (master receives acknowledgment and prints 'worked')
    void codeThatMakesMasterAckStopWorking()
    {
        radio.stopListening();
        delay(10);
     radio.startListening();
    }

There are times when I want my slave arduino to stop listening and transmit a message to another arduino. When it sends a message to a different arduino the master does not receive an acknowledgment anymore even though the slave is listening again. Why could this be?

title: Using NRF24L01 as transmitter and receiver (transceiver)

Answers: 0


body:
I am working on a project which uses two 18650 3400ma batteries to power some sensors, an Arduino Mini Pro, an 433mhz RF transmitter and an ESP8266-01. Most of the time the Arduino is in sleep mode and I only wake it up to check sensors, send info to Wi-Fi, and if needed switch on RF transmitter.

On the original prototype I turn on the Arduino ever two hours. I then turn on a capacitive proximity sensor and I check the battery level once. I next turn on a potentiometer and temperature sensor for eight seconds while reading them then turn them off.

I then read the proximity sensor. Then I turn on the ESP8266-01 for eight seconds while I post all reading on line. Then off with the ESP.

Depending on the readings from the proximity sensor I turn on the RF transmitter for about one second and then turn off the proximity sensor and put the Arduino back to sleep.

I have made a second prototype in which the coding is the same except I check the battery 50 times in quick succession for a truer average reading. I check the potentiometer ten times for a better average reading and I only wake the Arduino up every six hours instead of two.

The schematic (I'm posting) is basically the same except I have added four small capacitors to smooth out the current. I will circle them in red. Wiring on the first prototype is with .5mm copper wire while on the second prototype the traces on the pcb are .25mm 1 oz copper and some of them have been redone with 28 gauge copper wire.

My problem is that the original prototype will last for seven days before needing to be recharged while the second prototype only makes it four days. Could the capacitors be making a difference, or the sampling of the battery and potentiometer, or is it the wiring size. Is there too much resistance?

If the wiring is the problem what is a good size to have my pcb traces be? Is 2.5mm at 1oz or 2oz enough?

I know there are things I can rewrite in my code to cut times when things are on and cut energy use but I want to know why such a difference in the two prototypes.

Does anyone have any suggestions or questions?
[![enter image description here][1]][1]

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

title: Battery depleting on second prototype

Answers: 0


body:
I have an ESP8266 module with a relay like this: https://aliexpress.com/item/4000348370586.html.
I have been able to control the module, I can deactivate and activate the relay by means of an http request, with the following code.

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>

    #ifndef STASSID
    #define STASSID "wifi_name"
    #define STAPSK  "wifi_password"
    #endif

    const char* ssid = STASSID;
    const char* password = STAPSK;

    ESP8266WebServer server(80);

    IPAddress ip(192, 168, 0, 101); //ESP static ip
    IPAddress gateway(192, 168, 0, 1);   //IP Address of your WiFi Router (Gateway)
    IPAddress subnet(255, 255, 255, 0);  //Subnet mask
    IPAddress dns(8, 8, 8, 8);  //DNS
    const char* deviceName = "ligth101";

    const int relayPin = 0;

    void handleOn() {
        digitalWrite(relayPin, LOW);
        setCrossOrigin();
        server.send(200, "text/plain", "Ligth on");
    }

    void handleOff() {
        digitalWrite(relayPin, HIGH);
        setCrossOrigin();
        server.send(200, "text/plain", "Ligth off");
    }

    void handlePing() {
        setCrossOrigin();
        server.send(200, "text/plain", "ligth");
    }

    void configPin(){
        pinMode(relayPin, OUTPUT);
        digitalWrite(relayPin, HIGH);
    }

    void configWifi(){
        WiFi.setAutoConnect(false);
        WiFi.disconnect();
        WiFi.hostname(deviceName);
        WiFi.config(ip, subnet, gateway, dns);
        WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        }
    }

    void setCrossOrigin(){
        server.sendHeader(F("Access-Control-Allow-Origin"), F("*"));
        server.sendHeader(F("Access-Control-Max-Age"), F("600"));
        server.sendHeader(F("Access-Control-Allow-Methods"), F("PUT,POST,GET,OPTIONS"));
        server.sendHeader(F("Access-Control-Allow-Headers"), F("*"));
    }

    void sendCrossOriginHeader(){
        setCrossOrigin();
        server.send(204);
    }

    void configServerPaths(){
        server.on(F("/ping"), HTTP_OPTIONS, sendCrossOriginHeader);
        server.on(F("/ping"), HTTP_GET, handlePing);

        server.on(F("/on"), HTTP_OPTIONS, sendCrossOriginHeader);
        server.on(F("/on"), HTTP_GET, handleOn);

        server.on(F("/off"), HTTP_OPTIONS, sendCrossOriginHeader);
        server.on(F("/off"), HTTP_GET, handleOff);

        server.begin();
    }

    void setup() {
        configPin();
        configWifi();
        configServerPaths();
    }

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

Now, I want to use the GPIO2 pin to also turn the relay on and off. The desired behavior is to change the state of the relay regardless of whether it comes from the button or from an http request.

I have tried the following modifications to the code:

    const int buttonPin = 2;
    int buttonState = 0;

    void configPin(){
        ...
        digitalWrite(buttonPin, LOW);
    }

    void handleButton(){
        buttonState=digitalRead(buttonPin);
        if(buttonState == HIGH) {
            digitalWrite( relayPin, !digitalRead(relayPin) );
            delay(1000);
        }
    }

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

With these modifications to the code, I have tested the following two modifications to the hardware:

 1. Placing a switch between ground and GPIO2. As a result of this, each time I activate the push-button, the relay remains intermittent, going from one state to the other infinitely.
 2. Placing a switch between ground and GPIO2, but adding a resistor between the switch and the GPIO2 pin, but this also does not work.

Is there a way to deactivate / activate the relay using GPIO2 with a push button and via http as well?

Thanks!

title: ESP8266 - ESP01S with relay. Toggling the relay with http (GPIO0) and GPIO2 at the same time

Answers: 1

body:
Contrary to esp-01, on the esp-01S io 0 and io 2 pins have a pull-up resistor.

Wire a button between io 2 and ground and you will read LOW if the button is pushed.

Use a state variable for the state of the relay, don't read back the pin (does it even work to read the state of an output pin with digitalRead on esp8266?).


body:
I'm new here, so I hope my question is not naive.
I'm using Arduino mega connected with a pulse sensor and a GPS (and other things that are not related to our problem), pulse sensor and GPS data are sent momentarily through HC-12 433 Mhz module to a receiver arduino uno that is only receiving data through HC-12 as well

for processing reasons, I send GPS data with a "G" prefix .. e.g "G11.00,7.45".
and pulse data consist of those three: "S100"
                                        "Q97"
                                        "B22"  // 100,97,22 are just examples, and each one is sent alone

for some reason, the receiver Arduino uno, is reading the data in it's ASCII decimal form and also separate it in a new line.

I can not use Serial.readString(), because it only print data after terminating the Serial communication and I need it momentarily, I tried to configure Serial.setTimeout() , but I couldn't manage to find a suitable time for all data.

please check my code and help me solve my problem, thank you
```
#include <Adafruit_GPS.h>
// what's the name of the hardware serial port?
#define GPSSerial Serial1
// Connect to the GPS on the hardware port
Adafruit_GPS GPS(&GPSSerial);

String gpsData="";
String pulseData="";
#include <SoftwareSerial.h>
SoftwareSerial mySerial(12, 13); // RX, TX  HC-12
uint32_t timer = millis();
void setup(){  // I think there is no problem here
  Serial.begin(115200);             // we agree to talk fast!
  mySerial.begin(115200);
  interruptSetup();   // initialize timers to read pulse sensor and GPS at fixed intervals
      GPS.begin(9600);
  delay(100);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  delay(100);
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_100_MILLIHERTZ);
  GPS.sendCommand(PGCMD_ANTENNA);
  delay(1000);
  GPSSerial.println(PMTK_Q_RELEASE);
}
void loop(){
 // that show me if there is a new data, you can skip it
 if (GPS.newNMEAreceived()) {
    // a tricky thing here is if we print the NMEA sentence, or data
    // we end up not listening and catching other sentences!
    // so be very wary if using OUTPUT_ALLDATA and trying to print out data
    GPS.lastNMEA(); // this also sets the newNMEAreceived() flag to false
    if (!GPS.parse(GPS.lastNMEA())) // this also sets the newNMEAreceived() flag to false
      return; // we can fail to parse a sentence in which case we should just wait for another
  }

  //
if (millis() - timer > 10000) { // send GPS data every 10 seconds
    timer = millis(); // reset the timer
    if (GPS.fix) {

      gpsData.concat('G');
      x=GPS.latitude/100;
      gpsData.concat(x);  // I also tried String(x)
      gpsData.concat(',');
      y=GPS.longitude/100;
      gpsData.concat(y);  // I also tried String(y)
      mySerial.println(gpsData);  // here I send GPS  data through HC-12 to the receiver Arduino uno
      gpsData=""; // reset
    }
}
  sendDataToProcessing('S', Signal);     // send Processing the raw Pulse Sensor data
  if (QS == true){                       // Quantified Self flag is true when arduino finds a heartbeat

        sendDataToProcessing('B',BPM);   // send heart rate with a 'B' prefix
        sendDataToProcessing('Q',IBI);   // send time between beats with a 'Q' prefix
        QS = false;                      // reset the Quantified Self flag for next time

  }
  delay(50);
}
void sendDataToProcessing(char symbol, int data ){
 // here I send pulse data through HC-12 to the receiver Arduino uno, and then process it using processing in the receiver arduino
    pulseData.concat(symbol);
    pulseData.concat(data);
    Serial.println(pulseData);  // just for debugging and it was okay
    mySerial.println(pulseData);
    pulseData=""; //reset
  }

interruptSetup() {
// no need to read it, it is just some timer 1 and timer 2 initialization and their ISR, timer 1 read pulse sensor every 2 milliseconds (yeah fast but I guess mega could handle it),and do some calculations to find S, Q, and B.
and timer 2 read GPS coming sentences.
}
```

the receiver code
```
void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);  //I will connect HC-12 directly to pin 0,1
}

void loop() {
  // put your main code here, to run repeatedly:
while(Serial.available() >1){
  String input = String (Serial.read());//read string , I need to cast it into String because data comes in ASCII
// I also tried int input = Serial.read() ; //same thing happened
    Serial.println(input);
}
}
```
waiting for your response.

###edit###
to conclude the problem is that I want to receive data in the uno
as it has been sent from the mega

e.g: I receive sI guess the ascii of the letter and the number also changes to some number
```
send  |  recive
S490  | 52
        53
Q252  | 10
        83
B160  | 48
        13
```

I used Serial.write(Serial.read()) instead of
Serial.println, and it worked, does someone know why?

title: HC-12 problem with reading momentarily strings

Answers: 0


body:
[![enter image description here][1]][1]Problem is if I open the necklaceDoor first, nothing happens. I have to open the ringDoor first. That turns everything on. Then with the necklaceDoor open, the stepper motor will turn off and the lights and music will continue to play. But I want to be able to open the necklaceDoor first and play the music with the lights. I do not want it to matter which one is opened first. I also realized that if I can get an or statement to work within an and statement I could do away with the fourth if statement completely. Both ringDoor open and necklaceDoor open, as well as ringDoor closed and necklaceDoor open have the same outcome. Now if I switch the door states in the third if statement, I get necklaceDoor only plays audio after closed(original problem) but if both doors are open and then ringDoor is closed, the music will shut off after the stepper timer is done and then start again after necklaceDoor is closed?!?!?!?

    #include <SD.h>
    #include <TMRpcm.h>
    #include <Stepper.h>
    TMRpcm tmrpcm;

    const int stepsPerRevolution = 2048;   //Number of pulses per revolution
    const int ringDoor=2;                  //Ring door
    const int necklaceDoor=7;              //Necklace door
    const int relayPower=22;               //Turn relay on

    Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

    void setup() {
      Serial.begin(9600);                         //Start connection with computer

      if (!SD.begin(53))                         //Chip pin on card
      {
        Serial.println("failed!");                //SD card did not read
        return;
      }

      tmrpcm.speakerPin = 46;                      //Speaker output pin
      myStepper.setSpeed(5);                       //Stepper speed
      pinMode(ringDoor,INPUT);                     //Check state of ring door magnetic switch, NO
      pinMode(necklaceDoor,INPUT);                 //Check state of necklace door magnetic switch, NO
      pinMode(relayPower,OUTPUT);                  //Relay enable for 12V LED
      digitalWrite(ringDoor,HIGH);                 //Make door closed read high on start up
      digitalWrite(necklaceDoor,HIGH);             //Make door closed read high on start up
      digitalWrite(relayPower,LOW);                //Make relay off on start up
    }

    void loop() {

      if ((digitalRead(ringDoor)==HIGH)&&(digitalRead(necklaceDoor)==HIGH))
      {                                                                                //ring door and necklace door is closed, everything is off
        digitalWrite(relayPower,LOW);
      }

      if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
      {                                                                                //ring door is open and necklace door is closed, lights on, stepper motor spinning, music playing
        digitalWrite(relayPower,HIGH);
        tmrpcm.play("music.wav");
        myStepper.step(stepsPerRevolution);
        delay(500);
        myStepper.step(-stepsPerRevolution);
        delay(500);
      }

      if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
      {                                                                                //ring door closed and necklace door open, lights on, stepper motor off, music playing
        digitalWrite(relayPower,HIGH);
        tmrpcm.play("music.wav");
      }

      if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==LOW))
      {                                                                                //ring door and necklace door open, lights on, stepper motor off, music playing
        digitalWrite(relayPower,HIGH);
        tmrpcm.play("music.wav");
      }
    }

Please and thank you to any and all who help. It is greatly appreciated.
Yes, I asked the the original question and the answer I received not only did not work, somehow neither latch worked anymore.

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

title: I cannot get my code to play music in a or manner. I have to open one switch then the other. Music should play with either door open

Answers: 1

body:
First of all, you have to find out how your magnetic switches work. Are they opened or closed if you attach a magnet to them? Do they behave the same or is one closed and the other opened if you attach a magnet?
Your code above is written for active LOW switches i.e. if the respective door is closed the switch is opened and therefore the logic level of the pin is HIGH. The level is LOW if the door is opened (activated; hence active LOW).

In order your code had a chance to work, the switches must be connect the right way: on one side connect them to GND and on the other side to the respective Arduino pin. If this is not the case, the code must be changed or the switches must be conneted the right way. You did not show us your schematic, so I can not check it for you.

Here is some code to try: But first find out if the switches you use are LOW or HIGH active. I also have no access to an IDE at the moment, so I can not try out the code. Take it as a hint on how to do it.

And one tip from a guy that does the job for 30 years now: Don't comment variables if their names say it all:

    //  this sort of comments makes the code unreadable --V
    const int ringDoor=2;                          //Ring door

I know it is a common behavior in the Arduino community, but don't write comments after a statement. In your code above I did realize that there are comment for the `if` statements only when I copied the code in my answer. Comments are only usefull if they say something new and can be read without problems.

    #include <SD.h>
    #include <TMRpcm.h>
    #include <Stepper.h>
    TMRpcm tmrpcm;

    const int stepsPerRevolution = 2048;
    const int ringDoor = 2;
    const int necklaceDoor = 7;
    const int relayPower = 22;

    Stepper myStepper = Stepper( stepsPerRevolution, 8, 10, 9, 11 );

    void setup()
    {
      Serial.begin( 9600 );
      if ( ! SD.begin( 53 ) )
      {
        Serial.println( "failed!" );
        return;
      }

      tmrpcm.speakerPin = 46;
      myStepper.setSpeed( 5 );
      pinMode( ringDoor, INPUT );
      pinMode( necklaceDoor, INPUT );
      pinMode( relayPower, OUTPUT );

      digitalWrite( ringDoor, HIGH );
      digitalWrite( necklaceDoor, HIGH );

      digitalWrite( relayPower, LOW );
    }

    void loop() {

      // the following code works if both switches are LOW active
      // (i.e. LOW if the door is open)
      // if the "ringDoor-switch is HIGH active change
      // digitalRead( ringDoor ) == LOW to
      // digitalRead( ringDoor ) == HIGH
      // if the "necklaceDoor-switch is HIGH active change
      // digitalRead( necklaceDoor ) == LOW to
      // digitalRead( necklaceDoor ) == HIGH
      // and
      // digitalRead( necklaceDoor ) == HIGH to
      // digitalRead( necklaceDoor ) == LOW

      if ( ( digitalRead( ringDoor )     == LOW ) ||
           ( digitalRead( necklaceDoor ) == LOW ) )
      {
        // one of the doors is open
        digitalWrite( relayPower, HIGH );
        tmrpcm.play( "music.wav" );
        if ( digitalRead( necklaceDoor ) == HIGH )
        {
          // only the ring door is opend
          myStepper.step( stepsPerRevolution );
          delay( 500 );
          myStepper.step( -stepsPerRevolution );
          delay( 500 );
        }
      }
      else
      {
        digitalWrite( relayPower, LOW );
      }
    }


body:
I have an Arduino Mega 2560 with an ESP8266 built into it, and a SIM900 shield, which I am building a project with.

The shield is powered by an external adjustable 3-12V, 2A supply set at 6V so power is not an issue.

I have managed to get serial to work, and can issue commands to the device. My issue is the following;

1) I fire up the shield.
2) Shield reports back CREG = 2 which means ME is looking for an operator to connect to.
3) Shield reports back CREG = 1 which means it has connected to an operator.
 - Running AT+COPS? returns my provider, as long as CREG = 1.
4) Seconds in, CREG = 4, which means Unknown.

I don't see why it keeps disconnecting me, I have gone through 4 different SIM cards and the problem persists.

Has anyone else had this problem and if you did, how did you manage to work around it?

```
17:29:25.000 -> NORMAL POWER DOWN
17:29:25.000 ->
17:29:25.000 -> +CREG: 3
17:29:27.993 -> ?????????? (SHIELD TURNS ON, GARBAGE OUTPUT)
17:29:29.520 -> RDY
17:29:29.520 ->
17:29:29.520 -> +CREG: 2
17:29:29.520 ->
17:29:29.520 -> +CREG: 0
17:29:29.520 ->
17:29:29.553 -> +CFUN: 1
17:29:29.553 ->
17:29:29.553 -> +CPIN: SIM PIN
17:29:33.506 -> AT+CPIN=1234
17:29:33.506 ->
17:29:33.506 -> OK
17:29:34.503 ->
17:29:34.503 -> +CREG: 2
17:29:36.528 -> AT+COPS?
17:29:36.528 ->
17:29:36.528 -> +COPS: 0
17:29:36.528 ->
17:29:36.528 -> OK
17:29:38.022 ->
17:29:38.022 -> Call Ready
17:29:39.550 -> AT+COPS?
17:29:39.550 ->
17:29:39.550 -> +COPS: 0
17:29:39.550 ->
17:29:39.550 -> OK
17:29:41.044 ->
17:29:41.044 -> +CREG: 1
17:29:42.572 -> AT+COPS?
17:29:42.572 ->
17:29:42.572 -> +COPS: 0,0,"CYTAMOBILE-VODAFONE"
17:29:42.572 ->
17:29:42.572 -> OK
17:29:44.565 -> AT+COPS?
17:29:44.565 ->
17:29:44.565 -> +COPS: 0,0,"CYTAMOBILE-VODAFONE"
17:29:44.598 ->
17:29:44.598 -> OK
17:29:47.587 -> AT+COPS?
17:29:47.587 ->
17:29:47.587 -> +COPS: 0,0,"CYTAMOBILE-VODAFONE"
17:29:47.620 ->
17:29:47.620 -> OK
17:29:49.580 ->
17:29:49.580 -> +CREG: 4
17:29:50.111 -> AT+COPS?
17:29:50.111 ->
17:29:50.111 -> +COPS: 0
17:29:50.111 ->
17:29:50.111 -> OK
```

title: SIM900 module connects then disconnects from carrier soon after

Answers: 0