message:
Implement two processes at the same time

I am a beginner in arduino and due to the lockdown I have been learning it by implementing it on tinkercad. I have made a simulation where I have attached :

1. Servo Motor

2. Ultrasonic Sensor

3. Led Bulb

4. LCD display

to an arduino uno 3

My AIM :  When something falls under 30cm of the ultrasonic sensor, the servo motor starts from zero position and goes upto 180 degrees in a span of 20seconds and then goes back to its initial position. At the same time and led switches on for 20s and switches off when the motor returns back to its position.
I was able to successfully implement this. But then I added an lcd to show the time i.e time is initialized at 0seconds and then goes to 20 seconds and when the motor resets. Time also resets.

I was able to make a timer on another simulation and I tried to run it in this one by placing the code correctly but I am not able to figure out how?

The present code I have written keeps blinking the led at an interval of one second and the servo moves very very slowly.

Any sort of help will be amazing.

This is my [simulation](https://www.tinkercad.com/things/8vEXOf380IL), I have made it public, you may copy and simulate it if you have a tinkercad account. Even without an account you can see how it looks.

Here is the code:
(Please ask if you want me to add comments some areas)

```
//library code for lcd
#include <LiquidCrystal.h>
//setting up pins
const int rs = 9, en = 8, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

unsigned long readTime=20;

//servo motor
#include <Servo.h>
Servo servo_9;
int pos = 0;
//servo motor end

//ultrasonic sensor pin
const int pingPin = 12;

//lcd
signed short seconds;
char timeline[16];

void setup()
{

  servo_9.attach(13); //servo pin
  Serial.begin(9600);

  pinMode(11,OUTPUT);// led

  //lcd initialize
  lcd.begin(16, 2);
  lcd.print("Time : ");

}

void loop()
{

  long duration, cm;
  //Ultrasonic start
  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  cm = microsecondsToCentimeters(duration);

  // Print the distance
  Serial.print("Distance: ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  // ultrasonic end

  // the servo motor should activate when object is
  //less than 30cm close to the sensor

 if(cm < 30) {

  // sweep the servo from 0 to 180 degrees in steps
  // of 1 degrees
  for (pos = 0; pos <= 180; pos += 1) {

    // tell servo to go to position in variable 'pos'
    servo_9.write(pos);

     //LCD TIMER START
    lcd.setCursor(0, 1);
    sprintf(timeline,"%0.2d secs", seconds);
    lcd.print(timeline);
 delay(1000);
    seconds++;

    //led buld switch on
    digitalWrite(11,HIGH);

    // wait 20ms for servo to reach the position
    delay(200);

    //switch of the bulb
    digitalWrite(11,LOW);

  }

  //moving servo back to zero
  for (pos = 180; pos >= 0; pos -= 1) {
      // tell servo to go to position in variable 'pos'
      servo_9.write(pos);
      // wait 20 ms for servo to reach the position
      delay(20); // Wait for 15 millisecond(s)
     }

   } //if end

  delay(100);

}//loop end

//FUNCTIONS

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

```

body:
Think of an Arduino as a circus clown spinning plates. It has to spend very little time on any one plate, and then it can keep a lot of plates spinning, moving quickly from one to the next.

That's how "multi-tasking" works on a realtime device like an Arduino. You write a loop function that buzzes through a bunch of sub-tasks, spending a few microseconds on each one, and then repeats the process. Each plate (sub-task) gets a little bit of time on each pass, but only a little.

The `delay()` function is the death of that. If you're in a `delay()`, everything comes to a screeching halt. Your program stops checking for button presses, stops switching output pins to control your motors, etc. It's like the clown taking a coffee break. The plates start crashing to the ground.

You might get away with single-digit delays for things like timing changes in output state (and `delayMicroseconds()` is rarely a problem since those delays are so short), but a `delay(1000)` means everything comes to a screeching halt for a full second.

You need to refactor your code to get rid of calls to `delay()` with delay values of more than a few milliseconds. Do a search on "Arduino blink without delay" to figure out how.

Note that on a single core device with preemptive multi-tasking, the circus clown analogy still holds, but now the OS serves as the clown's manager. The OS schedules the clown's time, and tells it when to switch between plates. If the clown gets distracted by a particularly shiny plate and tries to spend too long on that plate, the OS forces the clown to switch plates. The OS also saves the clown's current state each time it switches away from a task, and restores that state when it returns to that task.

On A multi-core device with preemptive multi-tasking, the manager (OS) has a team of clowns (cores). Each clown (core) gets assigned to different plates (tasks), and all the clowns work at the same time (The cores run concurrently.) The OS has to make sure the clowns (cores) don't bump elbows (have conflicting access to the same memory or other resources.)


sender: user

message:
3 input (on/off/off with delay) to control 1device using ESP8266 as Web Server

I want to control one device in three ways : turn on / turn off / turn off with delay.
To do that i use an ESP8266 web server + android phone app.
The problem is that turn off with delay wont work.
It works with `delay()` but i dont want to use `delay()` as it stops other functions.
I would be grateful if you could help me.
here is my code :
```
#include <ESP8266WiFi.h>
const int device1 = 14;
unsigned long previousMillis = 0;
const long interval = 5000;
const char* ssid     = "****";
const char* password = "****";
#include <Arduino.h>
WiFiServer server(80);
String data = "";

void setup() {
 pinMode(device1, OUTPUT);
Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY);
WiFi.begin(ssid, password);
IPAddress ip(*,*,*,*);
IPAddress gateway(*,*,*,*);
IPAddress subnet(*,*,*,*);
WiFi.config(ip, gateway, subnet);
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected");

 server.begin();

 Serial.println(WiFi.localIP());
 }

void loop() {
    unsigned long currentMillis = millis();

  WiFiClient client = server.available();
 if (!client) {
   return;
 }

 while(!client.available()){
 }

 String req = client.readStringUntil('\r');
 client.flush();
 if (req.indexOf("/on") != -1)
   { digitalWrite(device1, HIGH);}
 if (req.indexOf("/off") != -1)
   { digitalWrite(device1, LOW);}

 if (req.indexOf("/delay") != -1)
 {
  unsigned long currentMillis = millis();
  unsigned long previousMillis = millis();
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    digitalWrite(device1, LOW);

}
}
```

sender: assistant

body:
You have various logic problems:

You block until WiFiClient has bytes available. Everything comes to a stop. So if you send a "/delay" command, it will receive and parse that command, turn on the device, then block again, indefinitely, until you send another command. Once you send another command, it will check the interval ONCE, and then lock up again. You need to rewrite your loop to check for bytes, read them if found, and do other work (like checking your time interval) if no bytes are available.

Next, your timing code is a mess. You only ever set currentMillis and previousMillis at the same time, so they will never be different. And you only ever check the times once when you first detect a "/delay" command.

Instead, refactor your logic. Only set previousMillis when you first detect the delay command, and then only compare if previousMillis to currentMillis if  previousMillis is not 0:

    if (req.indexOf("/delay") != -1)
    {
        previousMillis = millis();
    }

    if (previousMillis != 0 && millis() - previousMillis >= interval) {
        digitalWrite(device1, LOW);
        previousMillis = 0;
    }

 (Also note that you were declaring a second, independent variable  previousMillis inside your if statement, which only exists inside the curly braces for that if statement. Don't do that. Use the existing global variable you defined, as I show in my edited code.)


message:
what is good practice around initializing variables

Should vars be initialed when declared or in setup fuction?
 Safe to assume compiler will initialze?

Boolean x;      --- init to true/false here?
Void setup()
   .
   .            --- or init here?
   .

Void loop()
   If (x)       --- x is unknown state if not initialized.

body:
Initializing a global is appropriate if you know in advance that it should always have a given value at startup. The compiler will generate a globals image in ROM that will be copied into RAM before any of your code is executed.

> Safe to assume compiler will initialze?

The compiler will initialize to 0, a global not specifically initialized by you. Let's take the case of your Boolean. '0' means 'false', right? So 'x' is pre-initialized to 'false'. But I, as the reader (or yourself, six months later) may not know whether you intended this to be initialized to 'false' (the default value) or forgot to initialize it. Specifying it to be 'false' may not have any different effect on the code, but it does inform me or your future self, that you *meant* it to be set 'false' at startup. Remember that your code communicates to people as well as to the compiler. Write it so you or I will not only be able to understand it, but won't be able to misunderstand it.

If you initialize it in setup(), the compiler generates code in setup() specifically to do that. If the setup() function needs to decide during startup, what the initial value of that variable should be, then this is the place to do it. Otherwise, the extra code just takes up space in Flash. It's not any more harmful than wasting those few extra bytes of code-space, but it doesn't accomplish anything more than letting the globals image do it.

Whatever you did or didn't do with 'x' at load time or in 'setup()', it will persist into 'loop()', so 'x's state isn't unknown when you get there. (If I misunderstood that part of your question, please edit it in your question.)


body:
There is only one rule to follow, really:

**Never read a variable before writing a defined value to it.**

You don't need to write explicitly into a variable, because the C++ language distinguishes between two kinds of variables:

- *Static* variables are initialized to all zero bits, if no explicit initialization is done.
- *Automatic* variables are never automatically initialized. Their initial value is that of the memory cells they occupy, if no explicit initialization is done.

*Static* variables are defined outside any function or method, or with the keyword `static`.

*Automatic* variables are all others.

Example:

```
static int s1; // static, initialized to 0
int s2 = 42; // static, initialized to 42

void setup() {
    int a1; // automatic, has an unknown initial value
    static int s3; // static, initialized to 0
}

void your_function() {
    static int s4 = 23; // static, initialized to 23
    int a2 = 7; // automatic, initialized to 7 each time control flow comes here
}
```

All static variables are initialized exactly one time, before `main()` is called. Or in the case of Arduino, before `setup()` or any other method or function is called.

---

Oh, another quite important rule: Know, what you are doing, don't guess, be sure.

You might need to read the standard, or at least some good book.

If you use some rare feature, make it explicit or comment.

---

*Additional notes:*

The Arduino uses C++. This is a really different language than C.

You can think of `main()` as:

```
void main() {
    setup();
    for (;;) {
        loop();
    }
}
```


message:
Wire Library Timer Usage

I would like to know if the Wire Library is using a Hardware Timer from the Arduino Mega 2560. And If so which Timer it is.

As I am using the Timer 1. After implementing the Wire Library I have some strange things happening that are probably due to the Timer.

Thanks a lot.

body:
No, it's not.

It has its own timer called the "Bit Rate Generator Unit" which is controlled using the `TWBR` register.  It takes its time source direct from the main CPU clock and divides it down.


message:
Is it possible to exit a loop on the change of an input state?

I would like to exit a particular loop if the state of an input changes from LOW to HIGH. This is the current loop:

    void brakeFade() {
    pixels.clear();
    pixels.setBrightness(255);
    pixels.fill(16711680, 0, 0);

    for(int i=255; i>=10; i-=1) {
      pixels.setBrightness(i);
      pixels.show();
      delay(5);
      }
    for(int j=10; j<=255; j+=1) {
      pixels.setBrightness(j);
      pixels.show();
      delay(5);
}
}

I need that loop to exit if

    (digitalRead(brakeFeed) == LOW)

Changes to **HIGH** during the loop.

body:
figured it out:

    void brakeFade2() {
    pixels.clear();
    pixels.setBrightness(255);
    pixels.fill(16711680, 0, 0);

    for(int i=255; i>=10; i-=1) {
      if (digitalRead(brakeFeed) == LOW){
      pixels.setBrightness(i);
      pixels.show();
      delay(5);
      }
      else {
        break;
      }
    }
    for(int j=10; j<=255; j+=1) {
      if (digitalRead(brakeFeed) == LOW){
      pixels.setBrightness(j);
      pixels.show();
      delay(5);
      }
      else {
        break;
      }
      }
}


message:
Having problems with running two 74HC595 as a single 16bit shift register

I'm using two of these together to create a single 16bit register which will give me access to 16 outputs. I have gotten them to work but not exactly how I imagined them to work. The code written is for a 18650 cell charger/discharger. The first 6 bits (0-5) of the shift register will be connected to 6 NPNs which will turn on or off each of their tp4056s connected in series. The next 6 bits (5-11) will be connected to 6 different constant current loads. The user selects if they want to charge or discharge their cell and depending on the mode, that particular cell's charger or current sink is turned on (but both not on the same time). In reality, I have to firstly shift 6 bits manually by selecting a mode and then pressing select for all 6 cells in the register for it to show something and even after that it misses bits randomly. btw last 4 bits (12-15) will also get used in the final product. For experimenting, I've connected LEDs to all outputs.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <Arduino.h>
#include <LiquidCrystal_I2C.h>
#include <Encoder.h>

//initalisation
LiquidCrystal_I2C lcd(0x27, 20, 4);
Encoder encoder(2, 3);

//software constants
const int numOfCells = 6;
const int analogInput[numOfCells] = {A0, A1, A2, A3, A6, A7};
const float arduinoPowerLine = 4.80;
const long interval = 60000; //60 seconds
const char* functions [2] = {"CHARGE   ", "DISCHARGE"}; //mode select array
const int dataPin  = 12;//DS - pin 9
const int latchPin = 11;//ST_CP --pin12
const int clockPin = 8;//SH_CP --pin11

//Encoder setup
long oldPostion = -999;
long newPostion = 0;
long prevPostion;

//making battery arrays and setting their default flags
double batteryVoltage[numOfCells];
bool noBatteryFlag[numOfCells] = {LOW, LOW, LOW, LOW, LOW, LOW};
float minimum = 3.00; //Cutoff voltage
float capacity[numOfCells];

//mode variables
int modeState[numOfCells];
int confirmedModeState[numOfCells];

//button setup
int inputPin = 5;
int inputState;
int lastInputState = LOW;
int inputFlag = LOW;

//debounce timer
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;

//lcd varuables
int currentCell = -1;

//Cell timers
unsigned long prevMillis[numOfCells];
int minute[numOfCells];
unsigned long currentMillis;

//shift resister variables
word outputs = 0B0000000000000000;

void updateShiftRegister(word bits){//takes bits from the resolvemode function and sets them appropriately
  byte resisterOne  = lowByte(outputs);//right most byte
  byte resisterTwo = highByte(outputs);//left most byte
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, resisterTwo);
  shiftOut(dataPin, clockPin, MSBFIRST, resisterOne);
  digitalWrite(latchPin, HIGH);
}
void setup() {
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  pinMode(inputPin, INPUT_PULLUP);
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin,  OUTPUT);
  pinMode(clockPin, OUTPUT);
  updateShiftRegister(outputs);//Resets all shift resister output to LOW
}
void BatteryVoltage(){//reading each cells and converting the adc value into voltage
  for (int i = 0; i < numOfCells; i++){
    int reading = analogRead(analogInput[i]);
    batteryVoltage[i] = (reading * arduinoPowerLine) / 1023;
    //flagging stuff
    if (batteryVoltage[i] <= 0.50) {//checking if a battery is inserted in the holder
    noBatteryFlag[i] = HIGH;
    }else{
      noBatteryFlag[i] = LOW;
    }
  }
}
void ButtonDebounce(){//checking input state and flaggint button
  int reading = digitalRead(inputPin);
  if (reading != lastInputState){
    lastInputState = millis();
  }
  if ((millis() - lastInputState > debounceDelay)){//debouncing button
    if (reading != inputState){
      inputState = reading;
      if (inputState == HIGH) {
        inputFlag = HIGH;
      }
    }
  }
  lastInputState = reading;
}
void ResolveFlags(){
   if (inputFlag == HIGH){ //incrementing currentscreen
       if (currentCell == numOfCells - 1){ //if counter at its limit ,it wraps back to the start
        currentCell = 0;
      } else {
        currentCell++;
      }
      confirmedModeState[currentCell] = modeState[currentCell]; //mode selected in stored
      lcd.clear();//clears lab every time button is pressed
        inputFlag = LOW;
  }
}
void BatteryTimeKeeper(){//keeping track of battery time while it is discharging
for (int i = 0; i < numOfCells; i++){
  if (currentMillis - prevMillis[i] > interval){
    if (noBatteryFlag[i] == LOW){//if a battery is in the holder
      if (batteryVoltage[i] > minimum){//and if it is greater then 3v, it can be discharged
   minute[i]++;
   prevMillis[i] = currentMillis;
  }
  if (batteryVoltage[i] <= minimum){
    capacity[i] = (minute[i] / 60) * 500; //total time taken divided by 500mA (constant current load)
    minute[i] = 0;
    }
  }
}
    if (noBatteryFlag[i] == HIGH){//if a battery is removed, its timer is reset back to 0
      minute[i] = 0;
    }
  }
}
void EncoderFunctionNavigator(){//tracks encoder
  newPostion = encoder.read();
  if (newPostion != oldPostion){
    oldPostion = newPostion;
  }
  if(prevPostion < newPostion){
    modeState[currentCell]++;
  } else if(prevPostion > newPostion){
    modeState[currentCell]--;
  }
  if (modeState[currentCell] == 2){ //wraps back selection mode
    modeState[currentCell] = 0;
  } else if (modeState[currentCell] < 0){
    modeState[currentCell] = 1;
  }
}
void ResolveMode(){//sets shift resister output on or off depending on the mode selected
  for (int i = 0; i < numOfCells; i++){
    if (confirmedModeState[i] == 0){
      bitWrite(outputs, i, HIGH) && bitWrite(outputs, i+6, LOW);
    } else if (confirmedModeState[i] == 1){
      bitWrite(outputs, i, LOW) && bitWrite(outputs, i+6, HIGH);
    }
    updateShiftRegister(outputs);
  }
}
void PrintScreen(){//printing all the info in lcd
  lcd.home();
  int cellCounter = currentCell + 1; //this is here because I have ocd
  char buffer[25];
  sprintf(buffer, "Cell#:%d    %s", cellCounter, functions[modeState[currentCell]]);
  lcd.print(buffer);
  lcd.setCursor(0, 1);
  lcd.print("VOL:");
  lcd.setCursor(4, 1);
  lcd.print(batteryVoltage[currentCell]);
  lcd.setCursor(0, 2);
  lcd.print("Cap:");
  lcd.setCursor(4, 2);
  lcd.print(capacity[currentCell]);
}
void loop() {
 currentMillis = millis(); //main currentmillis variable
 BatteryVoltage();
 BatteryTimeKeeper();
 ButtonDebounce();
 EncoderFunctionNavigator();
 ResolveFlags();
 PrintScreen();
 ResolveMode();
 prevPostion = newPostion; //records the last postion of encoder
}

