body:
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.

title: feather 32u4 servo

Answers: 1

body:
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][1] 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][2] 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 `2`s in the timer register and bit names to `3`s. 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).

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf
  [2]: https://forums.adafruit.com/viewtopic.php?t=118972


body:
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);

    }

title: How will I display values from arduino to JTextArea (Java Netbeans)?

Answers: 1

body:
In you code : str = serialPort.readString();

Change this as ->   str = serialPort.readStringUntil('\n');


body:
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: [![enter image description here][1]][1]

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

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.

title: L298N Dual Motor Controller Enable Pin has power but motors not working

Answers: 2

body:
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

body:
I found this thread for a similar problem,
I realized that my scratch (taken from [here][1]) 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.

  [1]: https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/

**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.


body: 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.

title: STM32 Bluepill with Arduino IDE can not blink LEDs with a few pins

Answers: 0


body:
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?

title: 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

Answers: 1

body:
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);
    }


body:
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
[![enter image description here][1]][1]

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

title: How to use H3LIS331DL 3-Axis Linear Accelerometer with arduino to detect Harsh braking of vehicle

Answers: 1

body:
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.


body:
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][1] 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

  [1]: https://www.arduino.cc/en/uploads/Main/MKRFox1200-schematic.pdf

title: Powering a MKR with regulated 3.3v

Answers: 1

body:
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.


body: 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!

title: Motor shield and Arduino Led not turning on when connected to laptop and Arduino is heating up

Answers: 1

body:
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


body:
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.

https://arduino.stackexchange.com/questions/68168/how-to-scale-a-bitmap-uint8-t-array-in-arduino/70918#70918

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);

        }

    }

title: Thermal Printer - Qrcode

Answers: 0


body:
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);
      }
    }
  }
}

title: press button: servo move - hold X time - move back issue

Answers: 0


body:
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.

title: USB to Arduino to bluetooth

Answers: 2

body:
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.

body:
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.


body:
I am using the excellent [UIPEthernet library][1] 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).

  [1]: https://github.com/UIPEthernet/UIPEthernet

title: Can I reduce UIPEthernet library size (perhaps by ditching TCP)?

Answers: 0


body: 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

title: How to send data to multiple slave at a time

Answers: 2

body:
In the IP protocol there is something called "[broadcast address][1]" 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.

  [1]: https://en.wikipedia.org/wiki/Broadcast_address

body:
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 `Atmega328P`s (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).


body:
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'

title: Code help in Arduino ( Serial data)

Answers: 2

body:
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.

1. 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;

2. 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.

3. 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.

4. 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.

5. 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).

body:
`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.


body:
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: M\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?

title: ESP8266 Connection with WPA2-PEAP Enterprise Network

Answers: 0


body:
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][1] 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][2]).

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][3] (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.

  [1]: https://drive.google.com/open?id=1DzAtSFzGCcYntuK9mDvueiU4d1gAdTm8
  [2]: https://drive.google.com/open?id=1Afgj0XxU1DHjGEjxiTrjzezUcgv_W72o
  [3]: https://drive.google.com/open?id=1SWR2M671Ggv3elFdZxjRejziJwpBcRU-

title: Arduino One Wire Bus DS18B20 self developed driver missing bits or extraneous bits

Answers: 1

body:
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).


body:
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);
    }

title: HELP with making code size smaller for Attiny13a

Answers: 2

body:
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.

[avr-libc]: https://www.nongnu.org/avr-libc/user-manual/index.html

------------------------------------------------------------------------

**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:

```c
#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).

body:
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:

1. Bytes for the calling depth of functions (e.g. `loop` calls `copy` and this calls `memcpy`, the total memory is for `copy`: <some overhead> + 2 (byte*) + 2 (byte*) + 1 (byte) bytes, and for memcpy: <some overhead> + 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.
2. Also you have to add the cost of local variables (once per function), because these are also added to the stack.
3. 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();
    }


body:
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?

title: How to obtain the type of DHT sensor

Answers: 2

body:
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);

body:
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.


body:
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?

title: ESP8266 Webserver ESP8266WebServer move Handler-Function in separate .h .c file

Answers: 1

body:
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.


body:
I have a similar issue. I want to use the ESP32 with RS485.
I have used the Arduino <HardwareSerial.h> 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

