message:
Arduino Timer 1 Library manipulate Timer value

I'm using Timer1 library for generation of pulse.
But in my code, at some places i need to change the timer values.
Can anyone suggest the ways to do it.

In below code in place of 370000, I need to change the value after getting some inputs in conditional loops.
Ex. if (x==1) Timer value should be 370000 else 185000.

```
#include <TimerOne.h>

int count = 0;
int LED = 13;

void setup() {
 pinMode(LED, OUTPUT);
 Timer1.initialize(370000);
 Serial.begin(9600);
}

void loop() {
 Serial.print("Count Value: ");
 Serial.println(count++);
}

body:
When you look into TimerOne.h, which is the header file for the TimerOne library, you can see [at line 55][1] the method

    void setPeriod(unsigned long microseconds)

which can be used to set the period of the timer at any time in your program. The method `TimerOne.initialize()` also calls this method to set the timer period.

  [1]: https://github.com/PaulStoffregen/TimerOne/blob/ce0fa0b7965f189925d8b7dbba49d562f7c0a4b3/TimerOne.h#L55


sender: user

message:
Data in two 8 bit shift registers won't change

I'm trying to output 16 bits of data to two 8 bit shift registers (74HC595), which drive a 8x8 led matrix. There is a problem with the way the code outputs data to the registers, its like no data is even shifted onto them. The first 8 bits handle the rows and the last 8 bits handle the columns.

I have already written this code in Arduino, but I am trying to re-write in it C (we have to learn AVR programming in C for college). The Arduino version works fine, so I know the circuit is correct. I'm using Atmel Studio.

For example, I replaced all the `digitalWrite(clockPin, HIGH)`'s with `PORTD = PORTD | (1<<clockPin)`.
But I can't get anything to output with my code.
For refreshing the led display the variable `refreshFlag` is used. For updating the game state (which hasn't been implemented yet) the variable `updateFlag` is used.

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <stdlib.h>

    //portd 2(latch), 4(clock), 7(data). Same as pins on arduino board
    #define latchPin 2
    #define clockPin 4
    #define dataPin 7

    //functions
    void init_ports(void);
    void init_USART(void);
    void init_timer0(void);
    void sendmsg (char *s);
    void drawData(uint8_t myData[]);
    void shiftOut(uint8_t myDataOut);

    unsigned char qcntr = 0,sndcntr = 0;   /*indexes into the queue*/
    unsigned char queue[100];       /*character queue*/

    int updateTimeCount;
    int updateDelay;
    int updateFlag; // Flag for updating game state
    int refreshFlag;// Flag for refreshing display

    uint8_t data[] = {0b00000001,
                      0b01111110,
                      0b11000110,
                      0b01001010,
                      0b01010010,
                      0b11100010,
                      0b01111110,
                      0b01000010};

    int main(void) {
     //init_USART();// Serial for debugging purposes
     init_ports();
     init_timer0();
     clearData();
     newBlock();

     sei();

     PORTB = 0; //PortB for debugging
     updateTimeCount = 0;
     updateDelay = 13; // Game updates every 13* 16ms = 208ms.
     updateFlag = 0;
     refreshFlag = 0; // Display updates every 16ms

     while (1) {

      if(updateFlag) { //updates game state
                PORTB = (1<<5); //debugging led
       updateFlag = 0;
      }

      if(refreshFlag) { //refreshes display
       drawData(data); //output data array

       refreshFlag = 0;
      }
     }
     return 0;
    }

    void drawData(uint8_t myData[]) { //takes data and outputs it
      for (uint8_t j = 0; j <= 7; j++) {

        //ground latchPin and hold low for as long as you are transmitting
     PORTD = PORTD & ~(1<<latchPin); //latch pin low

        //shift data into regs

        shiftOut(~(1<<j)); //grounds row. For example 10111111 means 6th row is on

        shiftOut(myData[j]);  //outputs column data.

        //return the latch pin high to signal chip that it
        //no longer needs to listen for information
     PORTD = PORTD | (1<<latchPin); //latch pin high
      }
    }

    void shiftOut(uint8_t myDataOut) { //shifts 8 bits out to register

      // This shifts 8 bits out LSB first,
      //on the rising edge of the clock,
      //clock idles low

    //internal function setup
      uint8_t i=0;
      int pinState;

    //prepare shift register for bit shifting
      PORTD = PORTD & ~((1<<dataPin) | (1<<clockPin)); //clock & data pin low

      //for each bit in the myDataOut
      for (i=0; i<=7; i++)  {

     PORTD = PORTD & ~(1<<clockPin); //clock low

        //if the value passed to myDataOut and a bitmask result
        // true then... so if we are at i=6 and our value is
        // 010100 it would the code compares it to 000000
        // and proceeds to set pinState to 1.
        if ( myDataOut & (1<<i) ) {
          pinState= 1;
        }
        else {
          pinState= 0;
        }

        //Sets the pin to HIGH or LOW depending on pinState
     PORTD = PORTD | (pinState<<dataPin);

        //register shifts bits on upstroke of clock pin
     PORTD = PORTD | (1<<clockPin);

        //zero the data pin after shift to prevent bleed through
     PORTD = PORTD & ~(1<<dataPin);
      }

      //stop shifting
      PORTD = PORTD & ~(1<<clockPin);
    }

    void sendmsg (char *s) { //create serial message
     qcntr = 0;    /*preset indices*/
     sndcntr = 1;  /*set to one because first character already sent*/

     queue[qcntr++] = 0x0d;   /*put CRLF into the queue first*/
     queue[qcntr++] = 0x0a;
     while (*s)
     queue[qcntr++] = *s++;   /*put characters into queue*/

     UDR0 = queue[0];  /*send first character to start process*/
    }

    /*this interrupt occurs whenever the */
    /*USART has completed sending a character*/

    ISR(USART_TX_vect) {
     /*send next character and increment index*/
     if (qcntr != sndcntr)
      UDR0 = queue[sndcntr++];
    }

    ISR(TIMER0_OVF_vect) { //overflow every 16ms
     TCNT0 = 6; // 256-250 = 6
     ++updateTimeCount;
     if(updateTimeCount >= updateDelay) { //after 208ms, update game state
      updateFlag = 1; // Call for updating game
      updateTimeCount = 0;

     }

     refreshFlag = 1; // Call for updating screen
    }

    void init_ports() {
     DDRD = (1<<latchPin) | (1<<clockPin) | (1<<dataPin); //enable pins
     PORTD = 0; //set all pins low
     DDRB = (1<<5); //enable the built-in led for debugging
     PORTB = 0; //set all pins low
    }
    void init_USART() {
     UCSR0B = (1<<TXEN0) | (1<<TXCIE0); //enable transmitter and tx interrupt
     UBRR0 = 103; //baud 9600
    }
    void init_timer0() {
     TCCR0A = 0;
     TIMSK0 = (1<<TOIE0); // enable interrupt
     TCCR0B = (5<<CS00); // prescalar 1024. 16Mhz/1024 = 15625Hz = 0.064ms
     // For refresh rate of 62.5Hz, 16ms /0.064ms = 250
     TCNT0 = 6; // 256-250 = 6
    }

I really can't tell what the problem is and I don't what to look up either. I think the problem is in the functions `drawData` and `shiftOut`, because that's where all the data is shifted out. I tested the timer0 interrupt by flipping the built-in led and that seems to be working fine.
Are the ports flipping too fast for the shift regs to receive the data? Is there a semantic error somewhere? Can you see any problems. Thanks for any help!

sender: assistant

body:
Thanks to everyone who commented on my question, I was able to solve the problem with your help!

The first issue was that the compiler interpreted the `if(refreshFlag) {...}` as `if(0) {...}` so the data would have never been outputted to the display.

This happens is because the compiler doesn't see that the `refreshFlag` can be set to 1 in the timer0 interrupt service routine. From its perspective I have written an if statement that never runs.

As @KIIV pointed out, if the `volatile` keyword is used when declaring `refreshFlag`, this tells the compiler that this variable can change at any time.

The second and more embarrassing issue was that I forgot to remove a call to `clearData()` function which clears the data array. So I was just outputting nothing to the registers!

This is what the fixed variables and main should look like:

    int updateTimeCount;
    int updateDelay;
    volatile int updateFlag; // Flag for updating game state
    volatile int refreshFlag;// Flag for refreshing display

    uint8_t data[] = {0b00000001,
                      0b01111110,
                      0b11000110,
                      0b01001010,
                      0b01010010,
                      0b11100010,
                      0b01111110,
                      0b01000010};

    int main(void) {
        //init_USART();// Serial for debugging purposes
        init_ports();
        init_timer0();

        sei();

        PORTB = 0; //PortB for debugging
        updateTimeCount = 0;
        updateDelay = 13; // Game updates every 13* 16ms = 208ms.
        updateFlag = 0;
        refreshFlag = 0; // Display updates every 16ms

        while (1) {

            if(updateFlag) { //updates game state
                PORTB = (1<<5); //debugging led
                updateFlag = 0;
            }

            if(refreshFlag) { //refreshes display
                drawData(data); //output data array

                refreshFlag = 0;
            }
        }
        return 0;
    }


message:
Alternatives to read mp3 without using an sdcard as source for the files?

I am making a project that plays several sounds using a [DFPlayer Mini mp3 player][1] and a micro sd card. The size of the sounds I normally play is less than 20 MB, so a lot of space in the sd card is unused. I was wondering if there is an alternative to use an SD card to store the mp3 files, and if there is, what would be the best approach to switch to use this alternative.

Cheers!

  [1]: https://wiki.dfrobot.com/DFPlayer_Mini_SKU_DFR0299

body:
The problem of all alternatives I can think of is a commercial one:
Its more expensive than to waste space. So if you look up your facvorite online dealer you will quickly find out that e.g. buying the cheapest 1GB SD card costs double than buying the cheapest 32GB card (6$). So the more space you waste the cheaper.
 Get an used 512MB or 1GB card (cost in my country around 1$) and be happy with the space reserve.

Of course if saving space is a topic and not money get 20 x 1MB eeprom I2C boards (20*3$ from china), solder the hardware (you'll need some more parts to manage the board addresses), get a power source, write a library for managing the memory and after spending around 100$ and a lot of time you saved up to around 15.98 GB of free space but not the environment.


message:
Which Protocol to use to control WiFi (esp 32) enabled Led Light

I am developing a Wifi based Led light (for learning purpose). I have little knowledge about web server, clients, Web protocols. I will be using ESP32 as Controller cum WiFi module.

There are two ways to control Led light over WiFi.

Locally
Remotely // as of now am focusing on locally

Android/iOS app will be handling all the control part (Flutter app)

Which protocols can I use to control Led light, locally?
will set up multiple esp32 at that time its hard to control the device both devices will have different ip

Kindly help!
if anyone give good example it would be helpful

body:
You can use your ESP as a server by the following [code][1] and then put your DigitalWrite(1, HIGH) line in the code like the following:

     String line = client.readStringUntil('\r');
     Serial.print(line);
    if(line=="ledon")
    {
    DigitalWrite(1, HIGH);
    }
and at this point you just can call the following link to turn the led on

    http://192.168.*.**/ledon

or whatever the starting of your ipv4 is.

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/server-examples.html#put-it-together


message:
How to bridge free-running multichannel adc to serial?

I want to get meteo sensors values, and turn avr based 16mhz arduino (i have mega, but that seems not matter alot vs uno) into multichannel oscilloscope.

Task details. Desired data rate is 8(uno) to 16(mega) analog channels divide by 4 to 16 reads per second. Extra adc "speed capacity" must be spent on summing up on arduino. Prescale is almost not needed. Each reading is 32bit, lsb is always zeroed. Plus there is 0xffffffff between packets (easiest binary proto, i really hate those ascii low-quality slow shit, but this is personal and offtopic). So now you got the setup and purpose, lest get down to my simple sketch

    // defines for setting and clearing register bits
    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    // packet starts after indicator and goes before next such indicator.
    const long packetStartIndicator = 0xFFFFFFFFl;

    // values are fixed point ints 0..65534 (with LSB always cleared)
    // such descision is made because least significant bit almast always == noise;
    // also its just easist pck splitting scheme
    const long packetValueMask = 0xFFFFFFFEl;

    const int numPins = 8;

    long sensorValues[numPins+1];

    // TODO: configure this from host via serial (inside setup)
    int pinNumbers[] = {A0, A1, A2, A3, A4, A5, A6, A7, A8};
    //int pinNumbers[] = {A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15};

    // 1 reading is 10 bit. we can make 2^6==64 readings and sum them up (to top up to full 16 bit, to make kind of digital expoure)
    // upd. 1 reading is counted as 16 bit, for host convenience (no matter or real adc)
    // sum up like 256 of 16-bit readings to get 24bit value. send as 32bit long variable.
    const int adcOrder = 10;
    const int readingsOrder = 8;
    const int targetOrder = 24;
    const int numReadings = 1 << readingsOrder; //64;

    void setup() {
      // TODO: reset ADCSRA, or it would not work. Also: get clue on free run mode
    // sampling rate is [ADC clock] / [prescaler] / [conversion clock cycles]
    // for Arduino Uno ADC clock is 16 MHz and a conversion takes 13 clock cycles
    //ADCSRA |= (1 << ADPS2) | (1 << ADPS0);    // 32 prescaler for 38.5 KHz
    //ADCSRA |= (1 << ADPS2);                     // 16 prescaler for 76.9 KHz
    //ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz

    //sbi(ADCSRA,ADPS2); cbi(ADCSRA,ADPS1); sbi(ADCSRA,ADPS0); // set prescale to 32 for 38.5 KHz
    //sbi(ADCSRA,ADPS2); cbi(ADCSRA,ADPS1); cbi(ADCSRA,ADPS0); // set prescale to 16 for 76.9 KHz
    //cbi(ADCSRA,ADPS2); sbi(ADCSRA,ADPS1); sbi(ADCSRA,ADPS0); // set prescale to 8 for 153.8 KHz

      sensorValues[numPins] = packetStartIndicator;
      //analogReadResolution(10);
      Serial.begin(115200, SERIAL_8N1);
      //Serial.begin(250000, SERIAL_8N1);
      //Serial.begin(500000, SERIAL_8N1);
    }

    void zero_values() {
      int i;
      for(i=0; i<numPins; i++) {
        sensorValues[i] = 0;
      }
    }

    void clear_lsb() {
      int i;
      int shiftOrder = targetOrder - (adcOrder + readingsOrder);
      for(i=0; i<numPins; i++) {
        sensorValues[i] <<= shiftOrder;
        sensorValues[i] &= packetValueMask;
      }
    }

    void serial_write() {
      Serial.write( (uint8_t*)sensorValues, sizeof(long)*(numPins+1) );
    }

    void loop() {
      int i, j;
      zero_values();
      for(i=0; i<numPins; i++) {
        for (j=0;j<numReadings; j++) {
          sensorValues[i] += analogRead(pinNumbers[i]);
        }
      }
      clear_lsb();
      serial_write();
    }

I am weak with reading avr datasheets and lacking of knowledge on internals. My question is tied with my desire to switch it to freerun mode. I really dislike analogRead, seems it was written by real juniors, and is real slow. AFAIK free run mode is something when you have interrupt function running when conversion is done. I feel (dont know but really feel) that working with serial inside interrupt is a bad idea. How, in somple words, this can be reworked to event-based ISR with sending over serial when you would encounter inside your interrupt following: `currentPin == lastPin && currentReading == numReading` means *you have summed up desired bumber of readings, and this is last pin, so its time to post it over serial*.

body:
In the Arduino environment sending data over serial inside an interrupt is seldom a good idea. That's not to say it's impossible, you just need to keep certain caveats in mind.

The chief of which is that when the TX buffer fills up everything will lock up.

So with that in mind, if you can *guarantee* that all your data from one interrupt will be completely sent out before the next interrupt occurs then sending serial in an interrupt can be used.

And yes, `analogRead()`, like many things in the Arduino API, is not fast. It's not intended to be fast. It is, though, intended to be simple.  And also like many things in the Arduino API it's easy to out-grow them.

I am not familiar with the Atmel ADC registers (preferring PIC32 to AVR any day...) but looking at the datasheet I can see a few points of interest.

* First set the trigger source to "free running" (ADCSRB):

> * Bit 2:0 – ADTS2:0: ADC Auto Trigger Source
>
> If ADATE in ADCSRA is written to one, the value of these bits selects which source will trigger an ADC conversion. If ADATE is cleared, the ADTS2:0 settings will have no effect. A conversion will be triggered by the rising edge of
the selected Interrupt Flag. Note that switching from a trigger source that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. If ADEN in ADCSRA is set, this will start a conversion. Switching
to Free Running mode (ADTS[2:0]=0) will not cause a trigger event, even if the ADC Interrupt Flag is set.

Then set it to use the trigger source for starting conversions (ADCSRA):

> * Bit 5 – ADATE: ADC Auto Trigger Enable
>
>When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a positive
edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in
ADCSRB.

And enable interrupts (ADCSRA):

> * Bit 3 – ADIE: ADC Interrupt Enable
>
>When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete Interrupt is activated

Alternatively you could set it to use a timer for the trigger source so you have finer control over when a conversion is performed. That will help you to ensure that all of the previous data set has been sent over serial before the next interrupt occurs.


message:
ESP 8266 reverse digitalWrite behaviour on which pins?

I am using a device with an ESP 8266 microcontroller. I have discovered that setting `LED_BUILTIN` to `HIGH` turns the built-in LED **off** and  setting `LED_BUILTIN` to `LOW` turns the built-in LED **on**. This seems to be because the [microcontroller can sink more current than it can source](https://github.com/nodemcu/nodemcu-devkit-v1.0/issues/16).

Before I start using this microcontroller, I would like to know which other pins have this reverse behaviour. I've looked up datasheets for the ESP 8266 but I don't see how to discern this information. I would simply write a sketch to test, but I'm not sure what I might damage, and I'm not sure how to determine when an output pin is in the high-impedance state anyway.

**On the ESP 8266, how to know which pins are `HIGH -> 0v` and which pins are `HIGH -> 5v`?** Are the `HIGH -> 0v` pins necessarily `LOW -> 5v`? Where is this documented?

body:
The esp8266 must have a pull-up on io 2 for boot configuration. The Wemos D1 boards put the LED in series with the pull-up resistor on io 2. This creates the 'reversed' LED behavior.

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

The large D1s are retired and it is hard to find a good and readable schematics. The cut out is from D1 mini schematics.

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


message:
Use of "static" with "RTClib"

I've got a question concerning the Arduino library "RTClib" by Adafruit and the use of the word "static".

Here you can see an excerpt from the example provided for the pcf8523 real-time clock:

    #include "RTClib.h"

    RTC_PCF8523 rtc;

    void setup () {

      while (!Serial) {
        delay(1);  // for Leonardo/Micro/Zero
      }

      Serial.begin(57600);
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (! rtc.initialized()) {
        Serial.println("RTC is NOT running!");
      }
    }

    void loop () {
        DateTime now = rtc.now();

        Serial.print(now.year(), DEC);
     /*
     do some more stuff
     */
    }

In the beginning of loop() they wrote:

    DateTime now = rtc.now();

Thus, with every iteration of loop() "new" gets defined anew (on the heap?!), right?
This appears inefficient to me.

I thought about rewriting it this way:

    static DateTime now; // static declaration, executed only once
    now = rtc.now(); // assignment to "now" every time loop() starts over

In this case "new" should be allocated on the stack like a global variable, right?

I want to use "static" to increase overall performance by reducing work for the processor and the heap (thereby avoiding heap fragmentation). Does this make sense or will it cause more problems than it solves? Keep in mind that I want to learn both proper programming for Arduino and proper coding in general.

Link to the library:
https://github.com/adafruit/RTClib

Thank you! :-)

**EDIT:** For some reason I CAN NOT declare `DateTime now;` in global scope or else the program won't run. Don't know why though. This is why I want to use static in the first place.

body:
You don't need to use the `static` keyword.

The cleanest solution is to define `DateTime` outside of the `loop` function:

    DateTime now;

This will allocate the memory, and call the constructor of the class `DateTime` initializing it.

In case you would need a basic variable (like an `int`), you should initialize it, like:

    int now = 0;

When you use it in `setup` or `loop` you use the created instance (without the class name to declare it):

    void loop() {
       ...
       now = rtc.now();
    }

Also, find a better name for `now`, because the variable is the same as the `rtc`'s function `now`.

**Update**

after your comment, it cannot be used as a global variable:

I didn't try it myself, but I suspect, the constructor calls a function that uses variables or a function that is not initialized at that point. Actually, it's quite bad practice.

Anyway, one way to circumvent and stick as much to what I wrote above, is to use a pointer instead:

    RTC_PCF8523* rtc = NULL;

Than you create an empty pointer, without calling the constructor. You will do this at the end of `setup`:

    void setup() {
       ...
       rtc = new RTC_PCF8523();
    }

This will cause the variable to be put on the stack.

Than when using it, you call:

    now = rtc->now();

Note you have to use the -> notation, as rtc is a pointer.


body:
You wrote:
> ```c++
> DateTime now = rtc.now();
> ```
>
> Thus, with every iteration of loop() "now" gets defined anew (on the
> heap?!), right?

No. Local variables like this are usually allocated on the stack,
although the compiler may keep them in CPU registers if that helps
optimization.

> ```c++
> static DateTime now;    // static declaration, executed only once
> ```
>
> In this case "new" should be allocated on the stack like a global
> variable, right?

No. It is allocated statically, in the .bss section, like uninitialized
global variables.

> I want to use "static" to increase overall performance by reducing
> work for the processor

Not sure it will make much difference. Static allocation may save you a
few CPU instructions compared to stack allocation (the instructions that
move the stack pointer). On the other hand, it will cost you a few
instructions compared to register allocation (the instructions to access
the RAM).

> avoiding heap fragmentation

Stack allocation does not use the heap, and the stack never fragments.

> Does this make sense or will it cause more problems than it solves?

If you really care about sub-microsecond differences in the execution
time, you should either look and the disassembly of the program, or do
some benchmarking. Otherwise just write whatever makes more sense from
the point of view of the program's logic: does the variable need to keep
its value across calls to `loop()`? If the answer is “no”, do not use
`static`.


message:
Servo motor troubles

[![Here is the wiring ][1]][1]
  [1]: https://i.stack.imgur.com/sBk8J.jpg

The image is as clear as I can make it.

Here are the basics of my problem. My program is meant to make 6 red LED lights in sequence fade in and out, toggle 5 white LED's on and off with a button, and make a servo rotate from 90 to 15 degrees on a button press, and revert to 0 degrees when the button is no longer pressed.

All of my code has compiled correctly, the LED's do what they are supposed to do, but the servo is acting strange. At first, it would move fine but then after a few button presses it would kind of spaz out and glitch back to place instead of smoothly move, which will not work for my purposes. After even more time, the servo stopped working at all. I looked around and found some answers saying to route it through an alternative power source, but I did that with the power module that came with my kit and it still refuses to move. I swapped it out with a different servo and that one won't work either, which makes me wonder if my wiring is incorrect - and yet the motor is on and makes vibrations, instead of moving, so I know power is getting through. In addition, the onboard LED's on the mega2560 are turning on and off in response to my button, so I know that's wired in correctly as well! So why won't the servo move, and why won't it respond to my button presses?

Basically, using a 3.3V - 5.0 volt Elegoo power module, how do I correctly wire the servo to only draw power from the 9v battery I attach to said module? I've seen people saying something about putting the grounds of the board and the module together but I don't know how to do that and I'm getting frustrated looking all over the internet trying to find out how so I figured I would just ask a question.

Wiring details:

The 5 white LED's are in parallel, and the red LED's are in series; they are all powered by the arduino's 5V power source, and wired into the arduino GND pin.
Servo is connected by to pin 10, and the ground and power are both routed through the 5V power module which is attached to a 9V battery. The light on the module is on, and I have used the included jumpers to make sure I'm using the 5V source and not the 3.3V one.

Here is my code:

```// Servo
#include <Servo.h>
Servo servo1;
//------------------------
// White LED's:
int wL1 = 3;
int wL2 = 4;
int wL3 = 5;
int wL4 = 6;
int wL5 = 7;
//------------------------
// Red LED's:
int rL1 = 8;
//------------------------
// Buttons:
int wLbutton = 2;
int wLreading;
int wL1state = HIGH;
int wL2state = HIGH;
int wL3state = HIGH;
int wL4state = HIGH;
int wL5state = HIGH;
int wLprevious = LOW;

