text:
Combining two code of two sensor in one program
I'm using two sensors, which is Galvanic Skin Response sensor and Heartrate sensor. The problem is that when I combined both of the codes, the only output that is showing up is from Heartrate only which is at A0. If I run them separately both codes works perfectly fine. My background in coding is basic and both codes came from the internet.
These are the codes:
    #define BLYNK_PRINT Serial
    #include <ESP8266_Lib.h>
    #include <BlynkSimpleShieldEsp8266.h>
    #include <SoftwareSerial.h>
    SoftwareSerial EspSerial(2, 3); // RX, TX

    #define samp_siz 4
    #define rise_threshold 4

    // Your ESP8266 baud rate:
    #define ESP8266_BAUD 9600

    char auth[] = "ba4e5bd1bd9549669a02ac378db9faf6";
    char ssid[] = "vivo";
    char pass[] = "takoyaki";

    /*char auth[] = "b3f01a592b78471f9f720b09d2ff8047";
    char ssid[] = "vivo";
    char pass[] = "takoyaki";
    */
    ESP8266 wifi(&EspSerial);

    BLYNK_CONNECTED()
    {
      Blynk.syncAll();
    }

    BlynkTimer timer;

    // Pulse Monitor Test Script

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

      // Set ESP8266 baud rate
      EspSerial.begin(ESP8266_BAUD);
      delay(10);

      Blynk.begin(auth, wifi, ssid, pass);

      pinMode(A0, INPUT);
      pinMode(A1, INPUT);

      //timer.setInterval(1000L, myTimerEvent);     //send the arduino's                         uptime
      timer.setInterval(350L, sensor);            //send gsr data every         0.35s
    }

    /*void myTimerEvent()
    {
      // You can send any value at any time.
      // Please don't send more that 10 values per second.
      Blynk.virtualWrite(V4, millis() / 1000);
    }
    */
    void sensor(){

      const int GSR=A1;
      int inputvalue=0;
      int gsr_average=0;
      long total=0;
      for(int j=0;j<10;j++)                       //Average the 10                 measurements to remove the glitch
          {
          inputvalue=analogRead(GSR);
          total += inputvalue;
          delay(5);
          }
       gsr_average = total/10;
       Serial.println(gsr_average);
       Blynk.virtualWrite(V6, gsr_average);
    }

    void heartrate ()
    {
        int sensorPin =A0;
        float reads[samp_siz], sum;
        long int now, ptr;
        float last, reader, start;
        float first, second, third, before, print_value;
        bool rising;
        int rise_count;
        int heartrate;
        int n;
        long int last_beat;

        for (int i = 0; i < samp_siz; i++)
          reads[i] = 0;
        sum = 0;
        ptr = 0;

        while(1)
        {
          // calculate an average of the sensor
          // during a 20 ms period (this will eliminate
          // the 50 Hz noise caused by electric light
          n = 0;
          start = millis();
          reader = 0.;
          do
                  {
            reader += analogRead (sensorPin);
            n++;
            now = millis();
          }
          while (now < start + 20);
          reader /= n;  // we got an average

          // Add the newest measurement to an array
          // and subtract the oldest measurement from the array
          // to maintain a sum of last measurements
          sum -= reads[ptr];
          sum += reader;
          reads[ptr] = reader;
          last = sum / samp_siz;
          // now last holds the average of the values in the array

          // check for a rising curve (= a heart beat)
          if (last > before)
          {
            rise_count++;
            if (!rising && rise_count > rise_threshold)
            {
              // Ok, we have detected a rising curve, which implies a         heartbeat.
              // Record the time since last beat, keep track of the two previous
      // times (first, second, third) to get a weighed average.
      // The rising flag prevents us from detecting the same rise more than once.
              rising = true;
              first = millis() - last_beat;
              last_beat = millis();

              // Calculate the weighed average of heartbeat rate
              // according to the three last beats
              print_value = 60000. / (0.4 * first + 0.3 * second + 0.3 *         third);

              heartrate = print_value;

              //Serial.print(print_value);
              Serial.print(heartrate);
              Serial.print('\n');
              Blynk.virtualWrite(V7, heartrate);

              third = second;
              second = first;

            }
          }
          else
          {
            // Ok, the curve is falling
            rising = false;
            rise_count = 0;
          }
          before = last;

          ptr++;
          ptr %= samp_siz;

        }
    }

    void loop()
    {
      Blynk.run();
      //timer.run();
      sensor();
      heartrate();
    }

If you need the codes without those blynk's command just tell me in the comment section

the function heartrate() has an infinite loop, so the Uno is stuck there

so i cannot use the code as a function ? how do i need to edit it ?

The while(1) loop is the problem. Rewrite the function in a way, that it takes the reading, does somethings with it and then exits to the main loop to do something else

Since the code keeps record of the last measurements, you will have to make these variables static or global, so that they keep their value between different executions of the function. And btw: the start variable has to be an unsigned long, since that is the type, that the millis() function returns. The same goes for variable now.

Thank you so much for your help. I really do appreciate it sir. I'll do the edits soon and if i have questions I'll be here again

can you explain a little bit more about that while(1) loop ? im so lost

while(1){ ... } is an infinite loop - it never exits, therefore heartrate() can never end and return to loop. It just sits there taking readings - forever. Try calling only one of sensor() until it works. Then try calling only the other one, until it works, too. Once they each work correctly, only then try calling both of them. This is a classic "divide-and-conquer" debugging technique.

Ive done the tips like what you were suggesting and calling those sensors one by one and it works perfectly fine. What control structure is the most suitable for me to replace the while(1) ?

I have not tested the following code, so it will be up to you to do this and handle small errors. This is more about the coarse way to change the program. And you will have to understand, what the code really does, to be able to change it the way you need it.
First you will have to make some of the variables in the heartrate() function to global variables (by writing them near the top of the sketch outside of any function), so that they keep their values between the different executions of the function. I also changed some variable types, which match the type of the assigned values.
float reads[samp_siz], sum;
unsigned long now, start, ptr;
float last, before, reader;
unsigned long first, second, third;
bool rising;
int rise_count;
float print_value, heartrate;
unsigned long last_beat;

The sensor pin should be #defined at the top of the program (by convention). Then you should put this code:
for (int i = 0; i < samp_siz; i++)
    reads[i] = 0;
sum = 0;
ptr = 0;

into the setup() function.
Now we can look at the while(1) loop. On Arduino a value of 0 is treated as the boolean false and every other value as true. So this is the same as writing while(true). The while() structure loops as long, as the expression inside the brackets evaluates to true. Since this is always the case here, it will loop forever. At this point you can just erase this line (and the corresponding closing bracket }).
After these changes the function will only take 1 reading (averaged over 20ms), then check, if a heartbeat was detected, and finally exiting to the loop() function. Since not every reading is a heartbeat, you will get more output from the sensor() function (which outputs on every execution) than from the heartbeat() function. And now, due to your functions being non-blocking, you will get very fast output. You might want to slow that down, by using a delay() or (better) the millis() function (like in the BlinkWithoutDelay example of the Arduino IDE).
Note, that this code exhibits some bad coding styles. You can get much of good code on the web, but also much of bad code. I see wrong types for variables, the usage of totally unnecessary variables and usage of the millis() function, which doesn't handle the rollover. This doesn't mean, that the code does not work. But you can get weird and difficult to debug errors through them.


text:
Vary voltage using relay. Is this possible?
I am planning to control a RGB lamp using Arduino. The lamp is 24V and I want to be able to control the brightness of the lamp. I found a relay that will let me control the 3 channels (red green and blue), but will only let me turn it on and off (Not control brightness)
I am looking for a way to control the lamp both on/off and brightness. What component will do the same as my relay, but also let me use the varying voltage from the arduino to control my 24V lamp? (Just like a transistor)
I have an external 24V powersupply along with 5V for the arduino
Thanks!

No, you can't vary the voltage with a relay. The only way you could do it with a relay would be to have a selection of different voltages available, and then use multiple relays to select which voltage is used. Less than ideal.
You need to use PWM to create a square wave with varying duty cycle. The duty cycle (the percentage of time the power is on within a given period) defines the average voltage of the output.  That PWM needs to be fed into a MOSFET which will in turn control the 24V power to the lamp.
It's exactly the same as driving RGB LED strips, except it's in the shape of a lamp not a long strip.

Should be noted that this also can control the LED to be on/off so it it removes the need for a noisy relay completely.  With the PWM output off, the LED is off, and then it can be ramped up to full brightness using higher duty cycle, all the way to fully on.

This is what I have been looking for. Do you reckon I can find a premade PCB that can do this for me on eBay (preferably from China)?

More than likely, yes.

Would you be a champ and confirm that I can vary the voltage using this: https://www.ebay.co.uk/itm/5PCS-MOSFET-Button-IRF520-MOSFET-Driver-Module-for-Arduino-ARM-Raspberry-pi/272160515977?_trkparms=aid%3D555018%26algo%3DPL.SIM%26ao%3D1%26asc%3D20140122125356%26meid%3D6d7f25afcc134e48b34f9f3d9a275cec%26pid%3D100005%26rk%3D1%26rkt%3D8%26mehot%3Dag%26sd%3D232518999508%26itm%3D272160515977&_trksid=p2047675.c100005.m1851

Probably. As long as you have the ability to switch the ground (cathode on an LED) connection. If it's a "common anode" arrangement (like most LED strips are) then that's fine.

Yes it is possible to vary voltage with a relay.  A relay is simply a 2 way 3 pole switch.

simulate this circuit – Schematic created using CircuitLab
By switching in a resistor to the supply voltage you have lowered the voltage and will dim the 24V light source.  The actual resistor value will depend on how dim you want to go.  Make sure the resistor is rated for the load you plan to place on it.

This is assuming there is already some resistance in your LED device, you would not normally want to hook a bare LED up to the supply with no resister in series.  But this is a viable option when/if you only want OFF/DIM/FULL.  The PWM signal and transistor gives more control.

That would only give on or dim, but no off...

Yes, the purpose of the schematic was to illustrate how to use a relay to adjust voltage.  It wasn't intended to be a complete schematic.

The LEDS I'm using are actually a board with 12 powerful LEDS. The lamp looks a bit like this: https://www.thomann.de/dk/stairville_quad_par_profile_5x8w_rgb_ww.htm My lamp broke (control board broke), so now I am planning on using it for a party-project and plan to take the lamp apart and keep the PCB-board where the LEDS, a heatsink, plastic housing and LED-lenses are on. I am almost sure that there are resistors on the board already. I can check to be sure, but if I burn it, it doesn't really matter. The LEDS has no value.

Do you reckon I can find a board on eBay (preferably from china) that will do this for me?

