body:
I have 4 hx711 and each one reads 1 cell, i was using the 10hz mode, however, this was making my application very slow, as I needed to take 5 readings and take the average of these, when I put the 15 RATE in 1, it is having a lot of noise, despite having speeded up the reading of the weights, sometimes the variation is up to 3 digits at the end. See the code for reading the modules where I already show the weights in Kg:

```
n=6;
for(int x=0;x<n;x++){

v1[x] = CELL1.read();

v2[x] = CELL2.read();

v3[x] = CELL3.read();

v4[x] = CELL4.read();
}
v1m=0;
v2m=0;
v3m=0;
v4m=0;

for(int x=1;x<n;x++){ // sum of array
v1m=v1m+v1[x];
v2m=v2m+v2[x];
v3m=v3m+v3[x];
v4m=v4m+v4[x];
}
//mean array
v1m=v1m/(n-1);
v2m=v2m/(n-1);
v3m=v3m/(n-1);
v4m=v4m/(n-1);

p1=p;
p=((v1m-v10)/(M[1]) +(v2m-v20)/(M[2]) +(v3m-v30)/(M[3]) +(v4m-v40)/(M[4]))/2.5; // show the
weight in Kg
p=p*.7+p1*.3; // convert to kg
// ... i print the p (weight in Kg) now...
```

title: How to reduce noise when using 80Hz mode?

Answers: 1

body: I had a very similar problem with 4 load cells.  I ran 10,000+ readings at 80Hz, copied the serial monitor into MS Word to find my string (text) value labels and replace them with nothing. This lets me keep the numbers.  If you copy that into Excel and make a scatter plot graph you can see where your highs and lows are and their magnitudes.  I was able to simply write an IF condition to reject those outliers.  Interestingly the outliers are very large (positive or negative) and they weren't just random values. They were also occurring at a specific frequency that may have more to do with my application rather than being an element to your solution.


body:
I would like to create something similar to a multidimensional array.
I would like to get this effect.

```
setting = [
     0 => [// 0 is the day of the week, but it can be a number
         '1:25' => 25, // key is time. The value is a number (temperature)
         '7:12' => 22,
         '15: 30 '=> 21,
         '18: 00 '=> 23
         '22: 25 '=> 22
     ]
     1 => [
         '1:25' => 25,
         '7:00' => 21,
         '15: 00 '=> 22,
         '18: 00 '=> 25
         '22: 25 '=> 22
     ]
     2 => [
         '1:25' => 25,
         '7:00' => 21,
         '15: 32 '=> 21,
         '18: 40 '=> 25
         '22: 25 '=> 22
     ]
     .
     .
     .
     e.t.c
];
```
Then I would like to read these values. Days of the week and time are already downloading, but I do not know how to make such a board. I would like to download these values (temperature) to a variable.
Regards

title: Multidimensional array with date and numbers

Answers: 0


body:
I would like to change the delay() into a nonblocking function in the code below. I've implemented it (a part of a tutorial from arduino.cc) in my code, but the delay() is blocking the rest of my code. Can anyone help me to change this?

```
void speelMelodie(int melodie){

if(melodie == 1){

      for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      tone(speaker, melody1[thisNote], noteDuration);

      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes); // <-- this one has to be changed

      noTone(speaker);
      }
  }

else if (melodie == 2) {
      // the same part as previous part (for loop)
  }

else if (melodie == 3) {
      // the same part as previous part (for loop)
  }
}
```

title: Remove blocking delay() toneMelody function?

Answers: 1

body:
Define  global vars befor setup()

    unsigned long timeStamp = 0;
    bool pauseOn = false;

and use it

 void speelMelodie(int melodie) {

   if (melodie == 1) {

  for (int thisNote = 0; thisNote < 8; thisNote++) {

    int noteDuration = 1000 / noteDurations1[thisNote];
    if (millis() - timeStamp < noteDuration && pauseOn == false) {
    tone(speaker, melody1[thisNote], noteDuration);
    } else { // reset value and change pauseOn to true
   pauseOn = true;
   timeStamp = millis();
    }
    int pauseBetweenNotes = noteDuration * 1.30;

    //delay(pauseBetweenNotes); // <-- this one has to be changed
    if (millis() - timeStamp < pauseBetweenNotes && pauseOn == true) {
     noTone(speaker);
    } else {
    pauseOn = false;
    timeStamp = millis();
    }
  }
   }
 }

We need the state variable pauseOn to differentiate between the two states play note or silence. The code compiles, but you have to finetune in your program.
**A final tip** Tutorials **using delay()** other than

  - for debuging or
  - in setup for initializing hardware

are of very low quality

-> Its like a blind person talking about color composition.


body:
I have the following code in a Arduino Mega function to retrieve two 4-byte integers from a Teensy 3.2.

 Wire.requestFrom(SLAVE_ADDR, sizeof(float)+ 2*sizeof(long));
 mySerial.printf("\n<<<<<<<   In IsIRBeamAvail()  >>>>>>>>>>>>>>>>>>>>\n\n");
 mySerial.printf("Wire.Available() reports %d\n", Wire.available());
 I2C_readAnything(Fin1);
 mySerial.printf("Read Fin1 %d, Wire.Available() reports %d\n",Fin1, Wire.available());
 Fin2 = Fin1;
 mySerial.printf("Fin1 = %d, Fin2 = %d\n", Fin1, Fin2);
 I2C_readAnything(Fin2);
 mySerial.printf("Read Fin2 = %d, Wire.Available() reports %d\n", Fin2, Wire.available());
 mySerial.printf("Fin1 = %d, Fin2 = %d and SteeringValue = %2.2f\n", Fin1, Fin1, SteeringValue);
 mySerial.printf("Read %f, Wire.Available() reports %d\n", SteeringValue, Wire.available());
 mySerial.printf("Fin1 = %d, Fin2 = %d and SteeringValue = %2.2f\n", Fin1, Fin1, SteeringValue);

And this produces the following output:

    <<<<<<<   In IsIRBeamAvail()  >>>>>>>>>>>>>>>>>>>>

    Wire.Available() reports 12
    I2C_readAnything: Sizeof(value) = 4
    Read Fin1 5375, Wire.Available() reports 0
    Fin1 = 5375, Fin2 = 0
    I2C_readAnything: Sizeof(value) = 4
    Read Fin2 = 10750, Wire.Available() reports 0
    Fin1 = 5375, Fin2 = 0 and SteeringValue = 0.00
    Read 0, Wire.Available() reports 4
    Fin1 = 5375, Fin2 = 0 and SteeringValue = 0.00

This is driving me nuts, because while the Fin1 & Fin2 values are apparently received correctly, the Fin2 value is always reported as 0, even after it was explicitly set to be equal to Fin1 as a test (line 6 in the code).

The values obtained from the Teensy (5375 and 10750 in the output snippet) are correct, but I can't get Fin2 to print out correctly (the 'SteeringValue' issue is probably the same as the 'Fin2' problem, but I haven't gotten there yet).

I cannot for the life of me figure out what I'm doing wrong here.  Could someone walking by take a glance from 30 feet away and immediately see the problem?

TIA,

Frank

 3/31/20 Update:

I finally got Wire.requestFrom() & I2C_Anything() to behave the way I thought it should, but I'm still left with a mystery - why the PrintEx version of printf refuses to print the values properly:  Here's the code snippet:

 //get latest info from IR Demod Module
 long Fin1 = 0; //03/30/20 needs to be 'long int' (4 bytes) here to match Teensy int (4 bytes)
 long Fin2 = 23; //03/30/20 needs to be 'long int' (4 bytes) here to match Teensy int (4 bytes)
 float SteeringValue;

 mySerial.printf("\n<<<<<<<   In IsIRBeamAvail()  >>>>>>>>>>>>>>>>>>>>\n\n");

 Wire.requestFrom(SLAVE_ADDR, sizeof(Fin1) + sizeof(Fin2)+ sizeof(SteeringValue));
 mySerial.printf("Wire.Available() reports %d\n", Wire.available());

 I2C_readAnything(Fin1);
 mySerial.printf("Fin1 = %d\n", Fin1);

 I2C_readAnything(Fin2);
 mySerial.printf("Fin2 = %d\n", Fin2);

 I2C_readAnything(SteeringValue);
 mySerial.printf("SteeringValue = %2.3f\n", SteeringValue);

 mySerial.printf("Fin1 = %d, Fin2 = %d, SteeringVal = %6.3f\n", Fin1, Fin2, SteeringValue);

And here's the output produced.  As you can see, the individual values print out correctly, but when combined into the last mySerial.printf() statement, things go awry.  Anyone have a clue?

    Wire.Available() reports 12
    I2C_readAnything: Sizeof(value) = 4
    Fin1 = 1986
    I2C_readAnything: Sizeof(value) = 4
    Fin2 = 3972
    I2C_readAnything: Sizeof(value) = 4
    SteeringValue = 6239.219
    Fin1 = 1986, Fin2 = 0, SteeringVal =  0.000

Frank

And one last update:  I compared the output obtained by using the StreamEx mySerial = Serial; object, and the one obtained by using the more traditional Serial.print() statement.  The code

     Serial.print("Fin1 = "); Serial.print(Fin1); Serial.print(", ");
 Serial.print("Fin2 = "); Serial.print(Fin2); Serial.print(", ");
 Serial.print("SteeringValue = "); Serial.println(SteeringValue);
 mySerial.printf("Fin1 = %d, Fin2 = %d, SteeringValue = %3.2f\n", Fin1, Fin2, SteeringValue);

And the output:

    Fin1 = 9185, Fin2 = 18370, SteeringValue = 28851.73
    Fin1 = 9185, Fin2 = 0, SteeringValue = 0.00

The top line is entirely correct, but for some reason, the mySerial.printf() version gets it wrong. Ideas?

Frank

title: Crazy Results with I2C and I2C_Anything()

Answers: 1

body:
The devil is in the details. From the PrintEx repo [doc][1], this is the formatting for printf:

> %[flags][width][.precision][length]specifier

When you use ***long***, you will have to provide the [length], and the lib only accepts "**l**" (Letter L).

    #include <PrintEx.h>

    long int Fin1 = 5;
    long int Fin2 = 2;
    float SteeringValue = 3.5;

    void setup()
    {
      Serial.begin(9600);
      PrintEx mySerial = Serial;

      Serial.print("Fin1 = "); Serial.print(Fin1); Serial.print(", ");
      Serial.print("Fin2 = "); Serial.print(Fin2); Serial.print(", ");
      Serial.print("SteeringValue = "); Serial.println(SteeringValue);

      // This will fail
      mySerial.printf("Fin1 = %d, Fin2 = %d, SteeringValue = %3.2f\n", Fin1, Fin2, SteeringValue);

      // This will work as expected
      mySerial.printf("Fin1 = %ld, Fin2 = %ld, SteeringValue = %3.2f\n", Fin1, Fin2, SteeringValue);
    }

    void loop() {}

