text:
Activating a Relay with Wemos D1
I have a problem similar to these questions:
Wemos D1 doesnt drive Relay
Wemos D1 is not triggering Relay
I got this BC548B transistor from an old apparatus I scratched. The transistor saturation voltage is 0.6V  according to the datasheet:
https://alltransistors.com/pdfdatasheet_fairchild_semi/bc548_bc548a_bc548b_bc548c.pdf
When I set up my circuit the wemos d1 inboard leds dim and the board resets so I guess something is going really wrong. Can someone advise if my design makes sense?

UPDATE
I replaced the 12V relay with a 5V one but still can't get it to work. Basically, the 3.3V signal seems to be too low to activate the solenoid. How can I raise the 3V3 signal to 5V? What was wrong with my idea of using a transistor to do it?

so the relay doesn"t activate with 3.3 V as HIGH?

It makes no sense. Is that really the relay you are using? It has a transistor on there already. And did you see the voltage of the relay...?

@majenko 1. Yes, that's the relay, It looks like I need 12V to feed it. In the other hand, if I feed with 5V and the control signal is 5V it works,I have tested it so I though if I can use the 3.3V signal to control the transistor, it should saturate with that voltage and work as a switch for the 5V signal I need.

Without knowing the schematic of the relay we cannot predict what is going on. I would suggest that you don't want a transistor at all - just directly drive the IN pin.

That appears to be a 12 "solid state" relay. That means that it is designed to be both powered by and switched by 12V. You're trying to drive it with slightly more than 1/3 of its rated voltage. Don't do that.
Edit:
Note that none of the relays being discussed are true solid state relays. These are are all conventional coil relays that include cicuitry that allows them to be driven by CMOS logic signals. A true solid state relay does not have any moving parts, but uses solid state components to do the job of a relay. Those cost significantly more money however.)

It might be that you can get away with driving a 5V solid state relay with 3.3V, or 12V relay with 5V, but you shouldn't do those things either.
Also note that even if you are using the correct relay, your relay almost certainly takes more current than the 5V pin on an Arduino can provide (When driven from USB, the entire system is limited to 500 mA, including the power needed to the Arduino.)
Edit:
These solid state relays come in 12V, 5V, and 3V flavors. Get a 3V one: https://www.adafruit.com/product/3191?gclid=EAIaIQobChMIyY_dxM344gIVELbICh1ufwivEAQYBSABEgI3wPD_BwE

This answer is so wrong. This is not a SSR. And there is 5VDC on it. And the relay on link is not SSR either.

this is a SSR module https://www.seeedstudio.com/Grove-Solid-State-Relay-V2-p-3128.html

Vendors use the term solid state relay when they really shouldn't. It's a relay module with circuitry that enables you to switch it with low current logic level signals. I was being lazy by using that term, and should not have.

i added a note to point out that these are not really solid state relays. (And the relay I link to is a 3V relay. Look at the picture.)


text:
Which sources of randomness are available?
I need a souce of randomness to generate a seed to pass to randomSeed. Where can I get this randomness from?
Well, I hear I can read random noise from an unconnected pin.
But I need to connect 9 LEDs and 9 buttons to the board. There seem to be enough pins for this purpose: digital pins 2-13 + analog pins 0-5 makes a total of 18 pins. But does this leave any free pin for a source of randomness?
There are digital pins 0 and 1 left free but I'm reading these should be left free if the board's USB socket is connected and I'm planning to power the whole device by connecting it to a computer through USB. Does this mean I'm supposed to just left pins 0 and 1 unconnected or is it also forbidden to read noise from them?
Or are there any other available sources of randomness? Can I use any other pins for this purpose?
I remember when I was showing this project to the instructor I specifically asked if I have enough pins, noting that I need a source of randomness in addition to 9 LEDs and 9 buttons. He said there are enough pins. Only sadly I forgot to ask how can I read random noise then...
What are my options to somehow obtain a random seed?

i would use the timing of your button presses to mix the internal seed state.

@dandavis sadly I need to generate random numbers BEFORE the user is supposed to press any buttons.

you should use EEPROM to store the seed so that you eliminate the "no ent on boot" problem inherent in PRNGs. Readup on the fortuna algo on wiki for more info. You don't need to go THAT fancy, but applying some of the principles will solve your issue. You can also set the pins as analog inputs right away, scan them a few times, then set them back up as your device needs to run. You won't get a whole lot, but every bit (literally) counts.

@dandavis Oh my... I definitely don't need cryptographical security :)

here is an interesting video https://m.youtube.com/watch?v=1cUUfMeOijg

I get why this was closed as a duplicate, but you can also free up a good number of pins by using a shift register to control 8 of your LEDSs. https://learn.sparkfun.com/tutorials/shift-registers/all

Whether you need a source of random noise depends on whether your project needs to not run repeatably. Most experiments - Monte-Carlo simulations, for example, benefit by being able to be re-run. In those cases, you need to be able to re-use the seed, and having an non-reproducible seed (and thus, experiment) is a disadvantage.
If you really need something that runs differently each time you run it, then a seed derived from user reaction time, or from some kind of electrical noise, even reading analog values from a floating input pin, should give you plenty of non-reproducibility.

brilliant: get the seeds from the environment.  one can always use millis() as part of the seed as well.

source: Stack Exchange

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

sort: votes


text:
why arduino can not write to server?
i write a code for Arduino + SIM800 for connecting to server.
but it don't work!
SerialGsm.println("AT+CIPSEND=63\r\n");
delay( 1000 );
receive_message();
SerialGsm.print( "GET http://sasasas.ir.ir/hadi/signal.php?value=10" );
delay( 10000 );
receive_message();

all thing is true but "GET" can not retrun "OK".
it is arduino response:

AT
OK
Call Ready
SMS Ready
AT+CSTT="mtnirancell"
OK
AT+CIICR
OK
AT+CIFSR
100.65.157.141
AT+CIPSTART="TCP","sasasas.ir",80
OK
CONNECT OK
AT+CIPSEND=63

GET http://sasasas.ir/hadi/signal.php?value=10

"get" dont have response.what is wrong in this code?

Learn the proper format of a GET request.

Firstly you only have half of the first line of a GET request. Secondly the half you do have is badly formatted.
A GET request does NOT look like this:
GET http://jalambadani.ir/hadi/signal.php?value=10

A GET request DOES look like this:
GET /hadi/signal.php?value=10 HTTP/1.1
Host: jalambadani.ir
Connection: close
[extra blank line]

If you don't send the correct data you can't expect to get any response back.  You should learn the basics of what you are trying to do instead of just throwing random text a a web server.

Here is a full transcript of a GET request to your URL:
$ telnet jalambadani.ir 80
Trying 185.211.56.148...
Connected to jalambadani.ir.
Escape character is '^]'.
GET /hadi/signal.php?value=10 HTTP/1.1
Host: jalambadani.ir
Connection: close

HTTP/1.1 200 OK
Date: Tue, 25 Jun 2019 22:47:07 GMT
Server: Apache/2
X-Powered-By: PHP/5.6.35
Upgrade: h2,h2c
Connection: Upgrade, close
Vary: User-Agent
Content-Length: 31
Content-Type: text/html; charset=UTF-8

New record created successfullyConnection closed by foreign host.

