text:
How to heat the air with arduino?
I have a plant growing box, fully controlled with arduino.
Youtube: ESP8266 IOT Flora
All things are under control, besides the air temperature.
I can cool it down running fans, but cannot find a way to heat it up.
Need to keep the temperature between 25-28 C all the time.
I was thinking of:

8x8 (64) Leds - maybe this can heat up the temperature, how much ?
Dedicated Module - is there any 5v heating module available ?

How are you powering the ESP8266?

3A 5V - Typical iPhone charger.

It really depends on the space you need to heat. Are you brewing beer or trying to survive a high latitude winter? How much insulation does the space have, how often is it opened to the outside (for inspecting your beer, or people entering and leaving the space, respectively)? You could need to control anything between a Peltier-effect heater/cooler, to a house- (or larger?) sized HVAC unit.

@PeeS you can use a piece of nickel chrome wire to heat that tiny box, just have to calculate the length of wire...

You could add some insulation to the box.

@newbie - is there anything i can read about it? Seems like a simplest solution.

@JRobert - the box is in the garage, all year - actually the tempearture drops there during winter to 13C.

@Gerben - good point actually, thanks.

@PeeS see the answer i just posted.

LEDs are not really efficient for heating up, you can better use a normal light bulb for that (they are less efficient, thus giving more heat).
The Arduino can only control some 100's of mA, that's not much for heating purposes.
Did you think about using a real heater (maybe small size), and use a relay to turn it on by your Arduino, and using a temperature sensor to switch it off above 28 and switch it on below 25 (or a lesser margin to keep up with the time it takes to change the environment temperature)?
If you do not want an external mains power, you could use probably a 12V heater and use a 12V->5V converter for your Arduino, or use a 5V heater pad, but according to what I have seen they are more for warming up cold hands, I doubt they can bring up the heat to 25-28 degrees Celcius. Besides, they are probably not very efficient.

Thank You Michel,
sure i can go with the external power supply - reason i didn't do it yet is just because  i like how clean the whole setup is with a single 5V 3A power.
I also have ESP12E motor shield :
https://arduino-shop.eu/arduino-platform/1456-nodemcu-esp8266-motor-shield-lua-l293d-esp8266-wifi-motor-control-arduino-esp-12e.html
where i can connect external power source and there's a relay.
Question is what do i choose to keep that 25-28 ..

If you search for a recommendation for a heater, than I don't know. Also, to be honest, that's not an Arduino question and on Electronics stackexchange product recommendations are not allowed. Maybe you can try Home Improvement/ DIY stackexchange: https://diy.stackexchange.com/

Thanks again, will look more and update the post with findings.

Good luck with your project :-)

The total current of your power supply, 5V • 3A is only 15 watts. That's not enough power to create a meaningful amount of heat. (although looking at your video your grow box is really tiny...)
LEDs are a terrible choice for providing heat. They produce mostly light, and very little heat (which is good if you want light, but bad if your goal is to build a heater.)
You probably want 30-60 watts of heat. As others have said, you could use a light bulb with a relay to control it. You could use a digital thermometer like a DHT11 to measure the temp, and then have a "digital" relay to control the heat source. You'd write a sketch that would turn your heater on at slightly above your minimum temp and turn it off at slightly below your max temp. (How much above and below your thresholds should be would depend on how strong your heater is and how long it takes to heat up your grow space. You'd need to do some testing.)
I created a forced air "boot dryer" where I used a couple of 120V, 500 watt heating elements in series (which lowers the power to 250 watts) and a thermostat. That is likely way too much heat for your tiny grow-box. Here is a link to that heating element: https://www.amazon.com/gp/product/B005RG64LQ/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1
And for a relay I used a 5V "digital" relay like this one: https://vetco.net/products/single-relay-module-for-arduino?gclid=EAIaIQobChMIgfy8jtjJ4wIVA5-fCh2TXQH1EAQYBCABEgI3mfD_BwE

Note that if you have a high current DC supply you can use a MOSFET transistor rather than a relay to switch your heater on and off. To drive a heater you don't need a regulated supply. A simple high current "wall wart" style DC supply that puts out >= 30 watts and a low powered heating element would work.

For that matter, you could use an AC step-down transformer and a full wave bridge rectifier to create switched DC and feed that into a high power switching MOSFET and then to your heating element. For driving a heating element you don't need to regulate the power at all - just get rid of the negative voltage, since transistors can only switch current in one direction.

So why the down-vote? If you think my answer needs improvement please explain why.

note that most LEDs make about half light and half heat, which isn't half bad for making heat. even the best ones are only about 65% efficient.

You can use nickle chrome wire to easily heat that small box.
From Wikipedia:

Almost any conductive wire can be used for heating, but most metals conduct electricity with great efficiency, requiring them to be formed into very thin and delicate wires in order to create enough resistance to generate heat. When heated in air, most metals then oxidize quickly, become brittle, and break. Nichrome wire, however, when heated to red-hot temperatures, develops an outer layer of chromium oxide, which is thermodynamically stable in air, is mostly impervious to oxygen, and protects the heating element from further oxidation.

5V nickle chrome wires are available online to order, it's usually used as car seat heater.
Just be careful do not use Nickle chrome wire with Arduino directly because it can draw up to 2A from the power source and burn your Arduino board, instead use a relay to control the heater.
Here's the schematic to control a heater using Arduino and a relay:

simulate this circuit – Schematic created using CircuitLab

One simple way I can think of would be to turn a 100 W lightbulb (EDIT or whatever size makes sense for your application) on / off using a relay.  You could use a heat lamp, but with a small box like you have, a lightbulb should give off plenty of heat.  You would want to make sure that the bulb didn't give off enough heat to damage any plastic too close to it.

I was thinking a 100W bulb as well, but given how tiny that box is, 100W might be too much. I'm thinking 30W might be better.

Yeah, one of the cool things about using lightbulbs is you can tune it to the desired output just by swapping bulbs.  I'd think the desired result would be the minimum wattage that was able to maintain temp, so as to avoid thrashing the relay.

Thrashing the relay or cooking the seedlings. You don't want to either cycle the power too often or overshoot the target temp/blast the seedlings with too much infrared.

I wonder if an (incandescent) grow light (more expensive) would give a two for one deal and also provide better growing conditions?

I thought about that, but plants do best with a distinct day and night period. Lights that turn on and off at odd intervals driven by the temperature would likely disturb the plants' circadian rhythms. Better to run the lights based on day/night cycles, and the heater based on temp. Using LEDs for the grow lights would be a good idea to avoid overheating the plants during their day hours.

I had a similar concern.  I think if one were to go with the "lightbulb" approach then it would probably be best to use a low wattage heat lamp pointed away from the plants themselves.


text:
The ESP8266 connects to open WiFi hotspots, even If I supply a password
This question is more out of curiosity, then out of a need to solve something.
I was trying out some experiments with the ESP8266 Arduino core when I realized that I had programmed an SSID and password for the ESP8266, but the WiFi that I had set up was an open network.
I tried going through the documentation and then the Arduino core source code, but couldn't find if WiFi.begin(ssid,passphrase) a function does this on purposes, as in it was designed that way, or did it just happen to work this way.
Also, I would like to know if there is a way to stop the ESP from connecting to an open network when the passphrase is provided.

It's probably by chance - however it's impossible to know.
Connecting is done by wifi_station_connect(), which is a function provided by the (closed source) ESP8266 SDK. So we can never know what it's actually doing.
However, the sequence is probably something like:

-> Connect
<- Ok, give me a password
-> Here it is
<- Right, you're connected

Or, with no PSK:

-> Connect
<- Right, you're connected

Although you specify the password (which just gets stored in the configuration) if it never asks for it then it just doesn't use it.
Can you force it? Not without knowing what's going on in the mystery wifi_station_connect() function.  There is nothing much in the documentation for the SDK that even hints at a clue.

source: Stack Exchange

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

sort: votes


text:
Confusion between switch and if?
Following code is to control two LEDs for on and off by two dedicated push buttons. I have used if() for each condition and I was not comfortable writing this code, as I could feel, it can be better with switch...case, because if we increase more buttons, it will be a messy solution for that. However, I couldn't get optimized switch...case for it. Can some one suggest the nice switch transformation for this if().
int buttonState1 = 0; // variale for reading pushbutton1 status
int buttonState2 = 0;  // variable to reading push button2 status
//set pin numbers
int button1 = 2; // push button no. 1
int button2 =3;  // push button no. 2
int Led1 = 4; // led 1
int Led2 =5;  // led 2

void setup() {
  Serial.begin(9600); // serial begins at 9600
  // defining pin modes for led and buttons
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode (Led1, OUTPUT);
  pinMode (Led2, OUTPUT);
};

void loop() {
 buttonState1 = digitalRead(button1); // reading pushbutton 1 in the variable buttonstate1
 buttonState2 = digitalRead(button2); // reading pushbutton 2 in the variable buttonstate2
 // condintion for led 1 ON, if pushbutton1 is pressed
 if (buttonState1 == HIGH) {
  digitalWrite(Led1, HIGH);
  }
  // condition for led2 ON, if pushbutton2 is pressed.
 if (buttonState2 ==HIGH){

  digitalWrite(Led2, HIGH);

  }
  // both led are off if no push button is pressed
  else{
    digitalWrite(Led1, LOW);
    digitalWrite(Led2, LOW);
  }

};

Sidenote. The else only applies to the second if statement. So if you release button 1 while button 2 is still pressed, led 2 won't go off.

You could also do replace the entire code with, digitalWrite(Led1, digitalRead(button1)); digitalWrite(Led2, digitalRead(button2)); . Could you expand a bit on what you want to achieve, as that would limit the numerous different approaches you could take. If you want to read a  large number of buttons, and change their accompanying leds, you could use an array for the button pin numbers, and an array. Then use a for loop to read each of the buttons one by one, and run some code. That would reduce the amount of "duplicate" code.