int servoButton = 1;
int servoState = false;
int servoReading;
int servoPrevious = LOW;
//--------------------------
// Fading:
int brightness = 0;
int fade = 1;
//--------------------------
// Delays:
long time = 0;
long time2 = 0;
long debounce = 100;

unsigned long previousMillis = 0;
const long interval = 1000;
//--------------------------

// Setup ======================================================================================================================================

void setup()
{
  pinMode(wL1,OUTPUT);          // White LED's
  pinMode(wL2,OUTPUT);
  pinMode(wL3,OUTPUT);
  pinMode(wL4,OUTPUT);
  pinMode(wL5,OUTPUT);

  pinMode(rL1,OUTPUT);          // Red LED's

  pinMode(wLbutton, INPUT);     // Buttons
  pinMode(servoButton, INPUT);

  servo1.attach(10);
  servo1.write(90);             // Servo

  if (wL1state = HIGH)
{
  wL1state = LOW;                                                              // Set the state of the all White LED buttons to low at the beginning of the circuit (this doesnt run after the first time).
  wL2state = LOW;
  wL3state = LOW;
  wL4state = LOW;
  wL5state = LOW;
}
}

// Loop =========================================================================================================================================

void loop() {

// White LED Button -----------------------------------------------------------------------------------------------------------------------------

wLreading = digitalRead(wLbutton);                                             // Read the state of the White LED Button

if (wLreading == HIGH && wLprevious == LOW && millis() - time > debounce)      // If the button is different state from last reading and ignores noise
{
  if (wL1state == HIGH)                                                        // If the current button state of the White LED button is high
  {
  wL1state = LOW;                                                              // Set the state of the all White LED buttons to low
  wL2state = LOW;
  wL3state = LOW;
  wL4state = LOW;
  wL5state = LOW;
  }
  else {
    wL1state = HIGH;                                                           // Otherwise, set the state of the White LED button to high
  }
  time = millis();                                                             // Set the last time the button was pressed to the current time
}

digitalWrite(wL1,wL1state);
digitalWrite(wL2,wL1state);
digitalWrite(wL3,wL1state);
digitalWrite(wL4,wL1state);
digitalWrite(wL5,wL1state);

wLprevious = wLreading;                                                        // Set the previous reading of the White LED button to current reading

// Servo Button ----------------------------------------------------------------------------------------------------------------------------------

servoState = digitalRead(servoButton);

if (servoState == HIGH)
  {
    servo1.write(75);
  }
  else
  {
    servo1.write(0);
  }

// Red LED'S breathing ----------------------------------------------------------------------------------------------------------------------------

 analogWrite(rL1,brightness);                                                 // Write the set brightness to the red LED
 brightness = brightness + fade;                                              // Set new brightness to brightness value + fade value

 if (brightness <= 0 || brightness >=255)                                     // If brightness is less than 0 or more than 255
  {
  fade = -fade;                                                               // Negate the fade value, reversing the direction of the fade
  }
  delay(10);                                                                  // Wait a short delay to see the fade
}```

body:
> I've seen people saying something about putting the grounds of the board and the module together

Yes, I believe this is what you need to do.
>Servo is connected by to pin 10, and the ground and power are both routed through the 5V power module which is attached to a 9V battery.

From what I understand, you are wiring like this

Servo 5V - 5V Power module

Servo GND - GND Power module

Servo Signal - pin 10 Arduino

If so, you need to  make a Y-connection like this:

Servo GND - Power module GND - Arduino GND (these 3 pins should be connected together)


message:
How to convert four uint16_t to double float IEEE754?

I am working in a Modbus project where I have to read modbus Holding and Input registers using ESP8266, I am using ModbusMaster232 library. I returns a response buffer array of uint16_t. I need to convert the uint16_t to double precision float. A quick test in ESP8266 shows double datatype in ESP8266 stores 8 bytes.Does anybody know how to convert four uint16_t to double in Arduino. If so please share your knowledge.

body:
Here's a code fragment for converting a uint16_t. Expand this to work with your array of ints from the library.
Remember that on Arduino, - Uno and Mega, at least - doubles are implemented as floats. You won't get the precision you might be expecting.

    double xAsDouble;    // ** only float precision despite 'double' declaration
    uint16_t xAsInt;

    xDouble = xInt;      // the compiler knows how to make this conversion.

Update: After re-reading your question, I realize you're using an ESP8266. My comments about Uno's float precision may not apply.

Update 2: After some discussion, I've learned that the Modbus return is not 4 integers, but a double being passed as 4 words, which need to be reassembled to recreate the original double. The solution will depend on the order in which the words comprising the original double are sent.

Update 3: I suggested the OP try using this general scheme:

    // A union lets you look at memory as either (in this case) 4 ints or 1 double
    union {
       uint16_t data_out[4];
       double x;
    } buffer;

    // Assign the data from modbus using the 'int' way of viewing menmory.
    // Note I might have the ordering wrong but this is the idea:
    buffer.data_out[i] = data_in[i];

Then reading 'buffer.x' would get the 4 words of memory as a double.

... After trying both orderings, the OP reports he is obtaining the expected result,


message:
Using L298N bridge to control smart lock

I want to use L298N bridge to power up and control simple smart lock. It requires 12V power supply, so I've used L298N bridge to power this smart lock.

I removed jumper from enA pin and connected enA 12V to Arduino Nano D8 pin.

I sent value 255 through this pin but smart lock did nothing. Any suggestions?

I'm using BLE controller to send turn on/off signal from Android App (but its not relevant in this case, because **analogWrite** is called).

Lock:
https://www.aliexpress.com/item/32949292074.html

Here is code:

    #define enA 8

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

    void loop() {
     String msg = bluetooth.read(); //using BLE controller to get message from Android app.

     if(msg == "ON"){
       analogWrite(enA, 255);
     } else if(msg == "OFF"){
       analogWrite(enA, 0);
     }

    }

Here is setup:

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

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

body:
You really don't want an L239D to control that lock. It's overkill.  The L239D is a H-bridge that is designed to drive loads in two different polarities (forward / backwards on a motor for example).

That lock is merely a spring-loaded solenoid. You give it power and it pulls the lock back. You remove power and the spring closes it again.

All you need is a simple transistor circuit just like you'd use for a relay.

----

Since you insist on using an L239D, here's a schematic for you:

<!-- 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/Fvj2F.png)

<!-- End schematic -->


message:
Motor for a winch (with controller and external power supply)

I'm in need of a motor or continuous servo to power a winch. The motor must be continuous* and reversible, but it does not need to be fast, precise, nor bear a load when powered off. It just needs to overcome ~50 Newton of friction force (to winch open my bedroom curtains laterally).

(* it needs to, given a discrete drum (maybe max 4cm diamater), winch about 1m)

I am using a [MEGA2560 R3][1] which has a 5V port. I've tried using a 12V DC stepper motor ([24BYJ48][2]) with a standard ULN2003 controller, with a winch drum of ~2cm diameter, but it could not overcome the friction. I didn't spare much thought for the parameters of the arduino `Stepper` instance though; I just used a configuration which worked for winching lighter loads.

I'm a rookie, but I'm assuming my board cannot sufficiently power the motor(s) (I have 3), and possibly that they themselves are too weak. Hence I'm looking for a stronger motor and controller, controllable by my arduino, but which has a direct power supply (from mains). So:

- have I got this all wrong? Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?

- is there a shield for my MEGA which can enable these motors to function in parallel?

- otherwise, is there a strong *continuous* servo with an external power supply that would work here?

  [1]: https://store.arduino.cc/arduino-mega-2560-rev3
  [2]: https://www.amazon.co.uk/gp/product/B07QYLVK9F/ref=ppx_yo_dt_b_asin_title_o03_s03?ie=UTF8&psc=1

body:
"Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?"

Huh? Do you mean can you power a 12V stepper directly from the 5V supply on an Arduino? How would that work? You need an external power supply and a motor controller that converts the 5V control signals from the Arduino to 12V. The answer is "absolutely not." Motors draw way, way too much current to be powered from an Arduino logic pin, and all but the smallest motor will draw too much current for the 5V supply line. Plus you said you were using a 12V motor. You can't run a 12V motor on 5V.

A stepper seems like the wrong tool for this job. You should be able to use a high torque 12V DC motor and an H-bridge motor controller. An H-bridge will let you run the motor forwards or backwards.

You'll probably need a motor with a gearbox, since you likely want a fairly slow turning shaft. How many newton-meters/second do you need?


body:
> Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?

No, you should never ever power a motor through an Arduino. It can only provide a limited amount of current, before it gets fried. You need to provide the motor driver with voltage directly from your power source. You haven't stated, what you are using as a power supply. I assume, you are just using an USB port of a PC. That is also a no-go, since it will only provide 500mA at max (that's even less, than the Arduino can bear). You should power your motor with a power supply of 12V, since it is rated for that voltage. You can buy a simple wallwart for that.

Also, currently you are providing the 12V motor with only 5V, so it cannot give you it's full power. Use a power supply with the correct voltage and more than enough current capability. Though you should keep an eye on the current ratings of the ULN2003. The datasheet is not really clear, if that chip supports 12V supply voltage. Some variants like the ULN2004 seem to support it, but I'm not sure about the ULN2003. If it is not rated for 12V, you can destroy the chip that way.

We cannot know, if the motor with it's driver will be able to rotate the winch, since the seller does not name the torque of the motor. You could try to contact the seller and ask directly about this. More specialized sites, where you can buy motors, will tell you exactly, what the torque of the motor is, that you are buying. Buying a cheap part at Amazon is somewhat the lightweight variant of buying it directly from china: The documentation is a bit better, but still not great. Without documentation or information from the seller, you are stuck with just buying and trying.

> is there a shield for my MEGA which can enable these motors to
> function in parallel?

It isn't clear, what you mean by that. You can control as many motors simultaneously, as you have pins and as you have enough computation time (meaning not too much steps per second or other stuff going on in the program). As mentioned above the power has to be supplied to the drivers from outside of the Arduino, so that does not apply here.

> otherwise, is there a strong continuous servo with an external power supply that would work here?

Power supply and motors are 2 different parts, that aren't usually sold together. Also you should start with the motor: Look for a motor, that can provide the torque, that you need. Then look for a driver circuit, that can provide the functionality, is rated for the same voltage as the motor and can provide enough current for the motor (the max. motor current is also information, that a good seller will provide). Then look for a fitting power supply. Unless you are buying some kind of kit, you need to choose these parts yourself. (We don't do product recommendations here)

---

A possibility, that you might not have though about: You could buy a normal DC motor, which provides enough torque. As speed is not your biggest concern, you could buy a geared DC motor, which can be rather strong. For a driver you would need to buy or build a H-bridge controller (which is essentially just 4 transistors put together). Be sure to use a MOSFET based driver, if you want to buy a driver chip. The standard L298n is pretty lossy.

---

It seems, that you generally don't know, how to build such a project. So here are some notes, that might help you with that:

- **Connecting everything together:** In most cases (and especially when handling high current motors) you cannot get around soldering. You can buy a perfboard (cheap PCB material, with some pads already connected for ease of use), put the parts onto it and solder everything to the perfboard. Using shields as no-solder solution can only work, when you find a fitting shield and fitting motor for your requirements. That can be a far fetch. So if you want to get into electronics and Arduino, you probably should get yourself a soldering iron (there are also many tutorials about using it on the web).

- **Connecting the power supply:** When buying a walwart power supply, it will normally come with a cable attached to it. At the end of this cable may be a connector. You have 2 options: Cut the connector and solder the wires in the cable directly to your perfboard, or buy the counter part of the connector, which you then can solder to your perfboard. Depends on if you want to disconnect the power supply from the circuit or not.

As I'm suggesting here to invest in this a bit, I want to also sketch an alternative, if you just want to get it work and don't experiment (this site is full of makers, you do this for fun, but that does not have to apply to everyone):

You may be able to use a shield to do, what you want to. This might cost a more, than putting the parts together yourself, but it will safe you the investment in tools, which you might not need in future. As above you need to choose the parts fitting your requirements. Decide on the type of motors, that you want to use (if money is not such a deal, you can nearly use any motor with enough power, stepper motor, DC motor, ...). Look for a shield, that can provide the needed current and voltage to the motor.

Every motor shield has a terminal for connecting the external power supply for the motors. On good shields this is a screw terminal, so you would simply strip the cable of the power supply and put the wires of it into the screw terminal.


message:
Controlling Brickstuff with Arduino

I don't have much experience with electronics (I'm ok with programming). I have some Brickstuff lights in a Lego set. The lights are powered by 3 AA batteries. The Brickstuff documentation says that I should not connect then directly to an Arduino, as the current exceeds the Arduino limit. I want to use an Arduino to power the lights and activate them with a button, but I want to use the same power supply to feed the Arduino and the lights.

Any suggestions about what components I should use, and how to connect them? Thanks.

body:
Transistor is likely what you want for simplicity.

Be sure to add up all your amperage requirements and then add some extra when selecting a supply.  Having too little available will make your circuit misbehave while having a supply capable of giving you more doesn't hurt.

For voltage 3×1.5V = 4.5V if the batteries are in series.  Arduino runs on 5V (USB).  I suspect you'll probably be using a 5V supply.  Both circuits have a little margin, lights usually more so.


message:
Building projects on the command line using the Bare-Arduino-Project template

I'm trying to program an Adafruit Trinket using avr-gcc et. al. with the Makefile from the [Bare-Arduino-Project](https://github.com/ladislas/Bare-Arduino-Project/) on macOS Catalina.

I can build projects for standard boards like the Uno, but not for the Trinket. Everything works as expected using the "official" Arduino IDE (1.18.10). In the Bare-Arduino-Project Makefile I'm specifying the Trinket as:

```
BOARD_TAG         = trinket5
BOARD_SUB         = attiny85
```

I get an error from avr-gcc that **mmcu** is not defined. I assume this is because the command line tools aren't finding the Adafruit equivalent of *boards.txt*. When I look in the Arduino IDE package I don't find the Adafruit boards in *boards.txt* or anything that looks like the definitions for the Adafruit boards (despite having added them in the IDE).

Any ideas about how to set up support for the Trinket (or other third party boards) when using command line tools?

body:
You  probably look at the wrong `boards.txt`:

    # Trinket 5V Configuration
    trinket5.name=Adafruit Trinket (ATtiny85 @ 16MHz)

this can be found in the `boards.txt` in the main directory

    C:\Users\YOUR_USER_NAME\AppData\Local\Arduino15\packages\arduino\hardware

in the sub directory

   \adafruit\avr

in the same main directory should  also be a folder named `1.8.2` (for ArduinioIDE 1.8.12) for the core files

if added via board-manager using this line in preferences/additional bord manager urls

    https://adafruit.github.io/arduino-board-index/package_adafruit_index.json

If you did a manual installation check with [this guide for pit traps](https://learn.adafruit.com/adafruit-arduino-ide-setup?view=all).<br>Details on using trinket with the [avrdude command line can be found here](https://learn.adafruit.com/introducing-trinket/programming-with-avrdude)


message:
Is there a way to remove the 8.3 filename limitation on the SD.h library?

I need to be able to create text files on my SD card that are with names longer than 8 characters (which is what the SD.h currently limits me to). A choice would be to move to the SDFat library but before considering that option, is there a way to just remove the limit on the SD.h (because my code already implements the good-old SD.h)? What would be the best way to go about this issue?

body:
The 8.3 "limit" is not a "limit" that can be removed. It is how FAT filesystems work.  Longer filenames are a "fudge" extension overlaid on top of that fileststem structure. To be able to use them you would need to implement that extension.

Simpler to switch to a more modern implementation.  FatFS is your friend:

* LFN support, including UTF
* Faster device access
* More efficient
* Can handle more devices than just SD cards
* Can handle multiple devices at once

There is an implementation [here](https://github.com/gallegojm/Arduino-FatFs) though I don't know how good it is (I use it on chipKIT where it is bundled by default).

If you can't get FatFs then basically *anything* is better than the SD library to be brutally honest.


message:
Having trouble assigning colour to my neopixels

Hi I was wondering if someone is able to help me! I am currently trying to get a strip of 10 neopixels to change colour. I want to be able to code a random neopixel in the strip to change to either red, blue, green and yellow consecutively after 2 seconds. I am relatively new to Arduino so I'm still learning. I have been using the code below and it does everything that I want it to but I would like to set the colour so they're not as randomised. I found this code online.

    #include <Adafruit_NeoPixel.h>

    #define PIN 6
    #define LED_COUNT 50
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_RGB + NEO_KHZ800);

    void setup() {
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop()
    {
      randomPixelColor(100);

    }

    void randomPixelColor(int wait)
    {
      int i= random(strip.numPixels());

      uint32_t c = random(2147483647); // I have no idea what this crazy number does.
      strip.setPixelColor(i, c);
      strip.show();
      delay(1000);

    }    // end void randomPixelColor()

I don't even know if this is the right code to be using! Hopefully someone can help me cause I'm so confused.

body:
You already are choosing a random LED. Now you only need to define and use the colors, that you need. Define an array with the colors:

    #define COLOR_N 4
    uint32_t colors[COLOR_N] = {0x00FF0000, 0x000000FF, 0x0000FF00, 0x00FFFF00};

Also define a static or global variable to hold the current color:

    uint8_t current_color = 0;

Then use this array in `strip.setPixelColor()` with the `current_color` variable as index:

    strip.setPixelColor(i, colors[current_color]);

Now increment `current_color` for the next color. To go from yellow to red again, you can use the modulo operator `%`:

    current_color = (current_color + 1) % COLOR_N;

You can easily extend to more colors, by writing the new colors into the `colors` array and setting `COLOR_N` to the corresponding value.

---

**About the color values**: The neopixels use an RGB color model with 8 bit depth. That means, that each component (red, green and blue) occupies exactly 1 byte. Thus there are 256 steps for each component. To describe a full color, you need all three components, thus 3 bytes or 24 bits. The data type, that fits this `uint32_t` (unsigned integer with 32 bit), though the most significant byte is unused here (if you use an RGBW strip, this byte is the component for the white LEDs).

We can write the number, that is representing a full color, as a hexadecimal value. Each component occupies 2 hexadecimal digits:

    0x00RRGGBB

where `0x` is the prefix, which marks a hexadecimal number, and `RR`, `GG` and `BB` are the components red, green and blue of the color. So a full red is `0x00FF0000`, a full blue is `0x000000FF` (the leading zeros are not mandatory, but I think they help readability and comparability).

The color mixing works additive here, just like light does. All components mixed together at the same ratio gives you white, all components to zero means black. Thus you get yellow from mixing red and green the same ratio. So a full yellow is `0x00FFFF00`.


message:
Do Loop query not stopping

I am new to Arduino programming and I would like to ask a question.

Firstly apologies if this has been answered before and I understand if it gets locked if this has been answered elsewhere.

I am trying to get three LED's (red, amber, green) to loop 5 times (in a do loop).

for this I have created a integer variable (x) and initialised the variable to 0.

I then increase x by 1 each time.

However I cannot get them to stop looping when x is greater than 5. The program does work as expected for everything else (green LED lit, wait 1 sec, Yellow LED lit, wait 1 sec, red LED lit and then loop).

       //set LED pins
    int greenPin = 13;
    int yellowPin = 12;
    int redPin = 11;

    void setup()
    {
      pinMode(greenPin, OUTPUT);      // sets the digital pin as output
      pinMode(yellowPin, OUTPUT);
      pinMode(redPin, OUTPUT);
    }

    void loop(){
    int x = 0;

     do {
      digitalWrite(greenPin, HIGH);   // sets the LED on
      delay(1000);                  // waits for a second
      digitalWrite(greenPin, LOW);
      digitalWrite(yellowPin, HIGH);    // sets the LED off
      delay(1000);
      digitalWrite(yellowPin, LOW);// waits for a second
      digitalWrite(redPin, HIGH);    // sets the LED off
      delay(1000);
      digitalWrite(redPin, LOW);
     }
       while(x<=5); {
        x = x + 1;
       }
    }

body:
Chrisl already gave the clue.

However, to add a comment with a code example I use the answer box.

In C you have more or less two kind of loops:

- for
- do / while

The first one is when you know beforehand how many iterations you have, the second when it depends on external input (e.g. when you expect a value acquired from within the loop).

In your case, you can better use the `for` loop, so you get:

    for (x = 0; x < 6; x++)
    {
       ...
    }

What this does i:

1. Initializes x to 0 (first part of the `for` statement)
2. It checks the condition `x < 5' (second part of the `for` statement). If false, it continues with the first statement after the `for` body (after the } bracket).
3. It runs the body of the loop (inside the brackets)
4. It increases x (third part of the `for` statement)
5. It continues with 2