In code that would be:
SerialGsm.print("AT+CIPSEND=83\r\n");
delay(1000); // I hate that. Look for a proper OK instead.
SerialGsm.print("GET /hadi/signal.php?value=15 HTTP/1.1\r\n");
SerialGsm.print("Host: jalambadani.ir\r\n");
SerialGsm.print("Connection: close\r\n");
SerialGsm.print("\r\n);

thank you for your answer. i am electrical student and i don,t know about http...but i will try learn it.
i test your answer but it don,t work yet:|
"GET" don,t answer to me.@Majenko

PHP has nothing to do with it. You are talking in HTTP.

Did you try majenko's suggestion - which looks like it does work - running against your server - using telnet?? Once you see how that works translate that to your arduinon code. Don't reach for the final solution in the first attempt if it is too far away. Take it one step at a time. Copy majenko's telnet example -> learn the protocol. Then transfer the protocol to your app.

yes i use of majenko's suggestion.
  SerialGsm.print("AT+CIPSEND=50\r\n");
  delay( 3000 );
  receive_message();
  SerialGsm.print( "GET /hadi/signal.php?value=15 HTTP/1.1" );
  delay( 3000 );
  receive_message();

not work.

@hadisamani1996 What about the Host: and Connection: headers, along with the extra blank line? They are all part of the request. You have to send all the request.

i resolve it with your help@Majenko
i have 2 mistake.
first you saw and when i use of this line it solved.

SerialGsm.print( "GET /hadi/signal.php?value=150 HTTP/1.1\r\nHost: jalambadani.ir\r\n\r\n" );

two
next of " GET command " i use of a little delay.
i increase it a little and next solved my problem
thank you

Since Majenko helped you, you should accept his answer by clicking the little grey checkmark (tick mark) next to his answer.

nitpicking: why not println?

Depending on the system println could end with \n, \r or \r\n. Better to be explicit here.

HTTP specification requires \r\n. Arduino println() adds \r\n on all cores

@Juraj that can't be guaranteed. Certainly all cores should do it but there are so many written by so many different people with different skill sets that it can't be 100% guaranteed.

Print class is copied. there is nothing to change in println. if some core would change it, it would have an issue in the tracker immediately. basic examples of networking libraries would not work

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


text:
Serial Communication between arduino and nodeMCU
I am trying to connect a nodeMCU to arduino mega using serial communication so that i can read data from firebase.

I have put the following code on the NODEMCU.
#include<SoftwareSerial.h> //Included SoftwareSerial Library
//Started SoftwareSerial at RX and TX pin of ESP8266/NodeMCU
SoftwareSerial s(3,1);

void setup() {
  //Serial S Begin at 9600 Baud
  s.begin(9600);
}

void loop() {
  //Write '123' to Serial
  s.write('h');
  delay(1000);
}

And the following on the MEGA
int data; //Initialized variable to store recieved data

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

void loop() {
  if(Serial1.available()){
  data = Serial1.read(); //Read the serial data and store it
  delay(1000);
  Serial.print(data);}
}

I have connected TX1(arduino) to RX(nodeMCU) and RX1(arduino) to TX(nodeMCU) yet when ever i upload the code it doesnt work until i press the reset button then  some random numbers are passed over then eventually 123 comes accross. I am trying to do 2 way comunication but will worry about that when i finish this.

Any help would be much appreciated as I have spent the last 15 hours trying to solve this problem but to no avail.
Cheers, Hamish

you did not say how you connected the two controllers together ... please list all wires and all pins

Why not use the standard Serial instead of SoftwareSerial?

you use old esp8266 SoftwareSerial on hardware Serial pins of the esp8266. and you set the pins swapped in the SoftwareSerial constructor


text:
AC Voltage Sensing using Arduino Uno
Is it possible to sense AC Voltage using analog input for Arduino Uno or can it only read DC?
I mean I've tried connecting an AC voltage source to analog and I'm reading some numbers. However, I don't know if these numbers are actually AC voltage values or something else.
Ultimately I’m trying to find the avg voltage value for a given time duration. I know that analogRead ( ) gives ADC values. However, in my block of code, I have the conversion ratio of 1023/5 to get a good estimate of the voltage. However, I’m not too sure if Arduino analog sensing is suited for AC voltage? I’m using it to sense voltages generated by piezoelectric PVDF film and the frequency is pretty high. All I want is to use avg. voltage value to calculate electrical energy produced by the PVDF film.

the Arduino can read voltage at its analog input pin ... it takes time to convert the voltage to a numetic value ... if the voltage changes by a large amount during the conversion, then the result will not be accurate ... it can also change do quickly, that the change will not be detected

what is the frequency of the signal that you are trying to digitize?

Do you want a RMS value or to record the values of the waveform (eg. peak)?

@jsotola: Re “if the voltage changes by a large amount during the conversion, then the result will not be accurate”: That's not quite true. The ADC uses a sample-and-hold front-end which is actually pretty fast. Once sampled, the input voltage can change without disturbing the ongoing conversion. You get an accurate reading of the input voltage at the time of sampling. Obviously, a rapidly changing signal rises the issues of Nyquist frequency and aliasing, but these are completely unrelated to conversion accuracy.

You have to be a lot more specif if you want any kind of useful answer. What do you mean by the frequency being “pretty high”? What are the typical amplitude and DC offset? Re “I’m trying to find the avg voltage”: the easiest way to get the average voltage is to put a low-pass filter in front of the ADC.

The AC voltage that you are trying to measure is about 50/60Hz depending on where you live. And the maximum effective sampling rate for a regular Arduino ADC is 9615Hz. This means you're not going to experience any aliasing as the sampling rate is well above the 2 * Signal Frequency.
The values that are coming out of analogRead() are raw ADC values which you need to do, further calculation on if you want to have a correct voltage reading.

You have to set the ADC to auto-trigger if you want 9,615 Hz sampling rate. With analogRead() you get at most 8,929 Hz (112 µs/sample).

Ultimately I’m trying to find the avg voltage value for a given time duration. I know that analogRead ( ) gives ADC values. However, in my block of code, I have the conversion ratio of 1023/5 to get a good estimate of the voltage. However, I’m not too sure if Arduino analog sensing is suited for AC voltage? I’m using it to sense voltages generated by piezoelectric PVDF film and the frequency is pretty high. All I want is to use avg. voltage value to calculate electrical energy produced by the PVDF film.

so it is not mains AC with 50 Hz as the answer assumes

that is correct


text:
Update time in RTC over I2c fails
I am communicating two arduinos using the I2C protocol and sending from the slave to the master the integer value of UTC to update the time in the RTC module. When the master receives the UTC value from I2C and tries to set the time by the RTC.set () command the Arduino hangs and needs to be restarted, however, if I use RTC.set () in the loop () method it works perfectly. I do not understand why the system for when it is updated by I2c, is there any conflict?
This is the code with the loop() and Wire.onReceive():
#include <Thread.h>
#include <ThreadController.h>
#include <SoftwareSerial.h>
#include <LinkedList.h>
#include <SPI.h>
#include <TimeLib.h>
#include <DS3232RTC.h>
#include <Wire.h>

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

  Wire.begin(1);
  Wire.onReceive(receiveEvent);

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  setSyncProvider(RTC.get);
  if (timeStatus() != timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");

}

void loop() {

  digitalClockDisplay();
  delay(2000);

  // test only
  /*time_t t = processUTCFromI2c("1560810413");

  if (t != 0) {
    RTC.set(t);   // it's works
    setTime(t);
  }*/

}

// ================================ INIT ONRECEIVE ===========================================

void receiveEvent(int howMany) {
  char* vectorAction;
  char c;
  Serial.println(howMany);

  LinkedList<char> myLinkedList = LinkedList<char>();

  //while (1 < Wire.available()) { // loop through all but the last
  for (int i = 0; i < howMany; i++){
    c = Wire.read(); // receive byte as a character
    myLinkedList.add(c);
  }

  vectorAction = new char[myLinkedList.size()+1];

  for(int i=0; i < myLinkedList.size(); i++) {
    vectorAction[i] = myLinkedList.get(i);
  }

  vectorAction[myLinkedList.size()] = '\0';

  getParamsAndValues(vectorAction);

}

void getParamsAndValues(char* i2cValueString) {

  char* getValue;
  char* getParam;
  char* endValue;

  getValue = strchr (i2cValueString, '=');
  getParam = strchr (i2cValueString, '@');
  endValue = strchr (i2cValueString, '#');

  const size_t maxBuffLength = 15;

  char valueBuffer[maxBuffLength+1]; // allocate local buffer with space for trailing null char
  char paramBuffer[maxBuffLength+1];

  valueBuffer[0] = '\0';

  while(getValue && getParam && endValue && (getValue > getParam) && (endValue > getValue)) {
    Serial.println(i2cValueString);

    if (getValue && getParam && (getValue > getParam)) {
      size_t paramLength = getValue-getParam-1;
      valueBuffer[0] = '\0';

      if (paramLength <= maxBuffLength) {
        strncpy(paramBuffer, getParam+1, paramLength);// http://www.cplusplus.com/reference/cstring/strncpy/
        paramBuffer[paramLength] = '\0'; // properly terminate the c-string
      }
    } else {
      // handle Wrong Input
    }

    if (getValue && endValue && (endValue > getValue)) {
      size_t valueLength = endValue-getValue-1;
      valueBuffer[0] = '\0';

      if (valueLength <= maxBuffLength) {
        strncpy(valueBuffer, getValue+1, valueLength);// http://www.cplusplus.com/reference/cstring/strncpy/
        valueBuffer[valueLength] = '\0'; // properly terminate the c-string
      } else {
        // handle buffer too small
      }
    } else {
      // handle Wrong Input
    }

    getValue = strchr (getValue+1, '=');
    getParam = strchr (getParam+1, '@');
    endValue = strchr (endValue+1, '#');

    i2cActionReceived(paramBuffer, valueBuffer);
  }

}

void i2cActionReceived(char* param, char* value) {
  if(strcmp(param, "setTime") == 0) {
    time_t t = processUTCFromI2c(value);

    if (t != 0) {
      RTC.set(t);   // It's not works
      setTime(t);
    }
  }
}

// ================================ END ONRECEIVE ===========================================

// ================================ CONVERT UTC char* TO long ===============================
unsigned long processUTCFromI2c(char* utc) {
  unsigned long auxTime = 0L;

  if (strlen(utc)>0) {
    auxTime = atol(utc);
  }

  return auxTime;
}

The slave sends a string through I2C in the format @setTime=1560810413#.
In the loop() this commented the code that works onorata and on i2cActionReceived (char* param, char* value) is where the update fails by onReceive.

you are not using consistent data in your debugging effort ... in the first instance you use "1560810413"  ... in the second instance you use a parameter in a function

The symptom you are describing is: The RTC.set() method blocks in the onReceive callback of the Wire library, but not when used in the loop() function.
That sounds like an interrupt issue. The onReceive callback function is called from an ISR (Interrupt Service Routine) of the I2C hardware. It is no good to use any code, which utilizes interrupts, inside an ISR, until you know, what you are doing.
In this case the RTC.set() function (which you can find here at line 152) will call the method RTC.write(), which will do multiple I2C transactions (both sending and receiving as master). Doing these inside an ISR may already block the code from executing further.
But there is another problem. You have 2 Arduinos connected by I2C. The master Arduino talks only to the slave Arduino, while the slave Arduino is also a master for the RTC (You initialize this Arduino as slave, but it will become a master for the time, when you try to do master transmissions). Your slave code and the RTC library both use the Wire library, meaning the hardware I2C port of the Uno. So you have 2 masters on the same I2C port.
While the I2C standard supports multi-master setups via bus arbitration, the Wire library does not. In the case, when both masters start to transmit at the same time, it will block the bus (due to some blocking loops inside the Wire library, that cannot handle bus arbitration). So the setup, that you use is either not going to work at all or being very risky, depending on the amount of send data (When the bus is filled with more data, it get's more probable, that a collision between the masters happens).
With I2C on Arduino you should stick to single-master setups. For example you can set the first Arduino as slave, keeping the second Arduino as single master on the bus, which handles both getting UTC from the first Arduino and communicating with the RTC. On the first Arduino you would set up an onRequest callback, that fills the I2C buffer with the current UTC time, which then get's transmitted to the master Arduino, so that it can update the RTC's time with it.

EDIT:
I2C has a fundamental master-slave principle. The master generates the clock signal and initiates/stops any transactions on the bus. A slave cannot send anything over the bus, when the master didn't request data from it, including "calling" the master. Any communication start's with the master.
The Wire library gives you the possibility to initialize the Arduino as slave and then do master transactions. For this the I2C hardware is configured as master for the time of the transactions. So you can initialize both Arduinos as slaves with an address and let them change to master mode for any master transaction, that you need. That is the way, that you are talking about in your comment and what you use in the code in your question.
BUT you get a big problem, when both Arduinos try to send at the same time. That is called data collision. The I2C specification has the bus arbitration for this (basically the master that first sends a 1 has to back down from the transaction), so that collisions can gracefully be resolved. The Wire library doesn't implement this, so it will block in case of a collision. Then you have to reset the Arduino to get it going again.
You should again analyse your requirements and check, if you really need I2C for communication between the Arduinos, or if you really need individual bidirectional communication. That is often also a design choice.
If you really need individual 2 way communication between the Arduinos, I see 2 possibilities:

You can do it the hacky way and add an extra line between both Arduinos. You would set the Arduino with the RTC as I2C master and the other Arduino as slave. The slave Arduino can pull the extra line with a digital output pin to LOW, so that the master Arduino can sense this as signal at one of it's digital input pins (configured with internal pullup resistor). When the master Arduino senses, that the extra line goes to LOW, it can request data from the slave. So you are using the extra line for signaling the master, that new data is available at the slave.
If you are not bound to I2C, other communication interfaces might be better suited. UART (in the Arduino framework called Serial) implements bidirectional bytewise communication. No master/slave relationship. That would be a lot easier.

Thanks for the explanation and the hint of how to solve the problem! Because of the project specification I will not be able to set one of the Arduinos as master, the two need to be slave and communicate between them. To solve I set the variable time_t as global and another variable boolean also as global and when it arrives a value by I2C I assign the value to time_t and true to the other variable and do the update inside the loop().

I don't quite understand the project specification. In I2C communication there is always 1 master during a transmission. In a multi-master setup this role will just change between the devices. And the Wire library does not support multi-master. Why do you need multi-master? What exactly states the project specification about this?

I do not know much about the Wire library, but as far as I understand it, it is not possible for the slave to call the master because it does not have an address, so my "master" is at address 1 (Wire.begin (1);) and the slave in address 2 (Wire.begin (2);) and in this way one can call the other. Is there a way for the slave to call the master since it does not have an address?

@user2831852 I added more explanations at the end of my answer.

As explained by chrisl, the fact that the Arduinos communicate with I2c and the update of the RTC is by I2C, the update fails and locks the system. To resolve this I declare the global variables boolean updateRTC = false; and time_t setUTC; and in the method that processes UTC I assign the value true to updateRTC and the numeric value of UTC tosetUTC and do the verification in void loop().
// global vars
boolean updateRTC = false;
time_t setUTC;

// RTC update inside loop()
void loop() {
  digitalClockDisplay();
  delay(1000);

  if (setUTC > 0 && updateRTC == true) {
    updateRTC = false;
    RTC.set(setUTC);
    setTime(setUTC);
    setUTC = 0;
  }

}

// Method executed at the end of the onReceive() event
void i2cActionReceived(char* param, char* value) {
  if(strcmp(param, "setTime") == 0) {
    setUTC = processUTCFromI2c(value);

    updateRTC = true;
  }
}


text:
expected unidentified id before 'if"
#include <iostream>
using namespace std;
char board[3][3]={{'1','2','3'},{'4','5','6'},{'7','8','9'}};
char turn='X';
int draw=0;
int row,column;
void display_board()
{
    system("cls");
    cout<<"\n\n TIC TAC TOE GAME:";
    cout<<"\n\n PLAYER[1]==O\t\t\t PLAYER[2]==X";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t   "<<board[0][0]<<" |  "<<board[0][1]<<"  |  "<<board[0][2]<<"   \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t_____|_____|_____\n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t  "<<board[1][0]<<"  |  "<<board[1][1]<<"  |  "<<board[1][2]<<"    \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t_____|_____|_____\n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t  "<<board[2][0]<<"  |  "<<board[2][1]<<"  |   "<<board[2][2]<<"  \n";
    cout<<"\t\t     |     |     \n";
    cout<<"\t\t     |     |     \n";
}
void player_turn()
{
    int choice;
    if(turn=='X')
    {
        cout<<"\n\t  PLAYER[1]==O's turn";
    }
    if(turn=='O')
    {
        cout<<"\n\t  PLAYER[2]==X's turn";
    }
    cin>>choice;
    switch(choice)
    {
        case 1:row=0; column=0; break;
        case 2:row=0; column=1; break;
        case 3:row=0; column=2; break;
        case 4:row=1; column=0; break;
        case 5:row=1; column=1; break;
        case 6:row=1; column=2; break;
        case 7:row=2; column=0; break;
        case 8:row=2; column=1; break;
        case 9:row=2; column=2; break;
        default:
        cout<<"Invalid input";
        break;
    }
   if(turn=='X' && board[row][column]!='X' && board[row][column]!='O')
   {
       board[row][column]=='X';
       turn='O';
   }
   else if(turn=='O' && board[row][column]!='X' && board[row][column]!='O')
   {
       board[row][column]=='O';
       turn='X';
   }
   else
   {
       cout<<"Box already filled!\nplease try again!!";
       player_turn();
   }
   display_board();
}
int gameover()
{
    for(int i=0;i<3;i++)
    {
        if(board[i][0]==board[i][1] && board[i][0]==board[i][2] || board[0][i]==board[1][i] && board[0][i]==board[2][i])
        return 0;
        else if(board[0][0]==board[1][1] && board[0][0]==board[2][2] || board[0][0]==board[1][1] && board[0][0]==board[2][2])
        return 0;
    }
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            if(board[i][j]!='X' && board[i][j]!='O')
            return 1;
        }
    }
    draw=1;

    return 0;
}

