text:
Serial.println Issue with Flame Sensor
I'm really new to coding and Arduino so I would be eternally grateful for the help.
I'm trying to make a really basic flame sensor that beeps, lights up an LED and displays the distance from the sensor to the flame when activated. I keep getting a "'Serial' does not name a type" error message for the line that reads - Serial.println(analogRead(A0));
I’ve tried to figure it out from the information on this forum of similar questions to try to correct the issue but it seems like every time I fix one thing another 2 errors come up. I’ve been stuck on this one for a little while so I’m hoping I might be able to receive some kind of assistance from the Arduino community.
Below is the entire code - any help is appreciated, thanks :)
int Led = 4;
int Buzz = 7;
int Sensor = 11;
int Fire = HIGH;
void setup()
{ Serial.begin(9600);
pinMode(Buzz,OUTPUT);
pinMode(Sensor,INPUT);
pinMode(Led,OUTPUT);
}
void loop()
{
Fire = digitalRead(Sensor);
if(Fire == HIGH);
Serial.print("analog Read = ");
Serial.print(analogRead);
}
Serial.println("HELP! A FIRE!");
digitalWrite(Buzz,HIGH);
digitalWrite(Led,HIGH);
delay(200);
digitalWrite(Led,LOW);
delay(200);
Serial.println(analogRead(A0));
}
else
{
Serial.println("No fire detected");
digitalWrite(Buzz,LOW);
digitalWrite(Led,LOW);
}
delay(500);
}

You should learn to properly indent your code. You'd soon see the problem then.

You should also learn the difference between ( and {. And a tutorial like https://www.youtube.com/watch?v=QO_Jlz1qpDw or equal is recommended.

First things first; please INDENT YOUR CODE. The code you posted is a mess and I took at least double the time to fix that.
First, you have an extra closing curly bracket at line 17 and the if (Fire == High); should be changed to if (Fire == High){
Fixed code:
int Led = 4;
int Buzz = 7;
int Sensor = 11;
int Fire = HIGH;
void setup()
{
  Serial.begin(9600);
  pinMode(Buzz,OUTPUT);
  pinMode(Sensor,INPUT);
  pinMode(Led,OUTPUT);
}
void loop()
{
  Fire = digitalRead(Sensor);
  if(Fire == HIGH){
//Serial.print("analog Read = ");
//Serial.print(analogRead);
    Serial.println("HELP! A FIRE!");
    digitalWrite(Buzz,HIGH);
    digitalWrite(Led,HIGH);
    delay(200);
    digitalWrite(Led,LOW);
    delay(200);
    Serial.println(analogRead(A0));
 }
 else
 {
    Serial.println("No fire detected");
    digitalWrite(Buzz,LOW);
    digitalWrite(Led,LOW);
  }
  delay(500);
}

it looks like the answer helped https://stackoverflow.com/questions/58576149/trying-to-make-a-flame-sensor-code-is-giving-me-the-opposite-to-the-desired-ef

@Jurag can you flag that as a dupe?

no, it is a different question and a different site. it is a follow-up question

Well he took my answer, added a else if, and say that it is his own code. I don't have enough rep over there to comment, can you help me call it out?

you have the thank you in the question :-). the user60250 account is unregistered, so temporary.


text:
Converting human readable date to a unix timestamp
Can anyone provide a sample code that would convert a human readable date like 2019-10-27 22:10:35 to a unix timestamp like 1572214235?
I found many topics about it, but they eider refer to out of date libraries, or they seem to address more complex time functions, I find it hard to extract this functionality from them.

If you have a fixed format you can use strtok() to slice the string into individual segments, then convert those segments to integers. They can then be used with TimeLib.h with the setTime() function.  You can then query TimeLib for the unix timestamp with now().
Edit: using PaulStoffregen's TimeLib, this code sets current time and returns current unix timestamp.
#include <TimeLib.h>

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

  // hour, min, sec, day, month, year
  setTime(22, 30, 11, 29, 3, 2019);

  // 1553898611
  Serial.println(now());
}
void loop() {}

Edit 2: And to convert any given date to a unix timestamp (without setting current time):
#include "TimeLib.h"

tmElements_t my_time;  // time elements structure
time_t unix_timestamp; // a timestamp

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

  // convert a date and time into unix time, offset 1970
  my_time.Second = 0;
  my_time.Hour = 23;
  my_time.Minute = 0;
  my_time.Day = 25;
  my_time.Month = 3 - 1;      // months start from 0, so deduct 1
  my_time.Year = 2017 - 1970; // years since 1970, so deduct 1970

  unix_timestamp =  makeTime(my_time);
  Serial.println(unix_timestamp);
}

