body:
ok so I dont actually know anything about coding or electronics outside of being an electrician. This is something i've been working on for about a month.
I may be asking something dumb but here it is.

also i dont know where to put my code so ill put it in the comments (sorry).

so basically I want a visual metronome. I want to plug a control box into the wall, plug a lamp into the control box to blink at a set interval. the box will have a rotary encoder and lcd display to control the beats per minute. to achieve this im gonna use a SSR and some transformers to achieve a variety of voltages for different led lights. but I want to affect a 120v cct to do it all. but I just want to get the code down before I build it so im trying to blink the onboard led on my arduino uno for now.

I have the code, which is 3 different sketches, frankensteined together. probably poorly.
I added an arithmetic equation to facilitate the metronome timing but I cant transfer that value to the "interval" for the blinking light.

In my serial viewer, the equation works and it gives me the values I desire. I just cant get that into the interval.

the math equation is simple
(60/bpm)1000 = intended interval

example: (60/120)1000 = 500 as the milli interval for the blinking light. 2 blinks per second.

    enter code here

    // rotary encoder -----------------

    int val;
    int encoder0PinA = 6;
    int encoder0PinB = 7;
    int encoder0Pos = 59;
    int encoder0PinALast = LOW;
    int n = LOW;

    // lcd screen ---------------------

         // include the library code:
    #include <LiquidCrystal.h>

         // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    // led blink ----------------------

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

         // ledState used to set the LED
    int ledState = LOW;

         // will store last time LED was updated
    unsigned long previousMillis = 0;

         // interval at which to blink (milliseconds) --    long interval = ;

    // mathssss -----------------------

    float a = (60 / encoder0Pos) * 1000;

    // on to setup -------------------------------------------------------

    void setup() {
          // put your setup code here, to run once:

    // rotary encoder ---------------
     pinMode (encoder0PinA, INPUT);
      pinMode (encoder0PinB, INPUT);
      Serial.begin (9600);

      Serial.println ("hi");

    // lcd screen -------------------
          // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
          // Print a message to the LCD.
      lcd.print("BeatsPerMinute");

    // led blink -------------------
    pinMode(ledPin, OUTPUT);

    }

    // on to loop --------------------------------------------------------
    void loop() {
          // put your main code here, to run repeatedly:
          long interval = (60.00 / encoder0Pos) * 1000;

    // rotary encoder --------------
      n = digitalRead(encoder0PinA);
      if ((encoder0PinALast == LOW) && (n == HIGH)) {
        if (digitalRead(encoder0PinB) == LOW) {
          encoder0Pos--;
        } else {
          encoder0Pos++;
        }

         // serial ----------------------------------------------------------------------
      Serial.println ("BPM");
      Serial.println (encoder0Pos);
      Serial.println ("interval");
      Serial.println (interval);
      Serial.println ("intended interval");
      Serial.println (60.00 / encoder0Pos * 1000, 8);
      Serial.println ("----------------");
         // serial done -----------------------------------------------------------------
      }
      encoder0PinALast = n;

      // lcd screen ----------------

           // set the cursor to column 0, line 1
           // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
           // print the number of seconds since reset:
      lcd.print(encoder0Pos);

      // led blink -----------------

        unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
          previousMillis = currentMillis;
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        digitalWrite(ledPin, ledState);

     // serial --------------------

     // done

      }

    }

title: Can I get some help with a metronome code on my arduino uno?

Answers: 1

body:
As I wrote in my comment, you don't actually set the value of `interval` to the new value, when the encoder position changes. So the blinking interval does not change. You need to use the formula to set the new value to `interval`. Insert

    interval = 60.00 / encoder0Pos * 1000;

before your `Serial.print()` statements. Also, you need to remove the `const` keyword at the definition of `interval`, or you won't be able to change it's value.

---

Judging from your comments, you misunderstand how variables work. A variable does not save a formula, just a value. `a` is defined at global scope in your code (outside of any function). That means, that the definition get's executed at the very start of the program. Since `encoder0Pos` has the value 59 at that time, the value `1016.95` get's assigned to the variable `a`. This value only ever changes, if you actively assign a new value to that variable (which you never do). The formula is only executed once during the assignment.


body:
I have a 'pulse train' generated from a photo interrupter and slotted disc mounted on a rotating shaft. My goal is to measure the time between each rising edge.

I have looked at the data sheet for the SAM3X8E and figured out that I need to configure a timer in 'capture mode' to do this.

My problem is that I am new to Arduino Due / this level of programming so I do not know how to set-up all the prerequisites before this (PIO, PMC, SYSCLK? etc.)

I have spent an extensive period trying to find help/ example code to no avail. Anything I do find is on Arduino Uno or Mega and therefore is of little help because of the different architecture.

Can anyone help or has anyone else done this/ similar problem?

(I am using Atmel Studio 7 as it seems to be the go-to for advanced SAM3X8E programming)

Thanks

title: Arduino Due: Measuring the time between pulses

Answers: 0


body:
I'm working on phone-controlled car park gate. Trusted employees numbers are saved on SIM card/hard coded in program. So the idea is, if a trusted person calls  the "gate number" ; Nodemcu  will trigger a relay. The key issue is the "CLIP:"  line which is supposed to appear each time on the serial connection during incoming call. When it appears I can parse it in order to determine if the "source" number is "trusted". CLIP: line is the only one where the "source number" is visible. I've got the impression that the line sometimes appears and sometimes not. There is no rule , but usually it appears right after rebooting the controller . So now, I'm rebooting my Nodemcu every 10 minutes but even that doesn't guarantee success. Furthermore, the "RING line" appears on the serial connection always  during the incoming call (but in RING line there is no number)
I've already tested 2 GSM modules, based on SIM800L & A6 GSM/GPRS chips. The same problem.
I got stuck with and have no more ideas. Maybe someone here had the same problem? Thanks for any help.

PS
of course I send AT+CLIP=1 to the GSM module in setup function, and later in the main loop (just in case)

--------------- the most important piece of code below ----------

    void loop() {

      while(mySerial.available()) {
        incomingByte = mySerial.read();
        inputString += incomingByte;
        //Serial.print(incomingByte);
      }

      if (inputString.indexOf("MYNUMBER") > 0){
        trustedisCalling();//this function does the rest and it's OK
      }
    }

-------------------------------------------------
when I uncomment:

    Serial.print(incomingByte);

Sometimes I can see the CLIP line on serial console but sometimes not. RING notification, which is subsequent to CLIP appears always during incoming call.

title: Nodemcu & GSM module & CLIP problem (CLIP line not always appears on the serial connection)

Answers: 0