If there are no board on eBay. Perhaps I could build this and then use a transistor for the actualy powering of the LED lamps. Then I could just find a resistor that would dim so much, that the transistor barely sends power, making the LEDs look like they're off

If you want to have a variable dimmer then you'll have to go the power transistor route.  If you just want a simple On, Dim, Off circuit then a relay will work. (you'll actually need 2, one for dim/bright and one for on/off)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Can I make the BT module disconnect with a BT module and connect with another in the code?
I am working on a project that requires a connection between two BT modules (HC-05) and a mobile phone. Later on, I encountered a problem: I can't connect two BT modules to one at the same time, So I thought about the possibility of ending a connection and starting the other one when needed. If that was possible, how can I do that in an arduino code?
One of the BT modules is a master which means it can't connect to the phone and it has to be a master because it must be connected to the other slave BT module.

Send AT+ROLE=1 to BT module to set module into master role.
To set module back to slave mode, send AT+ROLE=0
Also check this video, you have source code in the description. It will help you understand how to do it.

But that requires reversing the rx-tx connection to enter the AT mode from the connection being used to send and receive data, which as far as I know can't be done during the code execution as the pins setup is being configured once at the beginning of the code.

Can you share your code? Serial comm(RX TX) is two way communication

I haven't written a code yet.

Try with this command. You can't know without the  code

As I knew recently that the BT connection is a point to point connection which means that can't connect the two BT modules and the mobile in one network at the same time.

That's true, only one device can be connected to one BT module. It's normall.

I have tried many time to enter the AT command mode connecting the tx with the rx and vice versa but it didn't work. Strange characters were appearing on the serial monitor. It didn't work till I connected the rx with the rx and the tx with the tx.

TX from BT module goes into RX pin from Arduino and vice versa. That's the way you talk with BT module.

So I decided to use the slave module to communicate between the masters in different times (connects with one and disconnects with the other). How can I make the BT module do that (to disconnect with the current BT module and wait for connection with another known module)?

To connect the BT module to the arduino for communication Rx to TX and TX to RX is used. But to enter the AT mode I had to connect the RX to the RX and the TX with the TX and it worked.

Send proper command to BT module. Here's link with list of all commands for HC-05 BT module. Anwser is edited

@SilvioCro, the trick with connecting RX to RX, TX to TX is that then the USB chip is connected RX to TX to module and you can talk to module from the Serial Monitor. The main MCU must have a sketch without Serial.begin() (empty sketch or Blink)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
could not convert 'digitalWrite(8u, 1u)' from 'void' to 'bool'
I am trying to make some LED lights to turn on when i flick a switch on my RC crontroller. I will connect the signal wire from RC controller to pin 8. The plan is: if i flick the swich, the LED's (pin 12,11,10,9) will turn on, and if i don't flick the swich the LED's wont turn on. This is a Arduino nano what will be connected on a drone.I found another question HERE, but there was no real answers.
 I get a error that say:

exit status 1
  could not convert 'digitalWrite(8u, 1u)' from 'void' to 'bool'

How can i fix this? Should i write the code another way?
Arduino Code:
    void setup() {

  pinMode(4, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, INPUT);

}

void loop() {

  if (digitalWrite(8, HIGH));
    digitalWrite(12, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(10, HIGH);
    digitalWrite(9, HIGH);
  else
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);

  digitalWrite(4,HIGH);
  delay(1500);
  digitalWrite(4,LOW);
}

why has this question upvotes?

Because it’s a clear, answerable question with an error message and (relatively) minimal reproduction @Juraj

upvote is for "usefull". and I agree with the text in bubble over the downvote button

You should be using digitalRead(8) instead of digitalWrite(8, HIGH). Your sketch is also missing some curly brackets.
void setup(){
  pinMode(4, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, INPUT);
}

void loop(){
  if(digitalRead(8) == HIGH){
    digitalWrite(12, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(10, HIGH);
    digitalWrite(9, HIGH);
  }
  else{
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
  }
  digitalWrite(4,HIGH);
  delay(1500);
  digitalWrite(4,LOW);
}

The use of delay() will block the sketch from doing anything else, and should be replaced with a millis() timer. Have a look at the BlinkWithoutDelay example in the IDE.

Can't i just make another void loop() and have the blinking there? Then it won't interfere with the if statement.

You can only have 1 void loop(). There are several libraries available that are easier to use than writing your own code, such as https://www.avdweb.nl/arduino/timing/virtualdelay. This library lets you use a similar syntax as the delay() function, and is non blocking.

This line of code is the source of your problem.

void loop() {

  if (digitalWrite(8, HIGH));

If expressions expect a boolean (true/false), but if you check the documentation for digitalWrite(), you’ll see it returns “Nothing” (i.e. void).
You need to use digitalRead() to check the current state of the pin.


text:
Is there a manometer available to use with Arduino?
I used an analog manometer in a plumb system. I would like to actually track information about water pressure across an entire building on different points and record all this information to analyze changes on pressure. I was wondering if there is a manometer that can be used with arduino. Or if there is some other homemade solution?
If there is any electronic sensor with an analog output that would be enough.

There are intrusive ones, i.e. you need to cut the pipes.  I can't say I have seen one that you could just wrap around the pipe, but the should exist.  I doubt you find one specifically for Arduinos, but you should be able to get one that the Arduino can talk to, look for I2C, SPI or One wire interfaces.  If you can get the datasheet it should be simple enough to write your own library for it.  Looking for libraries is another way of identifying a suitable part.

@CodeGorilla Yeah I was planning to cut the pipe, I already used an analog one cutting the pipe. Thanks for the advice, I will start looking for I2C and SPI One wire interfaces.

glue a neodymium magnet to the analog meter's needle, then mount a hall-effect sensor on the side of the meter and read it's value to determine pressure. you could also go optical.

I think the problem is not the way to connect a manometer but the choice od the manometer. I work on project for Firefighters and my main problem is to find flow meters able to measure flow between 0 and 1000 liters per minutes, and manoter for pressure up to 25 bars and so on.

Bruno, there are a number of sensors available, try an Ebay search, to do what you want.  However, you need to determine what pressure range you are looking at.  As you mention manometer I assume you are working in the mBar range but to me that would be at odds with the pressure typically seen in whole building systems.  An Ebay search on 'Pressure transducers' will yield a good range of devices, likely to be primarily industrial types and some using wheatstone bridge type outputs.  you may need an op-amp circuit to buffer / amplify the output signal but virtually all sensors can be interfaced to an Arduino with the correct conditioning cicuitry.  As you are aware to measure pressure all sensors will need to be invasive into the pipework.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Getting RFID tag data using C#
I am trying to get an RFID tag number using a WinForms application. But whenever I click the Button the application stops responding. Please help regarding this.
Arduino code
void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
}

void loop() {
  if(rfid.isCard()) {
    if(rfid.readCardSerial()) {
      Serial.print(rfid.serNum[0], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[1], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[2], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[3], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[4], HEX);
      Serial.println("");
      delay(1000);
    }
  }
  rfid.halt();
}

C# code
private void button1_Click(object sender, EventArgs e) {
  try {
    serialPort1.Open();
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
    textBox2.Text = "connected";
    serialPort1.Close();
  }
  catch(Exception ex) {
    textBox2.Text = "Com port disconnected";
  }
}

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) {
  SerialPort sp = (SerialPort)sender;
  string indata = sp.ReadExisting();
  textBox1.Text = indata;
}

Remove serialPort1.Close(); because that will close the serial port right after you open it.

i tried this now I am getting exception in textbox1.Text=indata; exception is System.InvalidOperationException: 'Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.'

You are closing the port immediately after you open it. You need to keep it open while you are expecting data. Remove the line
serialPort1.Close();

Then, in the callback you try to access the GUI from the callback thread. That's not allowed. Use Invoke().
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     SerialPort sp = (SerialPort)sender;
     //string indata = sp.ReadExisting();
     string indata = sp.ReadLine();
     //textBox1.Text = indata;
     Invoke(new Action<string>(
         (s) =>
         {
             textBox1.Text = s;
         }
     ), indata);
}

now the error is removed but nothing is shown in textbox

@Ravi First, I noticed I was missing a ) in the code. Second, since you are sending the data with Serial.println(""); you should probably use ReadLine() on the C# side. See updated answer.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Talking to Eurotherm 2416 temperature controller over modbus rs232
I am trying to implement the modbus library written by smarmengol to read process values and to set new setpoints (e.g. temperature) on a Eurotherm controller. The Arduino sketch looks like this:
/**
 *  Modbus master example 2:
 *  The purpose of this example is to query several sets of data
 *  from an external Modbus slave device.
 *  The link media can be USB or RS232.
 *
 *  Recommended Modbus slave:
 *  diagslave http://www.modbusdriver.com/diagslave.html
 *
 *  In a Linux box, run
 *  "./diagslave /dev/ttyUSB0 -b 9600 -d 8 -s 1 -p none -m rtu -a 1"
 *  This is:
 *      serial port /dev/ttyUSB0 at 9600 baud 8N1
 *      RTU mode and address @1
 */

#include <ModbusRtu.h>
#include <SoftwareSerial>

SoftwareSerial mySerial (3,5);

uint16_t au16data[16]; //!< data array for modbus network sharing
uint8_t u8state; //!< machine state
uint8_t u8query; //!< pointer to message query

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram[2];

unsigned long u32wait;

void setup() {
  // telegram 0: read registers
  telegram[0].u8id = 1; // slave address
  telegram[0].u8fct = 3; // function code (this one is registers read)
  telegram[0].u16RegAdd = 1; // start address in slave
  telegram[0].u16CoilsNo = 1; // number of elements (coils or registers) to read
  telegram[0].au16reg = au16data; // pointer to a memory array in the Arduino

  // telegram 1: write a single register
  telegram[1].u8id = 1; // slave address
  telegram[1].u8fct = 6; // function code (this one is write a single register)
  telegram[1].u16RegAdd = 2; // start address in slave
  telegram[1].u16CoilsNo = 250; // (Setpoint) number of elements (coils or registers) to read
  telegram[1].au16reg = au16data+4; // pointer to a memory array in the Arduino

  Serial.begin(9600);
  master.begin( &mySerial, 9600); // baud-rate at 9600

  master.setTimeOut( 5000 ); // if there is no answer in 5000 ms,roll over
  u32wait = millis() + 1000;
  u8state = u8query = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    master.query( telegram[u8query] ); // send query (only once)
    u8state++;
    u8query++;
    if (u8query > 2) u8query = 0;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 1000;
    }
    break;
  }
   Serial.print(au16data[O]);

  au16data[4] = analogRead( 0 );

}

I can read process values with telegram[0] very well (temperature and/or setpoint), but I cannot change the setpoint with telegram[1]. If I run the code, it puts the current temperature to serial monitor but resets manually changed setpoints to zero. Where is the error? Should I write the value for the setpoint as HEX or DEC? What does the last command do actually?
Thank you!