body:
To put the comments into an answer:

You are controlling the shift registers in this function

    void ResolveMode(){//sets shift resister output on or off depending on the mode selected
      for (int i = 0; i < numOfCells; i++){
        if (confirmedModeState[i] == 0){
          bitWrite(outputs, i, HIGH) && bitWrite(outputs, i+6, LOW);
        } else if (confirmedModeState[i] == 1){
          bitWrite(outputs, i, LOW) && bitWrite(outputs, i+6, HIGH);
        }
        updateShiftRegister(outputs);
      }
    }

Since the `updateShiftRegister()` call is inside the for loop, you are updating the shift registers for every bit, that you set. I guess this is the point, where you get your weird behavior. You don't need to update for every bit. Instead change all needed bits inside the `outputs` variable, and then at the end of `ResolveMode()` you can update the registers with all data at once.

So just move `updateShiftRegister(outputs);` one line down to outside of the for loop.


message:
How to interpret Serial data received by Bluetooth module

I'm experimenting with a hc-05 knockoff the JDY-30 and am confused about the Serial data I'm getting from it. I downloaded an app called BlueUino to send commands from my Android to my Arduino Uno via Bluetooth. I then print the data I get via Serial port using the code below:

      if(Serial.available() > 0){ // Checks whether data is comming from the serial port
        state = '1'; //Serial.read(); // Reads the data from the serial port0
        stateData = Serial.read();
        sprintf(data, "Data is %u", stateData);
        Serial.println(data);
        Serial.println();
     }

Here are some of the results I get in the log which I can't make sense of. For example, sending the string "def" doesn't contain the sequence of data from sending the command "e". Also, how does one convert these values to characters ?

Send Command "b"

    Data is 128
    Data is 0
    Data is 248

Send Command "abc":

    Data is 120 // doesn't contain the sequence of Data of "b"
    Data is 120
    Data is 120
    Data is 0
    Data is 120
    Data is 0
    Data is 248

body: This might be sending the data in bytes so convert it and then try. You can convert it by doing ```String(data)```.


body: Or just storing the inbound data in a char type and use single quotes when parsing incoming bytes so that the compiler knows your dealing with ASCII, print them out on serial and they should be familiar characters, of course with the baud rate mismatch fixed


message:
Fast random booleans