title: ESP32 Hardware Serial Flow control and full espressif/arduino-esp32 support

Answers: 2

body:
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

body:
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");
    }


body:
i'm really new to Arduino.
I have Arduino Mega, a USB host shield and a barcode scanner. I'm using this library >> [link][1] and modified it example so barcode scanner worked (Got it from [here][2]) 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.

  [1]: https://github.com/felis/USB_Host_Shield_2.0
  [2]: https://github.com/felis/USB_Host_Shield_2.0/issues/323

title: Get value from protected member of class

Answers: 0


body:
We're supposed to create a Simon Says game for our final. My professor is telling me I shouldn't need to modify much with what I already have. but I'm so confused because it feels like starting over.
The way I have the Simon Says game now, it generates random numbers for each round but increments by one as the rounds increase. I need it to instead repeat the same sequence as the last and add a new random LED and so forth. Why is it so hard? What am I missing?
this is Arduino BTW

        int ledArray[10];
    int buttonArray[10];
    int loopCounter;
    int ledCounter;
    int inputCounter;
    int game;
    int waiting;
    int pass;
    int wait;
    int timeUp;
    int levelCounter[10];

    //ALL THE BUTTONS & LEDS ARE GIVEN NAMES HERE SO THEY'RE EASIER TO REFERENCE
    const int buttonRed = 6;
    const int buttonYellow = 7;
    const int buttonGreen = 9;
    const int buttonBlue = 8;
    const int r = 2;
    const int y = 3;
    const int b = 4;
    const int g = 5;
    const int x = 10;//LED ON PIN 10 IS THE WHITE LED USED FOR PROMPTS

    ///USED FOR PROCESSING AND COMPARING INPUTS
    int randNumber;
    int array_Cmp;

    void youWin ()
    { digitalWrite(2, HIGH);
      delay(100);
      digitalWrite(2, LOW);
      delay(100);
      digitalWrite(3, HIGH);
      delay(100);
      digitalWrite(3, LOW);
      delay(100);
      digitalWrite(4, HIGH);
      delay(100);
      digitalWrite(4, LOW);
      delay(100);
      digitalWrite(5, HIGH);
      delay(100);
      digitalWrite(5, LOW);
      delay(100);
    }

    void ledPrompt()
    //prompts player for inout during game after
    //the LEDs have been picked randomly each round
    { digitalWrite(x, HIGH);
      delay(1000);
      digitalWrite(x, LOW);
      delay(50);
    }

    void gameHasStarted()
    //LED prompt after first button
    //is pushed to start the game
    {
      digitalWrite(10, HIGH);
      delay(1000);
      digitalWrite(10, LOW);
      delay(100);
    }

    void fail() //LED sequence when the wrong input is entered
    { digitalWrite(2, HIGH);
      delay(1000);
      digitalWrite(3, HIGH);
      delay(1000);
      digitalWrite(4, HIGH);
      delay(1000);
      digitalWrite(5, HIGH);
      delay(1000);
      digitalWrite(2, LOW);
      delay(50);
      digitalWrite(3, LOW);
      delay(50);
      digitalWrite(4, LOW);
      delay(50);
      digitalWrite(5, LOW);
      delay(50);
    }

    void waitToStart() //cycles through LEDs while waiting to start the game
    { digitalWrite(2, HIGH);
      delay(250);
      digitalWrite(2, LOW);
      delay(250);
      digitalWrite(3, HIGH);
      delay(250);
      digitalWrite(3, LOW);
      delay(250);
      digitalWrite(4, HIGH);
      delay(250);
      digitalWrite(4, LOW);
      delay(250);
      digitalWrite(5, HIGH);
      delay(250);
      digitalWrite(5, LOW);
      delay(250);
    }

    int initiate()//FUNCTION WAITS FOR ANY OF 4 BUTTONS TO BE PUSHED TO START THE GAME
    { game = 0;
      waiting = 0;
      loopCounter = 1;
      randNumber = 0;
      ledCounter = 0;
      inputCounter = 0;
      pass = 2;
      //FUNCTION INCLUDES ALL OF THE ASSUMPTIONS NEEDED TO EXECUTE THE 1ST ROUND PROPERLY
      do {
        if (digitalRead(buttonRed) == LOW)
        { game = 2;
          gameHasStarted();
        }
        if (digitalRead(buttonGreen) == LOW)
        { game = 2;
          gameHasStarted();
        }
        if (digitalRead(buttonBlue) == LOW)
        { game = 2;
          gameHasStarted();
        }
        if (digitalRead(buttonYellow) == LOW)
        { game = 2;
          gameHasStarted();
        }
        else {
          waitToStart();
        }
      }
      while (game <= 1);
      delay(1000);
    }//END OF GAME INITIATOR FUNCTION

    int pickLed ()//FUNCTION WILL PICK A RANDOM LED
    {
      do {
        randNumber = random(2, 6);
        digitalWrite(randNumber, HIGH);
        delay(500);
        digitalWrite(randNumber, LOW);
        delay(100);
        if (randNumber == 2)
        { ledArray[loopCounter] = 0;
          ledCounter++;
        }
        if (randNumber == 3)
        { ledArray[loopCounter] = 1;
          ledCounter++;
        }
        if (randNumber == 4)
        { ledArray[loopCounter] = 2;
          ledCounter++;
        }
        if (randNumber == 5)
        { ledArray[loopCounter] = 3;
          ledCounter++;
        }
      }
      while (ledCounter < loopCounter);
      ledPrompt();//signals for input after it's done picking the LEDs for each round
      wait == 1;
    }//END OF PICKLED FUNCTION

    int waitForInput ()//FUNCTION WILL WAIT FOR USER INPUT OR END GAME AFTER 10 SECONS OF NO INPUT
    {
      do
      {
        if (digitalRead(buttonRed) == LOW)
        { digitalWrite(r, HIGH);
          inputCounter++;
          delay(150);
          digitalWrite(r, LOW);
          delay(150);
          buttonArray[loopCounter] = 0;
        }
        if (digitalRead(buttonYellow) == LOW)
        { digitalWrite(y, HIGH);
          inputCounter++;
          delay(150);
          digitalWrite(y, LOW);
          delay(150);
          buttonArray[loopCounter] = 1;
        }
        if (digitalRead(buttonBlue) == LOW)
        { digitalWrite(b, HIGH);
          inputCounter++;
          delay(150);
          digitalWrite(b, LOW);
          delay(150);
          buttonArray[loopCounter] = 2;
        }
        if (digitalRead(buttonGreen) == LOW)
        { digitalWrite(g, HIGH);
          inputCounter++;
          delay(150);
          digitalWrite(g, LOW);
          delay(150);
          buttonArray[loopCounter] = 3;
        }
        else {
          wait++; //the wait counter is incremented each time the loop reads all 4 input and no input has been made
          delay(250);
        }//the delay here adds 1/4th of a second each time no input is made (every 4 loop here is 1 second);

        if (wait > 40) //40 divided by 0.25 = 10 seconds of wait
        {
          pass = 0;
          fail();
        } //after waiting 10 seconds for input the game automatically fails.
      }
      while (inputCounter < loopCounter);//WAIT FOR INPUT
    }   //END OF WAIT_FOR_INPUT FUNCTION

    int scoreInput ()//START OF SCORE_INPUT FUNCTION
    { if (memcmp(ledArray, buttonArray, sizeof(ledArray)) == 0)
      {
        delay(1000);
        loopCounter++;
        ledCounter = 0;
        inputCounter = 0;
        game++;
        pass = 2;
      }
      else
      {
        loopCounter = 0;
        ledCounter = 0;
        inputCounter = 0;
        pass = 0;
      }
    }
    //END OF SCORE_INPUT FUNCTION

    void setup ()
    { randomSeed(analogRead(0));
      pinMode (r, OUTPUT);
      pinMode (y, OUTPUT);
      pinMode (b, OUTPUT);
      pinMode (g, OUTPUT);
      pinMode (buttonRed, INPUT_PULLUP);
      pinMode (buttonYellow, INPUT_PULLUP);
      pinMode (buttonGreen, INPUT_PULLUP);
      pinMode (buttonBlue, INPUT_PULLUP);
      pinMode (buttonRed, INPUT);
      pinMode (buttonYellow, INPUT);
      pinMode (buttonGreen, INPUT);
      pinMode (buttonBlue, INPUT);
      pinMode (x, OUTPUT);
      game = 0;
      waiting = 0;
      loopCounter = 1;
      randNumber = 0;
      ledCounter = 0;
      inputCounter = 0;
      pass = 2;
      timeUp = 2;
      initiate();
    }

    void loop ()//by using functions, the void loop section here is very short.
    {
      do {
        pickLed();
        waitForInput();
        scoreInput();
        levelCounter++;
        if (loopCounter > 4)//states the game should end after round 10
        { youWin();
          pass = 0;
        }
      }
      while (pass > 1); // keeps the game going until round 10 or fail
      initiate();
    }