int main()
{
    system("cls");
    while(gameover())
    {
    display_board();
    player_turn();
    gameover();
    }
    return 0;
}

if(turn=='X' && draw=0)
{
    cout<<"PLAYER[2] WINS!!!";
}
else if(turn=='O' && draw==0)
{
    cout<<"PLAYER[1] WINS!!!";
}
else
{
    cout<<"GAMEDRAW!!!";
}

At which line you got the error?

This is no Arduino code, but C++ code for a PC. There is no cin or cout for Arduinos

if after main function is not in a function

Is this even a question? Ir is it simply a post of some random code as "guess where the error is" game? Why are people even putting in any effort to reply when the OP didn't even bother to.put any effort into the errr "question"?

This fragment is outside of a function:
if(turn=='X' && draw=0)
{
    cout<<"PLAYER[2] WINS!!!";
}
else if(turn=='O' && draw==0)
{
    cout<<"PLAYER[1] WINS!!!";
}
else
{
    cout<<"GAMEDRAW!!!";
}

Some other remarks:

Instead of multiple return statements, it is better to create a local variable, set it, and return that one at the end. So only use one return statement per function (that has a return value).
As chrisl mentions: Arduino does not have cin or cout. Use the Serial class for this.
You can replace the following code:

 switch(choice)
 {
    case 1:row=0; column=0; break;
    case 2:row=0; column=1; break;
    case 3:row=0; column=2; break;
    case 4:row=1; column=0; break;
    case 5:row=1; column=1; break;
    case 6:row=1; column=2; break;
    case 7:row=2; column=0; break;
    case 8:row=2; column=1; break;
    case 9:row=2; column=2; break;

by
row    = (int) ((choice - 1) / 3);
column =        (choice - 1) % 3;

Use an enum as return type for function gameover()
E.g. EGameState { Running, PlayerOneWon, PlayerTwoWon, Draw };
This removes also the global variable draw.
You call function gamover twice, one time within the while loop without checking the result.
Do not use a char for the variable turn but the player number, or a boolean (XPlayerHasTurn), or an enum.

For the person downvoting my answer, why?

it is not Arduino 2. it is only a typo. I think we should apply here on Arduino SE this StackOverflow 'rule' https://meta.stackoverflow.com/questions/252256/behavior-on-questions-caused-by-typographical-errors

Completely agree with 1, but I don't see what is a typo in this problem (unless you mean it's it's maybe copy/pasted wrongly). It can be easily converted to Arduino though (replacing cin/cout by Serial class calls).

as an analogy, on the Movies SE a movie identification questions are off-topic. because it was endless count of trivial question

Ok, so only the remark about cin/cout to Serial class is specific Arduino (but indeed, was not the question itself). Next time I will just make a remark and vote to close.

as per my comment above why would you put any effort into a "question" where the OP has been extremely lazy to a) seemingly randomly selected Arduino SE when the code is not intended for Arduino, too lazy to actually explain there problem, too lazy to even try to find the typo, too lazy to format the code and probably too lazy to accept your answer +1 for your answer (its a good answer) +2 for @juraj for trying to keep the site clean. -10 (if I could) to OP.


text:
i have a problem with mdns i'm using an ESP8266
I am working on a project on which I have to drive a DC 12V motor. I use an ESP8266 I manage to manage my engine remotely but my only problem is the mdns I use the mdns but it does not work. when I upload no error is displayed but I can not access my esp using his name.local

what esp8266 boards package version? PC has Windows or Linux?

I use the ESP12E and the version of my arduino is 1.8.9 my driving board is the pololu and my pc is on linux

sorry i forgot, i use linux on my pc


text:
i2c slave write to ARM powered device master
I want to communicate to an ARM microprocessor via I2C protocol (Multitech mDot, which uses Mbed platform). I successfully receive data from it (and got it displayed on Arduino's serial monitor), but when I want to send data from the Arduino I don't receive nothing on the other end. This is my sketch:

#include <DHT.h>
#include <Wire.h>

// Sensor temperatura, humedad DHT11 (test).
#define DHTPIN 10
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// Comunicacion i2c con nodo lora. 7bitaddress 010 1001 (r/w)
#define SLAVE_ADDRESS 0x29

// Variables globales de sensores
float h;
float t;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveEvent);
  dht.begin();
  Serial.begin(9600);
}

void loop() {
  delay(5000);
  h = dht.readHumidity();
  t = dht.readTemperature();

  // Comprobamos si ha habido algún error en la lectura
  if (isnan(h) || isnan(t)) {
    Serial.println("Error obteniendo los datos del sensor DHT11");
    return;
  }

  Serial.print("Humedad: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperatura: ");
  Serial.print(t);
  Serial.println(" *C ");

  Wire.onReceive(receiveEvent);
}

// Total de bytes del arreglo de datos a transmitir: 28 bytes.
void receiveEvent(int howMany) {
  Serial.print("Mensaje recibido por i2c desde MDOT LoRa Node: ");
  while (Wire.available() > 0) {
    Serial.print(char(Wire.read()));
  }
  Serial.println();
  char enviar = "Cacatua";
  Wire.write(enviar);
  return;
}

I wanted to know if this schematic is correct and if the wire write as it is written is performed. If so, I will need to see what is wrong with the code on my ARM device.

Are you requesting the data from the Arduino slave in your master code?

For sure I am, according to the documentation https://os.mbed.com/docs/mbed-os/v5.12/apis/i2c.html I'm performing an i2c.read(addr, pointer, length); but I am not getting any fetched data that's why I wanted to know if the sketch was ok so that I needed to check on what's going on with the way I'm handling the read instruction on the ARM device

You can implement an onRequest callback function and trigger an LED there, so that you can check, if the request is actually reaching the Arduino

I did it, and indeed I get a request notification. And to my surprise, if I perform a write in there the message is sent! Thanks dude! Post it as an answer and I vote it. Thanks again!

It is important to understand, that Wire.write() will not actually send data over the I2C bus. It will only put the data bytes into the send buffer of the library.
The normal way of the Wire library to send data as a slave is to implement the onRequest callback function. It will be called from an I2C ISR when a master on the I2C bus requests data from this slave. In the callback, you use Wire.write() to fill the buffer with data, which then get's send out to the master.
I'm not quite sure about the following: My guess regarding your previous code is, that the Wire library clears the send buffer at some time during the send or read code. That would mean, that the data written in the onReceive callback will simply be lost, instead of used for transmission of requested data. That might be meant that way, so that the users will stick to implementing the onRequest callback, which is the correct way of doing it.

Note: In your code, you call Wire.onReceive(receiveEvent) on every void loop() iteration. That isn't necessary. The Wire.onReceive() method only set's a function pointer to the callback function. It does NOT execute this callback function, which only will be called by the corresponding I2C ISR, when data is actually received. You should use this line only once in setup() to setup the callback function. Though using it multiple times does not break things here. It's just useless.