I am looking for a way of generating booleans rapidly. For booleans, one usually uses `random(0,2);` but in my case I need about 250 booleans and calling random every time is slow.

So I thought about using all bits of a random number on the whole range as such:

```
randomSeed(100); // A seed to always keep the same sequence
long rdm = random(MIN,MAX);  // Generate a number in range MIN,MAX of type long
long mask = 1;
for(int i=0; i<32; i++){
    if((rdm>>i)&mask){
        //do something
    } else {
        //do something else
    }
}
```

But with this I have three questions:

 1. What are MIN and MAX so that the LONG random uses all bits, with value ranging from -2,147,483,648 to 2,147,483,647 ([arduino long type][1]). I tried several MIN and MAX, also simply `random();` but without success.
 2. Is it a valid approach? Do I expect each bit to be uniformly distributed? Should I use fewer bits, e.g. `random(0, 2^16);` for a "better" distribution?
 3. Is there some seed known to be good or bad at this?

## My project ##
I am working on a device made of Neopixel LED strips. It is for a visual neuroscience experiment where each "pixel" is either ON or OFF. I need the speed to be able to reach high refresh rate (60-100Hz), with normal statistical distribution to avoid bias in neuron response analysis. With this approach, I can reach the desired speed but I'm concerned about the statistics. So I need a better understanding of `random()`'s behaviour to do it right!

  [1]: https://www.arduino.cc/reference/en/language/variables/data-types/long/

body:
1. I didn't try myself, but in the documentation it shows the MAX value is  2,147,483,647, which is 2^31-1. The MIN value I expect is -2^31, thus -2,148.483.648. Wondering what you mean by 'without success'.
2. Yes this is a valid approach. A 'perfect' random generator should be able to generate all values with an equal distribution. Since the values are within [-2^31, 2^31-1] this means all values within a 32 bit value is used, which automatically means all bits are also evenly distributed. So you can pick individual bits (as long as you use the entire MIN/MAX range).
3. In principle all seeds are good, as long as they are random. In the documentation it is advised to take an unconnected analog pin value. If you don't have one unconnected, you can use e.g. the `millis` function.


body:
The `random()` function returns a number between 0 and `RANDOM_MAX` (0x7FFFFFFF). The `random(min, max)` function takes the value from `random()` and manipulates it to fit into the specified range (calculate the offset difference, modulus the random value by that difference, then add the lower offset).

That means that the widest range you can get is from `random()` directly, whilch is the same as `random(0, RANDOM_MAX)`. However that is only ever going to be 31 bits, so your most significant bit will *always* be zero.

That's not what you want.

The best you can do to get 32 bits of random data is to take two random 31 bit values and combine them. Maybe left shifting one value by one bit and the XORing them together would be enough:

```
uint32_t rand1 = random();
uint32_t rand2 = random();
uint32_t fullrand = (rand1 << 1) ^ rand2;
```

Alternatively just working with 31 bits instead of 32 may be enough for your needs and would be faster than generating two numbers and combining them just to fill that one extra bit.


message:
How does supply voltage affect `analogRead()` on AVR-based microcontrollers?

I'm using an ATmega328P based Arduino to prototype reading a TMP36 temperature sensor. I will eventually move this to an ATtiny85 based board with a battery supply. Both the TMP36 and ATtiny85 have a Vcc range from 2.7V to 5.5V so a battery that starts at say 4.5V and slowly drops to 2.7V should not be out of range.

I am expecting to read temperatures in the range -5°C to +30°C which should correspond to a TMP36 output between 0.5 to 0.9V. I am getting 0.74V at around 23°C so this sort of range seems plausible.

The TMP36 outputs 10 mV/°C regardless of Vcc (within 2.7-5.5v). But I suspect the AnalogRead() value will be scaled by the supply voltage and so will slowly change as the battery drains. Is this correct?

Do I need to include an external voltage-regulator / voltage-reference device to supply some fixed voltage (e.g. 2.5V) to AREF?

----

Solution

Following [Edgar Bonet's Answer](https://arduino.stackexchange.com/a/76443/316) I successfully enabled the internal voltage reference for the ADC.

Initially I added a 100nF bypass capacitor to AREF and tried

    #define REFS1 7
    #define REFS0 6
    #define REFS2 4

...

    //ADMUX = (_BV(REFS1) | _BV(REFS2)); // 2.56V ATtiny85   datasheet §17.3 pp134
    ADMUX = (_BV(REFS1) | _BV(REFS0)); // 1.1V  ATmega328P datasheet §23.9 pp217

but didn't get it to work, my code had no effect on values from `analogRead()`. So after a bit of [further reading](https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/) I instead used

    analogReference(INTERNAL);

Which worked.

body:
The ADC measures a _voltage ratio_. The conversion result is the rounded
value of 1024×V/Vref, where V is the voltage at the input and
Vref is the voltage reference.

In the default Arduino configuration, the reference is connected to Vcc.
This will not fit your use case, as the voltage you want to read does
not vary proportionately to Vcc. You could use an external reference.
However, the ATtiny85 has two internal voltage references at 1.1 and
2.56 V. Either of these may be well suited for you application,
which should save you having to add an extra part.

See the [chapter on the ADC in the datasheet][datasheet] for details on
how to select the voltage reference.

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#G1.1202338


message:
How to produce rolling count per minute?

I have a counter attached to ISR:

    void ISR_impulse() {
      CNT++;
    }

and I want to calculate rolling count per minute with arbitrary update rate.

However I can only get it to update every minute:

    void loop() {
      if (t - t0 > 60000) {
        CPM = CNT - CNT0;
        t0 = t;
        CNT0 = CNT;
      }

      t = millis();
      delay(100);
    }

Requirement:

- Rolling count with a window of 1 minute, and arbitrary update rate like 1 second ?
- CPU has other tasks to do, which might take a significant amount of time.
- SAMD21 has pulse period measurement in TC, but I have no idea how to set it up.

Partial solution one by [edgar bonet][1]:
```
  static uint8_t buf[60];
  static uint8_t idx;
  static uint32_t t0;
  static uint16_t CNT0;
  static uint8_t cpm;

  if (millis() - t0 >= 1000) {
    t0 = millis();
    uint16_t cps = CNT - CNT0;
    CNT0 = CNT;
    cpm += cps - buf[idx];
    buf[idx] = cps;
    if (++idx >= 60) idx = 0;
  }
```
How ever this only works if the loop code finishes in less than 1ms.

  [1]: https://arduino.stackexchange.com/users/7508/edgar-bonet

body:
If you want to update every second a one minute running average, you
have no choice but store in memory the counts you got the previous
60 seconds. You store them in a ring buffer, so that every new
reading replaces the oldest one. Then, every second:

* you add to the CPM count the number of counts you got this second
* you subtract the number of counts you got on the second that just got
  out of the sliding window.

I would implement that logic this way:

```
const uint32_t ONE_SECOND = 1000;

uint16_t counts_per_minute;
uint16_t previous_counts[60];
size_t counts_pos;

void loop() {
    static uint32_t previous_second;
    if (millis() - previous_second >= ONE_SECOND) {
        previous_second += ONE_SECOND;
        noInterrupts();
        uint16_t CNT_copy = CNT;
        interrupts();
        static uint16_t CNT_previous;
        uint16_t second_count = CNT_copy - CNT_previous;
        CNT_previous = CNT_copy;
        counts_per_minute += second_count - previous_counts[counts_pos];
        previous_counts[counts_pos] = second_count;
        if (++counts_pos >= 60) counts_pos = 0;
    }
}
```

Note that:

* The timing variable is updated with `previous_second += ONE_SECOND`
  rather than `previous_second = now` in order to avoid the accumulation
  of small timing errors.
* The counter that is updated in the ISR has to be read only once,
  with interrupts disabled. Otherwise the interrupt may change it while
  you are in the middle of reading it.


body:
You need a First-In, First-Out buffer (FIFO) so that the oldest data drops off to make room for the newest. This is usually done with a circular buffer - an array whose beginning / end point change as data is added. (For comparison, the simplistic way is an array whose contents gets moved down (toward i = 0) each time you need to add a datum. But moving data is slow, so remembering where the oldest entry is, replacing it with the newest one, and updating the remembered oldest-data location gives a huge permormance improvement.

Secondly, you need to define how responsive your counter needs to be - how many updates per minute you'll need. That's the number of elements you need in the array.

Evaluating the immediately-passed minute's count is as simple as summing the array, which can be done without caring where the begin/end point is. Sum from 0 to N-1; the result will be the same.


message:
3pin (GND, 12V, tach) 12v FAN control using PWM

I know there are fans out there that have a dedicated PWM input, but I like to know if I can PWM control a fan that does not have such a dedicated PWM input. So...

If I have a 3 pin 12v fan like the [Noctua NF-A20][1] with connections:

- GND
- 12 V
- tach out (RPM measurement)

Can I control its speed by PWM on the 12V supply voltage (using a MOSFET most probably)?
Would the tach out still work?

  [1]: https://noctua.at/en/products/fan/nf-a20-flx

body:
Yes, and yes.

You have to modulate the +12V rather than GND because the output is referenced to ground. That means you need to use the classic N+P channel FET arrangement:

<!-- 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/HOe8H.png)

<!-- End schematic -->


message:
What is the maximum "wattage" can be pushed into an ATMega328 ADC pins?

I was doing some **Ohm's Law** calculations to calculate the voltage output from a 2-resistor voltage divider, the input will be with a maximum of 12 volts, I want the ATMega328 to measure that voltage, so I simply thought of putting two resistors in series with values of 330 ohms and 220 ohms like this:

<!-- 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/dc8Bq.png)

<!-- End schematic -->

Theoretically on paper the maximum voltage outputting from the node going to the ATMega328 is ~4.8V, but I want a special safety feature, I want to put in mind that at **anytime** the ground connection can be hung open (to simulate a lose breadboard connection, bad soldering joint etc...) now based upon my understanding if there is no ground connection, the voltage going to the Arduino will be 12V which is a killer, as after looking on the ATMMega328 datasheet it states that

> 28.1 Absolute Maximum Ratings. Voltage on any pin except RESET with respect
to ground => VCC + 0.5

The current will be limited by the 330ohm resistor to only 36mA which I think is a lot, I thought of doubling the resistors values to 330000 and 220000 by that the current will be limited to only 36uA. Again based upon my understanding there is still 12V going to the Arduino but wouldn't it directly drop if the ground connection was cut off ? That's why I ask what is the maximum input **power** to an Arduino?

body:
This is actually a special case that is undocumented, and in fact not as simple as you would at first think.