void loop() {}

I already have them into separate values like year, month, etc, I just have no clue on how the code should look when using the time library. I am new to Arduino.

Pass the values to setTime() - I forget the order, but I think it's setTime(hours, minutes, seconds, year, month, day) - though check the documentation or source to be sure.  Then you get the time since the unix epoch with now().

Thanks, I was able to do that and added a full sample code in your answer, I still need a way to convert any given date (not just current time).

I hope you don't mind, I altered a code once more so I am able to select your answer as the correct one :D

After parsing the time into numbers, you can use the standard C time library time.h. More specifically, use the mktime function to convert a struct tm into a time_t, and use difftime to get the seconds since the start of the Unix expoch:
#include <time.h>

void loop() {
    struct tm ltm = {0};
    ltm.tm_year = 2019 - 1900;
    ltm.tm_mon  = 11 - 1;
    ltm.tm_mday = 5;

    int32_t epoch_seconds = difftime(mktime(&ltm), (time_t)0);
    Serial.print("Remember, remember, ");
    Serial.print(epoch_seconds);
}

Note that in struct tm, the year starts at 1900 and the month starts at 0.
EDIT: In avr-libc, difftime returns an int32_t, not a double.

So I replace 2019 with my year and I leave/append the  -1900 part, same for month, then where do I specify the hour, minute and second ?

@adrianTNT Yes, you can use tm_hour, tm_min and tm_sec to specify hours, minutes and seconds, respectively. The available fields of struct tm are linked in the reference. Cf. https://en.cppreference.com/w/c/chrono/tm

I tried the code, seems close but I get a timestamp like 626227200.00 which (without .00) is around 1989, I am lost.

Serial.print might have some trouble printing double-precision floats. Does it work when you change it to Serial.print((float)epoch_seconds, 0);? This should also cut off the '.00' decimal places at the end.

Do I have to set current time first ? If I just set year to 0 and no month or day, it prints a timestamp since 2006-02-07 (1139293696). In another answer I was able to set current time and print current timestamp, but converting any date with mktime would be nice.

The order of setting variables should not matter. It's odd that it prints unrelated times. I did experience something similar before I added the = {0} part. It's either an initialization error (you could check by printing a non-set member of ltm, e.g. Serial.print(ltm.yday) and see if this is always 0); or it might be a problem with Serial.print itself (did you convert it to float? Or try using char buf[20]; sprintf(buf, "%.10g", epoch_seconds); Serial.print(buf) instead).

That timestamp seems to be a default or an offset, I found web results when searching for arduino 1139293696. I think different time components inside the library might use different defaults/offsets. I will do some more tests.

Note that: 1. mktime() interprets the time as being in the local time zone, which on AVR is UTC until you change it with set_zone()/set_dst(). 2. avr-libc uses the epoch 2000-01-01. If you want a Unix timestamp, you should use mktime(&ltm) + UNIX_OFFSET.