If you want to use a dedicated push button for every led, then it is not handy to use a switch .. case statement. This is because first you have to construct the switch-variable based on the readings of the switches before you can use it (the switch variable) for de case statements.
When you combine the reading of the switches with the setting of the leds you get a nice Loop-section:
    void loop() {
      digitalWrite(Led1, digitalRead(button1));
      digitalWrite(Led2, digitalRead(button2));
      digitalWrite(Led3, digitalRead(button3));
      digitalWrite(Led4, digitalRead(button4));
      digitalWrite(Led5, digitalRead(button5));
      // and so on
    }

A switch case does not seem like it would be an effective way of controlling your LEDs. It would make more sense (and would probably be easier) to create a function instead to control the LEDs.
void buttonToggle(int buttonPin, int ledPin) {
  int buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

You would then need to replace your if statement with calls to the function (EX buttonToggle(Button1, Led1);

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


text:
What is the relationship of an Arduino .ino file to main.cpp?
Is the .ino file an alternative from a main.cpp file?
If yes, then could someone mind explaining the structure of the .ino file in main.cpp and its relationship?

... ... What ... ... ?

No need to put on hold. English is not my native language, and I had no problem with the question.

As well, closure is usually applied for obviously off-topic questions or worse infractions. Why was this closed rather than just held for clarification? Voting to re-open.

@JRobert, the Answer by Jot is good. The Question should be edited.

The Arduino uses the gcc compiler. That compiler wants a normal main function of course. Arduino has put a layer on top of that with setup and loop.
The hidden main function for basic Arduino boards is in main.cpp (click on it to see it).
You see that init is called, and setup and loop and a few other things.
To learn how to use setup and loop, you can try a few examples. They are in the menu of the Arduino IDE and they are also online.
The .ino files are all combined together and presented to the compiler as a single .cpp file to compile. The Arduino libraries are compiled from source as well, and everything is linked into a binary.
When you know how to use setup and loop, try the Blink Without Delay example. It can be used to run different software timers and do all kind of tasks and keep everything running smooth.

It solves my query, thanks for explaining the int main function in main.cpp. Also I would try the blink w/o delay example as you suggested.

The link to main.cpp has moved to a new repository, here is the new location.

@LukeBayes Thanks, I have adjusted the link in my answer. The old standard avr has been moved to "ArduinoCore-avr".

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


text:
Extra "zero" displayed on LCD when integer sent from PC to Arduino through serial port
Every time I send an integer from computer to Arduino an extra zero is displayed on the LCD connected to Arduino. I don't know the reason. Why?
Here is the code:
#include <LiquidCrystal.h>

int en = 2, rs = 3, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
int a;
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);

void setup() {
    Serial.begin(9600);
    lcd.begin(16,2);

}

void loop() {
    Serial.println("Enter a number");
    while(Serial.available()==0){}
    a=Serial.parseInt();
    lcd.print(a);
}

The result is as follows:

Enter a number
When I enter the number 1
The result 10 is displayed instead of 1

and what you get if you print a back to Serial Monitor?

It is a typical problem when reading the serial input. The more experienced arduino users do not use such a while-statement to wait for input and do not use the Serial.parseInt functions. You might send a linefeed as well, and the Serial.parseInt can not make a number from the linefeed and returns zero or perhaps it has a timeout and returns zero. https://www.arduino.cc/en/Reference/StreamParseInt

Is there any alternate command/function instead of using Serial.available() and Serial.ParseInt()???

@Jot, not true. parseInt has no problem with LF or any other character. we still don't know what is the value of a

@Juraj there could be a linefeed and there could be a timeout. I'm pretty sure the parseInt returns a normal number the first time and a zero with the next call to parseInt. In my opinion it is very obvious (even without actually testing it).

@Jot, true. Rizwan, add while (Serial.read() != -1)' after parseInt();

It is display related problem. You need to clear display field(s) before printing number.

The Serial.parseInt returns zero when it can not find a number within a timeout. That timeout is default one second.
When a number is typed in the serial monitor, often a linefeed is added to it. That linefeed is read by Serial.parseInt. It can not make a number out of that and waits until the timeout and returns zero.
There is no way to tell if the Serial.parseInt returns zero because the number was zero, or if it returns zero because there was a timout.
You can try the next sketch to show the problem. Set the line ending in the serial monitor to linefeed or carriage return or both or nothing and see what happens.
int a;

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

void loop() {
  Serial.println("Enter a number");
  while(Serial.available()==0){}
  a=Serial.parseInt();   // it returns zero with a linefeed !
  Serial.println(a);
}

The easiest way to fix this, is to use a number that is only a single digit. The function isdigit is used to check the incoming characters.
void setup() {
  Serial.begin(9600);

  Serial.println("Enter a number (a single digit)");
}

void loop() {
  if (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isdigit(inChar)) {
      int value = inChar - '0';
      Serial.println(value);
    }
  }
}

The Serial.parseInt is not completely useless, but the number zero can not be used. The next sketch ignores the input when Serial.parseInt returns zero.
void setup() {
  Serial.begin(9600);

  Serial.println("Enter a integer, but not zero, with a linefeed at the end");
}

void loop() {
  if (Serial.available() > 0) {
    int value = Serial.parseInt();
    if (value != 0) {
      Serial.println(value);
      Serial.println("Enter a integer, but not zero, with a linefeed at the end");
    }
  }
}

To be able to allow to type the number 0, the Serial.parseInt can no longer be used. To avoid waiting and delays, every character is immediately put into a buffer. The sketch becomes larger, but there is no other way. Either use Serial.parseInt or do it right.
#define BUFFER_SIZE 40
char buffer[BUFFER_SIZE];
int index;

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

  Serial.println("Enter a integer, with a linefeed at the end");
}

void loop() {
  if (Serial.available() > 0) {
    bool ready = false;

    int inChar = Serial.read();
    buffer[index] = (char) inChar;
    index++;
    if (index >= BUFFER_SIZE) {
      index = BUFFER_SIZE - 1;
      ready = true;
    }

    if (inChar == '\n' || inChar == '\r') {
      ready = true;
    }

    if (ready) {
      if (isdigit(buffer[0]) || buffer[0] == '-') {
        buffer[BUFFER_SIZE - 1] = '\0';
        int value = atoi(buffer);
        Serial.println(value);
        Serial.println("Enter a integer, with a linefeed at the end");
      }
      index = 0;
    }
  }
}

thank you so much..@Jot..                                                                                Thank to all of you..

2 things:

use lcd.println() instead of lcd.print().

Once you open the serial monitor, set it to "No line ending" instead of "newline".

if you do step 1 but miss step 2 the 0 will print on the next line.


text:
Read only one line in SD card
I have some C++ code, but I cant convert it to Arduino language.
I just want to ask, what is the same as getline() (C++ code) function in Arduino?
I just wanted to get the first line in my SD card...
I can only display all text inside my SD card...
Example:
line1   <-   only this line should display(and this line will delete in text
             file... but that is another issue... i will just focus to get the
             line1 and get the value)

line2

line3

line4

line5

This code displays all lines
    #include <SPI.h>
    #include <SD.h>

    File myFile;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port                          only
       }

       Serial.print("Initializing SD card...");

       if (!SD.begin(4)) {
         Serial.println("initialization failed!");
         while (1);
       }
       Serial.println("initialization done.");

       // open the file. note that only one file can be open at a time,
       // so you have to close this one before opening another.
       myFile = SD.open("test.txt", FILE_WRITE);

       // re-open the file for reading:
       myFile = SD.open("test.txt");
       if (myFile) {
         Serial.println("test.txt:");

         // read from the file until there's nothing else in it:
         while (myFile.available()) {
           Serial.write(myFile.read());
         }
         // close the file:
         myFile.close();
       } else {
         // if the file didn't open, print an error:
         Serial.println("error opening test.txt");
       }
     }

     void loop() {
       // nothing happens after setup
     }

You'll be happy to learn that there is no Arduino language. Arduino's .ino files are C++! The only difference is the Arduino IDE automatically generates function prototypes if you don't provide them yourself, but that doesn't make it a different language.

There is no builtin way to do that but you got all the necessary tools at hand.
End of line should be signaled by a decimal 10, aka LF(Line Feed) character.
So what you do is keep reading until you encounter LF or end of file, which then is the entire line you want to read.
while (file.available() && file.peek() != 10) // peek returns the next character without incrementing the read index
    file.read();

This code does exactly that. Now you could either store the read bytes in a buffer (big enough!) right away or instead find out the number of bytes beforehand to create a precisely sized buffer afterwards and use the read(buffer, length) overload to read all bytes at once.
Please keep in mind that the LF character has to be there in order to be read. So if you are the one creating the files, be sure to place it. (most desktop text editors do that for you)
Example:
char buffer[20];
uint8_t i = 0;

while (file.available() && file.peek() != '\n' && i < 19)    // note how this also prevents the buffer from overflowing (18 max to leave space for '\0'!)
{
    buffer[i] = file.read();
    i++;
}
buffer[i + 1] = '\0';    // it is good practice to end strings with a terminating NULL character