The input port itself is not actually what is in question here. Instead every IO pin on the Arduino, be it set to INPUT or OUTPUT, has a set of ESD protection diodes on them. These look like this:

<!-- 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/XFVqY.png)

<!-- End schematic -->

The "IO MODULE" when in INPUT mode can pretty much be ignored, since it is a very high impedance. Just like a (roughly) 10MΩ resistor to ground. Very very little current will flow that way.

D2 is also reverse biased so that direction can be ignored.

So the current will want to flow through D1 to the VCC rail (+5V).  The diodes have approximately a 600mV forward voltage (which is where the VCC + *0.5* comes from).

So we can recalculate, given those parameters, what the current flowing through the diode will be to the 5V rail:

* Voltage difference = 12V - 5V - 0.5V = 6.5V
* Current = V/R = 6.5/330 = 19.7mA

The recommended maximum (from what I can gather) is only 1mA.  You have 20x that.

So you will need at least 20x higher resistances. 10kΩ in the upper half and 6.8kΩ in the bottom half.  That will give you 4.85V on the output at 12V and limit you to 0.65mA in a failure situation.

It also gives you an output impedance of a little over 4kΩ which is below the recommended maximum of 10kΩ for the ADC input.

You can further protect your input by adding a 5V zener diode and small series resistor on the ADC pin so if the voltage goes above 5V it clamps it and protects the pin.

<!-- 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/kkGzB.png)

<!-- End schematic -->


message:
Arduino exercise that i have no idea how to do

The messages received by the Arduino take the form: $ Ba, Pb, Rc #

Where $ represents the beginning of the message, # represents m, and B, P, and R are characters representing B button, P period and R repetition.

1. `a 'designates the button to be read, which can be 1, 2 or 3.
2. `b 'designates the time (in seconds) that the button should be expected to be pressed.
3. `c 'designates the number of times the button is expected to be pressed during the indicated period.

For example, with the message: $ B2, P4, R2 #
you want to know if button 2 has been pressed twice for four seconds. If condition is verified, then the Arduino must send the message $ MSG, TRUE # where MSG represents the message received without the start and m message characters. Otherwise, you must send the message $ MSG, FALSE #.

Incoming messages must respect the format presented. If not, the condition is not checked and the message $ NOK, MSG, KON # must be sent as a response.

I have no idea how to do this since im new to arduino

body:
To begin, forget the Arduino for a moment and assume the task of determining true or false from $....# message. Think about what you would have to do, step by step, to accomplish this. (e.g.: Read the buttons; Record the time and the button states. Is there a message from the Serial port beginning with '$'? Then read the rest of the message. etc.) Then, for each of those steps, do the same thing again: write down the smaller steps to accomplish what that step requires. Do that until you can't break it down any further.

Those small steps should each look like something you could do in C++ code (sometimes called "Arduino" code, but it's really C++). Start replacing each English (or your language) steps with the C++ equivalent. Do this until all of the human-language steps are written in C++.

There will inevitably be mistakes. Fix one or a few at a time. When you're stuck, ask here, something like "Here is my (well formatted) code. I tried [this]. I expected to see [that]. But what happened instead was [something else]. How can I fix it?"; or: "I am getting this error message [with its complete text including any line numbers, please] from the compiler. What does it mean, and how could I have found that out on my own?"

Small steps....


message:
Problem using 2 motors

I would like both the motors to spin the attached wheels forward when I push the joystick forward and vice versa. When the joystick is still, the motors should stop spinning. At the moment, when I push the joystick on x-axis and my `x` variable increases both motors spin, but when I push it in the opposite direction and `x` decreases, only motor A spins. Additionaly when I connect the arduino to the power (usb cable to my pc), motor B spins for approx 1 second and then stops.

This is the circuit I have (sorry for a lack of schematic, let's hope this wonderful drawing is enough):
![Text](https://i.stack.imgur.com/TNuvk.png)

The code:

    int MotorAA = 7;
    int MotorAB = 8;

    int MotorBA = 11;
    int MotorBB = 12;

    int x = 0;

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

      pinMode(MotorAA, OUTPUT);
      pinMode(MotorAB, OUTPUT);

      pinMode(MotorBA, OUTPUT);
      pinMode(MotorBB, OUTPUT);

      digitalWrite(MotorAA, LOW);
      digitalWrite(MotorAB, LOW);

      digitalWrite(MotorBA, LOW);
      digitalWrite(MotorBB, LOW);
    }

    void loop() {
      x = analogRead(A0);
      Move();
      Serial.println(x);
    }

    void Move() {
      if (x == 0){
        return;
      }

      if (x > 520)
      {
        digitalWrite(MotorAA, HIGH);
        digitalWrite(MotorAB, LOW);

        digitalWrite(MotorBA, HIGH);
        digitalWrite(MotorBB, LOW);
      }
      else if (x < 480)
      {
        digitalWrite(MotorAA, LOW);
        digitalWrite(MotorAB, HIGH);

        digitalWrite(MotorBA, LOW);
        digitalWrite(MotorBB, HIGH);
      }
      else{
        digitalWrite(MotorAA, LOW);
        digitalWrite(MotorAB, LOW);

        digitalWrite(MotorBA, LOW);
        digitalWrite(MotorBB, LOW);
      }
    }

body:
The Arduino can definitely not power that many motors. The Arduino's max output current is 0.1A and you might be drawing around 0.5A. Use an external battery like a LiPo battery for the motor controller.

NOTE: Please watch out! Drawing that many amps from Arduino can kill it! So please use the LiPo or normal batteries!


message:
Communication between 2 arduino boards

I am not really 100% too sure how to do this but I am trying to make my arduino UNO communicate with my arduino MEGA. The reason why I needed to do this was because I was using the RFID module along with a TFT display and the problem I faced is that on the arduino mega they both needed pin 53. Luckily I have an arduino UNO so I just went for that instead for the display. I am trying to use the `analogWrite()` function to send analog signals from my MEGA over to the UNO so that the TFT display on the UNO can display the results. The UNO would also read the analog inputs coming from the MEGA. This did not work very well. The analog inputs are being sent from the MEGA but the UNO is not reciving them. I am using a PWN pin on the MEGA to send the analog output to the UNO.

This diagram shows what I mean:

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

These are the 2 compotents I am using:

   https://i.stack.imgur.com/CqXdB.png
TFT display

[![][2]][2]

RFID

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

  [1]: https://i.stack.imgur.com/Wg6Dt.png
  [2]: https://i.stack.imgur.com/vmdKP.jpg
  [3]: https://i.stack.imgur.com/TfNjb.png
This shows how the libary sets out the pins. I am only a beginner so I personally don't want to mess around with the libary.

body:
Pin 53 is just the default "slave select" pin. There is nothing special about it. You can use any other pin as slave select, as long as the libraries for your devices allow it (check the documentation and tutorials for those libraries).

You cannot transmit information with `analogWrite()` since it isn't really analogue (it's PWM), and analogue doesn't have enough definition for reliably representing more than a handful of discrete values anyway.


body:
You can use the I2C interface.

TX:
```
// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}
```

RX:
```
// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}
```

Schematic:

[![Image by Dronebot Workshop; check out their tutorial for more info: https://dronebotworkshop.com/i2c-arduino-arduino/][1]][1]

Image by Dronebot Workshop; check out their tutorial for more info: https://dronebotworkshop.com/i2c-arduino-arduino/

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

  [1]: https://i.stack.imgur.com/hg5l7.png
  [2]: https://i.stack.imgur.com/B0oUp.png


message:
Arduino Nano-combo NRF2401

I am using two nano-combo for a RC car and when the remote emitter battery is too down if the car was running and battery finally empty the car was still running...is there any way by programming to check communication between the two nanos and solve this problem??. Thanks.

here is the code:
//Receiver program

#include <SPI.h>;
#include "Mirf.h"
#include "nRF24L01.h"
#include "MirfHardwareSpiDriver.h"
Nrf24l Mirf = Nrf24l(10, 9);

void setup()
{
  Serial.begin(9600);
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"FGHIJ"); //Set your own address (receiver address) using
  5 characters
  Mirf.payload = sizeof(datos);
  Mirf.channel = 90;             //Set the used channel
  Mirf.config();
  //Serial.println("Listening...");  //Start listening to received data

void loop()
{
 if (Mirf.dataReady()) { //When the program is received, the received data is
                            output from the serial port
     Mirf.getData(datos);
     delay(5);

if (datos[7] >= 150) {     //motor forward

    analogWrite(3,0);
    analogWrite(5,255);
  }

  if (datos[7] <= 90) {    motor back

    analogWrite(3,255);
    analogWrite(5,0);
  }

  if (datos[7] > 90 && datos[7] < 150 or datos[7] == 0) { //motor stop

    analogWrite(5,0);
    analogWrite(3,0);

  }
}
}

it works perfect I can control dc motor no problem but if remoto control battery is low or empty then no communication with NANO receiver and the motor spin itself non stop.

I try different things in the void loop like:

 if (!Mirf.dataReady()) {
    analogWrite(5,0);
    analogWrite(3,0);  }

but still the same problem. So that´s why must be something inside Rf library to check if remote control NANO comms is off I don`t know...

Thanks

body:
You can do somthing like:

    while(radio.hasData()){
    }
This works in the NRFLite library. I don't know about other libraries like RF24 etc.


message:
Problems with detecting button digital state