"2038". When using int32, it means only 31 valid bits for real numbers, the final bit (MSb) is the negative sign. So we can only get a number of 2'147'483'647, and that arrives at the year 2038. If someone needs to increase this, perhaps the simplest thing would be to use a base year to subtract, and avoid overflow. Maybe that's why the year 2000 is used as a base, and maybe it's interesting to use 2020. Try this yourself: https://timestampgenerator.com/date-from-timestamp/2147483647/+00:00

source: Stack Exchange

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

sort: votes


text:
FastLED library: How can I adjust the brightness of a single pixel on an absolute scale?
I'm using the FastLED library to control a digital RGB LED strip.
While this library seems very comprehensive in capability and ease of use, I do not yet see a way to simply set the brightness value of a individual pixel on an absolute scale. In other words, I want to simply set the brightness of a pixel, without passing a hue or saturation, and without it effecting other pixels.
FastLED.setBrightness() scales down the brightness of all pixels.
leds[i].fadeLightBy() scales down an individual pixel, but if it's called again for the same pixel before updating the LEDs, then the pixel will be faded again from it's already-faded value.
Is there truly no built-in method for setting the brightness of individual pixels to a particular value?

There is no dedicated function to adjust brightness.
You can (however) do this by using the HSV color model.

Breaking HSV (Anachronism) into Parts:
H (Hue) Controls the Color itself.
S (Saturation) of the Color.
V is called Lightness or Value.
'V' is what you want to control.
Just set the LEDs color to a HSV value and change it's V value.
leds[i] = HSV(color, saturation, brightness);

While 'Color' and Saturation' remain the same (to keep the same color), you can change the 'Brightness' directly on the third parameter.
Note that 'leds[i]' is still defined as 'CRGB', not as 'HSV'.
This assignment uses an implicit conversion, that is defined in the library.
You can see the 'HSV' usage example within the 'Cylon' example on the FastLED library.
There you will find the Hue value that gets changed; but it is the same principle as 'brightness'.

Now there is a problem to solve.
The FastLED library can convert 'HSV' Colors to 'RGB' Colors; but not the other way round.
So you cannot simply get the 'hue' and Saturation from an 'RGB' Color with this library.
You have 2 Alternatives:
1. You can just define an extra LEDs array with HSV colors and synchronize both arrays to contain the same data (everytime you want to change a color, you would set a 'HSV' color in the second array, convert that array to 'RGB' by using 'CRGB(hsv_leds[i])' and save that in the first array, which get's used by the FastLED library).
This is relatively easy, but you effectively need double the memory for storing the color values.
This is not an issue, if you have enough memory or few enough LEDs to control.
2. You can write your own function to convert 'RGB' values to 'HSV'; then use it to access the 'hue' and 'Saturation' values for the targeted 'RGB' Color, create a new 'HSV' Color with it and the new 'Brightness' and use it to set the 'RGB' values for the FastLED library.
In this forum thread there is a brief discussion about that, though it leaves you with the implementation yourself.
I think there are suitable implementations, that can be found on the web.
A quick search gave me this code from github gist.
I have not tested it, so I cannot say, if it really works correctly, but you should give it a try.
I'm sure there are also other implementations.

I realize that HSV let's you pass brightness, however I have applications that call for changing just brightness alone, given a certain trigger. It seems to me now that the solution is to do something like the following pseudo code: leds[i] = HSV(leds[i].color, leds[i].saturation, 127); so that I can manipulate the brightness to 127 without knowing offhand the current color, saturation, or brightness of that pixel at that time. I'll have to look around for the actual syntax of it. I certainly hope it can be done that way.

@Bort I added a short explanation for that topic.

I think your answer is misleading when you say "you can just do exactly this" because I think your answer then goes on to explain that I cannot do that and I have to do something else. For your solution #1, why would I need to convert to RGB when the library already takes HSV as input? I'll try #2 in a bit.

It's more of a "you can do exactly this, but it is a bit more complicated, than you wanted", since you can control the brightness of a single pixel with this, but it is more complicated than simply using one dedicated inbuild function. About #1: All examples, that I have seen, use CRGB as the array type, that is passed to the FastLED constructor. I tried using the construcktor with the HSV type, but that resulted in a corresponding compilation error. Thus I deducted, that the library works only with RGB, but also gives you HSV, which can then be converted to RGB

That deduction may be wrong. If you are able to directly use HSV for the array, please tell us and I will change my answer.

I just meant that if I already have what I want in HSV, I can just use leds[i] = HSV(color, saturation, brightness); so why convert to RGB? ....I must be misunderstanding you.

The array element leds[i] is then still defined as CRGB, thus you cannot get the color and saturation back from it via leds[i].saturation etc. The line above uses an implicit conversion from CHSV to CRGB, that is defined in the library. That exactly is the problem, why I added the two possibilities. I will add a bit more to the answer to make this clear.

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


text:
Can I get some help with a metronome code on my arduino uno?
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

  }

}