text:
Flashing ESP8266 ESP-12E/12F
I'm pretty new to Arduino programming and i'm trying to connect this ESP8266 module to my FTDI programmer but constantly getting this error on my ARDUINO IDE:  esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header.
My guess is that its not in flashing mode and that i have to connect GPIO0 to ground or sompthing else.

On my version of this "Adatper" adapter the io pins were not connected. I patched io 0 to the esp-01 like header, to be able to put the ESP in bootloader mode. On the picture you see a paperclip jumper connecting io 0 to ground for flashing mode.
Back then I could leave the jumper connected, because the esp8266 run the sketch after upload. In new versions of esp8266 arduino boards package the esptool hard resets the esp8266 so it returns into flashing mode. This can be changed in platform.txt.
I recommend you to buy an esp8266 dev board with USB (Wemos, NodeMcu and similar)

I connected it like this Check here but i still got same error TRACE +0.101 Timed out waiting for packet header. Any advice ? :S

is the io 0 pin of the esp-12F module connected to the header? on my it was not. do you see the wire soldered to esp-12F pin on my photo?

It's not, since i'm new to this can you explain to me how to connect it to header ?

you see it on my picture

I see soldered wire but I do not know where the other end of the wire is going

I connected wires as on the picture and connected io 0 pin of the esp-12F module to GPO0 on the bottom side of the esp-12 and when i tried to upload the code got this Check here

I added a photo of the bottom side. Do you still have the jumper wire on the header from Ground to io 0?

Thank you alot for your help but i still got this error: link

measure with multi-meter if the soldering and header connection is good

I think connections are good since Arduino IDE at start uploading shows that he read bytes and receives packet but after a while it crashes like on link :S

try it without breadboard

Same result link :/

do you supply 3.3 or 5 V to the adapter?

I supply with 3.3V

the adapter converts 5 V input to 3.3 V for the esp8266. supply 5 V

I't wooorkeed ;) Thaank you alot :)))))))))))

the purpose of the adapter is to convert 5 V power and logic level on RX pin to 3.3 V of the esp-12F


text:
What is "tCAN" in codes of CAN bus?
I'm new to Arduino and CAN bus. I'm studying some code examples which contain "tCAN message".
My guess it defines a class for of CAN messages. I did a lot of search but found no information on it except for sample codes. Can anyone help me out.  Thank you!
Some code from the example project:
void activateCAN()
{
 //***PREPARE MESSAGE***//
    tCAN message_act;
    message_act.id = 0x750;
    message_act.header.rtr = 0;
    message_act.header.length = 8;
    message_act.data[0] = 0x00;
    message_act.data[1] = 0x00;
    message_act.data[2] = 0x00;
    message_act.data[3] = 0x00;
    message_act.data[4] = 0x00;
    message_act.data[5] = 0x00;
    message_act.data[6] = 0x00;
    message_act.data[7] = 0x00;

    mcp2515_bit_modify(CANCTRL, (1 << REQOP2) | (1 << REQOP1) | (1 << REQOP0), 0);
    mcp2515_send_message(&message_act); //SEND MESSAGE
}
//******CAN ACTIVATION*****ENDS****//

could you please also state, which .h files are included at the beginning of this sketch?

From Re: Sending multiple messages over CAN with sparkfun can bus shield: #include <Canbus.h> among others.

tCAN will be a struct that defines the structure of the CAN message being sent.  The name tCAN is not a standard and will have been chosen by the author of the library you are using.  At a guess it's using a variant of Hungarian Notation, and the t prefix means type - so it's probably been typedef'd from a struct to a type name.
I am not familiar with CAN, but if there are standard message formats this struct will correspond with one of them.  You can find the actual structure within the header file for your chosen library (or maybe in the example sketch code itself?).

Thank you for the explanation.

tCAN here is a struct that defines a CAN frame to be sent over the network.
https://en.m.wikipedia.org/wiki/CAN_bus#Frames
There are several types of frames, standard, extended, and FD (flexible data).
The tables in the linked Wikipedia article describe the physical protocol. The struct won’t have a corresponding field for every section of the protocol, because the library will take care of setting the constant or calculatable things, like the CRC and End of Frame. You just have to set the relevant details, like ID, (maybe) data length and the data itself.
If you have trouble, check your baud rates and ensure you’re sending the expected kind of frame. Most hobbyist will use standard frames, but many industrial grade pieces of equipment will use Extended or FD frames.


text:
Multiple libraries were found for "WiFiClient.h" using nodemcu
I am trying to send HTTP requests from nodemcu so I started by uploading the esp8266 library but when I run the following code
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(115200);                                  //Serial connection
  WiFi.begin("Iphone de elaa", "27343550");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://localhost:8080/getallcadres/getnbpassage/5");      //Specify request destination
   http.addHeader("Content-Type", "text/plain");  //Specify content-type header

   int httpCode = http.POST("5");   //Send the request
   String payload = http.getString();                  //Get the response payload

   Serial.println(httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");

 }

  delay(30000);  //Send a request every 30 seconds

}

i got this error
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, nonos-sdk 2.2.1 (legacy), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Build options changed, rebuilding all
In file included from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecure.h:41:0,

                 from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiServerSecure.h:20,

                 from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/ESP8266WiFi.h:41,

                 from C:\Users\ELA_HIDRI\Desktop\PFE_ING\nodemcu\nodemcu.ino:2:

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:38:5: error: 'BearSSL::WiFiClientSecure::~WiFiClientSecure()' marked override, but does not override

     ~WiFiClientSecure() override;

     ^

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:41:9: error: 'int BearSSL::WiFiClientSecure::connect(const String&, uint16_t)' marked override, but does not override

     int connect(const String& host, uint16_t port) override;

         ^

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:46:12: error: 'size_t BearSSL::WiFiClientSecure::write_P(const char*, size_t)' marked override, but does not override

     size_t write_P(PGM_P buf, size_t size) override;

            ^

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:58:12: error: 'size_t BearSSL::WiFiClientSecure::peekBytes(uint8_t*, size_t)' marked override, but does not override

     size_t peekBytes(uint8_t *buffer, size_t length) override;

            ^

Multiple libraries were found for "WiFiClient.h"
 Used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\libraries\WiFi
 Not used: C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi
exit status 1
Error compiling for board Generic ESP8266 Module.

so what is this error why i am getting it
Edit
i switched to an other version of arduino ide 1.6.5 the error is gone but it looks like it is not connection i got

delete folder C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\libraries\WiFi. it is the WiFi library for the retired Arduino WiFi Shield

i could not acces to windowsApps

@Juraj please check my update

better answer to this question https://forum.arduino.cc/index.php?topic=623460.msg4223849#msg4223849

relevant issue.  UPVOTED

Simply Switch
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

to
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

really?  that simple?  will test to see if i can reproduce issue on ubuntu as well.  tks!!

I am new to nodemcu. When I was using ESP8266WiFi.h, I got the error "Error compiling for board NodeMCU 1.0 (ESP-12E Module)" which said that Multiple libraries were found for ESP8266WiFi.h. I solved by simply put the void loop(){} empty function at the end of my code. Now It's working...


text:
Arduino Timer with increase time button
I have an Arduino project to do, which requires a countdown timer(which I've already done). I connected a push button, and when I press that button I need it to increase my countdown timer by +10 seconds.
Can anyone help me with adding the code for this button?
Here is the code so far(I declared the button, but I don't know if it's any good):
#include <LiquidCrystal.h>

int buttonPin = 7;
int buttonState = 0;
int seconds = 30; // count seconds
int minutes = 0; // count minutes
int hours = 0; // count hours
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
//initialize the library with the numbers of the interface pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7); // pins connected to LCD

void setup()
{
  lcd.begin(16, 2); //set up the LCD's number of columns and rows
  pinMode(buttonPin, INPUT);
}
void loop()
{
  buttonState = digitalRead(buttonPin);
  lcd.setCursor(1, 0);
  lcd.print ("Sosire in:");
  lcd.setCursor(6, 1);
  lcd.print(":");
  lcd.setCursor(9, 1);
  lcd.print(":");

  seconds--;
  delay(1000);

 if (seconds < 0)
  {
    minutes--;
    seconds = 59;
  }
 if (minutes < 0)
  {
    hours--;
    minutes = 59;
  }
 if (hours < 0)
  {
    hours = 0;
    minutes = 0;
    seconds = 30;
  }
 if (minutes > 9)
  {
    lcd.setCursor(7, 1);
    lcd.print(minutes);
  }
 else
  {
    lcd.setCursor(7, 1);
    lcd.print("0");
    lcd.setCursor(8, 1);
    lcd.print(minutes);
    lcd.setCursor(9, 1);
    lcd.print(":");
  }

 if (seconds > 9)
  {
    lcd.setCursor(10, 1);
    lcd.print(seconds);
  }
 else
  {
    lcd.setCursor(10, 1);
    lcd.print("0");
    lcd.setCursor(11, 1);
    lcd.print(seconds);
    lcd.setCursor(12, 1);
    lcd.print(" ");
  }

 if (hours > 9)
  {
    lcd.setCursor(4, 1);
    lcd.print(hours);
  }
 else
  {
    lcd.setCursor(4, 1);
    lcd.print("0");
    lcd.setCursor(5, 1);
    lcd.print(hours);
    lcd.setCursor(6, 1);
    lcd.print(":");
  }
 if (seconds == 0)
  {
    lcd.clear();
    lcd.print("Este in statie");
    delay(5000);
    lcd.clear();
  }

}

Your code is very hard to read, please align it (parenthesis under each other and code within indented properly).

You should always name your variables for readability. Instead of "H", "M" and "S", use English names like "hours", "minutes", and "seconds". It will make it a lot easier for other people to help you, and also help you read your own code!

My program works correctly , but i don't know how to make when i press the button to increase time with 10+ seconds.

Increase which time? You will need to be more specific, you have 3 different 'time' variables, hours, minutes, and seconds.

Seconds , increase S with 10 seconds when i press the button.

your code is un-necessarily complex  .... the LCD keeps track of the next print position .... for example, the display seconds code can be reduced to these four lines ....
lcd.setCursor(10, 1);
if (seconds < 10)     lcd.print("0");
lcd.print(seconds);
lcd.print(" ");

So look at the button example and the state change example that come with the IDE.  the first explains how to use an if statement to do something when a button is pressed and the second explains how to have that happen only once per press of the button.

I don't fully understand your program, but I hope to give some guidelines/tips:

Instead of using all kind of different variables, with hour, minutes and seconds, with with only one variable that keeps the time. E.g. a long integer value that contains 24 * 60 * hours + 60 * minutes + seconds as one value. E.g. 12:34:56 will be 24 * 60 * 12 + 60 * 34 + 56 = 19,376.
Subtracting one or 10 seconds will be as easy as subtracting a value 1 or 10.
To calculate back to seconds, minutes and hours, use 3 formulas (assuming time is the time value):

int hours   = (int) time / 60 / 24;
int minutes = (int) (time - hours * 60 * 24) / 60;
int seconds = time % 60;

Keep the code to display the LCD separate, probably it's easier to update every digit every second. You probably change it every second, or when the button has been pressed, which is very slow for a MCU.
When using a button (you already put it in a variable), just remove 10 seconds, and update the time.
However, check also the Blink Without Delay example on the Arduino website, since when you press a button, high likely the button will bounce and one press may result in several times 10 seconds will be subtracted.
And as said above, use good and English variable names, and English comments (except the GUI text to be displayed... O zi buna).


text:
writting to buffer from serial input
Can some one explain this behaviour please, i have the following code
  byte buffer[512];
  byte block;
  byte len;

  Serial.setTimeout(60000L) ;     // wait until 20 seconds for input from serial
  // Ask personal data: Family name
  Serial.println(F("Type text followed by #"));
  len = Serial.readBytesUntil('#', (char *) buffer, 500) ; // read from serial
  Serial.print(len);
  for (byte i = len; i < 250; i++) buffer[i] = '#';     // pad with #
  Serial.print(len);

This works but if i change the "for" line to any thing higer then 250 it stops working and there is a "buffer out of memory condition)
My question is why can't the for loop say the below as the buffer size is 512?
for (byte i = len; i < 512; i++) buffer[i] = '#';

Am i right in thinking it has something to do with  (Char *), i did copy this code from the example ardunio code and was jsut trying to incress the lenth of input it accpeted.

A byte can only contain values from 0 to 255 (including).
So my guess it works for values until 255.
You should use a different type, e.g. unsigned int or unsigned short.
for (unsigned short i = len; i < 250; i++) buffer[i] = '#';     // pad with #

Also, I advise to use a constant or define for the buffer size, now you have 3 values (512, 500 and 250 in the loop, I assume they should be based on the same value).
About the char*: Looking at StreamReadBytesUntil, it seems that the parameter wants a char* instead of a byte* (which is more or less the same), but it's better to cast to show the parameter is of type char* since that is high likely the exact type (but the official Arduino documentation does not show the parameter types sadly).

I agree use same constant, it was original but i was playing about when i tried to go over 250. the fact is broke at 254 should have told me this.

No problem, btw, I opt to close this questions since it's not related to Arduino, but you can continue coding, good luck.

you could  also explain why (char *) is used in this code, is that there to insure it write to the begining of the buffer. why cant you jsut use "buffer" or is there a particaul advantage of doing it this way?

I added a note about it.

for len is byte small too

That make sence, thank you for takeing the time out to help.

@See Juraj's remark ... btw, unless you know beforehand you might run into memory problems, always use int or unsigned int. Or if you want to do it better, create a specific type for it: typedef unsigned short buffer_length

Brillent all and it addresses some other problems in the code block i was writing the example used "byte" a lot. something for me to remember when hacking other peoples examples. check the sizes fit ::)