Line 16 is what you have. Line 19 is the format you should use.

  [1]: https://github.com/Chris--A/PrintEx


body:
I'm writing a program for an ATmega microcontroller using the Arduino framework.
While implementing an hardware-related class (one to manage LEDs), I put some hardware initialization code such as `pinMode(OUTPUT)` in the class constructor. Then I realized that in all Arduino libraries I know the hardware initialization is done in a `begin()` or `init()`, so I created one for my Led class as well and moved `pinMode()` there.

Now I'm wondering if I really should define such initialization funcitons, i.e. why they are needed - or, if they are not, why so many libraries have them. I played around a bit and found that for example this code works on an ATmega1284 (it makes the LED on pin 28 light up).
```cpp
struct Test {
  Test() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
    // other stuff
  }
  // ...
};

Test test;

void setup() {
}

void loop() {
}
```
I presume that this code is somehow ill-conceived, letting alone the fact that it lights up a led without any code in the main function (or maybe that is exaclty the problem?), but if so I can not see why. What did I not consider?
Should the code above be rather writte as in the following snippet, as the existence of all these `begin()` functions leads me to believe?

```cpp
struct Test {
  Test() {
    // other stuff
  }
  void begin() {
    pinMode(28, OUTPUT);
    digitalWrite(28, HIGH);
  }
  // ...
};

Test test;

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

void loop() {
}
```

title: Why are begin() functions needed to initialize hardware (if they are)?

Answers: 1

body:
It's all to do with the order of execution.

Constructors are executed before normal functions. That includes the `main()` function which eventually calls `setup()` and (repeatedly) `loop()`. One of the other things that `main()` does is call `init()` (or some variant of) which configures the hardware.

Since that happens *after* any global constructors have been run anything that the constructor did to the hardware could potentially be undone.

Thus it is normal to defer any hardware configuration until *after* `main()` has done the work of setting things up, and the convention is to use a `begin()` function to do it.


body:
I'm trying to generate a consistent 153,600Hz square wave signal with 50% duty cycle from a Adafruit SI5351 3.3-5v breakout board for use as a fixed synchronous serial clock reference, but the closest frequency I get from it is 142,857Hz which is too far off the target.

Originally, I followed [this][1] article (my device looks exactly like the one in the pictures) from Adafruit to no avail. I tried using the Adafruit library and the mentioned ClockBuilder software, but the article makes no mention of how to apply the values returned from the software into code, and messing with the values myself didn't help either.

So, I then moved on to using [this][2] library from etherkit. It's has a lot simpler interface, and was easy for me to get at least something being output.

Here is my current code using the etherkit library running on my Arduino Mega. It seems to only output 142,857Hz, even though I specified my target frequency of 153,600Hz.

```cpp
//Arduino Mega
#include "si5351.h"
#include "Wire.h"

Si5351 si5351;

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

    if (!si5351.init(SI5351_CRYSTAL_LOAD_8PF, 0, 0))
    {
      Serial.print("Cannot communicate with SI5351.");
    }
    else
    {
      si5351.drive_strength(SI5351_CLK0, SI5351_DRIVE_8MA);
      si5351.output_enable(SI5351_CLK0, 1);
      si5351.set_freq(153600ULL * 100ULL, SI5351_CLK0);
    }
}

void loop(){}
```
But here is where it gets odd: I can set the frequency argument of `set_freq` to anything under `120000ULL * 100ULL` and the output will be spot on, but anything above that amount will "snap" back to 142,857Hz, up to `190000ULL * 100ULL`.

The other thing I got working against me is that I don't have access to a oscilloscope to more accurately measure it's output. My current solution is a Arduino UNO acting as a frequency measuring tool, running the following code:

```cpp
//Arduino Uno
#define pin_MeasureThis A0

volatile unsigned long on_time;
volatile unsigned long off_time;

float lfreq;
float freq;
char freq_str[12];
char msg[32];

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

void loop()
{
  on_time = pulseIn(pin_MeasureThis, HIGH);
  off_time = pulseIn(pin_MeasureThis, LOW);
  freq = 1000000 / (on_time + off_time);

  if (freq >= 0 && freq < 999999)
  {
      dtostrf(freq, 8, 0, freq_str);
  }

  if (freq != lfreq)
  {
    lfreq = freq;

    sprintf(msg, "%sHz", freq_str);
    Serial.println(msg);
  }
}
```
I tested my measuring code by comparing it's measurement against visible frequencies with a LED and it performed perfectly. I do understand that probably doesn't scale well for higher frequencies, but I really have no better way right now.

Here is a sample of the exact serial output I get back from my Arduino UNO measuring the CLK0 output of the SI5351 breakout board:
```
  ...
  142857Hz
  125000Hz
  142857Hz
  125000Hz
  ...
```
Any advice on how to get to a steady 153,600Hz signal would be much appreciated. Thanks.

  [1]: https://learn.adafruit.com/adafruit-si5351-clock-generator-breakout/wiring-and-test
  [2]: https://github.com/etherkit/Si5351Arduino

title: SI5351 Breakout 153,600Hz Square Wave Signal

Answers: 0


body:
I tried the tutorial in this link

<https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/>

to send an SMS message using a SIM900 GSM shield

I completed the section to send AT commands successfully but I can't get
the Arduino Uno to send an SMS. Below is the output I get after doing AT command tests

```
Initializing...
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CSQ

+CSQ: 6,0

OK
AT+CCID

8944500105191448516F

OK
AT+CREG?

+CREG: 0,5

OK
AT+COPS?

+COPS: 0,0,"T-Mobile "

OK
AT+COPS=?

+COPS: (2,"T-Mobile ","T-Mobile ","310260"),,(0,1,4),(0,1,2)

OK
```

and below are the responses from the SMS code

```
Initializing...
AT

OK
AT+CMGF=1

OK
AT+CMGS="+1mycellphonenumber"

> Last Minute Engineers | lastminuteengineers.com
```

so no response from the AT+CMGS command and NO SMS received.
Plug is 5V 2A.

Any idea what might be causing the issue?

Below is the code I used for the Setup() function

```
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+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
  updateSerial();
  mySerial.write(26);
}

```

title: Arduino SIM900 No SMS received

Answers: 2

body:
Normally in Setup() you have in the end this sequence

    Serial.println("Connecting to the network...");

    while( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) ||
        sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 );

         sprintf(aux_str, "ATD%s;", phone_number);
         sendATcommand(aux_str, "OK", 10000);

         delay(seconds * 1000);

        Serial.println("ATH"); // disconnects the existing call

So after the registering you send

     Serial.println("AT+CMGS=\"1234567890\""); //CHANGE TO DESTINATION NUMBER

Did you use the \" for the embracing the number. Without your real command its hard to guess. Better use a [test program Soft Serial GPRS Code](https://researchdesignlab.com/modules/gsm-modem-arduino-compatible.html), serial monitor is error prone.
**EDIT** The OP posted code parts. The code after:

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

should be in the loop()- Look at the linked examples how should communication take place if the code is run once so no recurring tasks like reading chars or similar.

body: Changed my SIM card to Ting from Hologram and it worked just fine!


body:
I have a problem , when send 1 or 0 by Bluetooth module the serial monitor print two time **(RECEIVED SMS)** . what's the wrong ?

**This is my code  :**

       char BluetoothData = 0 ;
    void setup() {
      // initialize serial communication:
      Serial.begin(9600);
        for (int pin = 1; pin <= 13; pin++)
         {
           pinMode(pin, OUTPUT); // sets the digitals pin  as outputs
           digitalWrite(pin, LOW); // sets the digitals pin off defult intial states
         }
           Serial.println("ALL LEDs NOW OFF \n ");
           Serial.println("Please, Enter : ( 1 to Turn on All LEDs )  or ( 0 to Turn off LEDs ) \n");
    }
    void loop() {
      // read the sensor:
      if (Serial.available() > 0) {

            BluetoothData = Serial.read();
                Serial.print("*** RECEIVED SMS *** : ==>> ");
                Serial.println(BluetoothData);

            if (BluetoothData == '1'){
            for (int Pin = 1; Pin <= 13; Pin++) {
              digitalWrite(Pin, HIGH);
              }
              Serial.println("ALL LEDs NOW ON");
             }
            // turn all the LEDs off:
       else if (BluetoothData == '0') {
            for (int Pin = 1; Pin <= 13; Pin++) {
              digitalWrite(Pin, LOW);
              }
              Serial.println("ALL LEDs NOW OFF");
             }
      }
       delay(100);
    }

**This is photo for serial monitor**

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

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

title: serial is print twice?

Answers: 2

body:
Probably the first time because you received the character '1' or '0'.
The second character is probably a '\0' or '\d', an `end-of-string` or `end-of-line` character.

You can easily check this by printing the value of each received character, like

    Serial.println((int)(BluetoothData));

You probably see the value for '0' (48), '1' (49), end of string '0' of end of line '13' or maybe '10' (new line).

body: In the Arduino IDE you should select "No Line Ending" from the menu, instead of "New line". Otherwise you are sending an extra "\n".


body:
I am using xbee pro s2c to get data from arduino (temp, pressure etc.) and I am sending data another xbee module and read these data from serial port.

Question is that I want to use esp8266 instead of xbee. Is it possible? Can I communicate 2 esp module like xbee?

title: Using esp8266 instead of xbee

Answers: 1

body: You can make two ESP8266 modules talk together, yes. It's not "simple" like an XBee, since you have a generic WiFi network interface, so there's many many different ways of doing it. Typically one would be running as a WiFi Access Point (SoftAP) and the other would connect to it. Then you'd run some "server" code on one module (typically the SoftAP one) and the other acts as a client and connects to it (or sends data to it).


body:
(Arduino Mega2560) I'm trying to test placing a counter n in a for loop, the problem is, every time it gets out and goes back to the for loop, the n is reset again, so it prints "counter: 245" every time. However, when I comment out *b++=data; and data++; it does count properly. What exactly is going on ?!

Code:

    uint8_t i=0;
    uint8_t buf[245];
    uint8_t *b=buf,*b2=buf;
    uint8_t data=10;
    int n=0;

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

    void loop() {
    for(i=0; i<245 ;i++){
      *b++=data;
      data++;
      delay(50);
      n++;
      Serial.println(buf[i]);
      }
      data=0;
      delay(5000);
      Serial.println("counter:");
      Serial.println(n);
      delay(5000);
    }

title: Counter variable gets reset to 0 without resetting it(Mega)

Answers: 1

body:
You never reset your `b` pointer. The first time through it works its way through the memory reserved for `buf`. The second time through your loop it's already at the end of that memory and you then start incrementing (and filling) past that overwriting other variables - the first of which sounds like it might be `n` - so `*b++=data` is writing `data` (245) to `n`.

You need to reset `b` each time you go through loop so it starts at the beginning of the array each time:

    b = buf;


body:
as the question title states, how will I go about turning the servo opposite of 90 degrees?