Also it is quite common for the condition to include the start element of the ragne (x = 0), but exclude the end element of the range (x < 6), thus it runs the last time with x == 5.


message:
Data type explanation regarding analogRead of a photoresistor

This is a fundamental question - very new (1st post) and trying to learn.  I have a photocell connected in series with a 10kOhm resistor between 5v & Gnd (to make a voltage divider) and the divided voltage is connected to A1.  In my code, when I specify the datatype as uint8_t I get values around the 200 range, yet when I change the type to uint16_t the values change to 1000 range.  Where should I be looking to understand this behavior?

body:
You should keep it `uint16_t`.

See: [analogRead][1].

It shows the return value is a 10 bit number, which means a value of 0 to 1023.

If you use `uint8_t`, which is an 8 bit value, it only can store values from 0-255.
This means if the value is higher, the most significant bits are clipped/removed, and you only have the value module 256 left.

With a 16 bit value, you will have the left 6 bits unused, but this does not matter. It has the 10 bits you get from the `analogRead` function.
Example

Assume the value is 1000, which is in binary:

    11 1110 1000

Written in 16 bits (using uint16_t), move it to the right and prefix with zeros you get:

    0000 0011 1110 1000

However, if you try to store this in 8 bits (using uint8_t) you get:

    (removed) 1110 1000