Personally I like to use types as int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t and bool ... some of them are predefined, some are not. But this way I always know exactly what ranges I can use. When a range could change in the future, I use a typedef and give if a specific name, like I said above (typedef uint16_t buffer_size). That saves a lot of type replacement when changed.

I seem to remember problems using unsigned as types for loop indexes. Someone please correct me if I’m wrong.

@RubberDuck Yes, for example, if you count down, you cannot check for >= 0, because an unsigned value always is >= 0, but for counting up (until value 254 max) an unsigned byte can be used.

Ahh. Yes. I made this mistake before. https://stackoverflow.com/a/9044067/3198973

@RubberDuck Yes ... sadly most compiler do not give a warning.


text:
How can I reset servo position?
When I do
myServo.write(0)

It isn't straight, I want it to be straight but it is at about a 45 degree angle anyone know how to reset the position with arduino to make other positions 0 and making everything relative to where that zero is?

The easy way is to remove the servo arm, set the servo position with the Arduino, and then put the servo arm back on.

if the servo class is designed to go from 0 to some maximum, then it's correct that a typical servo should be at 45 degrees (and it should be at 45 degrees the other way when you ask for maximum).  Typical modern servos have splined output shafts that are easy to reset.

On Arduino, 0 is 90 degrees one way,  90 is centered, and 180 is 90 degrees in the other direction. Not all servos can do 180 degrees so the actual maximum rotation may be less.

What kind of servo? And reference angle ?


text:
http.POST is not sending data to local web page
I am using a nodeMCU to send data to my local web page developed using Spring boot but when I run the code I don't get an error the esp8266 connects to WiFi but I don't get anything on my spring boot app or any responses.
Here is the rest controller used from spring boot

@RestController
@RequestMapping("/getallcadres")
public class cadreController {
    @Autowired
    cadreRepository cadre;

@PostMapping("/getnbpassage")
    public String getnbrpassage(@RequestBody String nb){
        System.out.println("nombre de passage = "+nb);
        return "received";

    }
}

and the Arduino code
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(9600);//Serial connection
  WiFi.disconnect();
  WiFi.begin("Iphone de elaa", "27343550");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }
  Serial.println("Wifi is connected");
  Serial.println(WiFi.localIP());

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status
 Serial.println("here we start");
   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://localhost:8080/getallcadres/getnbpassage");      //Specify request destination
   http.addHeader("Content-Type", "text/plain");  //Specify content-type header

   int httpCode = http.POST("5");   //Send the request
   String payload = http.getString();//Get the response payload

   Serial.println("return code"+httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");

 }

  delay(30000);  //Send a request every 30 seconds

}

I am using Arduino IDE 1.6.5 here is what I get

Your URL has localhost as the host name. That cannot work. localhost means “self”, the computer initiating the request. In this case it would mean the ESP8266, if it even understood it. You need to use the name or the IP address of the computer running your spring boot app, not localhost.

thank you that worked for me


text:
Timestamping AnalogBinLogger data
I would like to timestamp the data collected from AnalogBinLogger.ino on an Arduino Uno. The sketch uses 512-byte buffers, and I have read that writing data in 512-byte chunks is 'better' in terms of write latencies.
The sketch uses this structure for the buffers:
// Data block for 10-bit ADC mode.
const size_t DATA_DIM16 = 254;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
};

Since I want to add the timestamps which are of unsigned long type, I would have to modify the structure as follows:
// Data block for 10-bit ADC mode.
const size_t DATA_DIM16 = 254;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
  unsigned long  milli[DATA_DIM16]; // time in milliseconds
};

Now, this structure exceeds 512 bytes and is 1528 bytes. Due to unavailability of enough free stack, my program doesn't run (sketch reports FreeStack to be 1135 bytes). How can I go about this?
PS: My root problem is to achieve time-synchronisation among multiple data-collecting Arduinos which sample at high rates like 8kHz. Due to clock drifts, even if I sync the start times, the timestamps collected afterwards would not be relative to each other. Hence I plan to have a master Arduino send its time to the others in regular intervals.

The straightforward solution:
const size_t DATA_DIM16 = 84;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
  unsigned long  milli[DATA_DIM16]; // time in milliseconds
  unsigned long padding;   // pad to 512 bytes
};

Now, I suggest to think again about your requirements. Do you really
need a 32-bit timestamp for every data point? If they are closely spaced
in time, a 16-bit, or even 8-bit timestamp should be enough. You could
put a full 32-bit timestamp at the beginning of each block, then only
8-bit timestamps for every data point. This would allow you to store
168 samples per block. You could even pack a 6-bit timestamp with
the data sample into an uint16_t, and have 252 samples per block.

Writing in 512 byte chunks is done by SD libraries, so you could rely on that layer and simply write and store single events
struct block_t {
  uint32_t  milli; // time in milliseconds
  uint16_t data;
  uint8_t  overrun;  // overrun status since last block
};

I do not know your AnalogBinLogger.ino. In other circumstances there's no such 512 byte limit, but a general and strict RAM limit. (You could decrease your DATA_DIM to make it fit safely)

My understanding is that a 512-byte buffer was chosen for its efficiency, which is an important consideration when you try to log data at a high rate.

https://github.com/greiman/SdFat/blob/master/examples/AnalogBinLogger/AnalogBinLogger.ino is an interesting example. Thanks @Edgar and Harini


text:
Arduino core libraries
We have worked with a company to design a custom board based on the Arduino Zero and have also had them do some programming for us.
In doing so, they have had to modify the following Arduino core libraries:  variant.cpp, variant.h and wiring_analog.c.
Unfortunately, this causes problems with other projects using Arduino.
Is there a way to keep these libraries local to specific projects without modifying the original files?

you want to use the Arduino SAMD core with your board? create a board package which references the SAMD core

I'm wondering why they didn't define a new board type and use conditional compiling in the first place so that you could just use the new/modified files for everything.

for a mass sold board create a boards package for Boards Manager installation.  For a customized board or a small series put the files in the hardware folder https://arduino.stackexchange.com/questions/54484/adding-a-custom-board-to-the-arduino-ide/60660#60660

@Juraj - Yes, we are using the Arduino SAMD core (Arduino Zero Native USB).  I will check out the link you provided.  Thank you.

it would be better to avoid the change in wiring_analog.c. what change is it?

@Juraj - I am not sure what changes were made.  I have sent an email to the Software Engineer to inquire.  I'll report back when I know.


text:
ESP32 cam board and waking from deep sleep
I am getting an error that the sd card cant be mounted when the ESP32 comes out of deep sleep. The board is coded to wake up on a timer from deep sleep and mount the sd card and take a picture. My question is how can I get the SD card to mount properly? I am providing 3volts to the board and I think the same error happens when 5volts is applied. Here is the code:
/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-cam-take-photo-save-microsd-card

  IMPORTANT!!!
   - Select Board "ESP32 Wrover Module"
   - Select the Partion Scheme "Huge APP (3MB No OTA)
   - GPIO 0 must be connected to GND to upload a sketch
   - After connecting GPIO 0 to GND, press the ESP32-CAM on-board RESET button to put your board in flashing mode

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

#include "esp_camera.h"
#include "esp_timer.h"
#include "img_converters.h"
#include "Arduino.h"
#include "fb_gfx.h"
#include "fd_forward.h"
#include "fr_forward.h"
#include "FS.h"                // SD Card ESP32
#include "SD_MMC.h"            // SD Card ESP32
#include "soc/soc.h"           // Disable brownour problems
#include "soc/rtc_cntl_reg.h"  // Disable brownour problems
#include "dl_lib.h"
#include "driver/rtc_io.h"
#include <EEPROM.h>            // read and write from flash memo
// define the number of bytes you want to access
#define EEPROM_SIZE 1

RTC_DATA_ATTR int bootCount = 0;
// Pin definition for CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27

#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

int pictureNumber = 0;

#define uS_TO_S_FACTOR 1000000

#define TIME_TO_SLEEP  60