i understand what you are saying but
im sorry @mystery, i dont even know what function should i used :(
im just new in arduino...

Should it not be " i < 18" instead of "i < 19"? If i is 18 it will become 19 with the i++. Then buffer[i+1] will be buffer[20] which will fail.

it also needs a file.read() after the while loop. Otherwise the \n never gets read and next line being read will be stuck on that \n.

and it should be buffer[i] = '\0' in the end.

If I understand you correctly, it depends on what you want to do with that code. Do you want to execute lines of C++ code in/on the SD card or are you merely attempting to convert what you have in C++ to "Arduinoese?"
If you need to, you can actually execute microcontroler-based C/C++ code on your arduino if it has an AVR in it, and you have the proper AVR Toolchain.
Elliot William's "Make: AVR Programming" book is a great place to learn about this.

You can run C/C++ on any Arduino board, not only the AVR ones, and if you can use the board with the Arduino IDE then you already have the toolchain. This is certain because Arduino sketches are C++.


text:
Distance measuring utilizing (1 or 2) Arduino Nano's
I would like to develop a small-distance measuring device that will be primarily used in indoor scenarios to measure a distance with cm accuracy (mm if possible). The device would be in a small form factor and would calculate the distance it has moved in reference to the starting position. However, upon doing more research I have found that this is a bit harder than I thought it would be. My initial idea was to utilize an accelerometer and take the double integral to determine displacement, however, I learned that this is primarily impossible with consumer grade accelerometers.
My current idea for implementation would utilize a small stationary external device that sends signals constantly back and forth measuring the difference in time it takes the wave of information to be received. I have looked online to find similar projects to this, but could not find any. Perhaps I haven't looked hard enough, but does anyone know if projects like this exist (preferably Arduino based)? If not then, would a simple consumer-based IR sensor work for this situation? Maybe I'm overthinking it and there's an even easier solution for measuring small distances with an external device. I could use some guidance on this. Thank you.

please delete the wifi and bluetooth tags .... those two technologies are not for measuring distance and are not related to your question

the wifi and Bluetooth tags are there as they are possible means of wireless communication that I would have liked to explore to coming to the solution for the specification I am outlining here. Bluetooth and wifi can and have been used to measure the distance between two objects. However, I have not found one to the spec I have mentioned

people researching wifi or bluetooth problems will get your question as containing a possible solution ... do you honestly believe that an accepted answer to your question will actually be of use to them?

No, you're right that people searching for wifi or bluetooth problems will probably not have any use with this topic. However, the topics of wifi and bluetooth are related to this topic, and is that not what tags are for? Because I imagine people researching wifi or bluetooth problem are likely not going to find answers in a majority of the topics tagged with those subjects here (briefly looking through the list of tagged questions that is).

maybe you could use an optical sensor from a mouse  ..... it appears that you want to measure the total distance traveled ..... note: distance in reference to starting point is different from distance traveled, if the travel path is curved

Alright, thanks for the tip about optical sensors, I will definitely look into that. Yes, you're right displacement is the definition for my specification I gave in my opening question rather than total distance traveled. I should have been more clear on that, my apologies.

Try to take a look to Lidar sensors.
Here an interesting guide by SparkFun.

Look at Ping sensor also. Ultrasonic, way less expensive than Lidar.

Ultrasonic ranging module HC - SR04 provides 2cm - 400cm non-contact
  measurement function, the ranging accuracy can reach to 3mm.

https://www.digikey.com/product-detail/en/sparkfun-electronics/SEN-13959/1568-1421-ND/6193598&?gclid=EAIaIQobChMIs4Ltisap3wIVD4zICh0mkwyfEAQYAiABEgILqfD_BwE
Give it a shot, see if the $4 solution meets your needs.

Thanks for the suggestion, however, my specification would require the object in question to work reliably without any nearby walls to reflect the ultrasonic sensor back to it.

So sound won't bounce back - will light (LIDAR?) Are you looking for some mechanical means of measurement?

Light wouldn't work unless it was targeted to the device in question (ultrasonic would work in such a manner as well, but i'm not sure if either is capable of this). Ideally, the object being used to measure the distance should be operatable without the reliance of any external walls. I was thinking of having a device that could move in any direction within a 3-axis plane and the displacement would be measured in reference to an external object that is within line of sight. So more like a transmitter-receiver scenario where the transmitter and receiver are each connected to different devices.

Maybe you could use call back method with a beacon. Target sends out a request, beacon sends it back. Target calculates how far away based on time.  Have the target send it out in several directions while rotating in place to determine where the shortest direction is.  Course, radio waves travel at the speed of sound.  So sound may work better, give you a chance to measure more than just the response time of the beacon.  Or put the Tx unit on a servo and pan it around so you're not changing the target's orientation all the time.

Yes, that sounds like it might be possible, any recommendations/ideas on specific hardware?

Ping sensor as mentioned above, your choice servo panning. Any microservo should do. Send out one code, look for a different back as a response.


text:
strcat char concatenation trouble
Still don't understand about char concatenation.
void setup() {

  testCounter(3);

}

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

char testCounter(int countx){
  char a[10];
  strcpy(a, "COUNTER: ");
  strcat(a, printDigits(countx));
  return a;
}

char printDigits(int digits){
  char a[3];
  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {
    sprintf(a,"%d",digits);
  }
  return a;
}

Error:  invalid conversion from 'char' to 'const char' [-fpermissive]* in testCounter line:
strcat(a, printDigits(countx));

Don't understand this part of error.
printDigits function return char, so... strcat should be work. But why still error?
Please help...

char printDigits(int digits){

You are telling the compiler you will return one character.
 char a[3];

a is three characters. Thus the declaration doesn't match.

You could change the declaration to:
char * printDigits(int digits){

But even that would be bad because a would go out of scope after the function returns.

 char a[3];

That's a little short for putting an integer into. An integer might be 5 characters, plus possibly a minus sign, and you need a trailing "null" at the end. Seven bytes would be safer.

The simplest way of doing what you seem to be wanting is:
void setup() {
  Serial.begin (115200);
  testCounter(3);
}

void loop() {
}

char testCounter(int countx){
  char a[15];
  sprintf (a, "COUNTER: %02d", countx);
  Serial.println (a);
}

Also, here:
  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {

That won't work because you are putting "0" into a and then overwriting it with sprintf.

printDigits function return char, so... strcat should be work. But why still error?

Look at the prototype for strcat:
http://www.cplusplus.com/reference/cstring/strcat/
It expects char * not char. They are different things. One is a pointer, one isn't.


text:
SG90 not responding with Arduino Uno
I bought an SG90 servo motor, seller demonstrated by direct supply check, it works there but with Arduino servo sweep check it does not respond: no error during compiling and uploading, but it does not respond.
While other Arduino examples are working correctly like blink example.
I have changed another one but result is the same.
Neither it moves by Arduino nor after installing a grbl shield, where is the problem?

Please, post your arduino sketch and schematic connections.

Even a small servo motor requires a lot of current. You could add a power supply. Do you use a good quality usb cable? The component on the right of the arduino board, with the golden stripes is a polyfuse of 500mA. That servo motor can draw 500mA or more.

Leoc 7, I have already attached a picture.

@AdnanTahir please post your code. As Leoc7 said, usually powering servos from the Arduino directly isn't the best idea, but in my personal projects I've powered several servos from my arduino, as long as they weren't under any load :)

Arduino can readily power an SG90 servo under no load in my own experience. Also see this question on Electrical Engineering SE. If you're seeing no response, there is a fault in the wiring, the code, or the servo itself.
I think I'm seeing the servo's signal wire (orange) connected to the yellow wire to pin 9. Is your sketch attaching pin 9? What is the brown wire connected to the Arduino near the servo's power & ground (red & black)?

@JRobert those servos use Orange for Sig, Brown for GND and Red for Vcc. I use them all the time in my RC projects, and haven't had any issues using Arduinos either. My guess is coding, we'll see if he posts it or not

OP has issue when using Arduino servo sweep - it's an example in the Servo library - it uses pin 9 for Signal ... so I dare say it should work unless OP modified the example (highly doubt it)

Friends, I did not modify code even a litte bit, I uninstalled arduino and reinstalled but whenever I tried the code servo did not rotate, however no error occurred in compile and upload. The code is same in the arduino IDE Examples >Servo >Sweep. I wanted to ask if there is a possibility of any fault in my arduino board 5v, gnd or signal pin. Because servo with direct 5v battery power supply is rotating that means servo is fine. I watched several videos regarding sg90 test with arduino uno and same I have been trying to do but the outcome is NO ROTATION as I have mentioned in my query.

I always tried arduino IDE menu option i.e. Examples > Servo > Sweep, I did not try any thing manually or a self written code. Wiring is accurate as shown in my attached picture. I wanted to know that is there any action missing or it is a confirmed board fault.

Then your next step should be to measure the 5v with a DVM: at the 3-pin connector with- and without the servo connected to it, and at the Arduino pin the connector is plugged-in to. Maybe all of the Arduino 5v pins (without the servo connected) if everything else wasn't what it should be (5v +/- a few millivolts).

@HavocRC: I may be confused by a shadow, but it looks rather like there are 3 conductors connected to the top row of the board and a 4-th one to the bottom (pin 9).

@AdnanTahir we know these servos work fine with Arduinos, and since the wiring is correct, here's all that could be wrong: Broken 5v rail from Arduino, broken PWM pin on 9, or a faulty servo. You can even measure with your DMM if the P9 is putting out the proper PWM frequency/duty cycle.


text:
How to convert jpeg byte stream into jpeg image and display on 1.8 inch TFT display
I have an ESP32 having a cam and it is transmitting compressed JPEG stream.

TTGO T-Journal ESP32
Camera Development Board
OV2640
SMA WiFi
3dbi Antenna
0.91 OLED Camera Board

I have an ESP32 having a 1.8 inch TFT screen and a SD card slot which act as receiver.

ESP32 TS V1.2
MPU9250
1.8 Inch TFT
Bluetooth
Wifi
MicroSD Card Slot
Speakers Module

On Chrome browser, I get a display of the JPEG images as a continuous image after image (video).
I can see the incoming compressed JPEG stream and i print it on serial monitor .
But I need to decode/ decompress the JPEGstream at receiving end and paint pixel of TFT screen .
Which steps am I missing? Can anybody suggest code of JPEG image rendering on TFT screen?

Sketch of transmitter:
#include "OV2640.h"
#include <WiFi.h>
#include <WebServer.h>
#include <WiFiClient.h>

#define ENABLE_OLED //if want use oled ,turn on thi macro

#ifdef ENABLE_OLED
#include "SSD1306.h"
#define OLED_ADDRESS 0x3c
#define I2C_SDA 14
#define I2C_SCL 13
SSD1306Wire display(OLED_ADDRESS, I2C_SDA, I2C_SCL, GEOMETRY_128_32);
#endif

OV2640 cam;
WebServer server(80);

IPAddress apIP = IPAddress(192, 168, 1, 1);

void handle_jpg_stream(void)
{
    WiFiClient client = server.client();
    String response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n";
server.sendContent(response);

while (1)
{
    cam.run();
    if (!client.connected())
        break;
    response = "--frame\r\n";
    response += "Content-Type: image/jpeg\r\n\r\n";
    server.sendContent(response);

    client.write((char *)cam.getfb(), cam.getSize());
    server.sendContent("\r\n");
    if (!client.connected())
        break;
    }
}

void handle_jpg(void)
{
    WiFiClient client = server.client();

    cam.run();
    if (!client.connected())
    {
        return;
    }
     String response = "HTTP/1.1 200 OK\r\n";
     response += "Content-disposition: inline; filename=capture.jpg\r\n";
    response += "Content-type: image/jpeg\r\n\r\n";
    server.sendContent(response);
    client.write((char *)cam.getfb(), cam.getSize());
}

void handleNotFound()
{
    String message = "Server is running!\n\n";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET) ? "GET" : "POST";
   message += "\nArguments: ";
   message += server.args();
   message += "\n";
   server.send(200, "text/plain", message);
}

void setup()
{
    Serial.begin(115200);
    while (!Serial)
    {
        ;
     }
camera_config_t camera_config;
camera_config.ledc_channel = LEDC_CHANNEL_0;
camera_config.ledc_timer = LEDC_TIMER_0;
camera_config.pin_d0 = 17;
camera_config.pin_d1 = 35;
camera_config.pin_d2 = 34;
camera_config.pin_d3 = 5;
camera_config.pin_d4 = 39;
camera_config.pin_d5 = 18;
camera_config.pin_d6 = 36;
camera_config.pin_d7 = 19;
camera_config.pin_xclk = 27;
camera_config.pin_pclk = 21;
camera_config.pin_vsync = 22;
camera_config.pin_href = 26;
camera_config.pin_sscb_sda = 25;
camera_config.pin_sscb_scl = 23;
camera_config.pin_reset = 15;
camera_config.xclk_freq_hz = 20000000;
camera_config.pixel_format = CAMERA_PF_JPEG;
camera_config.frame_size = CAMERA_FS_SVGA;

cam.init(camera_config);

WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
bool result = WiFi.softAP("TTGO-CAMERA", "12345678", 1, 0);
if (!result)
{
    Serial.println("AP Config failed.");
    return;
}
else
{
    Serial.println("AP Config Success.");
    Serial.print("AP MAC: ");
    Serial.println(WiFi.softAPmacAddress());
}

#ifdef ENABLE_OLED
display.init();
display.flipScreenVertically();
display.setFont(ArialMT_Plain_16);
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(128 / 2, 32 / 2, WiFi.softAPIP().toString());
display.display();
#endif

server.on("/", HTTP_GET, handle_jpg_stream);
server.on("/jpg", HTTP_GET, handle_jpg);
server.onNotFound(handleNotFound);
server.begin();
}

void loop()
{
    server.handleClient();
}

Sketch of receiver:
#include <WiFi.h>
#include "FS.h"
#include "SD.h"
#include "SPI.h"
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <Adafruit_ImageReader.h> // Image-reading functions
//#include <Adafruit_TFTLCD.h> // Hardware-specific library
#include <SPI.h>
#include "WiFi.h"
#include <JPEGDecoder.h>
//#include <FileIO.h>

// For the breakout, you can use any 2 or 3 pins
// These pins will also work for the 1.8" TFT shield
#define TFT_CS 16
#define TFT_RST 9  // you can also connect this to the Arduino reset
                  // in which case, set this #define pin to -1!
#define TFT_DC 17

// Option 2: use any pins but a little slower!
#define TFT_SCLK 5   // set these to be whatever pins you like!
#define TFT_MOSI 23   // set these to be whatever pins you like!
#define PIN_NUM_MISO 2
#define PIN_NUM_MOSI 15
#define PIN_NUM_CLK  14
#define PIN_NUM_CS   13

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK,     TFT_RST);

String text="";

const char* ssid     = "TTGO-CAMERA";
const char* password = "12345678";
const char* host     = "192.168.1.1";
const char* url      = "/";

IPAddress local_IP(192, 168, 1, 3);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8); //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional

