text:
ESP8266 mqtt publish + subscribe + serial read
seems I have some issues in my code as I subscribe for specific mqtt topic and also read same value via serial and publish it to mqtt. It takes time for device connected to serial to change setting and I'am reading its state to quickly. How to optimize code that during subscribed topic value change serial read would be susspended or specific value data byte read ignored for some time.
Main code parts:
    const char* mqtt_topic_base = "panasonic_heat_pump/sdc";
    const char* mqtt_set_quiet_mode_topic =

"panasonic_heat_pump/SetQuietMode";
        byte inCheck = 0;

    #define MAXDATASIZE 256
    char data[MAXDATASIZE];
    int data_length = 0;

    // log message to sprintf to
    char log_msg[256];

    // mqtt topic to sprintf and then publish to
    char mqtt_topic[256];

    // mqtt
    WiFiClient mqtt_wifi_client;
    PubSubClient mqtt_client(mqtt_wifi_client);

    void send_command(byte* command, int length)
    {

      int bytesSent = Serial.write(command, length);
      sprintf(log_msg, "sent bytes    : %d", bytesSent); log_message(log_msg);

      // wait until the serial buffer is filled with the replies
      delay(1000);

      // read the serial
      readSerial();

      sprintf(log_msg, "received size : %d", data_length); log_message(log_msg);
    }

    // Callback function that is called when a message has been pushed to one of your topics.
    void mqtt_callback(char* topic, byte* payload, unsigned int length) {
      char msg[length + 1];
      for (int i=0; i < length; i++) {
        msg[i] = (char)payload[i];
      }
      msg[length] = '\0';
    // set 0 for Off mode, set 1 for Quiet mode 1, set 2 for Quiet mode 2, set 3 for Quiet mode 3
        if (strcmp(topic, mqtt_set_quiet_mode_topic) == 0)
         {
        String set_quiet_mode_string(msg);
        int quiet_mode = (set_quiet_mode_string.toInt() + 1) * 8;
        int checksum = 512 - (241 + 108 + 1 + 16 + quiet_mode);

        sprintf(log_msg, "set Quiet mode to %d", quiet_mode / 8 - 1); log_message(log_msg);
        byte command[] = {0xf1, 0x6c, 0x01, 0x10, 0x00, 0x00, 0x00, quiet_mode, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, checksum};
        send_command(command, sizeof(command));
         }

     if (strcmp(topic, mqtt_topic_base) == 0)
      {
        log_message("Updating..");

        update_everything();
      }
    }

    void update_everything()
    {

      get_heatpump_data();

    }

    void get_heatpump_data() {
        byte command[] = {0x71, 0x6c, 0x01, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12};
        send_command(command, sizeof(command));

        int quiet_mode_state = (int)(data[7]);

        char* quiet_mode_state_string;
        if (quiet_mode_state == 73) {
          quiet_mode_state_string = "0";
        } else if (quiet_mode_state == 81) {
          quiet_mode_state_string = "1";
        } else if (quiet_mode_state == 89) {
          quiet_mode_state_string = "2";
        } else if (quiet_mode_state == 97) {
          quiet_mode_state_string = "3";
        } else if (quiet_mode_state == 73) {
          powerfull_mode_state_string = "OFF";
        } else if (quiet_mode_state == 74) {
          powerfull_mode_state_string = "30min";
        } else if (quiet_mode_state == 75) {
          powerfull_mode_state_string = "60min";
        } else if (quiet_mode_state == 76) {
          powerfull_mode_state_string = "90min";
        } else {
          quiet_mode_state_string = "Unknown";
        }
        sprintf(log_msg, "received quiet mode state : %d (%s)", quiet_mode_state, quiet_mode_state_string); log_message(log_msg);
        sprintf(log_msg, "powerfull mode state : %d (%s)", quiet_mode_state, powerfull_mode_state_string); log_message(log_msg);

        sprintf(mqtt_topic, "%s/%s", mqtt_topic_base, "quiet_mode_state"); mqtt_client.publish(mqtt_topic, quiet_mode_state_string);
        sprintf(mqtt_topic, "%s/%s", mqtt_topic_base, "powerfull_mode_state"); mqtt_client.publish(mqtt_topic, powerfull_mode_state_string);

    }

    void loop() {
      // Handle OTA first.
      ArduinoOTA.handle();

      if (!mqtt_client.connected())
      {
        mqtt_reconnect();
      }
      mqtt_client.loop();

      update_everything();
      delay(5000);
    }

    void readSerial()
    {
        if(Serial.available() > 0){

          log_message("serial available");
        Serial.readBytes(data, 203);
        while(Serial.available()){
          delay(2);
          Serial.read();
        }

      }
    }

set the used value from the published mqtt, not from the internal value. it fires an event anyway, right? this pattern vastly simplifies reconciling values, at the slight cost of model update delay time, which often isn't strictly required anyway.

Any example how to do??


text:
NRF24L01 based project freezes for no good reason
I have built and coded a low power NRF24L01 transmitter and receiver, for purposes of transmitting the temperature of the transmitter's environment. I have used an Atmega328P chip for the project. The project itself works well, but after some time, around 10 days or so, the transmitter goes silent.
During my initial troubleshooting, I have concluded that the system hangs up during NRF transmission, and since it's stuck in the transmission phase, it eats up all the battery and dies. For this, I'm also transmitting battery usage, and I have added watchdog timers in my temperature sensing and transmission phases. This has not solved my problem, and I'm stuck as of now.
Some bits of code:
My low power cycle:
 while (1) {
  wdt_reset();  //watchdog timer added for 8S. See the beginning of loop func for timer settings.
  Serial.print("Loop Start ");
  delay(50);
    //Blink only at every wakeup
    digitalWrite(redLed, HIGH);
    setTime = millis() + ( 1 );
    while ( millis() <= setTime ) {
    }
    digitalWrite(redLed, LOW);
    //Blink only at every wakeup

    Serial.println("Powerdown begins");
      delay(50);
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
    sleepCounter++;
    Serial.println("Powerdown over");
      delay(50);
     wdt_enable(WDTO_4S);     // enable the watchdog
  //Reenabling radio for test purposes

//end of radio edit
         Serial.print("Slept for ");
         Serial.println(sleepCounter);
    if ( sleepCounter >= postPeriod || sleepCounter == -1 || interruptState == true ){       ///|| true ) {
      sleepCounter = 0;
      interruptState = false;

      break;

    }

  }

  //Serial.println(micros());
  //Serial.println("DEBUG nRf Test");

  radio.begin();
//  radio.powerUp(); //power up the nRF24

  digitalWrite(redLed, HIGH);

  Set_nRFTX_Data (1);

  nRF_Send ();

In the Set_nRFTX_Data() function, I'm writing my temperature value to the buffer, as such :
   nRF_BufferTX [23] = b1;             // 24th byte the first byte of a two-byte value for precision (msb)
    nRF_BufferTX [24] = b2;              // 25th byte the second byte of a two-byte value for precision (lsb)

And in the nRF_Send() function, I'm sending it over NRF:
void nRF_Send () {

  radio.closeReadingPipe(address);
  radio.openWritingPipe(address);
  radio.stopListening();

  bool isDataTransfer;
  radio.write(nRF_BufferTX, 32);

  radio.openReadingPipe(1, address);
  radio.startListening();
}

If anyone's interested, I may share circuit specifications as well.

is setTime unsigned long?

@Juraj Yes, I define it as unsigned long setTime = 0;

There is a known common problem with some cheap chinese clones of the nRF24L01+ whereby they get stuck in TX mode waiting for an auto-ACK that never arrives. The only way out of it is to reset the nRF24L01+ board through the power-down/up commands.

@Majenko is correct.  I have not used nRF24L01+ for a period of 10 days like the OP, but this solution fixes short-term hangups occurring after a few minutes/hours.

what is the purpose of while ( millis() <= setTime )?

@Juraj , no real purpose other than having the code halt for 1 ms.

@Majenko Hi, thanks for the valuable info, but I'm already using radio.powerDown(); in my void loop cycle for low power modes. Wouldn't this turn it on and off every cycle anyway?

source: Stack Exchange

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

sort: votes


text:
Program the Arduino Due with the ESP32
I'm trying to do OTA firmware updates for the Arduino Due with the ESP32.
Now so far I'm able to get the firmware from a website and transfer it over UART.
Now I'm looking to get the firmware and upload it to the Arduino due. My understanding is that I have to write it at 0x00080000 and from there I can write al the binary information.
The problem is that I have no idea how to:

Get the Arduino DUE in programming mode
Write to the Arduino DUE (which pins to use, what protocol...)

Can someone give me some pointers as to where to start with this? I have been reading through the documentation of the SAM3x8e, but I don't get any wiser.

reset it over reset pin (with the "double reset") to enter the bootloader. then you can do a serial upload

@Juraj I can't seem to find any documentation on this. Can you point me in the right direction?

sorry my first comment doesn't apply for Due. Here is something about reset and upload: https://www.arduino.cc/en/Guide/ArduinoDue#toc14

Thank you for that. So from what I get now is that have to open the native USB port at 1200 baud, to get it into flash programming mode (or hold the reset down). Then the only thing I have to do is to send the bytes directly to the Arduino?

https://playground.arduino.cc/Bootloader/DueBootloaderExplained/

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


text:
How to get the overall average of the data received
I have an arduino uno with two sensors. Voltage and current sensors. I need to get the average value of voltage and current each time the data is received. But i don't know how to add up the current and previous values and divide it to how many values that it has received.
Can someone help me, please? I need it for my project
This is the code i have made
void setup(){
Serial.begin(9600);
}
void loop(){
    int n=5;
    float sum=0;
    float ave=0;
    for(int x=0;x<n;x++){
        float volt=analogRead(A0);
        float voltage = map(volt,0,1023,0,2500);
        voltage/=100;
        Serial.print("Voltage: ");
        Serial.print(voltage,2);
       sum=sum+voltage;
       }
ave=sum/n;
Serial.print("Average: ");
Serial.print(average,2);
delay(3000);
}

But this only takes the average of 5 datas. I want to get the average of all data received.

Cheat: https://github.com/MajenkoLibraries/Average

it's actually communicative: (1/3 + 2/3 + 3/3) == (1+2+3)/3

@Majenko does your library offer cumulative average, running average, exponential average, or any/all of those?