void setup() {

  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector

  Serial.begin(115200);

  Serial.setDebugOutput(true);
  //Serial.println();

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  //pinMode(4, INPUT);
  //digitalWrite(4, LOW);

  if(psramFound()){
    config.frame_size = FRAMESIZE_UXGA; // FRAMESIZE_ + QVGA|CIF|VGA|SVGA|XGA|SXGA|UXGA
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }

  // Init Camera
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  Serial.println("Starting SD Card");
  delay(2000);
  if(!SD_MMC.begin()){
    Serial.println("SD Card Mount Failed");
    //return;
  }

  uint8_t cardType = SD_MMC.cardType();
  if(cardType == CARD_NONE){
    Serial.println("No SD Card attached");
    return;
  }

  camera_fb_t * fb = NULL;

  // Take Picture with Camera
  fb = esp_camera_fb_get();
  if(!fb) {
    Serial.println("Camera capture failed");
    return;
  }
  // initialize EEPROM with predefined size
  EEPROM.begin(EEPROM_SIZE);
  pictureNumber = EEPROM.read(0) + 1;

  // Path where new picture will be saved in SD Card
  String path = "/picture" + String(pictureNumber) +".jpg";

  fs::FS &fs = SD_MMC;
  Serial.printf("Picture file name: %s\n", path.c_str());

  File file = fs.open(path.c_str(), FILE_WRITE);
  if(!file){
    Serial.println("Failed to open file in writing mode");
  }
  else {
    file.write(fb->buf, fb->len); // payload (image), payload length
    Serial.printf("Saved file to path: %s\n", path.c_str());
    EEPROM.write(0, pictureNumber);
    EEPROM.commit();
  }
  file.close();
  delay(2000);
  // Turns off the ESP32-CAM white on-board LED (flash) connected to GPIO 4
  pinMode(4, OUTPUT);
  digitalWrite(4, LOW);
  rtc_gpio_hold_en(GPIO_NUM_4);

  esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);

  Serial.println("Going to sleep now");

  delay(2000);
  esp_deep_sleep_start();
  Serial.println("This will never be printed");
}

void loop() {

}

