message:
My ESP8266-01 doesn't want to respond to AT command after a successful flash!

Well hello, experts,
I've been trying to fix my issue all time, but all in vain.
I have an Esp8266-01 with 1MB memory. I've flashed it with an official AT firmware V2.0.0 of espressif with the help of this tutorial-arduino as a usb/TTL-: "https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now/", and it was a successful flash.
However, when trying to send AT commands in the serial monitor at different baud rates nothing happens.
I'll provide you with all the information down here:

 1. Schematic for both flash and normal mode:

[![Schematic][1]][1]

 2. I used the official flasher tool from espressif

 1. I used both Arduino IDE and Termite with no results
 2. I've uploaded the blink sketch successfully into my module, but it never runs and blinks.
 5. After lots of tries and resets I started to receive some information:
[![Reset info][2]][2]

  [1]: https://i.stack.imgur.com/dvVfN.jpg
  [2]: https://i.stack.imgur.com/HKDVV.png
But still no answers from this module!!!
Could you help me, please?

body:
The tutorial is to flash SDK 2.0 AT firmware. The AT 2.0.0 firmware is build with RTOS SDK. The 2.0 AT firmware available on Espressif site was build with settings not compatible with esp-01. It is built for 2 MB flash and  communicates over pins 13 and 15.

The latest NonOS SDK AT firmware is 1.7.1 (SDK 3), but it requires 2 MB flash too. It is possible to flash it to 1 MB module with the 2MB-c1 parameter with esptool.py. (The OTA update command will not work.)

GitHub user loboris (Boris Lovosevic) builds customized versions of AT firmware with SDK 3 for all flash sizes. You can download the files from his [ESP8266_AT_LoBo GitHub repository][1]. If you can't run his flash.sh utility, then for 1 MB flash you can Flash Download Tool with bin/upgrade/esp8266_AT_1_2.bin file and the right addresses for 1 MB flash: boot_v1.7.bin on 0x0; esp8266_AT_1_2.bin on 0x01000; esp_init_data_default.bin on 0xfc000 and blank.bin on 0x7e000 and 0xfe000.

  [1]: https://github.com/loboris/ESP8266_AT_LoBo


sender: user

sender: assistant

body: You need pullup resistors, 10kΩ or so, on both the NRST and GPIO0 lines. After you press and release the reset button the NRST line will be floating, and its voltage (and logic level) will be undefined. It's not unusual to see the behavior of a board change just by waving your hand over it if you leave inputs floating, so it's not surprising that you will sometimes get it to work.


message:
Keeping Adafruit Feather charged

I'm creating a keyboard for someone using an [Adafruit Feather 32u4 Bluetooth LE][1] as the brains. The case I want to put in into would be hard to remove to charge the battery.

Can I use this [USB LiIon/LiPoly charger][2] to charge the LiPo battery and keep power to the board? And then unpluging from the USB mini-B would switch over to the battery?

  [1]: https://www.adafruit.com/product/2829
  [2]: https://www.adafruit.com/product/259

body:
From the very page you linked to:

"... we added a connector for any of our 3.7V Lithium polymer batteries and built in battery charging. You don't need a battery, it will run just fine straight from the micro USB connector. But, if you do have a battery, you can take it on the go, then plug in the USB to recharge. The Feather will automatically switch over to USB power when its available. We also tied the battery thru a divider to an analog pin, so you can measure and monitor the battery voltage to detect when you need a recharge."

So, the board has a charger and battery connector already built in.


message:
Using the same variable between if-statements within loop()

I wonder if there is a good way to use the same variable value between two different if-statements within the loop().

Within the Servomotor section of the code, I want to use the value from the first if-statement's RewardTime within the next if-statement's RewardTime. Thus far, I cannot find a way to do it.
(Since there is no communication between these variables right now, the RewardTime remains 0).

I'd appreciate a certain guidance in this matter.

```
#include <Servo.h> // Library required for the servomotor (Make sure to download if not in the library)
#include <Button.h> // Library required for the microswitch (Make sure to download if not in the lbrary)

// PARAMETERS
// COPY THESE VALUES IN PROCESSING CODE MANUALLY
// Explanation: To prevent possible Arduino-Processing overflow. Do not want too much information flow between Arduino and Processing.
const float Scale = 1 * 1000; // milliseconds
const float Base = 1 * 1000; // milliseconds

Servo Servo1;
int servoPin = 9; // Declare the Servo pin
Button button(7); // Declare the microswitch pin (Can be varied from setup to setup)

unsigned long previousMillis = 0;
bool switching = false;
int State = LOW;

char BirdSings = 0;
//static float RewardTime = 0;

void setup() {
   Servo1.attach(servoPin);
   analogWrite(9, 0);
   Serial.begin(9600);
   button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop(){
   // MICROSWITCH
   // Get onset and offset times of when the bird arrives and leaves the perch
   button.loop();
   if(button.isPressed())
    Serial.println(1);
   if(button.isReleased())
    Serial.println(0);

   // SERVOMOTOR
   // Get times when the feeder is covered (food present) and uncovered (food not present)
    unsigned long currentMillis = millis();
    while (Serial.available() > 0) {
    unsigned long currentMillis = millis();
   if (Serial.read() == '\n') { // When there is a song
     //Serial.println(2); // Food is uncovered
     previousMillis = currentMillis; // 0 becomes the current milli
     static float RewardTime = (Serial.parseFloat() * Scale) + Base; // CALCULATE THE RewardTime HERE
     Serial.println(RewardTime);
     if (State == LOW)
      State = HIGH;
     else
      State = LOW;
    }
   }

  if (State == HIGH && switching == false){
    Servo1.write(0); // 0 degree
    unsigned long secondCurrentMillis = millis();
    if (secondCurrentMillis - previousMillis > RewardTime) { // USE THE ABOVE RewardTime HERE
      switching = true;
      previousMillis = secondCurrentMillis;
      if (State == LOW)
        State = HIGH;
      else
        State = LOW;
    }
  }
  if(State == LOW && switching == true){
    Servo1.write(90); // 90 degrees
    switching = false;
    //Serial.println(3); // Food is covered
    }
}
```

body:
Make the variable global, thus put it outside the `loop` function; also you don't need the `static` keyword anymore.

    float RewardTime = 0;

Than inside your first `if` statement, remove the `static float` keywords:

    RewardTime = (Serial.parseFloat() * Scale) + Base;

Some other tips:

- normally local variables do not start with a capital (so `rewardTime` is like most coding conventions)
- Always use brackets.

    if (State == LOW)
      State = HIGH;
    else
      State = LOW;

Change to:

      if (State == LOW)
      {
        State = HIGH;
      }
      else
      {
        State = LOW;
      }

- However, to make it more simpler, use the ternary operator, you can change it to:

    State = (State == LOW ? HIGH : LOW);

Which means: if some condition ? Do this : Else do this;


body: Since you defined it within the first `if` statement, it is only "in-scope" or defined within that block. To make it visible to both if statements, define it in the next outer block that contains both `if` statements - in this case, somewhere between `void loop(){` and `if (Serial.read()...`


message:
Porting "far" flash memory access from Arduino Mega to Due