oh no where do i post the code?

Post your code in your question. Copy and paste it, then select the code and press the {} button to format it.

im clearly not formatting the code correctly in this forum. I copy it, then click the dual squiggly brackets and then paste?

No. You copy.  Then you paste. Then you select (highlight your pasted code). Then you press {}.  It should indent all your code 4 spaces.

And why don't you just set the interval varaible with your math formula? Something like interval = <math formula>

as in interval = a?
i tried that and so many other combinations but it just doesnt work

it says 'a' was not defined in this scope. I tried looking up what that meant, and I thought I resolved the issue by putting the arithmetic statement in the beginning of the sketch to make it a global value, but I still get an error message.

so through the help from others on this site I managed to do what I wanted however the interval is one iteration behind the actual value. so if im stepping the encoder up to 120, the value at 119 is 504, and the value at 120 is 500 and so on. the problem is the value shown by the interval is one step behind, so at 120 the value still reads 504, and 121 the value reads 500 and so on.

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.

ok I think im understanding, ill edit the post to update the code,  but if im understanding you correctly, ive already tried this and it still doesnt give the result i want. how do Ihave variable 'a' change with the encoder reading?
also, I tried adding the
interval = 60.00 / encoder0Pos * 1000;
above the serial.println's but  I got an error message

ok I also added the formula above the serial.println section.
that has provided me with the correct value being returned from the interval in my serial viewer! thats great! but its not affecting the rate of blink of the led still. I updated the code in the OP.

ok I got it. thank you very much for your help!
the math doesnt stay true into the higher values, past around 200 bpm but it will certainly work for my purposes!


text:
Arduino Due: Measuring the time between pulses
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

As far as I know, there is no problem in using the Arduino IDE with the due, even for "advanced" code. The attacheInterrupt method should work like it does for the Mega or UNO. Starting a counter/timer should also be possible. Perhaps you can use the following  link as a start point. (The conversation starts with a discussion about possible counter speeds but after that, they show code for  capturing two signals and measure the time between them. If I understood by a quick look at it). I would suggest to use the Arduino IDE if possible.

what link sorry?

Wow, that's strange. Sorry, the link was removed. How can that happen? I answered the question on another computer and perhaps the link is still in the history of the browser. But, please be patient until I have access to this computer. In about ten hours. Here is another interesting link: https://forum.arduino.cc/index.php?topic=45926.0 They work with the rising and falling edges of a signal pin. Your problem is not far away from theirs. You only need the rising edge, Then read the actual time in the interrupt handler and compute the difference or mean value into a global variable.

The Firefox history does not forget ;-). Here is the link https://forum.arduino.cc/index.php?topic=400516.0 . But I had a second look into it and now I think the link from my last comment fits much better with what you want achieve.

Peter, thanks you for your response, I actually managed to find a library which seems to do the trick!

Andrew, you're welcome. Would you be so kind and add an answer with your solution and mark it as the correct answer. An unanswered question must be reviewed by the members and create some effort and perhaps there are other people having the same problem. It would be nice if they have also a link to that library. Thank you.