title: How do I adjust this?

Answers: 0


body:
I've got a 200 LEDs strip of sk9822's hooked up to a 5V 8A power supply.
As expected, at full white, there's considerable voltage drop and the far end of the strip turns from white to amber.

I wanted to hook up another set of V+ and GND at the far end of the strip, but doing so trips my psu? The strip blinks full white as a result.

Hooking up ONLY GND or ONLY V+ at the far end significantly improves the drop off where only the middle of the strip turns slightly amber-ish.
But! I do notice a faint buzzing from the PSU if I do this.

Am I doing something wrong here?

title: Powering LED Strip at both ends shorts my psu?

Answers: 1

body:
Put a diode to every psu cable or just take only one psu but make a connection between the input and the far end eith a cable of more than 0,5 mm^2... Spesker csble or so.

Problem with two psu is: one gives 5,00 Volt,  the other 5,05... And there is s power of 0,05 Volt / 8 Ampere running.

Second problem can be the influrnce of different PSU switching frequencies.
Regards,  Michael


body:
I have this(Wifi Manager - Autoconnect IP) program run in my arduino IDE. And I get the output in serial monitor as this

[![Serial Monitor Output][1]][1]

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

Can Anyone help me in displaying my SSID and PASS in this serial monitor output?

My code is this

    #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

    //needed for library
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager

    void setup() {
        // put your setup code here, to run once:
        Serial.begin(115200);

        //WiFiManager
        //Local intialization. Once its business is done, there is no need to keep it around
        WiFiManager wifiManager;
        //reset saved settings
        //wifiManager.resetSettings();

        //set custom ip for portal
        //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

        //fetches ssid and pass from eeprom and tries to connect
        //if it does not connect it starts an access point with the specified name
        //here  "AutoConnectAP"
        //and goes into a blocking loop awaiting configuration
        wifiManager.autoConnect("AutoConnectAP");
        //or use this for auto generated name ESP + ChipID
        //wifiManager.autoConnect();

        //if you get here you have connected to the WiFi
        Serial.println("connected...yeey :)");
    }

    void loop() {
        // put your main code here, to run repeatedly:

    }

    I am using WIFImanager library example - Autoconnect