I have a project that runs on the Arduino Mega 2560 which takes up almost the complete amount of flash memory available (https://github.com/fredlcore/bsb_lan/blob/master/BSB_lan.ino). Because of this, I'm planning on migrating the project to the Arduino Due.

My main problem at the moment is to port those functions that access flash memory in the "far" memory area (>64k) for which on the one hand various _PF functions (like strncpy_PF) are provided, and on the other hand a dummy "pointer" type uint_farptr_t (which is actually uint32_t) is available.

My problems now are twofold:

1. While the _PF functions have specific definements for the Due which under "normal" circumstances should work without changes in the code, they expect different variable types. For example, strncpy_PF takes uint_farptr_t (i.e. uint32_t) as argument for src on the Mega, it expects a const char * on the Due. Compilation thus results in lots of errors.

2. For the Mega to be able to access char arrays (which are 16 Bit on the Mega) above 128k, I need a rather dirty workaround (see function calc_enum_offset() in the code linked above). Basically I need to take the memory address of a 16 Bit char pointer and make some calculations to get the final address from which I read the strings. On the Mega, I can do these calculations on the basis of uint_farptr_t and then read from the calculated memory address with pgm_read_byte_far() for example. On the Due, however, pgm_read_byte_far(addr) is translated to (*(const unsigned char *)(addr)). Again, the uint32_t type does not fit this.

Do you have any suggestions on how I should tackle these issues with the least amount of code?

body:
The Due, being ARM, is a von Neumann architecture. That means that it has no concept of "progmem", "near" or "far" pointers, etc.  There are no _P or _PF variant functions, but the Arduino core provides simple stubs as a convenience.

Instead all "flash" memory access is just simple memory accesses using `const`.

The best thing you can do is to use preprocessor macros to select between AVR and ARM code:

    #if defined(__AVR__)
        strncpy_PF(buffer, enumstr+c, sizeof(buffer));
        buffer[sizeof(buffer)-1] = 0;
        outBufLen+=sprintf(outBuf+outBufLen,"%d - %s",val,buffer);
    #else
        outBufLen += sprintf(outBuf + oufBufLen, "%d - %s", val, cmdtbl[i].enumstr);
    #endif

In fact, given the huge amount of "hackiness" involved in that program with regards the `cmdtbl`, and the massive amounts of code that just aren't needed on the Due, it may be better to start a fresh program that is Due specific and delete the swathes of unneeded code.


message:
Error with led Blinking (avrdude: ser_open(): can't set com-state)

I am new with Arduino and I made something very basic and I don't know why it is not working . I placed the positive led in pin 13 and the negative in GND and wrote this code :

    #define LED 13
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

I verified if it 's connected to Arduino Uno and when I upload the code I have this errors :

    Sketch uses 924 bytes (2%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    avrdude: ser_open(): can't set com-state for "\\.\COM4"
    An error occurred while uploading the sketch

Sometimes IDE has problems ? What I did wrong ?

body:
You do not have a problem with LED blinking (although there seems a resistor missing for your led), but with uploading a sketch.

Hard test: switch off your computer, remove USB cable, switch on computer, check the COM port appearing when connecting the Arduino via USB cable. Then start IDE and try upload again.

Eventually something else was blocking the COM port.


message:
Which arduino will be suitable with bill acceptor

I want to connect a bill acceptor (protocol ID003) and 3 switches and an Ethernet shield to Arduino. I am building a system that accepts bill and pass on the information to our software. Which Arduino will be the best choice, we need something which will have lot of code and also communication should be fast.

1. ARDUINO MEGA 2560 REV3
2. ARDUINO DUE
3. Arduino Uno REV3

**--Edit--**

This is I want to create:

A bill acceptor connected with arduino. Arduino has 3 buttons. (1. Play button, 2. redeem cash button. 3rd is not necessary).

When user login on machine, I get the details of user account through an API.

When user inserts money in bill acceptor, it enables the play button and add money in users account (If user already has money in account, button will be enabled). User can play until his account is not empty (i.e. if user has 200 in account, he can play 10 times). User can earn or lose money.

I have to send this transaction detail through an API.
If user press redeem button, it will print a slip of account details (Total money in account)

**I am using Python.**

I need to know which arduino is suitable for this, Ethernet shield compatible with that arduino (I think I am going to use **ARDUINO MEGA 2560 REV3**, but I don’t know Ethernet shield compatible with this model).

Also I need some Idea how can I make this. This is first time I am using arduino and bill acceptor.

body:
- Define 'lot of code', the Arduino Uno has 32 KB Flash, the Mega 256 KB.
- Define 'fast', the Uno/Mega are 16 MHz, the Due 48 MHz
- Three switches use 3 GPIO's, shouldn't be a problem on neither of them; the Mega has more GPIOs than the Uno, but both have plenty for your needs.
- The Ethernet shield are available for all three
- I don't know the 'bill acceptor', add a datasheet.

Conclusion: it depends on what is lot of code, and what is fast.


message:
GSM module not working after power off

I am making a project on gsm module(sim 900a unofficial shield), when I will send a SMS led will turn ON. after uploading code, module works fine, and led turned ON after sending message. But when I power off sim900a and Arduino, and power on back, it's not working, led not power up after sending message, when I reupload sketches it is working fine, means every time after power off I need to upload code again, I am learning c and don't have much knowledge? Is my code right? Or some other fault?

    #include <SoftwareSerial.h> //software serial library for serial communication b/w arduino & GSM

        SoftwareSerial mySerial(8, 9);//connect Tx pin of GSM to pin 8 of arduino && Rx pin of GSM to pin no 9 of arduino

        int led = 7;
        String message;

        void setup()
        {
          mySerial.begin(9600);   // Setting the baud rate of GSM Module
          Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
          delay(100);

          mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
          delay(1000);
          pinMode(led,OUTPUT);
          digitalWrite(led,LOW);
        }

        void loop()
        {
          if (mySerial.available()>0){
          message = mySerial.readString();
          }

          if(message.indexOf("ON") > -1){
              Serial.println("LED ON");
             digitalWrite(led,HIGH);
             }
            else if(message.indexOf("OFF") > -1){

              Serial.println("LED OFF");
              digitalWrite(led,LOW);

          }

          delay(10);
        }

Circuit diagram

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

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

body:
The GSM takes time to start up.  Your program needs to be far more complex than the simple "Throw commands at it and hope" method you are using.

First you need to query the modem repeatedly until it responds.  This is usually done with the `AT` command.  A sequence would look like:

    Send: AT
    (Wait for OK response or timeout)
    Send: AT
    (Wait for OK response or timeout)
    Send: AT
    (Wait for OK response or timeout)
    Send: AT
    (Wait for OK response or timeout)
    Recv: OK

Once the modem has booted and is ready to receive commands you can start sending commands.  You shouldn't just "print and delay" though like you are at the moment. Instead you should send the command and then examine the response to see if the command worked ("OK") or failed ("ERR").


message:
Arduino code for turning an led on by one clap and then off by one clap

I want my Arduino to turn on a LED when sound sensor detects a clap (noise) and keeps the LED on until the sound sensor detects another clap (noise) which turns the LED off.

    int Sensor = A0;
    boolean status_lights = false;

    void setup() {
      pinMode(Sensor, INPUT);
      pinMode(13, OUTPUT);
    }

    void loop() {
      int status_sensor = digitalRead(Sensor);
      if (status_sensor == 0)
      {
        if (status_lights == true)
        {
          status_lights = false;
          digitalWrite(13, LOW);
        }
        else {
          status_lights = true;
          digitalWrite(13, HIGH);
        }
      }
    }

My sound sensor has 3 pins.
[sound sensor details][1]

EDIT: My code only turns on the led but dosen't turn it off when I clap.

  [1]: https://store.roboticsbd.com/robotics-parts/291-sound-sensor-module-sound-detection-robotics-bangladesh.html

body:
If the sound level is below the threshold, the DO pin of the sensor signals a high value. If the sound level exceeds the threshold, i.e you clap you hands, the DO is pulled to GND and the signal gets LOW for a short while. After this short while the signals gets HIGH again.

Now look at you loop:

    void loop()
    {
      int status_sensor = digitalRead(Sensor);

      if (status_sensor == 0)
      {
        // you enter this block if you clap your hands and the
        // mcu is fast enough to capture the signal / DO pin (LOW)
        // within the short time interval
        // I'm sure it is fast enough to enter this block multiple
        // times in the interval the clap is active.
        if (status_lights == true)
        {
          status_lights = false;
          digitalWrite(13, LOW);
        }
        else
        {
          status_lights = true;
          digitalWrite(13, HIGH);
        }
      }
    }

You see, the LED is toggled as long as the LOW interval of the sensor is active (DO=LOW).

I interpret you statement "My code only turns on the led but dosen't turn it off when I clap." so, that the LED is on, when the program starts without a clap. That means that the environmental noise is loud enough to activate the sensor. Then the loop above is iterated permanently and you switch on and off the LED at a very fast speed. That's like you would apply a PWM waveform on the LED pin. The LED is on but dimmed to about 50%.

To find out if I'm right, just add a delay in the loop. My assumption seems to be correct, if the LED blinks with one herz (one time per second).  The you can adjust the sound threshold until the LED stops blinking.

    void loop()
    {
      int status_sensor = digitalRead(Sensor);

      // Add the delay here ..........
      delay(500);

      if (status_sensor == 0)
      {

If you have calibrated the sensor, remove the delay from the code and add a new delay after changing the LED states. That should be much shorter, because it's only there to ensure that you don't toggle the LED while the sensor is active.

        if (status_lights == true)
        {
          status_lights = false;
          digitalWrite(13, LOW);
        }
        else
        {
          status_lights = true;
          digitalWrite(13, HIGH);
        }
        // wait until the clap is over
        delay(100);


message:
Nesting loops - if statement in a while loop

I have been trying many variations of code like this, cannot seem to get this to work with how I logically would think it would work.  Am I missing something with syntax or breaking some rules?  Everything works independently but not jointly.

    int switchS = 0;
    int var = 1;

    void setup() {
        pinMode(1,INPUT);
        pinMode(7,OUTPUT);
        digitalWrite(7,LOW);
    }

    void loop() {
        switchS = digitalRead(1);
        while(var == 1)
        {
            digitalWrite(7,HIGH);
            delay(100);
            digitalWrite(7,LOW);
            delay(100);
            if(switchS == HIGH)
            {
                var = 0;
            }
        }
        delay(5000);
        var = 1;
    }

body:
I guess you want the while loop to exit, when the switch goes to HIGH. (You didn't explain this in your question)

Currently the variable `switchS` cannot ever change while the code is in the while loop. The variable `var` only changes, when `switchS` is HIGH. So, if `switchS` is LOW at the start of the while loop, you have an infinite loop.

Instead, you can actually read the switch state inside the while loop, not outside of it. The variable `switchS` will not automatically track the state of the switch. You have to explicitly read it. Like this variant of your code:

    int switchS = 0;
    int var = 1;

    void setup() {
        pinMode(1,INPUT);
        pinMode(7,OUTPUT);
        digitalWrite(7,LOW);
    }

    void loop() {
        while(var == 1)
        {
            digitalWrite(7,HIGH);
            delay(100);
            digitalWrite(7,LOW);
            delay(100);
            switchS = digitalRead(1);  // I moved this line in the while loop, to read the switch on every loop iteration
            if(switchS == HIGH)
            {
                var = 0;
            }
        }
        delay(5000);
        var = 1;
    }

---

Note: You are using pin 1 as input pin. On the Uno this is a Serial (UART) pin, which is used to communicate with the PC. If you have enough pins, that are free, you should not use pins 0 and 1, so that you don't block the serial communication, unless you really need it and know, what you are doing.


message:
24v LED strip with common anode?

I have a [5m strip of 24v tunable white LEDs](https://www.environmentallights.com/17990-ct2216-240-10-reel.html) and I'm trying to figure out what I need set it up. There's a pad for V+ and then one for brightness and one for warmth. If I plug the V+ in V+ on a 24v supply and the two others to V-, the whole thing lights up full intensity. The strip draws 16 Watts per meter (80 for the whole thing). As I understand it, you vary the two anodes by varying the resistance to ground. I've seen some instructions that this can be done with PWM pins, but I'm assuming that given the voltage and current, no arduino or similar can handle that much. Do I need transistors then? What specs do I look for to understand the limitations?

body:
Your strip has 2 LEDs with different color temperature directly besides at the same spot for every element of the strip. So the adjusting of the overall color temperature is done by changing the relative brightness of both LEDs. If the LED with the warmer light is brighter, the overall color temperature will also be warmer. Common Anode means, that V+ is the connected to the positive pin (anode) of both LEDs, so it has to be connected to +24V. The electrical circuit is completed by connecting the pins W and C (Warm and Cold) to ground. To control the individual brightness of the warm and cold LED groups, you have to use PWM.

You are right, that an Arduino cannot handle currents this big. You need a transistor for this. I would suggest using a MOSFET, since this is the easiest and most efficient possibility. By one MOSFET for every channel (Warm and Cold), which is capable of handling the needed power (Important! Or you will fry the MOSFET). Also it should be a logic level MOSFET, that is well in saturation of the gate voltage for the output voltage of your Arduino. Connect the MOSFETs Drain pin to the channel on the strip, the Source pin to ground of your power supply and the Gate pin to a PWM pin of the Arduino. Also connect the ground of the power supply with the ground of the Arduino.

Now you can control the brightness of the Warm and of the Cold LEDs by adjusting the PWM duty cycle with the Arduino.


message:
Arduino I can't make this statement work

int val1 = 0;
    byte val2 = 10;
    int buttonPin = A0;
    byte result = 0;

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

    void loop() {
        val1 = digitalRead(buttonPin);

        if (buttonPin == HIGH) {
            result = result + val2;
            result = result + 10;
        }
        else
        {
            digitalWrite(val1, LOW);
        }

        Serial.print("STATE   ");
        Serial.print(val1);
        Serial.print("    ");
        Serial.print(result);
        Serial.println();

        delay(100);
    }

body:
I appears you want to increment the result by val2 each time the button is pressed.  If you want to wire it up this way you can but there are potential issues with this, such as not catching each time you press the button, or thinking you pressed the button twice when you accidentally held it down for more than 100ms.  The code for this method is below:

    const int buttonPin = A0;
    bool buttonState = LOW;
    int val = 10;
    int result = 0;

    void setup()
    {
      pinMode(buttonPin,INPUT);
      Serial.begin(115200);
    }

    void loop()
    {
        buttonState = digitalRead(buttonPin);

        if (buttonState == HIGH)
        {
            result = result + val;
        }

        Serial.print("STATE:   ");
        Serial.print(buttonState);
        Serial.print("\t");
        Serial.print("RESULT:  ");
        Serial.print(result);
        Serial.println();

        delay(100);
    }

The way to prevent double counts or missing counts would be to use interrupts.  Later I may write that one up if you need that instead.

Good Luck!


message:
Making Serial act as an interrupt

I am trying to make a program to control a stepper motor with serial inputs, and in writing a function to jog it, I am having trouble figuring out how to make a serial input stop the loop that steps the motor without making the time per step inconsistent.  Is there a way where I can have a new serial input act like an interrupt and break any loop that's in progress.

    void jog() {
      if(input[1] == 0) sd.setDirection(0);
      else sd.setDirection(1);
      while(true){
        if(Serial.available() > 0) break;
        sd.step();
        delayMicroseconds(10);
      }
      sd.setDirection(0);
    }

Right now I have this (I'm using a Pololu library that defines the steps), but for some reason this does nothing or at least moves so slow it's imperceptible (a single step only moves the motor 0.007 degrees).  It moves the motor very smoothly if I delete `if(Serial.available() > 0) break;` but then I can't stop it.

    void loop() {
      getData();
      switch(input[0]){
        case 'r':
          Serial.write('r');
          ramp();
          break;
        case 'c':
          Serial.write('c');
          cycle();
          break;
        case 'j':
          //Serial.write('j');
          jog();
          break;
        default:
          break;
      }
    }
    void getData(){
    if(Serial.available() > 0){
      for(int i = 0; i < 200; i ++){
        input[i] = 0;
      }
      for(int i = 0; i < Serial.available(); i++){
        input[i] = Serial.read();
        Serial.print(input[i]);
      }
    }
    Serial.flush();
    //Serial.print(input[0]);
    }
This is the relevant code that calls jog()

body:
How do you know, that there is nothing in the Serial buffer, when you enter the `jog()` function? You don't check for this.

I think your problem is actually in your `getData()` function. The for loop

    for(int i = 0; i < Serial.available(); i++){

might not work as you think, because i increases in every loop iteration while `Serial.available()` decreases in every iteration. So you actually read less data, than is available on the buffer. For example let's assume, that you have 2 Bytes on the buffer. `Serial.available()` returns 2. In the first for loop iteration `i` is 0, while `Serial.available()` is 2. When you read from the Serial buffer in the iteration, `Serial.available()` decreases to 1 (since you removed one byte from the buffer by reading it). At the end of the iteration, the for loop will increase `i` by 1 (due to the `i++`). Now in the condition of your for loop, you have `1 < 1` (because both `i` and `Serial.available()` are 1), thus the for loop will exit without any further iterations. But you still have 1 Byte left in the buffer, that you didn't read.

As I read from the [documentation][1] of `Serial.flush()` (though the documentation is notoriously bad) and from [this question][2], I see, that it will only wait until the output buffer is emptied by the interrupt routines. It does nothing with the input buffer. So you still have data in your RX buffer after this line.

That means, that you really have data in your RX buffer, when you get into the `jog()` function. Thus it will directly exit without doing any step.

---

To solve the issue, you should first correct your `getData()` function to read all the available data from the RX buffer. You can change your for loop like this:

    for(int i = 0; Serial.available() > 0 && i < INPUT_BUFFER_SIZE; i++){

This will loop until the RX buffer is empty (when `Serial.available()` returns 0) or until your `input[]` array is full (Please add a constant or a define for the input buffer size. Maybe you already have it. You didn't include the full code. But I guess it is 200).

After the for loop, you can empty the buffer by reading from it, until there is nothing left (Please see the linked question for that). You can even do this at the start of your `jog()` function. This ensures, mostly, that no data is in the buffer at the start of the `jog()` function (mostly, because the timing of data reception could be, that you receive a byte between the emptying of the RX buffer and the loop. Little probability, but not impossible).

Though - as Nick Gammon states in the linked answer - it is not the best way to empty the RX buffer and use every serial input as interrupt (sometimes you don't have exact control, when exactly the data is received). A better solution is to implement a message protocol, where the end of a full message is marked with a special character. Then you read from serial, until a full message is received (you can even do this non-blocking, so that you can do other things until the message is complete), and only then act upon the message. This would need bigger changes in your code. You would have to rewrite your `getData()` function and then remove all blocking code from the sketch (for example all delays) and work with non-blocking code instead (for example using the `micros()` function. The principle is explained in the `BlinkWithoutDelay` example, that comes with the Arduino IDE (though it uses `millis()` instead of `micros()` it is the same principle). You would call the `jog()` function repeatedly, which would only do a step, if it is time to do one. In the meantime the rest of the code can receive new messages. This makes you more flexible and independent of the exact timing of data reception. Since this would be a big rewrite of your code, you have to decide yourself, if you want to go this way, or stay with the simpler and more imperfect solution.

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/flush/
  [2]: https://arduino.stackexchange.com/questions/22363/how-to-flush-the-input-serial-buffer-in-arduino


message:
STM32 as keyboard

I would like to use a STM32F105xx to build my own computer keyboard.
That MCU has support to USB OTG (FS).
So, I have 2 questions:

 1. Can I flash microcontroller with usb or I need a external
    programer?
 2. How to do the computer recognize stm32 as a keyboard?

body:
The STM32F105xx series is not yet supported by either Arduino core ([STM32 core](https://github.com/stm32duino/Arduino_Core_STM32) or [maple core](https://github.com/rogerclarkmelbourne/Arduino_STM32)) and neither [mbed-os](https://github.com/ARMmbed/mbed-os/blob/master/targets/targets.json).

The chip is still usable with the STM32 provided framework, the STM32HAL, (e.g. through STM32CubeMX). There you can select your chip and generate a template project. The program lets you easily configure the chip for "USB Device" role and HID (Human-Interface-Device) class.

![cumbemx]][1]

Note that from a hardware side, you must provide the chip with an external crystal oscilator (usually 8MHz) so that the HSE+PLL can generate the 48MHz USB clock. This will not work on the internal HSI clock due to low precision. Activate the HSE Crystal in the RCC section of CubeMX and see the clock configuration tab.

From there on you'll have to read the [STM32F1 HAL documentation](https://www.st.com/content/ccc/resource/technical/document/user_manual/72/52/cc/53/05/e3/4c/98/DM00154093.pdf/files/DM00154093.pdf/jcr:content/translations/en.DM00154093.pdf) to figure out how to send keystrokes. There are also external resources [here](https://damogranlabs.com/2018/02/stm32-usb-hid-mouse-keyboard/) and [here](https://www.youtube.com/watch?v=WxypCwFR7tE).

Programming the board via USB is possible. Just set the BOOT0 and BOOT1 pins accordingly and reset the board to get into bootloader mode. It will then appear as a USB device which is flashable by given tools. See e.g. [here](http://www.emcu.eu/how-to-program-the-stm32/). The more direct way is to buy a cheap STLinkv2 and program it via the SWD pins (SWDIO + SWCLK), which also enables debugging, which USB flashing does not.

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


message:
light leds from an array

I have the project to build a robot for my school. It will record button pushes then move according to this record.

Before usig motors, i'm trying to do this using leds.

Thanks from posts from this community, I've succeed in recording button pushes in an array.

Now I'm trying to light the leds according to this array.
I have 4 buttons with 4 leds and one button tu run the recording when it's ready.

I'm stuck in lighting the leds when I push the play_button.

I hope someone can help me...

Here's my script :

    int arr[10];
    boolean previous = LOW;
    unsigned long time1 = 0;
    int debounce = 200;
    unsigned long time2 = 0;
    int index_state = 0;

    int play_button = 13; //define pin # for play button

    int button[4] = {2,4,6,8}; //store button pins in an array
    int leds[4] = {3,5,7,9}; //store led pins in an array

    void setup()
    {
      for(int n=0;n<10;n++) arr[n] = 0;//initialisition
     Serial.begin(9600);
    }

    void loop(){
     boolean mode = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead (8);
     while(mode == LOW) mode = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead (8);//wait here till one of the pushbutton goes high;
     //Serial.println("value");
     if( mode == HIGH && previous == LOW && millis() - time1 > debounce) {
     //find out which one is high and store that value in array;
     if(digitalRead(2)) arr[index_state] = 2;
     else if(digitalRead(4)) arr[index_state] = 4;
     else if(digitalRead(6)) arr[index_state] = 6;
     else if(digitalRead(8)) arr[index_state] = 8;
     else ;

     //print the value and the index;
     Serial.print(arr[index_state]);
     Serial.print(" Stored in index: ");
     Serial.println(index_state);
     index_state = (index_state + 1) % 10;
     //update value of time1 for button debouncing
     time1 =  millis();
    }

      //update the value of previous button state
      previous = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead(8);

      }

Thank you

body:
You have problems in including the further functionality (the playback), since your `loop()` function is solely written for providing the first part of functionality (the recording). You need an overall structure, that will execute the correct functionality at the correct time/logic order.

For this, an Finite State Machine (FSM) is the best way. It will help you to structure your code and the logic. It is an important principle to learn.

First you would have to divide your program logic into different states and transitions between them (don't look too close at the actual code at this point, but with a higher abstraction). Currently I see 2 states in your project: A state, where you are recording the button presses in an array, just like you already did. And a state, where the array is used for playback. The transition from the first to the second state happens, when the playback button is pressed. The transition back happens, when the playback is finished. It helps to draw a graph for this, to visualize the the states and their transitions. In my answer to [this question][1] I explained this further including an example of such a graph.

When you are finished creating the states and transitions, you can create the necessary code structure. The easiest way for a beginner is to use a simple state variable (simply an integer, or - if you want to use names for the states - an enum) in a `switch()`-`case` statement. You can also see this in the linked answer. Your code then goes into the case statements. The switch statement will only execute the code for the current state. To do a transition to another state, you simply change the state variable. So in the case statement of the first state, you put the code that you already have for reading the buttons, and an if statement, that checks the playback button. If the playback button was pressed, change the state variable to the second state.

You could also solve this problem without an FSM, but the structure won't be that good and easy to expand. Also you might get some extra points for implementing an FSM :D

---

Currently your code is blocking. That means, that it will block any further operation, until something happened, in this case, that one of the 4 buttons gets pressed. Often this is only a hindrance, when adding functionalities. It is better to use `do-maybe` code, means code, that will only do something, if some condition is met (like time). You are already doing this in the if statement

    if( mode == HIGH && previous == LOW && millis() - time1 > debounce) {

(it only triggers the recording of a new button, if a button was pressed and the debounce time has passed) so why are you blocking before this with the while loop? You could just write to `mode` without the while loop.

  [1]: https://arduino.stackexchange.com/questions/63488/wanted-to-control-2-servos-with-serial-read/63491#63491


message:
Scope of RtcDateTime object when declared outside of a function

I'm trying to merge 2 Arduino samples, in order to be able to use DS3231 RTC module with ESP8266 WiFi simple web server.

My RTC library is this:
[https://github.com/Makuna/Rtc/wiki][1]

Generally, to code runs ok (I have the Web server responses to my browser calls, and I think the DS3231 RTC code also works). But when I'm trying to use a variable from within the RTC object into the Web server function - I get nothing.

I thought declaring the 'now' object outside any function (Setup() nor Loop()) will make it global, and when I'll update it in the Loop() function using

    now = Rtc.GetDateTime();
It will be available to other functions as well, but all I get is "0" when I try to print it.

My code is here:
Definitions part:

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

    /* This block is for I2C protocol for DS3231 module (for normal hardware wire use below) */
    #include <Wire.h> // must be included here so that Arduino library object file references work
    #include <RtcDS3231.h>
    RtcDS3231<TwoWire> Rtc(Wire);
    /* The above block is for I2C protocol and DS3231 module  (for normal hardware wire use above) */

    ESP8266WebServer server(80);
    RtcDateTime now;

My Loop():

    void loop(void) {
      now = Rtc.GetDateTime();
      Serial.println(now.Minute());
      server.handleClient();
      delay(500);

    }

And all I get is "0" printed.

Any help would be appreciated!

  [1]: https://github.com/Makuna/Rtc/wiki

body:
As was suggested by more 'native' friends here - I'm 'Answering my question' to make things clear.

After a check and debug - I've found a mysterious behavior that happened to my DS3231 module. Probably a mistaken initializing set of calls - made it stop working - not getting time updates and not counting the time at all. (Freeze at 1/1/2000, 00:00:00).

Disconnecting it from power source, and taking out the battery - returned it to normal behavior, able to get time updates, and answering the calls from the library.

When that part solved - everything else went as easy as it should.

The code sample I posted in my question (declaring the 'now' object outside of setup() and loop() functions) made that object global, so another function (WebServer) can read its current value and use it internally.

Thanks everyone who looked at my problem and helped,
It was a great lesson about how not to take anything as 'known' without double-checking.


message:
How to get text to flash on ssd1306 i2c screen

I am trying to alternate a string back and forth on the SSD1306 oled screen.
So I want the display to show "test1" for 0.5 seconds, then "test2" for 0.5 seconds, repeating. the code below is just showing "test1" for 0.5 seconds then going blank...
I am using a ssd1306 128_32 i2c screen, and using the adafruit library.

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

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 32 // OLED display height, in pixels

    // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
    #define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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

      // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
        Serial.println(F("SSD1306 allocation failed"));
        for(;;); // Don't proceed, loop forever
      }

      // Show initial display buffer contents on the screen --
      // the library initializes this with an Adafruit splash screen.
      display.display();
      delay(2000); // Pause for 2 seconds

      // Clear the buffer
      display.clearDisplay();

      // Show the display buffer on the screen. You MUST call display() after
      // drawing commands to make them visible on screen!
      display.display();
      delay(2000);

      display.setTextSize(4);             // Draw 2X-scale text
      display.setTextColor(SSD1306_WHITE);

    }

    void loop() {
     testdrawstyles1();
     testdrawstyles2();
    }

    void testdrawstyles1(void) {
     display.clearDisplay();
     display.print(F("test1"));
     display.display();
     delay(500);
    }

    void testdrawstyles2(void) {
     display.clearDisplay();
     display.print(F("test2"));
     display.display();
     delay(500);
    }

body:
As approved by the OP, the error was caused by not having reset the cursor to a visible position on the display. The text was written outside of the OLED.

It seems as the `clearDisplay()` method does not reset the cursor.

The solution is to change the following methods

    void testdrawstyles1(void)
    {
      display.clearDisplay();
      display.setCursor(0,0);
      display.print(F("test1"));
      display.display();
      delay(500);
    }

    void testdrawstyles2(void)
    {
      display.clearDisplay();
      display.setCursor(0,0);
      display.print(F("test2"));
      display.display();
      delay(500);
    }


message:
How do i Connect multiple sensors in one arduino. Which are namely a accelerometer, GPS, microphone and a GSM module

I am a noob in the Arduino world and have only started reading about it. I have zero experience with Arduino some suggestions to increase my level will also be highly appreciated. But I have a lot of ideas, I want to work on.

I want to measure the velocity and noise levels with the GPS coordinates of a moving vehicle and send it to my phone using gsm or wifi but being a noobie, I have no clue where to start. Can anyone provide some kind of documentation or tutorial it will be really helpful and would help me kickstart my journey.

body:
I've actually done a good chunk of what you are looking for here:

GPS Coordinates & Velocity:

For this you can use the following Adafruit hardware:

 - [GPS Breakout][1]

 - [GPS Adapter][2]

 - [GPS Antenna][3]

This sensor will give you the coordinates and the velocity when you use the [Adafruit library][4].  I would connect it using the i2c port and start with the example code "[GPS_I2C_Parsing][5]".  You'll be able to remove most of the data as it is not needed in your example.  You'll also likely want to convert the speed to mph (it comes in as knots).

Noise Level:

I have not actually tried to stream audio from an arduino to a phone or anything but you can still get a noise level.  If you just want to get a dB reading and send that you can do that one of two ways; analog or digital.  For analog you can get something like [this][6] from adafrutit.  This has a built in microphone (probably not ideal) but it also has the amplification circuit you'll need.  You can always desolder the built in and connect your own.  For the digital route you could go with something like [this][7].  Adafruit has a few different variants of this, it would depend on what exactly you are looking for.

Sending Data:

I think you're best option will be a [GSM shield][8].  Wi-fi, in my opinion, would be difficult unless you are using your phone as a hot-spot in the car.  (Probably defeats the purpose of doing this then).  You can use the referenced shield to send texts, with data such as the coordinates, speed and noise level, and even make calls, for an audio stream.

Good luck!

  [1]: https://www.adafruit.com/product/746
  [2]: https://www.adafruit.com/product/851
  [3]: https://www.adafruit.com/product/960
  [4]: https://github.com/adafruit/Adafruit-GPS-Library/archive/master.zip
  [5]: https://github.com/adafruit/Adafruit_GPS/blob/master/examples/GPS_I2C_Parsing/GPS_I2C_Parsing.ino
  [6]: https://www.adafruit.com/product/1063
  [7]: https://www.adafruit.com/product/2716
  [8]: https://learn.adafruit.com/adafruit-fona-mini-gsm-gprs-cellular-phone-module/overview


message:
Arduino and DAC

this might be more general electronics question, forgive me if this is not the correct place to ask.

I am atempting to use the arduino and MCP4725 breakout board to inject 4 different voltages into an existing line that comes from V1.

V1 is the analog signal from an existing unit and varies between 2v, 3v and 4v. VM1 responds to those voltages and switches to a different working modes. 2v == Mode A, 3v == Mode B, 4v == Mode C.

My plan is to have MCP4725(represented as V2 below)hooked up to Arduino to simulate Modes A, B, C when needed.

MBR0540 D2 is there to prevent sending the voltage back to the sending unit, MBR0540 D1 is to do the same for DAC.

I am worried that if the D2 fails for whatever reason, I might loose the sending unit functionality.. is there a better way to do it?

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/kAJrv.png)

<!-- End schematic -->

Thanks for any help/comments you might have.

body:
Unless you are really stressing it, it is highly unlikely that D2 would fail.

You could, though, replace both diodes with a simple SPDT switch to select between the two voltage sources.

Whatever you do, though, it probably has about the same chance (or more so) of failing (and the same end result) as having the diodes.

You could always add an "emergency override" switch that both bypasses D2 and isolates V2 in case of failure.


message:
How can I make YX5300 MP3 player play song in a loop?

I am doing a Christmas project and I have an ultrasonic sensor that detects if a person is In front of it. I want that if someone is in front of it, it lights up LEDs, which it does, and it also has to play a Christmas song, which it doesn't. I tried to make it play the Christmas song but nothing happens. Also the LEDs are only blinking when you put ur hand in front of the ultrasonic sensor. I want it to light up the lEDs for the same amount of time the song is, 28 seconds, and than the lEDS should stop and the ultrasonic sensor should wait for another person and it repeats. I am new to this so please be specific in your reccomendations.
Here is my code:

    #define trigPin 10
    #define echoPin 13
    #include <SoftwareSerial.h>
    #define ARDUINO_RX 7//should connect to TX of the Serial MP3 Player module
    #define ARDUINO_TX 6//connect to RX of the module
    SoftwareSerial mySerial(ARDUINO_RX, ARDUINO_TX);
    static int8_t Send_buf[8] = {0} ;
    #define CMD_SEL_DEV 0X09
    #define DEV_TF 0X02
    #define CMD_PLAY_W_VOL 0X22
    #define CMD_PLAY 0X0D
    #define CMD_PAUSE 0X0E
    #define CMD_PREVIOUS 0X02
    #define CMD_NEXT 0X01

    int red1 = 5;
    int red2 = 4;
    int green1 = 3;
    int green2 = 2;

    long lCnt = 0;
    unsigned long lStart;

    void setup(){
      Serial.begin (9600);
      mySerial.begin(9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(red1,OUTPUT);
      pinMode(red2,OUTPUT);
      pinMode(green1,OUTPUT);
      pinMode(green2,OUTPUT);
      delay(500);//Wait chip initialization is complete
      sendCommand(CMD_SEL_DEV, DEV_TF);//select the TF card
      delay(200);//wait for 200ms

    }

    void loop(){
      float duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);

      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) * 0.0344;

      if(distance > 0 && distance <=60){

        digitalWrite(red1,HIGH);
        delay(50);
        digitalWrite(red2,HIGH);
        digitalWrite(green1,HIGH);
        delay(50);
        digitalWrite(red1,LOW);
        delay(50);
        digitalWrite(red2,LOW);
        digitalWrite(green2,HIGH);
        delay(50);
        digitalWrite(green1,LOW);
        digitalWrite(green2,LOW);
        delay(50);
        sendCommand(CMD_PLAY_W_VOL, 0X1E01);
      }

    }

    void sendCommand(int8_t command, int16_t dat)
    {
      delay(20);
      Send_buf[0] = 0x7e; //starting byte
      Send_buf[1] = 0xff; //version
      Send_buf[2] = 0x06; //the number of bytes of the command without starting byte and ending byte
      Send_buf[3] = command; //
      Send_buf[4] = 0x00;//0x00 = no feedback, 0x01 = feedback
      Send_buf[5] = (int8_t)(dat >> 8);//datah
      Send_buf[6] = (int8_t)(dat); //datal
      Send_buf[7] = 0xef; //ending byte
      for(uint8_t i=0; i<8; i++)//
      {
        mySerial.write(Send_buf[i]) ;
      }
    }

Thanks

body:
I think you want to use the command `[Single cycle play]` which is `7E FF 06 08 00 00 01 EF` (the `00 01` towards the end is the song number to play).

All the commands are detailed in [the manual](http://geekmatic.in.ua/pdf/Catalex_MP3_board.pdf).


message:
Mixed structure with int and string

I want to create a structure like this:
```
 struct commands
{
  int   cmd;
  char  descr[25];
};

commands cmds[] =
{
  {16, "Hammond Organ"},
  {17, "Percussive Organ"},
  {18, "Rock Organ"},
  { 0, "" }                   // end of list marker
};

```
The compiler doesn't protest, but in a simulator the values of cmds[i].descr are all zeros.

And the line
```
Serial.write(cmds[1].descr);
```
prints nothing.

Please recommend how to rewrite the code.

Thanks.

**EDIT**

Thanks for your answer. It helped me a lot.

There is something wrong with the simulator (Simulator for Arduino - version 1.11E Designed by Virtronics). In the meantime I received the Mega 2560 board and the code works well with the board.

body:
There must be something wrong with the simulator you're using, because your code works for me (Arduino IDE 1.8.9, OSX, Arduino Uno).

    struct commands
    {
      int   cmd;
      char  descr[25];
    };

    commands cmds[] =
    {
      {16, "Hammond Organ"},
      {17, "Percussive Organ"},
      {18, "Rock Organ"},
      { 0, "" }                   // end of list marker
    };

    void setup(){
      Serial.begin(9600);
      Serial.write(cmds[1].descr);
    }

    void loop(){}


body:
Try to use char pointer notation (char *) instead of array notation (char[]) in structure declaration:

    struct commands
    {
        int   cmd;
        char*  descr;
    };

- OR -

use struct declaration as-is, but change the array initialization like below:

    commands cmds[] =
    {
        {16, {"Hammond Organ"}},
        {17, {"Percussive Organ"}},
        {18, {"Rock Organ"}},
        { 0, {""}}                   // end of list marker
    };

Additionally, it seems that it always should be written as:

    struct commands cmds[] =
    {
        // here your code
    };

If you have disabled warnings in your compiler, enable them again - and try to write program the way that you will newer receive warnings.

Thanks for your answer. It helped me a lot.

There must be something wrong with the simulator (Simulator for Arduino - version 1.11E Designed by Virtronics).
In the meantime I received the Mega 2560 board and both char pointer notation (char *) and array notation (char[]) work well with the board.
The compiler (Arduino IDE v. 1.8.10) really produces warnings:
ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings].
Perhaps the simulator is more meticulous than the compiler and therefore refuses to work with a code thar generates warnings.


message:
How to use a potentiometer to access data within a 2 dimensional array?

I'm trying to create a 2D array of notes that are split into 3 scales. There are 3 notes in each scale. There are 3 buttons to play each note and I want to use an available potentiometer to select each of the scales to be played.

Despite my searching I cannot understand how to achieve this correctly. So far this is what I have.

Using an Arduino Uno:

    // musical notes
    int C = 1046;
    int D = 1175;
    int E = 1319;
    int F = 1397;
    int G = 1598;
    int A = 1760;
    int B = 1976;
    int C1 = 2093;
    int D1 = 2349;

    const int numScales = 3;
    const int numNotesPerScale = 3;

    const int  notes[numScales][numNotesPerScale] = {
      {C, D, E},
      {F, G, A},
      {B, C1, D1}
    };

    const int numberOfButtons = 3;
    int buttonPin[numberOfButtons] = {2, 7, 4};
    //int notes[numberOfButtons] = {C, D, E};
    int ledPin[numberOfButtons] = {11, 10, 9};

    int buttonState = 0;         // variable for reading the pushbutton status
    int speaker = 3;                 // name of the speaker key

    void setup() {

      for (int i = 0; i < numberOfButtons; i++) {
        pinMode(buttonPin[i], INPUT);
        pinMode(ledPin[i], OUTPUT);
      }
      pinMode(speaker, OUTPUT);     // set speaker to be an output
    }

    void loop() {
      int numScales = map(analogRead(A2), 0, 1023, 0, 2);
      //int numScales = analogRead(A2 / 341);

      for (int i = 0; i < numberOfButtons; i++) {
        checkButton(buttonPin[i], notes[i], ledPin[i]);
      }
    }

    void checkButton(int buttonPin, int note, int ledPin)
    {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if (buttonState == HIGH){
        digitalWrite(ledPin, HIGH);
        tone(speaker, note);                 // play the note
        delay(100);                       // wait for 1/10th of a second
      }  } else {
        digitalWrite(ledPin, LOW);
        noTone(speaker);                  // stop playing the note
      }
    }

body:
Using the Arduino `map()` function seems a reasonable approach to this, however you have a problem with the indexing.

    if (numScales == 3); {

Is probably *not* what you want, as that condition can never be true since you set it to something in the range of 0-2 before you reach this check.

Considering only the relevant dimension, you a 3-element array, which will have legal elements numbers 0, 1, and 2

You call `map(analogRead(A2), 0, 1023, 0, 2);` which can produce an output in the range of 0-2, so far so good.

But then check for a value 3 which is not only illegal as in index to a 3-element array, but unable to be produced by your code.

Additionally you should probably stop trying to use the `numScales` variable to do double duty holding both the initial size and later also the *current index*.  And you should probably pass that as an argument, rather than make it a global variable.

You are also failing to ever use the current scale as an index into the notes array.  The syntax of double array indexing would be `notes[x][y]` but of course this should only be done with indicies to elements that exist.

It would probably also be a good idea to add some debug output of the internal logic, for example print both the raw ADC reading and the result of mapping that to the selected "scale".


body:
    // musical notes
    int C = 1046;
    int D = 1175;
    int E = 1319;
    int F = 1397;
    int G = 1598;
    int A = 1760;
    int B = 1976;
    int C1 = 2093;
    int D1 = 2349;

    const int columns = 3;
    const int scales = 3;
    int potVal = 0;
    const int  notes[scales][columns] = {
      {C, D, E},
      {F, G, A},
      {B, C1, D1}
    };

    const int numberOfButtons = 3;
    int buttonPin[numberOfButtons] = {2, 7, 4};
    int ledPin[numberOfButtons] = {11, 10, 9};

    int buttonState = 0;         // variable for reading the pushbutton status
    int speaker = 3;                 // name of the speaker key

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

      for (int i = 0; i < numberOfButtons; i++) {
        pinMode(buttonPin[i], INPUT);
        pinMode(ledPin[i], OUTPUT);
      }
      pinMode(speaker, OUTPUT);     // set speaker to be an output
    }

    void loop() {
      int potVal = map(analogRead(A2), 0, 1024, 0, 3);
      Serial.println(notes[2][2]);
      for (int i = 0; i < numberOfButtons; i++) {
        //checkButton(buttonPin[i], notes[scales][columns], ledPin[i]);
        checkButton(potVal,i);
      }
    }

    void checkButton(int scaleNum, int buttonNum)
    {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin[buttonNum]);

      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if (buttonState == HIGH) {
        digitalWrite(ledPin[buttonNum], HIGH);
        tone(speaker, notes[scaleNum][buttonNum]);                 // play the     note
        delay(100);                       // wait for 1/10th of a second
      } else {
        digitalWrite(ledPin[buttonNum], LOW);
        noTone(speaker);                  // stop playing the note
      }
    }


message:
about receiving float on matlab from ATmega32 Avr

****i am using ATmega32 to send float and want to receive it on matlab,i send 4.85 from ATmega32 but on matlab i receive 4.260233679216239e-31...can any one help me..thanks in advance**
**

        //Atmel studio code++++code for sending float from Atmega32
        union abc{ float fo; unsigned long lo; };
     union abc data;
    int main(void)
     { usart_init();
     data.fo=4.85;
     while(1) {
    for(int i=0; i<=24; i+=8)
    {
        uart_send(data.lo>>i); }}}

     //Matlab code for receiving float
    s=serial('COM1','BaudRate',9600);
    fopen(s);
    out=fread(s,1,'single');
     fclose(s);

body:
The binary representation of 4.260233679216239e-31 is `0x0d0a40a3`. The
first two bytes (in big endian format) are `0x0d` and `0x0a`, which
happen to be the ASCII characters CR and LF. These characters, in
tandem, are often used as line terminators. My guess is that
`uart_send()` is not doing what you think...

I suggest using `Serial.write()` instead. This way you won't have
unwanted line terminators. And it will also make your problem on-topic
with respect to this site.

Also, do not send the bytes repeatedly, send them only once, on demand.
If you send them continuously, Matlab may catch the serial stream in the
middle of a number, and assemble the bytes in the wrong order.


body:
i found the solution for this problem, i set a header before sending the data from ATmega32,and on Matlab i check the frame ,if it received correctly,i receive the data

    //ATmega32 code
        float x =215.5;
        unsigned char *ptrx;
        int main(void)
        {   usart_init();
         //data.fo=12.85;

         ptrx=( unsigned char *) &x;
           while(1)
           {
         uart_send(0xAA);//equals to 170
         for(int i=0;i<4;i++){
         uart_send(*(ptrx+i));}

         x++;}}
        //on Matlab
        s=serial('COM1','BaudRate',9600);
        fopen(s);
         i=1;
        while i<1000
            header =fread(s,1,'uint8');

            if header==170//equal to 0xAA

         out=fread(s,1,'float');
        data(i)=out;

         i=i+1;
            end
         end
        fclose(s);


message:
Arduino IDE gives elf but does not give hex file

Arduino IDE give .elf file but does not generate .hex file.

Show verbose output during: compilation is already selected.

/Users/username/Library/Arduino15/packages/Seeeduino/tools/arm-none-eabi-gcc/4.8.3-2014q1/bin/arm-none-eabi-size -A /var/folders/_6/5v2q3kbs09b7fhtpnxj_zgt00000gn/T/arduino_build_274647/kuzu.ino.elf

Thanks...

body:
Arduino IDE can generate .hex file. The menu choice is Sketch:Export compiled binary.

Two files are created:
your_sketch_name_.ino.standard.hex
your_sketch_name_.ino.with_bootloader.standard.

The second one contains the basic bootloader as well.
Both are stored in the your_sketch_name directory that the IDE compiles and saves in to.

Edit: If you are using a non-AVR uC, I don't know if the command works - or exists even.


body: As I learnt, It does not generate .hex file for some board. If I change board in Arduino IDE it gives .hex file. It is something about CPU. Thanks for your answers


message:
How to link a computer processor to an Arduinno on a board?

I am completely new to Arduinno, so please forgive if the question is stupid.

Here is the problem: I have a project where I want an Arduino (or similar microchip board) to handle some sensors and actuators. But I need very advanced "artificial intelligence" to handle the data provided by those sensors.
There are two major obstacles for placing this intelligence on the Arduinno, according to my researches.

- First, the Arduinno is coded in a language similar to C: I could of course find a way to write the intelligence, but it will be a time-consuming task for the developper
- Second, I might encounter a problem with memory: I will store heavy matrix of data, do complicated calculation, and this might be too much for an Arduinno
- Third, I read on stackexchange that there are some ways to compile Python code on Arduinno boards, such as the Arduinno Mega. So I can code this intelligence in Python (which is an easy task), and compile the resulting code on Arduinno. However, I will reach a caveat: some libraries I will use will be entirely compiled, and this will take too much memory on an Arduinno (such as the second issue I mentionned)

So I have another solution, but I am not sure if it is state-fo-the-art, or even a feasible solution:
I would like to separate two tasks:

- Write an Arduinno code to handle the sensors and create numeric data
- Write a Python code on my computer and compile it as an executable file on my computer
- Then somehow, I "extract" the processor of my comouter (Intel, by the way) and I plug it on the Arduinno board. The Arduinno sends the data to the processor, and the processor runs permanently the Python file and gives back data

So question:

- Is it possible overall?
- Was it ever made?
- What communication links are good for exchanging data between processor and Arduinno microchip: USB, Serial, Ethernet?
- How can I handle the input of the processor, so that it collects data from the Arduinno and then uses it in the Python code?

body: I suggest that you use a different family of processor than the 8-bit AVR chips that are supported  by the Arduino IDE (and please fix your spelling errors, all the double-letter words are very distracting). A good example might the the Teensy 3.2 or Teensy 3.6 offered here  https://www.pjrc.com/  "Version 3.6 features a 32 bit 180 MHz ARM Cortex-M4 processor with floating point unit" Arduino is programmed in C++, see if your code can be exported in C++ and import it into the IDE for compiling for the selected uC.


body:
It sounds like you need a lot of compute power. You can either put the sensors and AI on one device (and @majenko's suggestion of a Raspberry Pi would be a direction to pursue) or you need two devices, one to manage the data collection - Arduino, perhaps -  and one to do the AI. We don't know enough about your post-processing and AI to make a good recommendation, but, as you already have a PC with Python running on it, an Arduino talking to the PC would be a good start.

You didn't say which Arduino you're considering, but as most people mean "Uno" when the speak of a generic Arduino, I'd just suggest that an Uno is far too under-resourced for the post-processing part of your project, but probably ideal for the data collection. Cross-compiling your Python code for an Uno still doesn't address its processing speed and memory size limitations.

There are, of course, a lot of "Arduino" products, some with considerably more resources, that may approach your needs - I'm thinking of the Arm-based boards, here - but I've no way of evaluating your project needs at that level.

My own first approach would be to use what you have, to start with: an Uno collecting data and sending it to your PC. Once you have something running, you'll understand the needs and issues better and if you still want a stand-alone solution at that point, you'll be much better able to make that choice.


body:
I may handle this case like using [pyserial][1] library I just log the data to my laptop and then using python to do your Advance AI code part.

 1. Send the sensor data as a combined String via Arduino serial port.
 2. read it using pyserial library
 3. add a data logging mechanism if you need or parallel process the data you gathered serially by cast them to their own data type.

Hope this may help you.

Thank you

  [1]: https://pyserial.readthedocs.io/en/latest/shortintro.html


body: For AI use there is the K210 based sipeed maix board. Dual core 400MHz, plus an AI coprocessor.


message:
How to (optimally) fetch a button press?

For my hardware, I need to check if the button was pressed, but I need to do things only once every half a second.

`if (digitalRead(pin) == HIGH)
{
    doStuff();
    delay(500);
}`

The above does not work, because I have to check other things in the main loop as well.

body:
You should use the `millis` function (see [millis][1]).

Create a variable of type `unsigned long` and check it against the current time, with some offset.

See also the [debouncing][2] example, how to use this function and maybe you want to implement the debouncing too.

  [1]: https://www.arduino.cc/reference/en/language/functions/time/millis/
  [2]: https://www.programmingelectronics.com/tutorial-19-debouncing-a-button-with-arduino-old-version/


message:
Powering the Arduino with a battery and reading the battery voltage

I am trying to display the battery level as it is being used to power the arduino.

I have tried powering the Arduino through the USB and the battery voltage is read accurately when compared to the multimeter reading.

But when the battery is powering the arduino and being read, it keeps displaying 5.00 V, when it should not be.

Just wondering what might be happening and how I can go about resolving this issue.

I have been trying to research some answers, and came across something about an 1.1 V reference voltage, but not entirely sure what they mean.

Here is my code for reference:

```
#include <SoftwareSerial.h>
SoftwareSerial BTserial(10,11);

int battPin = A1;

void setup() {
  pinMode(battPin, INPUT);
  BTserial.begin(9600);
  Serial.begin(9600);
}

void loop() {
  int voltReading = analogRead(battPin);
  float volts = (voltReading/204.6);
  BTserial.print(volts);
  BTserial.print(";");
  Serial.println(volts);
}
```

I am using a 3.7 V Lipo battery. It is connected to A1 and also Vin.

body:
You need to divide down the battery voltage into the 1.1V max range, and use the Internal bandgap voltage reference for the ADC conversions.

Connect the Battery to VCC, not Vin, you don't want it going thru the regulator.


body:
AFAIK, Arduinos are set up to use their operating voltage as the `analogRead` reference voltage by default.

So what I think is happening is that you are trying to measure the battery voltage *with the battery itself as a reference voltage.*

This will, of course, always show "full scale".

You could use a voltage divider to bring the measured battery voltage down to about 1V (max) and use the internal reference of 1.1 V for measuring.

Note that the 1.1 V internal reference is stable, but not necessarily exactly 1.1 V.


body: If you want measuring a "battery level" in mAh for example, you must measure Voltage AND Current, so INA219 is a better deal (it is a I2C control).


message:
NodeMCU second HARDWARE serial TX as a debug port

I'm using a NodeMCU board to send commands to my home electricity switching box - using RS485 communication.

For that, I've connected MAX485 TTL-to-RS485 converter module to my TX and RX pins.

Currently, I can see the serial commands (that my program sends via RS485) also on my Serial monitor (in Arduino IDE), because the CH341 on the NodeMCU is bridged to the serial pins of it.

My problem is that if I want to send debug strings to my Serial monitor (like 'time was updated using NTP') - the RS485 bus will get them also.

I found some documentation about second TX pin available that can be used for debug messages, but I have 2 questions:

1. Will it be a HARDWARE port? I don't want to load another library and deal with software Serial ports.
2. Is there a way to get its output via the USB cable connected between the NodeMCU and my computer? Or will I have to connect another USB converter externally to that port to get its output into computer?

Many thanks!

body:
ESP8266 Arduino core has Serial1 as write only hardware Serial on io 2 as TX. IO 2 is D4 on NodeMcu and Wemos D1 mini.

To use the USB chip of the NodeMcu/Wemos with Serial1 you could wire io 2 (D4) to TX. This would not disturb the flashing mode, because bootloader would still listen on standard Serial pins. I tested it.

And for RS485 adapter swap the Serial to io 13 (D7) as RX and io 15 (D8) as TX with the [Serial.swap() command][1].

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/reference.html#serial


message:
Coding issue with for loop

I have an issue with this piece of code concerning the use of 3 capcitance sensors each outputting a midi note chosen from one of three scales selected with a pot. Regarding the sensors triggering notes and the pot selecting scales, everything is perfect.
However, each sensor will play each of the scale's notes by itself with each finger press. This of course is not what I am intending as each sensor should only trigger its corresponding note. Thanks for any clues and tips!!

        #include <SPI.h>
    #include <CapacitiveSensor.h>
    #include <MIDI.h>
    MIDI_CREATE_DEFAULT_INSTANCE();
    // midi notes
    int c3 = 36;
    int d3 = 38;
    int e3 = 40;
    int g3 = 43;
    int a3 = 45;
    int c4 = 48;
    int d4 = 50;
    int e4 = 52;
    int g4 = 55;
    int a4 = 57;
    int c5 = 60;
    int d5 = 62;
    int e5 = 64;
    int g5 = 67;
    int a5 = 69;
    int c6 = 72;

    /////// code & 2d array for scale selection
    const int columns = 3;
    const int scales = 3;
    int potVal = 0;
    const int  notes[scales][columns] = {
      {c3, d3, e3},
      {c4, d4, e4},
      {c5, d5, e5}
    };

    const int numberOfSensors = 3;
    int sensorPin[numberOfSensors] = {38, 39, 40};
    /////////

    static const unsigned ledPin1 = 22;      // LED pin on Arduino Mega
    static const unsigned ledPin2 = 23;
    static const unsigned ledPin3 = 24;

    int val = 10; // this value is best around "10". works with "multiply"
    // and "Threshold" to enable Polyphony!
    int Threshold = (0); //Threshold of triggered mp3
    int Multiply = (0);  //increases or decreases the overal sensitivity

    CapacitiveSensor   cs_2_38 = CapacitiveSensor(2, 38); //Mega sensor pins
    CapacitiveSensor   cs_2_39 = CapacitiveSensor(2, 39);
    CapacitiveSensor   cs_2_40 = CapacitiveSensor(2, 40);

    void setup()
    {
      for (int i = 0; i < numberOfSensors; i++) {
        pinMode(sensorPin[i], INPUT);
        Serial.begin(9600); //midi(31250)

        pinMode(ledPin1, OUTPUT);
        pinMode(ledPin2, OUTPUT);
        pinMode(ledPin3, OUTPUT);

      }
    }
    void loop()
    {
      int potVal = map(analogRead(A2), 0, 1024, 0, 3);
      for (int i = 0; i < numberOfSensors; i++) {
        checkSensor(potVal, i);
      }
    }
    void checkSensor(int scaleIndex, int columnIndex)
    {
      static boolean lastSensorHit1 = false;
      static boolean lastSensorHit2 = false;
      static boolean lastSensorHit3 = false;

      bool sensorHit3 = cs_2_40.capacitiveSensor(Multiply) / val > (Threshold);
      bool sensorHit2 = cs_2_39.capacitiveSensor(Multiply) / val > (Threshold);
      bool sensorHit1 = cs_2_38.capacitiveSensor(Multiply) / val > (Threshold);

      Multiply = map(analogRead(A0), 0, 1023, 150, 5);
      Threshold = map(analogRead(A1), 0, 1023, 150, 5);

      long total1 =  cs_2_38.capacitiveSensor(Multiply);
      long total2 =  cs_2_39.capacitiveSensor(Multiply);
      long total3 =  cs_2_40.capacitiveSensor(Multiply);

      int Art1 = total1 / val;
      int Art2 = total2 / val;
      int Art3 = total3 / val;

      if (sensorHit1 != lastSensorHit1)

        if (sensorHit1 && !lastSensorHit1)
        {
          digitalWrite(ledPin1, HIGH);
          MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 80, velo 127 on channel 1)
          MIDI.sendControlChange(64, 127, 1);
        }

        else {
          digitalWrite(ledPin1, LOW);
          MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
          MIDI.sendControlChange(64, 0, 1);
        }

      if (sensorHit2 != lastSensorHit2)

        if (sensorHit2 && !lastSensorHit2)
        {
          digitalWrite(ledPin2, HIGH);
          MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 79, velo 127 on channel 1)
          MIDI.sendControlChange(64, 127, 1);
        }

        else {
          digitalWrite(ledPin2, LOW);
          MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
          MIDI.sendControlChange(64, 0, 1);
        }

      if (sensorHit3 != lastSensorHit3)

        if (sensorHit3 && !lastSensorHit3)
        {
          digitalWrite(ledPin3, HIGH);
          MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);    // Send a Note (pitch 78, velo 127 on channel 1)
          MIDI.sendControlChange(64, 127, 1);
        }

        else {
          digitalWrite(ledPin3, LOW);
          MIDI.sendNoteOff(notes[scaleIndex][columnIndex], 0, 1);     // Stop the note
          MIDI.sendControlChange(64, 0, 1);
        }

      lastSensorHit1 = sensorHit1;
      lastSensorHit2 = sensorHit2;
      lastSensorHit3 = sensorHit3;

    }

body:
I am just learning this program so I could be way off on this and I apologize if I am.

Instead of the loop inside of ````void setup()```` initialize each pin individually. Also you are telling the system to start the MIDI and set the ````pinMode```` 3 times.

Inside the ````Void checkSensor```` function you set all the ````sensorHits```` every time the function runs, you might save a little bit you do ````lastSensorHit(i)````.

I just noticed you have the if command running this function as ````(int i = 0; i < numberOfSensors; i++)````.  You don't have a sensor 0, so you might want to change that to ````(int i = 1; i < numberOfSensors+1; i++)// or just change it to 4````.

Inside the function checkSensor, it doesn't look your variable val has a value.

 ````if (sensorHit1 != lastSensorHit1)```` this is still under the same function as before and it is going to run once per channel that you specified in the controlling if function.
Maybe move this into the void loop() or create its own function?


body:
Well after more tinkering I found that the one change that fixed everything was simply this (in the if/else statements).....changing `MIDI.sendNoteOn(notes[scaleIndex][columnIndex], 127, 1);` to `MIDI.sendNoteOn(notes[scaleIndex][0], 127, 1);` [columnIndex] needs to be a [0], [1] or [2] representing one of three scales in the assigned array. This is fine as I'm writing out the code for a few sensors. However, for 16 sensors I'm going to have to use a for loop ....Thanks for all your help! Here's the full code for anyone who needs it...including some alterations to the leds...

````````#include <SPI.h>
#include <CapacitiveSensor.h>
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();

 int c3 = 36;
 int d3 = 38;
 int e3 = 40;
 int g3 = 43;
 int a3 = 45;
 int c4 = 48;
 int d4 = 50;
 int e4 = 52;
 int g4 = 55;
 int a4 = 57;
 int c5 = 60;
 int d5 = 62;
 int e5 = 64;
 int g5 = 67;
 int a5 = 69;
 int c6 = 72;

const int columns = 3;
const int scales = 3;
int potVal = 0;
const int  notes[scales][columns] = {
  {c3, d3, e3},
  {c4, d4, e4},
  {c5, d5, e5}
};
const int numberOfSensors = 3;
const int sensorPin[numberOfSensors] = {38, 39, 40};

const int ledPin[numberOfSensors] = {22, 23, 24};

const int val = 10; // this value is best around "10". works with "multiply"
// and "Threshold" to enable Polyphony!
int Threshold = (0); //Threshold of triggered mp3
int Multiply = (0);  //increases or decreases the overal sensitivity

CapacitiveSensor   cs_2_38 = CapacitiveSensor(2, 38);
CapacitiveSensor   cs_2_39 = CapacitiveSensor(2, 39);
CapacitiveSensor   cs_2_40 = CapacitiveSensor(2, 40);

void setup()
{
  Serial.begin(9600);//midi(31250)
  for (int i = 0; i < numberOfSensors; i++) {
    pinMode(ledPin[i], OUTPUT);
}
}
void loop()
{
    int potVal = map(analogRead(A2), 0, 1024, 0, 3);
for (int i = 0; i < numberOfSensors; i++) {
    checkSensor(potVal,i);
  }
}
void checkSensor(int scaleIndex, int columnIndex)
{
  static boolean lastSensorHit1 = false;
  static boolean lastSensorHit2 = false;
  static boolean lastSensorHit3 = false;

  bool sensorHit1 = cs_2_38.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit2 = cs_2_39.capacitiveSensor(Multiply) / val > (Threshold);
  bool sensorHit3 = cs_2_40.capacitiveSensor(Multiply) / val > (Threshold);

  Multiply = map(analogRead(A0), 0, 1023, 150, 5);
  Threshold = map(analogRead(A1), 0, 1023, 150, 5);

  if (sensorHit1 != lastSensorHit1)

    if (sensorHit1 && !lastSensorHit1)
    {
      digitalWrite(ledPin[0], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][0], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[0], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][0], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }
    if (sensorHit2 != lastSensorHit2)

    if (sensorHit2 && !lastSensorHit2)
    {
      digitalWrite(ledPin[1], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][1], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[1], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][1], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }
    if (sensorHit3 != lastSensorHit3)

    if (sensorHit3 && !lastSensorHit3)
    {
      digitalWrite(ledPin[2], HIGH);
      MIDI.sendNoteOn(notes[scaleIndex][2], 127, 1);
      MIDI.sendControlChange(64, 127, 1);
    }

    else {
      digitalWrite(ledPin[2], LOW);
      MIDI.sendNoteOff(notes[scaleIndex][2], 0, 1);
      MIDI.sendControlChange(64, 0, 1);
    }

  lastSensorHit1 = sensorHit1;
  lastSensorHit2 = sensorHit2;
  lastSensorHit3 = sensorHit3;

}````````


message:
SIM7600 A-H not responding directly when connected through pins

I am working on a project which utilizes three components:

 1. Arudino Pro Mini(5v)
 2. Breakout SIM7600 A-H from [AND technologies][1]
 3. 9V Battery (connected to RAW and GND on the Arduino board)

I am trying to communicate through the device using the pins provided on the SIM board, which unfortunately is not successful.

**I am able to connect to the board directly using an usb-c cable. After installing the right [drivers,][2] I am able to communicate with the board using AT commands from my Windows PC.**

However, I want to be able to send AT commands through the arduino. The set up looks like this:
I connect the following pins of arduino mini and SIM 7600A-H.

 - SIM 7600 TXD --> Arduino Pin 2
 - SIM 7600 RXD --> Arduino Pin 3
 - SIM 7600 Supply -->  5V
 - SIM 7600 GND -->  GND

The code that I am using, I tried it with every possible baud rate:

```c++
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}
```
After sending an AT command, there is no response, the module has both LED's on, indicating that it is up and running.

  [1]: http://www.thebackshed.com/forum/uploads/Grogster/2018-07-24_122343_BK-SIM7600_Board_user_manual_V1.0.pdf
  [2]: https://github.com/botletics/SIM7000-LTE-Shield/wiki/USB-Drivers

body:
Is your issue resolved? If not...
I'm using the same module and having the same problem.
Jump the resistors on the R and T pins on the module, they seem to be introducing high impedance on the line. After doing that on my module, the UART worked.

Now my problem now is the module is sending some weird characters, maybe my baud rate is not same or etc, still under investigation.


body:
The SIM7600 UART interface works with 1.8 levels:
[![enter image description here][1]][1]

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

I'm guessing that the AND board has a level shifter from 3.3 to 1.8 to work with the 7600. Since your Arduino Por Mini is a 5V board your UART levels must be at 5V too, try adding a voltage divider to bring down the UART to 3.3V.

Also try lowering the SIM7600 baudrate, the software_serial library doesn't work good with high speeds.


message:
Serial doesn't initialise on Arduino Mega 2560 when not powered via the USB port

I am working on a project with a Mega 2560 and a Sim800L module.

Everything works fine, however if i don't connect the USB port (at least once) and power only externally (either by Vin unregulated 7-12V or 5V regulated pin)
the program will seem not to initialize serial in setup().

I found this which is related to the issue but not a proper workaround:
https://forum.arduino.cc/index.php?topic=24642.0

edit: I can confirm using a resistor to short pins 0+1 together (serial) works but it is not a proper solution. This means you have to disassemble your project to access the resistor or add a switch if you want to use USB to debug later or upload new code. Another workaround which i need to test is to remove all Serial code (because i can in my specific project), but again this is not a proper solution.
Any ideas please?

edit2:
for comments

    if(SIM900.available()>0){
    // AT command to set SIM900 to SMS mode
    SIM900.print("AT+CMGF=1\r");
    delay(100);
    // Set module to send SMS data to serial out upon receipt
    SIM900.print("AT+CNMI=2,2,0,0,0\r");
    delay(100);
    textMessage = SIM900.readString();
    textMessage.toUpperCase();
    Serial.print(textMessage);
    delay(10);
    }

    if(textMessage.indexOf("SET PHONE")>=0){
    // Set phone number to receive notifications
    phoneNumber = textMessage.substring(9,21);
    Serial.println("Phone number set to: " + phoneNumber);
    String message = "Notification number set to: " + phoneNumber + "\nSend 'Help' for additional commands.\nNote in case of reset number returns to hardcoded default";
    sendSMS(message);
    Serial.println("Confirmication of phone number change sent");
    textMessage = "";
    }

body:
Ok i found the issue and the solution.

For some reason it seems that while the MCU is running Setup(); hardware or software serial don't work properly.

In my case i have code that set the SIM module to SMS mode and to send those messages to the serial port.

For some reason it doesn't send them (or probably the module is not ready to accept them).

Connecting the USB cable reset the arduino and run setup() when opening the serial monitor setting the module in the correct mode.

Adding this code in the main loop solves this issue even though i have them powered both by the same step down converter.

edit: That turns out 1 hour later after debugging more is not exactly a proper solution to the issue.
 That command to set into SMS mode only works when you are connected to the network.

I have a check for that and a reset function.

So now at Setup() i wait 10s for the module to boot up so it is ready to open a serial port, then i check if it is connected to the network before i send the commands to set into SMS mode.

Example:
````
// Initializing serial commmunication
Serial.begin(57600);
delay(10000);

while (ini){
    Serial3.begin(57600);
    delay(1000);
    Serial3.print("AT+CGREG?\r");
    delay(100);
    netStatus = Serial3.readString();
    if (netStatus.charAt(22) == '5' || netStatus.charAt(22) == '1') {
         digitalWrite(LED_NET, HIGH);
         ini=false;
         }
    else {
        digitalWrite(LED_NET, LOW);
        digitalWrite(resetPin, LOW);
        delay(2000);
        digitalWrite(resetPin, HIGH);
        delay(30000);
        }
}
  Serial.print("SIM800 ready...");

  // AT command to set SIM800 to SMS mode
  Serial3.print("AT+CMGF=1\r");
  delay(100);
  // Set module to send SMS data to serial out upon receipt
  Serial3.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);


message:
arduino uno freezes

Is there a reason why my Arduino Uno freezes after a few minutes of running with power coming from a usb cable connected to my pc?

    #include <GY6050.h>
    #include <Wire.h>
    #include <VarSpeedServo.h>

    #define angle1 20
    #define angle2 90

    #define Sensor_BL A0
    #define Sensor_BR A1

    VarSpeedServo servo;

    GY6050 gyro1(0x68);
    GY6050 gyro2(0x69);

    int X = 0;
    int Y = 0;

    int y1_axis = 0;
    int y2_axis = 0;

    int sensorBL;
    int sensorBR;

    int speed = 0;
    int angle = 0;

    int prev_y1_axis = 0;
    int y1_hold = 0;
    unsigned long timer;
    int start = 1;
    byte step = 0;
    String steps , laststep;
    int freq;

    void setup() {
      Serial.begin(9600);
      Wire.begin();
      gyro1.initialisation();
      gyro2.initialisation();
      delay(100);
      servo.attach(8);
      servo.write(90);
    }

    void loop() {
      y1_axis = gyro1.refresh('A', 'Y');
      y2_axis = gyro2.refresh('A', 'Y');
      sensorBL = analogRead(Sensor_BL);
      sensorBR = analogRead(Sensor_BR);

      //0 right - 90 centr - 180 left

      if (sensorBL > 250) {
        speed = map( sensorBL , 0 , 1023 , 0 , 255);
        if (sensorBL < 700) { //less pressure 90+20=110
          servo.write(95 , speed);
          angle = 95;
        }
        else if (sensorBL > 700) { //more pressre 90+90 = 180
          servo.write(105 , speed);
          angle = 105;
        }
      }
      else if (sensorBR > 250) {
        speed = map( sensorBR , 0 , 1023 , 0 , 255);
        if (sensorBR < 700) {
          servo.write(95 , speed);
          angle = 95;
        }
        else if (sensorBR > 700) {
          servo.write(105 , speed);
          angle = 105;
        }
      }
      else if ((start == 0 || millis() - timer > 800) && y1_axis > -90 && y1_axis < 20 && y2_axis > -90 && y2_axis < 20 && sensorBL < 10 && sensorBR < 20) //flat dead end no servo movement - center position - can we separate on different lines the pressure sensor and accell so that I can set the dead end value separately for the press sens and acc ?
      {
        servo.write( 85 , 15);
        //Serial.println("Servo goes to zero");
        start = 1;
        step = 0;
        angle = 0;
        steps = "0";
      }
      else if ((y1_axis < 60 & y1_axis >40) && (step == 0 || step == 2))
      {
        step = 1;
        steps = "1";
      }
      else if ((y2_axis < 55 & y2_axis > 40) && (step == 0 || step == 1))
      {
        step = 2;
        steps = "2";
      }

      if (!steps.equals(laststep)) {

        if ((step == 1 || step == 2) && millis() - timer <= 700) {
          if (freq > 1) {
            servo.write(70 , 20);
            angle = 70;
          }
          else {
            servo.write(78 , 20);
            angle = 78;
          }
          freq++;
        }
        else if ((step == 1 || step == 2 && millis() - timer > 750)) {
          servo.write(78 , 20);
          angle = 78;
          freq = 0;
        }

        timer = millis();
      }
      //Serial.println("Y1: " + String(y1_axis) + " Y2: " + String(y2_axis) + " S1: " + String(sensorBL) + " S2: " + String(sensorBR) + " Millis: " + String(millis() - timer) + " Step: " + String(steps) + " Last: " + String(laststep) + " Angle: " + String(angle));
      Serial.println("Millis: " + String(millis() - timer) + " Angle: " + String(angle));

      laststep = steps;

    }

---

I am using the pc usb power cable to power on the arduino and 2 accelerometers and one SG90 hobby servomotor. Would the best way power on the 1 servo with its own power supply ?

What power supply would you suggest for 1 servomotor?

When not connected to the pc, I use 9v battery to power on together the arduino and the one servomotor

thanks!

---

It is the part of the code for moving forward and backward in this locomotion system I came up with

https://github.com/marcob2178/Arduino-Based-Game-Locomotion

https://www.youtube.com/watch?v=OYTlF2GhXpQ

Sensors are mounted on shoes

body:
You haven't said or shown how your servo is powered but both the Arduino power supply is limited and your computer's USB power has a protective limit. You can power an SG90 hobby servo from the Arduino, but any larger servo needs its own supply, with only the PWM signal being taken from the Arduino. If the servo (or any other device or collection of devices) exceeds the capabilities of the Arduino's power supply, its output voltage will fall. One of the consequences of that is that the MCU stops. Or if your computer's USB supply is exceeded, it will shut down protectively.

My guess is you're powering your motor from the Arduino and it's starving the MCU.


message:
How to burn bootloader and upload sketches on custom arduino?

Ive turned a project I breadboarded with arduino and other modules into one pcb on EAGLE. The pcb includes the ATMEGA328p smt version that doesn't have the bootloader installed. My question is then what module or components can I use to burn the bootloader onto the atmega and upload programs to it together?

body:
You can use a second Arduino as a standalone programmer for it, either to upload your sketch directly, or to upload a bootloader (after which you'd upload your sketch in the normal way). The example program, ArduinoISP, uploaded into the second Arduino is what can do this. Here is a link to a [how-to article][1] for doing just that.

If you haven't already populated your PCB, good - sometimes your external (to the MCU) circuitry can interfere - but it's worth a try, even if you have.

  [1]: https://www.electronicshub.org/burn-bootloader-on-atmega328/


message:
How to count positive electrical pulses?

I have a device that has one blinking LED.

I want to count the number of blinks. I planned to do it using Arduino. I will connect two terminals of LED input to Arduino digital input pins, and I will count the number of positive voltage pulses

I just want to know if it is possible? and if yes then can you please hint the code for the same?

body:
You should not count the number of pulses, but the number of transition from 0 to VCC volts or VCC to 0 volts (called rising resp. falling edge).

If you don't want to solder, you can also use a light dependent resistor (LDR) very close by the LED to measure the difference in brightness. See also chrisl's remark below.

The counting you can do manually (in a loop, check as often as possible or needed), or by setting up a timer to check for either rising or falling edges.

I will give the pseudo code so you can figure out the actual code:

    bool _ldrPin;
    unsigned long int _counter;

    setup()
    {
       // Set Serial
       Serial.begin(9600);

       // Set LDR
       setAnalogPin(X, INPUT);
       _ldrPin = readAnalog(X);
    }

    loop()
    {
        if (!_ldrPin && readAnalog(X) == HIGH)
        {
            // Rising edge, increase counter
            _counter++;
            Serial.Write(_counter);
            _ldrPin = true;
        }
        else if (ldrPin && readAnalog(X) == LOW)
        {
           // Falling edge, reset status
            _ldrPin = false;
        }
    }


body:
Detecting the LED Pulses
============================
You want to detect each LED pulse. For this you will need **edge detection code**. There is an Arduino example built into the IDE and information describing the function here: [https://www.arduino.cc/en/Tutorial/BuiltInExamples/StateChangeDetection][2]

To add to the Arduino explanation, you can either detect the rising edge (ie. the transition from a LOW to a HIGH) or the falling edge (ie. the transition from a HIGH to a LOW). I personally prefer the following code to detect a rising edge. In simple terms the code can be translated to this:

    if ( (lastLedState == LOW) && (ledState == HIGH) )

where `ledState` would be assigned by a `digitalRead` and `lastLedState` would record the value of `ledState` at the end of the loop function (ie. just before it reads in the led states again).

Full Code
===============
Now if we optimise the above statement and put it into context:

    unsigned long int pulseCounter = 0;
    const int LedInput = 3;    // Digital input 3
    bool ledState = 0;
    bool lastLedState = 0;

    void setup() {

    }

    void loop() {
        ledState = digitalRead(LedInput);

        // If the LED turns ON
        if (ledState && !lastLedState)
        {
            // Increment your counter
            pulseCount++;
        }

        // Update LED flag
        lastLedState = ledState;
    }

  [2]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/StateChangeDetection


message:
LCD connection problem

First of all, i have some problems with an lcd .
For a better understanding, the lcd datasheet could be found here:
[https://www.mikrocontroller.net/attachment/53098/DGF-12232-S1FBLY-325-17231-1006.pdf][1]

i want to connect it to arduino mega but it has 20 pins and i can't figure it out how it should be connected.
Could someone help me ?

  [1]: https://www.mikrocontroller.net/attachment/53098/DGF-12232-S1FBLY-325-17231-1006.pdf

body:
For those reading this answer prior to acquiring an LCD for an Arduino project, consider using a more common alpha / numeric LCD rather than a graphic LCD or GLCD.  Likely there will be more examples to follow as well as more software with more community support.

The linked to Graphical LCD (or GLCD) uses a [SED1520 controller][1].  Searching the Arduino community resulted in finding [this openGLCD project][2].  There may be others.  Looking [here][3] (near the end of 2019) we see the comment "added custom sed1520 init routine to fully initialize sed1520 chips" next to the sed1520_Device.h file.  Likely this project supports GLCD modules which use the SED1520 chip.

With regards to wiring GLCD module, on page 19 of the specifications linked to in the question, the table in section 5.1 lists the description of the 20 GLCD pins.

  [1]: http://www.hpinfotech.ro/SED1520.pdf
  [2]: https://bitbucket.org/bperrybap/openglcd/wiki/Home
  [3]: https://bitbucket.org/bperrybap/openglcd/src/master/device/