//PImage logo;

#define BUFFPIXEL 20
  int      bmpWidth, bmpHeight;   // W+H in pixels
  uint8_t  bmpDepth;              // Bit depth (currently must be 24)
  uint32_t bmpImageoffset;        // Start of image data in file
  uint32_t rowSize;               // Not always = bmpWidth; may have     padding
  uint8_t  sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel)
  uint8_t  buffidx = sizeof(sdbuffer); // Current position in sdbuffer
  boolean  goodBmp = false;       // Set to true on valid header parse
  boolean  flip    = true;        // BMP is stored bottom-to-top
  int      w, h, row, col;
  uint8_t  r, g, b;               // pixel color for tft
  File     bmpFile; File     bmpFile1;
  uint32_t pos = 0, startTime ;
  uint8_t xx=0; uint16_t yy=0; int ww=0; int hh=0;
  int bmpfilepos;

//How to use -
//tft.fillScreen(ST7735_BLACK);
//testdrawtext(2,3,ST7735_GREEN,text);

void testdrawtext( int leftoffset , int topoffset , uint16_t color ,  String text ) {
  tft.setCursor(leftoffset, topoffset);  // (offset from left margin , offset from top margin. )
  tft.setTextColor(color);
  tft.setTextWrap(true);
  tft.setTextSize(1);
  tft.print(text  );
    }