Which is the value 232 instead of 1000.

Some guidelines:

- Always use a type that fits the value you want to store (in worst case).
- If you know for sure your value will be non-negative, use an unsigned type (e.g. `uint8_t`).
- If you want to preserve memory (or good practice) use a value that is not necessarily big (thus if you know a value will never be more than 1023 like in your case, don't use `uint32_t`).

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/


message:
Condition in a while loop not updated on my mkr1010

I am using a server-client system where i send data from the server to the client to turn on a led (the onboard led). Led must be turned off using digital input (labeled 7 on the connector).
I use therefore a while loop that checks the value of the input (button press). As long as value is not equal to LOW the led remains on (i use also a second led on pin 13 as doublecheck). I assume that the while loop will be left once i press the button, unfortunately this doesn't happen. The result of the condition seems not updated (remains HIGH).
I measured the voltage on the input when pressing the button and it goes from 3.3V to 0.0V so hardware seems to be OK.
From my undestanding the while loop is always (before each loop) checking the condition ? why doesn't this happen here ? did i do something wrong ?
I must use a while because i never know in advance when the button will be pressed.

this my code :

    #include <SPI.h>
    #include <WiFiNINA.h>
    #include <utility/wifi_drv.h>
    #include "arduino_secrets.h"
    ///////please enter your sensitive data in the Secret tab/arduino_secrets.h
    char ssid[] = SECRET_SSID;        // your network SSID (name)
    char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)

    //int keyIndex = 0;            // your network key Index number (needed only for WEP)

    const int buttonPin = 7;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin
    int buttonState;         // variable for reading the pushbutton status

    int status = WL_IDLE_STATUS;
    IPAddress ServerIP(192,168,0,157);
    WiFiClient client;

    int i;
    String response;

    void setup() {

      WiFiDrv::pinMode(25, OUTPUT); //GREEN
      WiFiDrv::pinMode(26, OUTPUT); //RED
      WiFiDrv::pinMode(27, OUTPUT); //BLUE

     pinMode(buttonPin, INPUT);
     pinMode(ledPin, OUTPUT);

      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
       ; // wait for serial port to connect. Needed for native USB port only
      }
      // check for the WiFi module:
      if (WiFi.status() == WL_NO_MODULE) {
        Serial.println("Communication with WiFi module failed!");
        // don't continue
        while (true);
      }

      String fv = WiFi.firmwareVersion();
      if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
      Serial.println("Please upgrade the firmware");
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
        status = WiFi.begin(ssid, pass);
        // wait 10 seconds for connection:
        delay(10000);
      }

        // you're connected now, so print out the status:
      printWifiStatus();
    }

    void loop() {

    if (client.connect(ServerIP, 23)) {
      client.print("90");
      String response = client.readStringUntil('\n');

      Serial.println(response);

    if (response == "9") {
      buttonState = digitalRead(buttonPin);
     // Serial.println(buttonState);
      while (buttonState != LOW){
        // turn LED on:
        digitalWrite(ledPin, HIGH);
         WiFiDrv::digitalWrite(25, 255); // for full brightness
         Serial.println(buttonState);
      }
      digitalWrite(ledPin, LOW);
      WiFiDrv::digitalWrite(25, LOW); // for full brightness
            }
      }

      client.stop();
    }

    void printWifiStatus() {
      // print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your board's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
     Serial.println(ip);

      // print the received signal strength:
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }

thanks a lot for helping me out !

body:
     while (buttonState != LOW){
        // turn LED on:
        digitalWrite(ledPin, HIGH);
         WiFiDrv::digitalWrite(25, 255); // for full brightness
         Serial.println(buttonState);
      }

You never update the value of buttonState in this while loop.  If buttonState is not LOW to get into the while loop, nothing inside the while loop will ever change it so every time it gets checked it will still not be LOW.  It's not going to surmise that you meant to read a pin just because you used that variable to read a pin once before.

But do you really need this while loop?  Couldn't you just write the led pin low when you first get a press and then write it high when it first gets released?  See the "State Change Example".  Let the loop function be the loop.  It will lead to better code.  You don't see this now because you are a novice, but you are about to paint yourself into a corner with this approach and you'll soon be rewriting the whole thing.  It's a trap that gets most new coders.  Better to get it right now.


message:
Linux not recoginizing Arduino Mega2560 Clone

I have an Elegoo Mega2560 R3. On my Windows machine, it recognizes fine and loads exactly like a Mega2560. I have a System76 laptop running Pop_os!. When I attach the board, I cannot connect to the port in Arduino studio (reinstalled today with newest version).

When I check, I don't see the ttyACM1 device (ACM1 specifically because of items listed below).

`lsusb before plugging in`

Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 5986:9102 Acer, Inc BisonCam,NB Pro
Bus 001 Device 002: ID 046d:c52b Logitech, Inc. Unifying Receiver
Bus 001 Device 004: ID 8087:0aaa Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

`lsusb after plugging in`

Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 5986:9102 Acer, Inc BisonCam,NB Pro
Bus 001 Device 020: ID 2341:0010 Arduino SA Mega 2560 (CDC ACM)
Bus 001 Device 002: ID 046d:c52b Logitech, Inc. Unifying Receiver
Bus 001 Device 004: ID 8087:0aaa Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

`dmsg after plugging in`

[65178.203006] usb 1-6: new full-speed USB device number 19 using xhci_hcd
[65178.353353] usb 1-6: New USB device found, idVendor=2341, idProduct=0010, bcdDevice= 0.01
[65178.353359] usb 1-6: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[65178.353363] usb 1-6: Product: Arduino Mega 2560
[65178.353366] usb 1-6: Manufacturer: Arduino (www.arduino.cc)
[65178.353369] usb 1-6: SerialNumber: 7563331323335130F170
[65178.357650] cdc_acm 1-6:1.0: ttyACM1: USB ACM device

`ls /dev/tty*`

