body:
I'm trying to upload sketch to a Gizduino board (these boards have PL2303 chip for USB-to-Serial communication; other than that they are entirely similar with Arduino Uno).

I have installed the driver for it and can verify that the board associates to a COM Port whenever the board is connected to my PC (Win10) via USB. But everytime I try to upload a sketch, IDE (tried with 1.8.2 and 1.6.9) throws the error below, with or without the PL2303 driver installed on my PC.

    avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

I'm certain that I have selected the right board from the Boards List.

So my intuition was that the PL2303 driver is not working the way it should be. I've been trying to get more information about avrdude and USBasp but so far was not able to find anything remotely similar to my case.

**UPDATE:** Realized that all I needed to do is install the driver for USBasp (whihch I'm having trouble doing); this post could be off-topic. But I'm urged to raise another question: Which programmer should I select from the programmer list? Currently its "AVRISP mkII". In fact it doesn't matter which one I use. Same error about USBasp occurs with any of them selected.

title: USBasp problem: could not upload sketches to Arduino clone with PL2303 USB-to-UART chip

Answers: 1

body: Do you have a USBasp plugged into the computer? if yes then you need to install USBasp driver else why don't you just use the bootloader option from the arduino IDE.


body:
what are the SDA & SCL pins in NodeMCU? (Pins 20 & 21 in Arduino MEGA2560) I already implemented a simple project to read 2 accelerometers values from Arduino and send them through wifi to firebase database. I used Arduino Mega before for the same project and the sensors gave me readings between approximately -300 to 300. Now when I moved to NodeMCU the sensors became very sensitive and are getting values up to 65500+. And with a very small angle change the axis reading drop down to 20 or less.

I used pins D1 and D2 for SCL and SDA. Are the pins correct? And What about the reading values how to fix that?

title: nodemcu pins + sensors reading values

Answers: 1

body:
The ESP8266 doesn't have a hardware Two Wire Interface. I²C is done in software, so you can use any 2 pins, as long as you specify them in your code using `Wire.begin(SDA, SCL)`.

My guess would be that there's another problem. 65500+ sounds like an integer overflow, for example. (`(uint16_t) -1 == 65535`)


body:
I'm trying to establish a wireless connection between two Arduino's(M0) using xbee s2c, one Arduino as the sender and other as the receiver. But I am not able to receive the message what the Arduino is sending.

The two radio modules are configured as:

**Sender**

    pan id- 1234
    CE- enable
    DH- 13A200
    DL- 40F8D876
    AP- Transparent mode

**Receiver**

    pan id- 1234
    CE- Disable
    JV- Enable
    DH- 13A200
    DL- 40F8D874
    AP- Transparent mode

**SENDER CODE**

    void setup() {
      // Begin the Serial at 9600 Baud
      Serial1.begin(9600);
      SerialUSB.begin(9600);
    }

    void loop() {
      SerialUSB.print(int(Serial1.write("1")));
      delay(1000);
    }

**RECEIVER CODE**

    void setup() {
      // Begin the Serial at 9600 Baud
      Serial1.begin(9600);
      SerialUSB.begin(9600);
    }

    void loop() {
      if (Serial1.available()){
      SerialUSB.print(int(Serial1.read()));
      delay(1000);
    }}

title: Arduino Communication with Xbee

Answers: 0


body:
For a major project at school i need to get a bluetooth module to be able to communicate between two  HC-05 modules as a master and slave. They need to be able to press a pushbutton on the slave and it lights up a LED on the master.
I have been able to get the two hc-05's to connect to each other but i cant find a code and wiring that will work for what i need to do.
any help will be appreciated. Thanks[![master code][1]][1]

[![slave code][2]][2]

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

title: Bluetooth a pushbutton from one arduino to another to turn on a LED

Answers: 1

body:
So, you have done the hard part and now need the easy bit :)

Firstly you need a button (failing that touching two wire together will just about do).  There are loads of quick tutorials on the web, here is one https://www.arduino.cc/en/Tutorial/Button.  They will end up with you having a pin that goes high or low when the button is pressed, you can either poll/loop to detect the press or go posh and use interrupts (leave that for later).  When the pin detects the press you need to send some data via your HC05 link to the master, something like 'ON' or 1, who cares so long as the master understands it.  And when it disconnects you need to send a off or 0 message (Remember the number 1 and the character '1' are not the same thing, so make sure you know what you are sending).

When the master receives the command it will execute a bit of code that will send a pin high (lets say pin 7).  Connected to pin 7 will be the +ve side of a LED, the -ve leg of the led will be connected to a resistor of 200-250 ohms and the other end of the resistor will be connected to ground.  Then when pin7 goes high it will light the resistor.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/cQPPk.png)

<!-- End schematic -->

As always you probably will need to break it down to test it, have a little app that toggles pin 7 high for 2 seconds and low for two seconds, etc (just like blink).

There is a phenomenon called 'bouncing' which is where the useless human finger presses a switch and doesn't instantly create a perfect connection and perfect disconnection.  This might make the slave send 101010101010101 when you just expect 1, you can either debounce using software or hardware, but only worry about that if you have a good quality switch :)


body: How do i code to transmit a sequence of bit using arduino uno?My project is about a transmitter and a receiver.Arduino as the transmitter and an application as the receiver.Light sensor will detect the bits sent.How do i send a sequence of bit for example 00101010.What kind of function should i use? i am a beginner for arduino. thank you.

Answers: 1

body:
Bit-wise sending of a chunk of data is really just:

* go through each byte of the data
* for each byte (= 8-bits), put each bit on the LED and wait

This also has some substantial drawbacks:

* no error detection or correction. If you get interference on your light sensor / camera due to the environment, you will read wrong data. For this you would need to code the data with some coding scheme or append a checksum
* outputting on the built-in LED on the Arduino Uno / Nano is a bad idea sine it's directly next to the power, RX and TX LED
* outputting in the visible spectrum is asking for interference. That's why we have InfraRed transmissions.
* receiver and transmitter might out of sync; that means that the receiver does not sample the output of the transmitter at the correct time -- you should use a preamble, oversampling and averaging at the receiver to overcome this

That said, you might be better off using other proven methods such as IR, 2.4GHz transceivers, et cetera, from my point of view. Other microcontrollers ([example][1]) have even built-in peripherals to do IR transmission according to some protocol.

On the Arduino Uno/Nano you could also use the [IRemote][2] library to send and receive data using a cheap IR LED and a IR receiver, many of which are included in starter kits (and are also otherwise cheap).

The code below simply takes a stream of bytes and outputs them bit-wise on the LED. Nothing else done. Also, `digitalWrite` is slow and should be replaced by [a faster variant][3].

    #include <Arduino.h>

    /* LED to output from */
    const int LEDTrans = 13;
    /* Length of a symbol */
    const int timeWait = 500;

    const char dataToSend[] = "Hello World";

    /* Transmits data bitwise */
    void transmitData(const char* data, size_t length) {
     //go through each byte of the data
     for(size_t i = 0; i < length; i++) {
      uint8_t currentByte = (uint8_t) data[i];

      //Go through each of the 8 bits in the byte
      //Goes from LSB to MSB (right-to-left)
      for(int j = 0; j < 8; j++) {
       //uses Arduino.h macro "bitRead"
       bool currentBit = bitRead(currentByte, j);

       //Set the LED on/off
       digitalWrite(LEDTrans, currentBit);
       //Wait for the symbol time
       delay(timeWait);
      }
     }
    }

    void setup() {
     pinMode(LEDTrans, OUTPUT);
    }

    void loop() {
     transmitData(dataToSend, strlen(dataToSend));
     //turn LED OFF again
     digitalWrite(LEDTrans, 0);
     delay(2000);
    }

  [1]: http://www.st.com/resource/en/datasheet/cd00161566.pdf
  [2]: https://github.com/z3t0/Arduino-IRremote
  [3]: https://github.com/NicksonYap/digitalWriteFast


body:
I've been trying to make a program that interacts with SIM800H trough AT commands. It worked with the String class, but it was full of "memory leaks" and after a few hours it just hanged. Then I tried to write it again with char arrays, but for some reason I couldn't get it to work properly.

Can someone suggest me a correction to my program and also a way to get char by char with loop and `Serial.read();`? Serial in this case (Arduino Leonardo) is the USB port and Serial1 is the port to the modem.

Here is my code:

    const long interval = 2000;
    static long currentMillis;

    char wherecclk = 0; //To determine where is the + in +CCLK in the char array

    char serialdata[256] = ""; //Array to store the chars before parsing

    char rtcy1[3]; //Current year  Format: yy\0
    char rtcm1[3]; //Current month  Format: mm\0
    char rtcd1[3]; //Current day  Format: dd\0
    char rtch1[3]; //Current hour  Format: hh\0
    char rtcmm1[3]; //Current minute  Format: mm\0
    char rtcs1[3]; //Current second  Format: ss\0

    int rdpos = 0;

    void setup() {
        Serial.begin(9600); //USB to Computer
        Serial1.begin(9600); //UART to Modem
        Serial1.print("ATE0\r"); //Disable echo
    }

    void loop() {
        wherecclk = 0;
        if (Serial1.available () > 0) { //when something comes on real serial
            strcpy(serialdata, "OK\n\n+CCLK: \"04/01/01,01:35:31+00\"\n\nOK\n"); //This is a real sample of the response coming from the modem emulated
            while (rdpos < 256) //loop timeout: 256 bytes
            {
                if (serialdata[rdpos] == '+') {
                    break; //We have reached the first + char. Stop incrementing it
                }
                rdpos++;
            }
            if (serialdata[rdpos + 1] == 'C' && serialdata[rdpos + 2] == 'C' && serialdata[rdpos + 3] == 'L' && serialdata[rdpos + 4] == 'K') { //If the serial command mathes +CCLK save its position
                wherecclk = rdpos;
            }
            rdpos = 0;

            if (wherecclk != 0) {
                rtcy1[0] = serialdata[wherecclk + 8]; //getting first char with its offset
                rtcy1[1] = serialdata[wherecclk + 9];
                rtcy1[2] = '\0';
                rtcm1[0] = serialdata[wherecclk + 11];
                rtcm1[1] = serialdata[wherecclk + 12];
                rtcm1[2] = '\0';
                rtcd1[0] = serialdata[wherecclk + 14];
                rtcd1[1] = serialdata[wherecclk + 16];
                rtcd1[2] = '\0';
                rtch1[0] = serialdata[wherecclk + 17];
                rtch1[1] = serialdata[wherecclk + 18];
                rtch1[2] = '\0';
                rtcm1[0] = serialdata[wherecclk + 20];
                rtcm1[1] = serialdata[wherecclk + 21];
                rtcm1[2] = '\0';
                rtcs1[0] = serialdata[wherecclk + 23];
                rtcs1[1] = serialdata[wherecclk + 24];
                rtcs1[2] = '\0';
            }

        }

        if (millis() - currentMillis >= interval) //This is done every second
        {
            Serial1.print("AT+CCLK?\r"); //ask for the time
            //delay(50);
            Serial.println("");
            Serial.println("=====");
            Serial.println(millis());

            Serial.println("YEAR: ");
            Serial.print(rtcy1[0]);
            Serial.println(rtcy1[1]);
            Serial.println("MONTH: ");
            Serial.print(rtcm1[0]);
            Serial.println(rtcm1[1]);
            Serial.println("DAY: ");
            Serial.print(rtcd1[0]);
            Serial.println(rtcd1[1]);
            Serial.println("HOUR: ");
            Serial.print(rtch1[0]);
            Serial.println(rtch1[1]);
            Serial.println("MINUTE: ");
            Serial.print(rtcmm1[0]);
            Serial.println(rtcmm1[1]);
            Serial.println("SECOND: ");
            Serial.print(rtcs1[0]);
            Serial.println(rtcs1[1]);

            currentMillis = millis();
        }
    }