I have written my code as such;

      // Turn servo to the right
      if(x > 520 && y < 510 && y > 490){
      servo.write(0);
      delay(50);

      //Turn left
      }else if(x < 490 && y < 510 && y > 490){
        servo.write(180);
        delay(50);

     //Turn backwards
    } else if(y < 490 && x < 520 && x > 490){
      servo.write(-90);
      delay(50);

Obviously -90 isn't an actual degree on the servo, and it will only turn between 0 and 180. I was therefore wondering if there was any other way to code it?

The servo is connected to a joystick, and the plan is to built a 360 degrees vertical and 180 degrees horizontal turret of sorts. Every other command works, and when I replace -90 with 90 degrees, it works as well. So it is wired correctly.

Of course I would have to add another joystick and another servo later on, but at this stage I am simply testing my own coding skills.

title: Programming Servo How To Get -90 Degrees

Answers: 3

body:
Normal servos only have a range of 180°. You can give yourself an "offset", so you have -90° to 90°, but you only ever get 180° range. You can't go -90° to 180°.

Using mechanics (outside the scope of this site) you can multiply your movement (think gears) so that your range is bigger.

body:
You say "The servo is connected to a joystick, and the plan is to built a 360 degrees vertical and 180 degrees horizontal turret of sorts. "

That doesn't make sense. How could a joystick rotate 360° in one dimension and 180° in the other dimension?

A joystick does not need an angle greater than 180°. It's mounted to a flat surface, and can only move 180° in two different dimensions, X and Y. (And actually probably more like 120° in each dimension.)

Use two 180 degree servos, one for the X axis and one for the Y axis.

Set the "neutral" position to 0

You can map the range 0 - 1320  to -90 to 90 using a map statement. (or adjust as needed since the range of motion of the joystick is probably less than 180 degrees - more like 120°, like  chrisl said in their comment.)

See [**this article**][1] for info on how a 2-axis joystick works. Specifically look at the section titled "Gimbal Mechanism" a little ways down in the article.

  [1]: https://lastminuteengineers.com/joystick-interfacing-arduino-processing/

body:
If I understand correctly, you only need to move your servo through 180 degrees total, from one limit to the other, but you want -90 to represent one of the limits and +90 to represent the opposite limit? If so, just add 90 to the servo angle before you send it:

    servo.write(angle+90);

This turns -90 into 0, 0 into 90, and 90 into 180. You get to use the coordinates that you like (-90 - +90) and the servo sees the coordinates it needs (0 - 180).

This is a simple case of mapping; there is a map() function that can do this for you for all mapping all kinds of ranges, one into another. Mapping (-90 - 90) into (0 - 180) is so straightforward that the map function really doesn't add anything, but in other cases it's handy to know about.


body:
# Introduction
I've been meaning to build a vehicle using arduino components and LEGO. I have a mechanical clamp built with arduino which will be locked on top of a custom LEGO build (It should be made out of LEGO blocks and arduino sensors). In my mind, it resembles a crawler.

# Question
I've been looking for a way of controlling it remotely.
I only have experience with IR controllers but I'm not sure if this technology would fit for my project.

What I'm looking for is a technology wich could transmit data to an Arduino board (thus, an emitter and a receiver component) which, in my case, could comfortably handle a veichle.

Plus, it should have a range of action of at least 5 meters (15 ft).

If such technology exists, do you know any controller which could do the job for me?

title: Arduino-compatible wireless technology which can be suitable for transmitting data

Answers: 2

body:
You can use radio transmitter/receivers, they are typically called RF (Radio Frequency) modules.

Typical examples are nRF24L01+ (2.4 GHz), or RF 315/433 modules (on 315/433 MHz).

There are more possibilities, but these are the most used on Arduino and libraries are available.

body:
Try a pair of Wixels (https://www.pololu.com/product/1336).  A pair of Wixels (one at the PC, one on the crawler) act as a fast USB cable emulator.  The PC-connected Wixel shows up as a USB port, and the one on the crawler (with a Wixel sheild) emulates the Arduiono end of a USB cable.  These are very easy to use, and in addition to remote control will allow you to wirelessly program the Arduino controller.

The ability to remotely program the crawler is a real god-send, as now you don't have to retrieve the crawler and connect it to a hardware USB cable for programming.

Just my $0.02

Frank


body:
I am trying to explore the possibilities of connecting an Arduino to Phonegap/Cordova. I have a RedBearLab BLE Shield, which I want to test the connection with. My MVP would be to get the value of a PIN to a Cordova app. Nevertheless, I couldn't make it even close.

The closest I got, it was using Don Coleman's [Phonegap plugin][1].
I am trying his [Simple Chat example][2].

With this example the sketch is attempting to include `Nordic_nRF8001.h`. Nevertheless, I can't seem to find this library. I downloaded it from various sources, but no matter what I do, my sketch still can't find the file.

The only way I could make it work was via CodeBender, but then the readings were a bit of a mess.

I'm not expecting anyone to do all the work for me, so if you can help me in one of the two directions, it would be awesome:

1. Figure out why I can't find that Nordic_nRF8001.h file.
2. Or help me find another method of BLE communication.

**Later edit**
Using the examples that come with RBL library, I figured out the name of the files I need to use. Now I'm running into another problem for which I opened [a new question][3].

Thank you!

  [1]: https://github.com/don/cordova-plugin-ble-central
  [2]: https://github.com/don/cordova-plugin-ble-central/tree/master/examples/redbearlab
  [3]: https://arduino.stackexchange.com/questions/74595/simplechat-ble-example-prints-scrambled-characters

title: How to connect RedBearLab BLE shield (Or how to find Nordic_nRF8001.h)?

Answers: 1

body:
I used Arduino Create Web Editor to load the SimpleChat example. It loads with these libraries, and it works perfectly:

    #include <SPI.h>
    #include <EEPROM.h>
    #include <boards.h>
    #include <RBL_nRF8001.h>

Thanks,
Andi


body:
I am using 4 LDR To track the sun for solar panels. Not using servos, but linear actuators(a little irrelevant but just to give scope)

my code gets stuck in this while loop as soon as it enters it, even tho the conditions are changed to break the loop. I want to leave the motors running in one direction until the "dvert"=Vertical difference is less then "tol"=tolerance. there are 4 of these loops. there is an if condition before each. so no adjustment is made if its already in tolerance.

Segment of code
``` code
  if (avgtop > avgbot)
  {  Serial.println("enter avgtop > avgbot");
    Serial.println( "");

   while (abs(dvert) > tol)
     {
      Serial.println("Enter While loop vert up....");
      Serial.println("Moving Vertical Axis begin...Moving UP  ");

                   digitalWrite(vrelay1, HIGH);              // Setting frame down
                   digitalWrite(vrelay2, LOW);              // Setting frame down
      delay(200);
      int topl = analogRead(ldrtopl);
      int topr = analogRead(ldrtopr);
      int botl = analogRead(ldrbotl);
      int botr = analogRead(ldrbotr);
      int avgtop = (topl + topr) / 2; //average of top LDRs
      int avgbot = (botl + botr) / 2; //average of bottom LDRs
      int dvert = avgtop - avgbot; // check the diffirence of up and down

      Serial.print("NEW DVERT:"  );
      Serial.println(dvert);

  }  ```

title: Stuck in While loop!

Answers: 1

body:
You're masking your outer `dvert` variable (and potentially others that you want to keep) with local variables inside the loop:

      int dvert = avgtop - avgbot; // check the diffirence of up and down

If you're just assigning a new value to an existing variable you do *not* want to declare a new variable!

Instead it should be just:

      dvert = avgtop - avgbot; // check the diffirence of up and down

And the same for anything else inside the loop that you want to assign to a variable that you have created outside the loop.


body:
Heres the code

    #include <AFMotor.h>

    AF_DCMotor motor(1, MOTOR12_8KHZ);
    AF_DCMotor motor(2, MOTOR12_8KHZ);
    AF_DCMotor motor(3, MOTOR34_1KHZ);

    void setup()  {
      Serial.begin(9600);
      Serial.printIn("Motor Test!");
      motor1.setSpeed(15); //set speed of motor
      motor2.setSpeed(15); //set speed of motor
      motor3.setSpeed(15); //set speed of motor

    }
    void loop() {
      Serial.print("tick");
      motor1.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor1.run(RELEASE);
      delay(5000);

      Serial.print("tack"); //first song starts
      motor1.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor1.run(RELEASE);
      delay(9000);

      Serial.print("tack");
      motor1.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //first song ends
      motor1.run(RELEASE);
      delay(20000);

      Serial.print("tick");
      motor1.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(5000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor1.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(FORWARD);
      delay(1000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor1.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

       Serial.print("tock");
      motor2.run(FORWARD);
      delay(1000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor1.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //first song stops
      motor2.run(RELEASE);
      delay(14000);

      Serial.print("tock"); //first song stops
      motor3.run(RELEASE);
      delay(11000);

      Serial.print("tick"); //first song stops
      motor3.run(FORWARD);
      delay(22000);

      Serial.print("tock"); //first song stops
      motor3.run(RELEASE);
      delay(19000);
    }

Here is the error: <br>

       ^~~~~~

       motor

    snowmanDC_Motor:13:3: error: 'motor3' was not declared in this scope

       motor3.setSpeed(15); //set speed of motor

       ^~~~~~

    C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:13:3: note: suggested alternative: 'motor'

       motor3.setSpeed(15); //set speed of motor

       ^~~~~~

       motor

    C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino: In function 'void loop()':

    snowmanDC_Motor:18:3: error: 'motor1' was not declared in this scope

       motor1.run(FORWARD);

       ^~~~~~

    C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:18:3: note: suggested alternative: 'motor'

       motor1.run(FORWARD);

       ^~~~~~

       motor

    snowmanDC_Motor:47:3: error: 'motor2' was not declared in this scope

       motor2.run(FORWARD);

       ^~~~~~

    C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:47:3: note: suggested alternative: 'motor'

       motor2.run(FORWARD);

       ^~~~~~

       motor

    snowmanDC_Motor:115:3: error: 'motor3' was not declared in this scope

       motor3.run(RELEASE);

       ^~~~~~

    C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:115:3: note: suggested alternative: 'motor'

       motor3.run(RELEASE);

       ^~~~~~

       motor

    exit status 1
    redefinition of 'AF_DCMotor motor'

title: Im having another problem with my code the error is "redefinition of 'AF_DCMotor motor'?

Answers: 1

body:
Adafruit has a V1 and a V2 motor shield. They have different libraries too. AFMotor.h is for the V1 shield. From the error, I can tell you installed V2 lib. For that you need to include:

    #include <Adafruit_MotorShield.h>


body:
In isolation (73 years old) and trying to get my macro photo stacking rail to return to start without a limit switch.  I know the number of steps taken, so it is just a matter of reversing the motor.  My code (copied and pasted from other sites) works like a dream (10 steps, fire an IR camera trigger) and continues up to when I want to return (line 73) taking 100 shots or steps however many I want - no problem.

I started a void return loop (and terminated the loop) but the coding has me beat.  I have attached my code (might look terrible, but it works).  Can anyone help out this old guy and give me the code to counter clockwise 1000 steps?

Thanks fellas
David
```
[code]
#include <AccelStepper.h>
#include <MultiStepper.h>

int smDirectionPin = 2; //Direction pin
int smStepPin = 3; //Stepper pin
int Distance = 0; // records the number of steps we have taken
byte numRepeats = 0;
byte maxRepeats = 100;
int smFirePin = 13;  //Trigger pin
#define fire 13

 void setup(){
  /*Sets all pin to output; the microcontroller will send them(the pins) bits, it will not expect to receive any bits from thiese pins.*/
  pinMode(2, OUTPUT);  //Direction Pin
  pinMode(3, OUTPUT);  //Step Pin
  pinMode(13, OUTPUT);  //LED pin
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(13,LOW);
  pinMode(smDirectionPin, OUTPUT);
  pinMode(smStepPin, OUTPUT);

  Serial.begin(9600); //Open Serial connection for debugging
}

void loop(){
   if (numRepeats < maxRepeats) {
   move1Step();
   Distance = Distance + 1; //record this step to see if we are et the end of our move

  if (Distance == 10)
  {
 if (digitalRead(2) == LOW)
 {
  digitalWrite(2 , LOW);
 }
 else
 {
  digitalWrite(2, LOW);
 }
 Distance = 0;
 numRepeats ++;
 delay(3000);
{
    trigger();
}
   }
 }
}
void move1Step() {
  digitalWrite(3, HIGH);
  delayMicroseconds(750);
  digitalWrite(3, LOW);
  delayMicroseconds(750);
}
// Power on the IR trigger circuit to fire the camera
void trigger()
{
    delay(1000); // wait for vibration to settle
    digitalWrite(fire, HIGH); // take the picture
    delay(2000); // wait for that to happen
    digitalWrite(fire, LOW); // disable the IR circuit again
}

// Advance the motor by one step
void step()
{
  digitalWrite(step, HIGH); //Trigger one step forward
  delay(1);
  digitalWrite(step, LOW); //Pull step pin low so it can be triggered again
  delay(1);
}

  void return();

{
  digitalWrite(smDirectionPin, HIGH);
  /*Slowly turns the motor 1600 steps*/
  for (int i = 0; i <200; i++){
    digitalWrite(smStepPin, HIGH);
    delayMicroseconds(700);
    digitalWrite(smStepPin, LOW);
    delayMicroseconds(700);
  }

  while(1) { }
}

[/code]
```

title: Return photo stacking rail to start

Answers: 1

body:
I cleaned up your code a bit. Removed duplicate and unused code. I used a `for`-loop to make it run for 100 repetitions.

Feel free to let me know if you have any more questions, or if there are things that aren't clear.

    // You aren't using these libraries, so I commented them out
    //#include <AccelStepper.h>
    //#include <MultiStepper.h>

    int smDirectionPin = 2; //Direction pin
    int smStepPin = 3; //Stepper pin
    int smFirePin = 13;  //Trigger pin

    byte maxRepeats = 100;

    void setup()
    {
      /*Sets all pin to output; the microcontroller will send them(the pins) bits, it will not expect to receive any bits from thiese pins.*/
      pinMode(smDirectionPin, OUTPUT);  //Direction Pin
      pinMode(smStepPin, OUTPUT);  //Step Pin
      pinMode(smFirePin, OUTPUT);  //Fire pin
      digitalWrite(smDirectionPin, LOW);
      digitalWrite(smStepPin, LOW);
      digitalWrite(smFirePin,LOW);

      Serial.begin(9600); //Open Serial connection for debugging
    }

    void loop()
    {
      digitalWrite(smDirectionPin, LOW); // set stepper motor to run forwards

      for( byte i=0; i<maxRepeats; i++ ) // run the following section 100 times
      {
        //move 10 steps forward
        for( byte j=0; j<10; j++ )
        {
          move1Step();
        }

        // wait and take a photo
        delay(3000);// there is already a delay in the `trigger` function, so this like could be removed
        trigger();
      }

      // return the stepper motor to the starting position
      digitalWrite(smDirectionPin, HIGH); // set stepper motor to run in reverse
      for( byte i=0; i<maxRepeats; i++ ) // run the following section 100 times
      {
        //move 10 steps backwards
        for( byte j=0; j<10; j++ )
        {
          move1Step();
        }
      }

      // Do nothing
      while(1){ }
    }

    void move1Step()
    {
      digitalWrite(smStepPin, HIGH);
      delayMicroseconds(750);
      digitalWrite(smStepPin, LOW);
      delayMicroseconds(750);
    }

    // Power on the IR trigger circuit to fire the camera
    void trigger()
    {
        delay(1000); // wait for vibration to settle
        digitalWrite(smFirePin, HIGH); // take the picture
        delay(2000); // wait for that to happen
        digitalWrite(smFirePin, LOW); // disable the IR circuit again
    }


body:
I've read that it's best to avoid using String in Arduino so I'm ready to use a char array if it's better.
I'm reading the file names from an SD Card and my goal is to store them in an array and then be able to read that array. What I'm currently doing is:

    String lib_arr[100];
    int lib_arr_size;
and then

    File dir = SD.open("/");
    int c = 0;
    while (true) {
      File entry = dir.openNextFile();
      if (!entry) {
        // If no more files
        lib_arr_size = c - 1;
        break;
      }
      if(strcmp(entry.name(), "SYSTEM~1") == 0) {
        continue;
      }
      lib_arr[c] = entry.name();
      entry.close();
      c++;
    }
and then

    for (int i = 0; i < lib_arr_size; i++) {
      if(i == pos) {
        tft.print("> ");
        tft.println(lib_arr[i]);
      } else {
        tft.println(lib_arr[i]);
      }
    }
This is not a solution because, for my purposes, the String lib_arr[100] can be 1000 or 10000 or 100000... and I found out that by increasing that value the global variables use skyrockets and Arduino says that it's out of memory. My goal is memory optimization. I don't know how to go about this problem.

title: Reading from SPIFFS - What's the best way to deal with a string (or char) array with undefined length?

Answers: 2

body:
Well, you cannot use more memory than you have. If the length of file names is (probably/possibly) too much, you just cannot store it in memory. Some alternatives:

- Use some compression... This will save you a bit, but at the end if you don't know how much the maximum bytes you need to store is, it will not help much
- Use external SRAM memory... You need to write your own memory functions. Also a slight performance hit.
- Use SD card memory... As SRAM, but much slower. Also not sure if you can use the same SD card to write on.
- The best solution, but could be a big performance hit, is not to store at all the file names, but go through the file names and process what you need along the way. This is not always possible or feasible though. In your solution you can print the file names directly without storing (but I guess you want to do some additional processing).

body:
Please look into the SPIFFS/ LittleFS library. You will see that the length of a filename (in those file systems it includes the path and the root indicator "/" as well as the extension .XXXXX as in .shtml ).
The maximum length defined in the libs is 32 as max length this means **31 chars to use** + 1 terminator. To all the wise guys claiming you can change that (Yes you can but you should not). Do not do it - there are reasons for that. [Read more](https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html).
The maximum files is defined by blocksize and howlargeyou defined your SPIFFS partition.

There is no difference between writing to SPIFFs or a SD card both have around 100.000 r/w cycles per individual physical "cell" Sometimes it is cheaper to get a new ESP than a SDcard.

**The question of the OP:**
 As long as you read its no problem to do it often if you do mass renames you might have a problem after some time. What you do is actually partly copying what the libs do - so utterly obsolete. Speed is the same because its the same flash memory anyway (+ your processing overhead).

You do not really have directories its a flat table system, so searching for path beginning with or containing (combined with a clever read strategy) can be done on the fly without problems.

 If you need data elsewhere (browser) filter & stream it - do not make in between storage (=duplication) with the small memory

As a final thought from the tech specs:

>   The main complication writing spiffs was that it cannot be assumed
> the target has a heap. Spiffs must go along only with the work ram
> buffer given to it.  This forces extra implementation on many areas of
> spiffs. ....
>
> SPI flash devices are physically divided in blocks. On some SPI flash
> devices, blocks are further divided into sectors. Datasheets sometimes
> name blocks as  sectors and vice versa.
>
> Common memory capacaties for SPI flashes are 512kB up to 8MB of data,
> where blocks may be 64kB. Sectors can be e.g. 4kB, if supported. Many
> SPI flashes  have uniform block sizes, whereas others have non-uniform
> - the latter meaning  that e.g. the first 16 blocks are 4kB big, and the rest are 64kB.
>
> The entire memory is linear and can be read and written in random
> access.  Erasing can only be done block- or sectorwise; or by mass
> erase.


body:
I want to refactor this code

    /*
    YF‐ S201 Water Flow Sensor
    Water Flow Sensor output processed to read in litres/hour
    Adaptation Courtesy: www.hobbytronics.co.uk
    */
    volatile int flow_frequency; // Measures flow sensor pulses
    unsigned int l_hour; // Calculated litres/hour
    unsigned char flowsensor = 2; // Sensor Input
    unsigned long currentTime;
    unsigned long cloopTime;
    void flow () // Interrupt function
    {
       flow_frequency++;
    }
    void setup()
    {
       pinMode(flowsensor, INPUT);
       digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
       Serial.begin(9600);
       attachInterrupt(0, flow, RISING); // Setup Interrupt
       sei(); // Enable interrupts
       currentTime = millis();
       cloopTime = currentTime;
    }
    void loop ()
    {
       currentTime = millis();
       // Every second, calculate and print litres/hour
       if(currentTime >= (cloopTime + 1000))
       {
          cloopTime = currentTime; // Updates cloopTime
          // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
          l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
          flow_frequency = 0; // Reset Counter
          Serial.print(l_hour, DEC); // Print litres/hour
          Serial.println(" L/hour");
       }
    }

*Originally found here: [source][1]*

to an Class based solution:

    /*
    YF‐ S201 Water Flow Sensor
    Water Flow Sensor output processed to read in litres/hour
    Adaptation Courtesy: www.hobbytronics.co.uk
    */
    class FlowSensor {
      volatile int flow_frequency;
      unsigned int l_hour;
      unsigned char pin;
      unsigned long currentTime;
      unsigned long cloopTime;
      public:
        void flow () {
          flow_frequency++;
        };
        void setup() {
          pinMode(pin, INPUT);
          digitalWrite(pin, HIGH); // Optional Internal Pull-Up
          Serial.begin(9600);
          attachInterrupt(digitalPinToInterrupt(pin), flow, RISING); // Setup Interrupt
          sei(); // Enable interrupts
          currentTime = millis();
          cloopTime = currentTime;
        }
        void loop() {
          currentTime = millis();
          // Every second, calculate and print litres/hour
          if(currentTime >= (cloopTime + 1000))
          {
            cloopTime = currentTime; // Updates cloopTime
            // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
            l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
            flow_frequency = 0; // Reset Counter
            Serial.print(l_hour, DEC); // Print litres/hour
            Serial.println(" L/hour");
          }
        }
        FlowSensor() {
          setup();
        };
    };
    FlowSensor flowsensor_intake;
    void setup()
    {
       flowsensor_intake = FlowSensor();
    }
    void loop ()
    {
       flowsensor_intake.loop();
    }

But i get the following error in the Arduino IDE:

> /tmp/087639235/water_flow/water_flow.ino: In static member function
> 'static void FlowSensor::flow()':
>
> /tmp/087639235/water_flow/water_flow.ino:17:19: error: cannot call
> member function 'void FlowSensor::update_flow()' without object
>
> update_flow()
>
> ^
>
> exit status 1

I understand that flow is not a static function and that i cannot make it static because it is midifying a non static member.

But i cannot think of an alternate solution to this Problem. My goal is to monitor multiple flow sensors by creating an object in the `setup()` function, and updating them with every `loop()` call.

  [1]: https://www.electroschematics.com/working-with-water-flow-sensors-arduino/

title: Update class attribute with attachInterrupt

Answers: 1

body:
You've run into a classic trap.  There are a couple of things to think about.  First off, if this is a singleton class (as in there will only ever be one instance) then you can just have a non-member function that you use with attachInterrupt and have that function just call the member function you want.  Normally what I would do would be to create the instance in the .cpp and put an extern declaration for it in the header so that it can just be used without creating it.  Look at how Serial works for an example.  Then put all the configuration type stuff into a begin or init method to call from setup.  That way the non-member function for the interrupt can be part of the header and the user never has to see or mess with it and it feels like it's part of the class.

If this is not a singleton class and you might one day have several instances of this in one program then you have to start asking yourself how will the interrupt know which instance to act upon.


body:
Is there a way to clean up this code...or do some smart coding?

In this example I use 6 relays, in the final code it will be 10.

Also I now use 5 switches and that will be 8, each with an own led. Now I only stated 1 led.

The code reads a button, and a few relays will get a signal. Also the buttonled will go on.
I will add more cases later. But I was wondering, is it possible/easier/just another way of writing the high/low to the relays and leds.

Can I somehow combine the LOWs or HIGHs within a case?

    int relay1 = A5;
    int relay2 = A4;
    int relay3 = A3;
    int relay4 = A2;
    int relay5 = A1;
    int relay6 = A0;

    int led1 = 3;

    int sw1 = 5;
    int sw2 = 6;
    int sw3 = 7;
    int sw4 = 8;
    int sw5 = 9;

    int sw1Status, sw2Status, sw3Status, sw4Status, sw5Status;
    int order = 1; // default is to set all relays off.

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

      pinMode(led1, OUTPUT);

      pinMode(relay1, OUTPUT);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
      pinMode(relay4, OUTPUT);
      pinMode(relay5, OUTPUT);
      pinMode(relay6, OUTPUT);
      // input pull-up, so default state of buttons is HIGH.
      pinMode(sw1, INPUT_PULLUP);
      pinMode(sw2, INPUT_PULLUP);
      pinMode(sw3, INPUT_PULLUP);
      pinMode(sw4, INPUT_PULLUP);
      pinMode(sw5, INPUT_PULLUP);

    }

    void loop() {

      // read the buttons status
      sw1Status = digitalRead(sw1);
      sw2Status = digitalRead(sw2);
      sw3Status = digitalRead(sw3);
      sw4Status = digitalRead(sw4);
      sw5Status = digitalRead(sw5);

      if (sw1Status == LOW) { // if button 1 pressed
        order = 2; // go to case 2
      }
      if (sw2Status == LOW) {
        order = 3;
      }
      if (sw3Status == LOW) {
        order = 4;
      }
      if (sw4Status == LOW) {
        order = 5;
      }
      if (sw5Status == LOW) { // button 4 toggle
        if (order != 7) { // if order is not equal 5 turn on relay 1 & 4
          order = 6;
        }
        else { // else go to case 1, which will turns off all relays
          order = 1;
        }
      }

      switch (order) {
        case 1: // if order equals 1
          digitalWrite(relay1, LOW);
          digitalWrite(relay2, LOW);
          digitalWrite(relay3, LOW);
          digitalWrite(relay4, LOW);
          digitalWrite(relay5, LOW);
          digitalWrite(relay6, LOW);
          digitalWrite(led1, LOW);
          break;

        case 2: // if order equals 2
          digitalWrite(relay1, HIGH);
          digitalWrite(relay2, LOW);
          digitalWrite(relay3, HIGH);
          digitalWrite(relay4, LOW);
          digitalWrite(relay5, HIGH);
          digitalWrite(relay6, LOW);
          digitalWrite(led1, HIGH);
          break;

        case 3: // if order equals 3
          digitalWrite(relay1, LOW);
          digitalWrite(relay2, HIGH);
          digitalWrite(relay3, LOW);
          digitalWrite(relay4, HIGH);
          digitalWrite(relay5, LOW);
          digitalWrite(relay6, HIGH);
          digitalWrite(led1, LOW);
          break;

        case 4: // if order equals 4
          digitalWrite(relay1, HIGH);
          digitalWrite(relay2, HIGH);
          digitalWrite(relay3, HIGH);
          digitalWrite(relay4, LOW);
          digitalWrite(relay5, LOW);
          digitalWrite(relay6, LOW);
          digitalWrite(led1, LOW);
          break;

        case 5: // if order equals 5
          digitalWrite(relay1, LOW);
          digitalWrite(relay2, LOW);
          digitalWrite(relay3, LOW);
          digitalWrite(relay4, HIGH);
          digitalWrite(relay5, HIGH);
          digitalWrite(relay6, HIGH);
          digitalWrite(led1, LOW);
          break;

        case 6: // if order equals 5
          digitalWrite(relay1, LOW);
          digitalWrite(relay2, LOW);
          digitalWrite(relay3, HIGH);
          digitalWrite(relay4, HIGH);
          digitalWrite(relay5, LOW);
          digitalWrite(relay6, LOW);
          digitalWrite(led1, LOW);
          break;

        default: // if none of above cases is valid go to case 1
          order = 1;
          break;
      }
    }

title: smart coding possible?

Answers: 2

body:
If all are handled the same and they don't have individual names, arrays and for loops are what you are looking for.

    const byte relayPins[] = { A5, A4, A3, A2, A1, A0};
    const byte ledPin = 3;
    const byte swPins[] = {5, 6, 7, 8, 9};

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      for (const byte relayPin: relayPins) pinMode(relayPin, OUTPUT);
      for (const byte swPin: swPins) pinMode(swPin, INPUT_PULLUP);
    }

*Even arduino C++ nowadays understands the foreach syntax.*

BTW: for your final pin count you'll need other/additional hardware. Either a Mega or shift registers or port expanders.

body:
Arduino Uno has 3 ports.
You can read and write the ports as 1 byte.

With all the switches on one port, you can read them all at once.
For example, using D7 to D3 to read the switches:

    switches = (PIND & 0b11111000) >>3; // read D7 to D0, mask off D2-1-0, move data to lower 5 bits

Then you could have case (switches): for the 0 to 31 cases that are possible.

With all the relays on one port, you can change them all at once.
For example, using D14 to D19 for the relays:

    PORTC = 0b00110011; // Dxx, Dxx, D19,18,17,16,15,14 or A5,A4,A3,A2,A1,A0
to turn on relays 1,2,5,6, and 3,4 off.

The LED would still be on its own.


body:
I'm trying to combine two scripts I've found. One to get my remote control model to work via a controller and the other to enable 6 ultrasound modules I have. When I omit the code highlighted in "THIS SECTION" (for the ultrasound modules) the controller and model works fine but when I put it in (to enable to ultrasound modules), the controller becomes unresponsive and the wheels spin uncontrollably.

I'm assuming it's something to do with having what should be two seperate loop sections combined into one?

Any help is much appreciated,
Thanks

```

//This section defines all the pin data and  to be used within the program loop.

//The following four lines set the pin numbers for the PS2 controller.
#define PS2_DAT        11 //Data pin.
#define PS2_CMD        10 //Command pin.
#define PS2_SEL        9  //Attention pin.
#define PS2_CLK        8  //Clock pin.

//The following six lines set the pin numbers for the motor module.
#define IN1     33 //Positive polarity for the right sided wheels.
#define IN2     35 //Negative polarity for the right sided wheels.
#define IN3     37 //Positive polarity for the left sided wheels.
#define IN4     39 //Negative polarity for the left sided wheels.
#define ENA     31 //Jumper pin start.
#define ENB     41 //Jumper pin end.

//The analogue values read from the PS2 contoller.
int LX = 0;
int LY = 0;
int RX = 0;
int RY = 0;

//The following twelve lines set pin numbers for the ultrasonic sensors.
int trigPin1=7; //Front transmitter (Object ahead detection).
int echoPin1=6; //Front receiver.
int trigPin2=5; //Right transmitter (Lane keeping).
int echoPin2=4; //Right receiver.
int trigPin3=3; //Rear right transmitter (Right blindspot detection).
int echoPin3=2; //Rear right receiver.
int trigPin4=14; //Rear centre transmitter (Parking sensor).
int echoPin4=15; //Rear centre receiver.
int trigPin5=16; //Rear left transmitter (Left blindspot detection).
int echoPin5=17; //Rear left receiver.
int trigPin6=19; //Left transmitter (Lane keeping).
int echoPin6=18; //Left receiver.

// This section sets the modes of PS2 controller.
//#define pressures   true
#define pressures   false
#define rumble      true
//#define rumble      false

PS2X ps2x; //Creates PS2 controller class.
int error = 0;
byte type = 0;
byte vibrate = 0;

void setup() {

Serial.begin (9600); //Opens the sensor serial ports and sets data rate to 9600bps
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);
  pinMode(trigPin4, OUTPUT);
  pinMode(echoPin4, INPUT);
  pinMode(trigPin5, OUTPUT);
  pinMode(echoPin5, INPUT);
  pinMode(trigPin6, OUTPUT);
  pinMode(echoPin6, INPUT);

  pinMode(IN1,  OUTPUT);
  pinMode(IN2,  OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);

  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);

  delay(300);  //Added delay to give the wireless PS2 module time to start up before configuring it.

  //Checks for errors determined by pin data: GamePad(clock, command, attention, data, pressures, rumble)
  error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble);

  if (error == 0) {
    Serial.print("Found Controller, configured successful ");
  }
  else if (error == 1)
    Serial.print("No controller found, check wiring");

  else if (error == 2)
    Serial.print("Controller found but not accepting commands");

  else if (error == 3)
    Serial.print("Controller refusing to enter Pressures mode, may not support it.");
  }

void loop() {
---------------------------------------THIS SECTION------------------------------
long duration1, distance1;
  digitalWrite(trigPin1, HIGH);**
  delayMicroseconds(10); // Added this line
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   if (distance1 >= 500 || distance1 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print ( "Sensor1  ");
    Serial.print ( distance1);
    Serial.println("cm");
  }

  long duration2, distance2;
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10); // Added this line
  duration2 = pulseIn(echoPin2, HIGH);
  distance2 = (duration2/2) / 29.1;

   if (distance2 >= 500 || distance2 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor2  ");
    Serial.print(distance2);
    Serial.println("cm");
  }
  long duration3, distance3;
  digitalWrite(trigPin3, HIGH);
  delayMicroseconds(10); // Added this line
  duration3 = pulseIn(echoPin3, HIGH);
  distance3 = (duration3/2) / 29.1;

   if (distance3 >= 500 || distance3 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor3  ");
    Serial.print(distance3);
    Serial.println("cm");
  }
  long duration4, distance4;
  digitalWrite(trigPin4, HIGH);
  delayMicroseconds(10); // Added this line
  duration4 = pulseIn(echoPin4, HIGH);
  distance4 = (duration4/2) / 29.1;

   if (distance4 >= 500 || distance4 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor4  ");
    Serial.print(distance4);
    Serial.println("cm");
  }
  long duration5, distance5;
  digitalWrite(trigPin5, HIGH);
  delayMicroseconds(10);
  duration5 = pulseIn(echoPin5, HIGH);
  distance5 = (duration5/2) / 29.1;

   if (distance5 >= 500 || distance5 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor5  ");
    Serial.print(distance5);
    Serial.println("cm");
  }
  long duration6, distance6;
  digitalWrite(trigPin6, HIGH);
  delayMicroseconds(10);
  duration6 = pulseIn(echoPin6, HIGH);
  distance6 = (duration6/2) / 29.1;

   if (distance6 >= 500 || distance6 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor6  ");
    Serial.print(distance6);
    Serial.println("cm");
  }
---------------------------------------------END----------------------------------------

  ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed

  delay(50);
  if (ps2x.Button(PSB_L1))
  {
    LY = ps2x.Analog(PSS_LY); //receive values from p22 joystick
    LX = ps2x.Analog(PSS_LX);
  }
  if (ps2x.Button(PSB_R1))
  {
    RY = ps2x.Analog(PSS_RY);
    RX = ps2x.Analog(PSS_RX);
  }
  if (LY > 200 || RY > 200) //check if the joystick pushed up side
  {
    REV();
  }
  if (LY < 100 || RY < 100)
  {
    forward();
  }
  if (LX < 100 || RX < 100)
  {
    left();
  }
  if (LX > 200 || RX > 200)
  {
    right();
  }
  if(LX == 128 && LY == 128 && RX == 128 && RY == 128)
  {
    waithere();
  }
LY = LX = 128;         //return to default vlaues
RY = RX = 128;         //return to default values
}

void forward()
{
  digitalWrite(ENA, HIGH);
  digitalWrite(ENB, HIGH);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}
void REV()
{
  digitalWrite(ENA, HIGH);
  digitalWrite(ENB, HIGH);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}
void left()
{
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, HIGH);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}
void right()
{
  digitalWrite(ENA, HIGH);
  digitalWrite(ENB, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
}
void waithere()
{
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
}

```

title: Combining two scripts

Answers: 0


body:
I am trying to use the SimpleChat application to test my RedBearLab Shield.
If I send "Hello" and to to Serial.print or Serial.write the return what I see in my Serial monitor is stuff like "Fh`Fx**-H3r:AJb6# E0CbJ"

Any idea what I'm doing wrong?

Thank you,
Andi Stancu

title: SimpleChat BLE Example prints scrambled characters

Answers: 1

body:
If you are transmitting `Hello` and receiving `Fh'Fx**-H3r:AJb6# E0CbJ`, then the problem is most likely a `baud rate mismatch`.

The receiver is sampling the data signal 3 or 4 times faster than it should.

Start by lowering the baud rate of the serial monitor to 1/4 of the current baud rate.

If that does not produce correct data reception, then start at the lowest baud rate and work your way up.


body:
I am setting up a potentiometer system that includes a motor that is supposed to spin with the potentiometer changing the speed of the spin and a button to reverse it. I checked the coding and it is correct, the potentiometer, button, and motor are all functioning, but the system does not run. Can anyone propose any solutions to this issue?

int enablePin = 11;
int in1Pin = 10;
int in2Pin = 9;
int switchPin = 7;
int potPin = 0;

void setup() {
  Serial.begin(9600);
  pinMode(in1Pin, OUTPUT);
  pinMode(in2Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);
  pinMode(switchPin, INPUT_PULLUP);
}

void loop() {
  int speed = analogRead(potPin) / 4;
  Serial.println(speed);
  boolean reverse = digitalRead(switchPin);
  setMotor(speed, reverse);

}
void setMotor(int speed, boolean reverse)
{
  analogWrite(enablePin, speed);
  digitalWrite(in1Pin, ! reverse);
  digitalWrite(in2Pin, reverse);

}

[![breadboard][2]][2]

[![reference board][3]][3]

  [1]: https://i.stack.imgur.com/doY4u.png
  [2]: https://i.stack.imgur.com/tPqNH.jpg
  [3]: https://i.stack.imgur.com/lfA8J.png

title: Potentiometer motor system is not working

Answers: 0


body:
Sorry if this question been posted but I couldn't find the one that matches my issue. I couldn't pass my struct values from the main file to a class. Any ideas? I got this:

    error: no matching function for call to 'ODriveArduino::SetParam(R_motor_params&)'

Main.cpp:

    #include ODriveArduino.h
    ODriveArduino odrive(Serial1);

    struct L_motor_params{
     int axis=1;
     float vel_Gain= 2.5f/10000.0f ;
     float pos_Gain= 40.0f;
     float vel_Int_Gain= 0.0f/10000.0f;
    };
    struct R_motor_params{
     int axis=0;
     float vel_Gain= 2.75f/10000.0f ;
     float pos_Gain= 40.0f;
     float vel_Int_Gain= 0.0f/10000.0f;
    };

    void setup() {
      struct R_motor_params M;
      odrive.SetParam(M);
    }

ODriveArduino.h:

    class ODriveArduino {

    private:

        struct motor_Params{
          int axis;
          float vel_Gain;
          float pos_Gain;
          float vel_Int_Gain;
        };

    public:
        ODriveArduino(Stream& serial);

        // Commands
        void SetParam(struct motor_Params M);

     }

ODriveArduino.cpp:

    #include "ODriveArduino.h"
    template<class T> inline Print& operator <<(Print &obj,     T arg) { obj.print(arg);    return obj; }
    template<>        inline Print& operator <<(Print &obj, float arg) { obj.print(arg, 4); return obj; }

    ODriveArduino::ODriveArduino(Stream& serial)
        : serial_(serial) {}

    void ODriveArduino::SetParam(struct motor_Params M){
      Serial1 << "w axis" << M.axis << ".motor.config.pos_gain " << M.pos_Gain << '\n';
      Serial1 << "w axis" << M.axis << ".motor.config.vel_gain " << M.vel_Gain << '\n';
      Serial1 << "w axis" << M.axis << ".motor.config.vel_integrator_gain " << M.vel_Int_Gain << '\n';
    }

title: Passing struct from main.cpp to a class

Answers: 1

body:
It looks like you're trying to implement polymorphism without implementing polymorphism.

What you have done is create three completely independent structures and assumed that they will all work together just because they are the same size, with similar names, and fields named the same. That's not the case. They are all completely separate.

Instead you want just *one* structure but to use it multiple times to create different variables:

```
// from ODriveArduino.h, but move *outside* the class
struct motor_Params{
      int axis;
      float vel_Gain;
      float pos_Gain;
      float vel_Int_Gain;
};

// in your code
struct motor_Params left_params = {
    1, 2.5f/10000.0f, 40.0f, 0.0f/10000.0f
};

struct motor_Params right_params = {
    0, 2.75f/10000.0f, 40.0f, 0.0f/10000.0f
};

// later
  odrive.SetParam(left_params);
```


body:
Can someone please help me write code that can read a 24-bit BMP file from an SD card, save converted to 8-bit BMP internally, and display the 8-bit BMP pixel values on Arduino terminal as a 2D matrix. The program should align the bytes as two HEX values on the Arduino terminal. I am new to this and not sure how to go about it. Your help will be much appreciated.

The image is present in the SD card and coded as:

```include <SPI.h>
include <SD.h>
include <SD_t3.h>

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

void loop() {
  if (!SD.begin (BUILTIN_SDCARD)) {
    Serial.println ("NO SDCARD");
    while (1);
  } else {
    Serial.println ("YES SDCARD");
  }
  delay (1000);
  if (SD.exists("filename.BMP")) {
    Serial.println ("filename.BMP exists");
  } else {
    Serial.println ("filename.BMP missing");
    while (1);
  }
  delay (1000);
  File hFi = SD.open ("filename.bmp", FILE_READ);
  if (hFi == false) {
    Serial.println ("File open failed");
    while (1);
  }
```

title: Reading bmp images from SD card, converting it and displaying it on serial monitor in Arduino

Answers: 1

body:
You have to writeyour own routines. To get you started Look at [this source code](https://javl.github.io/image2cpp/)
Add `view-source:https://javl.github.io/image2cpp/`. Although it is javascript, it can be transferred to C++ to a working conversion routine. The important part are the conversion routines.
A word of warning: As the memory os limited you will have to do a line by line read from SD card convert line and write line by line back or you use maximum 16x16 size.
Thats the reason why most converters run in browser or PC and the result is used in Arduino. An ESP8266 with 4MB memory would make life easier. For an implementation of graphic routines on Arduino Teensy look into this [gaming library](https://github.com/Duhjoker/GameR-Iot_T3)


body:
I have a very basic question, because I struggle to upload files to my FireBeetle ESP32 Board.

When I try to upload to the board I get an

    A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header

On other boards you have to press & hold the flash button, but this specific board just has a reset button.
What can I do?

title: Connecting a FireBeetle ESP32 to Arduino

Answers: 2

body:
The flash button is virtual and controlled by the RTS signal from the computer through the USB port (why are you trying to connect through an Arduino?). It should automatically enter bootloader mode when you go to program it. There should be nothing you need to do.

However, if you *do* want to manually enter bootloader mode, just connect IO0 (*note: not D0*) to GND and press the reset button.

body:
I suspect you do not have the right drivers installed. That's the issue I just solved for myself. And it can be easy to think you installed the right driver, when in fact you didn't.

Have you followed the instructions on DFRobot's product wiki?

I'm not sure if you have the ESP32-E or the earlier ESP32-IOT Firebeetle, but here's the link to the drivers mentioned for the [Firebeetle ESP32E][1] and here for the prior version, the [Firebeetle ESP32 IOT][2]

But I would suggest double checking which board you have an very meticulously ensuring you have the right driver installed.

  [1]: https://wiki.dfrobot.com/FireBeetle_Board_ESP32_E_SKU_DFR0654#target_11
  [2]: https://wiki.dfrobot.com/FireBeetle_ESP32_IOT_Microcontroller(V3.0)__Supports_Wi-Fi_&_Bluetooth__SKU__DFR0478#target_4


body:
I have a problem regarding a Nokia 5110 LCD display. I am currently building a soldering station based on a PID controller. The original code was using a 7 segment display and I adapted the code to the Nokia display.

The problem is that when I rotate the potentiometer, the "read temp" and "set temp" is showing the exactly the same number, and after I finish rotating the potentiometer, the values return to their normal number.

How can I solve this problem ?

This is my code: https://pastebin.com/inPtkniX

This is the original project: https://www.allaboutcircuits.com/projects/do-it-yourself-soldering-station-with-an-atmega8/

    //Soldering station Software using PID
    //Thank you Alex from https://geektimes.ru/ for help with led array function
    //AllAboutCircuits.com
    //epilepsynerd.wordpress.com

    #include <PID_v1.h>
    #include <PCD8544.h>

    PCD8544 lcd;
    unsigned long updaterate = 500; //Change how fast the display updates. No lower than 500
    unsigned long lastupdate;
    int temperature = 0;
    //Define Variables we'll be connecting to
    double Setpoint, Input, Output;
    //Define the aggressive and conservative Tuning Parameters
    double aggKp = 4, aggKi = 0.2, aggKd = 1;
    double consKp = 1, consKi = 0.05, consKd = 0.25;
    //Specify the links and initial tuning parameters
    PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

    void setup() {
      lcd.begin(84, 48);
      //We do not want to drive the soldering iron at 100% because it may burn, so we set it to about 85% (220/255)
      myPID.SetOutputLimits(0, 220);
      myPID.SetMode(AUTOMATIC);
      lastupdate = millis();
      Setpoint = 0;
    }

    void loop() {
      lcd.clear();
      //Read temperature
      Input = analogRead(0);
      //Transform the 10bit reading into degrees celsius
      Input = map(Input, 0, 450, 25, 350);
      //Display temperature
      if (millis() - lastupdate > updaterate) {
        lastupdate = millis();
        temperature = Input;
      }
      //Read setpoint and transform it into degrees celsius(minimum 150, maximum 350)
      double newSetpoint = analogRead(1);
      newSetpoint = map(newSetpoint, 0, 1023, 150, 350);
      //Display setpoint
      if (abs(newSetpoint - Setpoint) > 3) {
        Setpoint = newSetpoint;
        //temperature = newSetpoint;
        lastupdate = millis();
      }
      double gap = abs(Setpoint - Input); //distance away from setpoint
      if (gap < 10) {
      //we're close to setpoint, use conservative tuning parameters
        myPID.SetTunings(consKp, consKi, consKd);
      } else {
        //we're far from setpoint, use aggressive tuning parameters
        myPID.SetTunings(aggKp, aggKi, aggKd);
      }
      myPID.Compute();
      //Drive the output
      analogWrite(11, Output);
      //Display the temperature
      show(temperature, newSetpoint);
    }

    void show(int value, int newspnt) {
      lcd.setCursor(0, 0);
      lcd.print("READ TEMP");
      lcd.setCursor(0, 1);
      lcd.print(value);
      lcd.setCursor(0, 2);
      lcd.print("SET TEMP");
      lcd.setCursor(0, 3);
      lcd.print(newspnt);
      delay(200);
    }

title: Nokia 5110 LCD number display problem

Answers: 1

body:
Look at line 55, where you are doing this

    temperature = newSetpoint;

There is no reason to give temperature the same value as the set point. It does not make sense. And the `temperature` variable is the same, that you are using to display.

So, while you are changing the setpoint, the `temperatur` variable gets overwritten with the setpoint. When you are not changing it anymore, the measured temperature is still in this variable, when you are displaying it.

Just remove the mentioned line.


body:
Hello world (this is my first message in this forum).

I am quite a just-married-to-Arduino guy, I am very passionate about this platform that I kew since long time but never had the time to dedicate.

Now I have done several home projects that made me both feel happy and feel sooooo rookie... But hey, here I am trying more and more complex things.

I am trying to do something I haven't found information about: I have a 10" touch panel (I am not talking about a screen, just the touch surface) which is a capacitive 10 pin panel that communicates with I2C protocol (there are SCL and SDK pins). I have managed to scan the address and turns out it is in the #40.

However, other than that I do not have the knowledge to get the coordinates out of that panel. My question is: is there any library that can help me with that or will I need to code everything?

I am attaching some pictures of the panel and the pinout to have a clearer picture of what I am talking about.

I thank you all for your time reading my post, I hope some day I will be able to provide some answers rather than questioning!

Joan.
[![touch pannel][1]][1]

[![panel pinout][2]][2]

[![Controller][3]][3]

  [1]: https://i.stack.imgur.com/EFzRK.jpg
  [2]: https://i.stack.imgur.com/daowE.jpg
  [3]: https://i.stack.imgur.com/z7mtn.jpg

title: Getting coordinates from a touch panel with I2C

Answers: 1

body:
There is a simple [library](https://github.com/hellange/arduino/tree/master/capacitive_7in_panel) that works for FT5xx6 display panel.

**Other information available:**

Application node - https://cdn-shop.adafruit.com/datasheets/FT6x06_AN_public_ver0.1.3.pdf

Datasheet - https://www.newhavendisplay.com/appnotes/datasheets/touchpanel/FT5x26.pdf

In case those links might be no longer available in the future, a quick search on FocalTech FT5xx6 should give you the relevant information.


body:
I'd like to find out:

- how big can an Arduino project get, is there some limit?
- are there examples of large open source code bases? I did some research but find only example projects with single .ino file. Are there projects with multiple files e.g. functions, constants in separate files say to avoid a 10K+ .ino file?

title: What are examples of large Arduino code bases and how are they organized?

Answers: 4

body:
Each sketch uses Flash memory, you can see this when you compile your project.
You also can see how much percentually you have used.

And as jsotola explains, libraries are examples how multiple files can be used.

However, next to you .ino scene (in the same folder) you can put .h, .c and .cpp files which are automatically compiled (when used by the .ino file). However, if you use too many files, because tabs are placed horizontally in the Arduino IDE, it's better to use a decent editor. And while doing that, you use the Arduino IDE to compile (only).

body:
Big projects are likely not developed with Arduino IDE. Arduino IDE was make for designers/inventors, not for programmers.

> Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed at students without a background in electronics and programming.

<sub>[Source](https://www.arduino.cc/en/guide/introduction)</sub>

Programmers will use a fully-fledged IDE which has many features a programmer needs on a daily basis, such as:

* handling multiple files efficiently
* allowing to create libraries instead of just `setup()` and `loop()`
* code completion (suggestions as you type)
* debugging (inspection and changing of variables at runtime)
* refactoring (modifying the structure of your code without changing the behavior)
* integrated version control (like Git / Github)

Such an IDE could be [Eclipse with an Arduino Plugin](https://marketplace.eclipse.org/content/eclipse-c-ide-arduino) or [Atmel Studio](https://www.microchip.com/mplab/avr-support/atmel-studio-7) and perhaps Visual Studio.

So, what do you need to look for? Don't look for `.ino` files. Instead, look for `.h` and `.cpp` code, just like other non-Arduino C++ code.

Some examples:

* [SPI](https://github.com/arduino/ArduinoCore-sam/tree/master/libraries/SPI/src): 297 lines
* [Wire](https://github.com/arduino/ArduinoCore-sam/blob/master/libraries/Wire/src/Wire.cpp): 453 lines
* [SoftwareSerial](https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/SoftwareSerial/src/SoftwareSerial.cpp): 486 lines
* [I2S](https://github.com/arduino/ArduinoCore-samd/blob/master/libraries/I2S/src/I2S.cpp): 533 lines
* [USBHost](https://github.com/arduino/ArduinoCore-samd/blob/master/libraries/USBHost/src/): several files, up to 1600 lines

body:
Thats an [example](https://github.com/merlokk/SmartHome/tree/master/lib) how to organize by function groups.
Other good complex examples can be found when searching for
 `Arduino esp8266 webserver site:github.com`
The limit is basically your IDE -If you use ArduinoIDE the limit is (without already tested and working lib files) around 20 files, more is a pain in the a** to handle.

I keep the length of my files between 500 - max 1000 lines. For documentation and keeping relationship diagrams (valuable for debug) I use doxygen with the graph extension.

When using an IDE like eclipse you can use more files, you have a good overview over your classes, but time to spend (and learn) configuring a project is initially much higher and there are sometimes (release dependent) breaking changes in the tool chain.

body:
Again im late to the party...

If you are planning on making a larger project and splitting things up you can take advantage of libraries. This will work even if you are married to the arduino ide for some reason. if your not married to the arudino ide platformio doesn't suck too bad, and makes libraries a bit less messy when your doing the grunt work of setting them up the first time.

The idea should be to break your problem into smaller testable pieces of  code into smaller testable libraries.  If your code doesn't depend on arduino features you may be able to use test your library fully on a bigger machine to make sure there are no bugs (for example abuse clangs static analysis tool to see if you made any dumb pointer errors https://clang-analyzer.llvm.org/)

I kinda set an example of  this (https://gitlab.com/mikealger/ExampleArduinoProjectStructure) up for students a while back but i still think its handy for anyone looking to build /manage the lifecycle of a project, I still use the basic ideas when i'm doing one off small projects based on others work to keep my notes straight i.e.  https://gitlab.com/mikealger/celstronhomebrewgps

yea its probably shameless promotion but i haven't logged in for like 2 years...


body:
I did a quick search and couldn't seem to find this question posted already, but I'm sure it must have so forgive me if it's a repeat.

I'm using a piezo and Arduino on TinkerCad to produce notes using the tone function, and the quality is not great (it's as if I can hear beats while the note is playing). I vaguely remember a colleague telling me this was an issue with the way my computer speakers handle square waves (I have a Macbook Air if that makes any difference), but I'm not positive. Has anyone had success in using TinkerCad to produce nicer sounding notes? If not, can anyone explain what the issue is to me?

Thank you!

[![Setup on TinkerCad][1]][1]
[![Sample Code][2]][2]

  [1]: https://i.stack.imgur.com/lyDkb.png
  [2]: https://i.stack.imgur.com/KumST.png

title: Sound quality is poor using a piezo in TinkerCad

Answers: 1

body:
To pack the comments into a proper answer to the question:

As Majenko stated in the comments, Tinkercad is a simulation. The codes doesn't get compiled and uploaded to hardware. Instead Tinkercad interprets the code on the fly. Simulations are not perfect clones of the real hardware, so you cannot expect the same performance from it as from the real Arduino. Also it is not build for producing high quality sound. The focus is entirely on simulating how the Arduino works.

If you are using this with a real Arduino you most likely will not have the glitches in sound.

What you are currently hearing is not a problem of Arduino, but of Tinkercad. You could file a problem with the developer, but probably they will not think this is an issue, or they will give it a very low priority.


body:
I used availableForWrite() function as below in my code. When I compile it for nano 33 IoT, everything is OK and compiles perfectly. However, when I change the board to nano 33 BLE, I end up with two scenarios:
1. using Arduino IDE as compiler > gives no error but the board doesn't after programming.
2. using the web-based compiler in Arduino website > give the following error:
```
error: 'class Arduino::USBSerial' has no member named 'availableForWrite'; did you mean 'available'?"
```

my code:
```
NoreplyTime=millis();
TimePassed= millis()-NoreplyTime;

         while(!Serial.availableForWrite()){
         TimePassed= millis()-NoreplyTime;
         if (TimePassed>1000){
         return false;
         }
        }
```
even simply having:
```
while (!Serial.availableForWrite());
```
generates error ONLY for nano 33 BLE board!

Thoughts?

title: availableForWrite() function return error when compiling for Arduino nano 33 BLE

Answers: 1

body:
The new Arduino cores use [a common API maintained in a separate repository][1]. This was copied from AVR core long time ago and doesn't contain some function added later to other cores. The function Stream.availableForWrite [was added][2] to Arduino API repository 5 months ago.

For the Arduino Mbed core they created [a branch in the Arduino API repository][3] to move the Arduino core in C++ namespace 'arduino'. But this was before availableForWrite was added. So the API version used in Mbed core doesn't have the function.

I reported it as [issue][4]. Even if they add the function to API I doubt they add an implementation of it to Serial.

  [1]: https://github.com/arduino/ArduinoCore-API
  [2]: https://github.com/arduino/ArduinoCore-API/pull/104
  [3]: https://github.com/arduino/ArduinoCore-API/tree/namespace_arduino
  [4]: https://github.com/arduino/ArduinoCore-API/issues/108


body:
    /*
        Basic ESP8266 MQTT example

        This sketch demonstrates the capabilities of the pubsub library in combination
        with the ESP8266 board/library.

        It connects to an MQTT server then:
        - publishes "hello world" to the topic "outTopic" every two seconds
        - subscribes to the topic "inTopic", printing out any messages
        it receives. NB - it assumes the received payloads are strings not binary
        - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
        else switch it off

        It will reconnect to the server if the connection is lost using a blocking
        reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
        achieve the same result without blocking the main loop.

        To install the ESP8266 board, (using Arduino 1.6.4+):
        - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
        http://arduino.esp8266.com/stable/package_esp8266com_index.json
        - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
        - Select your ESP8266 in "Tools -> Board"

    */

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>

    // Update these with values suitable for your network.

    const char* ssid = "SepehrNet";
    const char* password = "orangecoffee";
    const char* mqtt_server = "test.mosquitto.org";

    WiFiClient espClient;
    PubSubClient client(espClient);
    long lastMsg = 0;
    char msg[50];
    int value = 0;

    void setup_wifi() {

        delay(10);
        // We start by connecting to a WiFi network
        Serial.println();
        Serial.print("Connecting to ");
        Serial.println(ssid);

        WiFi.begin(ssid, password);

        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
        }

        randomSeed(micros());

        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
    }

    void callback(char* topic, byte* payload, unsigned int length) {
        Serial.print("Message arrived [");
        Serial.print(topic);
        Serial.print("] ");
        for (int i = 0; i < length; i++) {
            Serial.print((char)payload[i]);
        }
        Serial.println();

        // Switch on the LED if an 1 was received as first character
        if ((char)payload[0] == '1') {
            digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
            // but actually the LED is on; this is because
            // it is active low on the ESP-01)
        } else {
            digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
        }

    }

    void reconnect() {
        // Loop until we're reconnected
        while (!client.connected()) {
            Serial.print("Attempting MQTT connection...");
            // Create a random client ID
            String clientId = "ESP8266Client-";
            clientId += String(random(0xffff), HEX);
            // Attempt to connect
            if (client.connect(clientId.c_str())) {
                Serial.println("connected");
                // Once connected, publish an announcement...
                client.publish("sepehr.ghasem.helloxxx", "hello world");
                // ... and resubscribe
                client.subscribe("inTopic");
            } else {
                Serial.print("failed, rc=");
                Serial.print(client.state());
                Serial.println(" try again in 5 seconds");
                // Wait 5 seconds before retrying
                delay(5000);
            }
        }
    }

    void setup() {
        pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
        Serial.begin(115200);
        setup_wifi();
        client.setServer(mqtt_server, 1883);
        client.setCallback(callback);
    }

    void loop() {

        if (!client.connected()) {
            reconnect();
        }
        client.loop();

        long now = millis();
        if (now - lastMsg > 2000) {
            lastMsg = now;
            ++value;
            snprintf (msg, 50, "hello world #%ld", value);
            Serial.print("Publish message: ");
            Serial.println(msg);
            client.publish("outTopic", msg);
        }
    }

[![enter image description here][1]][1]I'm beginner at IOT and I'm using NodeMcu ESP8266 board and I want to control it with Arduino IDE so I install everything necessary and also using PubSubClient library for that. I used example file of PubSub in arduino. The NodeMcu first connects to internet and after a second disconnects.
I also switched the server(I don't know internet connection) from home modem to my mobile internet but it doesn't worked. I installed MQTT android application and want to connect to test server"test.mosquitto.org" and publish a meassage from NodeMcu to MQTT dashboard on my android mobile.
what is the problem with this standard sample code?

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

title: node mcu disconnect from mqtt server

Answers: 0


body:
I have 1.8 TFT display for Arduino Nano and it changes color very slow. When I try to change the color of the whole screen I see how it changes color line by line. I use "Adafruit GFX graphics core" and "Adafruit ST7735" libraries to change colors.

**Question:** Slow refresh rate of 1.8 TFT display is due to limited computation capability of Arduino or 1.8 TFT display itself or library used?

title: Slow refresh rate of 1.8 TFT display

Answers: 2

body:
Given you use the last library versions and have the cables right - it is hard to guess without your code.

So to check if it your code load one or two of the library examles and see if it works there.
Another option is to set SPI speed the set with begin(freq) is not working, because its wrong [see more in this issue](https://github.com/adafruit/Adafruit-ST7735-Library/issues/107).
If the problem still exists come back with wiring and code used. The nano is not the best choice with TFTs but runs decently.

body:
The ST7735 TFT uses SPI to communicate. That can *never* be particularly fast.

At 160x128 pixels with 16-bit colour depth that gives you 327680 bits that you need to transfer just for the colour data.  On top of that you have 88 bits to set up a drawing window (11 bytes of "set X coordinate and width" [5 bytes], "set Y coordinate and height" [5 bytes] and "start drawing" [1 byte]).

That's a total of 327768 bits that you need to transfer.

Now the transferring of that data is at the mercy of the SPI clock speed. How fast that can go depends on what the ST7735 can work at and the quality of your wiring (if it's a shield you can almost discount the wiring).  Assuming you can operate at the maximum 8MHz that the Arduino can run SPI at (which is probable) then you get:

    8,000,000
    ---------   =  24.4 frames per second
     327768

That is the absolute maximum theoretical speed, and doesn't take into account any work done by the Arduino to actually send the data. The SPI library is completely blocking in its operation and each pixel has to be sent separately as one blocking transaction. So you can expect about half that rate in reality, if not less, while it loops around and sends each pixel, then blocks waiting for the pixel to be sent.

And of course that's assuming running at the maximum speed. In reality that probably isn't happening. Libraries that use SPI often choose the "lowest common denominator" for their SPI speed (if they actively choose a speed at all) so that the library "just works" in the majority of cases. So the speed the library is running at will most likely be considerably lower than the actual maximum speed you *could* run at.

For example, if it runs at 1MHz instead of 8MHz then you will get about 3 frames per second (which is more like what you are describing).

So examine your chosen library and see what it does in the way of configuring the SPI speed. If it doesn't do anything then consider adding code to increase the speed. If it does then consider increasing the speed it operates at (see the [SPI library reference](https://www.arduino.cc/en/reference/SPI) for more details).

TBH, though, a small Arduino is seldom a good choice to control a TFT screen. At the bare minimum you really need a chip with far more memory so you can draw graphics "off-screen" in a framebuffer, and then use DMA to transfer that off-screen buffer to the TFT screen over a 16-bit parallel connection at high speed while leaving the CPU free to do other jobs.  Or even better a microcontroller with a built-in TFT controller to directly generate the correct drive signals for a TFT panel and store the whole screen image in internal RAM.


body:
How/where do I find a complete listing of "acceptable" Marlin g-codes applicable to a Melzi Sanguino board on a 3D printer (Zonestar). It appears that not all printer boards accept all available Marlin codes.

---

Then I was thinking incorrectly. I had assumed that not all g-codes (from a Marlin build) were, in fact, “implemented” the same way on all boards, and some would not even be recognized or interpreted. But I still don’t understand why that is.

title: Marlin g-codes applicable for a Melzi Sanguino board

Answers: 1

body:
As already written in the comments the software defines what G-Codes are taken by a (printer) board<br>**BUT** Even if the software has the same name (eg Marlin) it might behave different on different boards because of:

 - different release versions for different hardware
 - different release repositories being ahead or behind the master repo
 - hardware specific features a G-code triggers (most unlikely)

The clever way is to go from features I need to software supporting thosefeatures to boards supported AND useable for my hardware to controll (3d-printer/CNC-router/laser-cutter aso)
  -


body:
I'm trying to receive MIDI messages on a Leonardo. To do that I used the circuit in the diagram below (only the top half for receiving). The only thing I did differently was using an 1N4148 diode instead of the 1N914. I connected GND to pin GND, 5V to pin 5V and RX to pin 0 (RX), and I used code below to see whether I do get any inputs or not. (I first started with some more complex code but it seems this is the minimal thing I can do.) As a MIDI source I used an Arturia Keystep which I tested on a midi instrument.

Unfortunately I don't get any input, and I don't know why. What I tried so far:

* Verified the polarity of all cables, and made sure all connections work.
* Swapped the Leonardo with a different one (both new).
* Swapped out the 6N137 optocoupler with another one (both new).
* Addded above the `if`-statement a `Serial.println("test");` which then resulted in an endless avalanche of "test" in the serial monitor - just to check if the USB connection works.
* Measured the voltage between pin 5 and 8 on the 6N137 and it is indeed 5V.

Is there anything obvious I'm doing wrong? What things do you suggest doing to try to find the bug? (I do have a multimeter but no oscilloscope.)

<img src="https://i.stack.imgur.com/TNCq2.png" width="300" /> (from [this answer](https://arduino.stackexchange.com/questions/14054/interfacing-an-attiny85-with-midi-via-software-serial/14055#14055)).

    byte b;
    void setup() {
      Serial.begin(9600); //USB
      Serial1.begin(31250); //MIDI
    }

    void loop() {
      if (Serial1.available() > 0) {
        b = Serial1.read();
        Serial.println((int)b);
      }
    }

title: How to debug MIDI input?

Answers: 1

body:
The solution:<br>
On the image is stated plugs are solder-side. So swapping pin 2/3 does the trick