body:
I have used the below code with proper Wifi Address and password. The Nodemcu connects to WIfi, and displays IP address, But the IP address cannot be used to open a web page. It says "This site cant be reached". Can anyone help with this

    #include <ESP8266WiFi.h>

    const char* ssid = "***";
    const char* password = "*******";

    int ledPin = D0;
    WiFiServer server(80);

    void setup() {

      pinMode(ledPin,OUTPUT);
      digitalWrite(ledPin,LOW);

      Serial.begin(115200);
      Serial.println();
      Serial.print("Wifi connecting to ");
      Serial.println( ssid );

      WiFi.begin(ssid,password);

      Serial.println();
      Serial.print("Connecting");

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

      Serial.println();

      Serial.println("Wifi Connected Success!");
      Serial.print("NodeMCU IP Address : ");
      Serial.println(WiFi.localIP() );

      server.begin();
      Serial.println("NodeMCU Server started");

      // Print the IP address
      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");

    }

    void loop() {

        // Check if a client has connected
      WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("Hello New client");
      while(!client.available()){
        delay(1);
      }

       // Read the first line of the request
      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();

       // Match the request

      int value = LOW;
      if (request.indexOf("/LED=ON") != -1)  {
        digitalWrite(ledPin, HIGH);
        value = HIGH;
      }
      if (request.indexOf("/LED=OFF") != -1)  {
        digitalWrite(ledPin, LOW);
        value = LOW;
      }

    // Set ledPin according to the request
    //digitalWrite(ledPin, value);

      // Return the response
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println(""); //  do not forget this one
      client.println("<!DOCTYPE HTML>");
      client.println("");

      client.print("Led pin is now: ");

      if(value == HIGH) {
        client.print("On");
      } else {
        client.print("Off");
      }
      client.println("

");
      client.println("<button>Turn On </button>");
      client.println("<button>Turn Off </button>
");
      client.println("");

      delay(1);
      Serial.println("Client disonnected");
      Serial.println("");

    }

title: NodeMCU ESP8266 Returns IP address, but cant open the web with IP address

Answers: 0


body:
    #include <Servo.h>
    const int buttonPin = 3;
    int buttonState = 0;

    Servo myservo;
    void setup() {
        myservo.attach(2);
        pinMode(buttonPin, INPUT);
    }

    void loop() {
        buttonState = digitalRead(buttonPin);
        if (buttonState == HIGH){ myservo.write(90); }
        else { myservo.write(155); }
        delay(1000);
    }

title: I am making a rubber band gun but i cant seem to get the button to work with my code to turn the servo?

Answers: 2

body:
Just put your button between pin3 and GND, and use the internal pullup resistor like this:
```
#include <Servo.h>
const int buttonPin = 3;
int buttonState = 0;

Servo myservo;
void setup()
{
    myservo.attach(2);
    pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
    buttonState = digitalRead(buttonPin);
    if(buttonState == LOW)
    {
      myservo.write(90);
    }
    else
    {
      myservo.write(155);
    }
    delay(1000);
}
```

body:
There are two problems you should pay attention to when using the button:

 - Floating input: => using pull-up or pull-down resistor, [see Using pull-up/ pull-down][1]
 - Chattering phenomenon => Debounce [See button debounce][2]

  [1]: https://arduinogetstarted.com/tutorials/arduino-button
  [2]: https://arduinogetstarted.com/tutorials/arduino-button-debounce


body:
I have a 5 meter strip of 12V digital RGB LEDs. The chip is WS2811 (see photo of IC). There are 50 addresses on the strip.

[![WS2811 IC][2]][1]

Using the [FastLED library][3], I am able to run the "FirstLight" example that chases full white with a single address at a time, up and down the length. That works fine. So I know they individually perform properly.

However, if I set all LEDs to full white (255), the first few addresses look white but then the higher the address, the more red it is. See photo below. The strip starts in the center of the reel.

[![All white WS2811 issue][4]][4]

    #include <FastLED.h>

    // How many leds are in the strip?
    #define NUM_LEDS 50

    // Data pin that led data will be written out over
    #define DATA_PIN 5

    // This is an array of leds.  One item for each led in your strip.
    CRGB leds[NUM_LEDS];

    // This function sets up the ledsand tells the controller about them
    void setup() {
     // sanity check delay - allows reprogramming if accidentally blowing power w/leds
        delay(2000);
     Serial.begin(115200);
     Serial.print("### SETUP ###");

          //Both strips are ordered BRG
          FastLED.addLeds<WS2811, DATA_PIN, BRG>(leds, NUM_LEDS);
          //FastLED.addLeds<UCS1903, DATA_PIN, BRG>(leds, NUM_LEDS);

    }

    void loop() {

       for (int i = 30; i < NUM_LEDS; i++) {

        leds[i] = CRGB::White;

       }

       FastLED.show();
    }

---

To debug, I tried turning on just the last half. The result was still problematic:
[![WS2811 last half][5]][5]

    for (int i = 30; i < NUM_LEDS; i++) {

        leds[i] = CRGB::White;

    }

---

I then tried setting all LEDs to white at half brightness, and that looks much better, but the LEDs at the outside are still off-color compared the inside:
[![WS2811 white half brightness][6]][6]

---

I've tried setting the whole strip to full blue, and that works fine.

I also have another nearly identical LED strip that instead uses the 1903 chip. The same code (initialized for 1903 instead of WS2811) works just fine on the 1903 strip!

Other things I've ruled out:

 - I'm using a bench power supply capable of 5A, this strip pulls less than 1.5A on full white.
 - I have verified the supply holds at 12V
 - I have not let the LEDs heat up while coiled in the reel. I make sure to unplug them after observing their color.

What could cause this on the WS2811 strip while the 1903 strip works perfectly?

  [1]: https://i.stack.imgur.com/uigus.jpg
  [2]: https://i.stack.imgur.com/uigusm.jpg
  [3]: https://github.com/FastLED/FastLED/wiki/Pixel-reference
  [4]: https://i.stack.imgur.com/NFZPf.jpg
  [5]: https://i.stack.imgur.com/rwkBg.jpg
  [6]: https://i.stack.imgur.com/ZqMwM.jpg

title: Addressable RGB strip works fine individually but cannot set all LEDs to full white

Answers: 6

body:
I would suspect that it is a voltage drop in the power rails caused by the current draw. Probably cheap construction with copper tracks that are just too thin and so have too high a resistance.

To combat it you will need to inject power into the strip at various points along it.  Initially to prove the theory you can try connecting the power to both ends of the strip and see if the "dull" spot is half way along the strip.  If it is, then it's certainly a voltage drop.  (incidentally, a voltage drop will cause the blue LEDs to fade out first making it go yellow-red. Then the green ones would probably be next, making it go red).

Then, once proved, you will need to add extra power connections into the strip at the middle of any dim sections and feed the voltage directly in at those points.

body:
Majenko's answer is correct, and you could also verify it with the test performed.

Since it is an issue I encountered myself in the past in a similar case, I want to share some measurements I took on the LED strip I have, in case it can be useful for you or other people.

Premise: the tests were done with a 5m 60 leds/m RGBW strip (SK6812, natural white).

The first test was done to measure the current from each LED. These are the results:

* All LEDs off: 230 mA (0.77 mA/led)
* 10 LEDs to max RED, GREEN or BLUE (one color): 320 mA
* 10 LEDs to max WHITE: 410 mA

This means that each R, G or B led absorbs at max 9 mA, while the W ones have a 18 mA current. Each LED, whether on or off, has a 0.77 mA current flowing through it.

In order to evaluate the voltage drop, I then turned on to full white the first 100 leds, then measured the current, the input voltage and output voltages of the strip. I got a voltage drop from 4.8 V to 4.16 V with a current of 2.11 A (which is almost equal to 230mA + 18mA/led * 100led).

I then modeled the strip as a sequence of ideal current generators joined by resistors:

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

<!-- End schematic -->

Calling R the resistance introduced by the strip, I_Led the current flowing into one LED and N the number of LEDs turned on (and ignoring the effects of the standby current), the voltage drop on the first resistor is dV1 = R*N*I_Led, the one on the second is dV2 = R*(N-1)*I_Led and so on, up to dVN = R*I_Led. The total voltage drop is dV = R*N*(N+1)*I_Led/2.

Using the measured data, we can calculate the resistance between two consecutive LEDs:

R = (2*dV)/(N*(N+1)*I_Led) = (2*0.64V) / (100*101*0.018A) = 7mOhm

NOTE: this is neglecting the effects of the standby current. However in my calculations I was searching for a worst case, and by excluding these effects I was in fact making worst assumptions, so I did not care about them

So, with this resistance I was able to calculate the voltage drop for arbitrary strips and consequently plan where to put the power supply joints. In my case I planned to have at max stubs 1.2m long (80 LEDs), so that the voltage at the end, in the very worst case (all LEDs on in RGBW, at max brightness), I had a voltage drop of slightly more than 1V.

Note that in my setup the voltage drop on the first element (the one with the largest drop) is (80*0.045A*0.007mOhm) = 25mV, with a power dissipation of 90mW.

body:
Those types of strip are simply not sized for full-on on all LEDs. It's expected that if you wanted that, you'd be running a parallel LED strip for lighting that is not addressible and that uses a much higher voltage such as 12 or 24V, where voltage drop is less critical.

Generally addressible LEDs aren't meant to be used in long strips, but are expected to be fit into an array of some kind with numerous short strips, where each can be fed individually.

Running a long stretch isn't a problem, but you will need to feed power at many locations if you want this level of illumination. And you will get murdered on either wire size or voltage drop because voltage drop is so critical when your voltage is only 5 volts.  Crunch the numbers but you can find yourself buying big 1/0 feeder wire in a hurry. I recommend instead carrying power at 24V or mains and converting to 5V in many locations.

I would suggest rethinking the design intent and if illumination is also desired, run a separate strip just for that.  Those are dirt cheap.

body:
The LEDs require 12v but the chips require lower voltage.
The WS chip requires 3.3v to 5v unlike the 6-7v that the IC require, the added resistance along with the fact that the last led has to run  10 metres on a return trip (5m on positive, 5m on negative = 10m total) could mean the drop is to much.

Easier way to find out is to connect in the middle, if it the problem persists (both ends are bad) it's the power supply

body:
As others have answered, it is because of voltage drop.

If you feed positive to the connector at one end, and negative to the other end, all leds will see the same voltage drop, as all leds have 5m connection to the power supply.

If we call the ends L and R with L+ and L- and R+ and R-:

Connect + to L+ and - to R-

If you want to be advanced, get a power supply with separate output and sense connections.

Then connect sense+ to R+ and sense- to L-

This will ensure that the voltage across the LEDs are 12V, by raising the voltage to compensate for the voltage drop.

I started a drawing in CircuitLab, but they want money now?! How rude...

body:
For completeness, I want to include an RGB circuit simulation I made a while ago, along with some data. It's for analog RGB strips, but the concept regarding voltage drop is the same. I've since added a few more LEDs to show the effect of voltage drop across the length, and added the ability to switch the power connection as well.

The simulation shows the current through each 3-LED segment. 12V strips typically have 3 LEDs in series, and repeat that along the strip.

When I created this simulation, I chose exaggerated resistance values, however, this WS2811 strip may be rather close. I haven't modeled it with particular measurements though.

There are switches in simulation circuit that you can click on to switch the connection to 12V and ground at either end of the strip.

[**\[Link to simulation\]**][1]
[![12V LED strip simulation][2]][2]

---

**Results:**

With 12V and ground on the same end:  28.389mA - 27.892mA = **2.123mA difference**

With 12V and ground on both ends:        28.389mA - 27.892mA = **0.497mA difference**

With 12V and ground on opposite ends: 27.310mA - 26.834mA = **0.476mA difference**

**While both power and ground can be connected at both ends of the strip, this simulation actually shows a better balance by simply moving the ground to the opposite end of the strip that receives 12V.**

The only way for each LED segment to be truly balanced would be for each to have it's own connection to power and ground.

[1]: http://www.falstad.com/circuit/circuitjs.html?cct=$+1+0.000005+1.5642631884188172+45+5+43
d+-128+80+-128+112+3+old-default-led
r+-128+176+-128+224+0+220
v+-352+288+-352+240+0+0+40+12+0+0+0.5
w+-352+400+-352+288+0
368+-128+80+-128+32+0+0
368+-128+320+-128+352+0+0
g+-352+400+-352+416+0
r+-128+80+-64+80+0+0.2
r+-128+320+-64+320+0+0.2
r+-64+320+0+320+0+0.2
r+-64+80+0+80+0+0.2
r+-64+176+-64+224+0+220
r+0+320+64+320+0+0.2
r+0+80+64+80+0+0.2
r+0+176+0+224+0+220
r+64+320+128+320+0+0.2
r+64+80+128+80+0+0.2
r+64+176+64+224+0+220
r+128+176+128+224+0+220
w+496+400+-128+400+0
370+-128+224+-128+272+1+0
370+-64+256+-64+320+1+0
w+-128+272+-128+320+0
w+-64+256+-64+224+0
w+128+272+128+320+0
370+128+224+128+272+1+0
w+0+272+0+320+0
370+0+224+0+272+1+0
w+64+256+64+224+0
370+64+256+64+320+1+0
d+-128+112+-128+144+3+old-default-led
d+-128+144+-128+176+3+old-default-led
d+-64+144+-64+176+3+old-default-led
d+-64+112+-64+144+3+old-default-led
d+-64+80+-64+112+3+old-default-led
d+0+144+0+176+3+old-default-led
d+0+112+0+144+3+old-default-led
d+0+80+0+112+3+old-default-led
d+64+144+64+176+3+old-default-led
d+64+112+64+144+3+old-default-led
d+64+80+64+112+3+old-default-led
d+128+144+128+176+3+old-default-led
d+128+112+128+144+3+old-default-led
d+128+80+128+112+3+old-default-led
x+-335+358+-184+361+4+12+Switch\sground\sconnection\s->
370+-352+240+-352+208+1+0
d+448+80+448+112+3+old-default-led
d+448+112+448+144+3+old-default-led
d+448+144+448+176+3+old-default-led
d+384+80+384+112+3+old-default-led
d+384+112+384+144+3+old-default-led
d+384+144+384+176+3+old-default-led
d+320+80+320+112+3+old-default-led
d+320+112+320+144+3+old-default-led
d+320+144+320+176+3+old-default-led
d+256+80+256+112+3+old-default-led
d+256+112+256+144+3+old-default-led
d+256+144+256+176+3+old-default-led
d+192+144+192+176+3+old-default-led
d+192+112+192+144+3+old-default-led
370+384+256+384+320+1+0
w+384+256+384+224+0
370+320+224+320+272+1+0
w+320+272+320+320+0
370+448+224+448+272+1+0
w+448+272+448+320+0
w+256+256+256+224+0
w+192+272+192+320+0
370+256+256+256+320+1+0
370+192+224+192+272+1+0
r+448+176+448+224+0+220
r+384+176+384+224+0+220
r+384+80+448+80+0+0.2
r+384+320+448+320+0+0.2
r+320+176+320+224+0+220
r+320+80+384+80+0+0.2
r+320+320+384+320+0+0.2
r+256+176+256+224+0+220
r+256+80+320+80+0+0.2
r+256+320+320+320+0+0.2
r+192+320+256+320+0+0.2
r+192+80+256+80+0+0.2
368+448+80+448+32+0+0
r+192+176+192+224+0+220
d+192+80+192+112+3+old-default-led
r+128+320+192+320+0+0.2
r+128+80+192+80+0+0.2
w+496+320+448+320+0
w+-352+208+-352+80+0
x+61+11+168+14+4+16+RGB\sLED\sStrip
x+481+425+495+428+4+8+Bort
w+496+80+448+80+0
368+-64+80+-64+32+0+0
368+0+80+0+32+0+0
368+64+80+64+32+0+0
368+192+80+192+32+0+0
368+128+80+128+32+0+0
368+256+80+256+32+0+0
368+320+80+320+32+0+0
w+496+-16+-160+-16+0
368+384+80+384+32+0+0
w+496+80+496+-16+0
s+-208+80+-160+80+0+0+false
s+-208+32+-160+32+0+1+false
s+-176+400+-128+400+0+0+false
x+-366+58+-219+61+4+12+Switch\spower\sconnection\s->
w+-128+80+-160+80+0
w+-208+80+-208+32+0
w+-160+32+-160+-16+0
s+-176+320+-128+320+0+1+false
w+-176+400+-224+400+0
w+-176+400+-176+320+0
w+496+400+496+320+0
368+64+320+64+368+0+0
368+128+320+128+352+0+0
368+0+320+0+352+0+0
368+-64+320+-64+368+0+0
368+256+320+256+352+0+0
368+192+320+192+368+0+0
368+384+320+384+352+0+0
368+320+320+320+368+0+0
368+448+320+448+368+0+0
w+-352+400+-224+400+0
w+-352+80+-208+80+0
x+-326+268+-284+271+4+12+12V\sDC

[2]: https://i.stack.imgur.com/ePafx.png


body:
I am trying to connect my MKR IMU Shield to my MKR1000 by placing the IMU shield in the MKR1000. When I do this, however, the Arduino IDE and Simulink are unable to find the port that my Arduino is connected to.

However, when my IMU shield is not connected to my MKR1000, the port can be found properly, and the code can be uploaded to the board. When I plug my IMU shield into my MKR1000 after the code has uploaded, my project crashes with an error.

Any ideas on how I can correct this so that I can able to connect to my MKR1000 when the IMU shield is plugged in? Thank you for all your help.

title: MKR 1000 not found in ports when MKR IMU Shield is connected

Answers: 0


body:
I am trying to create an unassigned array of size 512 and then assigning a reading to each indices. I want to get the start time before and after the loop and only run it once. Then I want to know how to retrieve the readings and serialprint the values after the loop. So far this is what I have but I don't think it is running as I want it to. I was able to get the start time but I'm not sure if it is running afterwards. Any help is greatly appreciated. Thanks!

```
void setup() {
int Vs[512] = {};
int analogPin = A0; // turn pin A0 on
pinMode(9, INPUT);
Serial.begin(9600); // setup serial
analogWrite(9, pow(2, 7)); //LED power 0
int time = micros();
Serial.println(time);
}

void loop() {
int i;
for (int i = 0; i <= 511; i++); { //loop setup for 512
int c = analogRead(A0) * (5.000/1024.000);
int Vs[i] = {c};
Serial.println(Vs[i]);
}
int stoptime = micros();
Serial.println(stoptime);
}

void stop() {
while(1);
}
```

title: Creating an array, assigning a value to each indices, and assessing the array

Answers: 1

body:
There are multiple issues with your program. The most obvious is that,
if you define a variable multiple times, you end up with mutliple
_different_ variables that share the same name. For example:

```c++
void setup() {
    int Vs[512] = {};  // this Vs is local to setup()
}

void loop() {
    int i;  // this i is local to loop()
    for (int i = 0;  // this other i is visible within the for loop only
            i <= 511;
            i++)
        ;  // this is the body of the for loop
    {
        ...
        int Vs[i] = {c};  // this Vs is local to loop()
    }
}
```

Another issue I pointed out in the snippet above is that a semicolon by
itself is an empty (i.e. do-nothing) statement. Thus you `for` loop is
empty.

There is no point in defining a constant such as `analogPin = A0` if you
don't use it.

The value returned by `micros()` is not an `int`, it's an
`unsigned log`.

If you store a voltage in volts in an `int`, you get a very poor
resolution of one volt. You could store in a `float`, but that would
fill up the memory of your Arduino. I would rather store the raw
readings, and convert to volts only for printing.

`Serial.println()` takes time, and you are doing this during the timed
part of your code, which is probably unintended.

Here is a version of your program that may better reflect your
intentions. It takes 512 analog readings, stores them in an array, then
prints them and reports the time taken to do the readings. Then it waits
for one second and repeats the whole thing again.

```c++
const uint8_t analogPin = A0;
const int readings_count = 512;
int Vs[readings_count];

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

void loop() {
    // Take a run of analog readings.
    unsigned long start_time = micros();
    for (int i = 0; i < readings_count; i++) {
        Vs[i] = analogRead(analogPin);
    }
    unsigned long stop_time = micros();

    // Print the readings.
    Serial.println("Voltage readings:");
    for (int i = 0; i < readings_count; i++) {
        Serial.println(5.0/1024 * Vs[i]);
    }
    Serial.print("Data recorded in ");
    Serial.print(stop_time - start_time);
    Serial.println(" µs");
    Serial.println();

    // Wait before the next run.
    delay(1000);
}
```

If you really want to run only one iteration of the process, then you
can just replace `delay(1000);` by `exit(0);`. Alternatively, move the
body of `loop()` to the end of `setup()`, and keep an empty `loop()`.


body: I have a mega arduino, which is supposed to to power 4 relays using 4 touch sensors TTP 223, the relays are 5V coil and 220V. the arduino is powered by a 5 V adapter "mobile phone charger" and it powers the relay module, the problem when the relays are not connected to the 220 V the arduino and code work well; the Arduino triggers the relays, when the 220V circuit is connected and the relays are supposed to operate solenoids the relays start to work differently and sometimes shuts off, some times just blink,the relay module has 8 only 4 are used, 1, 2, 3 and 8 all are NO wired. the module is powered from the 5V  port of arduino, (https://i.stack.imgur.com/o 30IA.jpg)![.jd-vcc is jumped with vcc ](https://i.stack.imgur.com/doeEp.jpg)![the charger's output is 5V 2A](https://i.stack.imgur.com/iHhVl.jpg) the charger's output is 5V 2A. jd-vcc is jumped with vcc

title: Arduino code does not function when relays are powered

Answers: 0


body: There are two ways of pulling the pins in Arduino – using internal and external resistor. I wonder when I should use external resistor instead of INPUT_PULLUP.

title: External vs internal pullup

Answers: 3

body:
You can use either the internal or external resistor in normal application.

Each method has each own advantages:

**Internal resistor**

 - Pros: flexible to change by changing the code
 - Pros: Reduce PCB size
 - Pros: Reduce cost (very small)
 - Cons: It may make MCU hot

**External resistor**

 - Pros: Reduce heat for MCU
 - Cons: Not easy to replace when it is built-in PCB
 - Cons: Increase PCB size

Besides, Pull-up and pull-down resistors are not only used for INPUT port but also for OUTPUT port. In the case of OUTPUT port. The external resistor has another advantage:  flexibility in connecting devices with different I/O voltages. For example, in I2C hardware [see I2C at the Hardware Level][1].

NOTE: As far as I know, at the writing time, Arduino library does NOT support INPUT_PULLDOWN

  [1]: https://learn.sparkfun.com/tutorials/i2c/all#i2c-at-the-hardware-level

body:
The "Arduino Language" (i.e. the `pinMode()` function) only knows INPUT_PULLUP.

So you need external resistors for PULLDOWN resistors.

OUTPUT signals are not floating, so the term PULLUP/PULLDOWN resistor does not really apply there.

Besides, the value of an internal pullup resistor is not adjustable. If that value (20 .. 50k) is not appropriate (I²C needs something less than 10k) an external resistor is required.

body:
"Cons: It may make MCU hot"
It will not. P=V^2/R, so 5*5/20,000 = 1.25mW, that will not make the processor hot. Even turning all 80 in a Mega2560, and pulling them all low, will only dissipate 0.1W.

"NOTE: As far as I know, at the writing time, Arduino library does NOT support INPUT_PULLDOWN"
That is because Atmega328P, '1284, '2560, etc. family of devices do not have internal pulldown resistors. Only pullup. See Section 14 of their datasheets, "I/O Ports".

This pullup is generally insufficient for I2C pullup, the rising edge created by the 20K to 50K internal pullup is very slow. External 4.7K down to around 2.2K (depends on how many I2C devices are connected) are needed. And the I2C bus spec says they should be at the end of the bus, not the origin of bus (which is generally the processor).

If you have a long wire coming from a button or switch, that is generally a good time to use an external pullup to ensure good switching levels between high and low.


body:
I need to send 259 bytes as answer to I2C master read request. AFAIK there is a buffer limit of 32 bytes in Wire.h <s>and in HW (Arduino Nano)</s>. Is there a way sending 259 byte answer, or I have to choose another HW?

The code is:

    void serveInitCommunication() {
      Serial.println("serveInitCommunication()");
      static unsigned int counter = 0;
      auto answer = findInitAnswer(counter);

      uint8_t buffer[260]; //maximum size from dataLengths[] in comm_init_data.h
      memcpy_P(buffer, answer.dataPtrProgmem, answer.dataSize);

      Serial.print(" dataSize:");
      Serial.print(answer.dataSize);
      Serial.print(" data:");
      Serial.println(int(buffer[answer.dataSize - 1]));

      auto bytesToWrite = answer.dataSize;
      uint16_t bytesWritten{0};

      while (bytesToWrite > BUFFER_LENGTH) {
        Serial.println("Write part");
        Wire.write(buffer + bytesWritten, BUFFER_LENGTH);
        bytesToWrite -= BUFFER_LENGTH;
        bytesWritten += BUFFER_LENGTH;
      }
      Serial.print("Bytes written:");
      Serial.print(bytesWritten);
      Serial.print(" Bytes yet to write:");
      Serial.println(bytesToWrite);
      Wire.write(buffer + bytesWritten, bytesToWrite);

      counter++;
    }

And called is it:

    void requestHandler() {
      char buff[100];
      sprintf(buff, "requestHandler addr:0x%x counter:%d", readAddress, msgReadCounter);
      Serial.println(buff);

      if (readAddress == INIT_MSG_ADDRESS) {
        serveInitCommunication();
      }
    }

I've tried moving the `serveInitCommunication()` into `void loop()` and setting a just a flag in `requestHandler()` but without success. Sending up to 32 bytes works fine. Tnx

update: `uint8_t twi_transmit(const uint8_t*, uint8_t);` so twi library self limit data to 255 bytes

update2: there is a hacker way doing it, by replacing the twi.c twi_txBuffer and twi_txBufferLength with buffer from the sketch

title: Sending more than BUFFER_LENGTH(32) bytes in slave answer I2C

Answers: 1

body:
The limitation is purely in software. The I2C hardware has a limit of one byte at a time, and the software creates a 32 byte buffer and feeds each byte from that in turn.

While it would be perfectly possible to increase that buffer size, you may find you have other problems when you get above 255 bytes, since lots of parameters and internal variables for the library are limited to 8 bit values.

It would also be considered very "hacky" since you can't easily upgrade the Wire library in future.

A better strategy would be to split your data into chunks and make multiple requests, each one saying "Give me chunk number ..." and then recombine them upon reception.


body:
I want to use four of MCP4725 DAC module at the same time but it only has two I2C addresses which can be set via jumpers:

[![][1]][1]

In page 10 of the [datasheet][2] it says:

> Device Address Selection pin. This pin can be tied to VSS or VDD, or
> can be actively driven by the digital logic levels. The logic state of
> this pin determines what the A0 bit of the I2C address bits should be.

Is there anyway to set more than two addresses for this module? or any hack via hardware/software...

  [1]: https://i.stack.imgur.com/8uTx9.png
  [2]: https://www.sparkfun.com/datasheets/BreakoutBoards/MCP4725.pdf

title: MCP4725 I2C address

Answers: 1

body:
There is a trick to this, and it involves considering one device "active" and all others "inactive".

You only ever work with one address, and that is the address of the "active" unit. All other units are on the secondary "inactive" address which you ignore.

The address pin of each unit is then connected to an IO pin, and can be considered a "chip select" pin.

The sequence, then, is:

* Set unit one's A0 low and all other units HIGH.
* Communicate on Address 0
* Set unit two's A0 LOW and all other units HIGH.
* Communicate on Address 0
* Etc for each unit

Since you never communicate on Address 1 the rest of the "inactive" units ignore all the communication.


body:
Im working on an arduino robot that needs to follower a leader robot infront of it. The leader robot can accelerate, decelerate , and stop and my robot needs to be able to follow the leader without crashing into it.

I have my two sensors working however Im having a harder time integrating the motors to ramp up or down. Currently only one wheel turns on at a time for the right and left commands.
How can I appropriatly ramp up or down the wheel speed.

```
int SpRMotor = 5;  //speed Right Motor
int MotorA1 = 7; //Right Motor = +
int MotorA2 = 6; //Right Motor = -
int MotorB1 = 8; //Left Motor = -
int MotorB2 = 9; //Left Motor = +
int SpLMotor = 10;  //speed Left Motor

int TriggerPIN1 = 3;//right
int EchoPIN1 = 2;
int TriggerPIN2 = 12;//left
int EchoPIN2 = 11;

void setup(){
  pinMode(TriggerPIN1,OUTPUT);
  pinMode(EchoPIN1,INPUT);
  pinMode(TriggerPIN2,OUTPUT);
  pinMode(EchoPIN2,INPUT);

  pinMode(MotorB1, OUTPUT);
  pinMode(MotorB2, OUTPUT);
  pinMode(MotorA1, OUTPUT);
  pinMode(MotorA2, OUTPUT);
  pinMode(SpLMotor, OUTPUT);
  pinMode(SpRMotor, OUTPUT);

  analogWrite(SpRMotor, 170);
  analogWrite(SpLMotor, 170);
  Serial.begin(9600);
  }
void loop(){

  int limit;
  int sampledata1, sampledata2;
  sampledata1 = distance(TriggerPIN1, EchoPIN1);
  Serial.print("distance1: ");
  Serial.print(sampledata1);
  delay(100);
  sampledata2 = distance(TriggerPIN2, EchoPIN2);
  Serial.print(" distance2: ");
  Serial.println(sampledata2);
  delay(100);
  limit = 10;
  if((15> sampledata1 >= limit)&&(15> sampledata2 >= limit))
  {
    Serial.print("True");
    forward();
    delay(100);
  }
     if (sampledata2  >= 15 )
    {turnRight();}
  if (sampledata1  >= 15 )
    {turnLeft();}
  if ((limit > sampledata1)&&(limit> sampledata2 ))
  {
    Stop();
  }

}

void forward(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
}

void turnRight(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
}

void turnLeft(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
}

void Stop(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
}
int distance(int trig, int echo)
{ digitalWrite(trig,LOW);
  delayMicroseconds(2);
  digitalWrite(trig,HIGH);
  delayMicroseconds(10);
  digitalWrite(trig,LOW);
  long timedelay = pulseIn(echo,HIGH);
  int distance = 0.0343 * (timedelay/2);

  return distance;
}
```

title: Ramping up and down arduino motor due to ultrasonic sensor input

Answers: 1

body:
The speed seams to be defined by a an analog write to `SpRMotor` and `SpLMotor`. You did that once (with value 170)  in the setup. If you use variables for that (e.g. `speedValueL` and `speedValueR`) you can change their values as you need it and write it to the PWM channels on each forward, backward, left or right statement.

A short example:

    int SpRMotor = 5;  //speed Right Motor
    int MotorA1 = 7; //Right Motor = +
    int MotorA2 = 6; //Right Motor = -
    int MotorB1 = 8; //Left Motor = -
    int MotorB2 = 9; //Left Motor = +
    int SpLMotor = 10;  //speed Left Motor

    int TriggerPIN1 = 3;//right
    int EchoPIN1 = 2;
    int TriggerPIN2 = 12;//left
    int EchoPIN2 = 11;

    int speedValueL = 0;
    int speedValueR = 0;

    void setup()
    {
      pinMode(TriggerPIN1,OUTPUT);
      pinMode(EchoPIN1,INPUT);
      pinMode(TriggerPIN2,OUTPUT);
      pinMode(EchoPIN2,INPUT);

      pinMode(MotorB1, OUTPUT);
      pinMode(MotorB2, OUTPUT);
      pinMode(MotorA1, OUTPUT);
      pinMode(MotorA2, OUTPUT);
      pinMode(SpLMotor, OUTPUT);
      pinMode(SpRMotor, OUTPUT);

      analogWrite(SpRMotor, speedValueR);
      analogWrite(SpLMotor, speedValueL);

      Serial.begin(9600);
    }

    void loop()
    {
      int limit;
      int sampledata1, sampledata2;
      sampledata1 = distance(TriggerPIN1, EchoPIN1);
      Serial.print("distance1: ");
      Serial.print(sampledata1);
      delay(100);
      sampledata2 = distance(TriggerPIN2, EchoPIN2);
      Serial.print(" distance2: ");
      Serial.println(sampledata2);
      delay(100);
      limit = 10;
      if( (15> sampledata1 >= limit) && (15> sampledata2 >= limit) )
      {
        Serial.print("True");
        // Just my guess - do what fits for you
        speedValueL = 170;
        speedValueR = 170;

        forward();
        delay(100);
      }

      if (sampledata2  >= 15 )
      {
        // Just my guess - do what fits for you
        speedValueL = 200;
        speedValueR = 0;

        turnRight();
      }

      if (sampledata1  >= 15 )
      {
        // Just my guess - do what fits for you
        speedValueL = 0;
        speedValueR = 200;

        turnLeft();
      }

      if ( ( limit > sampledata1 ) && ( limit> sampledata2 ) )
      {
        // Just my guess - do what fits for you
        speedValueL = 0;
        speedValueR = 0;

        Stop();
      }
    }

    void forward()
    {
      analogWrite(SpRMotor, speedValueR);
      analogWrite(SpLMotor, speedValueL);

      digitalWrite(MotorA1, LOW);
      digitalWrite(MotorA2, HIGH);
      digitalWrite(MotorB1, HIGH);
      digitalWrite(MotorB2, LOW);
    }

    void turnRight()
    {
      analogWrite(SpRMotor, speedValueR);
      analogWrite(SpLMotor, speedValueL);

      digitalWrite(MotorA1, LOW);
      digitalWrite(MotorA2, LOW);
      digitalWrite(MotorB1, HIGH);
      digitalWrite(MotorB2, LOW);
    }

    void turnLeft()
    {
      analogWrite(SpRMotor, speedValueR);
      analogWrite(SpLMotor, speedValueL);

      digitalWrite(MotorA1, LOW);
      digitalWrite(MotorA2, HIGH);
      digitalWrite(MotorB1, LOW);
      digitalWrite(MotorB2, LOW);
    }

    void Stop()
    {
      analogWrite(SpRMotor, speedValueR);
      analogWrite(SpLMotor, speedValueL);

      digitalWrite(MotorA1, LOW);
      digitalWrite(MotorA2, LOW);
      digitalWrite(MotorB1, LOW);
      digitalWrite(MotorB2, LOW);
    }

    int distance( int trig, int echo )
    {
      digitalWrite( trig, LOW );
      delayMicroseconds( 2 );
      digitalWrite( trig, HIGH );
      delayMicroseconds( 10 );
      digitalWrite( trig, LOW );
      long timedelay = pulseIn( echo, HIGH );
      int distance = 0.0343 * ( timedelay / 2);

      return distance;
    }


body: What are the data sizes of all the primitive datatypes on a Metro M4 Express SAMD51 C++ implementation? In some C++ implementations, `int` has 16 bits and in other implementations it has 32 bits. Is

title: What are the sizes of each primitive datatype on a Metro M4 Express SAMD51?

Answers: 2

body:
And that is the only difference in fundamental type sizes. On 8-bit Arduinos `int` is 16 bit and on 32-bit `int` is 32 bit.

 - `short` is 16 bit
 - `long` is 32 bit
 - `long long` is 64 bit

[https://en.cppreference.com/w/cpp/language/types][1]

  [1]: https://en.cppreference.com/w/cpp/language/types

body:
Here is a sketch to quickly find out **unsigned** maximum values on any architecture and deduce the bit width from them (I had to use sprintf, because Serial.println(unsigned long long) did not work on my Due):

    #include <limits.h>

    #define sprintfln(args...) { char _qsx6_[200]; snprintf(_qsx6_, 200, args); Serial.println(_qsx6_); } // _qsx6_ may collide with local var

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

        unsigned char  uc = 0; uc=~uc; Serial.println(uc);
        unsigned short us = 0; us=~us; Serial.println(us);
        unsigned int   ui = 0; ui=~ui; Serial.println(ui);
        unsigned long  ul = 0UL; ul=~ul; Serial.println(ul);
        unsigned long long ull = 0ULL; ull=~ull; // doesn't work: Serial.println(~ull);

        sprintfln("char:%u short:%u int:%u long:%lu long long:%llu", uc, us, ui, ul, ull);
        sprintfln("char:%u short:%u int:%u long:%lu long long:%llu", UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, ULLONG_MAX);
        sprintfln("char:%u short:%u int:%u long:%u long long:%u", sizeof(uc), sizeof(us), sizeof(ui), sizeof(ul), sizeof(ull));
        sprintfln("pointer:%u", sizeof(&uc));
    }

On Arduino Due this gives (I expect it to be the same on SAMD51):

    char:255
    short:65535
    int:4294967295
    long:4294967295
    long long:18446744073709551615
    char:1 short:2 int:4 long:4 long long:8
    pointer:4

Usually you could include "limits.h", but it seems that unsigned long long is missing (at least on Due). Hmmm, I didn't expect int and long to be the same, good to know.


body:
I'm building a GPS speedometer. I use Neo-6M module for GPS, Arduino uno and 128x64 OLED screen for monitoring the value. I've checked the GPS module. It gives me data about latitude and longitude. But on the OLED screen it didnt come out value. I NEED HELP. this is the code.

        /*
      Connections:
      GPS TX -> Arduino 0 // Disconnect Arduino 0 to upload this sketch
      GPS RX -> Arduino 1
      Screen SDA -> Arduino A4
      Screen SCL -> Arduino A5
    */

    #include "U8glib.h" // Call U8glib library to control OLED screen

    U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0|U8G_I2C_OPT_NO_ACK|U8G_I2C_OPT_FAST); // Fast I2C/TWI
    static const int RXPin = 3, TXPin = 4;
    static const uint32_t GPSBaud = 9600;

    #define GPS Serial // Define the serial connection as the GPS module

    const unsigned char UBLOX_INIT[] PROGMEM = {
      // These lines of code request data from the satellites. Most are disabled and turned off.
      // Disable NMEA
      0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x24, // GxGGA off
      0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x01,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x2B, // GxGLL off
      0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x02,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x32, // GxGSA off
      0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x03,0x00,0x00,0x00,0x00,0x00,0x01,0x03,0x39, // GxGSV off
      0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x04,0x00,0x00,0x00,0x00,0x00,0x01,0x04,0x40, // GxRMC off
      0xB5,0x62,0x06,0x01,0x08,0x00,0xF0,0x05,0x00,0x00,0x00,0x00,0x00,0x01,0x05,0x47, // GxVTG off

      // Disable UBX
      0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x17,0xDC, // NAV-PVT off
      0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x12,0xB9, // NAV-POSLLH off
      0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x13,0xC0, // NAV-STATUS off

      // Enable UBX—this is the key information we require
      0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x07,0x00,0x01,0x00,0x00,0x00,0x00,0x18,0xE1, //NAV-PVT on
      //0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x02,0x00,0x01,0x00,0x00,0x00,0x00,0x13,0xBE, //NAV-POSLLH on
      //0xB5,0x62,0x06,0x01,0x08,0x00,0x01,0x03,0x00,0x01,0x00,0x00,0x00,0x00,0x14,0xC5, //NAV-STATUS on

      // Rate
      0xB5,0x62,0x06,0x08,0x06,0x00,0x64,0x00,0x01,0x00,0x01,0x00,0x7A,0x12,    // (10Hz)
      //0xB5,0x62,0x06,0x08,0x06,0x00,0xC8,0x00,0x01,0x00,0x01,0x00,0xDE,0x6A, // (5Hz)
      //0xB5,0x62,0x06,0x08,0x06,0x00,0xE8,0x03,0x01,0x00,0x01,0x00,0x01,0x39  // (1Hz)
    };

    const unsigned char UBX_HEADER[] = { 0xB5, 0x62 };

    struct NAV_PVT { // This sets the GPS navigation data
      unsigned char cls;
      unsigned char id;
      unsigned short len;
      unsigned long iTOW; // GPS time of week of the navigation epoch (ms)

      unsigned short year;     // Year (UTC)
      unsigned char month;     // Month, range 1..12 (UTC)
      unsigned char day;       // Day of month, range 1..31 (UTC)
      unsigned char hour;      // Hour of day, range 0..23 (UTC)
      unsigned char minute;    // Minute of hour, range 0..59 (UTC)
      unsigned char second;    // Seconds of minute, range 0..60 (UTC)
      char valid;              // Validity Flags (see graphic below)
      unsigned long tAcc;      // Time accuracy estimate (UTC) (ns)
      long nano;               // Fraction of second, range -1e9 .. 1e9 (UTC) (ns)
      unsigned char fixType;   // GNSSfix Type, range 0..5
      char flags;              // Fix Status Flags
      unsigned char reserved1; // Reserved
      unsigned char numSV;     // Number of satellites used in Nav Solution

      long lon;           // Longitude (deg)
      long lat;           // Latitude (deg)
      long height;        // Height above Ellipsoid (mm)
      long hMSL;          // Height above mean sea level (mm)
      unsigned long hAcc; // Horizontal Accuracy Estimate (mm)
      unsigned long vAcc; // Vertical Accuracy Estimate (mm)

      long velN;                // NED north velocity (mm/s)
      long velE;                // NED east velocity (mm/s)
      long velD;                // NED down velocity (mm/s)
      long gSpeed;              // Ground Speed (2-D) (mm/s)
      long heading;             // Heading of motion 2-D (deg)
      unsigned long sAcc;       // Speed accuracy estimate
      unsigned long headingAcc; // Heading accuracy estimate
      unsigned short pDOP;      // Position dilution of precision
      short reserved2;          // Reserved
      unsigned long reserved3;  // Reserved
    };

    NAV_PVT pvt;

    void calcChecksum(unsigned char* CK) {
      memset(CK, 0, 2);
    for (int i = 0; i < (int)sizeof(NAV_PVT); i++) {
      CK[0] += ((unsigned char*)(&pvt))[i];
      CK[1] += CK[0];
      }
    }

    long numGPSMessagesReceived = 0;

    bool processGPS() {
      static int fpos = 0;
      static unsigned char checksum[2];
      const int payloadSize = sizeof(NAV_PVT);

      while ( GPS.available() ) {
        byte c = GPS.read();
        if ( fpos < 2 ) {
          if ( c == UBX_HEADER[fpos] )
            fpos++;
          else
            fpos = 0;
      }
      else {
        if ( (fpos-2) < payloadSize )
          ((unsigned char*)(&pvt))[fpos-2] = c;

        fpos++;

        if ( fpos == (payloadSize+2) ) {
          calcChecksum(checksum);
        }
        else if ( fpos == (payloadSize+3) ) {
          if ( c != checksum[0] )
             fpos = 0;
        }
        else if ( fpos == (payloadSize+4) ) {
          fpos = 0;
          if ( c == checksum[1] ) {
            return true;
          }
        }
        else if ( fpos > (payloadSize+4) ) {
           fpos = 0;
         }
       }
     }
     return false;
    }

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

      u8g.setColorIndex(1);

     // Send configuration data in UBX protocol
     for (unsigned int i = 0; i < sizeof(UBLOX_INIT); i++) {
       GPS.write( pgm_read_byte(UBLOX_INIT+i) );
       delay(5); // Simulate a 38400baud pace (or less),
                 // or otherwise commands are not accepted by the device

      }
    }

    long gSpeed = 0;
    int numSV = 0;
    unsigned long lastScreenUpdate = 0;
    char speedBuf[16];
    char satsBuf[16];

    char* spinner = "/-\\|"; // Symbol for the spinner on screen to
                             // show communication
    byte screenRefreshSpinnerPos = 0;
    byte gpsUpdateSpinnerPos = 0;

    void loop() {
      if (processGPS()) {
        numSV = pvt.numSV;
        gSpeed = pvt.gSpeed;
        gpsUpdateSpinnerPos = (gpsUpdateSpinnerPos + 1) % 4;
      }

      unsigned long now = millis();
      if (now - lastScreenUpdate > 100) {
         updateScreen();
         lastScreenUpdate = now;
         screenRefreshSpinnerPos = (screenRefreshSpinnerPos + 1) % 4;
      }
    }

    void draw() {
      u8g.setFont(u8g_font_courB24);
      u8g.drawStr( 36, 45, speedBuf);
      u8g.setFont(u8g_font_fur11);
      u8g.drawStr( 2, 12, satsBuf);
    }

    void updateScreen() {

      int kmh = gSpeed * 0.0036;
      sprintf(speedBuf, "=", kmh);
      sprintf(satsBuf, "%c %c %d", spinner[screenRefreshSpinnerPos], spinner[gpsUpdateSpinnerPos], numSV);

      u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );
    }![enter image description here](https://i.stack.imgur.com/Asw5t.jpg)![This is what it shown on my OLED but the value didnt change]

title: GPS Speedometer value didnt come out

Answers: 0


body:
So I am trying to use Port Manipulation to turn on LEDS but I need to use PORT Manipulations for specific reasons.

```
//22-29PORTA (0x01-0x80)
//30-37PORTC (0x80-0x01)
//38-45PORTD (0x80-0x01)

void setup(){
PORTA =  B0000000; //29--->22
PORTC =  B0000000; //37--->30
PORTD =  B0000000; //45--->38
}

void loop(){
 PORTA =  B1000100;
 PORTC =  B0101000;
 PORTD =  B0000010;
 delay(1000);

 PORTA =  B1010000;
 PORTC =  B0001010;
 PORTD =  B0100000;
 delay(1000);

 PORTA =  B0010100;
 PORTC =  B0100010;
 PORTD =  B0001000;
 delay(1000);

}```
Heres the code for Arduino Mega 2560

title: Why is this code not working?

Answers: 1

body:
You need to set the ports to output first, before you can use them.

To do that you use the DDRx (Data Direction) registers.  Your code should look like:

    //22-29PORTA (0x01-0x80)
    //30-37PORTC (0x80-0x01)
    //38-45PORTD (0x80-0x01)

    void setup(){
        // Set the pins all to output
        DDRA = 0xFF;
        DDRC = 0xFF;
        DDRD = 0xFF;

        PORTA =  B0000000; //29--->22
        PORTC =  B0000000; //37--->30
        PORTD =  B0000000; //45--->38
    }

    void loop(){
        PORTA =  B1000100;
        PORTC =  B0101000;
        PORTD =  B0000010;
        delay(1000);

        PORTA =  B1010000;
        PORTC =  B0001010;
        PORTD =  B0100000;
        delay(1000);

        PORTA =  B0010100;
        PORTC =  B0100010;
        PORTD =  B0001000;
        delay(1000);
    }

You can read more about direct port manipulation [here](https://www.arduino.cc/en/Reference/PortManipulation).


body:
Would using a thicker cable like 16 AWG affect the signal being received from an RFID or Ultrasonic sensor?

I understand AWG can make a significant impact on voltage when a thick cable is used over a long distance. In my head signal data is delicate so a nice thin wire will ensure little disturbance....

Looked around and couldn't find a clear answer so hopefully someone can help!

title: Does AWG size affect signal from sensors?

Answers: 1

body:
A signal is just a varying voltage.  A wire is just a (very long) small resistor.  The device reading the signal is just a current sink.

That's three terms there: voltage, resistance, and current. Three terms you should know are related by Ohm's Law.

Also, some simple rules:

* The thinner the wire the bigger the resistance
* The longer the wire the bigger the resistance
* The more load on the wire the greater the current

And of course, that all means:

* The greater the resistance or the greater the current, the greater the voltage drop across the wire.

If the voltage drop gets too great then the device receiving the signal won't be able to work out what it is.

But then of course a wire is also an antenna picking up all sorts of noise. The longer the wire the more noise it will pick up. And the thinner the wire the greater the resistance and the greater the resultant voltage drop, meaning the lower the noise margin and immunity.

**So no, a thinner wire isn't better than a thicker wire. The exact opposite is true.**


body:
I am a beginner to electronics and trying to make a portable air conditioner using a Peltier cooling pad (12V). I am planning on using a solar panel to power the Peltier and looking forward to your expert opinion  for below;
- Is this possible?
-What the specifications I have to consider prior to purchasing the solar panel?
- What is the weight of the solar panel?
- Can I operate the Peltier through an Arduino using Solar panel as the power source( without using batteries to power Arduino and Peltier). My idea is to control the Peltier cooler via Arduino using a phone App.
Really sorry if these questions are basic, yet your guidance will be very much helpful for me as well as for the other beginners like me.

title: Powering Peltier using solar panels

Answers: 2

body:
A microcontroller like an Arduino needs a constant source of regulated 5V (or 3.3V for some models.) The voltage of a solar panel varies depending on the amount of light, and in low light conditions there won't be enough power to run the Arduino.

So the short answer is no, you won't be able to run the Arduino reliably from a solar panel without a battery. You probably want a battery and a buck/boost voltage regulator that can convert a wide range of voltages to the 5V the Arduino needs.

What do you want the Arduino for? Temperature regulation? You'd probably be better off using a bimetallic thermostat that would turn the power to the Peltier pad on and off without needing electronics.

As for running a Peltier junction cooling pad from a solar panel, that should work. It would depend on the specs of the Peltier unit and of the panel. Again, you'll probably get the maximum cooling if you use a buck/boost voltage regulator to convert the variable output of your solar panel to a steady 12V. You'll need a big enough solar panel to provide the current that your Peltier pad needs.

All the talk about Peltier pads and solar panels is not Arduino-specific, however.

## Edit:

Research solar chargers for 12V batteries. Buy a solar panel made to charge a 12V battery. Make sure you select a solar panel that puts out enough current to run the Peltier panel at full power when it is in the sun. Ideally, select a solar panel that provides several times more current than needed to run the Peltier pad. That way the solar panel will charge the battery AND run the Peltier pad while the sun is shining, and when the sun is behind the clouds or at night, the Peltier pad will continue to run from the battery.

Start from that. Buy a buck/boost power supply that can convert a wide range of voltages to 5V. Use that to power the Arduino.

Buy a digital thermometer (like a DHT11 for example). Follow the instructions to wire it into your Arduino, and write a sketch that measures the temp in the thing you are trying to cool.

Buy a power MOSFET transistor that is made to work from a 5V logic signal. This one, for example: https://www.sparkfun.com/products/10213

Wire the MOSFET so a logic signal from one of the digital pins on the Arduino is connected to the gate of the MOSFET and it switches the power to the Peltier pad on and off. (You should be able to find a wiring diagram online.)

Write a sketch that measures the temp from the digital thermometer every few seconds, and turns on the power to the MOSFET if the temp rises above a threshold temp, and turns it off if it drops below a colder temp. (Say it turns on the MOSFET when the temp rises above 24°C, and turns the MOSFET off when the temp drops to 20°C. (This is really simple code to write.)

Note that if the battery gets too low, it won't provide enough power to the voltage regulator which supplies the Arduino and it will shut down. That will cause the Peltier pad to turn off. Once the solar panel charges the battery up enough, the voltage regulator will start providing 5V to the Arduino again, it will restart, your sketch will start running, and the cycle will continue. When the battery barely has enough power to drive the Arduino, it may restart the Arduino, try to turn on the Peltier pad, and immediately die again, every few seconds. That would be bad, and would put a lot of stress on all the electronics.

You might want to add a voltage sensor¹  to the battery and have the Arduino measure the battery voltage, and not try to power the Peltier pad unless and until the battery has a reasonable charge. Instead it would monitor the battery charge level and wait until there was enough power stored in the battery to run the Peltier pad. You could also have the Arduino detect that the battery charge level was getting low, and shut off the Peltier pad before it got too low.

A lead/acid battery would be a good choice since it's cheap, holds a lot of power, and it's easy to estimate the remaining power in a healthy lead/acid cell from its output voltage.

If you **do** use a lead-acid battery, it's important to add a battery charge level sensor and make your sketch avoid draining the battery too low. Lead-acid batteries are damaged when you discharge them too much.

## Edit #2:

You said in a comment to another answer that you're looking to provide small-scale cooling while traveling in a hot climate: The fact that you're trying to handle travel poses some interesting challenges, and perhaps some opportunities. If you're traveling in a car or truck you could tap the 12V power that is almost always available in a motor vehicle. If you don't have an external source of power then the shifting and turning you will likely experience while traveling will greatly reduce the efficiency of your solar panel. They only give maximum power when the panel is directly perpendicular to (or "normal to") the sun. As the angle of the panel to the sun shifts from the ideal angle the power output of your panel will drop significantly.

---
¹ A voltage sensor could be as simple as a voltage divider that reduces the input voltage from a max of a little under 14V down to 5 V, fed into an analog input on the Arudino. You might need to disconnect the solar panel input before measuring the battery charge level however, since input from the solar panel will make the battery voltage seem higher than it actually is. Also note that your battery charge level estimates are going to be crude, since you should really let a lead-acid battery rest with no input and no output for several minutes before taking a measurements in order to get an accurate reading.

body: Your first decision is to figure out the heat load on the space. How many BTU/hr you need to remove to keep the temperature you want. Then figure out how large / how many Peltier you need to remove that much heat. Do you need some reserve capacity for unusual circumstances or is a higher inside temperature Ok sometimes? Then you need a power budget - how much power will it take to remove that much heat with Peltier panels. How much PV area will you need to provide that power? If you need cooling when the sun isn't out, your power budget has to include the 24-hour demand, and the intermittent supply, perhaps again with some headroom. Power storage - batteries or the power grid - will be a requirement to match the two. The same storage can power your Arduino. The Arduino's power budget will be minuscule compared to the rest of the installation and you can totally ignore it. Do you have to power your internal network that connects the Arduino to the Internet, too? Figure that in. By this point, you'll have the answers to most of your questions. Just a heads-up: A Peltier beer-cooler is quite doable. A whole house A/C *might* be doable but no practical - you probably won't like the numbers! I'm guessing your project lies somewhere between the two.


body:
   The code I used was from online and I tried using it to send data to firebase through web server. But the ouput I get from serial monitor was just "ATE0" which means there's something wrong. Hence, I can't proceed in solving this issue.

I tried several resources online to match my current problem.

I hope someone can help me

Thank you :)

    #include <SoftwareSerial.h>;
    SoftwareSerial Serial1(10, 11);
    #include "DHT.h"
    #define Terra "terra1"
    #define DHTPIN 2

    #define DHTTYPE DHT22

    DHT dht(DHTPIN, DHTTYPE);

    //const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; eyagagana soy

    int j=0;
    int prev=0;
    int pres=0;
    String status="";
    String buff(64);
    String getStr(128);

    void setup() {

      Serial.begin(9600);
      Serial1.begin(9600);
    //  Serial.println(F("Humiture and Soil Moisture Sensors"));
      delay(2000);
      Serial1.setTimeout(5000);
      dht.begin();

       if (!connectWiFi()) {
        Serial.println("Can not connect to the WiFi.");
        while (true)
          ; // do nothing
      }
      Serial.println("OK, Connected to WiFi.");
      sendCommand("AT+CIPSTA?");
      sendCommand("AT+CIPDNS_CUR?");
      sendCommand("AT+CIPSTAMAC?");

    }

    void loop() {
     j=analogRead(A0);
      j=map(j,0,982,148,0);
      pres=j;
      if(j>100)
      j=100;
      else if(j<0)
      j=0;

      prev=j;
      delay(1000);

      float h = dht.readHumidity();
      // Read temperature as Celsius (the default)
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit (isFahrenheit = true)
      float f = dht.readTemperature(true);

      // Check if any reads failed and exit early (to try again).
    //  if (isnan(h) || isnan(t) || isnan(f)) {
    //    Serial.println(F("Failed to read from DHT sensor!"));
    //    return;
    //  }

      // Compute heat index in Fahrenheit (the default)
      float hif = dht.computeHeatIndex(f, h);
      // Compute heat index in Celsius (isFahreheit = false)
      float hic = dht.computeHeatIndex(t, h, false);

    //  Serial.print(F("Humidity: "));
    //  Serial.print(h);
    //  Serial.print(F("%  Temperature: "));
    //  Serial.print(t);
    //  Serial.print(F("°C "));
    //  Serial.print(("Soil Moisture: "));
    //  Serial.print(j);
    // Serial.println("%");

    // connect to server
      if (sendCommand("AT+CIPSTART=\"TCP\",\"https://terraduino.000webhostapp.com\",80")) {
        Serial.println("connected to Cloud");
        // build HTTP request
        getStr = "GET /upload.php?terra=";
        getStr += Terra;
        getStr += "&j=";
        getStr += j;
        getStr += "&t=";
        getStr += t;
        getStr += "&h=";
        getStr += h;
        getStr += " HTTP/1.1\r\n";
        //WEBSERVER
        getStr += "Host: https://terraduino.000webhostapp.com\r\n\r\n";
        // open send buffer
        buff = "AT+CIPSEND=";
        buff += getStr.length();
        if (sendCommand(buff.c_str()) && Serial1.find(">")) { // AT firmware is ready to accept data
          // send HTTP request
          Serial.println(getStr);
          Serial1.print(getStr);
          // print HTTP response
          if (Serial1.find("+IPD,")) { // response received
            int l = Serial1.parseInt();
            while (l > 0) {
              if (Serial1.available()) {
                Serial.write(Serial1.read());
              }
            }
            Serial.println("--------------");
          } else {
            Serial.println("no response");
          }
        } else {
          Serial.println("send error");
        }
        sendCommand("AT+CIPCLOSE");
      } else {
        Serial.println("Error connecting");
      }
    }
    bool connectWiFi() {
      if (!sendCommand("ATE0")) // echo off
        return false;
      if (!sendCommand("AT+CIPMUX=0")) // set single connection mode
        return false;
      if (!sendCommand("AT+CWMODE=1")) // set STA mode
        return false;

      return sendCommand("AT+CWJAP=\"I Pronounce you Man and Wifi\",\"-PX?*z3A_1x@.exe\"");
    }
    bool sendCommand(const char* cmd) {
      Serial.println(cmd);
      Serial1.println(cmd);
      while (true) {
        buff = Serial1.readStringUntil('\n');
        buff.trim();
        if (buff.length() > 0) {
          Serial.println(buff);
          if (buff == "OK" || buff == "SEND OK" || buff == "ALREADY CONNECTED")
            return true;
          if (buff == "ERROR" || buff == "FAIL" || buff == "SEND FAIL")
            return false;
        }
      }
    }

title: Sending the data for temperature and soil using esp8266-01 through software serial

Answers: 1

body:
I would say you are trapped in the `sendCommand` function. You print the `cmd` (cmd="ATE0") variable to the terminal and then send the command to the ESP over Serial1 = software serial. Serial1 is configured with a baud rate of 9600 (`Serial1.begin(9600)`)  it depends on your ESP but that might be wrong. A common value is 115200 (`Serial1.begin(115200)`). But because that can vary from board to board, it could also be wrong.

If I'm right and you configured a wrong baud rate, the command can not be understood by the ESP and even the newline after the command might be missing for it.

So the ESP send nothing back and the 'buff.length()' equals to 0. Then the `while(true)` runs and runs and runs ... .


body:
------------
Error message :

    "error: invalid declarator before 'MIDI'
             MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
                                                           ^
    Plusieurs bibliothèque trouvées pour "libMidi.h"
    /home/due32/Arduino/libraries/MIDI/midi_Defs.h:170:31: note: in definition of macro 'MIDI_CREATE_INSTANCE'
         midi::MidiInterface<Type> Name((Type&)SerialPort);"

--------
libMidi.h

    #ifndef libMidi_h
    #define libMidi_h

    #include <Arduino.h>
    #include <MIDI.h>

     void midiSetup();
     void pmbMIDI();

    // void MIDI_CREATE_DEFAULT_INSTANCE(); //doesn't work

    #endif

---------
libMidi.cpp

    #include "libMidi.h"
    #include <MIDI.h>

    void midiSetup(){

    //midi::MidiInterface<Type> Name((Type&)SerialPort);

      void MIDI_CREATE_DEFAULT_INSTANCE();
      void MIDI.begin(MIDI_CHANNEL_OMNI);
    }

    void pmbMIDI(){
     if (MIDI.getType() == 144){
      digitalWrite(13, 1);}

     if (MIDI.getType() == 128){
      digitalWrite(13, 0);}
    }

---
Thank you by advance

title: Using the MIDI library in my own library

Answers: 1

body:
    void MIDI_CREATE_DEFAULT_INSTANCE();

This line should not be placed inside a function, because it is a forward function declaration.

However, I think there are more problems in your code.

My wild guess is to improve the following lines:

- Uncomment line that doesn't work

Change

    MIDI_CREATE_DEFAULT_INSTANCE();

to

    MIDI_CREATE_DEFAULT_INSTANCE();

and place it outside a function.

Remove the word `void`  in the following lines

    void midiSetup();
    void pmbMIDI();

And also align the { and }

    void MIDI.begin(MIDI_CHANNEL_OMNI);

So it's a function call.

Other improvements is to remove spaces or tabs  in

        void midiSetup();
        void pmbMIDI();

Also align { and } in

    if (MIDI.getType() == 144){
        digitalWrite(13, 1);}

    if (MIDI.getType() == 128){
        digitalWrite(13, 0);}


body:
I am trying to use a Protocentral_MAX30102 Pulse Ox sensor to get SpO2 and serial write it to an SD logger. However, my serial write is a mess and I need is in a text form not what it is in now. I would live to write a CSV for to my SD card logger.

This is the stock code.

    #include "Protocentral_MAX30102.h"
    #include <Wire.h>

    MAX30100 sensor;  //attach sensor
    uint8_t data_len=8;
    uint8_t DataPacketHeader[15];
    volatile unsigned int IRR,REDD;

    void setup() {
      Wire.begin();
      Serial.begin(57600);
      while(!Serial);
      sensor.begin(pw1600, i50, sr100 );
    }

    void loop() {
        sensor.readSensor();        //read sensor
        IRR=sensor.IR;
        REDD=sensor.RED;
        DataPacketHeader[0] = 0x0A;
        DataPacketHeader[1] = 0xFA;Uni
        DataPacketHeader[2] = (uint8_t) (data_len);
        DataPacketHeader[3] = (uint8_t) (data_len>>8);
        DataPacketHeader[4] = 0x02;

        DataPacketHeader[5] = REDD;
        DataPacketHeader[6] = REDD>>8;
        DataPacketHeader[7] = REDD>>16;
        DataPacketHeader[8] = REDD>>24;

        DataPacketHeader[9] = IRR;
        DataPacketHeader[10] = IRR>>8;
        DataPacketHeader[11] = IRR>>16;
        DataPacketHeader[12] = IRR>>24;

        DataPacketHeader[13] = 0x00;
        DataPacketHeader[14] = 0x0b;

        for(int i=0; i<15; i++) // transmit the data
        {

           Serial.write(DataPacketHeader[i]);
         }

      delay(10);
    }

title: uint8_t to Text

Answers: 0


body: I want to make a keyboard type panel, which will only have 7 buttons and two knobs, and connect it arduino to program it with functions, he heard that he needed the Keyboard library. but it is not available with arduino uno, which is what I work with, he heard about what I should do a keyboard mapping, it would help me explain to lay a foundation and carry out the project that I want "please do not leave me with the doubt". first of all, Thanks.

title: Improvised Keyboard?

Answers: 1

body:
If you plan to trigger function on a PC by keystroke and want to simulate a PC keyboard on the PC with your computer than I recommend to use the keyboard lib which is able to map your button to key codes and send them to a PC over USB. But the communication over USB and the simulation of a HID (Human Interface Device) connection is (as far as I know) not possible with an Arduino. (You need a 32u4 or SAMD micro based board) like the leonardo.

But if you just plan to trigger functions, that run on the Arduino, the kb lib is not necessary. That a standard job for the Arduino and can be done with 7 input pins and 2 analog pins.


body:
I am making a device that measures temperature and vibrations and records the values onto an SD card. It will be a standalone device.

The hardware used:
- Arduino Uno
- PCF8523 RTC clock
- MAX3186 + PT100 RTD temperature sensor
- Adafruit data logger shield
- Typical bare piezo sensor

For the vibrations, a piezo sensor is used. Because it can produce a signal in two directions, I decided to use a voltage divider to offset the signal from GND. Two 5.1K resistors are connected from the piezo negative terminal to 5V and GND. A 1M resistor is placed in parallel with the piezo sensor. The positive terminal is connector to analog input 0.

[![Piezo circuit][1]][1]

The sensor is read 100 times per data point, the maximum and minimum values are stored and the final value is set to be the difference between the two (two times the amplitude).

**USB**

**9V wall adapter**

When the system is powered via a laptop USB port, the resting value has a jitter of a few bits. When a 9V wall adapter powers the arduino, the jitter is +/- 30 bits. Any small vibrations disappear in the noise.

**USB with piezo**

[![USB with piezo][2]][2]

**9V with piezo**

[![9V with piezo][3]][3]

**9V without piezo**

[![9V without piezo][4]][4]

I would like some help to find the best way forward.

_edit 29-10 17:53 Added better plots_

_edit 30-10 17:53 Added plots for 2.5V and 3.3V lines_

  [1]: https://i.stack.imgur.com/wFjDV.png
[2]: https://i.stack.imgur.com/JgVyc.png
[3]: https://i.stack.imgur.com/ZJ9vI.png
[4]: https://i.stack.imgur.com/lWc0U.png

title: Noise on piezo analog read due to Arduino power supply

Answers: 2

body:
The 9V wall adapter is in most cases a switched power regulator with a high frequency. That's like a radio transmitter direct beside the wire. So there is nothing mystical, when the smooth USB Voltage does not show problems but the
"radio transmitter" does.

There are two ways the power supply can impact: over radio wave or as ripples over the regulated Voltage of your Arduino.

I asked myself, which one it is (or even both)? If you use the extra regulated analog voltage reference (AREF) as the +5V on your Voltage divider, it would be more likely that the problem comes through the air. Then it would help if you activate the shield of the wire by connecting it to GND.

If a rippled supply voltage is the problem, you have to smooth it. Perhaps with a low pass filter (a big Elko between Vcc and GND).

Perhaps you have a solenoid iron core. Then you can wrap the wire to the piezo sensor a few times around it (near the A0 Pin). This technique is often used in computer power supplies to prevent the switching frequencies from escaping to the public power lines.

body:
In addition to what [Peter Paul Kiefer](https://arduino.stackexchange.com/users/10285/peter-paul-kiefer) suggests, you will also want to place an RC [low-pass filter](https://en.wikipedia.org/wiki/Low-pass_filter), between the piezo transducer, and the analog input.

You mention that you'll be sampling this value 100 times per second. So the cutoff frequency, for the filter, should be set to 50 Hz (the [Nyquist frequency](https://en.wikipedia.org/wiki/Nyquist_frequency)).


body:
I am using the attached code.
What I am trying to do is:

Test if there is a personalized "board serial number" written in the EEPROM (by previous code run)
If data found was not 7 characters (e.g `SN-XXXX`), then generate a serial number and save it to EEPROM

Problem is: it generates a serial correctly, it even stores and reads it a few times, but when I disconnect the USB cable and reconnect to test again, it returns some bad data from the EEPROM, like: `⸮^R⸮y⸮|` which seems to pass my 7 characters test and it doesn't generate a new one.

What am I doing wrong ?

```C++

#include <EEPROM.h>

// board SERIAL number
char serial_characters[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"};
// will be filled as SN-A2KH
String serial_number;

void setup() {

  Serial.begin(9600);

  // Get the float data from the EEPROM at position 0
  EEPROM.get(0, serial_number);

  // serial from EEPROM valid
  if (serial_number.length() == 7) {
    Serial.println("Found valid serial in EEPROM");
    Serial.println(serial_number);
  }

  // serial from EEPROM not valid (e.g not: SN-XYZ5)
  if (serial_number.length() != 7) {

    Serial.println("Serial from eeprom is NOT 7 chars, generating a random serial");
    Serial.println(serial_number);

    // if analog input pin 0 is not connected, use noise from it in order to generate a random seed, otherwise random is not so random
    randomSeed(analogRead(0));

    // serial might be empty now, set a "SN-" prefix
    serial_number = "SN-";
    for (int i = 1; i <= 4 ; i++) {
      serial_number = serial_number + serial_characters[random(0, 35)];
    }
    Serial.println("Generated serial now: " + serial_number);

    // save to eeprom if format is valid
    if (serial_number.length() == 7) {
      EEPROM.put(0, serial_number);
      Serial.println("Written serial to EEPROM");
    }

  } // <<< serial from eeprom not correct, generated one

}

void loop() {}
```

title: EEPROM.get returns bad data

Answers: 2

body:
You are saving a String object in EEPROM, which is useless. A string
object does not store the contents of your string. Instead, [it just
stores][string]:

* the memory address where the actual contents (the characters) is
  stored
* the amount of memory allocated for this contents
* the number of characters that actually make the string

This is what you are storing to, and retrieving from EEPROM. So you get
the correct number of characters (third item in the list above), but the
memory address now points to uninitialized RAM.

I suggest instead storing in the EEPROM a raw C string, i.e. an array of
8 chars (7 printable chars plus the terminating NUL). You could achieve
this by just changing the declaration of `serial_number`:

```c++
char serial_number[8];
```

For checking the validity, I would just check that it starts with "SN-"
and the last char is a NUL:

```c++
if (memcmp(serial_number, "SN-", 3) == 0 && serial_number[7] == '\0') {
    ...
}
```

You could do a more stringent validation though, and check that the
other 4 chars are within the valid set.

[string]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.1/cores/arduino/WString.h#L196-L198

**Edit**: to build `serial_number` with random chars:

```c++
strcpy(serial_number, "SN-");
for (int i = 3; i < 7; i++)
  serial_number[i] = serial_characters[random(0, 36)];
serial_number[7] = '\0'; // terminating NUL
```

body:
Just to have the full working code, I ended up with this:

```C++
#include <EEPROM.h>

char serial_characters[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"};
// 7 chars for serial and one for string end '\0'
char serial_number[8];

void setup() {

  Serial.begin(115200);

  EEPROM.get(0, serial_number);

  // check found format
  if (serial_number[0] == 'S' && serial_number[1] == 'N'  && serial_number[2] == '-' && serial_number[7] == '\0') {

    Serial.println("serial from eeprom is valid");
    Serial.println((char*)serial_number);

  } else {

    Serial.println("no valid serial found in eeprom, generating new serial");

    // if analog input pin 0 is unconnected, use noise from it in order to generate a random seed, otherwise random is not so random
    randomSeed(analogRead(0));

    // generate a new serial
    serial_number[0] = 'S';
    serial_number[1] = 'N';
    serial_number[2] = '-';

    // overwrite ending chars of serial with random values
    serial_number[3] = serial_characters[random(0, 35)];
    serial_number[4] = serial_characters[random(0, 35)];
    serial_number[5] = serial_characters[random(0, 35)];
    serial_number[6] = serial_characters[random(0, 35)];

    // end string with null as raw C strings ?!
    serial_number[7] = '\0';

    Serial.println((char*)serial_number);

    // write new serial to eeprom
    EEPROM.put(0, serial_number);

  }

}

void loop() {

}
```


body:
I am making a 20 x 15 LED matrix, and am having some super annoying problems. I was hoping you all could help me find some answers.

It is very important to note that I am following [BitLuni's video][1] on this, following it using almost the same parts, and most definitely the same code (I put it below)

To start, this are the main things I am making it with:

6 sets of [RGB LED Pixel Lights][2]

1 [Knock-off Arduino NANO][3]

1 [5v 20A Power Supply][5]

My first problem arose when I received the Arduino Nano. I was able to see it, but not able to write to it. I was eventually able to make it work by using the old boot loader. Let me make it clear, I fixed that problem. But then I short circuited it and bought another one. And now I am faced with the same problem. I have tried using the [company's own drivers][7] on the darn thing, same issue.
I was going to put the error here, but when I tried to flash, my computer (Windows) got the blue screen of death. I tried opening the app just now, instant death. So I suppose I'll just reinstall it, just saying, something is MESSED UP with it.

Pretty much, I get the error "the selected serial port does not exist or your board is not connected. "I know for a fact that the COM Port is correct, but it just doesn't seem to like what I am doing.

But I still have another problem. While I had the arduino that I got to work, when I transitioned from using the 5v power supply on it to using the power supply I bought, the lights go nuts. They change to seemingly random colors super fast. But as soon as I change it back to the arduino's power, it was fine. I have tested, and the power output is PRECISELY THE SAME. The arduino just sends out the data for the lights to interpret. I have absolutely no idea why this is happening.

So if you have anything to suggest for either of the problems, I would appreciate it.

Also, here is my code for the lights (sorry this post is really chopped up) It is based on Adafruit_NeoMatrix example

    #include <Adafruit_GFX.h>
    #include <Adafruit_NeoMatrix.h>
    #include <Adafruit_NeoPixel.h>
    #ifndef PSTR
     #define PSTR // Make Arduino Due happy
    #endif

    #define PIN 6

    // MATRIX DECLARATION:
    // Parameter 1 = width of NeoPixel matrix
    // Parameter 2 = height of matrix
    // Parameter 3 = pin number (most are valid)
    // Parameter 4 = matrix layout flags, add together as needed:
    //   NEO_MATRIX_TOP, NEO_MATRIX_BOTTOM, NEO_MATRIX_LEFT, NEO_MATRIX_RIGHT:
    //     Position of the FIRST LED in the matrix; pick two, e.g.
    //     NEO_MATRIX_TOP + NEO_MATRIX_LEFT for the top-left corner.
    //   NEO_MATRIX_ROWS, NEO_MATRIX_COLUMNS: LEDs are arranged in horizontal
    //     rows or in vertical columns, respectively; pick one or the other.
    //   NEO_MATRIX_PROGRESSIVE, NEO_MATRIX_ZIGZAG: all rows/columns proceed
    //     in the same order, or alternate lines reverse direction; pick one.
    //   See example below for these values in action.
    // Parameter 5 = pixel type flags, add together as needed:
    //   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
    //   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
    //   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
    //   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)

    // Example for NeoPixel Shield.  In this application we'd like to use it
    // as a 5x8 tall matrix, with the USB port positioned at the top of the
    // Arduino.  When held that way, the first pixel is at the top right, and
    // lines are arranged in columns, progressive order.  The shield uses
    // 800 KHz (v2) pixels that expect GRB color data.
    Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(20, 15, PIN,
      NEO_MATRIX_TOP     + NEO_MATRIX_LEFT +
      NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
      NEO_GRB            + NEO_KHZ800);

    void setup() {
      matrix.begin();
      matrix.setTextWrap(false);
      matrix.setBrightness(255);
    }

    int x    = matrix.width();
    int pass = 0;

    void loop() {
      static int i = 0;
      i++;
      //matrix.fillScreen(0);
      for(int y = 0; y < 15; y++)
        for(int x = 0; x < 20; x++)
          if(y & 1)
            matrix.setPixelColor(19 - x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * 8 + i * 128 * 2)));
          else
            matrix.setPixelColor(x + y * 20, matrix.gamma32(matrix.ColorHSV((x + y) * 256 * 8+ i * 128 * 2)));

      matrix.setTextColor(matrix.Color(0, 0, 0));
      matrix.setCursor(-((millis() / 30) & 127) + 20, 4);
      matrix.print(F(""));
      matrix.show();
    }

Thanks all!

-Micah

  [1]: https://www.youtube.com/watch?v=fz2QAV9z_o8
  [2]: https://www.amazon.com/WESIRI-Diffused-Individually-Addressable-Waterproof/dp/B076VBSB3B/ref=sr_1_1?keywords=5v 12mm led ws2811 pixel module 50 node&qid=1571354584&sr=8-1
  [3]: https://www.amazon.com/KEYESTUDIO-Arduino-Perfectly-Compatible-Sensor/dp/B01FSDVZ98/ref=sr_1_3?crid=1BYRO2Z0H9OV2&keywords=arduino nano&qid=1571353936&sprefix=aruino ,aps,175&sr=8-3
  [4]: https://www.amazon.com/Vessos-150pcs-Washable-Drinking-Practice/dp/B07K9N2ZFC/ref=sr_1_8?dchild=1&keywords=150 ping pong balls&qid=1571355000&sr=8-8
  [5]: https://www.ebay.com/itm/AC-110V-to-DC-5V-12V-24V-36V-48V-Transformer-Switch-Power-Supply-For-LED-Strip/172430906024?_trkparms=aid=1110001&algo=SPLICE.SIM&ao=1&asc=20131231084308&meid=c81b057721f042b4b03ca582d744c6fa&pid=100010&rk=3&rkt=12&mehot=pp&sd=392379761659&itm=172430906024&pmt=1&noa=1&pg=2047675&_trksid=p2047675.c100010.m2109
  [6]: https://www.ebay.com/itm/1x-24MM-Arcade-Push-Button-for-MAME-JAMMA-Replace-Sanwa-OBSF-24-OBSN-24-OBSC-24/192856336058?hash=item2ce72226ba:m:mSKy_ikGsHfTtrFIPrY3fLA
  [7]: https://wiki.keyestudio.com/Ks0173_keyestudio_Nano_ch340#Step2.7C_Installing_the_Driver

title: Arduino-Controlled LED Matrix issues

Answers: 0


body:
In the following code I'm computing crc and setting it as last (11th) byte in the array. The problem is it's sent on I2C just when I print it on the serial terminal.

      static constexpr uint8_t CLICK_MESSAGE_SIZE{11};
      ...
      uint8_t buf[CLICK_MESSAGE_SIZE];
      memcpy(buf, msgMouseClick[clickMessageCounter], CLICK_MESSAGE_SIZE);
      buf[10] = dallas_crc8(buf, 10);
      Serial.println(buf[10], HEX); //!!!has to be here, otherwise is CRC in packet wrong!!!
      Wire.write(buf, CLICK_MESSAGE_SIZE);

When I'm assig the result of to

    auto crc = dallas_crc8(buf, 10);
    buf[10] = crc;
    Serial.println(crc);

and Serial.print ing it. Then It's works. But with  `const auto crc = dallas_crc8(buf, 10);` <b>It does not!</b>

I have slightly modified Wire library, where I'm passing pointer to the buffer and it's size. With precalculated CRCs on 11th position it's working fine even for hundreds of bytes arrays.

It feels like a black magic, or compiler error. I'm using latest arduino-1.8.10

Any tips or hints?

title: Byte not written to the memory

Answers: 0


body:
I am trying to create a library, where I have an array of pointers to functions in it. This array is used by other functions in the library. This is the code of the header file:

    class Lib {
      public:
        static void call();
        static void (*caller[])();
      private:
    };
This is the code of the .cpp-file:

    #include "Lib.h"

    void (*caller[2])();

    void Lib::call() {
      caller[0]();
    }
The sketch executing this is

    #include <Lib.h>

    void setup() {
      Lib::call();
    }

    void loop() {}
When I try to compile this, I get the following error:

> undefined reference to `Lib::caller'

collect2: error: ld returned 1 exit status

Mehrere Bibliotheken wurden für "Lib.h" gefunden

Another weird thing is that the error about the multiple found libraries goes away if I take away the line

    Lib::call();

However, if I put the same code directly into the sketch like so:

    void (*caller[2])();

    void call() {
      caller[0]();
    }

    void setup() {
      call();
    }

    void loop() {}

I get no error. What's the problem here?

title: Calling functions from an array of pointers in a library causes 'undefined reference to' error

Answers: 1

body:
    void (*caller[2])();

should be:

    void (*Lib::caller[2])();

Since you are defining storage space for a static member variable you have to tell the compiler what class it's a static member of.


body:
I'm trying to send custom data. But it doesn't seem to work. I can't find a way to parse my string to a unit8_t. I tried to follow other people's solutions but they don't seem to work for me.

```
// Declaration
uint8_t myData[] = "";

void loop(){
    myData = *(uint8_t*)atoi("custom string".c_str());
}
```

This is the error message that I keep getting:
Incompatible types in assignment of __uint8_t {aka unsigned char}' to 'uint8_t [1] {aka unsigned char [1]}__ .

title: Incompatible types in assignment of 'uint8_t {aka unsigned char}' to 'uint8_t [1] {aka unsigned char [1]}'

Answers: 3

body:
`atoi` is for converting a textual representation of a number ("123" for example) into an actual integer.

The c_str() function gives you a pointer to the internal buffer of the String (assuming you actually have a String) which is no different to a `uint8_t[]` or `uint8_t *` (other than the signedness).

Without knowing exactly what the destination function for this buffer requires it's very hard to help you, but you may want something like:

    LoRaWan.send((uint8_t *)myString.c_str(), myString.length());

If you need to copy the data into a fixed length buffer then you need to first create a buffer of that actual size - then copy the string data into it:

    // Create a buffer of 32 bytes
    uint8_t myBuffer[32];
    // Copy at most 32 bytes, but no more than there actually is, into the buffer
    memcpy(myBuffer, myString.c_str(), min(myString.length(), 32));

body:
Your code is a mess. It's clear you are badly confused between arrays, pointers, and C++ strings.

When you say

    uint8_t myData[] = "";

you make myData of type "array of uint8_t" and make it contain an empty string. You should not then change that value.

When you say

    uint8_t *myData;

it means that `myData` is a variable of type "pointer to uint8_t", but it doesn't point to anything yet.

With that declaration, you can later say:

    myData = "custom string";

That points the `myData` pointer to the address of your constant string. I think that's what you want:

    // Declaration
    uint8_t *myData;

    void loop(){
        myData = "custom string";
    }

body:
Firstly, arrays in C and C++ are not assignable. So, your attempts to assign something to `myData` array with `=` operator are bound to fail in any case. Copying data into naked arrays should be done either manually or using library functions.

Secondly, your `myData` array is declared with size `1`. It is just one byte. It is too small to store anything useful. It will not magically "stretch" by itself to accommodate more data. If you need to store more data in that array, it is your responsibility to declare with the appropriate size in advance.

Thirdly, what is `"custom string".c_str()` supposed to mean??? Something looking very similar to that can be expressed in modern C++ as

    #include <string>
    ...
    using namespace std::string_literals;
    "custom string"s.c_str();

but I see no reason for that at all. If your input is a C-string, then function `atoi` is directly applicable to C-strings. No need to convert such C-string to `std::string` and then back.

Fourthly, `atoi` is a "dead" function that exists for compatibility with legacy code only. You are not supposed to use `atoi` in your code. A C-style string-to-number conversion functions are functions from `strto...` group. E.g. `strtol` in your case. But in C++ you might have better options, like `std::stoi` and such.


body: I'm doing a project on water purity finder. I dont know which arduino board can be used for the project. It uses upto 15 sensor modules excluded display, WiFi module. Can you tell me which board is better for my project.

title: How many sensors can be used in arduino for my project?

Answers: 1

body:
It depends on what kind of sensors you're using. If you use I2C based sensors, and you can configure each with a separate I2C address, you could theoretically drive up to 128 of them. I say theoretically since you might not be able to push the signal across an I2C bus with that many devices on it. You could certainly manage 15 of them however.

The Mega 2560 has tons of I/O lines, so that might be a good choice if you need separate single lines for each sensor.

If you need a separate analog input for each of your sensors, you'd need to use an Arduino with at least 15 separate analog inputs. The Arduino Mega 2560 has 16, so that would work.

If you need 4 bit binary inputs, you'd need 4*15 or 60 inputs. The Mega 2560 has 54 digital inputs, which would not be enough for that situation.

You might also be able to use some sort of signal multiplexer and enable one sensor at a time.

Tell us which type of sensor you're using and we can provide more concrete help.