Here is the output (a screenshot, because serial monitor doesn't give me full code):

[![serial monitor][1]][1]

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

title: Arduino receive response from SIM800H to AT+CCLK? command

Answers: 2

body: You declare your variables for month and minute differently (`rtcm1[3]` vs `rtcmm1[3]`), but you load `rtcm1` with month, and then a few lines later, with minutes.

body:
Here's the final code in case someone needs it:

 const long interval = 1000;
 static long currentMillis;

 char wherecclk = 0; //To determine where is the + in +CCLK in the char array

 char serialdata[256] = ""; //Array to store the chars before parsing

 char rtcy1[3]; //Current year  Format: yy\0
 char rtcm1[3]; //Current month  Format: mm\0
 char rtcd1[3]; //Current day  Format: dd\0
 char rtch1[3]; //Current hour  Format: hh\0
 char rtcmm1[3]; //Current minute  Format: mm\0
 char rtcs1[3]; //Current second  Format: ss\0

 int rdpos = 0;

 int pointingfinger = 0;

 void setup() {
   Serial.begin(9600); //USB to Computer
   Serial1.begin(9600); //UART to Modem
   Serial1.print("ATE0\r"); //Disable echo
 }

 void loop() {
   if (Serial1.available () > 0) { //when something comes on real serial
  rdpos = 0;
  wherecclk = 0;
  if (pointingfinger == 255) {
    pointingfinger = 0;
  }

  serialdata[pointingfinger] = Serial1.read();

  while (rdpos < 256) //loop timeout: 256 bytes
  {
    if (serialdata[rdpos] == '+') {
   break; //We have reached the first + char. Stop incrementing it
    }
    rdpos++;
  }
  if (serialdata[rdpos + 1] == 'C' && serialdata[rdpos + 2] == 'C' && serialdata[rdpos + 3] == 'L' && serialdata[rdpos + 4] == 'K') { //If the serial command mathes +CCLK save its position
    wherecclk = rdpos;
  }

  pointingfinger++;
   }

   if (millis() - currentMillis >= interval) //This is done every second
   {
  pointingfinger = 0;
  //Serial.println("=========");
  //Serial.println(serialdata);
  //Serial.println("=========");
  if (wherecclk != 0) {
    rtcy1[0] = serialdata[wherecclk + 8]; //getting first char with its offset
    rtcy1[1] = serialdata[wherecclk + 9];
    rtcy1[2] = '\0';
    rtcm1[0] = serialdata[wherecclk + 11];
    rtcm1[1] = serialdata[wherecclk + 12];
    rtcm1[2] = '\0';
    rtcd1[0] = serialdata[wherecclk + 14];
    rtcd1[1] = serialdata[wherecclk + 15];
    rtcd1[2] = '\0';
    rtch1[0] = serialdata[wherecclk + 17];
    rtch1[1] = serialdata[wherecclk + 18];
    rtch1[2] = '\0';
    rtcmm1[0] = serialdata[wherecclk + 20];
    rtcmm1[1] = serialdata[wherecclk + 21];
    rtcmm1[2] = '\0';
    rtcs1[0] = serialdata[wherecclk + 23];
    rtcs1[1] = serialdata[wherecclk + 24];
    rtcs1[2] = '\0';
  }
  Serial1.print("AT+CCLK?\r"); //ask for the time
  //delay(50);
  Serial.println("");
  Serial.println("=====");
  Serial.println(millis());

  Serial.println("YEAR: ");
  Serial.print(rtcy1[0]);
  Serial.println(rtcy1[1]);
  Serial.println("MONTH: ");
  Serial.print(rtcm1[0]);
  Serial.println(rtcm1[1]);
  Serial.println("DAY: ");
  Serial.print(rtcd1[0]);
  Serial.println(rtcd1[1]);
  Serial.println("HOUR: ");
  Serial.print(rtch1[0]);
  Serial.println(rtch1[1]);
  Serial.println("MINUTE: ");
  Serial.print(rtcmm1[0]);
  Serial.println(rtcmm1[1]);
  Serial.println("SECOND: ");
  Serial.print(rtcs1[0]);
  Serial.println(rtcs1[1]);

  currentMillis = millis();
   }
 }


body:
I am using:

    Serial.print(rawCodes[i - 1], DEC);

to print into serial monitor, but how can I save `(rawCodes[i - 1], DEC)` to save into variable?

title: Arduino - use print(.., DEC) to save into variable

Answers: 1

body:
Assuming your code comes from here: https://www.alanzucconi.com/2015/08/19/how-to-hack-any-ir-remote-controller/

Since `rawCodes` is declared as

    unsigned int rawCodes[35];

I.e., it is a 35-element array of `unsigned int` elements, we can access a single `unsigned int` element at some index and save it in a variable like

    unsigned int myVariable = rawCodes[i - 1]; //assuming i is some integer variable
                                               //and exists in this scope

If conversion to a `String` object is needed it can be passed into the constructor of the `String` class as

    String myString = String(myVariable);

That answers your syntactical question on how to save that element into a variable; however, it is unlikely that this is your real underlying problem. We cannot determine that until you tell us what exactly you actually want.

References:

* [Arrays in C tutorial][1]

  [1]: https://www.tutorialspoint.com/cprogramming/c_arrays.htm


body:
    #include "arduinoFFT.h"
    float y, x = 0;
    #define t PE_0
    #define SAMPLES 1024             //Must be a power of 2
    #define SAMPLING_FREQUENCY 1024 //Hz, must be less than 10000 due to ADC
    arduinoFFT FFT = arduinoFFT();

    unsigned int sampling_period_us;
    unsigned long microseconds;

    double  vReal[SAMPLES];
    double vImag[SAMPLES];

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

      sampling_period_us = round(1000000 * (1.0 / SAMPLING_FREQUENCY));
    }

    void loop() {

      /*SAMPLING*/
      for (int i = 0; i < SAMPLES; i++)
      {
        microseconds = micros();    //Overflows after around 70 minutes!
        y=(analogRead(t))*(3.3/4095.0)-1.65;
        x=((1000.0*y)/201.0);
        vReal[i] = x;
        vImag[i] = 0;

        while (micros() < (microseconds + sampling_period_us)) {
        }
      }

      /*FFT*/
      FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HANN , FFT_FORWARD);
      FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
      FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
      double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

      /*PRINT RESULTS*/
      //Serial.println(peak);     //Print out what frequency is the most dominant.

      for (int i = 0; i < (SAMPLES / 2); i++)
      {
        /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

        //Serial.println((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
        //Serial.print(" ");
        Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
      }

      delay(1000);  //Repeat the process every second OR:
      //while (1);      //Run code once
    Serial.println("//");
    }

title: how to send FFT array consist of 512 Samples Data From arduino to raspberry pi using i2c and this is the code for FFT any Suggestion plz?

Answers: 0


body:
I am doing a project and here is the code that I am using, but I do not know why the values of duration and sofia is always 0 so the values of distance and monroy are also 0

    const int trigPin = 9;
    const int echoPin = 10;

    const int t = 8;
    const int e = 7;

    long duration, sofia;
    int distance, monroy;
    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      pinMode(t, OUTPUT);
      pinMode (e, INPUT);
      Serial.begin(9600); // Starts the serial communication
    }
    void loop() {
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      digitalWrite (t, LOW);
      delayMicroseconds(2);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      digitalWrite (t, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      digitalWrite (t, LOW);
      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);
      sofia = pulseIn(e, HIGH);
      // Calculating the distance
      distance = duration * 0.034 / 2;
      monroy = sofia * 0.034 / 2;
      Serial.print(duration);
      if (distance = 15);
      {
        digitalWrite (3, HIGH);
        delay (5000);
        digitalWrite (3, LOW);
      }

      if ((monroy >= 0) && (monroy <= 5));
      {
        digitalWrite (4, HIGH);
        digitalWrite (5, LOW);
        digitalWrite (6, LOW);
      }
      if ((monroy >= 5.1) && (monroy <= 9));
      {

        digitalWrite (5, HIGH);
        digitalWrite (6, LOW);
      }
      if (monroy >= 9.1);
      {

        digitalWrite (5, LOW);
        digitalWrite (6, HIGH);
      }
    }

title: Why is this variable giving me always the value of 0?

Answers: 1

body:
When I formatted your code for readability and then compiled it I got these warnings:

    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino: In function 'void loop()':
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:20: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
       if (distance = 15);
                        ^
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
       if (distance = 15);
                         ^
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:41:38: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
       if ((monroy >= 0) && (monroy <= 5));
                                          ^
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:47:40: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
       if ((monroy >= 5.1) && (monroy <= 9));
                                            ^
    /tmp/arduino_modified_sketch_71221/sketch_may02a.ino:53:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
       if (monroy >= 9.1);

These are **important** - you should pay attention to them. For example, here:

      if (distance = 15);  // <-- NO SEMICOLON NEEDED HERE!
      {
        digitalWrite (3, HIGH);
        delay (5000);
        digitalWrite (3, LOW);
      }

Putting a semicolon there means that stuff under the `if` is **always executed** - the semicolon terminates the scope of the `if`.

---

To see the warnings open the Preferences dialog in the IDE GUI and change "Compiler warnings" to "All".

---

Also:

      if (distance = 15);

This **assigns** 15 to distance, so distance will always be 15. You mean:

      if (distance == 15)


body:
I'm trying to add a serial number to the bootloader's flash area of Adafruit Feather m0 board. Seems like feather m0 0-0x2000 area on the flash is non writable by the arduino sketch. i wanted to add a serial number to address 0x2000 - 8 on the flash.
The idea is for the data to be included in the bootloader elf\bin so i can easily flash it on devices and later on access it using flash address  (0x2000 - 8) with NVMCTRL.

I've started out with this solution:

downloaded the code from [samd21 arduino bootloader github directory][1] and in ./bootloaders/zero edited the boololoader ld script, first the "Memory" section

    FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x2000 /* First 8KB used by bootloader */
    FLASHID (rx) : ORIGIN = 0x00002000 - 0x0008, LENGTH = 8

Then the 'sections' section:

    .id_sec :
      {
        KEEP(*(.myid))
      } > FLASHID

This should have saved some room in the end of the flash for the id. now in the main.c file:

    __attribute__ ((section(".myid"))) const unsigned long ID = 0xdead1234;

Which should have saved the 0xdead1234 hex value in the (0x2000-8) address.

The issue is this:
I compiled this code and linked it just fine, got .hex,.bin,.elf files.
If i'm correct (unless they are somehow compressed) i should be able to see the code 0xdead in the binary.
**BUT** i don't.
After objdump on the binary(any of them) i can't find the 0xde 0xad in any order anywhere.
The `arm-none-eabi-size" --format=sysv -t -x build/.elf` does not show the new section i added no where.
Also i do wonder, as i said the 0x2000 address on the flash is non writable once i flashed with atmel-ice \j-link even the bootloader code cannot write to it, i did define in the ld script that i want that memory region part of the flash so i do expect that the compiler + linker + jlink flasher will know to write that data to the right place but not sure.

Anyone got some experience with it ? did it before ?

  [1]: https://github.com/arduino/ArduinoCore-samd

title: add ID number to the feather m0 bootloader (flash)

Answers: 1

body:
This is quite an easy fix, actually.

The problem here is the compiler doesn't think the const is used for anything - so it (quite rightly) throws it away.

All you need to do is tell the compiler that it's `used` and all should be good:

    __attribute__((section(".myid"),used)) const unsigned long ID = 0xdead1234;

And when you compile:

    build/.elf  :
    section             size         addr
    .vectors            0x40          0x0
    .text             0x18d4         0x40
    .data               0x5c   0x20000000
    .bss               0x34c   0x2000005c
    .id_sec              0x4       0x1ff8
    .ARM.attributes     0x28          0x0
    .comment            0x80          0x0
    .debug_frame        0x68          0x0
    Total             0x1dd0