text:
Nodemcu & GSM module & CLIP problem (CLIP line not always appears on the serial connection)
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.

Can you show us the sketch you're using?

I put the most important part of code to the first post.


text:
NodeMCU ESP8266 Returns IP address, but cant open the web with IP address
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("");

}

you must read the request. flush() doesn't do it. browsers don't like a response before they finished to send a request. see the WiFiWebServer example in the IDE examples menu

the example is now renamed to WiFiManualWebServer

Are you sure you are on the same wifi network as the esp unit ? eg. don't do it from your cellular connected phone.

Hi, did you find the solution to this problem?


text:
I am making a rubber band gun but i cant seem to get the button to work with my code to turn the servo?
#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);
}

And what exactly does not work? What do you see happending or not happending? What have you expected?

So it is supposed to move a servo when I push a button but the Servo just moves back and forth randomly.

Floating input. Show your wiring.

You may also print buttonState and check it's value in the serial monitor.

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

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
Chattering phenomenon => Debounce See button debounce

Since the servo pulse frequency is about 50 Hz it has a clock period of about 20 ms. This is more than enough to debounce buttons, so there is no need for it.


text:
Addressable RGB strip works fine individually but cannot set all LEDs to full white
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.

Using the FastLED library, 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.

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

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:

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?

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.

You were right! I connected both ends and the middle was only slightly off-color. I thought that such a simple product couldn't possibly have this issue, and yet here it is. I've never seen such a dramatic drop on such a short strip before.

@Bort It certainly looks worse than on my 5V, 5 metre strip with the same number of LEDs. Maybe they skimped on the track size (which is silly because PCB makers don't charge based on the amount of copper)

BTW, this strip was sold as IP67 and sealed in a single continuous rubber tube. Thus it wasn't really meant to be cut down to a shorter length.

@user253751 Knowing copper is expensive, why wouldn't more copper increase the price? Maybe things work differently in Asia?

@Bort PCBs are usually made with a subtractive process where the board is fully covered in copper and then some is removed and discarded. So you pay for all the copper you use and all that you discard. I dont know if this applies to flexible substrates.

@Matt - Wouldn't the baseline amount of copper change the cost though? Example: Starting with a PCB 1 unit thick of copper and then subtracting, vs starting 3 units thick and then subtracting. While the subtraction doesn't save the buyer money, the initial choice of thickness would, right? Or am I missing something?

@Bort Yes, you are correct, thickness changes the cost. I assumed we were just talking about copper trace widths.

@Matt - Oh, I now see that user253751 was referring to width, not thickness! But then I wonder why they didn't consider thickness...

@Bort You can still cut it, but you'll have to find something to seal the end with, which might take some research or experimentation (you can't just assume that filling the end with hot glue will keep it waterproof - though it might be sufficiently waterproof for your use, if it's only a small amount of water)

@user253751 Silicone sealant (bathroom sealant) is the normal method...

It's not necessarily cheap construction.. but the ws2811 strips where 3 RGB LEDs are controlled by 1 chip need quite a lot of traces routing on just 1cm of strip width. This in turn limits the width that the two power traces can have, which results in a rather high voltage drop over distance. For this reason, vendors of those strips usually advise to put secondary power injection points after each 1 or 2 meters of strip. This problem is less noticeable with ws2812 LEDs with their integrated controllers, as they can have two rather broad power traces runnng straight along the whole strip.

(but the ws2812 in turn are sold in variants with up to 144 LEDs per meter, which draws so much power that secondary power injection does become necessary again.. albeit with a much higher light output)

@WooShell That would explain the difference. The strip I had used WS2812s.

@Bort another trick you could try is connection only the ground at 1 side of the rail, and only the positive at the other side, this should mostly self balance the voltage any led sees

I've got a fair bit of experience with these strips. In theory, for the 5V, 60LEDs/M types, you need to power them every 1M or so along their length, in practice I find that every 2-2.5M is plenty - so long as you have a sufficiently high current power supply (although it's manufacturer specific). For 12V I'd imagine you could stretch to 2.5-3M between taps. The silicone jacketed types do need a small hole sliced out of the jacket to attach the power "taps", which should then be comprehensively filled with exterior silicone sealant.