To the OP, do you want a cumulative average? As mentioned in the comments on DataFiddler's answer, with a very large number of samples the average will change so slowly that it will be hard to detect a change. (e.g. After a million samples have been averaged, if the input value suddenly change to 0, it will take 100,000 new samples, all at 0, for the average value to change by 10%)

You might want to use an exponential value or other rolling average instead.

My library offers all sorts of averages and statistical analysis of the data.

void setup(){
Serial.begin(9600);
}
void loop(){
    static unsigned long count=0;
    static float sum=0;
    float ave=0;
    int volt=analogRead(A0);
    float voltage = map(volt,0,1023,0,2500) / 100.0;
    Serial.print("Voltage: ");
    Serial.print(voltage,2);
    sum=sum+voltage;
    count++;
    ave=sum/count;
    Serial.print("  Average: ");
    Serial.println(ave,2);
    delay(3000);
}

This runs quite a while. The average is restarted only with a Reset of your arduino.
Alternatively, you might want to learn about a moving average (aka low pass filter)

You println an unknown variable average.  You declared ave. You should also mention that with this method the algorithm can only run some time until float overflows. A saver way would be A(1) = x(1); A(n+1) = A(n) * (n/(n+1)) + x(n+1)/(n+1). "A(n) = avarage in the n-th iteration; x(n) the n-th sensor value."

ave fixed. It will overflow after 400 years of uninterrupted operation, thanks to delay(3000);

This code receives equal value or output for voltage and average of it. Maybe it doesn't count the previous datas it received

Did you observe the static keyword of sum? Eventually you add more Serial.println to check sum and count as well for debugging?

Oh. I got it! Thank you so much. I just put a wrong variable on the serialprint for average.

@Peter Paul Kiefer:  n/(n+1) will become 1 or overflow as well. That's not a real solution. The problem is not too realistic anyway, as after some time the average will be pretty constant.

Yes that's correct - it's not a good solution. It would be better to add a fixed number of values say the last 40, 80, or 150 ones to get a moving average. The reason for which I ask you to mention that the variable can overflow, is because the OP could possibly decrease the measurement interval and then the overflow could be a problem. I did not think about my solution so long, so I made the mistake, that the n could overflow too. So yes, my idea is not better than your way of doing it.


text:
feather 32u4 servo
I am attempting a project where I use a feather 32u4 to control a servo. It is controlled using the buttons on an attached oled featherwing to set the servo to 3 different values. The code that was provided to me produces an error for this board. After messing with similar code, it appears the statement #include <Servo.h> produces an error. There is also a note in the messages about Wire.h but that appears to not be a problem any other time.
The error messages are as follows:
Arduino: 1.6.13 (Mac OS X), Board: "Adafruit Feather 32u4"

libraries/Servo/avr/Servo.cpp.o (symbol from plugin): In function `ServoCount':
(.text+0x0): multiple definition of `__vector_17'
libraries/RadioHead-master/RH_ASK.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
Multiple libraries were found for "Wire.h"
 Used: /Users/bsd194.lab102/Library/Arduino15/packages/adafruit/hardware/avr/1.4.13/libraries/Wire
 Not used: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/Wire
exit status 1
Error compiling for board Adafruit Feather 32u4.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I would attach the code but I don't know how to post it without it appearing oddly.

The message multiple definition of __vector_17 means, that in your code the interrupt vector 17 is defined multiple times. Often this happens, because 2 used libraries use the same hardware peripherals like the timers. Only one library can configure and use the hardware. If 2 try it, you get a compiler error.
On the Atmega32u4 the interrupt with number 17 is the TIMER1 CAPT (Capture interrupt of Timer1)(see the datasheet of the Atmega32u4, chapter "Interrupts"). The error message says, that the Servo library and the RadioHead library both define this interrupt. They both try to use the hardware Timer1.
The consequence is, that you cannot simply use these two libraries together. So what to do? This can get rather difficult. You could change one of the libraries to use a different timer (the Atmega32u4 has 4 timers). This may involve extensive changes (mostly changing the register names, but sometimes more complex changes, if the new timer is not the same type). Some libraries directly provide the possibility to use a different timer, but most don't. Fortunate for you, the RadioHead library provides a simple way to change the used timer to Timer2, tough you cannot simply do this, since on the 32u4 the next 16bit Timer is Timer3. This Adafruit forum thread mentions how to set the RadioHead library for Timer2 (by uncommenting the define RH_ASK_ARDUINO_USE_TIMER2 in RH_ASK.cpp) and give a hint on how to then change to Timer3: Effectively by Changing all the 2s in the timer register and bit names to 3s. To be sure please check everytime, that the corresponding register/bit names really exist (you can see this in the register descriptions in the datasheet).