Properly, though, you should make some more changes to the linker script to properly isolate those 8 bytes of flash (though you don't *have* to).

1. You should reduce `FLASH` by 8 bytes.
2. You should include the FLASHID length in the `__sketch_vectors_ptr` calculation.

That's:

    MEMORY
    {
      FLASH   (rx) : ORIGIN = 0x00000000, LENGTH = 0x1FF8 /* First 8KB used by bootloader */
      FLASHID (rx) : ORIGIN = 0x00001FF8, LENGTH = 8
      RAM    (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000-0x0004 /* 4 bytes used by bootloader to keep data between resets */
    }

And:

    PROVIDE(__sketch_vectors_ptr = ORIGIN(FLASH) + LENGTH(FLASH) + LENGTH(FLASHID));

That way the compiled bootloader code can never be placed in the FLASHID area (not that it would at the moment, but if a new version of the bootloader were released that used 100% of the lower block of flash it would conflict).

Of course, if all you need is something unique to identify the board with, all AVR and SAMD devices that have built-in USB support have a unique ID number. This is intended to be used as the Serial Number for the USB, but could also be used for a MAC address for Ethernet (or for portions of it anyway) or other unique "node" addresses.


body:
Guys i have made an arduino 4wd rover using L298N BRIDGE MODULE, HC-05 and Arduino uno but the power supply output of L298N was very low that even 1 motor is working too slow so please help me with power out put please...
Here is the code...

    #define enA 9
    #define in1 4
    #define in2 5
    #define enB 10
    #define in3 6
    #define in4 7

    int xAxis, yAxis;
    int  x = 0;
    int  y = 0;

    int motorSpeedA = 0;
    int motorSpeedB = 0;

    void setup() {
      pinMode(enA, OUTPUT);
      pinMode(enB, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);

      Serial.begin(38400); // Default communication rate of the Bluetooth module
    }

    void loop() {
      // Default value - no movement when the Joystick stays in the center
      xAxis = 510;
      yAxis = 510;

      // Read the incoming data from the Smartphone Android App
      while (Serial.available() >= 2) {
        x = Serial.read();
        delay(10);
        y = Serial.read();
      }
      delay(10);

      // Makes sure we receive corrent values
      if (x > 60 & x < 220) {
        xAxis = map(x, 220, 60, 1023, 0); // Convert the smartphone X and Y values to 0 - 1023 range, suitable motor for the motor control code below
      }
      if (y > 60 & y < 220) {
        yAxis = map(y, 220, 60, 0, 1023);
      }

      // Y-axis used for forward and backward control
      if (yAxis < 470) {
        // Set Motor A backward
        digitalWrite(in1, HIGH);
        digitalWrite(in2, LOW);
        // Set Motor B backward
        digitalWrite(in3, HIGH);
        digitalWrite(in4, LOW);
        // Convert the declining Y-axis readings for going backward from 470 to 0 into 0 to 255 value for the PWM signal for increasing the motor speed
        motorSpeedA = map(yAxis, 470, 0, 0, 255);
        motorSpeedB = map(yAxis, 470, 0, 0, 255);
      }
      else if (yAxis > 550) {
        // Set Motor A forward
        digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
        // Set Motor B forward
        digitalWrite(in3, LOW);
        digitalWrite(in4, HIGH);
        // Convert the increasing Y-axis readings for going forward from 550 to 1023 into 0 to 255 value for the PWM signal for increasing the motor speed
        motorSpeedA = map(yAxis, 550, 1023, 0, 255);
        motorSpeedB = map(yAxis, 550, 1023, 0, 255);
      }
      // If joystick stays in middle the motors are not moving
      else {
        motorSpeedA = 0;
        motorSpeedB = 0;
      }

      // X-axis used for left and right control
      if (xAxis < 470) {
        // Convert the declining X-axis readings from 470 to 0 into increasing 0 to 255 value
        int xMapped = map(xAxis, 470, 0, 0, 255);
        // Move to left - decrease left motor speed, increase right motor speed
        motorSpeedA = motorSpeedA - xMapped;
        motorSpeedB = motorSpeedB + xMapped;
        // Confine the range from 0 to 255
        if (motorSpeedA < 0) {
          motorSpeedA = 0;
        }
        if (motorSpeedB > 255) {
          motorSpeedB = 255;
        }
      }
      if (xAxis > 550) {
        // Convert the increasing X-axis readings from 550 to 1023 into 0 to 255 value
        int xMapped = map(xAxis, 550, 1023, 0, 255);
        // Move right - decrease right motor speed, increase left motor speed
        motorSpeedA = motorSpeedA + xMapped;
        motorSpeedB = motorSpeedB - xMapped;
        // Confine the range from 0 to 255
        if (motorSpeedA > 255) {
          motorSpeedA = 255;
        }
        if (motorSpeedB < 0) {
          motorSpeedB = 0;
        }
      }
      // Prevent buzzing at low speeds (Adjust according to your motors. My motors couldn't start moving if PWM value was below value of 70)
      if (motorSpeedA < 70) {
        motorSpeedA = 0;
      }
      if (motorSpeedB < 70) {
        motorSpeedB = 0;
      }
      analogWrite(enA, motorSpeedA); // Send PWM signal to motor A
      analogWrite(enB, motorSpeedB); // Send PWM signal to motor B
    }

![enter image description here](https://i.stack.imgur.com/jjJP3.png)

title: Arduino 4wd rover

Answers: 1

body:
You need more power!

The formula for power is Volts * Amps. A PP3 has about 500mAh, which means its can (in theory) output 9V at 500mA for an hour, which means you have about 4.5 watts.

So what power do your motors need? I'll assume they are about 1.5W motors, which means you need 6W to drive all the motors.

Your PP3 can output 6W, but it won't last long if it does and it will get hot.  Also, if you have 12V motors and are only giving the 9V then they are going to be asking for 1/3 more amps to balance the equation and get their power.  You are probably asking the PP3 to supply 1A which means it will last less than 30 minutes if it is brand new and good quality.

A "simple" solution would be to use two (or more) batteries in parallel.  Parallel gives you more power without changing the voltage.  A better solution would be to look at alternative battery packs, a couple or LiPo 3.7V 1100mAh battery packs, a sealed lead acid gel (heavy).  An even better solution would be to see if you can get lower power motors that can supply the same torque.

Failing that, get a meaty desktop power supply and a long cable :)


body: I am trying to write a code so that I can detect how many times the IR detector has detected the IR signal from the IR transmitter.

title: How to write a code to detect how many times the IR detector has detected an IR signal.... HELP

Answers: 1

body:
Its quite simple:

    IRDetectorLibraryObject ir;
    int counter = 0;

    void setup()
    {
        ir.setup();
    }
    void loop ()
    {
        if (ir.detectedSignal())
        {
          ++counter;
        }
    }


body:
I'm trying to control 2 servos with 2 pots. I thought I could just amend the tutorial code by adding in the extra pot on a1 and extra servo on d8 (am using a Nano).

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    Servo myservo_2;

    int potpin = 0;  // analog pin used to connect the potentiometer
    int potpin_2 = 1;
    int val;    // variable to read the value from the analog pin
    int val_2;

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
      myservo_2.attach(8);
    }

    void loop() {
      val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
      val_2 = analogRead(potpin_2);
      val = map(val, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
      val_2 = map(val_2, 0, 1023, 0, 180);
      myservo.write(val);                  // sets the servo position according to the scaled value
      myservo_2.write(val_2);
      delay(15);                           // waits for the servo to get there
    }

...but the servos only respond to one of the pots (on a0) & both move to the same position regardless of what value is on a1.

Am I missing something really obvious? Why is the value on a1 ignored & why is the value mapped from a0 sent to both d8 & d9?

I have swapped out the pot on a1 just in case it was faulty but I get the same behavior.

EDIT: Added schematic

[![Dual servo schematic][1]][1]

EDIT: I swapped out the Nano for another Nano but that failed to upload the sketch. So I put the original back in & now evrything is working fine!

Darn'd if I can get my head around it, possibly a bad connection with the bread board?

Anyway all working now thanks for your suggestions.

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

title: Two pots controlling 2 servos -- odd behavior

Answers: 1

body:
I have no idea whats wrong with your system, but this might help you diagnose it.

    #include <Servo.h>

    static const size_t MaxServos = 2;    // The number of pots and servos attached
    const int servoPins[MaxServos] = {9, 8};  // The pins that the servos are controlled through
    const int potpins[MaxServos] = {A0, A1};  // analog pin used to connect the potentiometer
    Servo myservo[MaxServos];      // create servo object to control a servo

    void setup ()
    {
     for (size_t index = 0; index < MaxServos; ++index)
     {
      myservo[index].attach (servoPins[index]);
     }
    }

    void loop ()
    {
     for (size_t index = 0; index < MaxServos; ++index)
     {
      readAndSet (potpins[index], myservo[index]);
     }
     delay (15);                           // waits for the servo to get there - might want to multiply a value by the number of degrees turned to give a better value.
    }

    // \brief Read the specified analog pin and set the server proportionally
    // \param The analog pin that the pot is connected to.
    // \param The servo that will be moved
    void readAndSet (const int& pin, Servo& servo)
    {
     const int value = analogRead (pin);            // reads the value of the potentiometer (value between 0 and 1023)
     const int mappedValue = map (value, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
     servo.write (mappedValue);                  // sets the servo position according to the scaled value
    }

I have refactored your code to eliminate the duplication.  This means you will get more test coverage and you should find the bug quicker.  You could add a `Serial print` statement to the `readAndSet` function to ensure that you are passing and calculating the right values, but I suspect you are.

There appears to be nothing wrong with the code, so is it possible that there is some hardware limitation?  Is there a short between the lines that causes the pot on A1 to be bypassed?


body:
I recently came across this code in a tutorial. The code works, but this form of syntax seems to differ quite a bit from https://www.arduino.cc/reference/en/language/structure/control-structure/if/, as it's lacking comparison operators and curly braces for statements. Can someone please run down why this works?

    for (int i = 0; i < 15; i++)
    {
    lcd.setCursor(i, 1);
    if (pressed[i])
      lcd.print("X");
    else
      lcd.print(" ");

    if (justpressed[i])
      digitalWrite(led, HIGH);
    else
      digitalWrite(led, LOW);
     }

title: if/else statements without comparison operators and curly braces

Answers: 2

body:
About the missing conditions, e.g.:

    if (pressed[i])

If is supposed to be a boolean, this is the prefered way, as long as the boolean has value zero (0) when false and nonzero when true. It is the same as writing:

    if (pressed[i] != 0)

It is not usual to do this for integers, only for booleans.

About the brackets: If you have only one statement the brackets can be omitted. But it is quite a bad programming practice, since sooner or later you add a statement, without the brackets added and you have a bug introduced.

If you really want to shorten it than instead of

    if (justpressed[i])
      digitalWrite(led, HIGH);
    else
      digitalWrite(led, LOW);

use

    digitalWrite(justpressed[i] ? HIGH : LOW);

This is called the [Ternary operator][1].

  [1]: https://en.wikipedia.org/wiki/?:#C

**update**

Using the remark of wondra but with the ternary operation your code can be

    for (int i = 0; i < 15; i++)
    {
        lcd.setCursor(i, 1);
        lcd.print   (     pressed    [i] ? "X"  : " ");
        digitalWrite(led, justpressed[i] ? HIGH : LOW);
    }

body:
1. **if (something)** is the same as **if(something!=0)**, if condition is a non-zero value, it is considered as [fulfilled condition](https://www.le.ac.uk/users/rjm1/cotter/page_37.htm), read about the [Conditionals - The true or false story](http://www.cplusplus.com/forum/articles/3483/)
2. For single line statements you don't need to use curly braces. But using the braces makes the code more readable and the code is [less prone to errors](https://stackoverflow.com/questions/12193170/whats-the-purpose-of-using-braces-i-e-for-a-single-line-if-or-loop)


body:
I had this added to programmers.txt

    mysmartusb.name=mySmartUSB light
    mysmartusb.communication=serial
    mysmartusb.protocol=stk500v2
    mysmartusb.program.protocol=stk500v2
    mysmartusb.program.tool=avrdude
    mysmartusb.program.extra_params=-P{serial.port}

And was getting so annoyed with the loading time of Arduino IDE 1.8.5 so I tried Visual Micro but that didn't go well either. Now, Arduino IDE can no longer see my programmer. Tried rebooting, did a search for all programmer.txt files on the C: and deleted/updated as I thought appropriate. Has anyone else ever had that issue and if so, how did they solve it?

title: Arduino IDE loses programmer after installing Visual Micro

Answers: 1

body: Uninstalled and installed 1.9.0 as I heard that fixes the launch time (it does). I'm aware it's beta but it fixed my issue. I assume reinstalling 1.8.5 would've also gotten me my programmer back.


body: I am having an issue with external loads causing the computer I have my Arduino connected to to momentarily drop out, which causes the Arduino to lose USB power momentarily and the port drops out and won't reconnect unless I physically remove and reconnect the USB cable. Since I need the USB connected in order to send and receive serial data to/from the Arduino, I was wondering if I could physically open the USB cable, cut the 5V line, and supply it via and external regulated 5V supply. I wouldn't cut the ground wire, but would tie it to the external 5V supply. I have read conflicting information on this (something about handshaking) but was wondering if that applied to Arduino's specifically.

title: Powering USB cable that powers Arduino with regulated 5V

Answers: 2

body:
If you are drawing more than 500mA from your PC then that is why it is happening.

I suggest, rather than butchering a cable, you get yourself a "wallwart" (Mobile phone charger) and use that to power the board.  You really should work out how much current you are pulling before deciding on what PSU to use.

A problem with wall warts is earthing, you need to make sure that your PC and wall wart are connected to the same earth connection, so that they share a common ground.

If the current being drawn us only for a very short time then it might be possible to provide additional power using a capacitor in the power line.  But plugging a charger in is much easier.

body: I solved this problem by using a laptop instead. It is immune to these power fluctuations


body:
Im currently new on this and sucessfully made a sound-activated alarm with Arduino Uno and a microphone sensor. (If sound is detected, then it will alarm). Now, I am adding a ESP 8266 module into it so it can perform a HTTP GET or POST to IFTT Maker link.

My problem with it is how can I program the esp with arduino uno? Do I do something like this
>https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClient/WebClient.ino

(and add the threshold for the microphone sensor, buzzers and LEDs)??

Thanks for helping

title: ESP8266 with Arduino Uno and HTTP POST

Answers: 1

body:
Yes, the library

* https://github.com/bportaluri/WiFiEsp

Is suited for your task because it implements talking to a ESP8266 over a software serial. On this serial connection, AT+ commands will be sent. This also means that you must have the AT firmware flashed onto your ESP-01.

If that is not the case you can download the binary image [here][1] and flash it with a serial adapter, as instructed with the tools on that page. You can check whether your ESP8266 has the firmware flashed by attach a UART adpater to the TX output. It should print a "ready" on bootup.

For your wire-up, you will just have to add VCC (+3.3V), GND, TX and RX connections to the ESP-01 board, preferable with a big capacitor between VCC and GND, as the ESP8266 draws a lot of power when sending data over WiFi.

  [1]: http://www.electrodragon.com/w/ESP8266_AT-Command_firmware


body:
I built a sample of my project on a breadboard using little 700mh leds and other components that easily ran off my computers usb. Now I’m building my project to full size.  This includes 12 7w leds, soundboard and amps. It’s still going to be controlled by a arduino mega, obviously, the power consumption is substantially higher than the usb or even the arduino can provide. I’m using a high amp power supply that can drive everything including the arduino.

The question is... how will I be able to alter my sketch later???  Is it feasible to use a panel mount usb cord modified to only allow tx and rx, (cut the red and black)?  Or will I have to isolate the mega each time I need to send a change to it?

title: External power vs usb power

Answers: 2

body: You can modify a USB cable by cutting the power (red) wire. You'll still need the ground wire with RX and TX.

body: Using an altered USB cable and a separate power supply will work but isn't really necessary. I usually put a connector on my high-current devices like LEDs and whatnot so I can remove them from the equation while I upload code, and for debugging I leave the external power supply attached and use a regular USB cable to the PC (see https://arduino.stackexchange.com/questions/893/what-happens-if-i-power-the-arduino-with-both-the-usb-and-external-power-voltage?rq=1).


body:
I'm using the BNO055 9DOF Adafruit sensor to measure the acceleration/orientation. How can I change the configuration of the accelerometer from 4G (default) to 16G?

What I already know:

The datasheet : https://cdn-shop.adafruit.com/datasheets/BST_BNO055_DS000_12.pdf

From point 3.5.2 from page 27, I need to change xxxxxx01b to xxxxxx11b in the configuration file (that is the library). I use https://github.com/adafruit/Adafruit_BNO055 but I could not find any information on what to change and where in the .h file.

Any ideas?

Thank you

title: Configuring Accelerometer on BNO055 sensor

Answers: 1

body:
This was partly discussed as an issue on the library's github

* https://github.com/adafruit/Adafruit_BNO055/issues/48

Here's how I understand it:

The library doesn't configure the registers you want. I don't see a reference to writing to the `ACC_CONFIG` register (address 8). Not even defined in the header.

The sensor has two register-pages (0 and 1) [refer page 50]. I.e. if you select page 0 then the register at address X means something, at page 1 it means something else.

We want to write to `ACC_Config` at address `0x08` on Page 1.

Page 77 tells us that, regarding writing to the register: "Write: can only be changed in sensor mode, see section 3.5.2"

In code, you could hack something in there:

* https://github.com/adafruit/Adafruit_BNO055/blob/master/Adafruit_BNO055.cpp#L115

After changing to the sensore mode, you could then write to the register as

<!-- language: lang-cpp -->

    //values taken from section 3.5.2 page 27
    #define BNO055_ACC_CONFIG_2G (0) //0B00
    #define BNO055_ACC_CONFIG_4G (1) //0B01
    #define BNO055_ACC_CONFIG_8G (2)  //0B10
    #define BNO055_ACC_CONFIG_16G (3)  //0B11

    //bandwidth definitions
    #define BNO055_ACC_BW_7_81_Hz (0)
    #define BNO055_ACC_BW_15_63_Hz (1)
    #define BNO055_ACC_BW_31_25_Hz (2)
    #define BNO055_ACC_BW_62_5_Hz (3)
    #define BNO055_ACC_BW_125_Hz (4)
    #define BNO055_ACC_BW_250_Hz (5)
    #define BNO055_ACC_BW_500_Hz (6)
    #define BNO055_ACC_BW_1000_Hz (7)

    //powermode definitions
    #define BNO055_ACC_PWRMODE_NORMAL (0)
    #define BNO055_ACC_PWRMODE_SUSPEND (1)
    #define BNO055_ACC_PWRMODE_LP1 (2)
    #define BNO055_ACC_PWRMODE_STANDBY (3)
    #define BNO055_ACC_PWRMODE_LP2 (4)
    #define BNO055_ACC_PWRMODE_DEEP_SUSPEND (5)

    #define BNO055_ACC_CONFIG_ADDR 0x08

    //Select page ID 1 to write to the right register
    write8(BNO055_PAGE_ID_ADDR, 1);
    //build the config value with bitshifts
    //see page 77
    //use all standard values except 16G parameter
    uint8_t acc_config = (uint8_t)((BNO055_ACC_PWRMODE_NORMAL << 5)
                       | (BNO055_ACC_BW_62_5_Hz << 2)
                       | BNO055_ACC_CONFIG_16G);
    //write new accelerometer config
    write8(BNO055_ACC_CONFIG_ADDR, acc_config);

    //change back to page ID 0 (or whatever was before there)
    //Otherwise we read sensor data from the wrong page with entirely different meaning
    write8(BNO055_PAGE_ID_ADDR, 0);

Since I don't have that sensor here I have no way to test it. So this is just the basic idea. You can also read registers with `read8`, with which you can verify that before you write anything to the register, it has some standard (or expected) value. E.g., `ACC_CONFIG` should read as `0B00001101` = `0x0d`. And after you write a value there you should be able to read the same value back, otherwise the chip didn't let you execute the write and you have to investigate why.

Yes, you mostly have to do the hard work by yourself. Changing from 4G to 16G might also have the implication that some other calculations on the raw data has to be done different, however I am not sure of that.


body:
I have a finite state machine that goes to a function called patternOne, I can't seam to get out of this function though once I am in it and get back to the finite state machine. When I press a button my serial port shows it's been pressed but still stays in the function patternOne, I don't know how to get out of it and why this is happening. My code is below:

    #include <SPI.h>
    SPISettings settingsA(2000000, MSBFIRST, SPI_MODE1);
    #include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library
    #include <Wire.h>  // Include Wire if you're using I2C
    volatile unsigned long prevTime = 0;

    int time_interval_for_chip = 5;
    int blinking_interval = 500;
    unsigned long current_time = 0;
    #define PIN_RESET A6  // Connect RST to pin 9

    #define DC_JUMPER 0

    MicroOLED oled(PIN_RESET, DC_JUMPER);// I2C declaration

    const int buttonpin = A8;
    volatile int buttonState = 0;   // variable for reading the pushbutton status
    volatile int buttonState2 = 0;
    int buttonstate3 = 1;
    const int buttonpin2 = A7;

    enum State {flip, intro, option1, pattern1, intro_flip, option1_flipped, pattern1_flipped, pattern2, pattern3};
    //enum is the data type that consists of user defined varaibles ie like the words pattern, intro, ext
    State state = flip; //telling the intial state to start at intro

    unsigned int column_pattern1[] = {0b0000000100000100, 0b0000001000001000,0b0100000010000010};
    //unsigned int column_off_pattern1[]={0b0000000000000100, 0b00000000000001000,0b0100000000000010};
    const int css1 = 10;
    const int css2 = A0;
    void setup() {
      oled.begin();    // Initialize the OLED
      oled.clear(ALL); // Clear the display's internal memory
      //  oled.display();  // Display what's in the buffer (splashscreen)
      //  delay(1000);     // Delay 1000 ms
      oled.clear(PAGE); // Clear the buffer.
      //

      pinMode(css1, OUTPUT);
      pinMode(css2, OUTPUT);
      Serial.begin(9600);
      SPI.begin();
      SPI.beginTransaction(settingsA);

      pinMode(buttonpin, INPUT_PULLDOWN);
      pinMode(buttonpin2, INPUT_PULLDOWN);
      // watermark generates this interrupt
      attachInterrupt(buttonpin, button_pressed, FALLING); // interrrupt 1 is data ready
      //attachInterrupt(buttonpin2, button_pressed2, FALLING); // interrrupt 1 is data ready

    }

    void loop() {

      // blinking output 4 and 8 while using a finite state machine to change from intro to a patter
      //turning off the desplay when a pattern is chosen

      switch (state) {
        case flip:
        oled.setFontType(1);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print(" Flip  Screen?");
      oled.setFontType(0);
      oled.setCursor(0, 30);
      oled.print("yes");
      oled.setCursor(40, 30);
      oled.print("no");
      oled.circle(10, 43, 3.5);
      oled.circle(50, 43, 3.5);
      oled.display();
      buttonState = 0;

      if (digitalRead(buttonpin2) == HIGH) {
            oled.circleFill(50, 43, 3.5);
            oled.display();
            oled.clear(PAGE); // Clear the buffer.
            delay(500);
            //buttonstate3=0;
         state=intro;
      }
       if (digitalRead(buttonpin) != buttonState) {
        oled.circleFill(10, 43, 3.5);
         oled.display();
            oled.clear(PAGE); // Clear the buffer.
            delay(500);
            state=intro_flip;
       }
      break;

        case intro:

          oled.setFontType(1);
          oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
          //oled.setFontType(2);
          //  oled.setCursor(0, 0);
          oled.print("choose pattern");
          oled.circle(10, 40, 7);
          oled.display();
          buttonState = 0;

          if (digitalRead(buttonpin) != buttonState) {

            buttonState = 0; //reset button state
            oled.circleFill(10, 40, 7);
            oled.display();
            delay(500);
            state = option1;

          }
          break;

        case option1:
          oled.clear(PAGE); // Clear the buffer.

          //delay(300);
          oled.setFontType(0);
          oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
          //oled.setFontType(2);
          //  oled.setCursor(0, 0);
          oled.print("Pattern 1");
          oled.setCursor(0, 10);
          oled.print("next");
          oled.setCursor(40, 10);
          oled.print("yes");
          oled.circle(10, 40, 7);
          oled.circle(50, 40, 7);
          oled.display();

          if (digitalRead(buttonpin2) == HIGH) {
            Serial.println("right button pressed");

            oled.circleFill(50, 40, 7);
            oled.display();
            delay(500);
            state = pattern1;

          }
          break;
            case pattern1:
          oled.clear(PAGE);
          oled.display();

          patternONE();
          buttonState=0;
          if (digitalRead(buttonpin) != buttonState) {
            Serial.println("left button pressed");
            //         //delay to register that the button was pressed
            delay(500);
            //
            state = intro;
          }
          break;

    ////////////////////////////////////////////////////////
    ///////////FLIPPED FINITE STATE MACHINE/////////////////
    ////////////////////////////////////////////////////////

    case intro_flip:
      oled.flipVertical(true);
        oled.flipHorizontal(true);
         oled.setFontType(1);
          oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
          //oled.setFontType(2);
          //  oled.setCursor(0, 0);
          oled.print("choose pattern");
          oled.circle(50, 40, 7);
          oled.display();
          buttonState = 0;

          if (digitalRead(buttonpin) != buttonState) {

            buttonState = 0; //reset button state
            oled.circleFill(50, 40, 7);
            oled.display();
            delay(500);
            state = option1_flipped;

          }
          break;

          case option1_flipped:
    oled.flipVertical(true);
        oled.flipHorizontal(true);
          oled.clear(PAGE); // Clear the buffer.

          //delay(300);
          oled.setFontType(0);
          oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
          //oled.setFontType(2);
          //  oled.setCursor(0, 0);
          oled.print("Pattern 1");
           oled.setCursor(0, 10);
          oled.print("yes");
          oled.setCursor(40, 10);
          oled.print("next");
          oled.circle(10, 40, 7);
          oled.circle(50, 40, 7);
          oled.display();

          if (digitalRead(buttonpin2) == HIGH) {
            Serial.println("right button pressed");

            oled.circleFill(10, 40, 7);
            oled.display();
            delay(500);
            state = pattern1_flipped;

          }
          break;

           case pattern1_flipped:
          oled.clear(PAGE);
          oled.display();

          patternONE();
    //      buttonState=0;
          if (digitalRead(buttonpin) != buttonState) {
            Serial.println("left button pressed");
            //         //delay to register that the button was pressed
            delay(500);
            //
            state = intro_flip;
          }
          break;

      }
    }////////////////////////////////////////////////////////
    ///////////Pattern/////////////////
    ////////////////////////////////////////////////////////
    void patternONE() {
    buttonState = 0;
       unsigned int chip1 = 0;
      unsigned int chip2 = 0;
      byte inbyte = 0;
      byte inbyte2 = 0;

      for (int i = 0; i < 3; ++i) {

        digitalWrite(css2, LOW);
        chip2 = SPI.transfer16(column_pattern1[i]);
        Serial.print("chip2 column off=");
        Serial.println(chip2, BIN);
        digitalWrite(css2, HIGH);

        digitalWrite(css1, LOW);
        chip1 = SPI.transfer16(0b0001010000000000);
        Serial.print("chip1 row 8 on high driver= ");//not the chip is a look behind so the print statments are the previous output
        Serial.println(chip1, BIN);
        digitalWrite(css1, HIGH);

        delay(1);
        digitalWrite(css1, LOW);
        chip1 = SPI.transfer16(0b0100000100000000);
        Serial.print("chip1 row 4 and 6 on low driver= ");
        Serial.println(chip1, BIN);
        digitalWrite(css1, HIGH);

        delay(2000);

        digitalWrite(css1, LOW);
        chip1 = SPI.transfer16(0b0001010001010000);
        Serial.print("chip1 row 8 on low driver= ");
        Serial.println(chip1, BIN);
        digitalWrite(css1, HIGH);

        delay(1);

        digitalWrite(css1, LOW);
        chip1 = SPI.transfer16(0b0100000100000100);
        Serial.print("chip1 row 4 and 6 on high driver= ");
        Serial.println(chip1, BIN);
        digitalWrite(css1, HIGH);

        digitalWrite(css2, LOW);
        chip2 = SPI.transfer16(column_pattern1[i]);
        Serial.print("chip2 column on high driver= ");
        Serial.println(chip2, BIN);
        digitalWrite(css2, HIGH);

        //turn off the previous column
    //    digitalWrite(css2, LOW);
    //    chip2 = SPI.transfer16(column_off_pattern1[i]);
    //    Serial.print("chip2 column on high driver= ");
    //    Serial.println(chip2, BIN);
    //    digitalWrite(css2, HIGH);
    //
        delay(2000);

      }

    }

    // watermark generates this interrupt
    void button_pressed()
    {
      cli();
      //confirmitng that the button was pressed and that its not just like a bounce"
      if (millis() - prevTime > 50) {
        Serial.println("left button pressed");
        buttonState = 1;
      Serial.println("buttonState =");
      Serial.println(buttonState);
      }

      sei();
      prevTime = millis();

    }

title: trouble getting out of a for loop in a function and go back to a FSM with a button

Answers: 1

body:
From your question, it sounds like you are expecting PatternONE() to return on a button press but I don't see any code in the function that refers to a button or acts on one. The function defines a local variable `buttonState` and initializes it to 0, but never refers to it again.

I suspect you meant that as a declaration of the global `buttonState`, but you have two problems: 1) the function never uses buttonState to initiate a return; and 2) the local definition `buttonState` hides the global one while it is in scope; i.e., while the function is executing.


body:
board: Arduino Mega (ATMEGA2560)

I want to generate pulses using timer1 configured as Fast PWM, this is my code which works fine:

    #include <avr/io.h>

    int main(void)
    //void setup()
    {

      DDRB |= (1 << DDB5) | (1 << DDB6); // PWM outputs

      ICR1 = 0x7FFF;  // TOP
      OCR1A = 0x3FFF; // 50% of ICR1
      OCR1B = 0x3FFF; // 50% of ICR1

      TCCR1A |= (1 << COM1A1) | (1 << COM1B1);
      TCCR1A |= (1 << WGM11);
      TCCR1B |= (1 << WGM12) | (1 << WGM13);
      TCCR1B |= (1 << CS10);

    }

    void loop() {

    }

I don't understand why it doesn't work if I use `void setup()` instead of `int main(void)`. I'm working with arduino IDE 1.8.2 and always used void setup(), in this case I used int main(void) because it is used in some turorials I found like this one: [https://www.youtube.com/watch?v=O_Yqf_cugwE][1]

  [1]: https://www.youtube.com/watch?v=O_Yqf_cugwE

EDIT: When I say that it doesn't work, what happens is that instead of having PWM signals I just have a constant 5V output in both OC1A and OC1B pins

title: Fast PWM working with int main(void) but not with void setup()

Answers: 1

body:
If you don't define your own `main()`, your program will be linked with
the `main()` provided by the Arduino core library, which roughly looks
like this (I am simplifying a little bit):

<!-- language-all: lang-c++ -->

    int main(void)
    {
        init();      // Arduino core initialization
        setup();     // user's initialization
        for (;;)
            loop();  // user's main loop
    }

The [core's `init()` function][init] configures Timer 1 for 8-bit phase
correct PWM at 490 Hz, which means that, by the time your `setup()`
runs, the timer's control registers are not in their default state
anymore, and some of their bits are already set to 1. If you then
update these registers using the `|=` operator, you end up with a mix of
the core's configuration and your own.

This can be fixed either by zeroing these registers first or, more
simply, by setting their values with the `=` operator, which has the
effect or setting _every_ bit of those registers to the value you want.

The following works whether you use or not the Arduino core library:

    #ifdef NOCORE
    int main(void)
    #else
    void setup()
    #endif
    {
        DDRB   = _BV(PB5) | _BV(PB6);
        TCCR1A = _BV(COM1A1)
               | _BV(COM1B1)
               | _BV(WGM11);
        TCCR1B = _BV(WGM12)
               | _BV(WGM13)
               | _BV(CS10);
        ICR1   = 0x7fff;  // TOP
        OCR1A  = 0x3fff;  // 50% of ICR1
        OCR1B  = 0x3fff;  // 50% of ICR1
    }

    #ifndef NOCORE
    void loop(){}
    #endif

Note that:

1. The control registers are _set_ (`=`) rather than just modified with
`|=`
2. The mode is set before the output compare registers. This is because
setting the output compare registers does not work well when the timer
is in an 8-bit mode.

[init]: https://github.com/arduino/Arduino/blob/1.8.2/hardware/arduino/avr/cores/arduino/wiring.c#L241


body:
I'd like to alter the "LED_T_ON" values using an I2C enabled device (i.e. RPi)

Code for Arduino Mega slave:

    //slave

    #include <Wire.h>

    #define SLAVE_ADDRESS 0x08

    const int PWR_LED = 43;
    int LED_TinH_ON = 18;
    int LED_T_ON = 5000;
    int LED_T_OFF = 5000;

    String inString = "";    // string to hold input
    byte LastMasterCommand = 0;
    int Mval;

    char user_input;

    class Relay {
      int relayPin;
      long OnTime;     // milliseconds of on-time
      long OffTime;    // milliseconds of off-time

      // These maintain the current state
      int relayState;                 // pumpState used to set the PUMP
      unsigned long previousMillis;   // will store last time PUMP was updated

      // Constructor - creates a Timer and initializes the member variables and state
      public:
      Relay(int pin, long on, long off)
      {
        relayPin = pin;
        pinMode(relayPin, OUTPUT);

        OnTime = on;
        OffTime = off;

        relayState = LOW;
        previousMillis = 0;  //ORIGINALLY 0
      }

      void Update()
      {
        // check to see if it's time to change the state of the TIMER
        unsigned long currentMillis = millis();

        if((relayState == HIGH) && (currentMillis - previousMillis >= OnTime))
        {
          relayState = LOW;  // Turn it off
          previousMillis = currentMillis;  // Remember the time
          digitalWrite(relayPin, relayState);  // Update the actual LED
        }
        else if ((relayState == LOW) && (currentMillis - previousMillis >= OffTime))
        {
          relayState = HIGH;  // turn it on
          previousMillis = currentMillis;   // Remember the time
          digitalWrite(relayPin, relayState);   // Update the actual RELAY
        }
      }
    };

    Relay relay3(PWR_LED, LED_T_OFF, LED_T_ON);

    void setup() {
     // initialize serial communication with computer:
      Serial.begin(9600);

      Wire.begin(SLAVE_ADDRESS);

      Wire.onReceive(receiveData);
      Wire.onRequest(slavesRespond);

      pinMode(PWR_LED, OUTPUT);
    }

    void loop() {
      delay(1000);

      Serial.print("LED_T_ON=");
      Serial.println(LED_T_ON);
      Serial.print("LED_T_OFF=");
      Serial.println(LED_T_OFF);
      Serial.println();

      relay3.Update();

      switch (Mval) {
        case 1 ... 25:
          LED_TinH_ON = Mval;
          Serial.print("LED time on: ");
          Serial.print(LED_TinH_ON);
          Serial.println("h");
          LED_T_ON = LED_TinH_ON*1000;//*60*60;
          LED_T_OFF = (24-LED_TinH_ON)*1000;//*60*60;
        break;
      }
    }

    void receiveData(int byteCount) {
      LastMasterCommand = Wire.read();
      while (Wire.available()) {
        int msg = Wire.read();

        if (isDigit(msg)) {
          inString += (char)msg;
        }
      }
      Mval = inString.toInt();
      //Serial.println(LastMasterCommand);
      inString = "";
      //Serial.println(Mval);
    }

    void slavesRespond() {
    }

When I change the value on the RPi the Arduino receives and displays the correct value but the timed relays don't actually use the updated values.

Am I missing something?

title: Change values of timer using I2C

Answers: 1

body: Your updating `LED_T_ON` and `LED_T_OFF` but those values were already passed into the constructor and changing them will not change the object. you need to update  `relay3.OnTime` and `relay3.OffTime`


body:
I am using this TI device TCA9539 (http://www.ti.com/lit/ds/symlink/tca9539.pdf) with the pins A1 and A0 tied to ground resulting the write address to 0x74.

[![Image of the Address Byte][1]][1]

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

I don't have any issues writing to this device address and perform the necessary functions, however when I try to read registers using Arduino read functions, getting NACK there. Is 0x75 correct read address?

For second question:

Based on the device spec for read operation:

> Reading from a slave is very similar to writing, but requires some additional steps. In order to read from a slave,
the master must first instruct the slave which register it wishes to read from. This is done by the master starting
off the transmission in a similar fashion as the write, by sending the address with the R/W bit equal to 0
(signifying a write), followed by the register address it wishes to read from. When the slave acknowledges this
register address, the master sends a START condition again, followed by the slave address with the R/W bit set
to 1 (signifying a read). This time, the slave acknowledges the read request, and the master releases the SDA
bus but continues supplying the clock to the slave. During this part of the transaction, the master becomes the
master-receiver, and the slave becomes the slave-transmitter.
The master continues to send out the clock pulses, but releases the SDA line so that the slave can transmit data.
At the end of every byte of data, the master sends an ACK to the slave, letting the slave know that it is ready for
more data. When the master has received the number of bytes it is expecting, it sends a NACK, signaling to the
slave to halt communications and release the bus. The master follows this up with a STOP condition."

This is the code I am trying to use,

    Wire.begin();
    Wire.beginTransmission(0x74); // start i2c transmission as write addr
    Wire.write(0x01)              // the register i need to read from
    Wire.beginTransmission(0x75); // start i2c transmission as read addr given

I believe the device I2C read and arduino library functions for read is not making sense to me. Has anyone used this device for read?

title: I2C Read Operation in TCA9539

Answers: 2

body:
The arduino i2c libraries expect a 7 bit slave address, not 8 bit address + r/w bit, and will manage the read write bit internally based on if you do a write or read.

So begin transmission 0x74

Write 0x01

End transmission

Begin transmission 0x74

Read n

End transmission

body:
You have misunderstood, how the `Wire` library works. It is doing all the things with the direction bit for you.

**Write Operation:**

 - `Wire.beginTransmission()` takes a 7-bit address as a parameter. The direction bit is automatically and internally set to write operation.
 - `Wire.write()` writes a value to the library-internal buffer, but is not doing anything on the actual I2C bus
 - Finally you call `Wire.endTransmission()` to finally do the write operation on the actual I2C bus. Prior to this function call the library doesn't do anything on the bus. So you have to call it, so that the data can reach the slave device

**Read Operation:**

- For reading from a slave device there is an extra function: `Wire.requestFrom()`. It takes the (7-bit) address and the number of requested bytes as parameters and it returns the number of bytes, that were actually read from the slave device (is important if the slave is sending less data, than requested). After a call to this function, the read bytes are now lying in the library-internal buffer.
- To get the received bytes from the library-internal buffer, you have to use `Wire.read()`. Again it does not do anything on the I2C bus. It just reads from the internal buffer.

---
So for your code you need to send a command byte to the slave, that says, what registers of the slave (determinded by the lowest three bytes, as the datasheet says) you want to access next. After that you can either send more bytes (in order to write the chosen registers) or you can start a request, so that the slave will send you the current state of the selected register.

Look at this images from pages 23 and 24 of the datasheet:
[![enter image description here][1]][1]

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

These are showing exactly, what you have to send. Note that the address byte is automatically send by the `Wire` library, so you don't have to do it. I will put it in code for you:

**Write operation:**

    Wire.begin();
    Wire.beginTransmission(slave_address);
    Wire.write(register_address);
    Wire.write(new_register_data);
    Wire.endTransmission();

The register address is documented in the datasheet. In this case it is the register with address 0x01 (Though this makes no sense, since this is a read-only register).

**Read operation**

    Wire.begin();
    Wire.beginTransmission(slave_address);
    Wire.write(register_address);
    Wire.endTransmission();
    if(Wire.requestFrom(slave_address,1) > 0 ){
        byte data = Wire.read();
    }

Here we first do a write operation to tell the slave, what register we want to access. Then we request the data in this register with `Wire.requestFrom()`. To transfer from the internal buffer to our program is done with the `Wire.read()` function (but only, if there was actually something received).

---
For the address of the slave device: This depends on how you have set the pins A0 and A1. You can find a table with the corresponding addresses at page 21 of the datasheet. Note that these are NOT including the data direction bit. When you are using the `Wire` library, you don't have to bother about it.

  [1]: https://i.stack.imgur.com/iOk9e.png
  [2]: https://i.stack.imgur.com/9JEGM.png


body:
I’m trying to wrap my head around using binary addresses in a mux. Failing miserably.
For the circuit I have six 16 channel analog multiplexers CD74HC4067 as slaves to an eight channel multiplexor CD54HC4051 master.
They are bringing in 96 sensor readings (IR receiver diodes through Op Amps) into an array
that, in turn,  is used to constantly update lotsa LEDs through a series of shift registers (TLC5940) using the Arduino TLC5940 Library.

I’ve included the possible wiring scheme that the code is trying to control.
It probably needs work too.[![enter image description here][1]][1]

Question: I’ve seen, and SEMI-understand matrixes that address 32 inputs
(4 x 8 bits) but not quite understanding how I can address the six mux chips
with 96 inputs. Or if I can even do it this way. Example from this forum: https://arduino.stackexchange.com/questions/28134/how-to-code-for-cascading-multiplexers
Is it possible with this matrix of 96 inputs, and how? Am I barking up the wrong tree?

Code so far:

        #include <Tlc5940.h> //Arduino TLC5940 Library controls the individual LEDs - "Pixels"

    int ledCount = 96; //change  LED "PIXEL" count in matrix...also number of IR sensor inputs

    int thresh = 10; //value for usable distance reading from IR

    // main structures to hold LED Pixel array on/off state, IR reciever readings
    byte dsply_state[ledCount];    //pixel on-off grid, need for tlc5940
    uint_16  recv_state[ledCount];           // IR Readings - FROM mux set-up

    // Master IR -mux sensor pins for Arduino Pro MINI
    #define  M_S0 2
    #define  M_S1 4
    #define  M_S2 5
    // Slave IR mux sensor pins
    #define  S_S0 6
    #define  S_S1 7
    #define  S_S2 8
    #define  S_S3 12

    //  ANALOG PIN :
    #define  InputFromMux A0

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

        //tlc5940 Arduino library
        Tlc.init(0);

        // CONFIGURE ADDRESS PINS
        pinMode(M_S0, OUTPUT);
        pinMode(M_S1, OUTPUT);
        pinMode(M_S2, OUTPUT);

        pinMode(S_S0, OUTPUT);
        pinMode(S_S1, OUTPUT);
        pinMode(S_S2, OUTPUT);
        pinMode(S_S3, OUTPUT);
        pinMode(InputFromMux, INPUT);

    }

    void loop() {
        // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER and SLAVES.

      for (int i = 0; i < ledCount; i++) {

        digitalWrite(M_S2, i & 0b1000000);
        digitalWrite(M_S1, i & 0b0100000);
        digitalWrite(M_S0, i & 0b0010000);
        digitalWrite(S_S3, i & 0b0001000);
        digitalWrite(S_S2, i & 0b0000100);
        digitalWrite(S_S1, i & 0b0000010);
        digitalWrite(S_S0, i & 0b0000001);

        delay(2);

        //edited as per @Gerben. thanks so much

        //get an individual sensor reading from IR receiver/opAmp mux, store it in a variable
         int IRstate = analogRead(InputFromMux);

        //populate receiving array with a reading
         recv_state[i] = IRstate;

        //populate display array for tlc5940 to push out
         dsply_state[i] = recv_state[i];

    } //end for(i...) loop

          //run through display state array to check if the stored reading is greater than a threshold number
          //if yes, then turn on the "pixel". If not, set it to zero
          //

           for (int x = 0; x < ledCount; x++)
              if (dsply_state[x] >= thresh ) {

                   Tlc.set(dsply_state[x], 4000);

                 //or if reading from mux is zero
              } else if (dsply_state[x] < thresh) {

                  Tlc.set(dsply_state[x], 0);
                  }

                //tlc5940 Arduino library - update() clocks the chips
                // move update(); outside the for(x...) loop for speed?
            Tlc.update();
            delay(10);

          } //end For(x..) Loop

    }//endMainLoop

  [1]: https://i.stack.imgur.com/zcnUZ.gif

title: Binary addressing and coding to control a 96 input mux matrix

Answers: 1

body:
OK. First, how the multiplexer works. I have [a page about multiplexers](http://www.gammon.com.au/forum/?id=11976) in which there is this example of the 74HC4051:

 [![CD4051][1]][1]

Depending on the "binary" input to A/B/C (shown as S0/S1/S2 on your schematic) there is a low resistance path between one of the 8 inputs and the single output. The CD74HC4067 works in a similar way, except it switches 16 inputs.

So, if you set up the binary number 2 (010) in A/B/C then the third input is selected (number 02 because it is zero-relative).

In your schematic you have 6 x CD74HC4067 which therefore can have 16 x 6 inputs (96 inputs in total). The outputs of those 6 are fed into the 54HC4051 (2 aren't used) so therefore the 54HC4051 can select which of the 6 16-input chips it is interested in right now, by setting up a number between 0 and 5 on the 8-input multiplexer.

The four binary inputs to the 6 x CD74HC4067 are all tied together as you can see on the schematic.

Thus your method would be:

* Loop from 0 to 5 on the master multiplexer (the 54HC4051). This selects which of the 6 16-input multiplexers you are interested in right now.

* For each of those, loop through 0 to 15 on S0/S1/S2/S3 so that the currently-selected CD74HC4067 routes its input through to its output.

* Read the resulting value

Those two loops will give you 96 inputs, which is what you are trying to read.

This technique takes 7 output pins to output the binary numbers (3 bits plus 4 bits). It also needs one input pin to read the result.

---

Judging by the schematic it uses SPI (serial data) to control the 6 x TLC5940 shift registers which lets it turn LEDs on and off with only two control pins (SCK and MOSI named SCLK and SOUT on your schematic).

The chips are daisy-chained together so all of those TLC5940s are controlled by those two pins.

This fairly minimalist design has therefore left some spare pins on the Arduino Pro.

---

> Mostly having a hard time visualizing the code, especially how to write correctly the 7 binary digital write commands. Is it possible for you to correct what I've written above, so I might be able to see the pattern?

I know you changed the question by the time I saw this, but the code below illustrates what I mean by the two loops:

<!-- language: lang-c++ -->

    const int MUX_CHIPS = 6;
    const int LEDS_PER_CHIP = 16;
    const int TOTAL_IR_INPUTS = MUX_CHIPS * LEDS_PER_CHIP;
    // Master IR -mux sensor pins for Arduino Pro MINI
    const byte  M_S0 = 2;
    const byte  M_S1 = 4;
    const byte  M_S2 = 5;
    // Slave IR mux sensor pins
    const byte  S_S0 = 6;
    const byte  S_S1 = 7;
    const byte  S_S2 = 8;
    const byte  S_S3 = 12;
    //  ANALOG PIN :
    const byte INPUT_FROM_MUX = A0;

    int  recv_state[TOTAL_IR_INPUTS];           // IR Readings - FROM mux set-up

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

        // CONFIGURE ADDRESS PINS
        pinMode(M_S0, OUTPUT);
        pinMode(M_S1, OUTPUT);
        pinMode(M_S2, OUTPUT);

        pinMode(S_S0, OUTPUT);
        pinMode(S_S1, OUTPUT);
        pinMode(S_S2, OUTPUT);
        pinMode(S_S3, OUTPUT);
        pinMode(INPUT_FROM_MUX, INPUT);

        // set ADC prescaler of 32
        ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
        ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
    } // end of setup

    void loop() {

      unsigned long start = micros ();

      // read from IR diodes

      int whichLED = 0;
      for (byte master = 0; master < MUX_CHIPS; master++)
        {
        // select appropriate slave on the master MUX
        digitalWrite(M_S2, (master & 0b100) ? HIGH : LOW);
        digitalWrite(M_S1, (master & 0b010) ? HIGH : LOW);
        digitalWrite(M_S0, (master & 0b001) ? HIGH : LOW);

        // take each slave reading
        for (byte slave = 0; slave < LEDS_PER_CHIP; slave++)
          {
          digitalWrite(S_S3, (slave & 0b1000) ? HIGH : LOW);
          digitalWrite(S_S2, (slave & 0b0100) ? HIGH : LOW);
          digitalWrite(S_S1, (slave & 0b0010) ? HIGH : LOW);
          digitalWrite(S_S0, (slave & 0b0001) ? HIGH : LOW);

          // store this reading
          recv_state [whichLED++] = analogRead (INPUT_FROM_MUX);

          } // end of for each slave
        } // end of for each master

      // display results here ...

    } // of loop

The exact code above took 5148 µs (around 5 ms) to execute the loop once on my Uno. If we remove the speedup of the ADC (analogRead) it takes 13252 µs (13 ms).

To allow for your exact wiring you need to ignore the low-order bit on the master MUX because you are not using input A0_13 in which case you need to add 2 to the master value in the outer loop:

<!-- language: lang-c++ -->

        // select appropriate slave on the master MUX
        byte master_plus_2 = master + 2;  // allow for not using input A0
        digitalWrite(M_S2, (master_plus_2 & 0b100) ? HIGH : LOW);
        digitalWrite(M_S1, (master_plus_2 & 0b010) ? HIGH : LOW);
        digitalWrite(M_S0, (master_plus_2 & 0b001) ? HIGH : LOW);

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


body:
I bought an Arduino pro micro (looks like [this][1]) from a Chinese seller over E-Bay, for its HID interface.

I installed the Arduino software on my Linux machine (Kali Linux), and started writing a USB Rubber Ducky script, and converted it to Arduino using [Dckuino.js][2], which usually works just fine.

I may have used either:

* The wrong programmer, or
* The wrong board type

because when I uploaded the sketch, it said it failed, but HID script still worked when I plugged it into my Mac.

The Mac came up with a `Keyboard Assistant`, because it couldn't recognize the keyboard being use. So I plugged it back into my Linux machine, and it wouldn't recognize.

* `lsusb` and `dmesg -w` didn't show any updates when re-plugging the Arduino.
* Changing USB chords didn't work.
* Switching over to windows, `Device Manager` didn't do the normal "refresh" when you plug in a new device, and there was nothing under `COM Ports`.
* The HID input didn't work on the Mac anymore, when plugging it in again.
* The inbuilt LED lights up when connected.

Is this a brick?
I can't seem to find any `reset` button or header on the board, so I cant connect the ground and reset.
There is an `RST` header, but I don't know what that is.

Any help would be greatly appreciated!

  [1]: https://www.bazaargadgets.com/image/cache/catalog//products/electronics/arduino/ATMEGA32U4MiniUSBDevelopmentBoardForArduinoLeonardo-SKU207354-2-800x800.jpg
  [2]: https://seytonic.com/ducky/

title: Arduino pro micro might be bricked

Answers: 0


body:
    #include <LiquidCrystal.h>
    #include <SoftwareSerial.h>
    #include <Keypad.h>

    const byte ROWS = 4; //four rows
    const byte COLS = 4; //three columns
    char keys[ROWS][COLS] = {
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'E'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };
    int count = 0; char num[4];
    char key;
    byte rowPins[ROWS] = {A0, A1, A2, A3}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

    char adhaar[4][4] = {
      {'1', '0', '8', '3'},
      {'9', '1', '6', '0'},
      {'5', '7', '6', '1'},
      {'6', '7', '9', '3'}
    };

    char adhaar0[4] = {'1', '0', '8', '3'};
    char adhaar1[4] = {'9', '1', '6', '0'};
    char adhaar2[4] = {'5', '7', '6', '1'};
    char adhaar3[4] = {'6', '7', '9', '3'};
    boolean check, control, adhar, tag_status;
    int i = 0, j, p, q;

    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
    void setup() {
      Serial.begin(9600);
      Serial.println(" enter your adhaar ");
    }

    void loop() {
      getkey();
      checkkey();
    }

    void getkey() {
      while (i < 4) {
        char key = keypad.getKey();
        if (key) {
          num[i] = key;
          Serial.print(num[i]);
          i++;
        }
      }
    }

    void checkkey() {
      if (i == 4) {
        control = true;
        for (p = 0; p < 4; p++) {
          for (q = 0; q < 4; q++) {
            if (adhaar[p][q] == num[q]) {
              check = true;
              Serial.println(num[q]);
            } else {
              check = false;
              Serial.println(" not eligile");
              break;
            }
          }
          if (check == true) {
            adhar = true;
            Serial.println(" cast your vote");
          }
        }
        i = 0;
      }
    }

My problem is once the adhaar matches with the values initialised in the array I have, it's going to "cast your vote" as expected, but after that it's again executing "not eligible" 3 times.

title: Code output is not as expected

Answers: 1

body:
First, a general remark: most of your variables are never used. You
should get rid of them, as they only serve to make your code more
obscure.

Then, the reason for the observed behavior is that you are comparing the
entered code with 4 predefined codes. Whatever the user enters, there
will be at least 3 non-matches, hence 3 times the program prints “not
eligile”.

To get the behavior you expect, I would get rid all all those boolean
variables that make the logic hard to follow, and instead break down the
problem into smaller chunks, each implemented in its own small function.
This makes it easier to write code that is easy to understand.

First, how do you tell whether two 4-character codes are the same? Like
this:

<!-- language-all: lang-c++ -->

    // Do codes a and b match?
    bool match(char a[4], char b[4]) {
        for (int i = 0; i < 4; i++) {
            if (a[i] != b[i])
                return false;
        }
        return true;
    }

Then, given a code entered by the user, tell whether it matches
`adhaar[0]` or `adhaar[1]` or... or none of them:

    // Return the adhaar index matching the given key,
    // or -1 if there is no match.
    int matching_idx(char key[4]) {
        for (int i = 0; i < 4; i++) {
            if (match(key, adhaar[i]))
                return i;
        }
        return -1;  // no match
    }

Now your `checkkey()` function can be rewritten as follows:

    void checkkey() {
        if (i != 4) return;  // should never happen
        if (matching_idx(num) == -1)
            Serial.println(" not eligile");
        else
            Serial.println(" cast your vote");
        i = 0;
    }


body:
I am working on a project to calculate line frequency meter by reciprocal counting with Arduino. I am trying to print the the result on a 16*2 LCD but it is not displaying anything. It just gets on and stuck there. I got the project details from this website [Line Frequency Meter Based On Reciprocal Counting][1]

  [1]: https://electronicsforu.com/electronics-projects/line-frequency-meter-reciprocal-counting

I modified the stock program to interface the LCD but it's not working. Here is the code I am using:

    //To read and display the Line frequency
    //using Reciprocal counting method
    //clk for 'Time Counter'  is generated with 'Tone' function
    //'Time counter' is the physical counter T1
    // 'EVENT Counter' is a software counter
    #define Fin 6      // input pin for Line freq sig
    #define clk 7      // input to ' Time ' counter
    #include<LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    boolean FState;   // status of the 50 Hz Signal
    int countS;       // Signal count
    int countC=0;     //  Clock count
    int LineFreq;     // Result

    void setup() {
      tone(8, 5000); // generates ref freq of 5000 Hz at Pin 8
      pinMode(Fin, INPUT); // set the Fin pin as INPUT
      pinMode(clk, INPUT); // set the clk pin as INPUT
      lcd.begin(16, 2);
    }

    void loop() {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Frequency of signal");
      // to avoid partial cycles, first detect the rising edge
      while(digitalRead(Fin)) {
        //wait for '0' state of the Signal
        delayMicroseconds(10);
      }
      //here '0' state
      while(!digitalRead(Fin)) {
        //wait for '1' state
        delayMicroseconds(10);
      }
      //this is the rising edge of the Fin
      //counting can start from here
      // clear the TIME Counter T1
      counterStart1();
      //count 50 of the Line freq signals
      while(countS<50) {
        while(digitalRead(Fin)) {
          //wait for '0' state
          delayMicroseconds(1);
        }
        //here '0' state
        while(!digitalRead(Fin)) {
          //wait for '1' state
          delayMicroseconds(1);
        }
        // here '1' state
        // here one cycle is just over
        //increment the event counter
        countS=countS+1;
      }
      //here 50 Signal cycles over
      // read the contents of T1 & compute frequency
      countC = getCount1();
      LineFreq = 25000000/countC;

      //send to display
      lcd.setCursor(0,1);
      lcd.print(LineFreq);
      lcd.print(" Hz");
      delay(500);
      delay(100);
      // clear counter
      countS=0;
      // repeat
    }

    //The following code is obtained from on-line articles in the public domain
    void counterStart1() {
     // hardware counter setup,  for  the 16-bit Timer1 Timer/Counter
     TCCR1A=0; // reset timer/countern control register A
     TCCR1B=0; // reset timer/countern control register B
     TCNT1=0; // initialize the counter value to 0; this register holds the current count
      // set timer/counter1 hardware as a counter; it counts events on pin Tn (Arduino pin 5)
     TCCR1B = TCCR1B | 7; // Counter Clock source = pin Tn (Arduino pin 5) , start counting now
     // 7 in binary is 0111; OR-ing will set CS10,11,12 to 1's
    return;
    }

    // the following code is obtained from on-line articles in the public domain
    // Sub routine  to get the current count
    unsigned int getCount1() {
     unsigned int count; // this variable returns the current count from the counting register
     TCCR1B = TCCR1B & ~7; // Gate Off  / Counter T1 stopped,
     // this operation clears the bits (CS10,11,12)
     count = TCNT1; // read the counting register
     TCCR1B = TCCR1B | 7; // re-start counting by resetting the bits (CS10,11,12)
     return count; // return the retrieved count to the calling function
    }

I am getting a blank screen but the line at very first of the code "Frequency of signal" is printing accurately.

What is wrong with the code and what changes do I need?

Thanks in advance!

title: 16*2 LCD display doesn't display my result

Answers: 1

body:
Your variables are `int`, which on an Arduino is a 2-byte signed type by default, and has a range of `-32768` to `32767`.

When you execute:

    LineFreq = 25000000/countC;

is the result of the math a 2-byte `int`, or a 4-byte `long`? Regardless, you are possibly assigning a 4-byte value to an `int`.

You can declare `LineFreq` to be type `long`, and also append an `L` to the end of the constant value `25000000` to force `long` math, so that you have:

    long LineFreq;
    [...]
    LineFreq = 25000000L/countC;


body:
I'm using NodeMCU 0.9
My sketch crashes if the following 2 include are present in the sketch:

    #include <PubSubClient.h>
    #include <HX711.h>

I obtain a `Soft WDT reset`

If I do not use HX711 I can send message using mqtt.
If I do not use PubSubClient I can read weight values from the load cell connected to the hx711 board without problem

The code crashes at the following line:

    mqtt_client.connect("ESP8266Client", mqtt_user, mqtt_password)

Actually using [this debugger][1] suggested [here][2] the line that crashes is the following and it is inside the PubSubClient class:

    WiFiClient::available()

It is a function already existing at `~/.arduino15/packages/esp8266/hardware/esp8266/2.4.1/libraries/ESP8266WiFi/src/WiFiClient.cpp line 21`

Here I paste my code so you can reproduce it and tell me if you have the same problem:

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

    #define wifi_ssid "mqtt"
    #define wifi_password "testmqtt"

    #define mqtt_server "THE.IP.OF.MQTT"
    #define mqtt_user "USER"
    #define mqtt_password "PSW"

    #define humidity_topic "sensor/humidity"
    #define temperature_topic "sensor/temperature"
    #define weight_topic "sensor/weight"

    WiFiClient espClient;
    PubSubClient client(espClient);

    void setup() {
      Serial.begin(9600);
      setup_wifi();
      client.setServer(mqtt_server, 1883);
    }

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

      WiFi.begin(wifi_ssid, wifi_password);

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

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

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        // If you do not want to use a username and password, change next line to
        // if (client.connect("ESP8266Client")) {
        if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
          Serial.println("connected");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }

    long lastMsg = 0;
    float temp = 0.0;
    float hum = 0.0;
    float diff = 1.0;

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

      long now = millis();
      if (now - lastMsg > 1000) {
        lastMsg = now;

        float newTemp = 456;
        float newHum = 123;

        temp = newTemp+1;
        Serial.print("New temperature:");
        Serial.println(String(temp).c_str());
        client.publish(weight_topic, String(temp).c_str(), true);
      }
    }

It works if you comment the initial include

PS: Nothing change if HX711 is include as `<...>` or `"..."`

  [1]: https://github.com/me-no-dev/EspExceptionDecoder
  [2]: https://arduino.stackexchange.com/questions/51906/mqtt-not-working-on-esp8266-nodemcu-0-9

title: Soft WDT with HX711 and PubSubClient libraries

Answers: 0


body:
I have a SPST switch and I just want to sense whether it's on or not. I will then turn on/off a relay depending on the state of this switch.

The two options I'm considering are: create a digital out on a pin going to one side of the switch, and read the digital in on another pin off the other side of the switch. Or put 5v from my voltage regulator to the switch, and read a digital in off the other side of the switch.

Would a resistor be necessary for the digital in pin with either of these options?

title: SPST switch - powered from pin output, or voltage regulator

Answers: 2

body:
You could configure one of the digital pins as INPUT_PULLUP and connect one end of the switch to it. The other end of the switch goes to ground. LOW = switch ON, HIGH = switch OFF.

<!-- language: lang-c++ -->

    const byte pinNumber = 3;

    void setup(){
      pinMode(pinNumber, INPUT_PULLUP);
    }

    void loop(){
    }

body: It is wasting of IO pins to use the digital output pin just to get +5V rail. But both options will work. Don't forget to use [pull/up or pull/down resistor](https://www.arduino.cc/en/Tutorial/Button), or activate [internal pull/up resistor](https://www.arduino.cc/en/Tutorial/DigitalPins) on the sensing pin. When the switch will be open, the input pin is not connected anywhere and will act as antenna, so it might pick up some noise.