@Majenko, the poster has not specifically said he is using Arduino. Do you not think you should close down the question, as it might be off-topic, or is that just a rule for anyone that mentions the word MicroPython?

@PrestonDocks No, I count this as on topic. 99.999% of people using these are using them with Arduino. You don't need to specifically mention it. But using a non-Arduino microcontroller with non-arduino code is obviously off topic. If you don't like this question then exersize your close vote. That's what it's there for.

@Majenko 99.999% of people using ESP32 boards are using them with the Arduino IDE, but because I mentioned the word MicroPython in a question related to ESP32 you closed my question. Also most people using Arduino, are not using Arduino, they are using clones.

@PrestonDocks An ESP32 is not an Arduino. If you use it with Arduino code then we are happy to assist you. But since you aren't, then we can't help you. If you continue to moan and whinge I'll ban you.

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:

simulate this circuit – Schematic created using CircuitLab
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 = RNI_Led, the one on the second is dV2 = R*(N-1)I_Led and so on, up to dVN = RI_Led. The total voltage drop is dV = RN(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.

This strip was sold as IP67 and sealed in a single continuous rubber tube. I would have to break that seal to get those measurements, though I guess there's not much to lose at this point.

@majenko, this answer is about Electronics Theory, it is definitely not about Arduino so it is off-topic. Can we close it, please?

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]

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.

@majenko Another Electronics Theory answer, we are getting very of topic again. Can you please moderate appropriately.

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.

Actually, it is a 12V strip, I'm not sure where you got "5V" from. As the question also states, I have another 12V strip that is nearly identical except that it uses the 1903 IC, and that strip works fine with all white.

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

When you say the WS chip requires 3.3v to 5v [and the IC requires 6-7V], which IC are you referring to? IC and chip are pretty much the same to me.

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

Note that if power and ground are connected at opposite ends, there will still not be a perfectly even voltage for each LED segment. I have added an answer of my own with a simulation to address this


text:
MKR 1000 not found in ports when MKR IMU Shield is connected
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.

a damaged shield?

@Juraj Also, when the shield is plugged into the board, the shield becomes very hot. Could this also be a sign of a damaged shield?

a basic question: the pin labels match on MKR and shield?

@Juraj Yes, the pins match up when I plug the shield into the MKR. Thank you for your help!


text:
Creating an array, assigning a value to each indices, and assessing the array
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);
}

if you want to run the code only once, then put the code in the setup() block ... leave the loop() block empty

why do you have a stop() function? ... you never call it

make the array global. and it is too large for Uno. and Vs[i] = analogRead(A0) * (5.000/1024.000);

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


text:
Arduino code does not function when relays are powered
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) the charger's output is 5V 2A. jd-vcc is jumped with vcc

this is caused by EMI from relays. add relay (module) model and wiring to question

Does the phone charger put out enough current to drive the relays? Looks like each relay pulls more than 1/3 of a watt.

first try to wire the Ground pin next to jd-vcc and Vcc


text:
External vs internal pullup
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.

From my experience the only difference is "external pullup/pulldown is easier to replace" and maybe also "by just looking at the circuit you can see the external resistor so it's easier to understand the design after few months"

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.
NOTE: As far as I know, at the writing time, Arduino library does NOT support INPUT_PULLDOWN

The heat generated by the internal pullup is negligible. 2. Some boards (not the AVR-based ones) have INPUT_PULLDOWN.

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

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.

As I wrote in a comment to the previous answer, some Arduino cores do support INPUT_PULLDOWN.