also here is the board I am using
Here is output of the error:
rst:0x5 (DEEPSLEEP_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1100
load:0x40078000,len:9232
load:0x40080400,len:6400
entry 0x400806a8
Starting SD Card
E (4147) sdmmc_sd: sdmmc_check_scr: send_scr returned 0xffffffff
SD Card Mount Failed
No SD Card attached

Here is a diagram of the pins used by the SD card and Camera. Although I have nothing hooked up to them currently

try SD_MMC.end() before deep sleep

Still fails. @Juraj. I had actually tried stop, quit, exit.. and a few others. But yes, it still fails when I use SD_MMC.end() before deep sleep begins. I will try it now with 5 volts though. EDIT: it also fails on 5 volts

You need to initialize SD_MMC to 1 bit mode (by default 4 bit mode) this way the microsd is slow, but you free up 3 pins, GPIO4 too. I had this problem to write on SD when used GPIO4 to switch on/off the flash led.

if (!SD_MMC.begin("/sdcard", true)) {  // 1 bit mode
    Serial.println("SD Card Mount Failed !!!");
    return;
}
YOUR CODE HERE ...

After this I can use GPIO12 as pullup input (tested on my sketch), when it goes to GND the camera will take the frame and save it to microsd (and even send it over TCP socket to Android device and my PC that save to storage memory and show it :D).
GPIO16 don't worked here, it work just one time, then remains LOW and can't be reused.
Note that I do not use sleep function, just check in the loop() the state of GPIO12 to trigger a camera shot.

The code I posted forces GPIO4 to hold its value in this line:
rtc_gpio_hold_en(GPIO_NUM_4);
This pin is used for SD card interface. I needed to un-hold it after deep sleep wakeup if I wanted to use the pin again.

why do you use for SD card the same pin as used for cam flash LED?

I think it is part of the configuration of the camera. I.E. the LED is part of the camera config? I am not positive. I could use help understanding the pins because I want to use one of them to trigger a reset from code. I am not sure which pin to use however. Here is the tutorial I am following. I am trying to add a PIR sensor to this and reset the board. https://randomnerdtutorials.com/esp32-cam-take-photo-save-microsd-card/?unapproved=383075&moderation-hash=09b851163bbdb63c7d8f69240de09a06#comment-383075

Nevermind I was able to get it working using a pull down circuit to pin 13


text:
The current direction for digital output pins
I am new to Arduino. The digital pins can be configured as output (https://www.arduino.cc/en/Tutorial/DigitalPins) for triggering some sensors. I am now setting a digital (output pin), say no. 7,which is connected to the in1 pin of a SRD relay (https://blog.siliconstraits.vn/relay-what-is-it-and-how-to-use-it/):

I am not very clear about the direction of current flowing in the wire connecting the arduino digital pin to in1. To my understanding, when digitalWrite(pin, HIGH), no current flow into the arduino pin, the relay is not triggered, while digitalWrite(pin, LOW), the current flow into the arduino, and the relay is triggered. Please correct me if I am wrong. Thanks.

You are not driving the relay directly, are you?

I updated the post.

In your question, you mention connecting the Arduino to a relay, yet in the figure, you show a relay board. That's not the same! Please clarify. If using a relay board, please link to the datasheet or the supplier's product page.

I consider using a diode in my circuit, so I need to the current flow direction.

what would be the purpose of the diode? ... how would it be connected?

I want to put a diode between the signal pin of the relay and the digital output pin of arduino. So I wonder if the current flows into or from the digital pin.

you did not answer my first question

The relay board in the picture has a transistor on it that turns on the (blue) relay. The Arduino pin only turns on the transistor, which in then turns on the relay. The transistor makes it so that only a small amount of current is needed from the Arduino pin. This is because the coil in the relay requires more current that the Arduino pin can (safely) provide.

When you set a pin to HIGH then that pin will provide 5V.  When you set a pin to LOW then that pin will be set to 0 volts.  Which direction the current flows depends on what is at the other end of the wire.  Current always flows from higher voltage to lower voltage.  If you set a pin to HIGH and the thing it is connected to is at ground then current will flow out of the pin towards ground.  If you set a pin to HIGH but the thing it is connected to is already at 5V then no current flows.  If you set a pin to LOW and the thing it is connected to has some positive voltage then current will flow to the pin.  If you set the pin to HIGH (5V) but the thing it is connected to has more voltage than that (say 10V) then current will flow towards the lower voltage and into the pin, probably damaging the Arduino in the process.


text:
Is this the right way to blink a character on LCD?
The code is this:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

unsigned long blinkTime = 0;
int ValueA = 22;
String placeHolder = "  ";

void setup() {
  lcd.begin();
}

void loop() {
  lcd.setCursor(7, 0);
  if (millis() - blinkTime > 2000) {
    lcd.print(ValueA);
    blinkTime = millis();
  }
  if (millis() - blinkTime > 1000) {
    lcd.print(placeHolder);
  }
}

The I2C LCD library have a lcd.blink() function but it seems that only blinks a "cursor".
The problem with above code is the placeHolder, what if ValueA gets bigger than 2 digits?
Is there a better way to blink a value on LCD?

tip: lcd.setCursor(7, 0); is in both if blocks ... use it before the first if instead

@jsotola Done, thanks.

write a function that accepts three parameters ... boolean show, byte position and int value .... value is the data to display ... position is location of displayed data ... show if true, display data, if false, display spaces ..... show is set by a timer function at the beginning of loop()

@jsotola I've never wrote a function before, can you please post an example of what you just described?

google arduino functions ... https://www.arduino.cc/en/Reference/FunctionDeclaration

The LCD module has this feature built in. There is no need to implement yourself. Call lcd.blink(); and the current cursor position will blink.

it's blinking the cursor, i want to blink the character...!

Instead of redrawing you could periodically turn the display on and off.

@MikaelPatel turning the display on off? what do you mean?

You could use the back-light control instead of rewriting the display to create the illusion of blinking the text (all).

@MikaelPatel but that will blink the whole screen not a 2 or 3 digit character, right? plus i want to keep the backlight ON...

To blink a number (alternate between the number and empty space(s)), you could try the BlinkLCD class in this sketch. It only works with numbers from 0 to 4294967295 or text (char array, 16 characters max). It does not work with floating point numbers.
// 4540 bytes.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

class BlinkLCD{

  private:

    byte m_blinkState, m_startPosition, m_dataLength;
    unsigned long m_dataToBlink, m_previousMillis, m_blinkRate;
    char m_text[16 + 1];

  public:

    BlinkLCD(): m_blinkState(0), m_startPosition(0), m_dataLength(0),
                m_dataToBlink(0), m_previousMillis(0), m_blinkRate(500),
                m_text(){}

    void Update(){

      unsigned long m_currentMillis = millis();

      if(m_currentMillis - m_previousMillis >= m_blinkRate){

        byte m_row = 0;
        m_blinkState = !m_blinkState;
        m_previousMillis = m_currentMillis;

        if(m_startPosition > 15){
          m_startPosition -= 16;
          m_row = 1;
        }

        lcd.setCursor(m_startPosition, m_row);

        if(m_blinkState){
          if((unsigned)strlen(m_text) > 0){
            lcd.print(m_text);
          }
          else{
            lcd.print(m_dataToBlink);
          }
        }
        else{
          for(byte i = 0; i < m_dataLength; i++){
            lcd.print(" ");
          }
        }
      }
    }

    void SetBlinkRate(unsigned long blinkRate){
      m_blinkRate = blinkRate;
    }

    void SetNumber(unsigned long dataToBlink){
      m_dataToBlink = dataToBlink;
    }

    void SetLength(byte dataLength){
      m_dataLength = dataLength;
    }

    // LCD top row, columns 0 - 15
    // LCD Bottom row, 16 - 31
    void SetStartPosition(byte startPosition){
      m_startPosition = startPosition;
    }

    void SetText(char text[]){
      strcpy(m_text, text);
    }

};

BlinkLCD TopRowLCD;
BlinkLCD BottomRowLCD;
BlinkLCD BottomRowLCDtext;

void setup(){
  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.print("Temperature 35 C");
  lcd.setCursor(0, 1);
  lcd.print("Num = 4294967295");
}

void loop(){

  // Simulate sensor data.
  static byte counter = 35;
  static unsigned long previousMillis = 0;
  unsigned long currentMillis = millis();

  // Update the temperature reading every 2 seconds.
  if(currentMillis - previousMillis >= 2000){
    previousMillis = currentMillis;
    counter++;
    if(counter > 45){counter = 35;}
    lcd.setCursor(12, 0);
    lcd.print(counter);
  }

  // Blink the temperature reading if it's over 40 C.
  if(counter > 40){
    TopRowLCD.SetNumber(counter);
    TopRowLCD.SetStartPosition(12);
    TopRowLCD.SetLength(2);
    TopRowLCD.SetBlinkRate(250);
    TopRowLCD.Update();
  }

  // Blink a number on the second row of the LCD
  // with a default blink rate of 500ms ON, 500ms OFF.
  BottomRowLCD.SetNumber(4294967295);
  BottomRowLCD.SetStartPosition(22);
  BottomRowLCD.SetLength(10);
  BottomRowLCD.Update();

  // Blink some text with at the default blink rate.
  BottomRowLCDtext.SetText("Num");
  BottomRowLCDtext.SetStartPosition(16);
  BottomRowLCDtext.SetLength(3);
  BottomRowLCDtext.Update();

}


text:
What is the default setting for a digital output pin
With digitalWrite(pin_number,value), we can set an output pin as HIGH or LOW. But if only coding pinMode (pin_number, OUTPUT), what is the default state for the pin pin_number, LOW or HIGH? It is noted that: Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. Does that mean the pin will be in the state LOW?

neither, they are HI-Z ... all pins are set as input with pullup resistors disabled ... that means that they are seen as floating (disconnected) ... any pin that has an external pullup or pulldown resistor will be pulled in the direction of the resistor

On the AVR-based Arduinos at least, pins start in the INPUT, i.e. high
impedance state. If you then pinMode(pin, OUTPUT);, the pin turns to
OUTPUT LOW. Note, however, that if you first set the pin to
INPUT_PULLUP, and then to OUTPUT, the pin ends up in the
OPUTPUT HIGH state.
Sometimes you want to control the state the pin will have right when
it's turned to OUTPUT. You may for example simulate an open collector
output by switching between INPUT (or INPUT_PULLUP) and OUTPUT
LOW, while avoiding the OUTPUT HIGH state. In this case, a safe
idiom is to set the output level before switching the pin to OUTPUT,
e.g.
// Set pin to OUTPUT LOW without going throught the OUTPUT HIGH state.
digitalWrite(pin, LOW); // do this first
pinMode(pin, OUTPUT);

A side effect of performing a digitalWrite() on a pin that is not set
to OUTPUT is that the pin gets switched to either INPUT (if writing
LOW) or INPUT_PULLUP (if writing HIGH). This is an idiosyncrasy of
the AVR IO ports you should probably not rely on if you want your code
to be readable or portable.
Reference: the source code of pinMode() in the Arduino
core, and the datasheet of the relevant MCU. See for example the section
Ports as General Digital I/O in the ATmega328P’s datasheet.

I've had a similar issue with an ATTINY85 powered DIGISPARK board.
I was getting a glitch when setting a pin to OUTPUT and the driving it HIGH immediately. Looked something like this:
CH1:
pinMode(ch1, OUTPUT);          // it is at this line that ch1 becomes LOW
digitalWrite(ch1, LOW);        // technically redundant since ch1 pin already driven LOW
CH2:
pinMode(ch2, OUTPUT);          // at this point ch2 goes LOW
digitalWrite(ch2, HIGH);       // and only goes HIGH once this instruction executes

The solution that mitigated the above glitch in my case (ATTiny85 / Digispark Board) was, as Edgar Bonet pointed out above, going through the INPUT_PULLUP phase:
pinMode(ch2, INPUT_PULLUP);
pinMode(ch2, OUTPUT);
digitalWrite(ch2, HIGH);


text:
Control relay with both Arduino and DAQ at the same time
I want to control a relay with both Arduino and DAQ. Arduino is used as an embedded  device for the control, while the DAQ is hooked up with a computer and performs the control with a user interface. Here is below a schematic of the circuit wiring for the control:

The two signal pins of the relay are connected with the digital pins of Arduino and DAQ. For some reasons, when Arduino comes into play, the control via DAQ cannot be achieved. If only Arduino or DAQ is connected to the relay, there is no problems with the control.
My plan here is, mstly, to let Arduino to instruct some tasks. In some special cases, I want to have the control with DAQ. Anyone can debug my circuit above? Thanks!

Are the control lines active low or active high? In other words, from the Arduino do you digitalWrite(portnum, HIGH) or LOW? You might be able to solve this with a pair of diodes.

I guess, that you drive the digital pin of the Arduino directly with digitalWrite() for HIGH and LOW and that the DAQ does the same (I didn't researched this).
In that case your circuit is dangerous for the devices. As long, as they both output the same, everything is ok. But take the case, that the Arduino is driving it's pin HIGH, while the DAQ driving it LOW. That would be a short through the pin driving circuit's of both devices and most likely the flowing current will exceed the maximum current rating of the pin. This can fry the involved pins hardware or even the complete devices. You get some kind of race condition here: The device, that can handle drain/source more current will be the winner.
In general you have to implement rules, how the devices should work together. Do you need the actions from the DAQ to be executed no matter what the Arduino does? Or should the Arduino be the master here? Or something inbetween? It is not clear, what do you need here.
I will give you 2 suggestions about possible ways:

You could control the relay only with the Arduino. The DAQ can be connected to a digital input of the Arduino (so that it can sense the DAQ's output state) and in the Arduino code you can implement all the logic you need to drive the relay to your liking.
You could define an idle state of your relay input and set it with a pullup or pulldown resistor. It will ensure, that the relay input is at the defined idle state, as long as no device is driving the line to the opposite state. For this you need the devices outputs to be high impedance (on the Arduino this means the pin is configured as input; for the DAQ you need to know yourself or research it).
Let's say the idle state would be HIGH. We would connect the relay pin with 5V through a high resistor (this is the pullup resistor) (maybe 10k, the value is not critical). Both devices can be connected directly. If one device needs to change the state to LOW, it can drive it's output pin actively low, forcing the relay pin to also go to LOW. If it doesn't need the state to be LOW anymore, it should put it's pin into high impedance mode. The pullup resistor will pull the state to HIGH again. You can also add relatively low resistors between the devices to protect against damages from accidentally driving active HIGH while the other is LOW (These can be calculated from the maximum current rating for the pins; 20mA for the Arduino). This kind of logic is often called open drain logic.

simulate this circuit – Schematic created using CircuitLab
If the DAQ cannot put it's pins to high impedance, you can setup that circuit yourself with a single MOSFET:

simulate this circuit
If you use this circuit on both devices, you don't need the small resistors anymore.

The second possibility already implements a specific logic. You need to decide if this logic is good for you. You can invert it's logic (idle state LOW). Personally I would go with the first option, because it is easier and more flexible.

the signal pin is only TTL logic. almost no current.

Do you mean the pin of the relay module? Then yes, it is. But when you directly connect the 2 output pins of the devices to the same relay module pin, you can get a strong cross current (from one device to another, not through the relay pin). That is the problem that I've described. Is there something wrong with it?

sorry. no problem, you are right.


text:
DigiSpark AT Tiny85 compile problem?
Friend asked me to find problem with compilation for his DigiSpark AT Tiny85 board.
We are trying to compile sketch from here:
https://forum.arduino.cc/index.php?topic=314773.0
But with no luck - there is something mixed in headers or configuration and I do not know what exactly.
This ISR does not compile:
ISR(TIMER1_OVF_vect) {       //timer1 overflow
First there were some errors like TCCR1 = 0; not defined in this sketch, then after playing with #define __ AVR_ATtiny85__, #undef _AVR_IOXXX_H_ and replacing avr/io.h with iotn85.h errors like multiple definition of __vector_x(?) came. Commenting out this line:
//attachInterrupt(0,zeroCrossingInterrupt, FALLING)
helped, but now even this one works, but ISR not.
I know there is a lot of caches and you do not see what is going on behind curtains, but I am quite lost yet...
Maybe there is also problem I have multiple installs in different dirs, but do not know how to clean old ones (1.6.5-r2) and at the end both work same way now, my latest fresh installed is 1.8.9.
Does anyone have any experiences with or some working demo sketch using both compare match and overflow ISRs ?
Edit
Setup info
This board selected (...\AppData\Roaming\Arduino15\packages\digistump\hardware\avr\1.6.7\boards.txt):
digispark-tiny.name=Digispark (Default - 16.5mhz)
digispark-tiny.upload.using=micronucleusprog
digispark-tiny.upload.protocol=usb
digispark-tiny.upload.tool=micronucleus
digispark-tiny.upload.maximum_size=6012
digispark-tiny.build.mcu=attiny85
digispark-tiny.build.f_cpu=16500000L
digispark-tiny.build.board=AVR_DIGISPARK
digispark-tiny.build.core=tiny
digispark-tiny.build.variant=digispark
digispark-tiny.upload.wait_for_upload_port = false
digispark-tiny.upload.use_1200bps_touch = false
digispark-tiny.upload.disable_flushing = false

And these are available:
(...\AppData\Roaming\Arduino15\package_digistump_index.json)
...
"boards": [
  {
    "name": "Digispark (Default - 16.5mhz)"
  },
  {
    "name": "Digispark Pro (Default 16 Mhz)"
  },
  {
    "name": "Digispark Pro (16 Mhz) (32 byte buffer)"
  },
  {
    "name": "Digispark Pro (16 Mhz) (64 byte buffer)"
  },
  {
    "name": "Digispark (16mhz - No USB)"
  },
  {
    "name": "Digispark (8mhz - No USB)"
  },
  {
    "name": "Digispark (1mhz - No USB)"
  }
],
...

Edit 2
Fresh install attempt on W10
Few more links - 2nd manual here:
https://www.electronicshub.org/getting-started-with-attiny85/
http://digistump.com/package_digistump_index.json
have to be translated to
https://raw.githubusercontent.com/digistump/arduino-boards-index/master/package_digistump_index.json
https://downloads.arduino.cc/arduino-1.8.9-windows.zip
W10
When installing shows error downloading (timeout?):
http://downloads.arduino.cc/tools/avr-gcc-4.8.1-arduino5-i686-mingw32.zip
Downloaded by hand to (there was empty file of this name):
...\AppData\Local\Arduino15\staging\packages\
avr-gcc-4.8.1-arduino5-i686-mingw32.zip
...\AppData\Local\Temp\arduino_build_139604\core\core.a(wiring.c.o): In function `__vector_4':
...\AppData\Local\Arduino15\packages\digistump\hardware\avr\1.6.7\cores\tiny/wiring.c:93: multiple definition of `__vector_4'
...\AppData\Local\Temp\arduino_build_139604\sketch\sketch_jun28a.ino.cpp.o:...\arduino-1.8.9\SketchBook\sketch_jun28a/sketch_jun28a.ino:60: first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Digispark (Default - 16.5mhz).
...\AppData\Local\Arduino15\packages\digistump\hardware\avr\1.6.7\cores\tiny\core_build_options.h (not found that file in arduino dir):
/*=============================================================================
  Build options for the ATtiny85 processor
=============================================================================*/

#if defined( __AVR_ATtiny25__ ) || defined( __AVR_ATtiny45__ ) || defined( __AVR_ATtiny85__ )
#define __AVR_ATtinyX5__
#endif

#if defined( __AVR_ATtinyX5__ )

/*
  For various reasons, Timer 1 is a better choice for the millis timer on the
  '85 processor.
*/
#define TIMER_TO_USE_FOR_MILLIS                   1

Btw made best compression and speed-up of Adafruit fonts (to aprox. 1/2 better than LZW) and C++ .Net simulator for old AT Mega project setup if someone interested (it compiles Arduino code directly, but few files mocked and does not work in all versions - engine "black magic" changes often.

The code from the site seems ok. From the error message it seems, as if you are not choosing the correct board type in the Arduino IDE. Since the ATTiny85 is not in the standard core library: What core for ATTiny do you have installed?

He sent me a link https://www.instructables.com/id/Digispark-DIY-The-smallest-USB-Arduino/?%EF%BB%BF how to setup, thought I used the same, but remember I selected Default 16.5MHz - maybe from manual from a different page and now I see there is mentioned Tiny core ?? Will check that later too - not sure if there was this option. Did not installed drivers as I do not have the module and there was nothing related in that zip.

More info added to question, checked all boards, Tiny85 mentioned also @all 3 non-pro versions.

Please look into the file "arduino folder/packages/digistump/hardware/avr/1.6.7/cores/tiny/core_build_options.h". What number is used for the #define TIMER_TO_USE_FOR_MILLIS?

Not sure if proper section is selected in the file, but in theory 1, there are only 0/1 for 3 different CPUs groups (info from 1st install now).

The problem is the following:
The digispark core already implements the TIMER1_OVF_vect ISR (Timer1 Overflow Interrupt). Since you have a 1 for the #define TIMER_TO_USE_FOR_MILLIS, Timer1 will be used for counting the millis() value in the background. For this the Timer 1 Overflow interrupt is needed.
The code, that you copied from that site, does not anticipate, that you might use a core, that already implements the interrupts. It is written for a generic ATtiny85, not specifically for the Digispark version.
What you can do to solve the problem:

You can use Timer0 for your code, keeping the Digispark core untouched. You can change all registers from Timer1 to Timer0 (by replacing the 1 with a 0). Additionally you need to replace TCCR1 with TCCR0B, because for Timer0 that's the register, that set's the prescaler (and turns the timer off if zero is written to it). Also you need to consider, that Timer0 has other prescaler settings. So the line TCCR1 = B00001011; in zeroCrossingInterrupt()  must be changed to TCCR0B = B00000101;. That will set the prescaler to 1024 as mentioned in the comment. The resulting code compiles fine for me with the digispark core (though I have not tested it's functionality).
You can set the Digispark core to use Timer0 for millis(), by changing the definition of TIMER_TO_USE_FOR_MILLIS in the Attiny85 section of the file arduino_folder/packages/digistump/hardware/avr/1.6.7/cores/tiny/core_build_options.h to the value 0 instead of 1. If you do this, the original sketch compiles fine. Though the comment before that build options states, that Timer1 is better for millis() "for various reasons", which is not very specific. You can try, if it works good for you.
You can use another Attiny core. Though you might have to change it too, to accomodate for the unusual clock frequency fo 16.5MHz (most cores I have seen have 16, 8 and 1MHz). That might be as easy as changing the value of the defined clock speed in the cores files, but I'm not sure about that.

Excellent ! Will try it, hope also he will understand it as non-professional programmer and accept your answer. You can teach how to fight with this insane system 4 dummies ;-) You know making things simple often make them tangled...

Btw in case you will need to reduce GFX fonts size twice and speed up printing or compile and run Arduino + LCD code on PC, check my Github - lib maintainers defend against improvements.

When I changed the millis value for 1 to 0, the compile error disappeared but the program did not load properly.
I tried to load a simple blink blink sketch, it can  not load any more. It doesn't seem to communicate anymore ! Anyway this is probably a "feature" not a bug - bad architecture concept...

The upload has nothing to do with the compilation. You just are seeing another problem. I guess you are seeing some "programmer is not responding" error. Try google it, because this common error was answered several times on this site

Another simple option - rewrite or remove the ISR in wiring.c:
...\AppData\Local\Arduino15\packages\digistump\hardware\avr\1.6.7\cores\tiny\wiring.c
For example after changing like this was able to compile without problems.
Simplest solution would be to put that code to my ISR too or call one from another.
#ifdef nothing
// bluebie changed isr to noblock so it wouldn't mess up USB libraries
ISR(MILLISTIMER_OVF_vect, ISR_NOBLOCK)
{
  // copy these to local variables so they can be stored in registers
  // (volatile variables must be read from memory on every access)
  unsigned long m = millis_timer_millis;
  unsigned char f = millis_timer_fract;

/* rmv: The code below generates considerably less code (emtpy Sketch is 326 versus 304)...

  m += MILLIS_INC;
  f += FRACT_INC;
  if (f >= FRACT_MAX) {
    f -= FRACT_MAX;
    m += 1;
  }
...rmv */

  f += FRACT_INC;

  if (f >= FRACT_MAX)
  {
    f -= FRACT_MAX;
    m = m + MILLIS_INC + 1;
  }
  else
  {
    m += MILLIS_INC;
  }

  millis_timer_fract = f;
  millis_timer_millis = m;
  millis_timer_overflow_count++;
}
#endif

If you rename wiring.c and restart editor, you get main.cpp:5: undefined reference to `init' error, there is that "crappy" heart of arduino:
#include <WProgram.h>

int main(void)
{
    init();

    setup();

    for (;;)
        loop();

    return 0;
}

WProgram.h starts with:
#ifndef WProgram_h
#define WProgram_h

#include <stdlib.h>
#include <string.h>
#include <math.h>

#include <avr/interrupt.h>

#include "core_build_options.h"
#include "core_pins.h"
#include "wiring.h"
...

And init of that ATtiny85 (inside wiring.c) evn looks like this:
void init(void)
{
  // clock calibration stuff
  // recalibrate clock if it was calibrated by bootloader (like micronucleus)
  #if F_CPU != 16500000L
    if (OSCCAL != read_factory_calibration()) {
      // adjust the calibration down from 16.5mhz to 16.0mhz
      if (OSCCAL >= 128) {
        // maybe 8 is better? oh well - only about 0.3% out anyway
        OSCCAL -= 7;
      } else {
        OSCCAL -= 5;
      }
    }
  #endif

  // TODO: detect if fuses set to PLL, regular internal oscillator or external and change behaviour in this next section...
  #if F_CPU < 16000000L
    cli();
    CLKPR = 0b10000000;
    #if F_CPU == 8000000L
      CLKPR = 1; // div 2
    #elif F_CPU == 4000000L
      CLKPR = 2 // div 4
    #elif F_CPU == 2000000L
      CLKPR = 3; // div 8
    #elif F_CPU == 1000000L
      CLKPR = 4; // div 16
    #elif F_CPU == 500000L
      CLKPR = 5; // div 32 = 500khz
    #elif F_CPU == 250000L
      CLKPR = 6; // div 64 = 250khz
    #elif F_CPU == 125000L
      CLKPR = 7; // div 128 = 125khz cpu clock
    #else
      #warning "Cannot prescale chip to specified F_CPU speed"
    #endif
  #endif

  // this needs to be called before setup() or some functions won't work there
  sei();

  // In case the bootloader left our millis timer in a bad way
  #if defined( HAVE_BOOTLOADER ) && HAVE_BOOTLOADER
    MillisTimer_SetToPowerup();
  #endif

  // Use the Millis Timer for fast PWM
  MillisTimer_SetWaveformGenerationMode( MillisTimer_(Fast_PWM_FF) );

  // Millis timer is always processor clock divided by MillisTimer_Prescale_Value (64)
  MillisTimer_ClockSelect( MillisTimer_Prescale_Index );

  // Enable the overlow interrupt (this is the basic system tic-toc for millis)
  MillisTimer_EnableOverflowInterrupt();

  // Initialize the timer used for Tone
  #if defined( INITIALIZE_SECONDARY_TIMERS ) && INITIALIZE_SECONDARY_TIMERS
    initToneTimerInternal();
  #endif

  // Initialize the ADC
  #if defined( INITIALIZE_ANALOG_TO_DIGITAL_CONVERTER ) && INITIALIZE_ANALOG_TO_DIGITAL_CONVERTER
    ADC_PrescalerSelect( ADC_ARDUINO_PRESCALER );
    ADC_Enable();
  #endif
}

I had similar problem. I removed functions loop() and setup() and I used classic C construction with main() function and it started to work. (I think loop() and setup() enables using of other functions like delay() - and it uses timer - only my hypothesis).


text:
analogRead Function AC Voltage Reading Capabilities
Usually when you sense AC voltage, you get a sinusoidal waveform. However, for AC voltage sources, Arduino analogRead ( ) only presents positive voltage values. So what's basically happening? Is it skipping half the cycle where the voltage is negative. If so, how can I account for that when I try to use the voltage values to calculate for total electrical energy generated by the source (piezoelectric film) and avg. power?

I guess that you are showing the voltages there directly calculated from analogRead() and that you connected the AC voltage directly to the analog input (and it's ground with the Arduino's ground).
The reference for every communication/voltage measurement/digital input is ground. Naturally the Arduino can only measure voltages inside of it's own supplied voltage range, meaning 0 to 5V for the Uno. If you apply a negative voltage (relative to ground), you will measure a voltage of 0V. You can even damage the microcontroller, if the negative voltage is too high.
If you have negative and positive voltages, you should offset the signal at the analog input pin, so that the resulting signal stays in the range from 0 to 5V. You can do this with a simple voltage divider. Use two resistors with the same value (for example 5kOhm), so that you will get a new zero point at 2.5V. The AC signal will then variate around that value.

For what is happening inside the microcontroller:
The ADC is responsible for measuring the voltage. For this the voltage on the analog input pin will first be sampled (loaded onto an internal condensator) and then step by step compared to the voltages, that the ADC generates by dividing the supply voltage range into 1024 distinct values (10 bit). Again the reference, to which the voltage is measured/compared, is ground. It cannot generate negative voltages, thus cannot compare them.


text:
Serial Enable Maxim RS485 Pin
If I want to use a MAXIM 485 for a RS485 communication, is there any option to include the Control DE and RE' pin in a natural manner in the code, instead changing the control pin everytime I made a Serial.print()?
Should I overload the HardwareSerial object in order to add those pin operations everytime?

No, there isn't - you have to do it manually. And don't forget to flush.
You could inherit HardwareSerial if you really wanted - or just write a couple of functions to do the sending and controlling of the DE pin.

Should i use a slight delay and distinct signals for controlling the DE and RE' pins? Or it is enough to join them in the design?. When should I have different signals for them?

I usually tie them together. And no need for a delay normally.

The only time you might want separate control of directions is if you are doing fancy collision detection by reading what you're sending and seeing if it matches what you sent.