I am trying to start an event after pressing and holding the *FLASH built-in Nodemcu button* for a specific time, I wrote two functions, one for debouncing and detecting the state, the other is to detect the pressing time, I'm not getting any result unless I decrease the input pressing time to less than 1s, which makes the button works as a single-push button, I think i have a problem with **debouncing** the button, I can't figure out where it is?

    /**
    * @brief debounces the button and returns the current level high or low
    *
    * @return int the button state 0: low, 1: high, -1 indetermined
    */
    int button_state(int btn)
    {
        int const DEBOUNCE = 200;
        static int hi = DEBOUNCE;
        static int lo = 0;
        if (digitalRead(buttonPin[btn]))
        {
            if (hi < DEBOUNCE)
            {
                hi++;
            }
            if (lo > 0)
            {
                lo--;
            }
        }
        else
        {
            if (lo < DEBOUNCE)
            {
                lo++;
            }
            if (hi > 0)
            {
                hi--;
            }
        }

        if (hi == DEBOUNCE)
        {
            return 1;
        }
        else if (lo == DEBOUNCE)
        {
            return 0;
        }
        else
        {
            return -1;
        }
    }
    /**
     * @brief Detects the button state and starts a time to calculate pressing duration
     *
     * @param btn input button pin
     * @param PressTime Desired pressing duration to compare to
     * @return int returns 1 when PressTime is reached
     */
    int PressNHold(int btn, int PressTime)
    {
        int lastButtonState = 0, Startpressed = 0, endPressed = 0, holdTime = 0,
        buttonState = button_state(btn);
        if(buttonState != -1)
        {
            if (buttonState != lastButtonState)
            {
                if (buttonState == 1)
                {
                    Startpressed = millis();
                }
                else
                {
                    endPressed = millis();
                    holdTime = endPressed - Startpressed;
                    if (holdTime >= PressTime)
                    {
                        Serial.printf("Button %d pressed for %ds or more\n", btn, holdTime);
                        holdTime = 0;
                        return 1;
                    }
                }
            }
        }
        lastButtonState = buttonState;
    }
    .....

    void loop {

    if (PressNHold(buttonPin[1], 5 * 1000) == 1)
      {
       //launch your event
      }

body: turns out that it is very simple, I shouldn't put buttonPin[1] a variable for PressNHold, I had to put just1, buttonPin was used already in button_state, also, PressnHold local variables should be declared static to not get a reset after function execution.


message:
Arduino Uno R3 cannot detect GPRS Shield SIM900

I am new to Arduino which I got only this week for my project which sends sms from my windows     application.

I have **Arduino Uno R3** and **GPRS Shield (Simcom) Sim900  (S2-1040S-Z0912)**

I am currently following this guide > https://educ8s.tv/arduino-gsm-shield/

As of the moment I have problem connecting the Sim900 to Arduino (I think Arduino cannot detect Sim900). The Arduino is working properly as my PC detected it. Also I confirm that the SIM900 is working properly as I can call the Sim inside and it is ringing (also the led on the device is blinking almost every 3 secs or so)

I found this, but I'm planning to use USB powered only as I only need the SMS feature so I am stacking the SIM900 on top of the Arduino.
https://arduino.stackexchange.com/questions/9483/how-to-communicate-the-arduino-board-with-sim900

I am using this library http://www.tinyosshop.com/datasheet/GSM_GPRS_GPS_Shield_GSMSHIELD.rar

and below is the sketch:

    #include "SIM900.h"
    #include <SoftwareSerial.h>
    #include "sms.h"
    SMSGSM sms;

    int numdata;
    boolean started=false;
    char smsbuffer[160];
    char n[20];

    char sms_position;
    char phone_number[20];
    char sms_text[100];
    int i;

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

        if (gsm.begin(9600))
        {
            Serial.println("\nstatus=READY");
            started=true;
        }
        else
            Serial.println("\nstatus=IDLE");

        if(started)
        {
            if (sms.SendSMS("214", "?15001"))
            {
              Serial.println("\nSMS sent OK.");
            }
            else
            {
              Serial.println("\nError sending SMS.");
            }
        }
    };

    void loop()
    {
        if(started)
        {
            sms_position=sms.IsSMSPresent(SMS_UNREAD);
            if (sms_position)
            {
                Serial.print("SMS postion:");
                Serial.println(sms_position,DEC);
                sms.GetSMS(sms_position, phone_number, sms_text, 100);
                Serial.println(phone_number);
                Serial.println(sms_text);
            }
            delay(2000);
        }
    };

and here is the output

    Trying to force the baud-rate to 9600

    1200
    2400
    4800
    9600
    19200
    38400
    57600
    115200
    ERROR: SIM900 doesn't answer. Check power and serial pins in GSM.cpp

    status=IDLE

What I have tried so far:

I tried the sketch with ```SoftwareSerial mySerial(7, 8);``` and ```SoftwareSerial mySerial(9, 10)``` which i found on other tutorials but didn't work.

I tried modifying ```GSM.cpp``` and modify the value of ```_GSM_TXPIN_```  and ```_GSM_RXPIN_```  to 7, 8 and 9, 10 but didn't work.

Found that the pin on my Arduino is RX=0 and TX=1, and SIM900 is TX=0 and RX=1, tried the SoftwareSerial code above but with 0, 1 and GSM.cpp with 0, 1 but still not working.

I am currently still trying every other sketch i find on the internet but nothing works.

EDIT:
This is the link for the module i bought
https://www.lazada.com.ph/products/sim900-gsm-shield-i267689740-s379728457.html?mp=1

I cant find the link for the datasheet of this specific module so I will try to include the picture of the module

[![SIM900 Bottom][1]][1]

[![SIM900 Top][2]][2]

  [1]: https://i.stack.imgur.com/6VUi8.jpg
  [2]: https://i.stack.imgur.com/YVKHD.jpg

body:
After many trials, I found the solution to my problem, thanks to @Majenko for mentioning the jumpers.

I am still stacking the SIM900 module on top of Arduino.

Switching the jumpers from `D1` and `D0` to `D8` and `D7` solved the problem (see green square on the pic)

I don't know why it needs to be on `D8` and `D7` since on board it says TX=0 and RX=1 and vise-versa for Arduino

[![JUMPERS][1]][1]

Then used the below sketch from this tutorial > https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/

```
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}
```

With this, it displays correct output on serial monitor based on the tutorial and I can confirm that its working as well on my windows form application as it can send sms from the application.

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


message:
Sending arduino sensor data via WiFi to a MySQL server

I'm aware this question has probably been asked many times but I'm pulling my hair out.

I'm trying to get sensor data from an arduino to a MySQL server. I've checked the apache access log and the request is there. But it just isn't being inserted into the database. Manually adding the data using the browser works so the php code seems fine. I've allowed apache through the firewall and updated the permissions all to no avail. Code below:

Arduino Main Code:
```
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
#include <WiFi.h>

WiFiClient client;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);

  //Connect to WiFi network
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED){
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SSID);
    status = WiFi.begin(SSID, PASS);
    delay(10000);
  }
  Serial.println("This is connected.");

  if (!ENV.begin()) {
  Serial.println("Failed to initialize MKR ENV shield!");
  while(1);
  }
  pinMode(2, INPUT);
}

void loop() {
 relativeHumidity = int(ENV.readHumidity());
 lightIntensity = (ENV.readIlluminance());
 airPressure = int(ENV.readPressure(MILLIBAR));
 temperature = int(ENV.readTemperature());
 if(digitalRead(2) == LOW){
   rain = 1;
 }else if(digitalRead(2) == HIGH){
   rain = 0;
 }
 Serial.println("httpRequest");
 httpRequest();
 delay(10000);
}

void httpRequest(){
  // if there's a successful connection:
  if (client.connect(SERVER, 80)) {
    Serial.println("Connecting to server...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    Serial.println("GET /weather_data.php?);
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.print(" Host: ");
    client.println(SERVER);
    client.println();
    Serial.println("Added.");
  } else {
    Serial.println("Not connected.");
  }
  if (client.connected()){
    client.stop();
  }
}
```
thingProperties.h:
```
#include <WiFi.h>
#include <SPI.h>

const char THING_ID[] = "c942a18f-7696-4431-952c-76eaea3214ea";

const char SSID[]     = SECRET_SSID;    // Network SSID (name)
const char PASS[]     = SECRET_PASS;    // Network password (use for WPA, or use as key for WEP)
const char SERVER[]   = SECRET_IP;      // Server IP Address

int airPressure;
float lightIntensity;
float relativeHumidity;
bool rain;
float temperature;
```

body: WiFi.h is for Arduino WiFi shield. Use the WiFiNINA library for MKR1010


body:
So I don't quite know why, but I started from scratch and it works now. I've put the new code below in case it helps someone in my situation.