title: I need to Get my changed SSID and Password in my Serial monitor

Answers: 1

body:
You can use functions SSID() and psk() which are available on the WiFi object as documented [here][1].

Put these lines in setup() after `wifiManager.autoConnect`:
```
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
Serial.print("psk: ");
Serial.println(WiFi.psk());
```

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#ssid


body:
I am interfacing Amonia Sensor RS485 output  with Arduino Mega but not getting any response. i need to transmit  {0x06, 0x03, 0x00, 0x00, 0x00, 0x04, 0x45, 0xBE};
frame to sensor then senor will send response frame. i am using Max485 converter which has DE RE pins .could you guide ME to write proer code. please help me i am in trouble

 ```
 #include <SoftwareSerial.h>

#define SSerialRX        0
#define SSerialTX        1

#define modbusModuleDE   8
#define modbusModuleRE   9

SoftwareSerial RS485Serial(SSerialRX, SSerialTX);
byte byteSend;

//ModbusMaster node;

void setup()
{

  Serial.begin(9600);

  pinMode(modbusModuleRE , OUTPUT);
  pinMode(modbusModuleDE , OUTPUT);

   Serial.println("..... ");

   delay(10);

}

byte buf[8];
void loop()
{

      Serial.print("NH: ");
 digitalWrite(modbusModuleDE, 1);
  digitalWrite(modbusModuleRE, 1);
  delay(10);
      byte request[] = {0x06, 0x03, 0x00, 0x00, 0x00, 0x04, 0x45, 0xBE};
      RS485Serial.write(request, sizeof(request));
      RS485Serial.flush();
   digitalWrite(modbusModuleDE, 0);
  digitalWrite(modbusModuleRE, 0);
  delay(10);
      RS485Serial.readBytes(buf, 8);

      Serial.print("DATA:");
     Serial.println(buf[3], HEX);Serial.println(buf[4], HEX);

     delay(1000);

}
```

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