telegram[1].u16CoilsNo = looks like this must be 1 NOT 250 (writing single 16 bit register); 2) are you writing to the same register / setpoint you read in telegram[0]? if so why u16RegAdd address is different?

@Flanker You are right, it must be 1 (single register) and not 250. The solution for my problem was to set au16data[4] to a fixed value, e.g 250, or something like that. I think that au16data[4] can be set interactively by sending any number thru a hardware serial, since analogRead(0) is Rx on Arduino. The start address for setting (writing) a setpoint is 2 and 1 for reading of the same value (setpoint). That is why au16RegAdd differs.Thank You for an answer!!

You could also take a look at this github project:
https://github.com/ukos-git/arduino-eurotherm2416
It is specifically designed for the purpose you ask for.
It basically includes Module named Temperature and a possibility to set or read it:
Temperature.set(100)
t = Temperature.getTemperature()

Look at https://github.com/ukos-git/arduino-eurotherm2416/blob/master/app/app.ino.


text:
Wemos D1 mini not being shown when connected to macbook
I have multiple Wemos d1 mini lying around, but can't seem to get them connected to my macbook, to they do not show up in my /dev/tty?
I tried updating the driver, both using home-brew and installing the driver manually -  as suggested here
https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
but nothing seem to work?
I tried different cables? no way to connect to it?

I finally had success following the removal instructions, but NOT installing anything.

@josecanuc, what removal instructions?

In the link you give in your question, steps 1-3.

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

Oops! Well, that would definitely cause the problem! Glad you got them to connect.

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

@MichelKeijzers - the answer is written by the author of the question - so it does answer the question

I tried different cables? seems like you have multiple power only cables, so technically, the answer should've been "All of the cables I tried don't have a data line"

@anita it would be great if you could expand on your answer making it clear for others who have the same problem. Perhaps you could add diagrams or tests to perform to determine if the data line is there.


text:
Using a water sensor with a NodeMCU make it less sensitive?
I'm trying to digitalRead from a water sensor (the one in the picture) using NodeMCU v3,when I try the sensor with an Arduino board it works fine, but when I try it with an ESP8266 NodeMCU v3 it becomes less sensitive to water with some pins or doesn't work at all with the others. My question is: Is that normal or I'm doing something wrong ?

 int pin = 14;
 char printBuffer[128];
 int ledPin = 12;
 const int buzzerPin = 13;

  void setup()
  {
    pinMode(pin, INPUT);
    pinMode(buzzerPin, OUTPUT);
    pinMode(ledPin,OUTPUT);
    Serial.begin(115200);
  }

  void loop()
  {
    sprintf(printBuffer,"PIN %d level is %d\n",pin, digitalRead(pin));
    Serial.print(printBuffer);
    if (digitalRead(pin)==HIGH)
    {
      tone(buzzerPin, 100,1000);
      digitalWrite(ledPin, HIGH);
      delay(100);
      noTone(buzzerPin);
      digitalWrite(ledPin, LOW);
      delay(100);
      Serial.println("----------- ALARM ACTIVATED -----------");
    }
    else{
      noTone(buzzerPin);
      digitalWrite(ledPin, LOW);
    }
    delay(500);
   }

The ESP8266 GPIO pins are funny beasts at the best of times. Using an analog sensor like that on a digital pin is bound to be different with different hardware.

So isn't there a way to get more accurate results ?

Define "accurate"...  There's nothing accurate about that sensor in the first place.

I just want it to sense that it is in the water that's all

Do you have a link to the datasheet for the sensor so we can have a clue what the schematic is on it?

I can guess how you're wiring them. Without knowing what it is that you are using, though, we cannot help you. We need to know what the components on the board are, and how they relate to each other.

This is how I'm wiring them: (+) --> v3, (-)  --> G, and S --> D5 that's dor the sensor and the buzzer: G-->G and (+) --> D7

Without knowing what comes out of "S" and how that relates to the water "sensor" portion of the device it's impossible to know what is going on. I do find those "water sensors" very very crude and primitive. Not really worth wasting your time with. Proper water sensors cost hundreds of dollars (I work with these).

I'm using it for a school project actually

Do you even have a link to where you got it from?

doesn't that need an analog input, not a digital one? the only other diff would be 5v vs 3.3v, so feed it Vin (or external 5v if you have a CH340-based nodeMCU) and level shift the signal down to 3.3v.

Ok, I found some decent images online for a similar one and reverse engineered the circuit.

I know a similar sensor and I remeber that applying a constant voltage to + will lead to corrosion due to electrolysis. Therefore the sensor will be destroyed after running only a few hours. The key might be to just activate it for each reading, but I for myself didn't like it anyway and used a different sensor.

You are using it wrong.
That sensor (crude as it is) is an analog sensor. It's not designed to be used connected to a digital pin.
It outputs an analog voltage proportional to the resistance between the tracks in the sensing portion.
By feeding that voltage into a digital pin you are relying on the logic threshold values, plus any other components (pullup resistors, etc), to give you a "wet" or "try" signal.
Since pins differ (some have pullups, some pulldowns, some nothing, etc) and the logic thresholds are only an approximation in any case, it's doomed to failure.
You need to connect the sensor to an analog input and compare the value read to a threshold value of your choosing.  However the ESP8266 is very very poor when it comes to analog - it only has one analog input, and that is only capable of sensing between 0 and 1 volt.