/dev/tty    /dev/tty23  /dev/tty39  /dev/tty54      /dev/ttyS10  /dev/ttyS26
/dev/tty0   /dev/tty24  /dev/tty4   /dev/tty55      /dev/ttyS11  /dev/ttyS27
/dev/tty1   /dev/tty25  /dev/tty40  /dev/tty56      /dev/ttyS12  /dev/ttyS28
/dev/tty10  /dev/tty26  /dev/tty41  /dev/tty57      /dev/ttyS13  /dev/ttyS29
/dev/tty11  /dev/tty27  /dev/tty42  /dev/tty58      /dev/ttyS14  /dev/ttyS3
/dev/tty12  /dev/tty28  /dev/tty43  /dev/tty59      /dev/ttyS15  /dev/ttyS30
/dev/tty13  /dev/tty29  /dev/tty44  /dev/tty6       /dev/ttyS16  /dev/ttyS31
/dev/tty14  /dev/tty3   /dev/tty45  /dev/tty60      /dev/ttyS17  /dev/ttyS4
/dev/tty15  /dev/tty30  /dev/tty46  /dev/tty61      /dev/ttyS18  /dev/ttyS5
/dev/tty16  /dev/tty31  /dev/tty47  /dev/tty62      /dev/ttyS19  /dev/ttyS6
/dev/tty17  /dev/tty32  /dev/tty48  /dev/tty63      /dev/ttyS2   /dev/ttyS7
/dev/tty18  /dev/tty33  /dev/tty49  /dev/tty7       /dev/ttyS20  /dev/ttyS8
/dev/tty19  /dev/tty34  /dev/tty5   /dev/tty8       /dev/ttyS21  /dev/ttyS9
/dev/tty2   /dev/tty35  /dev/tty50  /dev/tty9       /dev/ttyS22
/dev/tty20  /dev/tty36  /dev/tty51  /dev/ttyprintk  /dev/ttyS23
/dev/tty21  /dev/tty37  /dev/tty52  /dev/ttyS0      /dev/ttyS24
/dev/tty22  /dev/tty38  /dev/tty53  /dev/ttyS1      /dev/ttyS25

body:
Running avrdude as root works. <br>
Adding permissions to ttyACM0/ttyACM1 for everybody also works. Execute

     sudo chmod 777 /dev/ttyACM0
     sudo chmod 777 /dev/ttyACM1

and after that you should be able to compile and upload the code to the arduino
The only issue with this is that you have to run that line everytime you connect the Arduino to the USB because ttyACM0/ttyACM1 is recreated. So as pointed in the comment
if thats the case than you add dialout group to your user, log out, then log in again, you should have access to the Arduino serial.

     sudo usermod -a -G dialout yourUserName


message:
how do i connect my Arduino Nano to my Linux Laptop

**update:**
I uninstalled the portable package of Arduino IDE, completely, and installed the IDE using `sudo apt install arduino`. yes, I verified that my Nano was plugged in, the status on the bottom right says `Arduino Nano w/ ATmega328 on COM1`, but sadly the IDE won't explain to me _why_ the `Tools > Serial Port` section is still unavailable.

Also, the online version doesn't recognize the board even though it's plugged in and configured in the settings to look for a "Nano". I also used a reliable USB Hub I use for my drawing tablet, because that was one of the remedies to troubleshoot the lack of connection, and because the Hub seems to do a lot of good things around here.

**end of update**

I received an Arduino Nano as a gift a couple months ago and had to place it on a shelf as a mere dust collector, because it was not as easy as I thought it would be to get it working.
I plugged the Nano into my computer with a cable, and attempted to load an example "blink" program and it gives errors saying "no device connected" in the errors.

It does light up and flash, so I know it is receiving power, so how do I specify where the Nano is?
I am familiar with the /dev category and how to use code in Linux, but I don't know how to communicate with the Arduino, as in, know which block device the Nano is in /dev

now that Thomas has brought to my attention the "port" setting in the drop down menus, I just realized that the port is greyed out. that could be a good detail in troubleshooting this issue.

body:
In the [Arduino IDE][1], the mcu will show up in `Tools > Port`.
Your Arduino Nano will probably be visible at `/dev/ttyUSB0` or `/dev/ttyUSB1` following whatever is already plugged on USB. Make sure to select it.

Select `Nano` in `Tools > Board`.

Last step is  `Verify/Compile` your code (^R), then `Upload` (^U).

This [link][2] sounds to be a good read to start.

  [1]: https://www.arduino.cc/en/guide/linux
  [2]: https://www.arduino.cc/en/Guide/Environment


body:
I have to sadly conclude that this issue posted was for nothing. the board I was using most likely has an underlying defect (of all odds, the 45 boards my teacher was using, he gives me 1 defect board? believable.) rendering the board inoperable. I plugged the board into an entirely different laptop, downloaded and installed a full IDE for it, ran it normally, ran it in Administrator, downloaded and installed the plugin, ran the Online IDE to test that... same **exact** issues: greyed out serial port settings, and no device detected upon plugging in.

again, I apologize for this being a waste of time. I wished this was not the case and that I could make some pretty cool stuff during this quarantine mess.

I salute to all you programmers out there.... and wish you all good luck in your own endeavors in Arduino.


body: If you have managed your Linux security well, a normal user may not have access to the port where Arduino is plugged into. If so, try from terminal with "sudo arduino". (At least works for me)


message:
Using different variables in a function

I have a function `SetTFgr(float T, int FGr)` to set the time and filtergrade of my LED enlarger.

It works without a problem and changes the values of `T` or `Fgr` according to the buttons I press. Both `T` and `FGr` are global variables.

Now I want to use the same funtion with different variables.
When I call the function with `SetTFgr(TExp[i], FGrExp[i])` I would expect the function to work with the values of `TExp[i]` or `FGrExp[i]` and increase/decrease these values. It does not, it appears to use the value of `T` or `Fgr` instead.

How can I get what I am after?

body: Parameters of functions in C++ are by value. So `T` in your function is not the variable you use to call the function. It only has the same value. Use `float& T` to pass the reference to the variable.


body:
To be clear, you want to read the values of buttons (meaning unspecified) and use those values to set a float and an int variable. Further, you want to write a function that takes a couple of parameters that specify where you want to store those button values?

That is an unusual way to use function parameters. Usually function parameters specify an input value, and then you use that value to do something. Instead, you want to have the inputs be globally available readings (button values) and have the function parameters specify where to store those values.

C and C++ function parameters are usually passed "by value". That means that what gets sent to the function is a value, not a pointer to the variable that contains that variable. Thus the called function can't change the original variable.

If you want to pass a pointer to the variable, you have to use the `&` "address of" operator to pass the variable "by reference".

Your function might look like this using C++ pass by reference syntax:

    void SetTFgr(float &T, int &FGr) {
        float input_T = //figure out button value for T
        T = input_T;
        int input_FGr = //figure out button value for Far
        FGr = input_FGr;
    }

Then you'd invoke it like this:

    SeTFgr(T, FGr);

You could also accomplish the same thing using C pointer syntax.


message:
Tilt Compensated Compass Using HMC5983 gives inconsistent output

I've been trying to build a tilt compensated compass for an autonomous Arduino car I'm building. I'm having issues with the consistency of my data.

This is the code I'm using.

    #include <Wire.h>
    #include <I2Cdev.h>
    #include <MPU6050_6Axis_MotionApps_V6_12.h>
    #define Magnetometer_addr 0x1E
    MPU6050 mpu;

    bool dmpReady = false;
    uint8_t mpuIntStatus;
    uint8_t devStatus;
    uint16_t packetSize;
    uint16_t fifoCount;
    uint8_t fifoBuffer[64];
    float prevoius_corrected_reading,corrected_reading;

    Quaternion q;
    VectorFloat gravity;
    float ypr[3];

    bool mpuInterrupt = false;

    float Xerror = 0.01;
    float Yerror = -0.385;
    float Zerror = -0.17;

    int X0, X1, Z0, Z1,Y0, Y1;
    float X, Y, Z;
    float compass_heading;

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

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x01);
      Wire.write(0x00);
      Wire.endTransmission();

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x02);
      Wire.write(0x00);
      Wire.endTransmission();

      mpu.initialize();
      //Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
      devStatus = mpu.dmpInitialize();

        mpu.setXGyroOffset(51);
        mpu.setYGyroOffset(8);
        mpu.setZGyroOffset(21);
        mpu.setXAccelOffset(1150);
        mpu.setYAccelOffset(-50);
        mpu.setZAccelOffset(1060);

        if (devStatus == 0) {

            mpu.CalibrateAccel(6);
            mpu.CalibrateGyro(6);
            //Serial.println();
            mpu.PrintActiveOffsets();
            mpu.setDMPEnabled(true);
            dmpReady = true;
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {
            //Serial.print(F("DMP Initialization failed (code "));
            //Serial.print(devStatus);
            //Serial.println(F(")"));
        }

      delay(20);

    }

    void loop() {

      compass_heading = request_compass_data();

      Serial.print("Raw compass heading is \t");
      Serial.print(compass_heading);

      Serial.print("\t\t");

      request_accel_data();

      Serial.print("YAW\t:");
      Serial.print(ypr[0] * 180/M_PI);
      Serial.print("\tROLL\t:");
      Serial.print(ypr[1] * 180/M_PI);
      Serial.print("\tPITCH\t:");
      Serial.print(ypr[2] * 180/M_PI);

      prevoius_corrected_reading = corrected_reading;

      Serial.print("\tCorrected compass heading is \t");
      float Xhor =  X*cos(ypr[2]) + Z*sin(ypr[2]);
      float Yhor =  Y*cos(ypr[1]) - Z*sin(ypr[1])*cos(ypr[2]) + X*sin(ypr[1])*sin(ypr[2]);

      corrected_reading = rad_to_deg(rad_ang(Yhor, Xhor));
      Serial.print(corrected_reading);

      Serial.print("\tFiltered compass heading is \t");

      Serial.print(0.1 * corrected_reading + 0.9 * prevoius_corrected_reading);
      Serial.println();

    }

    float rad_ang(float a, float b){
      float ang = atan2(a, b);
      if(ang<0){ang += 2*PI;}
      if(ang>2*PI){ang -= 2*PI;}
      return ang;
    }

    float rad_to_deg(float rad_in){
      return rad_in / PI * 180;
    }

    float request_compass_data(){
      //return compass heading
      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x03);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      X0 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x04);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      X1 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x05);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      Z0 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x06);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      Z1 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x07);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      Y0 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x08);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      Y1 = Wire.read();
      }

      X0 = X0<<8;
      Z0 = Z0<<8;
      Y0 = Y0<<8;

      X = X1 + X0;
      X -= Xerror;
      Y = Y1 + Y0;
      Y -= Yerror;
      Z = Z1 + Z0;
      Z -= Zerror;

      //Calibrated manually
      X = X * 0.00092 - Xerror;
      Y = Y * 0.00092 - Yerror;
      Z = Z * 0.00092 - Zerror;
      /*
      Serial.print("XYZ\t");
      Serial.print(X);
      Serial.print("\t");
      Serial.print(Y);
      Serial.print("\t");
      Serial.println(Z);
    */
      float dir = rad_to_deg(rad_ang(Y, X));

      return dir;

    }

    void request_accel_data(){
            if (!dmpReady) return;
        mpuInterrupt = true;

        while (!mpuInterrupt && fifoCount < packetSize) {
            if (mpuInterrupt && fifoCount < packetSize) {
              fifoCount = mpu.getFIFOCount();
            }

        }

        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();
        //Serial.print("INT STATUS:\t");
        //Serial.print(mpuIntStatus);
        fifoCount = mpu.getFIFOCount();
        //Serial.print("\tFIFO COUNT:\t");
        //Serial.print(fifoCount);

        if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {

            mpu.resetFIFO();
            fifoCount = mpu.getFIFOCount();
            Serial.println(F("FIFO overflow!"));

        }

        else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
            mpu.getFIFOBytes(fifoBuffer, packetSize);
            fifoCount -= packetSize;
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            mpu.resetFIFO();

        }
    }