text:
How will I display values from arduino to JTextArea (Java Netbeans)?
I want to display float values in JTextArea but it doesn't show any. It only displays on the systemout. Pls help me out. This is my Java code.
import jssc.SerialPort;
import jssc.SerialPortException;

    public ards() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(319, 319, 319)
                        .addComponent(jButton1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(154, 154, 154)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(140, 140, 140)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(157, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(74, 74, 74)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(94, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
         String str;

        //In the constructor pass the name of the port with which we work
        SerialPort serialPort = new SerialPort("COM6");

        try {
            //Open port
            serialPort.openPort();

            //We expose the settings. You can also use this line - serialPort.setParams(9600, 8, 1, 0);
            serialPort.setParams(SerialPort.BAUDRATE_9600,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            Thread.sleep(1000);//Very important !!!

            //Read data from port
            for (int i = 0; i < 1000; i++) {
                str = serialPort.readString();

                if (str != null) {
                    System.out.println(str);
                   jTextArea1.setText(str);
                    jLabel2.setText(str);
                }

                Thread.sleep(500);
            }

            //Closing the port
            serialPort.closePort();

        } catch (SerialPortException ex) {
            System.out.println(ex);
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ards.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ards.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ards.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ards.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ards().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration
}

And this is my Arduino code
const int model = 0;
void setup() {
Serial.begin(9600);
}

float sensitivity[] ={
0.185, // for ACS712ELCTR-05B-T
0.100, // for ACS712ELCTR-20A-T
0.066 // for ACS712ELCTR-30A-T } ;

void loop() {
static unsigned long count=0;
static float Vsum=0;
float Vave=0;
int volt = analogRead(A1);
float voltage= map(volt,0,1023, 0, 2500)/100.0;
Vsum=Vsum+voltage;

static float Csum=0;
float Cave=0;
 float milli = pow(10, -3);
 float current = (voltage / sensitivity[model]);
 float current1 = current*milli;
Csum=Csum+current1;
count++;
Vave=Vsum/count;
Cave=Csum/count;

Serial.print("Average voltage: ");
Serial.print(Vave,2);
Serial.println("V");
Serial.print("Average current: ");
Serial.print(Cave,3);
Serial.println("A");
Serial.println("-----");
delay(3000);

}

part of the java code is properly formatted ... please format all of the code

So that means, that the data is correctly received by your java code (because you see it on systemout)? That means, that your Arduino and even your serial read java code is correct and your problem lies purely in setting the textarea. That doesn't have to do anything with Arduino.

In you code : str = serialPort.readString();
Change this as ->   str = serialPort.readStringUntil('\n');


text:
L298N Dual Motor Controller Enable Pin has power but motors not working
I am trying to get the L298N to work with a simple DC motor.
For now, I have simplified the setup and the code to the basics to try to get it to work. I am using the following wiring setup with no button or pot:
Only 1 motor, I am using a 2S lipo which I measured the voltage to be 7.8V which should be enough. The DC motor works when directly powered from the battery and when power with ~5V from an Arduino so I know it is not the issue.
My code, simplified from this tutorial: https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
#define enA 9
#define in1 6
#define in2 7

void setup() {
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  // Set initial rotation direction
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
}
void loop() {
  analogWrite(enA, 255); // Send PWM signal to L298N Enable pin
}

I can measure the voltage at the input, it is good 7.8V. No voltage on motor output pins. In1 has voltage of 3.0V and In2 has 0V which corresponds to the code. However, Enable1 has 0V which doesn't make sense. So I attached the jumper for Enable 1 to give it the 5V, measured to confirm and still the motor is not working. I also tried a 2nd L298N with the exact same setup it and does not work. So I suspect it is something in my code or setup.
I feel like I am doing something stupid but I do not know what else to check. I checked continuity on the back of the board and it seems okay.

hint: you are mising a wire between the arduino and the L298N module

Give have to apply 5V to the 5V pin. The L298N's needs power supply for its logic circuitry, so you have:
  - voltage for the motor
  - voltage for the L298N
  - signal lines

Ah yes, this fixed the problem. Maybe I interpreted the tutorial wrong but it implied that for supplying a voltage greater than 7V the onboard regulator would supply the 5V for the logic circuity. Thanks!

I though a regulator converts 12V into 5V and supply for logic, isn't it true? I confirmed 5V with a digital multi meter.

@Watanabe.N L298N is only the H-bridge IC and it does not have a voltage regulator included, so you need to provide 5V yourself. Though, there are many different L298N modules and it's possible that some of those include a voltage regulator onboard

I found this thread for a similar problem,
I realized that my scratch (taken from here) wasn't able to works..
After many and many tries, I found that:
the scratch works only using Serial Plotter, and not using Serial monitor.
In my case it was not necessary to connect 5vout of L298N with arduino,
(clearly you need to connect ground to battery supply and to arduino ground too).
I don't know why the scratch works properly (make motors turn) only by Serial Plotter and it doesn't work by Serial monitor.
I really would like to understand it!! (if someone could explain this oddity I would be very grateful).
Hope this could help.
UPDATE:
I found why it doesn't work on Serial monitor..
In the serial monitor, by using:
int inByte = Serial.read();

you must select "no line ending".
:)
it's always human error!
NOTE:
the 5V pin let to power Raspberry and this is it use.
I don't know if that solution should be risky..
In the Datasheet it's said:

A non-inductive 100nF capacitor must be connected between this pin and ground

I searched about this solution on Raspberry but, after many readings, I just don't know if this could be a safe solution to power it.
I can't suggest it as a secure way.


text:
STM32 Bluepill with Arduino IDE can not blink LEDs with a few pins
There are a couple pins such as PB4, PA15, and the ones near it where it won't allow me to blink LEDs with. They are stuck at a constant voltage, one that is around 1.5V, which is lower than minimum output. This happened on both STMs. The issue is more apparent when trying to blink LEDs inside of a big program. I don't know why this is.

what is your question? ... also, we have no way to guess what code you are running

Maybe it's not genuine STM or at least those which passed quality testing. I've got one of those and whole RTC isn't working properly. On the other side genuine nucleo boards are working like charm.

@jsotola As specified, I am just running the typical LED blink program within the Arduino IDE. My question is why this is occurring.

@KIIV How do you identify a non-genuine STM? I purchased these from AliExpress, but many people do and still use them normally. Everything works with the STM32, but making an LED blink on some pins, specifically with other loads on it, does not work. It contains a steady voltage and no alternation.

@MahmoudMaarouf I'd guess strange behaviour would be the first sign. But, maybe you've just burned those pins by some heavy load. It's capable to drive few milliamps and some pins are weaker than others. I'd check this program on the other boards first.

@KIIV Thank you for the help KIIV. However, it's similar to another STM board I own. So I believe the board is fine. Initially I thought it was because the pins weren't PWM. But I later learned that it doesn't matter.


text:
hexadecimal 1 to float 1 - Compare the float 1 with a predefined float 2 - If the float 1 and float 2 are the same - Print hexadecimal 2
I want to input a hexadecimal data from cool terminal say like (05 00 02 03 00 04 00 E5) And convert the data to a float value say 45.3. Now that I have to preassign a float value say 45.3 in my program so that I can compare the converted float value with the preassigned float value. If the two values match I need to print another hexadecimal value i.e( 05 03 00 01 00 02 04 4F).
I have managed to do the conversion of hexadecimal to float. Can someone please help me in comparing the two float values?

In what format are you sending the float over serial? ASCII encoded decimal number? ASCII encoded hexadecimal number? binary? Currently you are reading ASCII encoded decimal.

please not that you're creating a char array floatString of size 9. your index 10 is out of bounds! also there are pleny of solutions for your problem online. just enter "hex string to float" into any websearch

What exactly are you trying to achieve with all this float to hex conversion? It sounds to me like you are trying to solve a problem and you have a pre-conceived, yet incorrect, notion of how to do it. What is the actual problem you are trying to solve here?

Let me edit the question for a better understanding. Sorry for the inappropriate question.

I guess you are not talking about hexadecimal data but binary data representing a double or float64 in IEEE 754 format. To compare two arrays of 8 bytes for equality, rather use memcmp

You need to clarify your question. As @DataFiddler says, it looks like what you are inputting is the binary representation of a float in IEEE floating point format. You need to edit your question to clarify.

Comparing floating point values is notoriously difficult. This is because floating point is only an approximation.
You should first define an error margin - a value which is how close together the two values need to be before you consider them to be the same.
For example 1.000000 and 1.000001 could be considered to be the same value in many circumstances.
The simplest method is to just subtract one value from the other, take the absolute value of the result, and see if it is below the error margin.
bool almost(float a, float b, float margin) {
  float diff = fabs(a - b);
  return (diff < margin);
}

Thanks for the reply


text:
How to use H3LIS331DL 3-Axis Linear Accelerometer with arduino to detect Harsh braking of vehicle
I am a newbie here, Recently I was working with H3LIS331DL 3-Axis Linear Accelerometer I²C Mini Module
Here is code for the X, Y, Z-axis.
 #include <movingAvg.h>
 #include <Wire.h>

// H3LIS331DL I2C address is 0x18(24)
 #define Addr 0x18

       movingAvg xAxisAverage(5);

       int readingIndex=0;
       int readingArray[10];
       int firstFiveReadingAverage;
       int lastFiveReadingAverage;

    void setup()
   {

      // Initialise I2C communication as MASTER
         Wire.begin();
     // Initialise Serial Communication, set baud rate = 9600
        Serial.begin(9600);

    // Start I2C Transmission
       Wire.beginTransmission(Addr);
   // Select control register 1
      Wire.write(0x20);
  // Enable X, Y, Z axis, power on mode, data output rate 50Hz
     Wire.write(0x27);
  // Stop I2C Transmission
     Wire.endTransmission();

// Start I2C Transmission
   Wire.beginTransmission(Addr);
// Select control register 4
   Wire.write(0x23);
 // Set full scale, +/- 100g, continuous update
  Wire.write(0x00);
 // Stop I2C Transmission
  Wire.endTransmission();
  delay(300);

   }
 void loop()
 {

   unsigned int data[6];
   for(int i = 0; i < 6; i++)
  {
    // Start I2C Transmission
    Wire.beginTransmission(Addr);
    // Select data register
    Wire.write((40+i));
    // Stop I2C Transmission
    Wire.endTransmission();

    // Request 1 byte of data
     Wire.requestFrom(Addr, 1);
    // Read 6 bytes of data
    // xAccl lsb, xAccl msb, yAccl lsb, yAccl msb, zAccl lsb, zAccl msb
     if(Wire.available() == 1)
       {
       data[i] = Wire.read();
      }
    }
   delay(300);

     // Convert the data
       int xAccl = ((data[1] * 256) + data[0]);
       int yAccl = ((data[3] * 256) + data[2]);
       int zAccl = ((data[5] * 256) + data[4]);

    if(readingIndex<10)
  {
     readingArray[readingIndex]=xAccl;
     readingIndex++;
     if(readingIndex == 10)
  {
    firstFiveReadingAverage=(readingArray[0]+readingArray[1]+readingArray[2]+readingArray[3]+readingArray[4])/5;
    lastFiveReadingAverage= (readingArray[5]+readingArray[6]+readingArray[7]+readingArray[8]+readingArray[9])/5  ;
   if(lastFiveReadingAverage>firstFiveReadingAverage)
    {
     Serial.print("Hardbrake Pressed");
     Serial.println();
    }
     readingIndex=0;
    }
    }

  //int avg = avgAccl.reading(xAccl);
  // calculate the moving average

     // Output data to serial monitor
        Serial.print("Acceleration in X-Axis : ");
        Serial.println(xAccl);
        Serial.print("Acceleration in Y-Axis : ");
        Serial.println(yAccl);
        Serial.print("Acceleration in Z-Axis : ");
        Serial.println(zAccl);
        delay(300);
        Serial.println();

     int average=xAxisAverage.reading(xAccl);

    if (average < -1000)
    {
     Serial.print("Hardbraking: ");
    //Serial.print(average/100.0);
      Serial.print(average);
      Serial.println();
        }
       }

I have changed the code, but values are keeps on repeating when I trigger the hard braking and it keep on repeating even I released the brake.
Here is the output

A harsh braking is nothing more than a strong negative acceleration, so you could compare your accelaration values to a threshold. How is this connected to averaging?

Acutally, I am a newbie in arduino, can you please share me some examples.

Examples of what? Your title and your question seem totally different to me? It is unclear, what you are actually asking

how can I use this sensor to detect the harsh braking of the vehicle using Arduino nano?

A harsh braking is nothing more than a strong negative acceleration, so you could compare your accelaration values to a threshold. Let's assume, that the positive x-axis is the moving direction of your vehicle. This means, that braking will give an acceleration in the negative x direction. Then you first define a specific threshold for the acceleration. An acceleration in the negative x direction above this level means, that it is a "harsh" braking (you will have to test yourself, what value you want for this). Then you test, if the read values are below the negative of our threshold (since acceleration in the negative direction will be presented by negative number).
int braking_threshold=1000;
...
void loop(){
    ...
    // Convert the data
    int xAccl = ((data[1] * 256) + data[0]);
    int yAccl = ((data[3] * 256) + data[2]);
    int zAccl = ((data[5] * 256) + data[4]);

    if(xAccl < -1*braking_threshold){
        // Do whatever you want to do at a harsh braking here
    }
    ...
}

Note, that often the accelerometer data is rather noisy, especially, when mounted on a vehicle, that will vibrate during the motion (due to motors and such). You might need to apply some filter to the read values, before you can use them. That can be as easy as averaging some values, but can also go on to more complex filter algorithms, depending on how noise free you need the data. You will have to test, what values you realistically get in your application and how noisy they are. But data noise reduction is a complete different topic and thus off-topic for this question.
Also note, that your accelerometer measures a range of 200g. That's quite much I would say. When measuring relatively low accelerations the signal to noise ratio will be rather bad. So I hope, that you really want to measure accelerations, that fill this range, rather than only using a very small percentage of the range.

Thanks for the help, I am thinking this way only but not sure how to use. and i thinking to store the values in an array, lets say 5 values stored  and then average of those 5 values is taken and then new 5 values stored and average of those values is taken.After that we will compare the average and this thing is happening in a loop.How to write code for this?

You can google for "moving average". There is plenty of example code on the web and on this site.

Thanx for the help.

I have made this code but when pressing hard brake, then the average value keeps on repeating  itself even I have released it.

You can check the code above..

What do you mean by "keeps on repeating itself"? Please be more clear and add example output with a description, what you have done to get this output

I have uploaded the output above..


text:
Powering a MKR with regulated 3.3v
I've a low power consumption regulator to get 3.3V from two 1.5V batteries.
I'm going to use it for powering an arduino MKR (MKRFOX1200), so my question is where I should connect it, to the battery connector or directly to VCC.
Looking at schematics it's not clear to me which is the best option in terms of power saving, as VCC seems better but I don't know if it's ok to use that pin to give power

You don't really need your regulator. That board has a connection (X1) intended for directly connecting two AA batteries (according to the schematic).
However, if you want to keep it regulated at 3.3V for other reasons (the MCU will happily run from as low as about 1.62V) then sure - use your regulator.  But just treat it like batteries regardless. Connect the output of your 3.3V regulator to the battery connector, which goes via the power switching and control circuitry to the 3.3V rail of the board.

Yes I want to keep it regulated to 3.3V as sensors as DS18B20 are not happy under 3V, and for some others I need a more accurate potential and less drift than the discharging batteries. I actually have tested both modes, through X1 battery connector and through VCC, and the consumption is identical for the resolution of my multimeter (and under my specs), so I'm going to proceed with X1 battery connector. Thanks!

@avelo The only difference between connecting to VCC and to X1 is that X1 is protected against reverse powering (which could damage your batteries) when the board is connected to USB.


text:
Motor shield and Arduino Led not turning on when connected to laptop and Arduino is heating up
I have a problem like that....As I connect my Arduino to the laptop with the usb cable and the motor shield connected, my led won't turn on neither does the led on the Arduino. And the small chip like thingy beside the usb cable also heats up really bad...please help!

disconnect the motor shield

Is a motor connected?

Do you mean this component gets hot?

There's not much information to go on here. If nothing is lighting up at all there's a problem. Disconnect everything and see if the Arduino works at all.

0
You might have burned one of the onboard voltage regulators. In my case, it was AMS1117 which was burned and my Arduino was behaving similarly. You will notice that the Arduino will work with an external power supply connected to the Vin pin of Arduino and it will not become hot.

 In short, the small chip which is getting hot is a voltage regulator may be AMS1117 and you have to replace it manually or buy a new Arduino


text:
Thermal Printer - Qrcode
I am trying to print QRcode (not bitmap) on my thermal printer with Arduino and ESP32.
I am using the same QRcode library and Adafruit Thermal printer library of this post.
How to scale a bitmap (uint8_t array) in Arduino?
Is it possible to convert the pixel coordinates + color to a bitmap or print the pixel(x,y, color)?
Thanks for all

I need some code to print a QRcode. I am using this code to my oled display.
static uint8_t buffer[QR_VERSION_BUFFER_SIZE(7)] = { 0 };

QRCode qrcode = { 0 };
const int8_t error = qrcode_initText(&qrcode, buffer, 7, 0, "1245");
ASSERT_DEBUG_MODE(0 == error);

const uint8_t y0 = 10;
const uint8_t x0 = 10;

for (uint8_t y = 0; y < qrcode.size; y++)
{
    for (uint8_t x = 0; x < qrcode.size; x++)
    {
        uint8_t pixel = 0;
        if(qrcode_getModule(&qrcode, x, y) )
        {
            /*Put black pixel*/
            pixel = 0;
        }
        else
        {
            /*White pixel*/
            pixel = 1;
        }

        HI_GFX_Draw_Pixel(x0 + x, y0 + y, pixel);

    }

}

Honestly I don't understand what you mean. Please explain more and include your code. Explain, what exactly in that code is the problem

Read the README of that library in the API section. Where it uses Serial.print use whatever pixel drawing function you have.

Add the code that I am using to print the QRcode on the screen. I don't know a function for print a pixel.


text:
press button: servo move - hold X time - move back issue
Besides being a total noob I've been lurking and reading like mad over the last week to understand how to get my servo to move to X position when a button is pushed, have it wait Y time, and return to the starting position.  I've come up with this code but could use some guidance.
#include <Servo.h>

const int buttonPin = 8;
const int servoPin = 9;
int buttonState = 0;
int directionState = 0;
Servo servoOne;
int pos = 0;

void setup() {
  servoOne.attach(9);
  servoOne.write(directionState);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (directionState == 0) {
    if (buttonState == HIGH) {
      directionState = 1;
      for (pos = 0; pos < 180; pos = pos + 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  } else if (directionState == 1) {
    delay(5000); {
      directionState = 0;
      for (pos = 180; pos > 1; pos = pos - 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  }
}

Besides an unnecessary  pair of curly brackets after the delay(5000) I don't see any obvious errors. What exactly is the problem with your current code? You wrote that you need guidance, but you didn't explain with what.

You should be more precise. What do you expect your code to do and what does it instead? A state machine is probably the simplest way to implement what you need, but for a user behaving appropriately I would expect your code to work


text:
USB to Arduino to bluetooth
I have a piece of equipment that has a USB output, that a flash drive gets inserted into, to collect data as the equipment completes its cycles. I need to make a device that can replace the Flash Drive and take the data from the USB port and either save onto an SD Card, to re transmit when completed, or to transmit live as the cycles complete.
I was thinking about using a UNO, & a USB HOST Shield. to receive the data. Then transmit with a wireless or Bluetooth shield.
I have a "SANDISK WIRELSS FLASH DRIVE" which works as a flashdrive, and then you can connect it to other devices through wireless transmission, problem with it is, the wireless feature disables when plugged into the usb port. If the wireless stayed connected, then this would be exactly what I needed.
Any help or ideas, sample schematics would be welcomed.

can you mod the device? if you can make your wifi card disconnected in-situ your problem is solved.

There once was once something called an "Infinite USB Memory Drive" that acted as a thumb drive that read and wrote data to a networked share over wifi.
They aren't selling those anymore, but their approach might be what you need - network share to resolve the issue of multi- device connected to same drive.
In your shoes, I'd be looking at a Raspberry Pi Zero W (the one with wireless) instead of an arduino.  More computing options means more ways to solve your problems with the same hardware.

Your plan is flawed.
First, you don't want a USB host - a flash drive is a device, not a host. This unspecified unit that you are connecting to is the host.
Secondly you would require an Arduino a lot more complex than an Uno. You need one that is capable of operating as a USB MSD (Mass Storage Device), and the Uno or any other '328p-based device cannot do that.
The only two kinds of Arduino-like board that I know of that can do that are Teensy and chipKIT.
On top of that is a simple fact that is the reason your existing wireless flash drive doesn't work for you: only one thing can access a "block device" at once. If you had the USB and the wireless both accessing the flash drive at once you would get massive data and filesystem corruption - so it is just disabled.  You need to have some manual way of switching off one point of access and switching on the other - and of course safely "unmounting" the device to ensure that all cached data is written to the disk properly.

I appreciate to input. That gives me a better avenue to search.


text:
Can I reduce UIPEthernet library size (perhaps by ditching TCP)?
I am using the excellent UIPEthernet library to get an Arduino Nano to drive an ENC28J60 Ethernet Shield for a UDP-based application. But I think the poor library has to do a lot of work to make up for the limitations of the ENC28J60, and that makes the library large compared to the W5x00 family devices.
My sketch is starting to run out of the 32K (actually 30720 bytes) program space; I'm at 26K and I've still got functionality to add. Right now, the application is using DHCP to get the IP address, it picks up UDP discovery broadcasts from a controller PC on the LAN and then asynchronously chats to it (and only it) with UDP msgs. My uip-conf.h, condensed, looks like:
#define UIP_CONF_MAX_CONNECTIONS   0
#define UIP_CONF_MAX_LISTENPORTS   0
#define UIP_CONF_BUFFER_SIZE      98
#define UIP_CONF_TCP_MSS          64
#define UIP_CONF_RECEIVE_WINDOW  256
#define UIP_CONF_LOGGING           0
#define UIP_CONF_UDP               1
#define UIP_CONF_UDP_CONNS         2
#define UIP_CONF_UDP_CHECKSUMS     1
#define UIP_CONF_BROADCAST         1
#define UIP_CONF_STATISTICS        0

So I'm looking at ways to shave some KBs. There is much made of the fact that you can disable the library's UDP subsystem to save ~5KB (which is sort of how much I'm looking for, maybe less, though more is always nice!). And I was rather hoping I could disable TCP, but I can't see an easy way.
Are there any configurations or tricks I can play with UIPEthernet to save code space, given I'm not using TCP?
(I do have other options: switch to a W5x00 board, get a CPU with bigger memory, etc - but I want to explore this option before I revise the hardware spec).

you could use the EtherCard library

@Juraj I was wondering that - but it's quite a lot of rewriting and testing. Also, the EtherCard docs say it has no ARP cache, so it can't talk to LAN non-gateway hosts; this app is all about doing that!

now I can recommend my EthernetENC library which has a setting to disable TCP


text:
How to send data to multiple slave at a time
I have one master and three slave devices and i need to send data to all the slaves at a time.is that possible if so how to check which slave has recieved the data first

The I2C protocol implements the general call/broadcast address for this purpose. If you send data to the address 0 (zero), this is interpreted as general call by all slaves. All slaves, that can receive data, will respond by pulling the SDA line to low in the acknowledgement cycle (the timing is set up by the masters clock so all slaves will do it at the same time, thus no problem with garbled data). Note, that you cannot read from the general call address, since then all slaves might transmit at the same time. As the Atmega328Ps (the microcontroller on the Arduino Uno) datasheet states:

Note that transmitting the general call address followed by a Read bit
  is meaningless, as this would cause contention if several slaves started transmitting different data.

I think the Wire library does not do any read operations on the general call address to prevent this, so this would not block up the I2C bus.

how to check which slave has recieved the first

Not, because all slaves receive the data at the same time. The I2C bus is much like the IP protocol in this topic. A master/sender is sending out packages of data with the address of the intended target. But it is up to the slaves/receivers to decide, on which address they want to listen. So on every I2C transmission you are sending data over the bus, that could be read by all slaves. Only that in normal operation a slave will decide to only listen to the bus, when it sees it's own address (or the general call address).

In the IP protocol there is something called "broadcast address" when a packet contains this address all devices read it. You can do the same with i2c. Each slave has it's own address, but you can program them to also look for a "broadcast address" of your choosing. A single master can then send a single i2c message that will be read by all slaves at the same time.


text:
Code help in Arduino ( Serial data)
I Need a help in this code
I am trying to assign the serial.write(OutData[i]) to byte data[]. Can anyone help me assign it.
Here is my code
#define ECHOPIN 11// Pin to receive echo pulse
#define TRIGPIN 12// Pin to send trigger pulse
int distance=0;
 byte OutData[] = {0x05, 0x03, 0x04, 0x43, 0x65, 0xBA, 0x7D, 0x04, 0xE8};
#include <Crc16.h>
Crc16 crc;
void setup()\
{
  Serial.begin(9600);
 pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  digitalWrite(ECHOPIN, HIGH);
}
void loop() {
digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW); // Send pin low again
  distance = pulseIn(ECHOPIN, HIGH,26000); // Read in times pulse
  distance= distance/58;
  Serial.print(distance, HEX);
   OutData[3] = 0x00;

  OutData[4] = 0x00;

  OutData[5] = 0x41;

  OutData[6] = distance;
for (int i = 0; i <= sizeof(OutData); i++) {

    Serial.write(OutData[i]);

    byte data[] = OutData[i];
    crc.clearCrc();
  for(byte i=0;i<9;i++)
  {
     Serial.print("byte ");
     Serial.print(i);
     Serial.print(" = ");
     Serial.println(data[i]);
     crc.updateCrc(data[i]);
  }
  unsigned short value = crc.getCrc();
  Serial.print("crc = 0x");
  Serial.println(value, HEX);

  Serial.println("The crc Check of the byte array");

  //Modbus
  value = crc.Modbus(data,0,9);
  Serial.print("Modbus crc = 0x");
  Serial.println(value, HEX);

  while(true);
}
int calcrc(char *ptr, int count)
{
    int  crc;
    char i;
    crc = 0;
    while (--count >= 0)
    {
        crc = crc ^ (int) *ptr++ << 8;
        i = 8;
        do
        {
            if (crc & 0x8000)
                crc = crc << 1 ^ 0x1021;
            else
                crc = crc << 1;
        } while(--i);
    }
    return (crc);
}

My Error is :
C:\Users\system3\AppData\Local\Temp\arduino_modified_sketch_307616\sketch_dec13a.ino: In function 'void loop()':

sketch_dec13a:34:25: error: initializer fails to determine size of 'data'

     byte data[] = sizeof(OutData);

                         ^

sketch_dec13a:34:25: error: array must be initialized with a brace-enclosed initializer

sketch_dec13a:60:1: error: a function-definition is not allowed here before '{' token

 {

 ^

sketch_dec13a:77:1: error: expected '}' at end of input

 }

 ^

Multiple libraries were found for "Crc16.h"
 Used: C:\Users\system3\Documents\Arduino\libraries\Crc16-master
exit status 1
initializer fails to determine size of 'data'

I don't see any Serial.read() call in your code (and this method does not have a parameter, I think). Also you should include the complete error message, including information about the problematic line.

I am really sorry its Serial.write(). And the complete error message is initializer fails to determine size of 'data'

With complete error message I meant the complete output of the compiler or at least the complete section, where the error is described. When the compiler finds an error, it also outputs, where it found the error. That makes it easier for us to find the problem. Also sometimes the error is caused by a previous error, so the complete compiler output is the best way to include all information, that might be relevant.

I have added the additional error message which is showing now.

The following code block does not make sense:
for (int i = 0; i <= sizeof(OutData); i++) {
    Serial.write(OutData[i]);
    byte data[] = OutData[i];
    crc.clearCrc();
} // I added this bracket for you.

It is formally wrong to create an array this way. The compiler does not have any way to know, how big the array should be. I think the declaration with [] works only, when you initialize the array, but you are simply assigning 1 byte value to it. byte is not the same as array of byte. So this cannot work. To make it formally correct, you can either change data to a simple byte variable (not an array), or define the size of the array via byte data[3]; and then assigning the OutData[i] value to one of it's elements in the next line;
Above I added the closing curly bracket for you after the first for loop. It seems, that you forgot it, thus you would get more errors due to imbalanced brackets.
You are create a variable/array inside your for loop, that is not used anywhere. As soon as the current for loop iteration is finished, the variable/array is out of scope and will vanish. You have to declare it outside of the for loop (either inside the loop() function or globally), so that you can use it in the following code.
It seems, that you try to copy the data from the OutData array into the  data array to output the values in the later code and calculate the CRC value. I don't see, why you are doing this. Is there a reason, why you could not do this directly with the OutData array? I don't see the need for copying the data in an extra array.
The following line can easily be a problem:
OutData[6] = distance;

distance is defined as an int, which is a 16bit/2byte signed number. OutData is defined as an array of byte, which is a 8bit/1byte unsigned number. pulseIn() returns an unsigned long (32bit/4byte unsigned number). Since you have configured a timeout of 26000, you won't get in conflict there, but easily, when trying to assign the distance value to an element of OutData. You can get distance values up to 448, but a byte can only hold numbers between 0 and 255. So you will get an overflow and thus garbled data. You will have to send both bytes of distance to always get the full value. (You can easily google how to get the individual bytes of an int; The Arduino framework even has defines for this, lowByte and highByte, I think).

Thank you so much

@JoshEarnest If you think, that one of the answers is correct, you can mark it as the correct answer. That way others know, that this question was successfully answered and which of the answers helped you the most

byte data[] = OutData[i]; is an invalid statement.
You try to initialize an array with unknown size [] with a single element.
you must use an array to initialize an array and not a single element.
byte data[] = { 0xca, 0xfe, 0xba, 0xbe };
would initialize data with an array of four elements.

Thanks for your valuable comment


text:
ESP8266 Connection with WPA2-PEAP Enterprise Network
I am trying to connect my nodemcu 12E module to WPA2-entrprise network but not able to connect.
I had gone through the Espressif Forum and GitHub but still not able to resolve my problem.
here is the code I am using
#include<ESP8266WiFi.h>
#include<EEPROM.h>
extern "C" {
#include "user_interface.h"

#include "wpa2_enterprise.h"
#include "c_types.h"
}

// SSID to connect to
char ssid[] = "TEST";
char wlpasswd[] = "";
char username[] = "test@test.local";
char password[] = "test1234";

#define addr_username 0x0000
#define addr_password 0x007F
#define addr_certificate 0x00FF

unsigned char ca_cert[] = {
  0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49,
  0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x31, 0x37, 0x61, 0x61,
  0x31, 0x33, 0x62, 0x62, 0x37, 0x31, 0x33, 0x61, 0x37, 0x62, 0x34, 0x36, 0x66, 0x39, 0x66, 0x63,
  0x61, 0x37, 0x64, 0x62, 0x61, 0x31, 0x30, 0x32, 0x61, 0x33, 0x35, 0x63, 0x65, 0x33, 0x36, 0x38,
  0x31, 0x39, 0x31, 0x33, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45,
  0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x00,
};

void setup() {

  WiFi.mode(WIFI_STA);
  Serial.begin(115200);
  delay(1000);
  Serial.setDebugOutput(true);
  Serial.printf("SDK version: %s\n", system_get_sdk_version());
  Serial.printf("Free Heap: %4d\n",ESP.getFreeHeap());

  // Setting ESP into STATION mode only (no AP mode or dual mode)

  // Clean up to be sure no old data is still inside
  wifi_station_clear_cert_key();
  wifi_station_clear_enterprise_ca_cert();
  wifi_station_set_wpa2_enterprise_auth(1);

  wifi_station_set_enterprise_username((uint8*)username, strlen(username));
  wifi_station_set_enterprise_password((uint8*)password, strlen((char*)password));
  wifi_station_set_enterprise_ca_cert(ca_cert, sizeof(ca_cert));

  WiFi.begin(ssid);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");

    delay(100);
  }

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

void loop() {

}

Here are the logs I am getting
SDK version: 2.2.2-dev(38a443e)
Free Heap: 47672
WPA2 ENTERPRISE VERSION: [v2.0] enable
scandone
.............................scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt
...................................................................................................pm open,type:2 0
........................................................................................................................................................................................................state: 5 -> 0 (2)
rm 0
pm close 7
reconnect
.scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
.state: 3 -> 5 (10)
add 0
aid 1
cnt
...................................................................................................pm open,type:2 0
........................................................................................................................................................................................................state: 5 -> 0 (2)
rm 0
pm close 7
reconnect
.scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt
...................................................................................................pm open,type:2 0
........................................................................................................................................................................................................state: 5 -> 0 (2)
rm 0
pm close 7
reconnect
.scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt
....................................................................................................pm open,type:2 0
........................................................................................................................................................................................................state: 5 -> 0 (2)
rm 0
pm close 7
reconnect
.scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt
....................................................................................................pm open,type:2 0
........................................................................................................................................................................................................state: 5 -> 0 (2)

Any help in this?


text:
Arduino One Wire Bus DS18B20 self developed driver missing bits or extraneous bits
I recently got to code my own driver for the One-Wire-Bus specifically with the ubiquitous DS18B20 temperature sensor in mind for an application.
I am running that code on an Arduino Mega 2560. Programming is done in Atmel Studio 7 and an AVR ISP mk2.
In the version as-of yesterday see here I get missing binary digits while trying to send the 0x55 One-Wire-Command (i.e. Match-Rom-Code).
It appears like it where the least significant two bits that are missing (Oscilloscope capture).
Today I tried to sort out that bug and "fixed" it by counting to 9 instead of 8 (even though I can't explain why this should work, it should rather break stuff [turns out it does]...) and subtracting 1 from my index variable. (See file "OneWire.c" line 83 and following for the old version).
Todays version is here (compare file "OneWire.c" line 81 and following).
In the new version (as-of today) I am able to get the 0x33 opcode (i.e. Send-Rom-Command) transmitted as wanted and get the ID of my specific sensor on the bus (atleast my oscilloscope shows the correct waveform). In the newer version I do the following chain of operations:

get the ID of the single sensor I have connected at the moment
send the Match-Rom-Command (just because that is something actually meaningful to do)
send the 64-Bit Rom-Code after that (or atleast what ever the statemachine of the getID function did end up writing in the output parameter)
send the 0x44 opcode (i.e. start temperature conversion)

This scenario yields me no correct Rom-code being sent on the bus, one byte more on the bus and another single bit too much on the bus for the temperature-conversion opcode. The Match Rom Code command does get transfered as supposed to and does not yield any extraneous or missing bits (no scope capture for that since that would not be possible to get into one shot that shows it all [at a workable scaling]...).
I would highly apprechiate anyone looking at my code and trying to figure out what is going wrong here since I am completely in the dark right now.
Before anybody asks:
I specifically did not want to use the readily available One-Wire-Libraries as they tend to be bloated and heavily rely on the delay function, which is fine if you are doing little else with your chip but not else. Since I have multiple sensors to read out (not yet but as soon as I got the drivers working) have to do some post processing on the raw data (i.e. put some sort of math to it) and transmit that data on a usually slow interface (I2C, Serial, you name it), which all takes time (and all that [periodically and as fast as possible of-course] on a poor 8-Bit Micro that runs at a underwhelming 16MHz...), I decided to keep polling and delay()-uses to a minimum and rather rely (heavily?) on a timer interrupt and a series of Statemachines...
It is not at  all obvious to me why the code does act in that way.

I can't say much about your specific problem as a don't have too much experience with 1-wire. Actually, I always avoided using it, because those software implementations usually are so slow and blocking. That's why I'm curious about what you are trying to achieve. From what I know, 1-wire needs very accurate timing. I guews, one does not want anything else to happen while communication with a 1-wire device is going on. I think, reading several sensors synchronously will not be trivial

yes they are slow and blocking (due to the use of the delay function and similar bad techniques (we are talking about 500us for the reset and presence pulse together alone so roughly 7500 clock cycles at a 16MHz uC…) this is exactly what i want to circumvent by writing my own code for the job and by relying on timers where-ever possible. reading several sensors syncronously is not neccesary and not possible (if they are on the same bus else it is possible but anywhy) i plan to read them sequentially as soon as i can get at least one sensor working. The problem it self is not 1-wire-specific...

what i am exactly trying to archive is to measure a bunch of temperatures for a engine test rig. My supervisor advocated for the one wire temperature sensors and gave me the Arduino mega to have it all running on. it is planned to make the test rig a distributed System so that there is not much else going on on the uC just reading many sensors one at a time and converting the raw data to natural units and send them over to a "master"-Controller. Maybe some statistical stuff as well (mean temperature, dTemp/dTime and the like). The 7500 cycles mentioned above should be suffice for the math.

thats why i dont want to waste them. the real issue is just that the bit pattern on the bus shows more (or less) bits than what it is supposed to and from the code i can not get why it behaves that why. though i think that who ever takes a look at the code should easily see that i am somewhat proficent in writing code so its not that that is a problem...

DS18B20 is not the sensor for you, it's to slow you had to find another sensor!

@Carlmikael i have to use it. this how the Setup is no matter if you like it or dont. i have a half running Code for reading and writing the bus and an as far as i can test it with not working baselayer a working toplayer Code to read the scratchpad and thus the temperatures. provide helpful feedback or dont give any at all. btw the dynamics of temperature-related systems are low (i mean really really slow) so a slow sensor on a slow bus with a slow processor is absolutely fine

Sorry can´t help you.

I managed to find the bug and fix it.
I was missing that after the reset pulse the master must be in RX mode for atleast 480us no matter what, even if the presence pulse did occur and even if it's rising Edge did appear already. This mistiming did lead to the missing bits that were corrected with sending more bits until now (which in turn lead to the extraneous bits later on in the transmission).


text:
HELP with making code size smaller for Attiny13a
Iam making an awesome christmas present a custom pcb badge.
Everything works great with hooked up uno, but its heart is actually a Attiny13a, where I get ONLY around
1024bytes (mine code has 1944)
64bytes of variabels (I somehow managed to make few things copy on run so i barely get to it at 59 bytes)
The thing is how can I make this even smaller??
void setup() {
  pinMode(3, INPUT_PULLUP);
}

void charlie(int a[])
{

  if(a[0] < 0){

    pinMode(5, INPUT);
  }else
  {
    pinMode(5, OUTPUT);
    digitalWrite(5, a[0]);
  }
  if(a[1] < 0){

    pinMode(6, INPUT);
  }else
  {
    pinMode(6, OUTPUT);
    digitalWrite(6, a[1]);
  }
  if(a[2] < 0){

    pinMode(2, INPUT);
  }else
  {
    pinMode(2, OUTPUT);
    digitalWrite(2, a[2]);
  }
  if(a[3] < 0){

    pinMode(4, INPUT);
  }else
  {
    pinMode(4, OUTPUT);
    digitalWrite(4, a[3]);
  }
}

void copy(int* src, int* dst, int len) {
    memcpy(dst, src, sizeof(src[0])*len);
}
void resetP()
{
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}
void loop() {

  int koz1[4] = {-2,LOW,HIGH,-2};
  //int koz2[4] = {-2,HIGH,LOW,-2};

  int koz2[4];
  copy(koz1, koz2, 4);
  koz2[1] = HIGH;
  koz2[2] = LOW;

  int koz3[4] = {LOW,HIGH,-2,-2};
  //int koz4[4] = {HIGH,LOW,-2,-2};
  int koz4[4];
  copy(koz3, koz4, 4);
  koz4[0] = HIGH;
  koz4[1] = LOW;

  int koz5[4] = {LOW, -2,-2,HIGH};
  //int koz6[4] = {HIGH, -2,-2,LOW};
  int koz6[4];
  copy(koz5, koz6, 4);
  koz4[0] = HIGH;
  koz4[3] = LOW;

  int cap[4] = {-2, HIGH,-2,LOW};

  int oko1[4] = {LOW, -2,HIGH,-2};
  //int oko2[4] = {HIGH, -2,LOW,-2};

  int oko2[4];
  copy(oko1, oko2, 4);
  oko2[0] = HIGH;
  oko2[2] = LOW;

  // put your main code here, to run repeatedly:

  static long oldTime = 0;
  long Ctime = millis();
  long diffT = Ctime - oldTime;
  oldTime = Ctime;

  static bool holdButt = false;
  static long holdTime = 0;
  static long shortPressATime = 0;
  //static long longPressATime = 0;
  static bool kozichOn = true;

  //charlie(oko1);
  //charlie(oko2);

  if(digitalRead(3) == LOW)
  {
    holdButt = true;
    holdTime = holdTime + diffT;
  }
  else if (holdButt && digitalRead(3) == HIGH){
    holdButt = false;
    if(holdTime > 1000){
      //longPressATime = 5000;
      kozichOn = !kozichOn;
    }
    else
    {
      shortPressATime = 5000;
    }
    holdTime = 0;
  }

  if(shortPressATime > 0)
  {
    shortPressATime = shortPressATime - diffT;
    /*charlie(koz1);
    charlie(koz2);
    charlie(koz3);
    charlie(koz4);
    charlie(koz5);
    charlie(koz6);
    charlie(cap);
    */
    if(((round(shortPressATime/100) / 2) & 1) == 0){
      charlie(oko1);
      charlie(oko2);
      resetP();
    }
    else{

    }

  }

  /*
  else if (longPressATime > 0)
  {
    longPressATime = longPressATime - diffT;
    charlie(oko1);
    delay(5000/longPressATime);

    charlie(oko2);
    delay(5000/longPressATime);

    longPressATime = longPressATime - 5000/longPressATime;
    longPressATime = longPressATime - 5000/longPressATime;
  }*/
  else{
    if(kozichOn){
      charlie(koz1);
      charlie(koz2);
      charlie(koz3);
      charlie(koz4);
      charlie(koz5);
      charlie(koz6);
      charlie(cap);
    }
    charlie(oko1);
    charlie(oko2);
  }
  resetP();
}

EDIT: Guys you are awesome together with those on arduino forums it looks like I finally achieved it, I will try to optimize little bit more as its 1010bytes 98%. But I thank you all. You teached me in 1 hour more practical things, than I could read in a week.
void setup() {
  pinMode(3, INPUT_PULLUP);
}

void charlie(byte a[])
{

  if(a[0] == 0x0F){

    pinMode(5, INPUT);
  }else
  {
    pinMode(5, OUTPUT);
    digitalWrite(5, a[0]);
  }
  if(a[1] == 0x0F){

    pinMode(6, INPUT);
  }else
  {
    pinMode(6, OUTPUT);
    digitalWrite(6, a[1]);
  }
  if(a[2] == 0x0F){

    pinMode(2, INPUT);
  }else
  {
    pinMode(2, OUTPUT);
    digitalWrite(2, a[2]);
  }
  if(a[3] == 0x0F){

    pinMode(4, INPUT);
  }else
  {
    pinMode(4, OUTPUT);
    digitalWrite(4, a[3]);
  }
}
/*
void copy(int* src, int* dst, int len) {
    memcpy(dst, src, sizeof(src[0])*len);

}
*/
/*
void resetP()
{
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}
*/

void loop() {

  byte koz1[4] = {0x0F,LOW,HIGH,0x0F};
  //int koz2[4] = {null,HIGH,LOW,null};

  byte koz2[4];
  //copy(koz1, koz2, 4);
  memcpy(koz2, koz1, sizeof(koz1[0])*4);
  koz2[1] = HIGH;
  koz2[2] = LOW;

  byte koz3[4] = {LOW,HIGH,0x0F,0x0F};
  //int koz4[4] = {HIGH,LOW,2,2};
  byte koz4[4];
  //copy(koz3, koz4, 4);
  memcpy(koz4, koz3, sizeof(koz3[0])*4);
  koz4[0] = HIGH;
  koz4[1] = LOW;

  byte koz5[4] = {LOW, 0x0F,0x0F,HIGH};
  //int koz6[4] = {HIGH, 2,2,LOW};
  byte koz6[4];
  //copy(koz5, koz6, 4);
  memcpy(koz6, koz5, sizeof(koz5[0])*4);
  koz4[0] = HIGH;
  koz4[3] = LOW;

  byte cap[4] = {0x0F, HIGH,0x0F,LOW};

  byte oko1[4] = {LOW, 0x0F,HIGH,0x0F};
  //int oko2[4] = {HIGH, 2,LOW,2};

  byte oko2[4];
  //copy(oko1, oko2, 4);
  memcpy(oko2, oko1, sizeof(oko1[0])*4);
  oko2[0] = HIGH;
  oko2[2] = LOW;

  // put your main code here, to run repeatedly:

  static uint16_t oldTime = 0;
  uint16_t Ctime = millis();
  uint16_t diffT = Ctime - oldTime;
  oldTime = Ctime;

  static bool holdButt = false;
  static uint16_t holdTime = 0;
  static uint16_t shortPressATime = 0;
  //static long longPressATime = 0;
  static bool kozichOn = true;

  //charlie(oko1);
  //charlie(oko2);

  if(digitalRead(3) == LOW)
  {
    holdButt = true;
    holdTime = holdTime + diffT;
  }
  else if (holdButt && digitalRead(3) == HIGH){
    holdButt = false;
    if(holdTime > 1000){
      //longPressATime = 5000;
      kozichOn = !kozichOn;
    }
    else
    {
      shortPressATime = 5000;
    }
    holdTime = 0;
  }

  if(shortPressATime > 0)
  {
    shortPressATime = shortPressATime - diffT;
    if(((uint16_t(shortPressATime/128) / 2) & 1) == 0){
      charlie(oko1);
      charlie(oko2);

    }
    else{

    }

  }
  else{
    if(kozichOn){
      charlie(koz1);
      charlie(koz2);
      charlie(koz3);
      charlie(koz4);
      charlie(koz5);
      charlie(koz6);
      charlie(cap);
    }
    charlie(oko1);
    charlie(oko2);
  }
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}

what is the desired functionality?

The first thing I would try is to get rid of the Arduino core, and program instead at the avr-libc level:

use direct port access instead of digitalRead()/digitalWrite()
setup a timer and measure time in units of timer overflows instead of using millis().

Also, use int8_t for all small ints (especially in arrays), and uint16_t for time management if you don't need to handle durations larger than 65,535 time units.

Edit: Here is my attempt at translating your code to plain C +
avr-libc. Note that, as I don't know the pinout of the core you are
using (what is pin 6?), I am making one up. I also implemented Michel
Keijzers suggestion about factoring duplicated code into a function,
which I called set_pin(). Completely untested:
#include <stdbool.h>
#include <string.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>

#define INPUT 0x0f
#define LOW   0x00
#define HIGH  0x01

// Configure Timer 0 to count milliseconds, assuming F_CPU = 8 MHz.
static void init_timer() {
  OCR0A  = 125 - 1;     // period = 125*64 = 8000 CPU cycles
  TCCR0A = _BV(WGM01);  // CTC, TOP = OCR0A
  TCCR0B = _BV(CS00)    // clock @ F_CPU/64
         | _BV(CS01);   // ditto
  TIMSK0 = _BV(TOIE0);  // enable timer overflow interrupt
}

volatile uint16_t millis_counter;

// Count a millisecond on each timer overflow.
ISR(TIM0_OVF_vect) {
  ++millis_counter;
}

// Read the milliseconds counter avoiding race conditions.
static uint16_t millis() {
  uint16_t millis_counter_copy;
  ATOMIC_BLOCK(ATOMIC_FORCEON) {
    millis_counter_copy = millis_counter;
  }
  return millis_counter_copy;
}

static void setup() {
  PORTB |= _BV(PB4);  // pullup on PB4
  init_timer();
  sei();
}

// Set a pin as either INPUT, LOW or HIGH.
static void set_pin(uint8_t pin_mask, uint8_t state) {
  if (state == INPUT) {
    DDRB &= ~pin_mask;     // INPUT
    PORTB &= ~pin_mask;    // no pullup
  } else {
    if (state)
      PORTB |= pin_mask;   // HIGH
    else
      PORTB &= ~pin_mask;  // LOW
    DDRB |= pin_mask;      // OUTPUT
  }
}

static void charlie(uint8_t a[])
{
  set_pin(_BV(PB0), a[0]);
  set_pin(_BV(PB1), a[1]);
  set_pin(_BV(PB2), a[2]);
  set_pin(_BV(PB3), a[3]);
}

void loop() {

  uint8_t koz1[4] = {INPUT,LOW,HIGH,INPUT};

  uint8_t koz2[4];
  memcpy(koz2, koz1, sizeof(koz1[0])*4);
  koz2[1] = HIGH;
  koz2[2] = LOW;

  uint8_t koz3[4] = {LOW,HIGH,INPUT,INPUT};
  uint8_t koz4[4];
  memcpy(koz4, koz3, sizeof(koz3[0])*4);
  koz4[0] = HIGH;
  koz4[1] = LOW;

  uint8_t koz5[4] = {LOW, INPUT,INPUT,HIGH};
  uint8_t koz6[4];
  memcpy(koz6, koz5, sizeof(koz5[0])*4);
  koz4[0] = HIGH;
  koz4[3] = LOW;

  uint8_t cap[4] = {INPUT, HIGH,INPUT,LOW};

  uint8_t oko1[4] = {LOW, INPUT,HIGH,INPUT};
  uint8_t oko2[4];
  memcpy(oko2, oko1, sizeof(oko1[0])*4);
  oko2[0] = HIGH;
  oko2[2] = LOW;

  static uint16_t oldTime = 0;
  uint16_t Ctime = millis();
  uint16_t diffT = Ctime - oldTime;
  oldTime = Ctime;

  static bool holdButt = false;
  static uint16_t holdTime = 0;
  static uint16_t shortPressATime = 0;
  static bool kozichOn = true;

  if (bit_is_clear(PINB, PB4))
  {
    holdButt = true;
    holdTime = holdTime + diffT;
  }
  else if (holdButt && bit_is_set(PINB, PB4)){
    holdButt = false;
    if(holdTime > 1000){
      kozichOn = !kozichOn;
    }
    else
    {
      shortPressATime = 5000;
    }
    holdTime = 0;
  }

  if(shortPressATime > 0)
  {
    shortPressATime = shortPressATime - diffT;
    if(((shortPressATime/128 / 2) & 1) == 0){
      charlie(oko1);
      charlie(oko2);
    }
  }
  else{
    if(kozichOn){
      charlie(koz1);
      charlie(koz2);
      charlie(koz3);
      charlie(koz4);
      charlie(koz5);
      charlie(koz6);
      charlie(cap);
    }
    charlie(oko1);
    charlie(oko2);
  }
  DDRB &= ~(_BV(PB0) | _BV(PB1) | _BV(PB2) | _BV(PB3));
}

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

Compiling with avr-gcc 5.4.0, I get 642 bytes of flash and 31 bytes of
RAM (data + BSS, not counting the stack).

I suggest ditching the ArduinoIDE and moving to Atmel Studio. I had good experience using it with USBasp and using avrdude (supplied as a part of Arduino IDE) to upload the program to ATTiny13a directly.

Made it thank you, thank for suggestion, ive heard of it, but it seems even harder to me, like i know c# and similiar bcz of game development, but idek what atmel studio uses, but i will give it a try in some upcoming project. Again big thanks.

I will try your translation, I was prototyping with arduino so it should have been
0,1,2,4 plexing
3 - pullup button

When I compile it, I get:
Sketch uses 2630 bytes (8%) of program storage space. Maximum is 32256 bytes.
Global variables use 64 bytes (3%) of dynamic memory, leaving 1984 bytes for local variables. Maximum is 2048 bytes.

I removed all commented lines, and changed the integers to bytes (according to Edgar Bonet's answer as a start.
Than I get the code (added at end) and the following results:
Sketch uses 2432 bytes (7%) of program storage space. Maximum is 32256 bytes.
Global variables use 24 bytes (1%) of dynamic memory, leaving 2024 bytes for local variables. Maximum is 2048 bytes.

According to the specs, an AtTiny85 has 8 KB Program memory and 512 bytes SRAM, so you should be safe.
Note however, if you want to count SRAM memory (24 bytes counted by the IDE), but also you have to add:

Bytes for the calling depth of functions (e.g. loop calls copy and this calls memcpy, the total memory is for copy:  + 2 (byte*) + 2 (byte*) + 1 (byte) bytes, and for memcpy:  + dst (2) + src (2) + sizeof (1) byte. You have to check the most 'worse' call (so check the deepest invocation with all arguments added). This is all added to the so-called stack.
Also you have to add the cost of local variables (once per function), because these are also added to the stack.
If you use dynamic variables (malloc) you also have to add them, but this is not used in your sketch.

The bytes used for items 1 to 3 are not mentioned (because these are allocated at runtime).
void setup() {
  pinMode(3, INPUT_PULLUP);
}

void charlie(byte a[])
{
  if(a[0] < 0){

    pinMode(5, INPUT);
  }else
  {
    pinMode(5, OUTPUT);
    digitalWrite(5, a[0]);
  }
  if(a[1] < 0){

    pinMode(6, INPUT);
  }else
  {
    pinMode(6, OUTPUT);
    digitalWrite(6, a[1]);
  }
  if(a[2] < 0){

    pinMode(2, INPUT);
  }else
  {
    pinMode(2, OUTPUT);
    digitalWrite(2, a[2]);
  }
  if(a[3] < 0){

    pinMode(4, INPUT);
  }else
  {
    pinMode(4, OUTPUT);
    digitalWrite(4, a[3]);
  }
}

void copy(byte* src, byte* dst, byte len) {
    memcpy(dst, src, sizeof(src[0])*len);
}

void resetP()
{
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}
void loop() {

  byte koz1[4] = {-2,LOW,HIGH,-2};
  byte koz2[4];
  copy(koz1, koz2, 4);
  koz2[1] = HIGH;
  koz2[2] = LOW;

  byte koz3[4] = {LOW,HIGH,-2,-2};
  byte koz4[4];
  copy(koz3, koz4, 4);
  koz4[0] = HIGH;
  koz4[1] = LOW;

  byte koz5[4] = {LOW, -2,-2,HIGH};
  byte koz6[4];
  copy(koz5, koz6, 4);
  koz4[0] = HIGH;
  koz4[3] = LOW;

  byte cap[4] = {-2, HIGH,-2,LOW};
  byte oko1[4] = {LOW, -2,HIGH,-2};

  byte oko2[4];
  copy(oko1, oko2, 4);
  oko2[0] = HIGH;
  oko2[2] = LOW;

  static long oldTime = 0;
  long Ctime = millis();
  long diffT = Ctime - oldTime;
  oldTime = Ctime;

  static bool holdButt = false;
  static long holdTime = 0;
  static long shortPressATime = 0;
  static bool kozichOn = true;

  if(digitalRead(3) == LOW)
  {
    holdButt = true;
    holdTime = holdTime + diffT;
  }
  else if (holdButt && digitalRead(3) == HIGH){
    holdButt = false;
    if(holdTime > 1000){
      //longPressATime = 5000;
      kozichOn = !kozichOn;
    }
    else
    {
      shortPressATime = 5000;
    }
    holdTime = 0;
  }

  if(shortPressATime > 0)
  {
    shortPressATime = shortPressATime - diffT;

    if(((round(shortPressATime/100) / 2) & 1) == 0){
      charlie(oko1);
      charlie(oko2);
      resetP();
    }
    else{
    }
  }
  else{
    if(kozichOn){
      charlie(koz1);
      charlie(koz2);
      charlie(koz3);
      charlie(koz4);
      charlie(koz5);
      charlie(koz6);
      charlie(cap);
    }
    charlie(oko1);
    charlie(oko2);
  }
  resetP();
}

Iam actually using Attiny13a which has only 1024bytes, thru using some help from arduino forum i got to great 1218bytes which is super close to the goal, I will now try to implement this.
EDIT: With your improvement Iam at 1074bytes super close.

So you need to reduce the code size (Flash), not SRAM? These are two different things.

Sorry but iam back at the problem I need to diffirentiate 3 values and when I use bytes I need to change the function so it ifs(==2) but then Iam back at 1246

Not sure what you say (also you didn't give an answer I think) ... You could copy the duplicated code to a single function and call it with parameters, that saves you some Flash space.

Made it. Thank you

You're welcome ... if you think the answer is useful, upvote it (press the up-arrow next to the question); if you think the answers solved your problem, also accept it (press the check sign next to the answer). Good luck with your project.

@eternaldownvoter: please write what can be improved.


text:
How to obtain the type of DHT sensor
I made a simple temperature controller on DHT11.
I want it to work with DHT22 as well having the same code.
However, I can’t find a way how to get known what type of sensor is installed.
Is there a way?

internet search reveals that DHT11  needs 1 second between readings ... DHT22 needs 2 seconds between readings  .... run tests .... see what happens if you try to read each of the sensors at 1.2 second intervals

You can use another library for DHT: https://github.com/markruys/arduino-DHT
Although, the library is quite old, it works fine and has auto-detection feature.

Wow, I'll try this library. Thanks!

I don't think that is possible.
What you should do is pass the type (DHT11 or DHT12) to the code, store it and change calculations (or functions) accordingly.
If you use a class, you can pass it as argument of the constructor, so the user of the library only need to set it up once (in the constructor where it belongs). Make it an enumeration, copy it into a class variable and all methods inside your class can use the type.
Something like (not checked):
MyDht.hpp:
class MyDht
{
public:
    enum EType { DHT11, DHT12 };

    public MyDht(EType type);

private:
    EType _type;
}

Dht.cpp:
MyDht::MyDht(EType type)
{
    _type = type;
}

And you create the class by:
MyDht sensor1(MyDht::DHT11);
MyDht sensor2(Mydht::DHT12);

Actually it is possible. If DHT type is wrong, I get empty results. Then I try another type and the results are correct.

Ok, than use your method in case you don't know, and use mine if you want to do it programmatically... Actually, you could combine both solutions by creating (dynamically) the correct type after your 'one time check', Create a pointer to MyDht, and create either a DHT11 or DHT12 instance.


text:
ESP8266 Webserver ESP8266WebServer move Handler-Function in separate .h .c file
The plan is to create a bigger project and to split the ESP8266 webserver-code over several modules (.h .c files). The main problem is that the ESP8266WebServer server is not declared in the index.h and index.c files.
What I've been trying to do:
Content main.c
#include <ESP8266WiFi.h>
#include "ESP8266WebServer.h"
#include "index.h"

ESP8266WebServer server(80);
const char* ssid =     "test";
const char* password = "12345678";

void setup()
{
  WiFi.softAP(ssid, password);
  server.on("/", handleRoot(server));           // <-- use of deleted function 'esp8266webserver::ESP8266WebServerTemplate<WiFiServer>::ESP8266WebServerTemplate(const esp8266webserver::ESP8266WebServerTemplate<WiFiServer>&)'
  server.begin();
}

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

Content index.h:
void handleRoot(ESP8266WebServer server);

const char htmlIndex[] PROGMEM = R"=====(

    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>

Hello World!

)=====";

Content index.c:
#include "webpages/index.h"

void handleRoot(ESP8266WebServer server)
{
  Serial.println("GET /");
  server.send(200, "text/html", htmlIndex);
}

How can I use the ESP8266WebServer server created in the main.c in index.c?

Move the webserver to index.c and include the webserver type:
ESP8266WebServer server(80);

Add an external reference in index.h and include it:
#include "ESP8266WebServer.h"

extern ESP8266WebServer server;

Index.h is included by both main.c and index.c so it will know about server being an ESP8266WebServer type, but does not allocate memory for it; that is done in index.c
This is called a forward reference.

I shifted
#include "ESP8266WebServer.h" extern ESP8266WebServer server; to main.h and included it in index.c but in the end it is your idea. thx.

Yes, in principle it does not matter where you place the external variable, as long as it is not in a header file (or at least not one that is included twice). Good luck with your project.


text:
ESP32 Hardware Serial Flow control and full espressif/arduino-esp32 support
I have a similar issue. I want to use the ESP32 with RS485.
I have used the Arduino  and this works well assigning pins, but it seems not to allow full use of the UART.
I see the new uarts in the ESP32 can support the direction control (RTS) of the direction pin and there is actually a hardware RS485 mode.
See the repository that the board package is based on:
https://github.com/espressif/arduino-esp32
Then
https://github.com/espressif/arduino-esp32/tree/master/tools/sdk/include/driver/driver
uart.h
This shows we can actually have full hardware flow control, so no more guessing delays for controlling the DIR lines or getting interrupts when the send buffer is empty in order to know when to switch back to receive.
I found using board manager this did not all get installed, so I followed some tutorials on how to install it manually.
The board either doesn't appear at all, or I can't reference "uart.h".
Any ideas or examples?
Thanks,
Mark

I've got no problem simply including driver/uart.h and copy-paste code from the official RS485 example (https://github.com/espressif/esp-idf/blob/master/examples/peripherals/uart/uart_echo_rs485/main/rs485_example.c). See my example at https://pastebin.com/2PtWJvd6. What is your exact error message?

Also the documentation at https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/uart.html#overview-of-rs485-specific-communication-options and the example docs https://github.com/espressif/esp-idf/tree/master/examples/peripherals/uart/uart_echo_rs485 apply here.

Why would you guys delays for the dir line? Just flush() after sending any data.

your example was of great help solving the problem of driving RTS properly, thanks a lot!
I found a small bug in the code example, the data buffer is allocated in the loop() function instead of setup() and as a result, eventually the memory leak will fill-up all available memory.
Ciao!
Alessandro

Espressif and Arduino use the same UART numbering, and there are no hidden properties of hardwareSerial that are bound to it UART instance So it's possible to perform a reach-around and replace the arduino harwareSerial UART driver instance with an espressif RS485 uart instance and then use Arduinos hardwareSerial methods to communicate with the UART.
#include <Arduino.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <driver/uart.h>

#define ECHO_UART_PORT UART_NUM_1
#define ECHO_TEST_TXD   (25)
#define ECHO_TEST_RXD   (26)
#define ECHO_TEST_RTS   (27)
#define ECHO_TEST_CTS  UART_PIN_NO_CHANGE
#define BUF_SIZE        (127)
#define BAUD_RATE       (9600)

#if   ECHO_UART_PORT == UART_NUM_0
#define         SERIAL_485 Serial
#error  Serial is already committed elsewhere in this code

#elif ECHO_UART_PORT == UART_NUM_1
#define         SERIAL_485 Serial1

#elif ECHO_UART_PORT == UART_NUM_2
#define         SERIAL_485 Serial2
#endif

static const char *TAG = "RS485_ECHO_APP";

void setup() {
    Serial.begin(115200); //uses UART_NUM_0
    //configure UART_NUM_2 for RS485
    const uart_port_t uart_num = ECHO_UART_PORT;
    uart_config_t uart_config = {
        .baud_rate = BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .rx_flow_ctrl_thresh = 122,
    };

    Serial.println("Start RS485 application test and configure UART.");

    // start arduino serial port
    SERIAL_485.begin(BAUD_RATE);
    SERIAL_485.setTimeout(1+(10000/BAUD_RATE) ); // 10000 is 10 symbols per byte * 1000 ms per second

    // drop rhe Arduino installed UART driver!
    // we will replace this with a 485 capable driver.
    uart_driver_delete(uart_num);

    // Configure UART parameters
    uart_param_config(uart_num, &uart_config);

    Serial.println("UART set pins, mode and install driver.");
    // Set UART1 pins(TX: IO23, RX: I022, RTS: IO18, CTS: IO19)
    uart_set_pin(uart_num, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS);

    // Install UART driver (we don't need an event queue here)
    // In this example we don't even use a buffer for sending data.
    uart_driver_install(uart_num, BUF_SIZE * 2, 0, 0, NULL, 0);

    // Set RS485 half duplex mode
    uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX);

    ESP_LOGI(TAG, "UART start recieve loop.\r\n");
    SERIAL_485.printf("Start RS485 UART test.\r\n");
}


text:
Get value from protected member of class
i'm really new to Arduino.
I have Arduino Mega, a USB host shield and a barcode scanner. I'm using this library >> link and modified it example so barcode scanner worked (Got it from here) to read what barcode scanner scanned and it worked just fine.
#include <usbhid.h>
#include <usbhub.h>
#include <hiduniversal.h>
#include <hidboot.h>
#include <SPI.h>

class MyParser : public HIDReportParser {
  public:
    MyParser();
    void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
    uint8_t getValue();
  protected:
    uint8_t KeyToAscii(bool upper, uint8_t mod, uint8_t key);
    virtual void OnKeyScanned(bool upper, uint8_t mod, uint8_t key);
    virtual void OnScanFinished();
};

MyParser::MyParser() {}

void MyParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
  // If error or empty, return
  if (buf[2] == 1 || buf[2] == 0) return;

  for (uint8_t i = 7; i >= 2; i--) {
    // If empty, skip
    if (buf[i] == 0) continue;

    // If enter signal emitted, scan finished
    if (buf[i] == UHS_HID_BOOT_KEY_ENTER) {
      OnScanFinished();
    }

    // If not, continue normally
    else {
      // If bit position not in 2, it's uppercase words
      OnKeyScanned(i > 2, buf, buf[i]);
    }

    return;
  }
}

uint8_t MyParser::getValue() {
  uint8_t getAscii;
  bool upper; uint8_t mod; uint8_t key;
  getAscii = KeyToAscii(upper, mod, key);
  return getAscii;
}

uint8_t MyParser::KeyToAscii(bool upper, uint8_t mod, uint8_t key) {
  // Letters
  if (VALUE_WITHIN(key, 0x04, 0x1d)) {
    if (upper) return (key - 4 + 'A');
    else return (key - 4 + 'a');
  }

  // Numbers
  else if (VALUE_WITHIN(key, 0x1e, 0x27)) {
    return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1');
  }

  return 0;
}

void MyParser::OnKeyScanned(bool upper, uint8_t mod, uint8_t key) {
  uint8_t ascii = KeyToAscii(upper, mod, key);
  Serial.print((char)ascii);
}

void MyParser::OnScanFinished() {
  Serial.println(" - Finished");
}

USB          Usb;
USBHub       Hub(&Usb);
HIDUniversal Hid(&Usb);
MyParser     Parser;

void setup() {
  Serial.begin( 115200 );
  Serial.println("Start");

  if (Usb.Init() == -1) {
    Serial.println("OSC did not start.");
  }

  delay( 200 );

  Hid.SetReportParser(0, &Parser);
}

void loop() {
  Usb.Task();
}

So, I want to get the value from (char)ascii, store to char on loop and run it.
void MyParser::OnKeyScanned(bool upper, uint8_t mod, uint8_t key) {
  uint8_t ascii = KeyToAscii(upper, mod, key);
  Serial.print((char)ascii);
}

I tried created function that return the value but still no luck.
uint8_t MyParser::getValue() {
  uint8_t getAscii;
  bool upper; uint8_t mod; uint8_t key;
  getAscii = KeyToAscii(upper, mod, key);
  return getAscii;
}

Called it on loop:
void loop() {
  Usb.Task();
  uint8_t abcd = Parser.getValue();
  char c = (char)abcd;
  Serial.print(c);
}

What am I missing? Thank you.

Upper mod and key have no defined value in getValue.

I don't understamd, what the problem is or what you are trying to achieve. Is your KeyToAscii function not working properly? If so, how is it not working?