how did you determine that that water sensor is analog Since it's got a + and - input and a third sense line I would expect it to put out a logic level signal. Why would it need power if it's just a variable resistor? (I guess it could be a voltage divider, but the picture looks like it has an IC and a few discrete components.

It has a transistor as an amplifier.

I wanted to use the analog input, but since I'm using it with a soil moisture sensor I decided to use this water sensor in a digital mode, should I just use an multiplexer and use them both in a analog mode and compare the value read to a threshold value as you said ? otherwise I have an arduino uno, can I use it but without changing code (since the code above is just for testing , the actual project is displaying sensors value in a esp8266 webserver)?

reading multiple analog signals on an ESP8266 is simple


text:
STM32F103C8 - Arduino Mega FAST MODE(400000L) I2C communcation not working
I'm trying to connect a stm32F103C8 board (master) to an Arduino Mega (slave) over I2C. I have a master and slave program which runs perfectly fine when the clock frequency for I2C communication is set to standard (100000L) which is default.
I wanted the communication to happen a bit faster. So I changed the clock frequency to fast mode i.e., 400000L. I am seeing some weird behavior.
I can send data from master to slave (I can see the data appearing on slave) but when the master requests data from the slave, I don't receive any data on master.
I have tried the same code out on an Arduino Uno (master) and Mega (slave). The code works fine for both standard and fast mode.
I run the code in standard mode by commenting the following line in the master code.

    Wire.setClock(400000L);
Here's the code I have for the Master and Slave:
//Master Code

#include <Wire.h>

int data = 1;
void setup() {

  Wire.begin();
  Wire.setClock(400000L);
  Serial.begin(9600);
}
void loop() {
  Wire.beginTransmission(9);
  Wire.write(data);
  Wire.endTransmission();

  Wire.requestFrom(9, 1);
  int x = Wire.read();
  Serial.print(x);
  delay(500);

}

//Slave Code

#include <Wire.h>

int send_data = 1;
void setup() {

  Serial.begin(9600);

  Wire.begin(9);

  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}
void requestEvent()
{
  Wire.write(send_data);
}

void receiveEvent(int bytes) {
  int x = Wire.read();
  Serial.println(x);
}
void loop() {
delay(500);
}

I'm having hard time understanding what's causing the issue. Please help me make sense as to why it's doing this and how I can resolve it.

try setting the i2c clock speed in the slave alsp

tried it. it didn't work.

Please add information about the wiring, wire length, common ground, power source, pullup resistors, etc.


text:
Detect the end of playback of a MP3 file with DFPlayerMini / DFRobotDFPlayerMini.h library
For a project I'm doing I've used an ESP8266/12e, a RTC Module DS3231 and a DFplayerMini
Basically it's a caller for birds and it has to play a 12-minute long MP3. The MP3 file should be played for 2 hours at the sunrise and 2 hours before the sunset, so each time it should be played 10 times (10 × 12 = 120 minutes (2 hours))
The code I wrote so far (some parts are omitted for brevity):
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
#include <Wire.h>
#include <RtcDS3231.h>

#define DELAY_ONPLAY 1000
#define DELAY_ONPAUSE 20000

// RTC Library (I2C)
RtcDS3231<TwoWire> rtcObject(Wire);

// MP3 Serial communication
SoftwareSerial mySoftwareSerial(14, 12);
DFRobotDFPlayerMini myDFPlayer;

// Variables
int volume, mth, day, h, m;

// State of the playback
int playbackCount = 0;
bool isPlaying = false;

RtcDateTime currentTime;

void setup() {

    mySoftwareSerial.begin(9600);
    // Start serial connection
    Serial.begin(115200);
    // Start I2C
    rtcObject.Begin();

    if (!myDFPlayer.begin(mySoftwareSerial)) {
      while(true){
        delay(10);
      }
    }

    /* Get the value of potentiometer in the range of [3..30] and
     * set the volume
     */
    setVolume();

}

void loop() {

    setVolume();
    currentTime = rtcObject.GetDateTime();    //get the time from the RTC

    mth  = currentTime.Month();
    day  = currentTime.Day();
    h    = currentTime.Hour();
    m    = currentTime.Minute();

    /* The caller is not playing: check if date and time should
     * start the playback
     */
    if (isPlaying == false) {

        if (startSunrise() || startSunset()) {
            isPlaying = true;
        }

        else {
            // Nothing to do for the next 20 seconds
            delay(DELAY_ONPAUSE);
        }
    }

    else {

      // Currently playing
      if (playbackCount < 10) {

          if (/* MP3mini_is_idle */) {

            myDFPlayer.play(1);
            playbackCount = playbackCount + 1;

          }
      }

      else {
        playbackCount = 0;
        isPlaying = false;
        Serial.print("End of playback");
      }

      delay(DELAY_ONPLAY);

    }
}

void setVolume() {

    // Get the value of potentiometer in the range of [3..30]
    volume = map(analogRead(A0), 0, 1023, 2, 30);
    volume = constrain(volume, 3, 30);
    // Set the player volume
    myDFPlayer.volume(volume);
    Serial.println(String(volume));

}

bool startSunrise() {

    /* at the sunrise the call has to be played for 2 hours */

    if (mth == 2) {
        if ((day == 20 && h == 7 && m == 8) ||
            (day == 21 && h == 7 && m == 6) ||
            ...
            (day == 28 && h == 6 && m == 54) ||
            (day == 29 && h == 6 && m == 52)) { return true; }
    }

    if (mth == 3) {
        if ((day == 1  && h == 6 && m >= 49) ||
            (day == 2  && h == 6 && m >= 47) ||
            (day == 3  && h == 6 && m >= 45 ) ||
            (day == 4  && h == 6 && m >= 43) ||
            ...
            (day == 27 && h == 6 && m >= 0) ||
            (day == 28 && h == 5 && m >= 58)) { return true; }
    }

    return false;
}

bool startSunset() {

    /* 2 hours before sunset the call has to be played for 2 hours */

    if (mth == 2) {
        if ((day == 20 && h == 15 && m >= 41) ||
            (day == 21 && h == 15 && m >= 42) ||
            ...
            (day == 28 && h == 15 && m >= 52) ||
            (day == 29 && h == 15 && m >= 54)) { return true; }
    }

    if (mth == 3) {
        if ((day == 1  && h == 15 && m >= 56) ||
            (day == 2  && h == 15 && m >= 58) ||
            (day == 3  && h == 15 && m >= 59) ||
            (day == 4  && h == 16 && m >= 1) ||
            ...
            (day == 27 && h == 16 && m >= 31) ||
            (day == 28 && h == 16 && m >= 33)) { return true; }
    }

    return false;
}

The part I'm stuck on is
  if (playbackCount < 10) {

      if (/* MP3mini_is_idle */) {

        myDFPlayer.play(1);
        playbackCount = playbackCount + 1;

      }

  }

How do I detect in the if condition if the MP3 is actually playing before play it again?
I think a 12-minute delay() is not the right approach.
In the image below the DFPlayerMini pinout: I noticed It has a BUSY pin  but I haven't found examples so far that uses this pin to detect the playback state.

Thanks for any suggestion.

Have you googled for this? I directly found this site. The table under the image, that you have in your question, states, that the BUSY pin is LOW, when the DFPlayer is playing something. Isn't that exactly, what you want?

Thank you. I'll try as soon as possibile and I'll give you a feedback in a few hours

Alternatively you could create a new audio file that has the bird song, repeated 10 times, in it. PS if you go with the repeated playback code, I'd have the song repeat till it reaches 120minutes (using millis()), instead of repeating it 10 times. That way if you ever change the sound file, and that file has a different length, you wouldn't have to update the code.

@chrisl, I've solved checking the busy pin. If you like to put the comment as the answer I would be happy to accept it

As @chrisl alread said, you could use the busy pin. Or a simple serial query
myDFPlayer.readState();

If the result is something like DFPlayerPlayFinishe the actual track is complete.

I've solved checking the busy pin, thank you

The busy pin, means that the flash memory is being accessed. So its not the same as "track being played".


text:
Run two steppers one by one
I want to run two stepper motors one after the other. Stepper 1 has to move 5 rotations, and stepper 2 has to move 1 rotation. Here is the code.
Stepper 1 is nema 34
And stepper 2 is nema 24
#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper1 (1, 3, 2); // Defaults to 4 pins on 2, 3, 4, 5 mortor (A)
AccelStepper stepper2 (1, 5, 4); // Defaults to 4 pins on 2, 3, 4, 5 motor (B)

long Steps_For_Distance1 = 3; // 3cm
long Steps_For_Distance2 = 5; // 5cm
long currentPos = 0;
long targetPos = 200;
long targetPos_Reverse = -200;
long Motor_Speed1 = 50;
long Motor_Speed2 = 400;
long Motor_Speed3 = 800;
int Op_Sw = 0;
const int buttonPin = 2;     // the number of the pushbutton pin

const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup()
{
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);

  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void checkStepper1_For_DT(AccelStepper &astepper)
{
  if (astepper.distanceToGo() == 0)
  {
    // Random change to speed, position and acceleration
    // Make sure we dont get 0 speed or accelerations
    astepper.setCurrentPosition(currentPos);
    astepper.moveTo(targetPos);
    astepper.setSpeed(Motor_Speed1);
    astepper.setAcceleration(100);
  }
}
void checkStepper2_For_360(AccelStepper &astepper)
{
  if (astepper.distanceToGo() == 0)
  {
    // Random change to speed, position and acceleration
    // Make sure we dont get 0 speed or accelerations

    astepper.moveTo(targetPos);
    astepper.setMaxSpeed(Motor_Speed2);
    astepper.setAcceleration(100);
  }
}
void PatternToBeLooped_For_Cycle1()
{
  int count = 0;

  for (count == 0; count <= 5; count ++)
  {
    checkStepper1_For_DT(stepper1);
    stepper1.runSpeedToPosition();
  }

  checkStepper2_For_360(stepper2);
  stepper2.runSpeedToPosition();
}
void loop() {
    PatternToBeLooped_For_Cycle1();
  }

I ran the code, but it didn't work. Both motors are running at the same time.
Please help me. Where did I make a mistake?
Thank you in advance.

I tried with delay(1000);, but
But still both steppers are moving  at the same time and get delay at the same time.

please show the wiring diagram

May it be that they are not moving at the same time but moving one after another very fast, so that you cannot see the difference? Try putting a delay inbetween of the two stepper run statements in your looped function and see what happens

-Dir pin  to arduino gnd

-Dir pin , - pulse pin  to arduino gnd.     And + dir to arduino 3 pin  ,5pin.    And +pulse to pin 2,4

I looked into the source of the AccelStepper library here, which may be your library or one similar to it. The function runSpeedToPosition() does not block until the desired position is reached. Instead inside the function you see code that executes a step, when the right time (according to millis()), calculated through the speed, is reached, else it will return false. You are supposed to call this function very often while the motor moves. This enables you to drive more than one motor simultaneously with different speeds.
Since you don't want to drive both motors at the same time, you have to loop, until the first motor have reached the desired position; then doing the same with the second motor. Try something like this:
void PatternToBeLooped_For_Cycle1()
{
  int count = 0;
  for (count == 0; count <= 5; count ++)
  {
    checkStepper1_For_DT(stepper1);
    while(stepper1.currentPosition() != stepper1.targetPosition()) stepper1.runSpeedToPosition();
  }

  checkStepper2_For_360(stepper2);
  while(stepper2.currentPosition() != stepper2.targetPosition()) stepper2.runSpeedToPosition();
}

Note: With this change the function PatternToBeLooped_For_Cycle1() blocks the execution of the loop function, until the motors have done their movement. To avoid this you can use an if-statement, which executes the code for stepper1 or stepper2 depending on the millis() function. This works the same way as the BlinkWithoutDelay example in the Arduino IDE.


text:
How to send MFRC522 data to a C# app using a NodeMCU TCP server?
I am trying to send MFRC522 data to a C# application through a NodeMCU acting as an access point for the C# app. I have modified the code I got from this site.
#include ESP8266WiFi.h>
#include SPI.h>
#include MFRC522.h>

const char* AP_SSID ="IoT4143" ;
const char* AP_PASSWORD ="iot4143";

#define RST_PIN D3
#define SS_PIN D4

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

WiFiServer server(80);
WiFiClient client;

void wifiConnect() {
  WiFi.disconnect();
  WiFi.softAP(AP_SSID, AP_PASSWORD);

  int watchDog = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    watchDog++;
    if(watchDog == 60) {
      WiFi.disconnect();
      WiFi.printDiag(Serial);
      watchDog = 0;
      return;
    }
  }
  server.begin();
}

void setup() {
  Serial.begin(115200);
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522
  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
  wifiConnect();
}

void loop() {
  //Are we connected to WiFi?
  if(WiFi.status() != WL_CONNECTED) {
    wifiConnect();
  }

  //Wait for a connection attempt
  client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  int watchDog = 0;
  while(!client.available()) {
    delay(1);
    if(watchDog == 10000) {
      watchDog = 0;
      return;
    }
    watchDog++;
  }
  sendData();
}

void sendData() {
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  client.flush();

  // Match the request
  while(request=="READSTOP") {
    Serial.println("RFID READING STARTED..."); //Forward to C# App
    if (!mfrc522.PICC_IsNewCardPresent()) {
      return;
    }
    // Select one of the cards
    if (!mfrc522.PICC_ReadCardSerial()) {
      return;
    }
    // Dump debug info about the card; PICC_HaltA() is automatically called
    client.print(mfrc522.uid));
  }
  Serial.println("RFID READING STOPPED"); //Stop server
  delay(1);
  client.stop();
}

I am very new to hardware/network programming. I don't know what will be possible errors in this code and whether it will work or not.
When I verified the code in the Arduino IDE, there was an error on this line of code:
client.print(mfrc522.uid));

error:= no matching function for call to 'WiFiClient::print(MFRC522::Uid&)'

When the connect button in the application is clicked the "READSTART" string is sent to NodeMCU and when disconnect is clicked the "READSTOP" string is sent.
Please help!

client.print(mfrc522.uid)); How many opening and closing parentheses do you count in that line? Hmm...?

Sorry it was a typo even after i corrected that i got the same error..

MFRC522::uid is a struct (see source code). There's no defined way to print it.
If you want to write the raw bytes over the TCP connection, you can just use
client.write((uint8_t*)mfrc522.uid.uidByte, mfrc522.uid.size);

If you want to write it as ASCII text, you can use the following:
void byte_to_str(char* buff, uint8_t val) {  // convert an 8-bit byte to a string of 2 hexadecimal characters
  buff[0] = nibble_to_hex(val >> 4);
  buff[1] = nibble_to_hex(val);
}

char nibble_to_hex(uint8_t nibble) {  // convert a 4-bit nibble to a hexadecimal character
  nibble &= 0xF;
  return nibble > 9 ? nibble - 10 + 'A' : nibble + '0';
}

void printHEX(Stream &s, uint8_t *data, size_t length) {
  char *buffer = new char[length*2];
  for (size_t i = 0; i < length; i++) {
    byte_to_str(&buffer[i*2], data[i]);
  }
  s.write(buffer, length*2);
  delete[] buffer;
}

Then use it like this:
  printHEX(client, mfrc522.uid.uidByte, mfrc522.uid.size);

It loops over all bytes in the UID, converts them to ASCII (hexadecimal representation, so 2 characters per byte), and then writes the text over the TCP connection.
(Note that there are many other problems with your code as well, e.g. the includes are missing the opening '<'.)

Thank you @tttapa for your explanation, the includes missing '<' was purposly done other than that what could be the possible errors/problems you are taking abt????

In file included from \libraries\ESP8266WiFi\src/ESP8266WiFi.h:39:0,
             from \typrojectTRY1.ino:1:

src/WiFiClient.h: In instantiation of 'size_t WiFiClient::write(T&, size_t) [with T = unsigned char [10]; size_t = unsigned int]':
\typrojectTRY1.ino:103:53:   required from here
libraries\ESP8266WiFi\src/WiFiClient.h:123:36: error: request for member 'available' in 'source', which is of non-class type 'unsigned char [10]'  (part1/2)