text:
Sending more than BUFFER_LENGTH(32) bytes in slave answer I2C
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 and in HW (Arduino Nano). 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

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.

I have to communicate with existing HW. For now I've passed the data pointer and data size from the sketch into twi.c and using it directly. A "hacky" way indeed. However I'm hoping there is some standard way doing that.

Not using Arduino software, no. It's not designed for that kind of amount of data. Neither, really, was I2C...


text:
MCP4725 I2C address
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:

In page 10 of the datasheet 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...

The MCP4725 has 3 variable address bits. A0 on which you have access and A1 A2 which can be chosen by the customer that bought the chips to create these breakout boards (see picture above). Perhaps there is a chance to get boards of two address series. I know, that's a bad advice if you just bought the boards, but if not this could be a chance to four boards on the bus.

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.

Thanks, If DAC1 output is for example 1024 and then I switch to DAC2 the value on DAC1 will reset to 0 or stays at that value?

The DACs only ever change their value if you change the value or if you reset the device by removing the power.

This concept will surely work, but the OP should be aware of that, he can not use this solution in a setup with variable/pluggable devices where scans of the I2C bus are necessary. (e.g. switching to a raspi may cause this).


text:
Ramping up and down arduino motor due to ultrasonic sensor input
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;
}

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


text:
What are the sizes of each primitive datatype on a Metro M4 Express SAMD51?
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

It depends on compiler's data model for target processor. But I'd rather use int16_t/int32_t instead. It's much better for portability.

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

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.

Note that unsigned int ui = -1; is a valid way to set an unsigned number to it's maximum value. 2. sizeof(int) may be more convenient. 3. int and long are both 32 bits on most 32-bit environments, and even on 64-bit Windows. 4. It would be cool to have also the size of pointers.

Oh, forgot about sizeof() which works on pointers, too. To your suggestion (1) I would comment that 'unsigned long long x = -1LL' is strange style with type conversion and its up to the compiler to do the right thing. I would not do that.


text:
GPS Speedometer value didnt come out
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, "%3d", 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]

run OLED example code

What have you tried to debug the code? Can you display literal text? Does the data get correctly read by the Arduino? What is actually happening on the display? (Really nothing, or just not the correct data) Please give us more information

Instead of tackling two potential problems at once, do it one after the other. 1. Make sure you that you received the position correctly. You may use the serial connection and the IDE's serial monitor for this. 2. Make sure that you can write arbitrary contents on the display.


text:
Why is this code not working?
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

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.


text:
Does AWG size affect signal from sensors?
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!

you asked the same question twice ... yes, wire size does affect the signal ... whether the actual data is affected depends on the type of data, analog or digital ...... nice thin wire will ensure little disturbance most of the signal will be absorbed by the wire

I don't think thickness matters. The problem is that a long wire acts like an antenna, picking up external "noise", that can influence your signal. This is mostly an issue for analog signals, or really fast digital signals.

I use 30AWG wire for Arduino signals. I never had any problems with those wires. And to be precise I use silicon wires which are extremely flexible - perfect.

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.

There are also things like it has some self inductance and capacitance which acts against changes. And of course there is signal crosstalk caused by it. Also there should be matching impedance on both ends, so there are no signal reflections.

Yes, but none of that really has anything much to do with the thickness of the wire. I could have gone into signalling methods, voltage levels, NRZ, differential signals, shielding, etc... but all that is outside of the scope. Maybe if the question was asked on the EE.SE, but not here.

True. Maybe skin effect, but it'll be on higher frequencies than low speed serial or pulses from ultrasonic sensor.

I'd put the last line in bold to make it easy on skimmers.

Of course at high frequencies the problem gets a lot more complicated. As you say, most of that doesn't have much to do with wire thickness, but I would make that the major point of the answer: "As long as your wire is thick enough to limit the voltage drop so that you have good signal to noise, wire thickness is much less important than a whole range of other factors: Inductance, capacitance, RF shielding, etc etc."