void jpegbytesdisplay()
{
 // Create a buffer for the packet
    char dataBuff[240];

    delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  int cnt=0;

  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the cam server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");
  unsigned long timeout = millis();

  while (client.available() == 0)
  {
    if (millis() - timeout > 5000)
    {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

   int max_y=200;
   int ypos =200;
   int max_x=0 ;
   int xpos =0;

  // Read all the lines of the reply from server and print them to Serial

  ImageReturnCode stat;
  while (client.available())
  {
    //================================
   // String line = client.readStringUntil('\r');
   // Serial.print(line);

    //================================
    //bytes put into char[len] databuffer.
    size_t len=client.available();
    unsigned char buf[len];
    client.readBytes(buf, len);

    Serial.println("------------------------");
    Serial.println(len);
    //Serial.write(buf);

     //================================
     // bufffer to tft screen pixel rendering

      int col=0;
  int buffidx =0;
  cnt++;

    tft.fillScreen(ST7735_BLACK);
    tft.startWrite();
    tft.setAddrWindow(0, 0, 500, 500);

String fname="/image2" + String(cnt) + ".jpg";
File myFile = SD.open(fname, FILE_WRITE);
myFile.write(buf,len);
myFile.close();

     for (col=0; col<len; col++)
       {
          Serial.print(buf[col]);
       }
    Serial.println();
    Serial.println("------------------------");

      // For each pixel...
     for (col=0; col<len; col++)
     {
         if (buffidx >= sizeof(buf))
              {
          buffidx = 0; // Set index to beginning
                break;
        }

        b = buf[buffidx++]; //          [B]
        g = buf[buffidx++]; //     [G]
        r = buf[buffidx++]; //   [R]

        tft.pushColor(tft.color565(r,g,b));
                             // Display pixel on tft screen one after another.

   } // end pixel loop.

    //================================

   delay(1000);
    tft.endWrite();
  }

    }

 void setupNormal()
{

   Serial.begin(115200);

   // Use this initializer if you're using a 1.8" TFT
  tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab

  Serial.println("Initialized");

  if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("STA Failed to configure");
  }

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

  WiFi.begin(ssid, password);

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

  tft.fillScreen(ST7735_BLACK);

}

void setup()
{

    setupNormal();
    jpegbytesdisplay();

      }

void loop()
{

}

Here is what i found for JPEG image file display on any TFT -
i used JPEGDecoder library and instead of tft.pushColor , i used tft.drawPixel  method.
  for (int jj  =mcu_y;jj<mcu_y + win_h;jj++)
     {
        for (int ii=mcu_x;ii<mcu_x + win_w ;ii++)
        {
            // TFTscreen.drawPixel(ii,jj,tft.color565(255,0,0));
             TFTscreen.drawPixel(ii,jj,*pImg++ );
        }
     }

For BMP , we need rgb values to render each pixel on TFT screen.
But in case of JPG , first  we need to decode and create MCU tiles on TFT.
Then we paint those MCU tiles by color which we receive from JPEG stream decoder.
Here *pImg is the pointer which hold the color information.
As we increment *pImg++ array , each time we receive new color code of type uInt8_t type . Within MCU tiles , these color have to be injected .
Each MCU tile is colored and drawn in the given sequence by considering where the border line of TFT screen is.
It automatically create a JPEG image .
//////////////////////////////////////////////////////////////
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <Adafruit_ImageReader.h> // Image-reading functions

// For the breakout, you can use any 2 or 3 pins
// These pins will also work for the 1.8" TFT shield
#define TFT_CS 16
#define TFT_RST 9  // you can also connect this to the Arduino reset
                      // set these to be whatever pins you like!
// in which case, set this #define pin to -1!
#define TFT_DC 17

// Option 2: use any pins but a little slower!
#define TFT_SCLK 5   // set these to be whatever pins you like!
#define TFT_MOSI 23

Adafruit_ST7735 TFTscreen = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

//////////////////////////////////////////////////////////////

#include <JPEGDecoder.h>  // JPEG decoder library

//////////////////////////////////////////////////////////////
// include the necessary libraries
#include <SPI.h>
#include <SD.h>
//////////////////////////////////////////////////////////////

// pin definition for the Mega
#define sd_cs  53
#define lcd_cs 49
#define dc     48
#define rst    47

#define TFT_WHITE 0xFFFF
#define TFT_BLACK 0x0000
#define TFT_RED   0xF800

 //////////////////////////////////////////////////////////////

 #define PIN_NUM_MISO 2
#define PIN_NUM_MOSI 15
#define PIN_NUM_CLK  14
#define PIN_NUM_CS   13

  Adafruit_ImageReader reader;
    ///////////////////////////////////////////////////////

String text="";

// this function determines the minimum of two numbers
#define minimum(a,b)     (((a) < (b)) ? (a) : (b))

  //====================================================================================
    //   setup
    //====================================================================================

void setup() {
  // initialize the GLCD and show a message
  // asking the user to open the serial line
  //////////////////////////////////////////////////////////////////
   // Use this initializer if you're using a 1.8" TFT
  TFTscreen.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab
//////////////////////////////////////////////////////////////////

  TFTscreen.fillScreen(TFT_WHITE); // Alternative:

TFTscreen.background(255, 255, 255);

TFTscreen.setTextColor(TFT_RED); // Alternative: TFTscreen.stroke(0, 0, 255);
  TFTscreen.println();
  TFTscreen.println(F("Arduino TFT Jpeg Example"));

  TFTscreen.setTextColor(TFT_BLACK); // Alternative: TFTscreen.stroke(0, 0, 0);
  TFTscreen.println(F("Open serial monitor"));
  TFTscreen.println(F("to run the sketch"));

  // initialize the serial port: it will be used to
  // print some diagnostic info
  Serial.begin(115200);
  while (!Serial) {
    // wait for serial port to connect. Needed for native USB port only
  }

  // clear the GLCD screen before starting
//  TFTscreen.background(255, 255, 255);
  TFTscreen.fillScreen(TFT_WHITE);

  // try to access the SD card. If that fails (e.g.
  // no card present), the setup process will stop.
  Serial.print(F("Initializing SD card..."));

//////////////////////////////////////////////////////////////////

  SPI.begin(PIN_NUM_CLK, PIN_NUM_MISO, PIN_NUM_MOSI, PIN_NUM_CS);

  if (!SD.begin(PIN_NUM_CS)) {
    Serial.println(F("failed!"));
    while (1); // SD initialisation failed so wait here
  }
  Serial.println(F("OK!"));
//////////////////////////////////////////////////////////////////

  // initialize and clear the GLCD screen
 // TFTscreen.begin();
  TFTscreen.fillScreen(TFT_WHITE); // Alternative: TFTscreen.background(255, 255, 255);

  // now that the SD card can be accessed, check the
  // image file exists.
  if (SD.exists("/EagleEye.jpg")) {
    Serial.println("EagleEye.jpg found on SD card.");
  } else {
    Serial.println("EagleEye.jpg not found on SD card.");
    while (1); // Image file missing so stay here
  }

}

//====================================================================================
//   Main loop
//====================================================================================
void loop() {

  // open the image file
  File jpgFile = SD.open( "/EagleEye.jpg", FILE_READ);

  // initialise the decoder to give access to image information
  JpegDec.decodeSdFile(jpgFile);

  // print information about the image to the serial port
  jpegInfo();

  // render the image onto the screen at coordinate 0,0
  renderJPEG(0, 0);

  // wait a little bit before clearing the screen to random color and drawing again
  delay(4000);

  // clear screen
  TFTscreen.fillScreen(random(0xFFFF));  // Alternative: TFTscreen.background(255, 255, 255);
}

//====================================================================================
//   Print information about the image
//====================================================================================

void jpegInfo() {
  Serial.println(F("==============="));
  Serial.println(F("JPEG image info"));
  Serial.println(F("==============="));
  Serial.print(F(  "Width      :")); Serial.println(JpegDec.width);
  Serial.print(F(  "Height     :")); Serial.println(JpegDec.height);
  Serial.print(F(  "Components :")); Serial.println(JpegDec.comps);
  Serial.print(F(  "MCU / row  :")); Serial.println(JpegDec.MCUSPerRow);
  Serial.print(F(  "MCU / col  :")); Serial.println(JpegDec.MCUSPerCol);
  Serial.print(F(  "Scan type  :")); Serial.println(JpegDec.scanType);
  Serial.print(F(  "MCU width  :")); Serial.println(JpegDec.MCUWidth);
  Serial.print(F(  "MCU height :")); Serial.println(JpegDec.MCUHeight);
  Serial.println(F("==============="));
}

//====================================================================================
//   Decode and paint onto the TFT screen
//====================================================================================
void renderJPEG(int xpos, int ypos) {

  // retrieve infomration about the image
  uint16_t *pImg;
  uint16_t mcu_w = JpegDec.MCUWidth;
  uint16_t mcu_h = JpegDec.MCUHeight;
  uint32_t max_x = JpegDec.width;
  uint32_t max_y = JpegDec.height;

  // Jpeg images are draw as a set of image block (tiles) called Minimum Coding Units (MCUs)
  // Typically these MCUs are 16x16 pixel blocks
  // Determine the width and height of the right and bottom edge image blocks
  uint32_t min_w = minimum(mcu_w, max_x % mcu_w);
  uint32_t min_h = minimum(mcu_h, max_y % mcu_h);

  // save the current image block size
  uint32_t win_w = mcu_w;
  uint32_t win_h = mcu_h;

  // record the current time so we can measure how long it takes to draw an image
  uint32_t drawTime = millis();

  // save the coordinate of the right and bottom edges to assist image cropping
  // to the screen size
  max_x += xpos;
  max_y += ypos;

   char str[100];
  // read each MCU block until there are no more
  while ( JpegDec.read()) {

    // save a pointer to the image block
    pImg = JpegDec.pImage;

    // calculate where the image block should be drawn on the screen
    int mcu_x = JpegDec.MCUx * mcu_w + xpos;
    int mcu_y = JpegDec.MCUy * mcu_h + ypos;

    // check if the image block size needs to be changed for the right and bottom edges
    if (mcu_x + mcu_w <= max_x) win_w = mcu_w;
    else win_w = min_w;
    if (mcu_y + mcu_h <= max_y) win_h = mcu_h;
    else win_h = min_h;

    // calculate how many pixels must be drawn
    uint32_t mcu_pixels = win_w * win_h;

    // draw image block if it will fit on the screen
    if ( ( mcu_x + win_w) <= TFTscreen.width() && ( mcu_y + win_h) <= TFTscreen.height()) {
      // open a window onto the screen to paint the pixels into
      //TFTscreen.setAddrWindow(mcu_x, mcu_y, mcu_x + win_w - 1, mcu_y + win_h - 1);
      //TFTscreen.setAddrWindow(mcu_x, mcu_y, mcu_x + win_w - 1, mcu_y + win_h - 1);
      // push all the image block pixels to the screen

 ////////////////////////////////////////////////////////

 // while (mcu_pixels--)
 // {
 // TFTscreen.pushColor(*pImg++);
 // } // Send to TFT 16 bits at a time

 ////////////////////////////////////////////////////////

 //  Write all MCU pixels to the TFT window

  for (int jj=mcu_y;jj<mcu_y + win_h;jj++)
     {
        for (int ii=mcu_x;ii<mcu_x + win_w ;ii++)
        {
            // TFTscreen.drawPixel(ii,jj,tft.color565(255,0,0));
             TFTscreen.drawPixel(ii,jj,*pImg++ );
        }
     }

 ////////////////////////////////////////////////////////

    }

    // stop drawing blocks if the bottom of the screen has been reached
    // the abort function will close the file
    else if ( ( mcu_y + win_h) >= TFTscreen.height()) JpegDec.abort();

  }

  // calculate how long it took to draw the image
  drawTime = millis() - drawTime; // Calculate the time it took

 // print the results to the serial port
  Serial.print  ("Total render time was    : "); Serial.print(drawTime); Serial.println(" ms");
  Serial.println("=====================================");

}


text:
Arduino I2C Register Read
I am trying to read a specific register from a device. In this case I am trying to read the value stored in register 0X1F from slave device 0x08. On the scope I see writes for
ADDRESS_SLAVE(Wire.beginTransmission), ADDRESS_TESTCOMP0 (Wire.write)

and
ADDRESS_TESTCOMP0 (Wire.requestFrom(ADDRESS_TESTCOMP0,8))

but I don't see the register values reading out.  Here is my code:
#include <Wire.h>

int ADDRESS_SLAVE = 0X08;
int ADDRESS_TESTCOMP0 = 0X1F;

void setup()
{
 Wire.setClock(3400000);
 Wire.begin();
 Serial.begin(9600);
}

void loop()
{
   Wire.beginTransmission(byte(ADDRESS_SLAVE));
   Wire.write(byte(ADDRESS_TESTCOMP0));
   Wire.endTransmission(byte(ADDRESS_TESTCOMP0));

   Wire.requestFrom(ADDRESS_TESTCOMP0,8);
   char read = Wire.read();
   Serial.println(read);

   delay(1000);
}

please format your code  as code ..... select the code text and click {} ..... or just indent each line by 4 more spaces

maybe the arduino is "talking" too fast

Remove the Wire.setClock. The arduino mega 2560 can not do 3.4MHz. Only 100 kHz and perhaps 400 kHz with short wires. The Wire.endTransmission does not take data as a parameter, only a parameter for a stop condition. The Wire.requestFrom takes the slave address as a parameter, not the register address. The second parameter of the Wire.requestFrom is the number of bytes that you want, since you want just 1 byte, make that 1 and not 8. Which device is it? I hope not a device that runs at 3.3v. Start here: https://www.arduino.cc/en/reference/wire and read the reference pages of the functions.

Wire.begin sets default clock. the setClock line is not applied

Thank you for all the feedback. Code is still not accomplishing what I need it to and maybe I am going about it all wrong. Here is what I am trying to do:

I corrected set clock to 100K, eliminated the parameter in end transmission, corrected the request from parameter and set it to 1 byte....I am still not reading the register I am looking for. This is a 5 volt device. I've read the reference section on the wire library on the Arduino website exhaustively, which is why I am here now.

errors corrected
#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

void setup()
{
 Wire.begin();
 Wire.setClock(400000); // set I2C 'full-speed'
 Serial.begin(9600);
}

void loop()
{
   Wire.beginTransmission(ADDRESS_SLAVE);
   Wire.write(REGISTER_XY);  // set register for read
   Wire.endTransmission(false); // false to not release the line

   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH); // request bytes from register XY
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}

if you read only one register of the device, you can setup the device in setup() and in loop() only read the data from the register:
#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

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

  Wire.begin();
  Wire.setClock(400000); // set I2C 'full-speed'

  Wire.beginTransmission(ADDRESS_SLAVE);
  Wire.write(REGISTER_XY);  // set register for read
  Wire.endTransmission();
}

void loop() {
   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH);
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}

we don't know if the register address is 8-bit or 16-bit. Perhaps the slave is a microcontroller and needs a delay. The Wire.read does not take parameters, it reads a single byte. You were thinking about Wire.readBytes? We don't know how long the wires are and we don't know what the slave device is or how it behaves.