size_t left = source.available();
\libraries\ESP8266WiFi\src/WiFiClient.h:127:5: error: request for member 'read' in 'source', which is of non-class type 'unsigned char [10]'
 source.read(buffer.get(), will_send);

Error compiling for board NodeMCU 1.0 (ESP-12E Module); part(2/2) now i am getting this error seriously i don't what it means i am a c# programmer.

@VenkateshShiga : I updated my answer. You have to cast it to a uint8_t*.

Thank you,i have done compiling there isn't any error...


text:
How to not wait for USB to become active?
EDIT: My original question was a bit "off" since the Arduino Nano I was using appeared to be faulty. This edited question is based on my other Arduino Nano which is working.
When I plug my Arduino into the PC, it keeps blinking it's LED until I open the Serial Monitor.
After opening the serial monitor the Arduino will start to execute my code.
How can I get my Arduino to "not wait on a connection", or simply put, start whenever it receives power.
I believe it's the bootloader which somehow doesn't time-out (I'm not sure if that's how the bootloader works).
The code below (though I don't see why this would make it hang until a connection):
void setup() {
  // put your setup code here, to run once:
  Serial.begin(256000);
  Serial.write("Restart");
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0) {
    incomingByte = Serial.read();

    // say what you got:
    startSend();
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
    stopSend();
  }else{
    startSend();
    Serial.println("I'm still standing");
    stopSend();
    delay(400);
  }
}

(Code is only for testing purposes)

It's likely people will need to see your code (sketch) in your question in order to help.

I've just changed board, and it seems to work a lot better. But it still seems  Arduino won't start until I open the serial monitor.

After you post your code this answer may not apply.  But, guessing, you may benefit from changing your code from:
loop()
{
 data = Serial.read();
 // Do other sutff
}

To something like this:
loop()
{
 if(Serial.available() > 1)
 {
  data = Serial.read();
 }
 // Do other stuff
}

Hmm, it appeared to be some vague hardware problem. My CH340G board runs fine, the FTDI (from China) doesn't, I think it's a fake.

And, the code won't upload while I have it connected to the MAX485, I think it might "drain the bits".


text:
Parsing Arduino Receiving Strings
I'm currently using google geolocation to get location data to one nodemcu and sending it through serial to another Arduino.
The serial command I'm getting right now is,

1.450187T103.824745

I'm using the following code to parse it.
 if (Serial.available())  {
    char c = Serial.read();  //gets one byte from serial buffer
    //if (c == '\n') {  //looks for end of data packet marker
    if (c == '\n') {
     // Serial.println(readString); //prints string to serial port out
      //do stuff
      substring = readString.substring(0,8);
      lati = substring;
      loc = readString.indexOf("T");
      substring = readString.substring(loc+1, loc+11);
     longi = substring;
       readString=""; //clears variable for new input
      substring="";

    }
    else {
      readString += c; //makes the string readString
    }
  }

It works most of the time but sometimes I get 'T' inside the string as well.
like this
lat=1.450146&longi=102464T103

What's wrong in my code?

what is the reason for transmitting the H? ... you only need the T to separate the two values

Can you show us the actual serial String, that you received in that case?

with readBytesUntil and C string
if (Serial.available()) {
  char buff[32];
  int l = Serial.readBytesUntil('\n', buff, sizeof(buff));
  if (l > 0 && buff[l - 1] == '\r') {
    l--; // to remove \r if it is there
  }
  buff[l] = 0; // terminate the string
  char* p = strchr(buff,'T'); // returns pointer in string
  if (p != NULL) {
    *p = 0; // write 0 as char at pointer to terminate the first part
    p++; // move the pointer to next char
    Serial.println(buff);
    Serial.println(p);
  } else {
    Serial.println(buff);
  }
}


text:
'Delay command' and bluetooth communication problem
I have a project where I send data to Arduino via Bluetooth using an Android application. For example, when I press 1 from the 'bar led' part of the application, an animation needs to happen. When I press 2, a different animation will be displayed. However, because there is a 'delay command' in the animations, there is a delay in data exchange when I press the button. How can I prevent this? Is there a command I can use instead of the 'Delay command'?

void loop() {
  if (bluetooth.available()) {
  while (bluetooth.available())
    {
      bar_analog = bluetooth.parseInt();
      head_analog = bluetooth.parseInt();
      bar_anim = bluetooth.parseInt();
      strip_anim = bluetooth.parseInt();
      motor_speed = bluetooth.parseInt();
      direct = bluetooth.parseInt();
      level = bluetooth.parseInt();
      if (debug) {
        Serial.print("Bar Brightness: ");
        Serial.println(bar_analog);
        Serial.print("Bar Animation Type: ");
        Serial.println(bar_anim);
        Serial.print("Headlight Brightness: ");
        Serial.println(head_analog);
        Serial.print("Strip Animation Type: ");
        Serial.println(strip_anim);
        Serial.print("Motor Speed Level: ");
        Serial.println(motor_speed);
        Serial.print("Direction: ");
        Serial.println(direct);
        Serial.print("Mast Goes: ");
        Serial.println(level);
        Serial.println("--------------------------------");
      }
      if (bluetooth.read() == '\n') {

      }
  }}
  if(bar_anim==1) {
  digitalWrite(8,HIGH);
  delay(50);
  digitalWrite(8,LOW);
  delay(250);
  }
  else if(bar_anim==2) {
  digitalWrite(8,HIGH);
  delay(250);
  digitalWrite(8,LOW);
  delay(50);
}
}

Do you mean a delay with every command that you send? Or just with one special command?

Every data I send is delayed because there is a 'delay command' in the animation part.

See the example program BlinkWithoutDelay.ino in the IDE.

I see 2 problems with your code:

You use the delay() function, which is not good coding style, since it is basically busy waiting. The Arduino will do nothing in this time, also not reacting to any input. Instead you should use a non-blocking coding style, which only does something, when it is time to do so, and will not block until something happens. You can see this style in the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses millis() as a time measure. Think of how you would bake a pizza. You would not sit on front of the oven doing nothing, until the pizza is ready. You would do other things while looking at your watch regularily, checking, if it is time to take out the pizza.
In the Serial communication part you use parseInt(). That can be a problem, since it has a timeout of 1s (standard value). Until the timeout the function will block. This is mitigated, if you consecently send a non-digit character at the end of every value. But it is better to first read a full message (until the newline character \n) and then process the message as a whole.

Also the line if (bluetooth.available()) is not necessary here, since the while loop will do the same.

Thank you for your nice answer.I tried to use the millis () command. However, I was able to turn the LED on and off with only 1 second interval.For example, I want the LED to be on for one second and off for half a second.How do I do this using millis ()?

You can use an if statement to distinguish between OFF state and ON state. Inside this if/else you put the millis() if statements with different interval values

I solved this problem, thank you.I have one last question.Is it possible to use millis () with the for loop?e.g
for (int j = 0; j <NUM_LEDS_PER_STRIP; j ++) {
fastled.setbrightness (255);
leds [j] = CRGB (100, 172, 45);
fastled.show ();
delay (100);
}
Can I use millis () instead of 'delay' here?

You should not use a for loop in this case. You have to build the functionality yourself by declaring a variable, that holds the number of the current LED. Then write a millis if statement, in which you set the color of the current LED and increment the variable to the next number.


text:
Convert Arduino MEGA Code to Arduino DUE Code?
I've been working with MEGA before. This code works completely with MEGA. I'm still at beginner level in Arduino.
Q: How do I adapt this code to DUE?
Note: I'm asking this question because I think the only problem in adaptation seems to be SoftwareSerial.

#include <SoftwareSerial.h>
SoftwareSerial bluetooth(52,53);    // TX,RX
int bar_analog=0;
int head_analog=0;
int bar_anim=0;
int strip_anim=0;
int motor_speed=1;
int direct=0;
int level=0;
boolean debug = true;
int IN1a=49;
int IN2a=48;
int PWM1=3;
int IN1b=22;
int IN2b=23;
int PWM2=4;
int hiz=100;
int PWM_kare=2;
int INA_kare = 51;
int INB_kare = 50; //LED '+'sı OUTPUT B'de olduğu için INB'yi  HIGH yapıyoruz.
void m1_cw() {
    digitalWrite(IN1a,HIGH);
    digitalWrite(IN2a,LOW);
    analogWrite(PWM1,hiz);
}
void m1_ccw() {
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,HIGH);
    analogWrite(PWM1,hiz);
}
void m2_cw() {
    digitalWrite(IN1b,HIGH);
    digitalWrite(IN2b,LOW);
    analogWrite(PWM2,hiz);
}
void m2_ccw() {
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,HIGH);
    analogWrite(PWM2,hiz);
}
void m1_stop() {
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,LOW);
    analogWrite(PWM1,0);
}
void m2_stop() {
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,LOW);
    analogWrite(PWM2,0);
}
void mast_up() {
    digitalWrite(24,HIGH);
    digitalWrite(25,LOW);
}
void mast_down() {
    digitalWrite(24,LOW);
    digitalWrite(25,HIGH);
}
void mast_stop() {
    digitalWrite(24,LOW);
    digitalWrite(25,LOW);
}
void kare() {
    analogWrite(PWM_kare,head_analog);
    digitalWrite(INB_kare, HIGH);
    digitalWrite(INA_kare, LOW);
}
void setup() {
    Serial.begin(9600);
    bluetooth.begin(9600);
    Serial.println("Program is starting...");
    Serial.println("by Berke Ogulcan Parlak");
    pinMode(IN1a,OUTPUT);
    pinMode(IN2a,OUTPUT);
    pinMode(IN1b,OUTPUT);
    pinMode(IN2b,OUTPUT);
    pinMode(PWM1,OUTPUT);
    pinMode(PWM2,OUTPUT);
    pinMode(24,OUTPUT);
    pinMode(25,OUTPUT);
    pinMode(INA_kare, OUTPUT);
    pinMode(INB_kare, OUTPUT);
    pinMode(PWM_kare, OUTPUT);
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,LOW);
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,LOW);
    digitalWrite(PWM1,LOW);
    digitalWrite(PWM2,LOW);
    digitalWrite(24,LOW);
    digitalWrite(25,LOW);
    digitalWrite(INA_kare, LOW);
    digitalWrite(INB_kare, LOW);
    digitalWrite(PWM_kare, LOW);
}