title: I am interfacing Amonia Sensor RS485 output with Arduino Mega . not getting any response

Answers: 0


body:
I am in the planning stage of chaning two ATSAMD21 with a Zero or Nano 33 bootloade r in a SPI connection. The rational for this is that i am in need of 30 pin GPIO expansion and using 2 mcp23s17 takes a fair bit amount of space and also slightly bit more expensive. Since the ATSAMD21 has theoretical 37 GPIOs why not use that. having not owned a zero board yet, i would like to know if:

Is it easily doable, just connecting the appropriate pins?

If so, i have read in the [Arduino SPI documentation][1] that the zero doesnt have any Slave Select for Master and Slave, does this mean i can use whatever i want? And just code it to detect that pin

Does the built in SPI library capable of handling the slightly higher clock speed of the zero ?

  [1]: https://www.arduino.cc/en/reference/SPI

title: Arduino Zero to Arduino Zero SPI configuration

Answers: 1

body:
A zero has the same number of IO pins then a UNO, they use the same header layout. So I believe you want to use the chips on a self made PCB. (?)

Based on this, I think a second SAMD21 is not the best solution.

They are easily connectable as they use the same Voltage. I used the SPI lib on a zero, so yes, I think its programmable with Arduino techniques. And you can use a CS pin of your choice. The SPI lib uses Arduino header files for the selected platform. So the MCU clock speed shouldn't be a problem.

But you have to program the master and the slave and maintain this firmware. An MCP23(s/0)17 is ready to use.

Two MCP23S17 (QFN packages) don't take that much space.

SAMD21 is capable of driving max. 3.6 V; MCP can handle 5.5 V. (But if you want to use 5V you have to level shift the connection between your Arduino zero and the MCP.

And adding two more MCP23S17 is way easier that adding a third SAMD21, when even the old firmware must be reprogrammed.

A MCP23S17 can drive and sink 25 mA on each pin.

A SAMD21 can handle 14 mA source current and 19.5 mA sink current per IO cluster (there are 6 clusters each of them has between 2 and 16 pins).

On the other hand, if you are sure, you don't need more than 3.6 volts and ~1 mA per pin and the number of the additional IO pins is enough, there is no reason not to use a second SAMD21.

If you need capacitive  touch pins, or more I2S ports or other capabilities of the SAMD21, then the second SAMD21 is even the better choice.

Have you seen the Arduino DUE? It has all the features of a zero and way more IO pins (54) and 12 analog inputs and 2 real analog outputs.


body:
The aim is to display a non-static html page depending on some variable condition.

The code I created hast the problem, that the esp8266 is ressetting in the moment I request the page.

    const char htmlIndexHeader[] 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

    )=====";

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

lorem

    )=====";

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

ipsum

    )=====";

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

    )=====";

    char htmlIndexAll[2000];

    void handleRoot()
    {
      Serial.println("GET /");

       strcpy(htmlIndexAll, htmlIndexHeader);

       if(var1==true)
       {
         strcat(htmlIndexAll, htmlIndexProgress1);
       }

       if(var2==true)
       {
         strcat(htmlIndexAll, htmlIndexProgress2);
       }

       strcat(htmlIndexAll, htmlIndexFooter);

      server.send(200, "text/html", htmlIndexAll);
    }

If I display a static page the esp8266 does not restart at page request.

title: ESP8266 Webserver ESP8266WebServer variable html page (not as one const char)

Answers: 1

body:
Compiler can't differentiate the PROGMEM strings from constant strings in SRAM strings. Both are `const char*`. But the PROGMEM string must be handled differently. For that reason _P variants of functions exists.

You should use stcpy_P and strcat_P functions.

Note: On esp8266 some functions of Arduino core use a trick to identify PROGMEM strings by their specific address range.