@Juraj Wow...thank you very much Juraj! That works! It seems like I was pretty far off the mark with what I was trying to do. Do you know of an available reference I can use for these types of problems i.e. text/book?


text:
Doubt with the library esp8266wifi and Station Mode
I have been working for a while with the ESP8266 I have a question:
According to the online documentation of GitHub from the esp8266wifi library I can initialize the WiFi in Station mode to (obviously) connect to a nearby AP, I can initialize the station mode in 3 "different ways":

WiFi.begin (): The module initializes the Station mode and connects to the last network that is connected, because the credentials (SSID and Password) are stored in its internal memory (flash?).
WiFi.begin (ssid, password): The module initializes the Station mode and connects to the network with "ssid" and "password".
WiFi.begin (ssid, password, channel, bssid, connect): The same as the previous one, only that you pass more parameters: the one that interests me is the bssid, which is the MAC address of the AP to which I am going to connect.

Now comes the question: if I wanted to use the last mode, because I want to make sure that the ESP connects ONLY to an AP (a kind of MAC filtering), I also have to specify the channel and set the connect parameter? Or I can simply use something like this:
WiFi.begin ("MyOwnNetwork", "123456789", "00: 1B: 44: 11: 3A: B7")

I can not prove it right now, I do not have the module in my hands.

type of parameter bssid is  const uint8_t* (byte array)

the configuration is saved to flash https://media.readthedocs.org/pdf/arduino-esp8266/docs_to_readthedocs/arduino-esp8266.pdf

the configuration is saved including the bssid

What do you mean with: "type of parameter bssid is const uint8_t* (byte array)", the way I wrote the sentence is wrong? Could you give some example? Thanks!

anything inside quote marks "" is a string .... google c++ byte array ... https://stackoverflow.com/questions/2240405/byte-array-assignment

This is the function prototype:

Per C++ rules, in order to supply an argument for bssid, you have to pass an argument for channel as well, but connect is optional since it's positioned after your target argument. This should not be a problem though since you can just pass the default value of channel (i.e. 0) into the function; the channel argument is only relevant if you enter a value between 1 and 13 inclusive.
So your call should basically look like:
char ssid[] = "ssid";
char pwd[] = "pwd";
uint8_t bssid[] = {0x00, 0x1b, 0x44, 0x11, 0x3a, 0xb7};
WiFi.begin(ssid, pwd, 0, bssid);

Great answer!!! Just the one I was looking for!!! Thanks!!!!!

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


text:
Not getting pure color while using the FastLED with WS2812b
I am working with the LED strip WS2812b and FastLED library, currently I have only 3 LEDs connected in such a way that the first 2 receive a color (say green) and the last one receives another one (say blue).
The problem is that by putting the color (blue) on the last LED, the other two (currently only in green) also take a portion of blue, preventing it from being a pure (green) color. It happens with any combination of color.
I leave the piece of my code referring to the LED strip:
#include "FastLED.h"
#define NUM_LEDS 3
#define DATA_PIN 2

//Variables declaration...
....

void setup() {
  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
.....

  }

void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
      if (digitalRead(pinNo+3) == HIGH){
        leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
           FastLED.show();
            }
        }

  }

I already change the pin for where I put the signal for the LED strip, I try to change the type of LED strip

FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS)
FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS)
FastLED.addLeds<WS2812, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS)

without any success...
Can anyone point me in the rigth direction?
Edit: actually, the first LED of the strip is flashing, not in the way of the Blinking example, but I can see a little flashing.

Hey @gre_gor, how can I put lists when I'm asking?

https://arduino.stackexchange.com/editing-help

I can see what the problem is, I put FastLED.show(); where it should not, that's also why I saw the flash ... fix it and here's the result:
void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
    if (digitalRead(pinNo+3) == HIGH){
      leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
    }
  }

  FastLED.show(); //NOW IS IN THE RIGHT POSITION
}


text:
Nano v3 dual power source use & detection
I would like to run a Nano 3.0 from both the VIN (mains power supply 7V) and USB power (backup). I understand it selects the highest voltage and switches to VIN at 6.6V. However I am unsure of the following:

How is it possible to detect which power source is being used?
How is it possible to detect if the source has been switched?
How is it possible to detect if the power source NOT in use has been disconnected.

Could you not take a line of each of the inputs and (after suitable level shifting) test them using two of the digital pins?

To check, if VIN is connected, you can connect VIN through a voltage divider to a digital pin (as suggested in the comment of Code Gorilla). For checking the USB connection you would have to connect VUSB to another digital pin. Since VUSB is not exposed on a pin, this could be difficult to do, but it is possible.
But note, that this would also show a disconnect, when the voltage drops (e.g. empty battery). When you want to detect real mechanical disconnects, you need a power jack with an extra switch integrated.
Let's take a look at the schematics: Arduino Nano 3.0 Schematics

The selection of voltage supply is done by the diode D1. If the voltage resultung from the VIN regulator is higher than VUSB - diode_voltage_drop, the diode is closing and the power comes from VIN. If the voltage resulting from VIN is lesser, the current can flow from VUSB. How much power is really drawn from USB depends on the voltage difference.
So - to detect which source is actually used - you can measure the voltage on the diode with an analog measurement with the ADC or through connecting for example a comparator and using a digital pin.
Note that the voltage on the diode can be positive or negative, depending on which source is used.


text:
Convert Arduino Pro Mini 5v to use 3.3v
Id like to make my 5v pro mini use 3.3 v instead of 5 because i want to use it in an existing piece of electronics that uses 3v throughout.
Looking at the specs for the pro mini it says the 3.3v version can accept higher voltages.
So is there a regulator i can bypass/bridge that will convert my 5v version to a 3.3v version? or am i wasting my time?

Replace U2 with the 3.3V version.

And Q1 with 12mHz (or less) crystal.

Just use 3 diodes in series one diode reduces in 0.7 volts.
5v----->|----->|------->|------- = 2,9volts

I have good news, and I have bad news.
The good news is that only two changes to the board are required to change it from a 5V board to a 3.3V (or any voltage within spec) board.
The bad news is that there's no way in hell you'll be able to do them.
So, we work around them and get the board up and running.
The first is obvious: a 3.3V board should be running off of 3.3V. Since we can't replace the SOT23-5 regulator on the board (the little 5-pin device towards the end) we need a voltage regulator to supply this, directly to the VCC pin. Find yourself a linear or switching regulator that provides this voltage.
The second is that the microcontroller, an Atmel ATmega168/P, is not specced to run at 16MHz when the supply voltage is only 3.3V; the maximum speed is 12MHz. Since we can't replace the crystal on the board (the little silver package next to the MCU itself) we need to perform some trickery to tell the MCU divide the frequency down to something way below safe, and then boost it up after. Use a programmer (see some of my other answers for more info about this) to set the CKDIV8 fuse and then use the routines in avr/power.h in your code to "reduce" the divisor to 2, bringing the clock speed back up to 8MHz. While you're at it, check the BOD fuses to make sure they're not set to something useless like 0b100.
As always, see the datasheet.

wow great. thanks. i may attempt this, but it sounds like it would be easier for me to just get another (3.3v) pro board. theyre cheap and i can use the 5v version some other time.

I'm curious: Why is there no way in hell the OP will be able to do this? It sounds like the 3V3 supply won't be an issue (“because i want to use it in an existing piece of electronics that uses 3v throughout”). Is setting the fuses properly much more difficult than setting up an ArduinoISP and telling your Arduino IDE to write a bootloader for that configuration?

@ChristopherCreutzig: The changes described can be performed by replacing two components on the board. However, even if one had the equipment and skill to replace them it would be a difficult task due to the density of the board. Replacement by someone that doesn't know what's required in the first place? Not happening.

See this nice article by Adafruit, which explains how to run an Arduino Uno at 16Mhz with 3.3v. Both the Arduino Pro Mini and the Uno use the same ATmega328p chip, and they claim that even though running at 16Mhz is out of specs, it should work.
As Ignacio mentioned in his answer, there will be no alternative to downclocking the Mini Pro if you want to play it safe and stay within the specs. If you are willing to take the chance, remove the 5v regulator as suggested, and connect a regulated 3.3v to Vin. Consider the hazards; they might include device resets, misbehaving code or malfunctioning I/O pins.
If you are using an unregulated 3v voltage source, you will need to step up the voltage - using DC DC step up converter such as this one. (By the way - you could also find a step up converter to 5v - hence problem solved...)
In addition, see this SO answer for more details. The safe clock speed for the ATmega328p operating at 3.3v would be 13.33Mhz. For reference, here is the Safe Operating Area graph from the datasheet supplied in the answer:

Again thanks for sharing your knowledge. I may try the step up idea.


text:
How to build an arduino project with multiple source files?
I'm building an arduino program on linux, using the following Makefile:
ARDUINO_DIR = /usr/share/arduino
BOARD_TAG = uno
ARDUINO_PORT = /dev/ttyAMA0
ARDUINO_LIBS = Wire
include /usr/share/arduino/Arduino.mk

Currently all of my code is spread among a dozen header files and a single .ino file - it gets compiled and it runs properly when flashed. I know that's not correct though and I'm trying to split my code into the proper structure of source and header files but when I do and try to build it I get the following output:
In file included from gear.c:1:0:
gear.h:19:1: error: unknown type name ‘byte’
 byte GEAR = 3;
 ^

Which leads me to believe that the source file is getting compiled separately and does not know what a byte is, which is supposedly defined somewhere within the arduino library.
What's the proper way to build my project with source files?

avrdude is an uploader/downloader ... it does not do any building

@jsotola I'm sorry, my mistake.

There is a byte datatype in C, its called char. for flipping bits in ardunio you could use bitSet, which allows you to change values of bits in a datatype. https://www.arduino.cc/reference/en/language/functions/bits-and-bytes/bitset/
not really sure what exactly your doing.

First of all, I recommend you write in C++ (file extension .cpp) rather
than in plain C (files in .c). The reason is that the Arduino
programming environment is based on C++, some of the libraries are
C++-only, and your main .ino file will be compiled as C++ source. Mixing
this with C is possible, using some extern "C" declarations, but it is
probably more hassle that it's worth.
Now, to answer your actual question, just add thsi near the top of your
source files:
#include <Arduino.h>