void loop() {
    if (bluetooth.available()) {
        while (bluetooth.available())
        {                                                //AppInventor'dan çektiğimiz verileri,değişkenlere atıyoruz.
            bar_analog = bluetooth.parseInt();
            head_analog = bluetooth.parseInt();
            bar_anim = bluetooth.parseInt();
            strip_anim = bluetooth.parseInt();
            motor_speed = bluetooth.parseInt();
            direct = bluetooth.parseInt();
            level = bluetooth.parseInt();
            if (debug) {                                   // Arduin seri ekranından değerleri okumak için gereklidir.
                Serial.print("Bar Brightness: ");
                Serial.println(bar_analog);
                Serial.print("Bar Animation Type: ");
                Serial.println(bar_anim);
                Serial.print("Headlight Brightness: ");
                Serial.println(head_analog);
                Serial.print("Strip Animation Type: ");
                Serial.println(strip_anim);
                Serial.print("Motor Speed Level: ");
                Serial.println(motor_speed);
                Serial.print("Direction: ");
                Serial.println(direct);
                Serial.print("Mast Goes: ");
                Serial.println(level);
                Serial.println("--------------------------------");
            }
            if (bluetooth.read() == '\n') {               //Yazdırma işlemleri bu satırda yapılacak..

            }
        }}
    if(direct==1) { //ileri
        m1_ccw();
        m2_ccw();
    }
    else if(direct==2) { //geri
        m1_cw();
        m2_cw();
    }
    else if(direct==3) { //sol
        m1_ccw();
        m2_cw();
    }
    else if(direct==4) { //sağ
        m1_cw();
        m2_ccw();
    }
    else if(direct==0) { //durur
        m1_stop();
        m2_stop();
    }
    if(level==1) { //mast yukarı
        mast_up();
    }
    else if(level==2) { //mast aşağı
        mast_down();
    }
    else if(level==0) { //mast durur
        mast_stop();
    }
    kare();            //kare LED aktif.
}

Why would you have been using SoftwareSerial on the Mega in the first place?!

You posted almost 300 lines of code with no explanation of what it does, and asked a very broad, open-ended question "how to convert." The code also only has a couple of comments, and those are not in English. You need to provide a detailed description of what your program does, what hardware it interfaces with, what I/O lines it uses, and what MEGA-specific features it uses.

You should also add detailed comments to your code, in English, so your readers can understand what it's doing. Further, you need to make an attempt to rewrite your sketch yourself, test it, and then post back asking for help with the problem you find.

SoftwareSerial is a workaround for Arduino versions without enough Hardware Serial ports, which is not the case of Arduino Mega or Arduino Uno which have 4.
Delete SoftwareSerial, replace all occurrences of bluetooth by Serial1, and rewire the Serial communication from pins 52|53 into pins 18|19 instead of (TX|RX)
Besides, the Arduino Due tends to be more "strict" than Arduino Mega compiler.
Besides that, your code will compile with no issues.
Also, remember Arduino Due is 3.3V and not 5V.


text:
Arduino Bluetooth communication is slowing down because of the 'for' loop!
I'm sending data to Arduino through the mobile app. So far, all the code has been running consistently.

#include <SoftwareSerial.h>
#define FASTLED_INTERNAL
#include <FastLED.h>
#define NUM_LEDS_PER_STRIP 48
SoftwareSerial bluetooth(53,52);    // TX,RX
int bar_analog=0;
int head_analog=0;
int bar_anim=0;
int anim=0;
int motor_speed=1;
int direct=0;
int level=0;
CRGB strip1[NUM_LEDS_PER_STRIP];
CRGB strip2[NUM_LEDS_PER_STRIP];
CRGB strip3[NUM_LEDS_PER_STRIP];
CRGB strip4[NUM_LEDS_PER_STRIP];
boolean debug = true;
int IN1a=49;
int IN2a=48;
int PWM1=3;
int IN1b=22;
int IN2b=23;
int PWM2=4;
int hiz=100;
int PWM_kare=2;
int INA_kare = 51;
int INB_kare = 50; //LED '+'sı OUTPUT B'de olduğu için INB'yi  HIGH yapıyoruz.
void m1_cw() {
digitalWrite(IN1a,HIGH);
digitalWrite(IN2a,LOW);
analogWrite(PWM1,hiz);
}
void m1_ccw() {
digitalWrite(IN1a,LOW);
digitalWrite(IN2a,HIGH);
analogWrite(PWM1,hiz);
}
void m2_cw() {
digitalWrite(IN1b,HIGH);
digitalWrite(IN2b,LOW);
analogWrite(PWM2,hiz);
}
void m2_ccw() {
digitalWrite(IN1b,LOW);
digitalWrite(IN2b,HIGH);
analogWrite(PWM2,hiz);
}
void m1_stop() {
digitalWrite(IN1a,LOW);
digitalWrite(IN2a,LOW);
analogWrite(PWM1,0);
}
void m2_stop() {
digitalWrite(IN1b,LOW);
digitalWrite(IN2b,LOW);
analogWrite(PWM2,0);
}
void mast_up() {
digitalWrite(24,HIGH);
digitalWrite(25,LOW);
}
void mast_down() {
digitalWrite(24,LOW);
digitalWrite(25,HIGH);
}
void mast_stop() {
digitalWrite(24,LOW);
digitalWrite(25,LOW);
}
void kare() {
analogWrite(PWM_kare,head_analog);
digitalWrite(INB_kare, HIGH);
digitalWrite(INA_kare, LOW);
}
void strip_dim() {
for(int i=0;i<256;i=i+10) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i); //Parlaklık
strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
strip2[j] = CRGB( 100, 172, 45);
strip3[j] = CRGB( 100, 172, 45);
strip4[j] = CRGB( 100, 172, 45);
FastLED.show();
}}
for(int i=255;i>=0;i=i-10) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i); //Parlaklık
strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
strip2[j] = CRGB( 100, 172, 45);
strip3[j] = CRGB( 100, 172, 45);
strip4[j] = CRGB( 100, 172, 45);
FastLED.show();
}}
}
void strip_stop() {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(0); //Parlaklık
strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
strip2[j] = CRGB( 100, 172, 45);
strip3[j] = CRGB( 100, 172, 45);
strip4[j] = CRGB( 100, 172, 45);
FastLED.show();
}
}
void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
  Serial.println("Program is starting...");
  Serial.println("by Berke Ogulcan Parlak");
pinMode(IN1a,OUTPUT);
pinMode(IN2a,OUTPUT);
pinMode(IN1b,OUTPUT);
pinMode(IN2b,OUTPUT);
pinMode(PWM1,OUTPUT);
pinMode(PWM2,OUTPUT);
pinMode(24,OUTPUT);
pinMode(25,OUTPUT);
pinMode(INA_kare, OUTPUT);
pinMode(INB_kare, OUTPUT);
pinMode(PWM_kare, OUTPUT);
digitalWrite(IN1a,LOW);
digitalWrite(IN2a,LOW);
digitalWrite(IN1b,LOW);
digitalWrite(IN2b,LOW);
digitalWrite(PWM1,LOW);
digitalWrite(PWM2,LOW);
digitalWrite(24,LOW);
digitalWrite(25,LOW);
digitalWrite(INA_kare, LOW);
digitalWrite(INB_kare, LOW);
digitalWrite(PWM_kare, LOW);
FastLED.addLeds<NEOPIXEL, 26>(strip1, NUM_LEDS_PER_STRIP);
FastLED.addLeds<NEOPIXEL, 28>(strip2, NUM_LEDS_PER_STRIP);
FastLED.addLeds<NEOPIXEL, 30>(strip3, NUM_LEDS_PER_STRIP);
FastLED.addLeds<NEOPIXEL, 32>(strip4, NUM_LEDS_PER_STRIP);
FastLED.setBrightness(0);
}

void loop() {
  while (bluetooth.available())
    {
      bar_analog = bluetooth.parseInt();
      head_analog = bluetooth.parseInt();
      bar_anim = bluetooth.parseInt();
      anim = bluetooth.parseInt();
      motor_speed = bluetooth.parseInt();
      direct = bluetooth.parseInt();
      level = bluetooth.parseInt();
      if (debug) {
        Serial.print("Bar Brightness: ");
        Serial.println(bar_analog);
        Serial.print("Bar Animation Type: ");
        Serial.println(bar_anim);
        Serial.print("Headlight Brightness: ");
        Serial.println(head_analog);
        Serial.print("Strip Animation Type: ");
        Serial.println(anim);
        Serial.print("Motor Speed Level: ");
        Serial.println(motor_speed);
        Serial.print("Direction: ");
        Serial.println(direct);
        Serial.print("Mast Goes: ");
        Serial.println(level);
        Serial.println("--------------------------------");
      }
      if (bluetooth.read() == '\n') {

  }}
        kare();
       if(direct==1) { //ileri
  m1_ccw();
  m2_ccw();
  }
else if(direct==2) { //geri
  m1_cw();
  m2_cw();
  }
else if(direct==3) { //sol
  m1_ccw();
  m2_cw();
  }
else if(direct==4) { //sağ
  m1_cw();
  m2_ccw();
  }
else if(direct==0) { //durur
  m1_stop();
  m2_stop();
  }
if(level==1) { //mast yukarı
  mast_up();
  }
else if(level==2) { //mast aşağı
  mast_down();
  }
else if(level==0) { //mast durur
  mast_stop();
  }
if(anim==2) {
  strip_dim();
  }
else if(anim==0) {
  strip_stop();
  }
  }

But when I added the for loop to the code, all the data started to shift. (When I press the button from the application 'lag' occurs and the data is mixed.)I mentioned that part of the code below. Why does the data shift?
void strip_dim() {
for(int i=0;i<256;i=i+10) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i); //Parlaklık
strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
strip2[j] = CRGB( 100, 172, 45);
strip3[j] = CRGB( 100, 172, 45);
strip4[j] = CRGB( 100, 172, 45);
FastLED.show();
}}
for(int i=255;i>=0;i=i-10) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i); //Parlaklık
strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
strip2[j] = CRGB( 100, 172, 45);
strip3[j] = CRGB( 100, 172, 45);
strip4[j] = CRGB( 100, 172, 45);
FastLED.show();
}}
}
void strip_stop() {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(0); //Parlaklık
strip1[j] = CRGB( 100, 172, 45); //leds[0] şeritteki 1.Ledi ifade eder. (Buradaki leds variable'dır.)
strip2[j] = CRGB( 100, 172, 45);
strip3[j] = CRGB( 100, 172, 45);
strip4[j] = CRGB( 100, 172, 45);
FastLED.show();
}
}

Why are you using software serial on a Mega?!?!