```#include "arduino_secrets.h"
// Arduino Low Power - Version: Latest
//#include <ArduinoLowPower.h>
//#include <ArduinoIoTCloud.h>
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
/*
  Repeating Wifi Web Client

  This sketch connects to a a web server and makes a request
  using a WiFi equipped Arduino board.

  created 23 April 2012
  modified 31 May 2012
  by Tom Igoe
  modified 13 Jan 2014
  by Federico Vanzati

  http://www.arduino.cc/en/Tutorial/WifiWebClientRepeating
  This code is in the public domain.
*/

#include <SPI.h>
#include <WiFiNINA.h>

int status = WL_IDLE_STATUS;

// Initialize the Wifi client library
WiFiClient client;

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

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    //Serial.print("Attempting to connect to SSID: ");
    //Serial.println(SSID);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(SSID, PASS);

    // wait 10 seconds for connection:
    delay(10000);
  }
  // you're connected now, so print out the status:
  //printWifiStatus();
  //Start arduino cloud.
  //ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  //Begin ENV shield.
  if (!ENV.begin()) {
    Serial.println("Failed to initialize MKR ENV shield!");
    while (1);
  }
}

void loop() {
  //ArduinoCloud.update();
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
    //Serial.println("Start reading sensors.");
    relativeHumidity = int(ENV.readHumidity());
    //Serial.println(relativeHumidity);
    lightIntensity = int(ENV.readIlluminance());
    //Serial.println(lightIntensity);
    airPressure = int(ENV.readPressure(MILLIBAR));
    //Serial.println(airPressure);
    temperature = int(ENV.readTemperature());
    //Serial.println(temperature);
    UV_Index = int(ENV.readUVIndex());
    //Serial.println(UV_Index);
    if (digitalRead(2) == LOW) {
      rain = 1;
    } else if (digitalRead(2) == HIGH) {
      rain = 0;
    }
    //Serial.println(rain);
    //Serial.println("Sensor data read.");
    //Serial.println("Start http request.");
    httpRequest();
    //Serial.println("Stop http request");
    delay(60000);
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the Nina module
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    //Serial.println("connecting...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&UV_Index=");
    client.print(UV_Index);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.println("Host: 192.168.0.29");
    client.println("User-Agent: ArduinoWiFi/1.1");
    client.println("Connection: close");
    client.println();
  } else {
    // if you couldn't make a connection:
    //Serial.println("connection failed");
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}


message:
Can I force a function to live in the boot sector without overwriting the bootloader?

Not for any practical purpose but just out of curiosity, I want to abuse the flash memory and write it dynamically at run-time.  This is, in a sense, what the bootloader does.  If I understand it, the only way to modify flash is to do so from instructions written to the boot sector.  Is it possible to stick a simple function in there that writes to flash memory, and call it from running code?  If so, how do I put it there?  I have no issue with calling functions from function pointers, so I don't think I'll have an issue actually calling the function once I get there, but I need to know how to stick into flash in the first place.

body:
The Optiboot version 8 has a `do_spm` function which can be called from application. The Optiboot repository contains [an example][1] for the use of this function.

SPM is the AVR CPU instruction to write to flash memory. The Optiboot wraps this in a function. A pointer to this function is put in a 'vector table' at the beginning of the bootloader. The first pointer jumps to `main`, the second pointer jumps to `do_spm`. The optiboot.h then has the function as (version for small Optiboot)
```c
typedef void (*do_spm_t)(uint16_t address, uint8_t command, uint16_t data);
const do_spm_t do_spm = (do_spm_t)((FLASHEND-511+2)>>1)
```

I made an enhancement of this, a [copy_flash_pages function][2] with reset option to bootload an AVR from its own flash. It is added as third entry in the 'vectors table' of Optiboot. It is used in my [ArduinoOTA][3] library for AVR MCUs.
```c
typedef void (*copy_flash_pages_t)(uint32_t dest, uint32_t src, uint16_t page_count, uint8_t reset);
const copy_flash_pages_t copy_flash_pages = (copy_flash_pages_t)((FLASHEND-1023+4)>>1);
```

  [1]: https://github.com/Optiboot/optiboot/tree/master/optiboot/examples/test_dospm
  [2]: https://github.com/Optiboot/optiboot/pull/269
  [3]: https://github.com/jandrassy/ArduinoOTA


message:
How to connect HC-06 with HC-08 with the HC-06 as master and HC-08 as slave?

How do you connect HC-06 with HC-08 with the HC-06 as master and HC-08 as slave? I will try it using 2 Arduino Unos.

body:
You cannot. The HC-06 is a slave only device.

So you need to use a device as master, that is actually capable of it. I don't know, if the HC-08 can do it. Another typical bluetooth master device is the HC-05. Just like HC-06, but can also be a master.


message:
Motor noise on my Arduino RC?

I want to make an RC car based on two Arduino Nanos, two [nRF24L01](https://infocenter.nordicsemi.com/pdf/nRF24L01P_PS_v1.0.pdf)s (Rx and Tx), and a [Pololu brushed motor driver](https://www.pololu.com/product/2990), and it works, more or less.

Sometimes it works very well and everything goes nicely and suddenly it will "freeze" and stop receiving and when it does, the servo always goes to 0° (I think it must be the Rx because it prints the same value until the next restart in the serial monitor).

It seems the servo trebles in the same direction (to 0°) only when I send high PWM values until it stops reading new data and "freezes".

I have 2 batteries, one for the Nano with a step-up converter, and another for the servo and the brushed motor;  they share a common ground. Everything is close to each other and connected by wires soldered to a prototype breadboard. It is really messy but makes a good contact.

So it seems it is a noise problem, doesn't it? But what else could it be? How can I suppress that noise? I have already watched the Pololu guide about noise but I didn't try the bypass capacitors since I don't know how to solder them properly (can they burn the servo?)

Here is the code for the Tx

```C++
#include <SPI.h>
#include "RF24.h"

const int ledBot = 8;
const int padx = A0;
const int pady = A1;
const int sw = 3;
int sws;
int x;
int y;
int botState;
int aBotState;
int ledState;
const float un = 0.25;
const float fy = 0.176;
int sens [4]; // 0: throttle, 1: foward/backwards, 2: steering, 3: lights

RF24 radio(9, 10); // CE, CSN
const byte address[6] = "00001";
void setup() {
  //Serial.begin(9600);
  pinMode(padx, INPUT);
  pinMode(pady, INPUT);
  pinMode(sw, INPUT);
  pinMode(ledBot, INPUT_PULLUP);
  radio.begin();
  radio.setDataRate (RF24_2MBPS);
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
  x = analogRead(padx);
  y = analogRead(pady);
  sws = digitalRead(sw);
  botState = digitalRead(ledBot);
  y = 1024-y;

  switch (sws){ //foward and backwards

  case 0:
    sens [0] = un*x;
    sens [1] = 0;
    sens [2] = min(135, max(50, y*fy-2));
    break;

  case 1:
    sens [0] = un*x;
    sens [1] = 1;
    sens [2] = min(135, max(50, y*fy-2));
    break;
  }

  if ( botState == HIGH && aBotState == LOW) { //button switch part
    if (ledState == 0) {
      ledState = 1;
      sens [3] = ledState;
    }
    else {
      ledState = 0;
      sens [3] = ledState;
    }
  }
  aBotState = botState;
  radio.write(&sens, sizeof(sens));

  //Serial.println(sens[0]);
  //Serial.println(ledState);
  // Serial.println(sens[1]);
  //Serial.println(sens [3]);
}
```

And here for the Rx:

```c++
#include <Servo.h>
#include <SPI.h>
#include "RF24.h"

int sens [4];
const int polph = 7;
const int polen = 6;
const int led1 = 2;
const int led2 = 3;
const int ledError = 8;

Servo servo;
RF24 radio(9, 10); //
const byte address[6] = "00001";

void setup() {
  pinMode(polph, OUTPUT);
  pinMode(polen, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);

  pinMode(ledError, OUTPUT);
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  delay(300);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  delay(300);
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  delay(300);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  servo.attach(5);
  //Serial.begin(9600);
  radio.begin();
  radio.setDataRate (RF24_2MBPS);
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    digitalWrite(ledError, LOW);
    radio.read(&sens, sizeof(sens));
    analogWrite(polen, sens [0]);
    digitalWrite(polph, sens[1]);
    servo.write(sens [2]);
    digitalWrite(led1, sens [3]);
    digitalWrite(led2, sens [3]);
  }
}
```

body:
Electrical noise is **the** problem quite often. In order to minimize noise, several key points must be observed:

1. Solder one 0.1uF ceramic capacitor from each terminal to the motor case. These are called decoupling capacitors and are used to suppress HF noise creeping in from the motors due to sparking/arching.

2. Choose appropriate AWS rating for your motor leads and adequate power supply. Inappropriately thin leads or insufficient battery discharge current can cause abrupt voltage drop on acceleration which will lead to sudden MCU resets (brown out resets).

3. Twist the leads around each other. This helps to further nullify arching noise.

As for Arduino, it is not the best way for making reliable RC software because it does simple things terribly wrong, e.g. sequential software polling instead of using hardware input capture. I would highly recommend learning how to write firmware for MCUs in native mode.

Check out this link to gain some inspiration on how to build an RC motor driver:

https://github.com/neoxic/STM8-RC-Dual-Motor-Driver#building-a-dual-12a-bidirectional-esc


message:
Error while inputting EEPROM.read() and EEPROM.write()

I am trying to store data in ATmega328 (Arduino Uno) using the following code using tinkercad:
```
#include <EEPROM.h>

void setup() {
  int addr, data=1;
  Serial.begin(9600);
  for (addr=0; addr<1023; addr++) {
    EEPROM.write(addr, data);
  }
  for (addr=0; addr<1023 ; addr++) {
    Serial.print(EEPROM.read(addr), DEC);
  }
}
```
When I simulate the code in the tinkercad, then i get the following error:
```
In function `main':
43: undefined reference to `loop'
 error: ld returned 1 exit status