When I have the below sensor orientation my data output(corrected_reading) varies as shown in the below graph on one complete rotation.I'm happy with this output as there is only very little inconsistency and the tilt compensation works fine too.

[![Data variation][1]][1]

[![Sensor Orientation][2]][2]

However keeping them in the above orientation within my car is not practically possible in my case.
So I tried this orientation.
[![Sensor Orientation 2][3]][3]

But no matter how I adjust my code to suit this orientation I always end up getting very inconsistent data like below.

[![second Graph][4]][4]
[![third graph][5]][5]

I'm sure that there is some mistake i'm making in the second orientation i used.The biggest problem is that the raw magnetometer output(compass_heading) also becomes inconsistent in this case.

  [1]: https://i.stack.imgur.com/WYFsp.png
  [2]: https://i.stack.imgur.com/Es7t6.png
  [3]: https://i.stack.imgur.com/3jxye.png
  [4]: https://i.stack.imgur.com/xOTb5.png
  [5]: https://i.stack.imgur.com/Pten9.png

Please give me your suggestions as to what changes I should make in order to get a smooth output with the second orientation.
Thanks in advance.

Microcontroller - Arduino Uno
Magnetometer - HMC 5983
Accelerometer - MPU 6050

body:
As it is not possible to reproduce the errors and analyse the program in detail, the thing which jumped at me that you have no gliding error correction (or its hidden in a library) for the compass (The MPU6050 has probably one as FIFO is called but you should look it up). The method is easy to explain:

  - You take an array of lets say 20 measure points.
  - You apply FIFO First value in is the last out
  - you do gliding average over the first 15 values -> this is the orientation output
  - the last 2 are used for value validation:
    - if you get a value out of a defined data range AND the next is in the range then ditch the before value (error corection)
   - if you get a value out of a defined data range AND the next 4 values are also in the range compared tothe first out of range this will cause the array to empty and start a new gliding average with these values. (Might not be the case when driving a car but in plane models this can happen -> 180 degree turns)