Your chief problem is that FastLED turns off interrupts when sending the data. It does that because timing is critical, and with interrupts turned on that timing will get completely messed up.
So with FastLED running repeatedly in a loop there is very little time when interrupts are enabled for reception to occur over SoftwareSerial.
Unlike a real UART, which can receive and store a byte before triggering an interrupt, SoftwareSerial triggers an interrupt to at the start of receiving a byte and that interrupt routine is used to do the actual reception. So if interrupts aren't enabled at the moment a byte starts arriving on the GPIO pin it can't start receiving, so it misses the byte and it ends up a mess.
Since you are using an Arduino Mega there is absolutely no reason for you to use SoftwareSerial. You have plenty of real hardware UARTs available to connect your Bluetooth device to which will be able to receive a byte while FastLED is sending out data (as long as it's not sending out data for too long...).

Upvoted your comment, and your answer gave rise to a question from my side related to your answer. I hope you can take a short look at it. https://arduino.stackexchange.com/questions/67381/does-dmxserial-stops-interrupts

First of all, thank you for your answer, but I don't know much about UART. What kind of change should I make in code to use UART instead of SoftwareSerial?

You are creating an instance of a class a lot of times (25 * 48 * 8 + 255 * 48 * 4 = 58,560 times), and that is a costly operation.
Instead, make one instance (before the for loops), and use that to assign everywhere you need it.
Something like;
CRGB crgb( 100, 172, 45);

for(int i=0;i<256;i=i+10) {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
        FastLED.setBrightness(i);
        strip1[j] = crgb;
        ...

Good point. However, if setBrightness is doing serial communications, >58,000 loop iterations is still going to take a substantial amount of time.

@DuncanC True, but I didn't want to change functionality.

Thanks for the comment but there hasn't been any change.


text:
Factory Pattern on Arduino
I'm looking to create a factory pattern to identify which of N objects is attached to my Serial port. Assuming each object has a unique response to the input stream "What topic is this?", How can I get my ScienceFactory class to create my Science subclasses?
EDIT 2 To clarify,

Arduino sends identification query to device.
Device responds withidentification string
Arduino receives identification string
Arduino constructs correct Science Child

Looking at various examples, I've been able to get the following skeleton code:
class ScienceFactoy
{
    public:
      enum Subject {Biology, Chemistry, Physics};
      enum Subject Topic;
      bool GetTopic();
};

bool ScienceFactoy::GetTopic()
{
    Serial.println("What Topic is this?");
    /*The Device will respond with "Biology", "Chemestry" or "Physics"
    over Serial*/

    Topic=Biology;
      /*Instead of writing the Serial.read() logic,
      let's pretend the device is a Biology device*/

    if(Topic==Biology)
    {
        //Create Biology Science Class
        return true;
    }
    if(Topic==Chemistry)
    {
        //Create Chemistry Science Class
        return true;
    }
    if(Topic==Physics)
    {
        //Create Physics Science Class
        return true;
    }
    else
    {
        return false;
    }
}

class Science
{
    public:
      enum Subject {Biology, Chemistry, Physics};
      enum Subject Topic;
      //bool takeAttendance()
      //virtual void TestStudents();
      //virtual void PopQuiz();
      virtual void Free() = 0;
};

class Biology : public Science
{
    public:
    Biology(){Serial.println("Ready For Bio");}
      //bool DissectFrogs(){}
};

class Chemistry : public Science
{
    public:
    Chemistry(){Serial.println("Ready For Chem");}
      //bool MixChemicals(){}
};

class Physics : public Science
{
    public:
    Physics(){Serial.println("Ready For Physics");}
      //bool OpticsLab(){}
};

Science ConnectedClass;

void setup() {
  Serial.begin(9600);
  ScienceFactory ClassAtSerialPort; /*(Something happens that redefines
  ClassAtSerialPort to be the correct class)*/
  /*SerialOut "Ready For Bio\n" should happen here*/
  ConnectedClass=ClassAtSerialPort;

}

void loop() {
  if(ConnectedClass.Topic==Biology){DissectFrogs();};

}

However, I don't know where to go from here as my code is Arduino specific. (Edit changed the code so to something that compiles)

this does not appear to be Arduino related .... please clarify, if the Arduino sends out "What Topic is this?" on the serial port, what device is receiving the string and acting on it in the way that you describe?

Updated for clarification the code listed is running on the Arduino which is responsible for giving appropriate commands to the Science child device

the Arduino does not have the capacity to compile code at runtime

I don't think I need to compile code at runtime, I just need to know how to read Serial to determine if I should initialize a Biology or Chem class. Everything should already be compiled.

I'm sorry I'm not making myself clear... My question is "how do I make Factory Class create an instance of  Class A or Class B based on information the Factory Class constructor receives from Serial?"

What have you tried so far to either research the Serial class or to code serial receiving? What baud rate are you using, etc.

This is not a simple solution because of the way your Factory and Science classes are structured.
Your Science class needs to hold an actual instance of itself for use when the loop wants to call the children.  This instance will be called 'device' in my example.
class Science
{
    public:
      enum Subject {Biology, Chemistry, Physics};
      enum Subject Topic;
      //bool takeAttendance()
      //virtual void TestStudents();
      //virtual void PopQuiz();
      virtual void Free() = 0;
      Science* device;
};

In your GetTopic() call you then need to instantiate the actual child class
if(Topic==Biology)
{
    //Create Biology Science Class
    device = new Biology(); // with appropriate parms
    return true;
}

Then in your setup() you have to use the class that was created
ConnectedClass=ClassAtSerialPort.device;

So in the loop() code you call call the device specific method.
void loop() {
  if(ConnectedClass.Topic==Biology){connectedClass.doScience();};

}

There is problem with your approach you might still need to resolve.  Relying on polymorphism like this is typically done by creating a common method in the parent that all the children override (ex. doScience()) and each child class does whatever is appropriate.  You can have class specific methods but then you'll likely need to cast the device to the specifc class first.


text:
How to determine hardware/software compatibility?
Currently, I'm using Greiman's SdFat Library with Adafruit's Data logging Shield.
I'm thinking about switching to the Adafruit micro SD Card Breakout. I imagine that it will work as both products are made by Adafruit, and the board schematics look similar. However, I don't know what to look at to be sure they are the same.
Is it enough that they both use the HC4050M chip, or is there something else that I need to be aware of?
Short of buying one and testing it. What do I need to look at to verify that these two boards will work with the library?

A difficult question.  Any list would only be good if it were maintained, perhaps, monthly at the slowest.  Unfortunately, the obvious solution is likely the most difficult.  That is, to analyze the chip specifications used on each board and compare that with the source code in the intended to be used libraries.  That, or the hardware is usually cheap enough that trying to see if it works is also an option.  I should add that the schematic of the board and any non-volatile configuration data (like the address of an I2C chip) should also be considered.

look at example code if it is available

Will it work in principle? I'd say it is safe to assume it will. Will it work with your code? The easiest way to answer that is to test.

The HC4050M is just used for logic level translation (SD cards are 3.3V devices). It is "enough" that you are talking to an SD card using an SD card library. The SD card is really all the hardware there is - everything else is just interfacing fluff - completely transparent to the software.


text:
CH340 3.3v stability
I want to use the 3.3v on a cheap Arduino Nano clone as my ADC analog reference voltage. The 3.3v comes from a regulator inside the CH340 USB serial chip.
I've measured the voltages (My DMM is NOT calibrated) on seven different Nanos and the voltages vary (2.96-3.38v).
I'm happy to calibrate each board to this voltage, but are there any figures available on how stable this 3.3v supply is? Long term and temperature wise?

Datasheet says?

Very little, just that it's a 3.3v LDO rated to 25mA

The internal analog voltage reference of 1.1V is better. That voltage can be 1.0 to 1.2V so you have to determine it for each board (just once). After setting the analogReference to 1.1V, you can measure the actual voltage at the aref pin: http://www.pighixxx.com/test/portfolio-items/nano/ Why do you need a reference of 3.3V? Is it for a analog sensor running at 3.3V?

I wanted to try the 3.3v as the input voltage from USB (VCC) differs on each host it's plugged into.  I'm wanting to measure an external battery voltage.  It goes through a voltage divider with high precision resistors, but if I divide it down to a max of 1.0 volts, I have to use very high precision resistors for the divider circuit.

@John see my answer; in any case your 3.3V varies not only from host to host, but also during the time. If you want a precise measure, use an external reference, otherwise you'll have to calibrate the internal one. And if you don't want to use a high reducing of the input voltage, use the trick I wrote in the answer (measure the reference and then use that measure to compensate)

Using the VCC as voltage reference is ok only if

you accept poor performances or
you need to measure a ratiometric output.

Case 2 is because the output depends on VCC (so you compensate). For instance, if you want to get the value of position in a potentiometer, you have that the voltage you see is Vo = Vcc * X (where 0<=X<=1 is the position), then the result you have on your ADC is Y = Vi / Vcc * k = X * k (where k is the maximum value of the ADC reading - e.g. 1023). So you actually compensate the Vcc deviation.
If you want to measure an absolute voltage, however (case 1) you will have a lot of uncertainties. For instance, if your current varies during the time (for instance you turn on the LED), the Vcc voltage can vary quite a lot. This is why for precise measurements you always must use a voltage reference.
In your case, you can

Use the internal reference - for the Atmega328 it is nominally 1.1V, but it can range from 1.0V to 1.2V
Use an external reference

You have to keep in mind that the voltage reference is the maximum value you can read. For instance, if you use the internal reference and then try to measure a 2.3V, you will not be able to do it (you will read the maximum value of 1.1V)
In order to fix this, you can use a trick: use Vcc as reference, and then use a voltage reference to get a precise calibration every time you need to measure something. For instance, if you have to read values from ADC1 and ADC3, you can

Read the value of the internal/external reference
Read ADC1
Read ADC3
Use the reading in point 1 to be able to guess what ADC1 and ADC3 readings were

This way you compensate for variations in the supply.
Just note that, even if the internal reference is not very precise (it has a 10% deviation from the standard value), it is indeed stable, while the VCC varies (a lot) during time. So if you have to calibrate, calibrate against the internal reference and not the Vcc.
If you can afford an external voltage reference, these are usually very stable and have very little deviation from sample to sample, so you may assume their value is "fixed"

Thanks, I don't quite understand where the voltage reference connects to - I'm pretty sure I cant connect a voltage reference up to ARef and simultaneously use VCC as the reference.
In your example did you mean to, leave ARef internally connected to VCC, connect the precise reference to ADC1 and my analog input ADC3?

@John In fact it was implicit that you have to attach the reference to another ADC channel, and treat it as another input. Then you can make the measruements relative to that one. If you use the internal reference, you have a special channel (look on the datasheet) used to read the voltage, but of course you will have to use the VCC as reference


text:
Arduino connection with Arduino
I have 3 Arduino boards, let's call them be A, B, C. I'm connecting A with a bluetooth module and I'm getting the input from the bluetooth module.
Now I want to send output from A using the digital pins and I want the output of A to be the inputs of B and C. The output sent from A will be based on voice input from the bluetooth module. The inputs of B and C will provide output signals to L293D and L298N motor drives. I have only one bluetooth module. Is this possible? Please let me know, it's urgent. I'm working on a project.

No. Simple as that

If you can connect ABC with wires, then it is easy - I use Wire library to send a lot of messages to net of many Arduinos.
Also other protocols are avaiable, like SPI, software serial, ... or if the communication is extremely easy (like just On/Off), then digitalWrite()/digitalRead() would work really easy.
I see the voice input to be more difficult in Arduino-size computers (voice recognition is not easy), but maybe you can process the voice before sending BT (on PC/tablet/phone/...) and then the BT would transfer only simple commands and it would be no problem at all.
If there is something I missed, you may write more, where you see the main problem.


text:
Using a button to cycle an array
So. I would like to cycle through an array using a button. My current code goes through if statements when the button is pushed. In each if statement I have a loop to print out a list of strings. I am curious if there is anyway to directly cycle through an array using buttons instead of this indirect route I have taken.
Last question - Is there a way to set the indents in the Arduino IDE to make formatting easier here?
//------------------------------------------------------------------------------------------------
// Displays information when a push button is pressed. Also turns on and off a corresponding led.
// 5/3/2016
//------------------------------------------------------------------------------------------------

// declare variables

char* titles[] = {
  "RELATION",
  "FIRST NAME",
  "LAST NAME",
  "LOCATION",
  "PHONE NUMBER"
};
char* user_info[] = {
  "SELF",
  "JOHN",
  "SMITH",
  "FLORIDA",
  "999-888-6666"
};
char* econ_one[] = {
  "BROTHER",
  "MICHAEL",
  "SMITH",
  "FLORIDA",
  "999-888-5555"
};
char* econ_two[] = {
  "WIFE",
  "EMILY",
  "SMITH",
  "FLORIDA",
  "999-888-4444"
};
char* econ_three[] = {
  "SISTER",
  "SOPHIA",
  "ADAMS",
  "NEW YORK",
  "888-777-3333"
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;
// setup - set pins

void setup() {
  Serial.begin(9600);
  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.println("Emergency Contact");
}

// main
void loop() {
  if (digitalRead(buttonPin)) {
    if (state == 0) {
      int x;
      for (x = 0; x <= 4; x++) {
        Serial.println(" ");
        Serial.print(titles[x]);
        Serial.print(" ");
        Serial.print(user_info[x]);
      }
      Serial.println(" ");
      setLights(HIGH, LOW, LOW, LOW);
      state = 1;
    } else if (state == 1) {
      int y;
      for (y = 0; y <= 4; y++) {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econ_one[y]);
      }
      Serial.println(" ");
      setLights(LOW, HIGH, LOW, LOW);
      state = 2;
    } else if (state == 2) {
      int z;
      for (z = 0; z <= 4; z++) {
        Serial.println(" ");
        Serial.print(titles[z]);
        Serial.print(" ");
        Serial.print(econ_two[z]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, HIGH, LOW);
      state = 3;
    } else if (state == 3) {
      int q;
      for (q = 0; q <= 4; q++) {
        Serial.println(" ");
        Serial.print(titles[q]);
        Serial.print(" ");
        Serial.print(econ_three[q]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, LOW, HIGH);
      state = 0;
    }
    delay(1000);
  }
}

// function to turn LEDs on/off

void setLights(int one, int two, int three, int four) {
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

output image
https://www.dropbox.com/sc/fwll0qe7cyye1mt/AAD5vI9buU_X0bl04KXFAQyja

The question is how do you want to cycle through the array? Also its Ctrl+T in the IDE to format the code.

Since the question is pretty old and it has some answers, if some of them fits your needs please accept it; otherwise the question will periodically show up in the homepage making possible answerer's lose a lot of time for matters you don't care anymore...

I would recommend using multidemnsional arrays for both your contacts and your light states.
//------------------------------------------------ declare variables

char* titles[] = {"RELATION", "FIRST NAME", "LAST NAME", "LOCATION", "PHONE NUMBER"};

char* econs[][5] = {
  {"SELF", "JOHN", "SMITH", "FLORIDA", "999-888-6666"},
  {"BROTHER", "MICHAEL", "SMITH", "FLORIDA", "999-888-5555"},
  {"WIFE", "EMILY", "SMITH", "FLORIDA", "999-888-4444"},
  {"SISTER", "SOPHIA", "ADAMS", "NEW YORK", "888-777-3333"}
};

uint8_t lights[][4] {   {HIGH, LOW, LOW, LOW},
  {LOW, HIGH, LOW, LOW},
  {LOW, LOW, HIGH, LOW},
  {LOW, LOW, LOW, HIGH},
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;

//------------------------------------------------ setup - set pins
void setup() {
  Serial.begin(9600);

  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);

  Serial.println("Emergency Contact");
}

//------------------------------------------------ main
void loop() {

  if (digitalRead(buttonPin))
  {
    if (state > 3)
      state = 0;

    {
      for (int y = 0; y <= 4; y++)
      {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econs[state][y]);
      }

      Serial.println(" ");
      setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
    }

    delay(1000);
    state++;

  }

}

//------------------------------------------------ function to turn LEDs on/off

void setLights(int one, int two, int three, int four)
{
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

I haven't tested the above, but it should provide the same result.
As for the second part of your question, there is an autoformat tool in the Tools menu that will auto-indent your code. Ctrl-T will do the same.

The multidimensional array is a good idea. I haven't used one before. The code you provided cycles through the array entirely with one button push. I was trying to see if I could cycle through the elements one at a time with each button press. I might try a switch-case. Thank you again for your help I really appreciate it.

I guess i misunderstood yohrnask. You could accomplish what you want to do with a counter, but stil, store the data as shown above. Instead of having the nested for loops (for x, for y), you could replace the for x with a counter that increments with each button press until it reaches 4, the cycles back to zero. It would be a simple change to the code above. When I get a chance, I can show you how to change it.

I updated the code in the answer above to cycle through the contacts with each button push.

@Prdufresne if you keep the button pressed it will cycle through all the values; moreover if you press it twice within 1 second it will not cycle twice. I'd use the bounce library to detect just the rising edge and avoid that delay; for more info see my answer

@frarugi87, I think you're right on the point of debounce. I was focused on giving him a cleaner way to cycle the records.

As for your question, your way is (kind of) the best way.
I just saw a problem: when you keep the button pressed you will go on showing. Moreover I really don't like the delay at the end, and if its purpose is just to avoid bounces, well, use the Bounce2 class.
As for the repeated ifs, I prefer a switch-case statement.
I highly suggest you to use the Bounce2 class, though. Here is an example of its usage:
Bounce debouncer = Bounce();

void setup()
{
    ...
    pinMode(buttonPin, INPUT);
    debouncer.attach(buttonPin);
    debouncer.interval(5); // interval in ms
}

void loop()
{
    debouncer.update();
    if (debouncer.rose())
    {
        switch (state)
        {
        case 0:
            {
                int x;
                for (x=0; x <= 4; x++)
                {
                    Serial.println(" ");
                    Serial.print(titles[x]);
                    Serial.print(" ");
                    Serial.print(user_info[x]);
                }
                Serial.println(" ");
                setLights(HIGH, LOW, LOW, LOW);
                state = 1;
            }
            break;
        case 1:
        ...
        }
    }
}

As you can see the class has a rose member, which tells you if the button was just pressed (only on the rising edge).
Now, your particular problem can be solved in another way. Since you are repeating the same code for all the cases, you can cycle through two arrays; one stating which is the second array you need to use, the other the lights.
This is an example. Please note that I haven't tested it, so there might be some errors
char ** second_array[] = { user_info, econ_one, econ_two, econ_three }
uint8_t lights[][4] {   {HIGH, LOW, LOW, LOW},
                        {LOW, HIGH, LOW, LOW},
                        {LOW, LOW, HIGH, LOW},
                        {LOW, LOW, LOW, HIGH},
                    }

void loop()
{
    debouncer.update();
    if (debouncer.rose())
    {
        int x;
        for (x=0; x <= 4; x++)
        {
            Serial.println(" ");
            Serial.print(titles[x]);
            Serial.print(" ");
            Serial.print(second_array[state][x]);
        }
        Serial.println(" ");
        setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
        state++;
        if (state >= 4)
            state = 0;
    }
}

Try to use it and then report back if there is some issue ;)

thank you very much, I will look at this this evening after work.


text:
Need help in connecting 64x32 LED Matrix
I recently got a 64x32 LED Matrix. However, I'm not sure how to connect it to an arduino uno. I tried following the docs here: https://cdn-learn.adafruit.com/downloads/pdf/32x16-32x32-rgb-led-matrix.pdf, but I can't get my OLED matrix to display the example.
This is my current connection so far:

(I have the R0 at the top left variant. I tried connecting it to the ESP8266 before and it works well, just that I do not know how to translate the connections to the Arduino UNO) I have a feeling that my connection is wrong since I copied the PI to PO connections from here:

and I only changed the PI to ESP8266 connections to the adafruit docs connections.
The code I am running is the example testshapes_32x64 from the RGB matrix panel library: https://github.com/adafruit/RGB-matrix-Panel/blob/master/examples/testshapes_32x64/testshapes_32x64.ino
EDIT: Since my connection for the CLK pin is connected to pin 8, I made changes in the code but it is still not working.
x-post from: https://www.reddit.com/r/arduino/comments/8qgm9x/need_help_in_connecting_a_64x32_oled_matrix_to_an/ and https://forum.arduino.cc/index.php?topic=552832.0

Why do you use connections shown on twitter? Have you tried doing all connections like described in Adafruits documentation, that you linked to? And using the same example code from there?

@chrisl that connection worked when I connected it to an ESP8266. I tried the connections and the code, but it didn't work.

@chrisl I even tried the connections from here: https://learn.sparkfun.com/tutorials/rgb-panel-hookup-guide but it isn't working

Jumping in, just wanted to make sure you @Dominic understand - just because different boards are all called Arduino does not mean the code nor electrical connections are compatible.  If you are going to use an Arduino Uno, you should start over with instructions and software specifically for an Arduino Uno.  Unless you completely understand the processor's hardware, the board's hardware and the software including the libraries.

If your matrix is the same as mine (32x64) I don't think you can drive it with a UNO. You should use a MEGA. Then follow the wiring supplied by SparkFun and make sure you connect CLK to Pin 11, NOT Pin 8.

There is NO demand for using an Arduino MEGA! If you read the documentation an Arduino UNO or eq. is sufficient.


text:
How do I free up space on arduino Yun shield?
I recently bought arduino Yun shield, and I didnt had any external USB storage connected, I downloaded get-pip.py on Yun using wget and ran python get-pip.py which resulted in 5mb storage on yun now full and even pip is not installed.
how do I free up space or reset yun shield to original , and use USB storage as default location for storing all opkg and python onto USB storage drive ?