text:
Powering Peltier using solar panels
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.

If you don't want to use batteries, but a direct relation between solar radiation and the peltier effect, what's the purpose of an arduino?

Limit current based on temp in cooler, it will be more efficient. You don't need to use 12V, go lower. DS18B20 is a good option if you're digital, else consider a dielectric temp switch.

@user2497, Thank you for the suggestion and I will be able to achieve the required maximum cooling level even with 6V. Controlling the cooling level of the Peltier with the help of a temperature sensor is an interesting idea. I will definitely try this.

@Indee An LDR and a potentiometer, along with a P-FET should make a decent driver circuit.

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.

Hi Duncan,  Your answer is very helpful and informative. I will work on the solar Peltier circuit. I wanted the Arduino to control the cooling effect of the Peltier using a phone App. Seems like I have to use a battery and voltage regulator to obtain this.It

It would be a great support if you could help me with the Solar, Arduino, Voltage regulator and battery circuit?

Hi DataFiddle, I need the Arduino to control the Peltier using a phone App.

See the edit to my answer. I gave you some guidelines on what to do. I'm not going to design the project for you in detail however.

Hi Duncan, The answer is very helpful and have enough information for me to try it by myself. Thank you very much.

@Indee I added a little more detail about lead-acid batteries.

Hi Duncan, Thank you very much and the guidance you provided is highly appreciated.

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.

Well, yeah. If you need to solve a real-world cooling problem, that is indeed the way to go. (voted.) BUT BTUs? Really?!?

@JRobert: Thank you very much for your answer. My project is closer to 'a Peltier beer-cooler' as I'm planning on to develop a Peltier cooler to provide cooling to food and beverages when travelling under hot climate conditions. Seems  like reserving energy is an important aspect which I need to consider.


text:
Sending the data for temperature and soil using esp8266-01 through software serial
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;
    }
  }
}

ESP boards are definitely nothing for beginners. The problem with them is that they might have very different Firmware versions on them. You can for example not be sure what baud rate they are using. So, you have to find out which baud rate the Serial interface uses. You configured 9600 Bit/sec but most of the boards need 115200. Event ESP Gurus do flushing the ESP with a well define firmware: e.g.  https://medium.com/@aallan/getting-started-with-the-esp8266-270e30feb4d1

It would be a good idea to also add the complete output of the arduino to the question. The output helps us to follow the program and how it executes.

thank you sir, the output was just "ATE0"

did you set the baud rate of AT firmware to 9600 baud? (btw, I wrote this version of sendCommand function)

not yet sir, awsome!

It doesn't work

after I uploaded the bareminimum to separate ESP-01 to arduino, then I got this output Both NL & CR 115200 baud set in the serial monitor, ets Jan  8 2013,rst cause:4, boot mode:(3,0)
wdt reset
load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79
2nd boot version : 1.5
SPI Speed      : 40MHz
SPI Mode       : DOUT
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

@Juraj need help sir

I connected RX and TX of arduino and esp-01 accordingly while uploading the bareminimum and set BL & NR and baud rate of 115200, still not work

https://chat.stackexchange.com/transcript/85432/2018/11/7

short version https://arduino.stackexchange.com/questions/57496/arduino-uno-with-esp8266-01-with-at

Possible duplicate of Arduino Uno with ESP8266-01 with AT

I already read those articles

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

yes, this was the idea. But I can't go back with the AT Commands, I checked all the wires and process done well. output are just some internal information and unknown  random symbols printed in serial monitor


text:
Using the MIDI library in my own library

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

You should include the complete error message. Every error has a line number, where it happened. And please show us your complete code, including the Arduino sketch, that is using your library, so that we also can test.

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


text:
uint8_t to Text
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);
}

You first need to define how your string looks like, and than convert each value to a string (or text characters you place/append in a character array).

You currently create binary data. Why? You want text, so just Serial.print() the data directly.