This includes the type definitions specific to the Arduino environment,
together with the core API. This include is added automatically to any
file ending in .ino, but you have to add it explicitly to your .cpp
files.

Mixing this with C is possible, using some extern "C" declarations, but it is probably more hassle that it's worth. Are you talking about having to prefix all variable definitions with extern? Even by renaming the file to .cpp I still had to add that or I would get errors that variables were not declared. There's a high probability I'm doing something wrong though, have literally 0 practical experience with C/C++

@php_nub_qq: No, I am not talking about extern. My point is that you cannot access C++ objects (e.g. Serial) from C, and accessing C functions from C++ requires extern "C" declarations.

Well for now it seems to work fine with the Wire library. Thanks for mentioning though, if I come across it I'll know what to look up and not waste 3 hours.


text:
How to include a file from another (parent) directory
This is my structure
program/
  src/
    Makefile
    main.ino
    test.h
    ...
  lib/
    i2c.h

In main.ino I include test.h and in test.h I'm trying to include i2c.h but it is just not working, I keep getting:
make: *** No rule to make target 'i2c.h', needed by 'build-uno/main.ino.o'.  Stop.

I tried including like this
// test.h
#include "../lib/i2c.h"

I also tried making a symlink to my lib folder in arduino libraries and adding it as a library in Makefile
sudo ln -s /home/pi/program/lib /usr/share/arduino/libraries/GAVR
# Makefile
ARDUINO_DIR = /usr/share/arduino
BOARD_TAG = uno
ARDUINO_PORT = /dev/ttyAMA0
ARDUINO_LIBS = GAVR
include /usr/share/arduino/Arduino.mk

I also tried making a symlink to lib inside the src directory
ln -s /home/pi/program/lib /home/pi/program/src/lib
None of the above had any effect, the error message stays the same.
How can I include a file from another directory in my program?

It's a make error not compilation error. If you have rule, for main.ino, where is that i2c.h listed as dependency and it's not in the same directory, it'll fail. Depends on Makefile directory it might be ../lib/i2c.h (or you can ommit this dependency, but if it changes, it won't get recompiled)

@KIIV I'm still quite new to c and I don't really know what I'm doing. My Makefile is in the src directory and I have posted the contents of it. I'm not aware how I must specify the lib directory as part of the build process. I found many examples that suggest adding -I to gcc but the arduino makefile does magic and I don't know how to add parameters to the compiler command.

I was using platformio (as there was no command line interface back then). 1. libraries are usually in it's own subdirectory, so it might need something like lib/i2c_lib/i2c.h and ARDUINO_LIBS=/home/pi/program/lib

If you don't know what you're doing with a Makefile (and Makefiles are black magic) then you really shouldn't be using one. If you must use the command line then use ardiuno-cli instead. Also be aware that building is not normally done in the source directory but in a separate build directory elsewhere.

@Majenko there are probably a lot of things I'm doing wrong, but all I care about is my program to work as I expect, everything else is noise. It's a hobby project on which I'm working alone so nobody is going to suffer from my ignorance and I'll likely never do any professional work with C, so it's fine. Guess I'll follow the advice if I can't figure out a way to make the Makefile work.

You may suffer the same problem with arduino-cli because of how Arduino building is done - not in the source directory. You will have to work out what the build directory's path is relative to where your file is. If you are using a proper library, though, then arduino-cli will know that and handle it all for you.

@Majenko I seem to have found a solution, following the symlink to /usr/share/arduino/libraries/GAVR I just had to create a GAVR.h file which includes my other files. That would probably make a proper C programmer cringe but it works for me, so I'm not sure whether I should put it as an answer or delete the question altogether.

Put it as an answer. It may help someone. And hey, if it works it works. In C there is more opinion than right and wrong.

This is definitely on the hacky side and not a proper solution to the problem, but it works nevertheless so I'm sharing it.
After making a symlink in the /usr/share/arduino/libraries directory you must make sure that there is a header file with the exact name of the directory, apparently that's how arduino is set up to include them.
In my case my symlink was named GAVR, so I had to create a GAVR.h file inside my lib directory, which would then go ahead and include my i2c.h file and possibly any other file that I'd need.
Also in test.h or anywhere I need to use i2c.h I must include <GAVR.h> instead.
Turns out Also 1 is false, you just need to include <GAVR.h> once in the .ino file and its members will be available everywhere, just like any other library.
Also 2, now that ARDUINO_LIBS is not empty in the Makefile you will need to manually declare all libraries that your code is using.


text:
How to compile without adding the bootloader?
I'm using a standalone atmega328p with a 16MHz crystal.
I'm programming it via avrdude on a raspberry pi, using the SPI and RESET pins.
When I compile my program, this is what I see at the end of the output:
----------------
Device: atmega328p

Program:    4152 bytes (12.7% Full)
(.text + .data + .bootloader)

Data:        253 bytes (12.4% Full)
(.data + .bss + .noinit)

As far as I understand, the bootloader is used to program the chip via UART, which I do not need(?). I'm assuming that the bootloader is still being compiled because of the output above containing .bootloader in the program part.
My program is compiled using the arduino SDK, with the following Makefile
ARDUINO_DIR = /usr/share/arduino
BOARD_TAG = uno

include /usr/share/arduino/Arduino.mk

I went through Arduino.mk and found this on line 1626:
ifndef AVRDUDE_ISP_BURN_BOOTLOADER
    ifneq ($(strip $(BOOTLOADER_FILE)),)
        AVRDUDE_ISP_BURN_BOOTLOADER += -U flash:w:$(BOOTLOADER_PARENT)/$(BOOTLOADER_PATH)/$(BOOTLOADER_FILE):i
    endif
endif

Which supposedly provides an option to turn off adding the bootloader but I couldn't figure out how to use it, so I just commented the line out:
ifndef AVRDUDE_ISP_BURN_BOOTLOADER
    ifneq ($(strip $(BOOTLOADER_FILE)),)
        # AVRDUDE_ISP_BURN_BOOTLOADER += -U flash:w:$(BOOTLOADER_PARENT)/$(BOOTLOADER_PATH)/$(BOOTLOADER_FILE):i
    endif
endif

But still, after compiling i see the .bootloader part and the program size remains the same.
Is it possible to tell it to skip adding the bootloader?
And yes, this is completely unnecessary for my application, I just want it, I want it bad.

Seeing .bootloader section in size output doesn't mean it's really present. It just means the sum of all three is 4152 bytes.
You can check the hex file if it contains large block of data at the bootloader address space. The main program starts at the lower adresses and then there should be big gap and at the end bigger chunk of data with adresses in bootloader section (but only if you really have a bootloader).
But unless you program also BOOTRST fuse, it won't start in bootloader anyway.
Usage of AVRDUDE_ISP_BURN_BOOTLOADER is normal environment variable (can be also set inside of Makefile) and as it's tested for not being present so you can just check if it's not being set somewhere in Makefile

Is there any tool that allows for easier preview of the whole address space?

I found this question which shows that the bootloader's address space is 7800 to 7FF0. I also confirmed that by taking a look at atmega328p's bootloader hex file stored in /usr/share/arduino/hardware/arduino/bootloaders/atmega/ATmegaBOOT_168_atmega328.hex and indeed the first line is this:
:107800000C94343C0C94513C0C94513C0C94513CE1

Hex file format explained here.
So I then went back to my compiled hex file and checked whether there's anything at this address and there wasn't.
So apparently my program does not contain the bootloader.
I'm adding this as a separate answer with all the details because it took me some time to figure it out after reading KIIV's answer, credit goes to him.

I strongly doubt the compiler adds the bootloader. What that message is probably trying to tell you is that the bootloader is being included in its assumed address space.
There are various bootloaders, Optiboot is only 512 bytes. If you are programming directly (not via a bootloader) then the bootloader isn't required, of course.
If you program via SPI and set the BOOTRST flag appropriately then the processor will boot directly into your code which will save a small amount of time as the bootloader waits to see if there is any serial input for reprogramming. Plus, you get another 512 bytes for your code.
In your case, it hardly matters as the reported 4152 bytes is way short of 32 KB.


text:
How much ohm resistance I should put between tp120 base and uno?
I have set up solenoid on of based on soil moisture,
The solenoid is powered by 24 volts, so I power solenoid by 24 volt and Arduino uno by stepping down to 6 volt powering through Vin and gnd.
I have used resistance of 10k ohm but I have twice burnt em.
Not sure how should calculate resistance required of signal coming out from D6 pin to TP120 base !