```
Please help me where is the error in my code. I am not able to understand the error source.

body:
Have you looked at any Arduino IDE example programs?

They all have a `setup()` and `loop()` function.

Apparently, Tinkercad is missing the `loop()` function in your code.

You can solve the issue by adding an empty `void loop() { }` after your `void setup() { ... }` code.


message:
Speed control of BLDC with an integrated controller (Hall out, PWM in)

I am aiming at precise speed control of [this BLDC motor][1]: it has an integrated controller, outputting digital Hall signal (period 20.8ms on oscilloscope, w/o load) and taking PWM as input for speed regulation.

As far as my knowledge goes, this is a task for PID: measure Hall pulses at input, adjust duty cycle of the PWM based on target period/frequency of the Hall output.

The speed should be controlled with <1% error (even less is better).

* Is this goal realistic with this particular motor?
* How should I measure pulse duration?
* Is `pulseIn` (with interrupts disabled) going to be sufficiently precise? Should I measure lows or highs?
* Should I measure several pulses instead (and how)? Or should I accept imprecision in the pulse period and compensate (smooth) it using integral/derivative terms?
* Do I need more than 8-bit PWM resolution for this task? (I will use Nano at first, but might switch to Nano Every, which has 10-bit PWM).

Any other comments/suggestions are welcome.

  [1]: https://www.ebay.com/itm/DC-6V-12V-24V-Schnecken-Getriebemotor-5-60RPM-Brushless-Worm-Gear-Motor-GW4058/283678690228

body:
This is only a partial answer, about measuring pulse period or duration.

For best accuracy, I would recommend using the “input capture” feature
of a 16-bit timer. This is not as easy as using `pulseIn()` or timing
the signal with `micros()`: you will have to carefully study the MCU's
datasheet and manually configure the bits of some I/O registers. You
will be rewarded with high accuracy (single-cycle if the timer runs at
the MCU clock speed) and without the jitter inherent to any
software-based approach.

Beware that the Nano and Nano Every use different MCUs, with very
different timers. Both have input capture capability, but if you switch
from one to the other you will have to redo most of the work. Note that
the Nano is capable of 10-bit PWM if you program it low-level.

A software-based approach (`pulseIn()` or `attachInterrupt()` +
`micros()`) has the advantage of portability.


body:
To expand a little on Edgar's answer:

There are two main ways of measuring frequency, and both require different resources and are better for different situations.

The method Edgar describes using the Input Capture method, is good for rapidly changing low frequency signals where you want to respond very quickly to changes in the frequency. It works by measuring the time between two pulses using a free-running timer. Of course you can only measure frequencies as fast as the timer can run, which is pretty fast anyway, and if configured right it can run almost entirely asynchronously so you can just query the current recorded time whenever you need to.

The other option is to count the number of pulses within a given time period. This can also be done in hardware but using a different set of peripherals.

For this you have two timers. Timer 1 has the ability to us an external signal on pin D5 as its clock. This basically turns it into a pulse counter, and every time a pulse arrives on the timer pin it increments the count by one.

Then you have a second timer which triggers an interrupt at a predefined period. What that period is depends on the responsiveness you want and the frequency range you want to measure.  You can also use the "prescaler" of Timer 1 to increase the frequency measurement range by only counting every 2nd or 4th or 8th etc edge.

Of course, all that timer use would interfere with PWM generation on the Nano, but should be better on the Nano Every, but you'd want to check the datasheet for timer usages.

So in summary:

**Input capture**

* Fast response
* Limited frequency range

**Pulse counting with timer 1**

* Slower response
* Naturally smoothed output
* Greater frequency range
* Understands the concept of zero Hz
* Interferes with PWM generation

Whichever method you choose, sure, feed it through PID to create a stable output RPM.


message:
NRF24L01 Transmission Problems between Arduino UNO and Arduino Nano

I'm a beginner in using NRF24L01 tranceiver module. I tried sending a simple "Hello world" using Arduino Nano and a Arduino UNO with the use of two NRF24L01 modules. I don't get any output in the serial monitor at the receiver side. I checked the wire connection numerous times. Also checked the baud rate of both receiver code and the serial monitor are same and adddresses of the tranceiver code and the receiver code are same. Looking for a solution. Thanks in advance.

This is my tranceiver code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    RF24 radio(7, 8); // CE, CSN
    const byte address[6] = "00001";
    void setup() {
      radio.begin();
      radio.openWritingPipe(address);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();
    }
    void loop() {
      const char text[] = "Hello World";
      radio.write(&text, sizeof(text));
      delay(1000);
    }

And this is my Receiver code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    RF24 radio(7, 8); // CE, CSN
    const byte address[6] = "00001";
    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.openReadingPipe(0, address);
      radio.setPALevel(RF24_PA_MIN);
      radio.startListening();
    }
    void loop() {
      if (radio.available()) {
        char text[32] = "";
        radio.read(&text, sizeof(text));
        Serial.println(text);
      }
    }

body:
I had the same problem and when I tried the isChipConnected () function, it told me that one of the nrf24l01 was not connected to the SPI and I assumed that one was bad. I bought 2 nrf24l01 with antenas and they work well (mostly). ( [Here is the link to the library reference][1]. Also, make sure you are using the TMRh20 version of the library, [This one][2]. This is more updated and better as far as I'm aware.

Like everyone would suggest, try to solder a 10uF capacitor between GND and VCC (that module requires more power sometimes). And the last thing I tried was to use one of this socket adaptors for the 2 modules [here][3] to use the 5v output from the arduino since it can deliver more mA and thus the module can work better.
This guide help me a little bit, I'll drop it [here][4]
I don't see anything wrong in the code, but I'm a newbie like you so (It seems we are using the same adress in our codes)

  [1]: https://tmrh20.github.io/RF24/classRF24.html#ac224c55270d26dbe7b4f3492ea3056b5
  [2]: https://tmrh20.github.io/RF24/index.html
  [3]: https://es.aliexpress.com/item/4000581444984.html?src=google&src=google&albch=shopping&acnt=631-313-3945&isdl=y&slnk=&plac=&mtctp=&albbt=Gploogle_7_shopping&aff_atform=google&aff_short_key=UneMJZVf&&albagn=888888&albcp=9866812513&albag=101880764522&trgt=896505316494&crea=es4000581444984&netw=u&device=c&albpg=896505316494&albpd=es4000581444984&gclid=CjwKCAjwltH3BRB6EiwAhj0IUCfw4KSDmSKgvcsDt2Mr-7kaVs6966bjcXevAQOEUn091gvA0wYaCBoCiI0QAvD_BwE&gclsrc=aw.ds
  [4]: https://forum.arduino.cc/index.php?topic=421081


body:
You can also try using the NRFLite library. It is a lot easier to use. Also make sure you have a minimum of 3.3V and 0.5A power at the radio pin. If not, it may not transmit.

Here is a TX and RX example of sending text using the NRFLite. It worked perfectly for me!

TX:
```
/*

Demonstrates sending and receiving packets of different length.

Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND

*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 1;
const static uint8_t DESTINATION_RADIO_ID = 0;
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket1
{
    uint8_t FromRadioId;
    uint8_t Counter;
};

struct RadioPacket2
{
    uint8_t FromRadioId;
    char Message[31];    // Note the max packet size is 32, so 31 is all we can use here.
};

NRFLite _radio;
RadioPacket1 _radioData1;
RadioPacket2 _radioData2;

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

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }

    _radioData1.FromRadioId = RADIO_ID;
    _radioData2.FromRadioId = RADIO_ID;
}

void loop()
{
    // Pick a number from 0 - 60,000.
    uint16_t randomNumber = random(60001);

    if (randomNumber > 30000)
    {
        // Send RadioPacket1.

        _radioData1.Counter++;

        Serial.print("Sending ");
        Serial.print(_radioData1.Counter);

        if (_radio.send(DESTINATION_RADIO_ID, &_radioData1, sizeof(_radioData1)))
        {
            Serial.println("...Success");
        }
        else
        {
            Serial.println("...Failed");
        }
    }
    else
    {
        // Send RadioPacket2.

        // Create a message and assign it to the packet.
        // Strings need to be converted to a char array and note they cannot be longer
        // than 31 characters since that is the size of _radioData2.Message.
        String msg = "Hello " + String(randomNumber);
        msg.toCharArray(_radioData2.Message, msg.length() + 1);

        Serial.print("Sending '");
        Serial.print(msg);
        Serial.print("'");

        if (_radio.send(DESTINATION_RADIO_ID, &_radioData2, sizeof(_radioData2)))
        {
            Serial.println("...Success");
        }
        else
        {
            Serial.println("...Failed");
        }
    }

    delay(1000);
}
```

RX:
```
/*

Demonstrates sending and receiving packets of different length.

Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND

*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 0;
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket1
{
    uint8_t FromRadioId;
    uint8_t Counter;
};

struct RadioPacket2
{
    uint8_t FromRadioId;
    char Message[31];    // Note the max packet size is 32, so 31 is all we can use here.
};

NRFLite _radio;
RadioPacket1 _radioData1;
RadioPacket2 _radioData2;

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

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }
}

void loop()
{
    // 'hasData' returns the size of the packet that was received, or 0 if there is no data.
    uint8_t packetSize = _radio.hasData();

    if (packetSize == sizeof(RadioPacket1))
    {
        _radio.readData(&_radioData1);

        Serial.print("Received ");
        Serial.print(_radioData1.Counter);
        Serial.print(" from radio ");
        Serial.println(_radioData1.FromRadioId);
    }
    else if (packetSize == sizeof(RadioPacket2))
    {
        _radio.readData(&_radioData2);

        String msg = String(_radioData2.Message);

        Serial.print("Received '");
        Serial.print(msg);
        Serial.print("' from radio ");
        Serial.println(_radioData2.FromRadioId);
    }
}
```
```


body: @Erick Navarrte @dragonflyrobotics Thank you so much for your response, I've tried each an every option you've mentioned, but for an unknown reason it didn't work out for me. Then I researched more on and found out the NRF24L01 base module.This NRF24L01 base module help you to fix 8 pin NRF24L01 series RF module without any problem. And also this module comes with 3.3V regulator and a built in capacitor and easy pin connection to connect PIC or arduino. Using NRF24L01 module and NRF24L01 base module I was successfully able to transmit data.Thanks again for taking time in answering, highly appreciate it.


body:
I use Chinese clone nRF24L01. It has very narrow voltage tolerance. My Arduino is also clone.
The 3.3V output voltage was 3.27. The nRF24L01 was not working.  I added a 3 terminal regulator between Arduino 5V output pin and nRF24L01. The voltage was 3.303V.
Then nRF24L01 was working normally.

```c++
///////////////////////////////////////////////
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);
const byte rxAddr[6] = "00001";
void setup()
{
  radio.begin();
  radio.setRetries(15, 15);
  radio.openWritingPipe(rxAddr);
radio.stopListening();
pinMode(4,OUTPUT);
}
void loop()
{
  const char text[] = "Kawasaki_JP";
  radio.write(&text, sizeof(text));

  delay(1000);
}
////////////////////////////////////////////////

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);
const byte rxAddr[6] = "00001";
void setup()
{
  Serial.begin(9600);
  while (!Serial);
  radio.begin();
  radio.openReadingPipe(0, rxAddr);
   radio.startListening();
}
void loop()
{
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

////////////////////////////////////////////
```
library ;  https://downloads.arduino.cc/libraries/github.com/TMRh20/RF24-1.4.0.zip


message:
Arduino Pro Micro not recognized by PC

so I've got myself a Arduino Pro Micro ATmega32U4 5V 16MHz and my PC (Win10 64bit) won't recognize it.
So, after I firstly plugged it in, it was detected as a Leonardo, rather than a Pro Micro, afterwards I installed hte drivers as noted by Sparkfun, and added the board to the IDE. Afterwards, my Arduino got detected as an unknown device where I can't use it anymore. I tried installing the drivers as given by sparkfun over the "unknown device" and no luck by trying, I always get an error saying that Windows has already the best drivers for it already installed.

And later, I uninstalled the "uknown device" in hope that it will re-install itself upon pluggin it back it, and it actually disappeard totally and got repalced by "Unknown USB Device (Device Descriptor Request Failed)" under USB controllers in the Device manager.

And I'm stuck here. In the IDE, the Pro Micro is detected as being on "COM1" no matter what COM port it really is, or is it even plugged it at all. Uploading a code results in the bar being filled up and "Uploading..." message, while maybe after a few minutes a very long error pops up without anything specific since you can plug out the board and get the same error.

I also tried a different PC with Windows 7 64bit on it, and instead of getting recognized as a Leonardo, this time it came straight to becoming a "Unknown device". I tried installing drivers multiple times with no luck, also again tried manually overiding the drivers in the Device manager and it always says that the best drivers are already installed.

I'm really stuck here.
Pics of  the board: https://postimg.cc/gallery/rwCDRfv

body: It was wrong of you to try and install the driver as this board SHOULD be recognized as Leonardo. I would try to reinstall the Arduino IDE, it will also reinstall the drivers (hopefully)


body:
I got similar problem, I was trying to burn some HEX files and somehow, my windows wasn't able to recognize my atmega32u4 anymore, not even in Device Manager. I found that the bootloader was "bricked", and to fix it, you need to burn a valid HEX file, like the simplest led blink code. I've done that by the prompt command, using avrdude. So you reset twice, and you have 8 seconds to upload the hex file. It's faster doing that with prompt command than arduino software. After I uploaded the LED blink code successfully, the windows naturally recognized my atmega32u4 instantly, I could identify it in Device Manager as PCOM 4 since then. So you need to revive your bricked atmega's bootloader.
I guess there's nothing to do with the drivers in this case.


message:
Getting enum name from enum instance

Hello Arduino Stack Exchange,

I have an an `enum` instance called `state`:

```lang-C
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;
States state = SLEEP;
```

I would like to convert the value of `state` to a `String` so I can serially print it using `Serial.println()`.

Currently, when I type `String(state)`, I get a value `0`, `1`, etc.  I suppose this corresponds with the index of the `enum`'s key.

How can I get it to return `"SLEEP"`, `"AWAKE"`, etc.?

body:
You can print the value as it is:
```
Serial.println(state);
```
This will print the the ordering number of the enum, but you can specify the value as any number **or char**.
```
enum States
{
  SLEEP = 'S',
  AWAKE = 'A',
  CRAZY = 'C'
};
```
Now if you print it with cast to char `Serial.println((char) state);` it will print a character, which in my opinion is much better then some number.

If you want to convert the enum values identifiers to strings you can do it with a preprocessor macro.
```
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;

#define IDNAME(name) #name
const char* stateNames[] = {IDNAME(SLEEP), IDNAME(AWAKE), IDNAME(CRAZY)};
```
I don't think this is better then to print the char values. To do a pretty print it is better to use descriptions.
```
const char* stateStr[] = {"Sleep", "Awake", "Undefined"};
Serial.println(stateStr[state]);
```


message:
Possible to drive Waveshare E-ink without driver hat?

I bought and E-Ink display from waveshare and it came with such a “driver hat”: https://www.waveshare.com/wiki/E-Paper_Driver_HAT#Display_Config_Switch

I am wondering what exactly is the role of this component? Why can’t I directly connect the cables from the display to the GIPO pins and drive the display without the driver hat - given the right software?

(I am also happy to get a pointer to a better forum to ask in if this here isn’t the right place.)

body:
No, you need the hat, or something equivalent. Turn it over. You see all those components? They exist to generate the right voltages for the ePaper display. Without those it won't work.

Sure, you can recreate it from [the schematic](https://www.waveshare.com/w/upload/8/87/E-Paper-Driver-HAT-Schematic.pdf), but why bother when you have it already?


message:
Liquid Crystal LCD and serial monitor not playing well together

On my Arduino Uno, when I'm not using the serial everything seems in order:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

    void setup()
    {
        // put your setup code here, to run once:
        lcd.begin(16, 2);
        lcd.clear();
        lcd.print("Prints");
        lcd.setCursor(0, 1);
        lcd.print("Well");
    }

    void loop()
    {
        delay(1000);
    }

However the moment I open the serial port with:

    Serial.begin(9600);

The problem starts.

Clearing the LCD does not clear it but prints a character with 4 horizontal lines. Trying to move the cursor will print a different  unrecognisable character. Sending things to the Arduino via the Serial port prints gibberish on the LCD.

[![character with 4 horizontal lines][1]][1]

Any idea why? Is there a way to work with the LCD and the serial port simultaneously? I require the serial port in order to control the Arduino from NodeJS.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

    void setup()
    {
        // put your setup code here, to run once:
        lcd.begin(16, 2);
        lcd.clear();
        lcd.print("Prints");
        lcd.setCursor(0, 1);
        lcd.print("Well");

        Serial.begin(9600);

        while (!Serial)
        {
            ; // wait for serial port to connect. Needed for Native USB only
        }
    }

    void loop()
    {
        lcd.clear(); // This will print 4 horizontal lines character instead of clearing
        delay(500);
    }

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

body:
On an UNO pin 1 is one of the hardware serial pins.  You can’t use pin 0 or pin 1 for other things if you are using Serial in your code.

Even if you aren’t using Serial, you use pins 0 and 1 when uploading your code and having other things connected can mess up that process.  It’s generally advisable to stay away from pins 0 and 1 unless you absolutely must use them.


message:
Motor does not work for a specific case when programming with L293D motor driver shield

I tried to make a car that moves using a 4x4 keypad.
Pressing "12" unlocks the car and sets the motors to move forward. After that, if I press 4, the speed of the left motor is reduced to half allowing the motor to turn left, and vice versa for right wheel when key 6 is pressed.

Here is the code:

```
#include <Key.h>
#include <Keypad.h>

char* startCar = "12";
int position = 0, state = 0;

/*
 * state 0: off
 * state 1: forward
 * state 2: backward
 *
 */