Its up to you how many values you take as a base reference and how many lead to an aprupt direction change. As we are in hobby electronics you can not expect high quality value delivery sowe have to use math to get to a desired result.
Regarding the changed orientation of the magnetometer.
**EDIT**
In my experience the turning of the magnetometer upside down resultedin weird behavior and more unstable readings. I guess this is due to the elctronics shielding now from the top rather than the bottom.
For reading and error handling I looked [into this library code]((https://github.com/keepworking/Mecha_QMC5883L/blob/master/MechaQMC5883.cpp) and adapted the read routine to my needs. Also lookat the examplesfor valuable input.


message:
Using SDA and SCL with analog inputs at the same time

I'm trying to build a robot arm based on Arduino UNO and PCA9685 controlled by few potentiometers. The easiest way that I figure out and find on internet is using two Arduino's, one as master and second as slave.
This is where my question comes from, there is a way to use single Arduino UNO instead of two by using at the same time SDA and SCL with analog inputs? Maybe there is another way to do that?

That's my actual code:
```
#include <Arduino.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwmDriver = Adafruit_PWMServoDriver(0x40);

void setup()
{
  pwmDriver.begin();
  pwmDriver.setPWMFreq(51);
}

int tempPotVal = 0;
int adcPin[4] = {A0, A1, A2, A3};
int pwmRisingTime = 0;
int pwmFallingTime = 0;

void loop()
{
  for (int id = 0; id < 4; id++)
  {
    tempPotVal = analogRead(adcPin[id]);
    pwmFallingTime = map(tempPotVal, 113, 842, 102, 512);
    pwmDriver.setPWM(id, pwmRisingTime, pwmFallingTime);
  }
}
```

body:
No. You can't. Not unless you could come up with some way of disconnecting one set of devices and connecting the other.

Instead you could add an I2C ADC chip to the existing SCL/SDA bus to expand the number of ADC channels you have available. Or use an analog MUX chip on one of the other ADC pins to expand the number of devices you could connect to it. Or you could add an SPI ADC chip to pins 10-13 (SPI bus) to give you more analog inputs.


body: I2C on Uno/Nano/Mini uses only pins labeled A4 and A5. you can still use 4 ADC pins A0 to A3 on Uno.


message:
Is there a way to reuse an old robot using arduino?

I had purchased a simple robot (named Qu-Bot) for a school project a couple of years ago. After the project, it just went into the attic. A few days ago, I purchased an Arduino Uno and started learning the how to operate it. But, before I could purchase LEDs, sensors, LCD, etc, a total lockdown was implemented in my country due to coronavirus.

Is there a way I could program that old robot in Arduino IDE like I program my Uno?

> I'm not sure if this is useful or not, but, when I execute ```$ lsusb``` , the bot appears as ```Bus 001 Device 018: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port```

Here's a link to some documentation of the bot:
http://www.technogravity.com/products/qu_bot/qu_bot_downloads.php

Here are photos of all the 3 chips I can see on the board of the bot:

![](https://i.stack.imgur.com/p3Rce.jpg)

![](https://i.stack.imgur.com/NLCHW.jpg)

![](https://i.stack.imgur.com/jyOUF.jpg)

body:
As to your question can I program in ArduinIDE - Yes.

- The main chip is from AVR ATMEGA16,
- the LCD is a 16x2 (pinout for use with the LCD library is enclosed)
- motor driver is (Big thanks to Juraj not a mystery) a ULN2803. Example to work with can be [found here](https://roboindia.com/tutorials/arduino-stepper-motor/).

The circuit diagram enclosed:

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

How to use in ArduinoIDE:

  - First install the driver for prolific and makes sure your OS finds the robot  (done)
 - Then install the [MightyCore which supports ATMega16](https://github.com/mcudude/MightyCore) - there are detailed instructions how to do it
- Start with a blink led example (pins from the schematic) compile and upload to test
 - Then a simple LCD example and so on.

Another posibility would be tor scrap the bot and salvage most parts.

If its feasable the [Manual](http://robokits.co.in/documentation/Qu-bot_V2_Manual.pdf) will tell you which parts can be removed without soldering

To get started you need the [USB drivers for OS](http://robokitsworld.com/downloads/Qu-Bot USB Drivers All OS.zip) and the original SW to test wether the QBot is still ok from a hardware perspective,
Than you can salvage the parts from it to use with Arduino:
[![enter image description here][2]][2]

Than you have to make a new base plate (google for pics of 2-wheel robot base plates) and get a motor driver (I recommend for a beginner a cheap motor shield like an Adafruit V2 motor shield clone 5-7$).
As you probably have downloaded ArduinoIDE latest version for your OS, get some example programs and start to play around.

  [1]: https://i.stack.imgur.com/hnBpZ.jpg
  [2]: https://i.stack.imgur.com/gBMJN.jpg


body:
On your linked website I wasn't able to open the sample programs (404 Not Found). The site seems very outdated (it has news from 2015 on it). So I cannot be sure, how the robot is meant do be programmed.

But: The Atmega16A is a programmable microcontroller and it most likely is the brain of the robot. Depending on how the original bot was programmed, you can have 2 ways to go:

1. If it was originally build around the Arduino platform, meaning, that it already has a fitting bootloader in it, then you might be able to program directly over USB/Serial from the Arduino IDE.

2. If not you can program it with the Arduino IDE over ISP by using your Arduino Uno as a programmer. Look at [this documentation site][1] for a more detailed description, how this is done. Note, that you will most likely have to remove the Atmega from the bot for programming, since the programming can interfere with the circuit of the bot (The Atmega seems to be in a socket, so that you can remove it from there). After programming you can put it into the bot again.

In both cases you need to install the correct core for that chip in the Arduino IDE, for example by following [this guide][2] (found by a quick search, not tested). (Maybe you even can find a core specifically for that robot)

---

The other shown chips seem to be the motor drivers.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [2]: https://elementztechblog.wordpress.com/2016/10/28/mightycore-an-arduino-core-for-the-atmega16-atmega32-atmega324-and-more/


message:
Problem with interrupts and 4x encoders on Nano 33 BLE

I have a [Pololu 4x encoder](https://www.pololu.com/product/4761) and am trying to write some code to make it work on my Nano 33 BLE. (Interestingly enough, the issue preventing some pre-existing libraries from working for me is the same issue that I'm about to describe here...)

When I turn the motor shaft clockwise, these are the signals that I get (first bit in each pair is channel A, second bit channel B):

`11 -> 10 -> 11 -> 10 -> 11 -> 10`

Note how channel A's value never changes, and B's value toggles back and forth.

Likewise, for the counterclockwise direction:

`01 -> 11 -> 01 -> 11 -> 01 -> 11`

This is of course wrong, as [the channels' values should be something like `00 -> 10 -> 11 -> 01 -> 00` as the shaft turns](http://4.bp.blogspot.com/-w-6mSdd0s5A/UHULV8RjH_I/AAAAAAAAAok/-FBhle0uW8o/s400/ROTARY-state.png). As a matter of fact, that is exactly what I get when I run the *exact same code* on a regular Arduino Nano.

Does anyone know what's going on? Here's my code. AFAIK I'm not using interrupts incorrectly or anything, at least for the regular Nano.

```
#define PIN_A 2
#define PIN_B 3

volatile int val = 0;
volatile bool newVal = true;

void encoder() {
  int a = digitalRead(PIN_A);
  int b = digitalRead(PIN_B);
  val = ((a << 1) | b);
  newVal = true;
}

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

  pinMode(PIN_A, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, CHANGE);

  pinMode(PIN_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_B), encoder, CHANGE);
}

void loop() {
  if (newVal) {
    Serial.print(bool(val & 0b10));
    Serial.print(bool(val & 0b01));
    Serial.println();
    newVal = false;
  }
}
```

**EDIT:** After taking a look at the following diagram, it appears that the erroneous encoder patterns match those in which only rising edges are detected. So for some reason, `attachInterrupt()` is acting as if the `CHANGE` argument were `RISING` instead for the Nano BLE.

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

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

body:
Best practice would be to use a single interrupt for the encoder.  BLE has a faster processor and your code is not frame-based so that just might affect it also.  This code doesn't do exactly what your code did but it will use val to track position as a number.
It can also be made a bit finer using CHANGE instead of RISING, but for debugging bare bones means less that can go wrong.

    #define PIN_A 2
    #define PIN_B 3

    volatile int val = 0;
    int oldVal;
    //volatile bool newVal = true;

    void encoder() {
      if(digitalRead(PIN_B)) ++val;
      else --val;
    }

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

      pinMode(PIN_A, INPUT_PULLUP);
      pinMode(PIN_B, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, RISING);
    }

    void loop() {
      if (val != oldVal) {
        oldVal = val;
        Serial.println(oldVal);
      }
      delay(500);
    }


body:
So it turns out the cause of the issue was that `attachInterrupt()`'s implementation in the nRF528x Mbed core does not properly support rising/falling edge detection as required for mode `CHANGE`. I've [opened a pull request](https://github.com/arduino/ArduinoCore-nRF528x-mbedos/pull/69) implementing the changes required and tested them with my encoder, and I can confirm that everything works properly now.

If you'd like to test the updated core yourself, you can follow the installation instructions from the repo's [`README`](https://github.com/arduino/ArduinoCore-nRF528x-mbedos) or from this very well-written [forum post](https://forum.arduino.cc/index.php?topic=634250.msg4297961#msg4297961).


message:
Why do I keep blowing up Nanos when I solder them?

I have blown up 2 Arduino Nanos and I'm trying to figure out what I'm doing wrong.

In both cases, I was powering the boards with a 16V supply (I know this is high, but the regulator datasheet says it is good to 25V, and the regulator was not damaged). I unplug the supply and USB cable and then start soldering to one of the pins (A6). When I plug the board back in, the L LED does not flash, indicating the bootloader has been erased. The POW light is on and I still measure 5V, indicating the regulator is working. When I connect the board to my PC, the serial port pops up just fine. But when I try to upload a sketch, the IDE times out and says it cannot communicate with the board.

I attempted to reprogram the bootloader using a raspberry pi but avrdude also says it cannot find the device either. It looks like the microcontroller is blown.

My iron tip is grounded, so my best guess is some residual power in the supply travels through the microcontroller to my iron and shorts something out. But this seems unlikely seeing as A6 is an input and grounding it should be just fine even when the supply is fully on.

Any ideas what I could be doing wrong? FYI, I am cross-posting this on the Arduino forums.

body: My advice would be not to solder directly to the Nano pins.  Instead, use the appropriately sized DIL socket, and solder to the pins of that instead.   Then plug in the Nano once the soldering is complete.


message:
Receiving garbage value when sending a Json object from Arduino Uno to NodeMCU using SoftwareSerial

I am trying to send a Json Object from Arduino UNO to NodeMCU using SoftwareSerial. I am using Arduino IDE. I am getting garbage value on Serial monitor of NodeMCU. Tried it with different garbage values, couldn't receive data from Arduino UNO. Below is the code. PLease help. Thank you in advance. I haven't made a common ground. I have referred this webpage [here](https://engineeringprojectshub.com/serial-communication-between-nodemcu-and-arduino).

Arduino UNO code:

        #include <SoftwareSerial.h>
        #include <ArduinoJson.h>
        SoftwareSerial s(5,6);

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

        void loop() {
         StaticJsonBuffer<1000> jsonBuffer;
         JsonObject& root = jsonBuffer.createObject();
          root["data1"] = 100;
          root["data2"] = 200;
          if(s.available()>0)
          {
           root.printTo(s);
          }
        }

NodeMCU code:

        #include <SoftwareSerial.h>
        SoftwareSerial s(D6,D5);
        #include <ArduinoJson.h>

        void setup() {
          // Initialize Serial port
          Serial.begin(9600);
          s.begin(9600);
          while (!Serial) continue;

        }

        void loop() {
          StaticJsonBuffer<1000> jsonBuffer;
          JsonObject& root = jsonBuffer.parseObject(s);
          if (root == JsonObject::invalid())
            return;

          Serial.println("JSON received and parsed");
          root.prettyPrintTo(Serial);
          Serial.print("Data 1 ");
          Serial.println("");
          int data1=root["data1"];
          Serial.print(data1);
          Serial.print("   Data 2 ");
          int data2=root["data2"];
          Serial.print(data2);
          Serial.println("");
          Serial.println("---------------------xxxxx--------------------");

        }

body:
The problem with ArduinoJson.h is that it doesn't ensure robust and reliable transfer over UART serial.

Instead, you should use [SerialTransfer.h][1] to automatically packetize and parse your data for inter-Arduino communication without the headace.The library is installable through the Arduino IDE and includes many examples.

Here are the library's features:

> This library:
>
>  - can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
>  - works with "software-serial" libraries
>  - is non blocking
>  - uses packet delimiters
>  - uses consistent overhead byte stuffing
>  - uses CRC-8 (Polynomial 0x9B with lookup table)
>  - allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
>  - can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(115200);
      myTransfer.begin(Serial1);
    }

    void loop()
    {
      char buff[] = "hi";

      myTransfer.txObj(buff, sizeof(buff));
      myTransfer.sendData(sizeof(buff));
      delay(100);
    }

Example RX Arduino Sketch:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(115200);
      myTransfer.begin(Serial1);
    }

    void loop()
    {
      if(myTransfer.available())
      {
        char buff[40];

        myTransfer.rxObj(buff, sizeof(buff));

        Serial.println("New Data: ");
        Serial.write(buff, sizeof(buff));
        Serial.println();
      }
      else if(myTransfer.status < 0)
      {
        Serial.print("ERROR: ");

        if(myTransfer.status == -1)
          Serial.println(F("CRC_ERROR"));
        else if(myTransfer.status == -2)
          Serial.println(F("PAYLOAD_ERROR"));
        else if(myTransfer.status == -3)
          Serial.println(F("STOP_BYTE_ERROR"));
      }
    }

  [1]: https://github.com/PowerBroker2/SerialTransfer


message:
C3 not declared in this scope when running MIDI example code

I'm trying to run the [MIDI example from Arduino.CC](https://www.arduino.cc/en/Tutorial/MidiDevice) in Arduino Studio.

I am using an Arduino Leonardo, which has USB HID capabilities. I have installed the library as mentioned:

[![MIDI Library installed][1]][1]

When I press the compile or upload button, it says:

    'D3' was not declared in this scope

What's wrong? How do I fix this?

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

body:
The pitches for the notes are taken from [pitchToNote.h](https://github.com/arduino-libraries/MIDIUSB/blob/master/src/pitchToNote.h). In there you can see definitions for the notes like:

    #define pitchC3  48

It seems that the names were changed from `C3` to `pitchC3`.

I am not 100% sure, but my guess is that this was done to avoid conflicts between the note `A3` and the analog input `A3` (and silimar).

So, in line 25 of the example code, add `pitch` for all notes:

    const byte notePitches[NUM_BUTTONS] = {pitchC3, pitchD3, pitchE3, pitchF3, pitchG3, pitchA3, pitchB3};


message:
Why can't I use 3V output of arduino pro mini?

I have an Arduino pro mini and I tested digital write of an pin and it is 3.2V and then I connected it to a 3V motor, but when I connected the motor to it, The voltage drops under 0.2 Volt, Can any one describe the science behind voltage drop ?

I know I've better use a transistor and separate the motor power but, what you should do when you have a single 3V power source? and I know there are some motor driver chips, but is it possible to keep it simple?

body:
**NEVER** drive a motor directly from an Arduino IO pin.  You **will** kill the Arduino.

It's not a question of voltage, it's a question of current, and that is where the transistor comes in.  If you have a 3.3V Arduino (as it sounds like you have) then you *may* be able to drive the motor using the 3.3V output of the Arduino (VCC pin? Not sure with that model) and a transistor. That is the *simplest* arrangement.

<!-- 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/aCf8t.png)

<!-- End schematic -->


body:
You can drive the motor from the same 3v supply that powers your Arduino (assuming the supply can deliver enough current for both). What you can't do is power the motor *through* the Arduino, neither from a pin, nor from its on-board voltage-regulator. And especially don't try to use a 5v Arduino's 3v pin to drive it. Their 3v regulators provide only a limited amount of current.

If you try to drive a motor through the Arduino and it needs too much current, you risk frying the Arduino. If you supply the motor from the same power supply but not through the Arduino, and the motor takes too much current, the worst that will happen is the supply voltage will fall and Arduino will shut down.


message:
IR Remote with Arduino

I want to build a remote with Arduino Nano. I have viewed many tutorials in the web, but I don't have the IR Receiver (TSOP1740). Is there any way to use Jjust an IR Led as the receiver?

body:
No, you can't use *just* an IR LED as the receiver.  While it is true that an IR LED can also be an IR receiver the voltages it generates are really really small. So you would need an amplification circuit. On top of that the TSOP1740 includes a band-pass filter to isolate the carrier frequency of the transmitted signal from the background light, which you would *also* need to implement.

So yes, while you *could* use an IR LED as a receiver, you need a large amount of support circuitry with it (which takes expertise not relevant to this website) to get it to do anything useful.


body:
You could make a remote without a receiver.  It would require knowing what signals to send.  The receiver is to essentially help in training your arduino by letting it detect the signal from an already working remote and then replay it on the LED.

You can't make a receiver with JUST an LED. (Majenko's got this one covered).


message:
SD card with arduino UNO

I am trying to use a micro SD card in order to store data sent from an arduino UNO.
My setup consists of:

 - Arduino UNO (5V logic), powered directly from USB cable
 - [Digilent Full-sized SD Card Slot][1]
 - Simple microSD to SD adapter
 - Transcend 4GB microSD card SDHC
 - [TXB104 Logic Level Converter][2]
 - USB-powered PSU, that provides both the 3.3Volts and the 5Volts

The above components are connected as mentioned below:
Pins 1 to 4 of the Digilent SD module are driven to the 3.3Voltage side of the logic level converter. Also the SD module is powered with 3.3Volts. The 4 signals (SS, MOSI, MISO, SCK) are then taken from the 5Volt side of the logic level converter and are driven to the arduino UNO pins 10, 11, 12 and 13 respectively. Also, all the components have a common ground. The card is formatted to FAT32 using the [SD card Formatter][3] from sdcard.org.

In the arduino, I upload the SdInfo sketch of the Sdfat library. The result I get is the following:

[![enter image description here][4]][4]

Let me know if I can provide any more info.

  [1]: https://store.digilentinc.com/pmod-sd-full-sized-sd-card-slot/
  [2]: https://www.ti.com/lit/ds/symlink/txb0104.pdf?ts=1587925861218
  [3]: https://www.sdcard.org/downloads/formatter/eula_windows/index.html
  [4]: https://i.stack.imgur.com/dBW2Q.png

body:
I doubt the SDHC card is supported.

I don't have the same card slot reader, however, mine only worked with 'old' SD cards, not SDHC, SDXC etc.

So try an old one to see if it works (at least you rule out this option).