Is the 24 V a DC or an AC voltage?  Can you draw a circuit diagram to clarify the connections?  [Click the Circuit icon on the edit-box toolbar, if you don't have a schematics program to use] Note, edit the question in reply

24 volt dc, I have added Fritzing

Your diagram shows nothing connected to one end of the diode - is that an omission? What have you burnt twice? The resistor?

sorry fixed the fritzing, yea I am talking about resistor.

1-2.2k comes up in a web search

Are you absolutely certain the circuit is connected as shown? I can imagine it not working if you've got the wrong value resistor, but I can't see any way you'd burn the resistor up and not kill the Ardino as well. Have you perhaps got a short from one pin of the resistor to somewhere it shouldn't be?

To calculate you need to know the maximum current the solenoid uses. The TP120 has a gain of around 500-1000. So the current going into the base needs to be 1/500th of the current going through the solenoid.
So now you know the current needed. Then you can calculate the resistance value you need with R = V/I. So R = 5 / ( <solenoidcurrent> / 500 ).
So with e.g. a 2A solenoid, you get a value of 1.2kOhm.


text:
Should I use LLC to power sensors on grid pcb at 4mtr wire length distance?
I have setup a grid pcb that further distributes power and receive signal from sensors, I know low voltage can detroit if not damage sensors , so I am thinking to put BD-LLC  to distribute power output to 6 sensors connected to PCB shown below.
[ignore 24 volt power that feeds solenoid it is separate and comes from power adapter not from mega though the wire has same red colour] the 5 volt wire connecting to main connector from other connector is not visible.

And I have Arduino Mega from which I am drawing power 5 volt (using digital multimeter I found it's 4.98 volt). And all sensors are connected to this 5volt parallely.
So the question is should I put this BD-LLC on above PCB to distribute correct power output to sensors ?

A logic level converter has nothing to do with power conversion. To answer your real question though there are two more pieces of information that are needed: the current draw of your board, and the gauge of your 4m long power and ground wires.

4m long wire adds 2.79 to 3ohm resistance, the board is on 6.98 voltage input from VIN pin of step down from 24 volt

The voltage at the board end will depend on the current draw of the board, and if that varies then the voltage will vary. You may be better off using a 24V -> 5V step-down at the board and providing 24V to the board instead (known as "point of load regulation") to ensure the board runs at 5V.

In that case I would have to send back 5 volt to VIN  of Arduino mega

Why would you want to? The Arduino is already 5V.

Because from that 24 volt I am feeding both

You aren't making sense. You have 24V->7v->5v and one end, and tee off the 24V to give 24V->5V at the other end. The only power you send down the wire is 24V, and since you are (or should be) using "buck" regulators for this the current draw down the wire will be less, so the wire losses will be less. As long as the two devices share ground it doesn't really matter where the power comes from, as long as both boards run at 5V, not one at 5V and one at "somewhere up to 7V".

Actually you do make sense to put buck converter at the pcb end however my earlier setup used POE so where the 24 volt adapter is connected is also where router is lying inside room, while pcb is lying out in corridor, I can take power in from outside and send 5 volt to mega from PCB. Little bit of more work I would have to do but my original question to boost power for sensors to get exact 5 volt is still not answered

Sending 5V from the board to the Arduino is going to still suffer from the same problem. You will end up with a random voltage at the Arduino due to wire losses dependent on the current draw of the Arduino at any one time.

@Majenko  AFAIK Arduino mega requires 6volt -20volt

The VIN requires minimum 6.2V for linear regulation down to 5V. If you send 5V from board to Arduino it will go into the 5V pin not the VIN pin (which will be connected to nothing). But that 5V will be below 5V because of wire losses.

So do u mean to say I can power mega from 5volt pin as well instead of VIN? I have never tried that!

Transmitting power over longer distances requires careful consideration. The actual voltage you will get at the remote end depends on two major factors:

The resistance of the wire, and
The current draw of the remote device

If you regulate your 24V incoming power down to 7V for the Arduino and then send the Arduino's 5V over 4m of wire to power your remote board the actual voltage the board will receive depends on the amount of current the board draws.
If this current is tiny then the voltage drop for the wire will be small and can largely be ignored. For instance, you quote about 3Ω resistance for 4m of wire, which to me seems incredibly high (32AWG which is like hair thin is only ~0.5Ω/m), but anyway.  If your board draws 100mA, over your 4m wire, which is actually 8m when you take into account the length of the ground wire ("There and back again - an electron's tale.") you would drop (2*3Ω)*0.1 = 6*0.1 = 0.6V, so your 5V would turn to 4.4V by the time your board sees it. Not only that but the ground wire would be offset at the board end by 0.2V, which may impact LOW logic level detection.
So ideally you need to both minimise and mitigate that voltage drop. And both can be done using a buck regulator at the board and powering it from the 24V supply instead of 5V.
By using a buck regulator you massively reduce the current over the wire (for 24V to 5V you could be looking at around a quarter of the current or even less, depending on the efficiency of the regulator) which reduces the voltage drop on both the power and ground wires. It also guarantees that the board runs at 5V regardless of the current draw of the board.
Here's a diagram:

For digital sensors this loss of voltage could cause damage if any incoming logic signals are above the absolute maximum for the sensor (which is usually a function of the supply voltage, say Vcc + 0.3V). For analog sensors it will affect the values you are reading, since the voltage emitted from the sensor is often a function of the supply voltage, and if that is not what you expect it to be your calculations from the ADC values will be incorrect.

To answer your original question "can I use a LLC to distribute power" the answer is "no". The LLC can allow you to interface logic signals between two different voltage levels, but not affect power at all. And further more it requires that you have both voltages availabe for the LLC to operate, and you don't have both voltages, you only have the 5V minus the wire's voltage drop available, so you can't use it to mitigate any offset in the logic levels either.

How do I figure out current draw at remote device(pcb sensor grid) in my case? Do you mean sum up power of all sensors connected to grid?

Sum up the current requirements for all the sensors. You can usually find that kind of information in the datasheet for the sensor.

I do have to step down converter but it does really bothers me

What bothers you about it? The colour?

Baaah u still there, I meant having to put another step down converter

Why does that bother you? It's the normal thing to do.


text:
Why do I have to open Serial Monitor to display what is in loop function?
Why do I have to open Serial Monitor to display non-NaN values retrieved from DHT22,
what am I doing wrong in the code below?
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
// OLED display TWI address
#define OLED_ADDR   0x3C
// reset pin not used on 4-pin OLED module
Adafruit_SSD1306 display(-1);  // -1 = no reset pin
// 128 x 64 pixel display
#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
#define DHTPIN D3
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {

Serial.begin(115200);
delay(100);
  dht.begin();
  pinMode (DHTPIN, OUTPUT);
  /// initialize and clear display
  display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR);
  display.clearDisplay();
  //  display.drawRect(1, 1, display.width()-1, display.height()-1, WHITE);   // draws the outer rectangular boundary on the screen
  display.display();
  // display a pixel in each corner of the screen
  display.drawPixel(0, 0, WHITE);
  display.drawPixel(127, 0, WHITE);
  display.drawPixel(0, 63, WHITE);
  display.drawPixel(127, 63, WHITE);
  // display a line of text
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(20, 18);
  display.print("Welcome");
  display.setCursor(25, 40);
  display.print("San");

  // update display with all of the above graphics
  display.display();
}
void loop() {
  // put your main code here, to run repeatedly:
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 1);
  display.print("Showing Temperature");
  // display Temperature
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(1, 18);
  display.print("T : ");
  display.print(t);
  display.setTextSize(1);
  display.print((char)247);
  display.setTextSize(2);
  display.print("C");
  display.setCursor(1, 40);
  display.print("H : ");
  display.print(h);
  display.print(" %");
  // update display with all of the above graphics
  display.display();
}

After uploading code it does will display NaN but when I open serial monitor it works fine displaying actual values from DHT22  :o
below is the fritzing of the hookup, I do not have witty cloud in fritzing, so I have used wemos D1Mini instead. on wemos d1 mini 3v3 is VCC on witty cloud dev board.

It looks like loop function doesn't execute by itself unless I open the serial monitor, why is it so? please help

What happens if you remove/comment out "Serial.begin(115200);"?

Please show your wiring schematic. Do you use pull-up resistors for RX and TX?

Also asked at: http://forum.arduino.cc/index.php?topic=512284 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

if i do not have serial monitor open loop function doesnt work. if I have serial monitor open the OLED updates, if i close serial monitor window the text on doest updates from the loop function.
why is loop function  dependent on serial monitor window being open ?

@MikaelPatel I have tried commenting that too didnt help, long time back I had similar issue and commented the serial.begin and it worked but with witty cloud dev board it didnt.

@AltAir I have added fritzing. please have a look

@per1234 I tried and troubleshooted to fix the issue but couldn't before posting on SO or arduino forum, I wanted to get the message to larger community so I can get some help.

The missing connection between GND of the D1 mini and breadboard.

Hard to tell from your fritzing which actual ESP8266 pin you are using, but you require a pull up resistor on the data line of the DHT22.
My guess is that you are using one of the serial UART pins for the data connection, and opening the serial monitor activates the output of the onboard UART chip which then acts as your missing pullup resistor.

Used D7 i.e. GPIO13 on witty cloud.

Serial monitor sends a RESET signal during its initialization - maybe this is the problem. Sometimes these Witty boards need an implicit RESET after power up / programming.


text:
Call by reference
I am trying to learn 'call by reference'. I want to call a function fcn1 from the main loop and pass a reference of the local variable var to the function fcn1. Next step is to call a second function fcn2 from the function fcn1 and pass again the reference of the local loop variable var. I always get this error massage:
invalid conversion from 'int' to 'int*' [-fpermissive]

Here a small example code:
void fcn1(int *variable)
{
  fcn2(&variable);
}

void fcn2(int *variable)
{
  //do something with the variable
}

void setup()
{

}

void loop()
{
  int var = 1000;
  fcn1(&var);
}

I tried to solve that issue by using:
void fcn1(int *variable)
{
  fcn2(*variable);
}

But it's the same error.
By deleting the * respectively & it works fine, but is it still a reference?

Thanks a lot! If I interpret your answer and the link correctly, the following code works only with references, right? void fcn1(int &variable) { variable++; fcn2(variable); } void fcn2(int &variable) { Serial.println(variable); } void setup() { Serial.begin(9600); } void loop() { static int var = 1000; fcn1(var); delay(1000); } Many thanks!

Yes, however, it will not compile that way .. int & variable denotes a pointer, to increase it, you should use variable++.

void fcn1(int *variable)
{
  fcn2(*variable);
}

This function takes a pointer to an integer as parameter, and then passes the value of the integer to the second function.
To do it by reference, use an ampersand (&, not to be confused with the address-of operator).
void fcn1(int &variable) {
  // Do something to variable
}

For example:
void increment(int &variable) { // Reference to an integer
  variable++;
}
void setup() {
  Serial.begin(115200);
  int a = 1;
  Serial.println(a); // 1
  increment(a);
  Serial.println(a); // 2
}
void loop() {}

You could achieve the same thing using pointers, but using references is much cleaner and easier to read.
void increment(int *variable) { // Pointer to an integer
  ++*variable; // dereference first, then increment value
}
void setup() {
  Serial.begin(115200);
  int a = 1;
  Serial.println(a); // 1
  increment(&a); // address of a
  Serial.println(a); // 2
}
void loop() {}

Please note: this question is not specific to Arduino, it is just C++. For questions like this, it is best to google for 'C++ pass by reference' instead of 'Arduino pass by reference'.