const byte rows = 3;
const byte cols = 3;
char keys[rows][cols] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'}
};

byte rowPins[rows] = {2,3,4};
byte colPins[cols] = {PD7, PD6, PD5};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);

int a=12,b=11,c=10,d=9;
void setup()
{
  pinMode(a,OUTPUT);
  pinMode(b,OUTPUT);
  pinMode(c,OUTPUT);
  pinMode(d,OUTPUT);
  Serial.begin(9600);
  setLocked(true);
}

void loop()
{
  char key = keypad.getKey();
  Serial.print(key);
  if (key == '9')
  {
    position = 0;
    setLocked(true);
  }
  if (key == startCar[position])
  {
    position ++;
  }
  if (position == 2)
  {
    setLocked(false);
  }
  if(state)
  {
    if(key=='2')
     {
      //Move forward
        state = 1;
        runmotors(255,0,0,255);
     }
     if(key=='8')
     {
      //Move backward
        state = 2;
        runmotors(0,255,255,0);
     }
    if(key == '4')
    {
      if(state == 1)
      {
        runmotors(127.5,0,0,255);
      }

      else if(state==2)
        runmotors(0,127.5,255,0);
    }
    if(key == '6')
    {
      if(state == 1)
        runmotors(255,0,0,127.5);
      else if(state==2)
        runmotors(0,255,127.5,0);

    }
  }
  delay(100);
}

void setLocked(int locked)
{
  if (locked)
  {
    state = 0;
    runmotors(0,0,0,0);
  }
  else
  {
    state = 1; // Moves forward
    runmotors(127.5,0,0,255);
  }
}
void runmotors(int s1,int s2,int s3,int s4)
{
  analogWrite(a,s1);
  analogWrite(b,s2);
  analogWrite(c,s3);
  analogWrite(d,s4);
}
```

Everything works perfectly, except for the fact that when the state is 1, i.e. car is running forward, and I press 4 the left motor completely stops instead of reduced speed. The LED on the motor driver shield which shows whether a motor is running or not also goes off.
It is not a fault of the motor shield or the arduino as it worked when I test it individually with the motors (i.e. without the keypad etc).

Here is a photo of the shield:
[![Arduino motor driver shield][1]][1]

Although my problem is not quite visible in this, but here is a video of the car: https://www.youtube.com/watch?v=bq19gNOL8Pg

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

body:
On an UNO only certain pins are capable of PWM.  Pin 12 is not one of them.  When you try to call analogWrite with pin 12 it will recognize this and will simply call digitalRead for you with HIGH or LOW depending on whether your input is greater than 127.

With most motor controllers you can use one pin as a direction pin and the other as a PWM pin.  So to go one direction you set pin 12 HIGH and do inverted PWM on 11 (if those indeed go to the same motor I didn't look at your shield).  To go the other direction you write LOW on 12 and PWM on 11.

The motor turns when one pin is HIGH and the other is LOW.  When you set pin 12 high then PWM pin 11, whenever 11 is LOW in the PWM cycle it is turning the motor on and when it is HIGH it is turning it off.  So to make it run you might have to PWM 0 for go and 255 for stop.  Sometimes your PWM is on the enable line and then you still use 255 for go and 0 for stop.  It just depends on how things are wired.

When pin 12 is set to LOW then the motor is on when 11 is at the high part of the PWM cycle and off when it's low so you use 255 for go and 0 for stop.  But the whole time pin 12 doesn't have to change.

Now I am not 100% sure that this is the case with your particular motor controller, I'm more of a coder than a hardware guy.  But I've written enough code for motor controllers to know that you usually either need two direction lines and one PWM line or one direction and one PWM.  If that's not the case here then we can let someone else work on why.


message:
SPI Slave Programming for Arduino

In my application Arduino Due is configured as master and instead of the actual slave device I am making use of Arduino Uno as Slave.I will share the Master code which I have worked out. Can Anyone please help me with respect to slave code of Arduino Uno to display the data in serial monitor at slave side. Any Help With respect to this aspect will be greatly greatly appreciated.

    #include <SPI.h>

    SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
    const uint8_t ss = 10;

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

      SPI.begin();

      digitalWrite(ss, LOW);
      SPI.beginTransaction(mySettting);
      SPI.transfer(0x00);
      SPI.transfer(0x25);
      SPI.transfer(0x1C);
      SPI.endTransaction();
      digitalWrite(ss, HIGH);
    }

    void loop() {
    }

----------

Thanks for the reply.
Referring to the code attached below at the slave side as you have mentioned that HEX to be displayed in serial monitor window, Do I need to add the HEX at the master side I mean Do I need to load the Hexadecimal data (0x00251C) into HEX buffer??

Thanks in Advance

    #include <SPI.h>

    SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
    const uint8_t ss = 10;

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

      SPI.begin();

      digitalWrite(ss, LOW);
      SPI.beginTransaction(mySettting);
      SPI.transfer(0x00);
      SPI.transfer(0x25);
      SPI.transfer(0x1C);
      SPI.endTransaction();
      digitalWrite(ss, HIGH);
    }

    void loop() {
    }

body:
SPI.h library by default only support Master mode, the `SPI.begin()` will automatically set slave select (ss) pin to HIGH whether you have `pinMode(ss, OUTPUT)` in your setup() code or not and set the Arduino as an SPI master. This can be see on SPI library [source code](https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/SPI/src/SPI.cpp#L36-L51).

As the SPI library does not contain the functionality for slave mode, in order to use Arduino as a Slave, you will need to do some customised setup, mainly on 1) setting MISO as OUTPUT for slave to send data; 2) enable slave mode by setting the SPCR register; 3) enable interrupt when data is received. Here is an example for an SPI slave on Arduino.

    #include<SPI.h>

    volatile boolean received;
    volatile byte receivedData;

    ISR (SPI_STC_vect)        //Inerrrput routine function
    {
      receivedData = SPDR;   // Get the received data from SPDR register
      received = true;       // Sets received as True
    }

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

      pinMode(MISO,OUTPUT);   //Sets MISO as OUTPUT
      SPCR |= _BV(SPE);       //Turn on SPI in Slave Mode
      received = false;
      SPI.attachInterrupt();  //Activate SPI Interuupt
    }

    void loop()
    {
      if(received) {
        SPDR = receivedData;    // send back the received data, this is not necessary, only for demo purpose
        received = false;
        Serial.print(receivedData, HEX);
      }
    }