text:
How to listen to multiple server ports with ESP8266?
I'm using WeMos D1 R2. I'm trying to listen to both ports 1992 and 1993. This is my current code:

    #include
WiFiServer server_1992(1992);
WiFiServer server_1993(1993);

void setup() {
    Serial.begin(9600);
    WiFi.begin("MySSID", "MyPassword");
    while (WiFi.status() != WL_CONNECTED){
        delay(500);
        Serial.print(".");
    }
    Serial.println(" connected");

    server_1992.begin();
    server_1992.setNoDelay(true);
    server_1993.begin();
    server_1993.setNoDelay(true);
}

void check_server(WiFiClient* client, WiFiServer* server, const char* text){
    if (client->connected()) {
        if (client->available()){
            unsigned char c[250];
            client->readBytes(c, 1);
            Serial.print(c[0]);
            Serial.print(" ");
        }
    } else {
        client->stop(); //Adding it here like Juraj said. Not tested.
        *client = server->available();
        if (*client) Serial.print(text);
    }
}

void loop() {
    WiFiClient client_1992, client_1993;
    while (1){
        check_server(&client_1992, &server_1992, "1992 connected \n");
        check_server(&client_1993, &server_1993, "1993 connected \n");
    }
}

The problem is when the client(s) disconnect from the hotspot, my code keeps waiting for data forever without trying to acquire new client (with client = server->available();).
Solution: for now I ask the client "Hey are we still connected?" every few seconds and manually kick the client out if it doesn't reply.
More on this
Sorry if it's wrong to link other question here, I just hope people who have the same problem as mine can find the solution.

stop the client if it is not connected

If i understand it correctly, you mean close the client from the client side right (not the server side)?
The disconnection happens when my phone turn off / disconnect from wifi so I don't think I can close the connection properly?

no. stop the esp8266 side of the socket when it is not connected, before you ask if new client is available. there are more tcp states of the connection and after the client side disconnects, it is not established (what connected tests), but not closed either

I will test it when I can get back home, is it like the one I added to the code ?(before the *client = server->available();   )

yes, that is what I meant. I am not sure if it helps, so I do not write it as answer until you test it. I use extensively esp8266 from Atmega over WiFi Link at it has it's own tricks. there the stop() solves this kind of problem

Didn't work.It seems like "client->connected()" isn't doing too well checking the connection. The client->connected() seems to still think it's connected when I turn off my phone WiFi.

You could try to read all buffered data before stop(), because connected() checks if data are available in buffer: while (client.read() != -1);

It doesn't work.
For now I will use a timer to check if the client haven't sent any data in the last 10 seconds and kick the client out that way my server won't be stuck forever in the loop. Ugly solution.

it is not ugly for unexpected disconnections

Use the    client.status()    function to check if the client is connected
Returns 4 if connected and 0 if not
I don't have detailed information about its use and I found it by chance
You can check other output modes of this function
If you get any other information, please let me know.
void loop()
{

  WiFiClient client_8080;
  WiFiClient client_8081;

  delay(200);
  Serial.println(client_8080.status());
  Serial.println();
  Serial.println();

  while (1)
  {

    if(client_8080.connected())
    {

      delay(200);
      Serial.println(client_8080.status());
      Serial.println();
      Serial.println();

      while (client_8080.available())
      {

        delay(200);
        Serial.println(client_8080.status());
        Serial.println();
        Serial.println();

        Serial.print(client_8080.available());
        char Buffer_8080 = client_8080.read();
        Serial.println(Buffer_8080);
        client_8080.println(Buffer_8080);

      }

       while (Serial.available())
      {
        client_8080.print(Serial.available());
        client_8081.print(Serial.available());
        char Buffer_Serial = Serial.read();

        client_8080.println(Buffer_Serial);
        client_8081.println(Buffer_Serial);
      }

    }else if (!client_8080.connected())
    {

       Serial.println(client_8080.status());
       Serial.println();
       Serial.println();

      client_8080 = server1.available();

       Serial.println(client_8080.status());
       Serial.println();
       Serial.println();

      Serial.println("server lisening to port 8080 ");

    }

    //_______________________________________________

    if(client_8081.connected())
    {
      while (client_8081.available())
      {

        Serial.print(client_8081.available());
        char Buffer_8081 = client_8081.read();
        Serial.println(Buffer_8081);
        client_8081.println(Buffer_8081);

      }

      while (Serial.available())
      {
        client_8080.print(Serial.available());
        client_8081.print(Serial.available());
        char Buffer_Serial = Serial.read();

        client_8080.println(Buffer_Serial);
        client_8081.println(Buffer_Serial);
      }

    }else if (!client_8081.connected())
    {
      client_8081 = server2.available();

      Serial.println("server lisening to port 8081 ");

    }

  }
}


text:
Send HTTP request from Arduino UNO+ESP8266
I am trying to send an HTTP request from from an Arduino UNO through an ESP-01 connected by Serial.
Communication with the ESP and connection to the AP work fine. But when i try to send an HTTP request to a server, it fails with a strange response from the ESP:

What are those strange characters coming from the ESP ?
(Note that other characters are mistaken as well, like the "http://xxx.col" instead of "http://xxx.com")
Here is the code I am using:

#include <SoftwareSerial.h>
#define RX 10
#define TX 11
String AP = "xxx";
String PASS = "xxx";
String HOST = "\"http://xxx.com\"";
String PORT = "80";
String tcp = "\"TCP\"";
String field = "field1";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
int valSensor = 1;
SoftwareSerial esp8266(RX,TX);

void setup() {
  Serial.begin(115200);
  esp8266.begin(115200);
  sendCommand("AT",5,"OK");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}
void loop() {
 sendCommand("AT+CIPMUX=1",5,"OK");
 //String connection = "AT+CIPSTART="+ tcp +"," + remoteip + "," + portnum + "\r\n");

 String getData = "GET battery/add.php?RAWVOLT=99&VOLT=99&RAWCURR=99 HTTP/1.0\r\n"; //this is mockup data for testing purpose
 getData += "Host: xxx.000webhostapp.com\r\n"; // add the required header
 getData += "\r\n";

 sendData("AT+CIPSTART="+ tcp +"," + HOST + "," + PORT + "\r\n",150000,true);
 sendData("AT+CIPSEND=0," +String(getData.length()+4),4000,true);

 //sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
 esp8266.println(getData);delay(1500);countTrueCommand++;
 sendCommand("AT+CIPCLOSE=0",5,"OK");
}

 void sendCommand(String command, int maxTime, char readReplay[]) {
   ***similar to sendData below***
 }

 String sendData(String command, const int timeout, boolean debug)
{
    String response = ""; // ESP8266 sendData String
    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {
        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }
    return response;
}

use the WiFiEsp library

the hostname can't contain http://

You can't use SoftwareSerial at 115200 baud. The Arduino is not fast enough to keep up. Either switch to a board with a spare hardware UART or work out how to safely change the baud rate on your version of the ESP-01 to 9600.

@Juraj thanks, i removed the http://

@Majenko I changed to 9600 baud rate, still having the same issue :
`AT+CIPST@RT="TCP","app.⸮Kѡ⸮ͅ⸮⸮⸮嵅⸮⸮⸮⸮⸮b⸮⸮j
ERROR
`

did you change the baud rate of the AT firmware with AT+UART command?

When I try with the AT command, it fails: 1. at command => AT+UART=9600 Fail

AT+UART_DEF=9600,8,1,0,0. send it at 115200 baud. the AT firmware will remember it as default. then switch the SoftwareSerial to 9600 baud

@Juraj: Same response as before: 0. at command => AT+UART_DEF=9600,8,1,0,0 Fail

what is 0. at command =>?

it's nothing, just a comment to make the output easier to read. Basically the ESP fails to execute the AT command.

the response to AT+UART is not important. was it applied? btw. you have CIPMUX but you don't specify linkId with CIPSTART

source: Stack Exchange

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

sort: votes


text:
Not able to control digital pins using commands sent via HC-05 module
I am trying to control the LED on pin13 using the below code but it's not working.
With this code I am able to print to the Serial Monitor but the code has no effect on the any of the digital pins. I am unable to control the LED and so I have gotten stuck and can't advance further. I can't understand why it is happening even if I have excluded the new line from the Bluetooth app that I am using to send the strings and same on the Serial Monitor.
#include<SoftwareSerial.h>          // import the serial library

SoftwareSerial bluetooth(6, 7);     // RX, TX

void setup(){
  Serial.begin(9600);               //set baud rate
  bluetooth.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop(){
  while (bluetooth.available()){
    char ch = bluetooth.read();
    message += ch;
  }

  if(!bluetooth.available()){
    if(message != ""){
      if(message.equalsIgnoreCase("on")){
        digitalWrite(13, HIGH);
      }else{
        digitalWrite(13, LOW);
      }
      Serial.println(message);
      message = "";
    }
  }
}

What is the output of the serial terminal? That is exactly what is reaching the code, so this would help alot. I will update my answer, when you provide more information. Also: How have you connected the HC-05? Did you use a voltage divider for it's RX line? (The HC-05 works with 3.3V and most Arduino boards with 5V) And the if-statement if(!bluetooth.available()) isn't necessary here, because when you are leaving the while loop there is nothing available, unless it is received on this few clock cycle of the execution between.

the serial monitor outputs "on" as 'o' and 'n' in separate lines. bluetooth terminal on my phone doesn't print anything. But the code works fine if I am using the normal (Rx,Tx) pins, the terminal on my phone also prints the strings it sends,that works fine even without the voltage divider. I just don't want to engage the pins(1,2). I don't know if there is a problem with the SoftwareSerial library

the chars come slower over SoftwareSerial and your code doesn't wait for them. if next char is not available immediately  you continue in loop

please elaborate I tried while(blurtooth.available()==0);  to wait for the data but that is not working;

I was basically getting the problem due to some garbage values flowing in and I managed that by using if(message.substring(0,2).equals("on")). and now it works fine

Your logic is a complete mess.  You have:

If a character is available, read it and add it to message.
If another character is available, compare what you have already stored with on.

If it's equal ('o' is not equal to 'on') turn on, otherwise turn off.
Print what you have stored.

Forget what you stored
Go to 1 (a character is still available since you never read it in stage 2).

Instead you need something more like:

If a character is available, read it into a variable.
If the character you read is a line ending character:

Compare your message with 'on' and take appropriate action

If the character you read is not a line ending character:

Add the character to message.

Go to 1.

Note how you only check once if there is a character available, and all your testing is done within that one if block.

so i basically tried that but it's  not working

Comments are not places to dump code.

really srry about that

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


text:
Merging arduino code
I have a project where we need to create a virtual cane for blind people and it will have 3 functions:

Pressure button when pressed will connect to an android phone through HC-06 Bluetooth modulo to an app that I developed and will
can to someone that I defined
Temperature sensor that is attached to a buzzer that will buzz if the
temperature is higher than 40 Degrees
Ultrasonic sensor attached to and vibration motor that will vibrate
if there is any object less than 70 cm from the person.

When I combine the code from the ultrasonic and the temperature sensor, everything works fine, when I add the bluetooth code, nothing works, anyone see the problem? Or could you show me the problem and solveit?
Code without Bluetooth:
int DHT11_PIN=8;
dht DHT;
int buzzer=6;
int trigPin=3;
int echoPin=2;
int motor=7;

void setup(){
  Serial.begin(115200);
  pinMode(DHT11_PIN,INPUT);
  pinMode(buzzer, OUTPUT);
  delay(5000);

  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motor, OUTPUT);
  delay(5000);
}

void loop(){
  Stemperature();
  Sultrassom();
}

// sensor de tempratura e Buzzer-------------------------------
void Stemperature(){
  digitalWrite(buzzer,LOW);
  DHT.read11(DHT11_PIN);
  float t=DHT.temperature;
  Serial.print("Temperature = ");
  Serial.println(t);

  if (t>40){
    digitalWrite(buzzer,HIGH);
    {tone(6,100,20);
    delay(1);
    noTone(1);
    delay(1);
    }
    delay(1000);
    Serial.print("ON T=");
  }else{
    digitalWrite(buzzer,LOW);
    Serial.print("OF T=");
  }
}

//Sensor de Ultrassom e Motor vibração-----------------
void Sultrassom(){
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) * 0.0340;
  Serial.println(distance);

  if (distance < 70){ // se a distância for menor que 70 cm o motor vibra
    digitalWrite(motor,HIGH);// quando a distância for menor que 70 cm
    Serial.print("MOTOR ON=");
  }else{
    digitalWrite(motor,LOW);// quando a distância for maior que 70 cm
    Serial.print("MOTOR OFF=");
  }
  delay(5);
}

Bluetooth Code:
const int buttonPin = 4;     // the number of the pushbutton pin
boolean buttonState;         // variable for reading the pushbutton status

void setup(){
  Serial.begin(9600);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  buttonState = LOW;
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if(buttonState == HIGH) {
    // send char 1 via Bluetooth:
    Serial.println("1");
    delay(20000);
    while (0);
  }
}

In the bluetooth loop you use:
delay(20000);
while (0);

This means you first wait 20 seconds, and while(0) does not do anything (unuseful instruction).
Actually, this results when the button is pressed, it starts the loop again, but you have to merge both codes into one.
I would add the sending of the serial command in the code above, remove the while and see what happens. If you need some delay for debouncing reaons for the button, implement a decent deboucing algorithm instead of the delay of 20000.
And why there are two }} at the end?

while(1); means wait forever while(0); means never wait, which is pointless.

True ... I will change it

No - zero is false :)

Adapted it more clearly

The following code is not tested in any way. It should give you some help, to detect the problems. First you used the same Serial connection for your PC and the Bluetooth module, which leads to problems. Second, you had some delays, which seemed useless. Third your noTone() function didn't matched the right pin. Also I added an Interrupt for the Button. It could be, that your DHT reading need the same Interruptprotection, which I added to the Usonic measurment. Last but not least I replaced your Pin definitions to make it more readable.
// New Include for the bluetooth connection
#include <SoftwareSerial.h>
#include <dht.h>

#define DHT11PIN        8
#define BTRXPIN         10                    // Pay attention to your wiring
#define BTTXPIN         11
#define BUZZERPIN       6
#define TRIGGERPIN      5                     // Changed, to keep an interrupt Pin free !!!
#define ECHOPIN         4                     // Changed, to keep an interrupt Pin free !!!
#define MOTORPIN        7
#define BUTTONPIN       2                     // Changed to an interrupt Pin

dht DHT;
SoftwareSerial bluetooth(BTRXPIN, BTTXPIN);

void setup(){
  Serial.begin(9600);                         // Only once
  bluetooth.begin(9600);                      // Serial connection for the bluetooth module
                                              // Check your needed Baudrate
  pinMode(DHT11PIN,  INPUT);
  pinMode(BUTTONPIN, INPUT);
  pinMode(ECHOPIN,   INPUT);
  pinMode(TRIGGERPIN, OUTPUT);
  pinMode(BUZZERPIN,  OUTPUT);
  pinMode(MOTORPIN,   OUTPUT);
  digitalWrite(BUZZERPIN, LOW);

  attachInterrupt(digitalPinToInterrupt(BUTTONPIN), buttonISR, RISING); // I did not pay attention to bouncing here!!
  // I see no need for 5sec delay, so i cut it out
}

void loop(){
  temperatureMeasure();
  ultraSonicMeasure();
  delay(2000);                                  // 2 sec delay, so it won't measure all the time.
}

float temperatureMeasure(){                     // Added return types
  DHT.read11(DHT11_PIN);
  float t = DHT.temperature;
  Serial.print("Temperature = ");
  Serial.println(t);

  if (t > 40){
    tone(BUZZERPIN,100);
    delay(20);
    noTone(BUZZERPIN);
    Serial.print("ON");
  }else{
    noTone(BUZZERPIN);
    Serial.print("OFF");
  }
  return temperatureMeasure;
}

long ultraSonicMeasure(){
  long duration{0};
  long distance{0};
  noInterrupts();
  digitalWrite(TRIGGERPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGERPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGERPIN, LOW);

  duration = pulseIn(ECHOPIN, HIGH);
  interrupts();
  distance = (duration/2) * 0.0340;
  Serial.println(distance);

  if (distance < 70){
    digitalWrite(MOTORPIN, HIGH);
    Serial.print("MOTOR ON");
  }else{
    digitalWrite(MOTORPIN, LOW);
    Serial.print("MOTOR OFF");
  }
  return distance;
}

// Called when button is pressed
void buttonISR(){
  bluetooth.println("1");                         // Would be better, to put this outside of the ISR, but is is only on character.
}

It worked with some modifications!!!
Thank you :)

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


text:
Sending Simultaneous Data from 2 NRF24L01 Transmitters to 1 NRF24L01 Receiver
I'm using three NRF24L01 transceivers, each connected to one Arduino Nano. One of the NRF24L01's is configured as a receiver, while the other two NRF24L01's are set as transmitters. Firstly, I'm aware that is not possible for two transmitters to send data at once, but what I want to do, basically is to simultaneously display the transmitters' data in the serial monitor in the same time, and row as each other.
The transmitters collect data from the respective sensors attached to it, such as accelerometer and so forth. Both have the same amount of inputs and sensors.
The receiver is plugged in to the computer awaiting the transmission of data from the transmitters.
Everything is fine in the serial monitor when only one of the transmitters are transmitting, however, when both the transmitters are sending data to the receiver, a garbled mess of data could be seen in the jpg file.

What I'm trying to visualize in the serial monitor is this: the sensor values of transmitter 1 and transmitter 2, all placed in the same row every second of transmission. That is the format, because I've written a short Python script that takes the serial data and prints it in a csv file, so the format needs to be preserved.
How do I go about it? I've read about the use of arrays and payloads but I'm relatively unfamiliar with those as it is my first time exploring networking peripherals in Arduino. I hope you could help me. Thank you.
Edit: Here is the left transmitter code:

#include <SPI.h> //libraries para sa nrf24l01
#include "RF24.h" //

#include <Wire.h> // MPU-6050 I2C LIBRARY
#include <I2Cdev.h> //
#include <MPU6050.h> //

#define flex_1 A0 //declaring ng variable tsaka pin assignment ng 5 flex sensors
#define flex_2 A1
#define flex_3 A2
#define flex_4 A3
#define flex_5 A6

MPU6050 accelgyro; // variable ng mpu6050

int16_t ax, ay, az; // variables para accelerometer and gyroscope
int16_t gx, gy, gz;

int pinx=2; // pin assignment ng contact sensors
int piny=3;

RF24 myRadio (8, 9); // CSN AT CE PIN ASSIGNMENT
byte addresses[6] = {"1Node"}; // address ng both transmitter and receiver

// structure para masend ng inorder
struct Pack {
  int data11;
  int data22;
  int data33;
  int data44;
  int data55;
  int accxx;
  int accyy;
  int acczz;

} packet1;

void setup() {

  Serial.begin(9600); // para magamit ang serial monitor
  Serial.println(F("RF24/Simple Transmit data Test"));

  Wire.begin(); //

  accelgyro.initialize(); // para maread ang pin ng mpu6050

  pinMode(pinx, INPUT);
digitalWrite(pinx, HIGH);
pinMode(piny, INPUT);
digitalWrite(piny, HIGH);
/*
    accelgyro.setXAccelOffset(2825);
    accelgyro.setYAccelOffset(457);
    accelgyro.setZAccelOffset(645);
*/
  myRadio.begin(); // nrf24l01
  myRadio.setChannel(108);
  myRadio.setPALevel(RF24_PA_MIN);
  myRadio.openWritingPipe(addresses[1]);
}

void loop() {
  packet1.data11 = analogRead(flex_1);
  packet1.data11=map(packet1.data11, 450, 950, 3000, 4000);
  packet1.data22 = analogRead(flex_2);
  packet1.data22=map(packet1.data22, 450, 950, 3300, 4500);
  packet1.data33 = analogRead(flex_3);
  packet1.data33=map(packet1.data33, 450, 950, 3000, 4000);
  packet1.data44 = analogRead(flex_4);
  packet1.data44=map(packet1.data44, 450, 950, 3000, 4000);
  packet1.data55 = analogRead(flex_5);
  packet1.data55=map(packet1.data55, 450, 950, 3000, 4000);
  packet1.accxx=ax;
  packet1.accyy=ay;
  packet1.acczz=az;

  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  if (myRadio.write(&packet1, sizeof(packet1))) {
    Serial.print(F("flex1 = "));
    Serial.print(packet1.data11);
    Serial.print(F(" flex2 = "));

    Serial.print(packet1.data22);
    Serial.print(F(" flex3 = "));
    Serial.print(packet1.data33);
    Serial.print(F(" flex4 = "));
    Serial.print(packet1.data44);
    Serial.print(F(" flex5 = "));
    Serial.print(packet1.data55);

    Serial.print(F(" accx = "));
    Serial.print(packet1.accxx);
    Serial.print(F(" accy = "));
    Serial.print(packet1.accyy);
    Serial.print(F(" accz = "));
    Serial.print(packet1.acczz);
    Serial.print(F(" con1 = "));

    Serial.println();
  }

  else {
    Serial.print(F("Send failed."));
  }

}

And here is the right transmitter code:
#include <SPI.h> //libraries para sa nrf24l01
#include "RF24.h" //

#include <Wire.h> // MPU-6050 I2C LIBRARY
#include <I2Cdev.h> //
#include <MPU6050.h> //

#define flex_1 A0 //declaring ng variable tsaka pin assignment ng 5 flex sensors
#define flex_2 A1
#define flex_3 A2
#define flex_4 A3
#define flex_5 A6

MPU6050 accelgyro; // variable ng mpu6050

int16_t ax, ay, az; // variables para accelerometer and gyroscope
int16_t gx, gy, gz;

int pinx=2; // pin assignment ng contact sensors
int piny=3;

RF24 myRadio (8, 9); // CSN AT CE PIN ASSIGNMENT
byte addresses[6] = {"1Node"}; // address ng both transmitter and receiver

// structure para masend ng inorder
struct Pack {
  int data1;
  int data2;
  int data3;
  int data4;
  int data5;
  int accx;
  int accy;
  int accz;
  int con1;
  int con2;
} packet;

void setup() {

  Serial.begin(38400); // para magamit ang serial monitor
  Serial.println(F("RF24/Simple Transmit data Test"));

  Wire.begin(); //

  accelgyro.initialize(); // para maread ang pin ng mpu6050

  pinMode(pinx, INPUT);
digitalWrite(pinx, HIGH);
pinMode(piny, INPUT);
digitalWrite(piny, HIGH);
/*
    accelgyro.setXAccelOffset(2825);
    accelgyro.setYAccelOffset(457);
    accelgyro.setZAccelOffset(645);
*/
  myRadio.begin(); // nrf24l01
  myRadio.setChannel(108);
  myRadio.setPALevel(RF24_PA_MIN);
  myRadio.openWritingPipe(addresses[0]);
}

void loop() {
  packet.data1 = analogRead(flex_1);
  packet.data1=map(packet.data1, 450, 950, 3000, 4000);
  packet.data2 = analogRead(flex_2);
  packet.data2=map(packet.data2, 450, 950, 3300, 4500);
  packet.data3 = analogRead(flex_3);
  packet.data3=map(packet.data3, 450, 950, 3000, 4000);
  packet.data4 = analogRead(flex_4);
  packet.data4=map(packet.data4, 450, 950, 3000, 4000);
  packet.data5 = analogRead(flex_5);
  packet.data5=map(packet.data5, 450, 950, 3000, 4000);
  packet.accx=ax;
  packet.accy=ay;
  packet.accz=az;
  packet.con1=digitalRead(pinx);
  packet.con2=digitalRead(piny);

  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  if (myRadio.write(&packet, sizeof(packet))) {
    Serial.print(F("flex1 = "));
    Serial.print(packet.data1);
    Serial.print(F(" flex2 = "));

    Serial.print(packet.data2);
    Serial.print(F(" flex3 = "));
    Serial.print(packet.data3);
    Serial.print(F(" flex4 = "));
    Serial.print(packet.data4);
    Serial.print(F(" flex5 = "));
    Serial.print(packet.data5);

    Serial.print(F(" accx = "));
    Serial.print(packet.accx);
    Serial.print(F(" accy = "));
    Serial.print(packet.accy);
    Serial.print(F(" accz = "));
    Serial.print(packet.accz);
    Serial.print(F(" con1 = "));
    Serial.print(packet.con1);
    Serial.print(F(" con2 = "));
    Serial.print(packet.con2);

    Serial.println();
  }

  else {
    Serial.print(F("Send failed."));
  }

}

And the code for the receiver:
#include <SPI.h>
#include "RF24.h"

RF24 myRadio (8, 9);
byte addresses[][6] = {"1Node"};

int accelgyroscope[3];

int ax, ay, az;
int gx, gy, gz;

int LED_GREEN = A3;
int LED_RED = A2;

struct Pack {
  int data1;
  int data2;
  int data3;
  int data4;
  int data5;
  int accx;
  int accy;
  int accz;
  int con1;
  int con2;

} packet;

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

  myRadio.begin();
  myRadio.setChannel(108);
  myRadio.setPALevel(RF24_PA_MIN);
  myRadio.openReadingPipe(1, addresses[0]);
  myRadio.startListening();

  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_RED, OUTPUT);

}

void loop() {
  if ( myRadio.available())   {

    analogWrite(LED_GREEN, 1023);
    analogWrite(LED_RED, 0);

    myRadio.read( &packet, sizeof(packet) );
    Serial.print("0");
    Serial.print(", ");
    Serial.print(packet.data1);
    Serial.print(", ");
    Serial.print(packet.data2);
    Serial.print(", ");
    Serial.print(packet.data3);
    Serial.print(", ");
    Serial.print(packet.data4);
    Serial.print(", ");
    Serial.print(packet.data5);

    Serial.print(", ");
    Serial.print(packet.accx);
    Serial.print(", ");
    Serial.print(packet.accy);
    Serial.print(", ");
    Serial.print(packet.accz);
    Serial.print(", ");

    Serial.print(packet.con1);
    Serial.print(", ");
    Serial.print(packet.con2);
    Serial.println();

  }
  else
  {
    analogWrite(LED_RED, 1023);
    analogWrite(LED_GREEN, 0);
  }

}

Without seeing your code it's impossible to know what you're doing that makes the output look like that. I think you need to decouple your reception from your printing and update an internal list of values whenever you happen to receive them, and periodically print that list of values as a single unit whenever you deem appropriate.

I already added the codes per your request. What do you mean with "decouple your reception from your printing and update an internal list of values whenever you happen to receive them, and periodically print that list of values as a single unit whenever you deem appropriate."? I'm unfamiliar with those as my Arduino skills are limited.

That code doesn't match the output that you are showing in your image.

I'm sorry I just updated it again

It seems like you are assuming both transmitters are sending at the same rate, and all packets get received. Why do you want to have the data from the two receivers next to each other? I'd put them all on their own line. It might be useful to add a column for the received timestamp.

PS It seems that the left transmitter's packet is different from the right's (no con1 and con2). While the receiver assumes both types of packets are of the same size.

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


text:
Arduino Ultrasonic Sensor and LCD - Help Needed-
I just recently purchased an Arduino Uno 3 and I wanted to make an ultrasonic distance sensor that outputs the readings to a 16x2 LCD. I followed this guide:
http://www.mertarduino.com/using-ultrasonic-distance-sensor-hc-sr04-with-lcd-display-and-arduino/2018/11/22/ but it gave an error when I uploaded the code. The error was: a function definition is not allowed here before '{' token. I don't know too much about Arduinos, so I need help.
Thanks to whoever responds!
Here is the code:

// put your setup code here, to run once:
#include <LiquidCrystal.h> //Please replace the single quote characters ('') with the parenthesis character (<>)

LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters:
(rs, enable, d4, d5, d6, d7)

const int trigPin = 9;
const int echoPin = 10;
long duration;
int distanceCm, distanceInch;

void setup() {

lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

}

void loop() {

digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2;
distanceInch = duration*0.0133/2;

lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distanceCm); // Prints the distance value from the sensor
lcd.print("  cm");
delay(10);
lcd.setCursor(0,1);
lcd.print("Distance: ");
lcd.print(distanceInch);
lcd.print("inch");
delay(10);
}

your comments are broken. please take a coding course

The root of your problem is this bit:
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters:
(rs, enable, d4, d5, d6, d7)

I think in copying-and-pasting you ended up with a line split across two giving you an error. It should read:
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)

You have a similar problem here:
lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display

Again that has split across two lines and should read:
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display

And a third:
lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed

which should be:
lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed

When those three are corrected the code compiles properly.

Why the downvote? Is there something wrong with this answer?

Thanks for the answer! the code now works and I don't know who gave the downvote as I don't actually have an account.

Upvoted; nothing wrong with the answer (as usual).


text:
Problem with powering ublox NEO-6M GPS module
Firstly, I'd like to mention that I'm a beginner. This is the first time I've worked with a GPS module. The serial monitor is completely empty when I upload the following code to my circuit:

#include <SoftwareSerial.h>

// The serial connection to the GPS module
SoftwareSerial ss(4, 3);

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

void loop(){
  while (ss.available() > 0){
    // get the byte data from the GPS
    byte gpsData = ss.read();
    Serial.write(gpsData);
  }
}

Things I might've done wrong and some things I'd like to mention:

As you can see, I connected the module to 5V pin of Arduino but the datasheet says:

The reason why I think this might not be the case is that there are multiple projects on the internet that have used a circuit like mine.
I've placed my module on the window edge so that it can get a good line of sight. I'm yet to try it outdoors.
After reading the datasheet, I tried a potential divider using resistors to get 3.3V and the result is still nothing. I later realized that this was probably a really silly thing to do since I created an unstable supply which is not suitable for the module.
For cold-start conditions, how long can it take to lock to a satellite? I've waited several times for half an hour each time only to get no result in the end. Can it take more than that? Should I wait?
What can I use to supply constant 3.3V to the module? Are there any special power supplies for GPS modules?
Is it possible to tell if my module is damaged just by seeing?

The module may very well be dead now, due to giving it 5V.

But depending on which board the module is mounted on, there might be a voltage regulator that expects 5V. Check the specifications for the board you bought.

A window means that at least 50% of the sky is blocked by the building. The module might not be able to get a signal from enough satellites for a cold start.
A voltage divider only works if there is constant current. As you've noted, you just created an unstable power supply.
The datasheet says 27 s but that is probably with a clear view of the sky.
Next to the 5V pin on the Uno is a 3.3V pin. How about using that?
Visually, no. But the Arduino should be able to communicate with the module if the module still works, regardless if the module has a GPS fix or not.

I've tried that too, forgot to mention. Also, could you please say something about the other points in my question as well?

Tried that after I had initially used the 5V pin.

"But depending on which board the module is mounted on, there might be a voltage regulator that expects 5V. Check the specifications for the board you bought." I know this is a really dumb question but how do I do that?

If the store where you bought the module knows what they sold to you, you could get the information form them. If the store does not know, and you do not now, you're in for quite some detective work.

"But the Arduino should be able to communicate with the module if the module still works, regardless if the module has a GPS fix or not." Does that mean that the serial monitor for the code I uploaded should not give empty output?

That depends on which module board you have, and if it was correctly wired. But yes, the code should give output similar to page 2 in https://www.terraelectronica.ru/pdf/show?pdf_file=%2Fz%2FDatasheet%2FU%2FUART+GPS+NEO-6M+User+Manual.pdf


text:
How to Connect Dc motor with encoder (pololou) with motor shield and Arduino Mega 2560?
I tried to search a bout how to connect plolou motor with encoder to arduino mega and the motor control shield as in those pics  if any one knows how to connect those to each other please tell me

Did you try anything already, or look up a tutorial online perhaps?

A quick look on Pololu's website reveals that:
    Color   Function
  --------  --------------------------------------------
    Red     motor power (connects to one motor terminal)
    Black   motor power (connects to the other motor terminal)
    Green   encoder GND
    Blue    encoder Vcc (3.5 – 20 V)
    Yellow  encoder A output
    White   encoder B output

Thus: Red goes to M1A and Black goes to M1B on the motor shield.
The remaining wires are for the encoder and go to Arduino pins.
Green goes to Arduino GND, Blue goes to 5V, Yellow and White go to the
digital i/O pins of your choice.
Note: Your motor shield has extra 5V and GND pins so you can connect the Blue and Green wires there.


text:
Connect a button to bluetooth board and comunicate with Android
I want to create a small device, just a button that sends its status to an Android application through Bluetooth.
I bought a Bluno Beetle, but the information it exposes to Bluetooth cannot be modified from Arduino code, so I have no way to send the button status to the Android App, rookie mistake I guess.
Could you please tell me which model of arduino+bluetooth should I purchase to do this ?

buy a bluetooth button like this https://www.amazon.com/iBOLT-Bluetooth-distance-Customize-commands/dp/B00R3H4II8

"access features of compatible apps" seems suspicious, also I can´t find anywhere if it can be used on custom Apps.

it is unclear why the Bluno Beetle is unsuitable for your project .... please post the code that you tried .......... the Bluno Beetle is an arduino with a bluetooth module and you are asking about replacing it with another arduino and another bluetooth module

I connected a button to the Bluno Beetle and I want the Android App to know when the button is pushed and when is not. I can´t change the characteristic the Bluno Beetle exposes on the Bluetooth Service from the code, so I cannot send the button status to the Android App.

have you seen  this page? ... https://www.dfrobot.com/blog-283.html

Yes, what I am supposed to be missing ?

many different Bluetooth buttons are in shops.

The beetle supports both acting as HID device or as a serial interface. You can use both ways to interact with a button (though using as HID is better, because you can even control other apps with it).

For your project you can buy cheap Arduino Nano, or even Mini(programmer needed). For BT module buy HM10. It's cheap and it supports Bluetooth Low Energy.

but that is exactly what Bluno Beetle is. a 328p plus CC2540

Why he asked then what he should buy

because he doesn't understand how it works

Hi Juraj,
If you understand how it works, could you explain to me how can I get the status of a button connected to the bluno to an android app connected to the bluno by Bluetooth ?

@Grefu, you must use @ to get a user notified. the manufacturer has examples. jsotola posted a link in comments to  the question


text:
Sending data through esp8266 using arduino
I'm trying to send GPS data using esp8266 using Arduino board. I've used neo-6m receiver and esp8266-01 module. Below is my program using AT commands. The program is successfully compiled and loaded to the Arduino board, but the only output it gives on serial monitor is a simple begin. None of the AT commands are being executed. Not even the module connects to wi-fi. I can't point the error in my code. Please help me find the possible error.
Thank you

#include <TinyGPS++.h>
#include <SoftwareSerial.h>

TinyGPSPlus gps;

String ssid = "JioFi_244DB1D";

String password = "q52fq74c9s";

SoftwareSerial esp(6,7);

SoftwareSerial ss(8,9);

char Lat[12], Lon[12], alt[12],ch;

byte NOS;

byte l;

String webpage;

void reset(){

  esp.println("AT+RST");

  delay(1000);

  if(esp.find("OK"))

    Serial.println("Module Reset");

    }

    void ConnectWifi(){

      esp.println("AT+CIPMUX=1");

      esp.println("AT+CWMODE=1");

      String cmd = "AT+CWJAP=\""+ssid+"\",\""+password+"\"";

      esp.println(cmd);

      delay(4000);

      if(esp.find("OK"))

      Serial.println("Connected!");

      else {

        ConnectWifi();

        Serial.println("Connecting..");

        }

      }

void setup(){

  esp.begin(9600);

  Serial.begin(9600);

    Serial.println("begin");

  reset();

  ConnectWifi();

  esp.println("AT+CIFSR");

  while(esp.available()>0){

  if(esp.find("STAIP"))

  {Serial.println("IP Address:");

  while(esp.available()>0)

  {ch=esp.read();

  Serial.print(ch);}

  }}}

void loop() {

    ss.listen();

    delay(2000);

    while(ss.available()>0)

    {

    gps.encode(ss.read());

    {

      if(gps.location.isValid()){

           // dtostrf(gps.location.lat(),1,6,Lat);

      //dtostrf(gps.location.lng(),1,6,Lon);

      webpage = "<!DOCTYPE html><form method = \"post\" action =\"http://localhost/php/esppost.php\">Latitude:<\label><input type=number id = \"latitude\" name= \"latitude\" readonly value=";

        //                L = Lat.length();

      l= webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lat(),6);

      esp.print("\">");

      delay(500);

      webpage = "Longitude:<input type = \"number\" id = \"Longitude\" name = \"Longitude\" readonly value =\"";
      l=webpage.length();

      //L = Lon.length();

      esp.println("AT+CIPSEND=0,");

                        esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lng(),6);

      esp.print("\">");

      }

      else

      webpage="Location Invalid";

      l=webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(l+2);

      esp.println(webpage);

      delay(500);

      if(gps.altitude.isValid()){

      dtostrf(gps.altitude.meters(),1,6,alt);

      webpage = "Altitude:<\label><input type = number id=\"Altitude\" name=\"Altitude\" readonly value=";

      l=webpage.length();

      //L= alt.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+2);

      esp.println(webpage);

      esp.print(gps.altitude.meters(),6);

      esp.print("\">");

      }

     if(gps.satellites.isValid()){

        NOS= gps.satellites.value();

        webpage= "<lable for = \"NOS \"> Number of Satellites:<\label><input type=number id=NOS name= NOS readonly value =";

        l= webpage.length();

        esp.println("AT+CIPSEND=0,");

        esp.print(2+l+22);

        esp.println(webpage);

        esp.print(gps.satellites.value());

        esp.print(">");

        delay(500);

     }}

    esp.println("AT+CIPCLOSE");

      }
}

?do you have RX to TX for esp?

yes, m using the similar connections

write a minimal test sketch

thank you. I changed the baud rate to 115200 and now it's working well.

SoftwareSerial can't listen on two instances. There is a .listen() function to switch between SoftwareSerial instances.
The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.
You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.
You could use the RX pin of Uno to receive data from GPS module over hardware Serial.

I've made some changes to my program. I connected GPS Tx to Rx of my UNO board, replaced ss with Serial and removed ss.listen(). but still m getting the same result as before. Can you please suggest me what's the error I m still doing?

@user3185742, did this answer help? which interface's baud rate did you change?


text:
Using use the STM32F103C8T6 board with the Arduino
last two days I am trying to program my blue pill with Arduino IDE, helplessly...
Actually, I managed to install simple blink program, but after that, all other attempts ended up with:

Failed to init device.
  stm32flash Arduino_STM32_0.9
http://github.com/rogerclarkmelbourne/arduino_stm32
Using Parser : Raw BINARY
  Interface serial_posix: 115200 8E1
An error occurred while uploading the sketch

I crawled internet but no help so far... I followed simply tutorial:
https://www.youtube.com/watch?v=K-jYSysmw9w just as this https://github.com/rogerclarkmelbourne/Arduino_STM32/wiki/Installation, and as I said, first time was problem but finally successfully upload it. However, after that when I wanted some real working program to install failed.
All mappings ftdi -> stm32 are correct, jumper booto is set to 1 mode, for programming, I have required files within /etc/udev/rules.d, stm32 library folder in sketch folder, and yet the error above is happening for a last 20 hours... (I am using Ubuntu 16.04)
Please, if anyone point me what is wrong (why first time worked and second wont), or to give me precise steps to perform in order to work, I appreciate.
EDIT: Blinking program works just fine when I move jumper to 0, and supply power via usb.

I did... Clean up and delete everything, and started from scratch. But nothing, really frustrating... FTDI red led is on, stm32 red led is on, but when I do upload, the same error, over and over again..
stm32flash Arduino_STM32_0.9
http://github.com/rogerclarkmelbourne/arduino_stm32
Using Parser : Raw BINARY
Interface serial_posix: 115200 8E1
Failed to init device.

thanx for help... It turns out that I have been sold crappy additional pins to plugin into breadboard. Even STM32 blink, turns out that one of the tx/rx has no contact with board (probably for microns).
However, firmed them altogether without breadboard, and it works...I spent 15 hours with this issue...

I don't think additional pins are really crappy. It supposed to be soldered on the board.


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:
Calculate statistic in EEPROM
I've search on how to do statistic calculation in EEPROM, but non related.
The data that I stored in EEPROM is body temperature.
Currently I stored the data using float.
Below is my code for data store in eeprom.
I'm stuck at the void function named "printTemp". I know how to calculate average in array using for loop statement, but not EEPROM. From average/mean, I can find standard deviation.
Does anyone have an idea on how can we do calculation using data from EEPROM?
#define LM35 A1
#define READSAMPLES 100

float bt;
int buttonPin1 = D5;     // the number of the pushbutton pin 1 MEASURE
int buttonPin2 = D6;     // the number of the pushbutton pin 2 RESET CYCLE
int buttonState = 0;         // variable for reading the pushbutton status
int ButtonState = 0;         // variable for reading the pushbutton status
int address = 0;      //EEPROM address counter
int count, counT;
int sample[READSAMPLES];

void setup() {

    int contCount = EEPROM.get(5, count) / 10;

}

void loop() {

  buttonState = digitalRead(buttonPin1);
  ButtonState = digitalRead(buttonPin2);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
        Serial.println("Measuring your Body Temperature:");

        count = counting();
        counT = count / 10;
        Serial.print("Data count entering: ");
        Serial.println(counT);

        writeTemp();
  }

  if (ButtonState == LOW) {

        Serial.println("Update New Cycle of body temp...");
        printTemp();
        clearEEPROM();
        Particle.publish("DONE new Cycle");

  }

}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    float cel = EEPROM.read(i);                //read EEPROM data at address i
    //How to find MEAN of all data?
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  //getting the voltage reading from the temperature sensor
  int j;
  float average;
  for (j = 0; j < READSAMPLES; j++)
  {
    sample[j] = analogRead(LM35);        //read sensor value
    delay(50);
  }

  average = 0;
  for (j = 0; j < READSAMPLES; j++)
  {
    average += sample[j];
  }
  average /= READSAMPLES;

  //float mv = ( average / 4096.0) * 3300;
  //float cel = ( mv / 10 ) - 55.01;
  float mv = ( average / 1024.0) * 5000;
  float cel = ( mv / 10 );

  EEPROM.write(address, cel);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}

float counting()
{
  count = count + 10;   // plus 10 is because to give a space for data entering the eeprom for LATER CODE. Just live it here.
    Particle.publish("Start Count =", String(count));
  return count;
}

What I can share from my problem findings are, to do the calculation of statistic from EEPROM data;

we need to know how to read back all the data in EEPROM. As in my code I know how to read the data, but the data cannot be hold because in FOR loop the the process will running until the end of 'i'.
we need to know how many data are there in EEPROM that have entered. To solve this, I'm using count; in order to count the entering data.

I need suggestion links or maybe any idea on how to do statistics in EEPROM.
Thanks.

Doing that calculation from EEPROM is exactly the same as doing it from any other source.  You have a count so you know where the EEPROM data ends.  You know where the EEPROM data starts.  You know how to read a number out of EEPROM.  What is stopping you from creating a for loop to read the i'th address from EEPROM and add all those numbers together just like you would for an array?
for (int i = EEPROM_START; i < EEPROM_END; i++){
   sum = sum + EEPROM.read(i);
}
average = sum / count;

where EEPROM_START and EEPROM_END are supplied by you by knowing what address you started and ended writing at.

There are quite a few issues with your program. Averaging is just one of
them.
You wrote:

Currently I stored the data using float.

No, you didn't. You stored 8-bit unsigned integers (aka uint8_t).
int contCount = EEPROM.get(5, count) / 10;

Assuming you are using an 8-bit Arduino, this is reading the EEPROM
cells at addresses 5 and 6, combining these two readings into a single
signed 16-bit number, and storing it in count. Given that these EEPROM
cells are also used to store temperature readings, this operation makes
no sense at all. BTW, the line above also stores a copy of the newly
updated count into a fresh local variable that gets immediately
discarded. This also makes no sense.
Later you wrote:
for (int i = 0 ; i < EEPROM.length() ; i++) {
  if(EEPROM.read(i) != 0)  //skip already "empty" addresses
  {
    EEPROM.write(i, 0);    //write 0 to address i
  }
}

There is an EEPROM.update() method meant to do this in a simpler way:
for (int i = 0 ; i < EEPROM.length() ; i++) {
  EEPROM.update(i, 0);  //write 0 to address i unless it is already 0
}

Later:
for (j = 0; j < READSAMPLES; j++)
{
  sample[j] = analogRead(LM35);        //read sensor value
  delay(50);
}

There is no point in storing all the readings in RAM just to compute the
average. You can get rid of the sample array and instead:
float average = 0;
for (int j = 0; j < READSAMPLES; j++)
{
  average += analogRead(LM35);  //read sensor value
  delay(50);
}
average /= READSAMPLES;

Later:
float cel = ( mv / 10 );
EEPROM.write(address, cel);
[...]
address++;

This is probably your biggest issue. You may believe you are storing
floats, yet EEPROM.write() can only write bytes. Thus the value
cel, which is a voltage in centivolts, is implicitly casted to a
uint8_t. This means it is rounded down to the nearest integer below
it, then wrapped modulo 256. This is quite likely not what you want.
If you really want to store floats, you should replace the last two
lines of code above by
EEPROM.put(address, cel);
address += sizeof cel;

but then beware that when reading the EEPROM you should also increment
the address in steps of sizeof(float).


text:
My GY-MAX30100 pulse oximeter issue with Arduino Uno
I connected the purple oximeter (GY-MAX30100) to the Arduino Uno with the following connections.
OXIMETER       ARDUINO UNO
VIN              5V
GND              GND
SCL              SCL
SDA              SDA
INT              D2

It shows me inaccurate measurements.
13:16:02.851 -> Pulse oxymeter test!
13:16:02.851 -> BEAT
13:16:02.851 -> BPM: 8616.35 | SaO2: 92.01%
13:16:03.055 -> BEAT
13:16:03.055 -> BPM: 4313.73 | SaO2: 92.66%
13:16:03.089 -> BEAT
13:16:03.089 -> BPM: 1209.15 | SaO2: 92.74%

I used this sketch from github
https://github.com/xcoder123/MAX30100/blob/master/max30100.ino
This is the sensor
EDIT
I have run an I2C scanner and this is the result: I2C device found on address 0x57. The library has the same address hard coded in it.

You might want to include a link to the library that sketch uses. Given how specific your question is, you might not get much help here. (Your potential pool of help is going to be people who have used the same sensor, with the same library, using the same sketch.) I'd suggest contacting the author of the sketch.

BTW, how does that sensor work? Every pulse-ox sensor I've ever seen shines a red light through a finger or other body part, and puts a sensor on the other side. That sensor doesn't appear to have separate emitter and sensor parts.

@DuncanC - This sensor has a visible light LED, IR LED and a Photodiode all built in :)

Ok, but it doesn't have a gap into which you would put your finger. Does it shine light into your body and then measure the light reflected back?

@DuncanC - All you have to do is put your finger on the sensor. https://datasheets.maximintegrated.com/en/ds/MAX30100.pdf


text:
Built-In Digital Map for Robot Driving
So, I'm creating this project for school. It's a simple robot with Arduino MEGA 2560 and basically, I create a digital map, feed it into the Arduino program and then the robot can drive. However, I've run into some problems while trying to implement my idea. Parsing errors mostly. And I want to know if there is another and different approach.
So, basically at the moment, this is how my digital map works:
Using C# and Visual Studio IDE I've created a program with which I can create the map. Basically, I create connections(lines/roads) and the connection has a starting and end point, a median point and a label(what it is). So, each connection info token is something like this:
"Connection[x1: 0, y1: 0|x2: 13, y2: 0|xm: 6.5, ym: 0|label: Nothing]"

"Connection[x1: 13, y1: 0|x2: 13, y2: 28|xm: 13, ym: 14|label: library]"
Now, I have figured out a way to import this information into Arduino, and I've stored the information into a class object I created. Now, the difficulty I'm experiencing is how am I going to drive the robot from one point to another, store the robot's position and go to any point in the map when asked to.
Edit:
As for the implementation and storage of the map, it's like this:
So, I have a class Vertex. It basically the equivalent of a point and store (x, y) values.

class Vertex {
  public:
    int x;
    int y;

    Vertex(int _x, int _y) {
       x = _x;
       y = _y;
    }
};

Then there's the connection class. It stores the starting vertex, the end vertex, the median vertex and the label(string). It's like this:
class Connection {
  Vertex v1();
  Vertex v2();
  Vertex median();
  String label;

  public:
    Connection(Vertex _v1, Vertex _v2, Vertex _median, String _label) {
        v1() =  Vertex(_v1.x, _v1.y);
        v2() =  Vertex(_v2.x, _v2.y);
        median() = Vertex(_median.x, _median.y);
        String label = _label;
  }
};

And, finally, there's the map class where the user passes in the info tokens produced by my map creating application made in Visual Studio and it works like this:
#include "Connection.h"

class Map {
  public:
    Map(string infoTokens[]) {
      //I import the info tokens here.
    }

    void drawMap(MCUFRIEND_kbv tft, String ) {
      //This is a totally different function, it is just for drawing the map
        on top of the TFT screen that I have on my robot.
    }

    void driveTo(Vertex rP, String destinationLabel) {
      //This is where I drive my robot when the user requests to go to a
        destination and provides the label.
    }
};

As for the importing of the info tokens(the map information) I just do some String Manipulation on, for example, this
"Connection[x1: 0, y1: 0|x2: 13, y2: 0|xm: 6.5, ym: 0|label: Nothing]"
and get back all the info in the required data types. As for the importing it doesn't really change anything because I have tested my function(not present here) a lot of times and it works brilliantly. My question is how to use that information to hopefully drive the robot.

Do you want to command the robo "go to position 6, 3" or "got to library" (last one is using the label instead of the physical location)?

And do you want the shortest connection to the target through your street net?

I want it to command using 'go to position 6,3' as it would be more useful. And yeah implementing the shortest distance possible would be a great idea.

Can you please show the implementation of your class object, so that we can see, how the data is stored?

Added the information you requested. Hopefully, it is what you need and can give me a solution. Thanks!

You were able to create a custom data structure from your string, but it seems, that the connections, that are stored in the Map class, are not connected. So the map does not really represent the structure of the "street" net. I would propose a different approach:
Instead of defining connections you can define the nodes of your net (where 2 or more streets meet). For each node you save the position (x, y) (or an instance of your vertex class), a label (like "library") and an array of pointers to other node objects. In code this may look like this (I left the methods out):
class Node {
    Vertex pos;
    char label[25];
    Node *connections[6];
}

Excursion: If you don't know, what pointers are in C/C++, here a short introduction. You should definitely read more about it on the web.
A pointer variable contains the address of another variable in the RAM. You can change this address and let the pointer point to another variable. A variable is marked as pointer with a * at the declaration. You can get the address of a variable (to set the pointer to this variable) through the & operator: pointer = &variable . If you dereference a pointer (by writing a * before the pointer name), you can work with the value, that the pointer points to. Each pointer variable has a type. It is the type of the object, that it points to. The pointer declaration int *var let's var point to int variables. If the type is a class or struct and you want to access members of the target (where it points to), you can use the shortened version pointer->member.

You define each node and add pointers to other nodes to represent connections. To traverse through the map, you need a start node. You save the address of the current node in a pointer. Then you can use it to access the connections of the current node. To actually go to the next node, you would set your pointer to the value saved in one of the connections elements, because that are pointers to the connected nodes.
The robot can then be moved along the straight lines between 2 nodes. When you want to also have non-straight, you can also do that by defining a middle point. You just to define the geometrical form, that the line should take.
The Map class can contain an array of Nodes. You can loop through all nodes in the array, if you need to, or you can traverse through the net by using the pointers.

The actual algorithm to find the path with the smallest travel distance is a big out of scope here. Doing that efficiently can be a complex task. You can research these algorithms on the web. The easiest way is to test all different paths in your program (without actually moving the robot), save the needed distance for each path and then choose the path based on that. You would need to write a termination condition, so that no connected will be taken twice on the same path (which would mean some kind of loop). Also keep in mind, that this will need more and more computation time, as your net grows. If it stays small and you don't need very fast computation, it might stay sufficient. If your implementation is recursive, you also have to consider, that each recursion takes up memory on the stack. You don't want to get out of memory.
Speaking of memory: In your implementation you use String for the label and you might want to use dynamic memory allocation for your map. That is not a good idea, because it can make swiss cheese out of your heap memory (heap fragmentation). It is better to define a fixed array, that can hold the maximal number of elements (as I have done with the connection of a node). The not needed elements can be set to something meaningless (for the connections you can use the null pointer and for unused nodes simply only null pointer connections).

Oh, thank you so much. Exactly what I needed. I was stuck with trying to implement the idea based solely on coordinates and ended with nothing. This was exactly the solution I was looking for. Thank you!


text:
HardwareSerial and SoftwareSerial not compatible
The HardwareSerial requires to run an interrupt to store received bytes in the buffer. Look at this file from the Arduino Core.
If I am now constantly receiving and writing on the Software Serial, the data from the HardwareSerial cannot be buffered, since external interrupts are higher priority.
In my application, I need to constantly listen to the SoftwareSerial and respond immediately to incoming data (actually inside the receive interrupt of the SoftwareSerial, so its modified), so the SoftwareSerial has higher priority. But when I do this, I lose data on the HardwareSerial.
Is there any way to circumvent this limitation, without disabling any interrupts or getting a chip with more UART ports?
EDIT: the actual interrupt vector is here
EDIT2: This is question is not answered by the answers in my previous question. It is clearly a fact that HardwareSerial needs its receive interrupt to store data in a buffer. My question now is how I can still use the SoftwareSerial while it is constantly receiving.

Does this answer your question? SoftwareSerial and HardwareSerial lost data

This was my question which has clearly been misunderstood. People don't understand that HardwareSerial is using a receive interrupt to store bytes in a buffer. My question is how to use SoftwareSerial together with HardwareSerial, if SoftwareSerial is constantly receiving.

Duplicate of https://arduino.stackexchange.com/questions/93772/softwareserial-and-hardwareserial-lost-data

This is question is not answered by the answers in my previous question ... look again ... that question  does not have any answers

@jsotola, nervertheless, it is still the same question.

You have asked the same question twice, here and here. It is hard to know which one to close because they both have answers. Please don't do that. Don't re-ask the question just because you don't get an answer to the first one.

If you are sending something in SoftwareSerial ISR handler that means ISRs are disabled and you are blocking other ISRs being called (if needed).
If you're using some crazy slow baudrate like 9600 then it means over 1 millisecond per character sent and during that time you might be missing other interrupts calls (millis, HW serials). If there is only one character, it's not problem, it'll be handled after interrupts are enabled again, but if there will be second or more character, previous are lost, as the've never been readed out from the UDR register (that should set flag for buffer overrun or how it's called).
If your Hw serial has some nice speed like 115200, you can lose up to 12 characters during sending single characted on software serial with speed 9600
The cli() in software serial library but as you wrote it's called from ISR handler and the ISRs are disabled anyway already during whole ISR handler

"If your Hw serial has some nice speed like 115200, you can loose up to 12 characters during sending single characted on software serial with speed 9600"
This is exactly the situation I'm in, which is unfortunately required.
Thanks for your Info. I'm currently looking into AltSoftSerial, which doesn't block as much.

Go for something like Nano Every (note that Every), that has several USARTs and one connected to the USB is different from second connected to pins 0 and 1

Another solution would probably be to implement some sort of hardware flowcontrol, since the device on the HW serial supports it. This would require a modification to the receive isr of the HW serial AND a new PCB. We'll see

@LiessJemai Another solution is to swap the interfaces. Use the software serial with the higher speed (it can handle up to 115200 bits per second) and the hardware serial with the lower speed. Or, if you can choose the speeds, adjust them.


text:
Get when a button close the circuit
That seems to be a bit stupid to myself but I can't figure out to get to know when my button is pushed (closed) or released (open).
You must know that this not just a simple push button. Actually it is more of a complex button with multiples output (Y, G, 0V, COM, NO, NC, HORM, 12V).
With a multimeter i've been able to locale witch output are closed when the button is pressed. These are HORM (that is the name for two outputs -?!-) and on the other side COM and NO.
I've tried to plug that to my arduino Mega, on PIN 7, and getting the value with Digital.Read. Tho when i try to display it on the Serial, it doesn't work and return an error. (It did the same for HORM and COM/NO)
I also noticed something strange. When the button is pressed, Arduino seems to notice it because my "ON" led turns off and then turns back on. Like if the arduino was crashing. The 13th pin LED stay HIGH after the arduino goes back on.
Please, have a look at my code.
int ledPin = 13; // choose the pin for the LED
int inPin = 7;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
}

void loop(){
  val = digitalRead(inPin);  // read input value
  Serial.write(val);
  if (val == HIGH) {         // check if the input is HIGH (button released)
    digitalWrite(ledPin, LOW);  // turn LED OFF
  } else {
    digitalWrite(ledPin, HIGH);  // turn LED ON
  }

  delay(1000);
}

Do you guys have any advice ?
Thank you very much in advance.
Also please have a look at the circuit. The only difference is that instead of having this kind of simple pushbutton, i've got my NO and COM plugged the same way.

Please show your wiring

@Majenko Added something to illustrate. Just the button is different, but the plugs are the same

If the LED is OFF and ON on the Arduino means, there is a chance you shortcut VCC and GND somewhere during the button push!

@Sener And what could that come from ?

Button's self mostly likely is doing this shortcut. You have to give us exact schematic and the datasheet of the button for a better prognosis.

We need to see your wiring, not something else entirely that may have something inconsequential in common.

Oh, and if it is you that plugged an LED in like that then remove it immediately. If you are following a tutorial that has the LED plugged in like that then comment on the tutorial to tell the author they know nothing and use a better tutorial.

@Majenko Yes I know about the resistor for the led :) I didn't plugged any led tho, just using the 13th that is already on the arduino. Way better for debug, and easier. The tutorial is actually on the official arduino.org site. I'm taking pictures for my circuit.

A good enough reason for ignoring anything even remotely technical-looking on the Arduino websites. Just goes to show how much misinformation and blatantly incorrect information they are spouting.

@Majenko, I agree with you.

Ok then.
I just tried that again and it simply seems that the wiring shown on the tutorial is not good at all.
I made another wiring that worked exactly fine.


text:
getting error while trying to compile code for soil moisture sensor
I think the below logic should work but its throwing error
void setup() {
  Serial.begin(9600);
}

void loop() {
  int soil_moisture = analogRead(A0); // read from analog pin A3
//  int soil_moisture = pinMode(AO);
  Serial.print(“analog value: “);
  if (soil_moisture < 30) {
    Serial.println(“Dry soil”);
  }
  if ((soil_moisture > 300) && (soil_moisture < 700)) {
    Serial.println(“Humid soil”);
  }
  if ((soil_moisture > 700) && (soil_moisture < 950)) {
    Serial.println(“water”);
  }
}

error i get is
Arduino: 1.6.12 (Mac OS X), Board: "Arduino/Genuino Uno"

analog_soil_moisture_v02.ino:16: error: stray '\342' in program
   Serial.print(“analog value: “);
   ^
analog_soil_moisture_v02.ino:16: error: stray '\200' in program
analog_soil_moisture_v02.ino:16: error: stray '\234' in program
analog_soil_moisture_v02.ino:16: error: stray '\342' in program
analog_soil_moisture_v02.ino:16: error: stray '\200' in program
analog_soil_moisture_v02.ino:16: error: stray '\234' in program
analog_soil_moisture_v02.ino:18: error: stray '\342' in program
     Serial.println(“Dry soil”);
     ^
analog_soil_moisture_v02.ino:18: error: stray '\200' in program
analog_soil_moisture_v02.ino:18: error: stray '\234' in program
analog_soil_moisture_v02.ino:18: error: stray '\342' in program
analog_soil_moisture_v02.ino:18: error: stray '\200' in program
analog_soil_moisture_v02.ino:18: error: stray '\235' in program
analog_soil_moisture_v02.ino:21: error: stray '\342' in program
     Serial.println(“Humid soil”);
     ^
analog_soil_moisture_v02.ino:21: error: stray '\200' in program
analog_soil_moisture_v02.ino:21: error: stray '\234' in program
analog_soil_moisture_v02.ino:21: error: stray '\342' in program
analog_soil_moisture_v02.ino:21: error: stray '\200' in program
analog_soil_moisture_v02.ino:21: error: stray '\235' in program
analog_soil_moisture_v02.ino:24: error: stray '\342' in program
     Serial.println(“water”);
     ^
analog_soil_moisture_v02.ino:24: error: stray '\200' in program
analog_soil_moisture_v02.ino:24: error: stray '\234' in program
analog_soil_moisture_v02.ino:24: error: stray '\342' in program
analog_soil_moisture_v02.ino:24: error: stray '\200' in program
analog_soil_moisture_v02.ino:24: error: stray '\235' in program
/Users/ciastro/Documents/Arduino/analog_soil_moisture_v01/analog_soil_moisture_v02.ino/analog_soil_moisture_v02.ino.ino: In function 'void loop()':
analog_soil_moisture_v02.ino:16: error: 'analog' was not declared in this scope
   Serial.print(“analog value: “);
                   ^
analog_soil_moisture_v02.ino:18: error: 'Dry' was not declared in this scope
     Serial.println(“Dry soil”);
                       ^
analog_soil_moisture_v02.ino:21: error: 'Humid' was not declared in this scope
     Serial.println(“Humid soil”);
                       ^
analog_soil_moisture_v02.ino:24: error: 'water' was not declared in this scope
     Serial.println(“water”);
                       ^
exit status 1
stray '\342' in program

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

It is because you declared NONE of your variables (int, floats) (except soil_moisture)
You must declare them. This is not Python where you can simply name a variable without declaring its type. Arduino language is based on C/C++.

Where did you get that Arduino language comes from JavaScript? I have known C and C++ for over 20 years, JavaScript for about 10 years and I don't see where Arduino language could be based on the latter.

My bad, its Java (not JavaScript). It's actually the function printf() from Java which translates to Serial.print(F())

printf is initially a standard C function, long before Java.

The actual error you are seeing is caused by the use of incorrect quotes in your program. You most likely copied and pasted the code from a website which has replaced the proper quotes with typeset-standard quotes:
    Serial.println(“Humid soil”);

should be:
    Serial.println("Humid soil");

Note the subtle difference in the quite shape. The first set are typesetter's open- and close-quote characters. The latter are just plain double-quotes (shift-2 on a UK keyboard).
There are other special characters in your program that need replacing with the standard ASCII equivalent, as well.


text:
Problem Writing/Reading EEPROM on MEGA
I want to make a program that writes on the EEPROM some structs, the final device will take structs of RGB LED data:

typedef struct{
    unsigned char r;
    unsigned char g;
    unsigned char b;
} led_color;

I will have 16 LEDS and I need to keep the RGB data of each LED despite of powering off the Arduino, I have developed this functions:
void getColorValuesFromEEPROM(led_color *colorStructArray) { // Here I need to read all the data and store it in an array of structs with 16 positions
  int eedirection = 0;
  int i = 0;
  while (eedirection <= 16 * sizeof(led_color)) {
    EEPROM.get(eedirection, color[i]);
    i++;
    eedirection *= i * sizeof(led_color);
  }
}

void getSingleColorValueFromEEPROM(led_color *sing_color) { //Here I want to read only one struct that is stored in an arbitrary position(3700) the position could be anyone that doesn't interferes with the array data
  EEPROM.get(3700, sing_color);
}

void writeColorValuesToEEPROM(unsigned char led_number, led_color *color) { //Here I need to write the struct data of the led_number given(from 1 to 16);
  int eedirection;
  eedirection = led_number * sizeof(led_color);
  EEPROM.update(eedirection, color);
}

void writeSingleColorValueToEEPROM(led_color *single) { //Here I want to write only one struct of data in the arbitary direction(3700)
  EEPROM.update(3700, single);
}

The problem is that my Arduino freezes when I try to read/write data with the functions above, here I paste the full code, it freezes in the setup():
ddj.c
#include "ddj.h"
#include <EEPROM.h>
#include <RotaryEncoder.h>
#include <MIDI.h>
#include <Adafruit_NeoPixel.h>

#define DATA_PIN 6  //DATA PIN OF THE RGB LEDS

#define runEvery(t) for (static uint16_t _lasttime;\
                         (uint16_t)((uint16_t)millis() - _lasttime) >= (t);\
                         _lasttime += (t))

RotaryEncoder encoder(18, 19); //Encoders are connected to pins 18-19 and 2-3 (A and B of each encoder)
RotaryEncoder encoder1(20, 21);
Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, DATA_PIN, NEO_GRB + NEO_KHZ800);

MIDI_CREATE_DEFAULT_INSTANCE();

led_color color[16];
led_color single_color;
unsigned char ledMode = 0;
bool ledState = LOW;
unsigned int interval = 500; //Interval in milliseconds of the Led Blinking mode
int potenciometro[6] = {A0, A1, A2, A3, A4, A5};  //The potentiometers are connected to A0, A1, A2 and A3
int valpot[6] = {0, 0, 0, 0, 0, 0};
int lastval[6] = {0, 0, 0, 0, 0, 0};
bool state[44] = {0};
bool laststate[44] = {0};

void getColorValuesFromEEPROM(led_color *colorStructArray) {
  int eedirection = 0;
  int i = 0;
  while (eedirection <= 16 * sizeof(led_color)) {
    EEPROM.get(eedirection, color[i]);
    i++;
    eedirection *= i * sizeof(led_color);
  }
}

void getSingleColorValueFromEEPROM(led_color *sing_color) {
  EEPROM.get(3700, sing_color);
}

void writeColorValuesToEEPROM(unsigned char led_number, led_color *color) {
  int eedirection;
  eedirection = led_number * sizeof(led_color);
  EEPROM.update(eedirection, color);
}

void writeSingleColorValueToEEPROM(led_color *single) {
  EEPROM.update(3700, single);
}

void setLedMode(unsigned char n) { // 0 - All On; 1 - All Off; 2 - Blink With Delay; 3 - On When Pressed
  ledMode = n;
}

void setSingleLed(unsigned char led_number, led_color colorStructArray) {
  strip.setPixelColor(led_number, colorStructArray.r, colorStructArray.g, colorStructArray.b);
  strip.show();
}

void setAllLeds(unsigned char mode) { // 0 - All On; 1 - All Off;
  if (mode = 0) {
    for (int i = 0; i < 16; i++) {
      strip.setPixelColor(i, single_color.r, single_color.g, single_color.b);
      strip.show();
    }
  } else if (mode = 1) {
    for (int i = 0; i < 16; i++) {
      strip.setPixelColor(i, 0, 0, 0);
      strip.show();
    }
  }
}

void pushbuttonsRead() {
  for (int i = 2; i < 14; i++) {
    state[i + 30] = digitalRead(i); //This statement read the state of the digital pin
    if (state[i + 30] != laststate[i + 30]) { //This two if conditionals make the interrupt and "debounce" the button so it only will send data when the state changes, and that state is LOW
      if (state[i + 30] == 0) {
        MIDI.sendNoteOn(i + 30, 127, 1); //This send the MIDI data---  NOTE 56, VELOCITY 127, CHANNEL 1
      }
    }
    laststate[i + 30] = state[i + 30];
  }
  for (int i = 22; i < 54; i++) { //32 BUTTONS
    state[i - 22] = digitalRead(i); //This statement read the state of the digital pin
    if (state[i - 22] != laststate[i - 22]) { //This two if conditionals make the interrupt and "debounce" the button so it only will send data when the state changes, and that state is LOW
      if (state[i - 22] == 0) {
        MIDI.sendNoteOn(i - 21, 127, 1); //This send the MIDI data---  NOTE 56, VELOCITY 127, CHANNEL 1
        if ((ledMode == 3) && (i >= 22 && i <= 38)) {
          setSingleLed(i - 22, color[i - 22]);
        }
      }
    }
    laststate[i - 22] = state[i - 22];
  }
}

void potentiometersRead() {
  for (int i = 0; i < 6; i++) {   //Here you read the potentiometers data, convert them from 10 bit(Arduino's ADC read resolution) to 7 bit (MIDI protocol resolution) and send them
    valpot[i] = analogRead(potenciometro[i]) >> 3;
    if (valpot[i] != lastval[i]) {
      MIDI.sendControlChange(i + 1, valpot[i], 1);
    }
    lastval[i] = valpot[i];
  }
}

void setup()
{
  //MIDI.begin(MIDI_CHANNEL_OMNI);  //Here the MIDI communication starts
  strip.begin();
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  for (int i = 30; i < 46; i++) {
    pinMode(i, INPUT_PULLUP);  //Set the pushbuttons pins as input with a PULLUP resistor
  }
  getSingleColorValueFromEEPROM(&single_color);
  //getColorValuesFromEEPROM(color);
}

void loop()
{
  if (ledMode == 0 || ledMode == 1) { //ALL ON AND ALL OFF MODES
    setAllLeds(ledMode);
  } else if (ledMode == 2) { //BLINK WITH DELAY MODE
    runEvery(interval) {
      if (ledState == LOW) {
        ledState = HIGH;
      }
      else {
        ledState = LOW;
      }
      setAllLeds(ledState);
    }
  }

  pushbuttonsRead();

  potentiometersRead();

  static int pos = 60;
  encoder.tick();

  int newPos = encoder.getPosition(); //Here you read the encoder position and if it has changed from the last time, you send it
  if (pos != newPos) {
    if (pos < newPos) {
      MIDI.sendControlChange(15, 1, 2);
    } else if (pos > newPos) {
      MIDI.sendControlChange(15, 127, 2);
    }
    pos = newPos;
  }
  static int pos1 = 60;
  encoder1.tick();

  int newPos1 = encoder1.getPosition();
  if (pos1 != newPos1) {
    if (pos1 < newPos1) {
      MIDI.sendControlChange(16, 1, 2);
    } else if (pos1 > newPos1) {
      MIDI.sendControlChange(16, 127, 2);
    }
    pos1 = newPos1;
  }
}

ddj.h
typedef struct{
    unsigned char r;
    unsigned char g;
    unsigned char b;
} led_color;

void getColorValuesFromEEPROM(led_color colorStructArray[]);

void getSingleColorValueFromEEPROM(led_color *sing_color);

void writeColorValuesToEEPROM(unsigned char led_number, unsigned char red, unsigned char green, unsigned char blue);

void writeSingleColorValueToEEPROM(unsigned char red, unsigned char green, unsigned char blue);

void setLedMode(unsigned char n);

void setSingleLed(unsigned char led_number, led_color colorStructArray[]);

void setAllLeds(unsigned char mode);

void pushbuttonsRead();

you can do EEPROM.put(0, color); and EEPROM.get(0, color); where color is your array of structs

I can not find code that freezes. I can not find stack overflow or array out of bounds. There is something going on with EEPROM.get. You may not use a pointer there, only a full variable/struct/anything because it uses the size of that full variable/struct/anything. The color[i] might work but not the led_color *. Something else is perhaps a voltage drop when the led strip is initialized. What is the voltage of the 5v pin?


text:
Arduino malfunction tmrpcm while used digitalRead
I am programming Arduino UNO for this functionality:
with use of SD card reader module and SIM900 GSM/GPRS shield I am trying to:
 1. Pick up incomming call, play message from SD file and after the message ends, hang up.
 2. Call from Arduino to defined telephone number, after the call is picked up, play message and after the message ends, hang up.
3. In case of outcomming call (arduino calls to defined number) and its declined or not picked up, Arduino makes another try for a total of 3 tries.
4. I want to play the message in Czech language OR English message, based on pushed/unpushed button.
Its all working, but number 4. the button for language switch is not working. If I place in code another "digitalRead(pin)" Arduino does all the stuff but does not play the message - its silent on the other end. If I delete this line of code, it is working. So the functionality is good, but the language switch is not working. I have tried to switch it to Global/Local variables, tried to put it straight into the If statement. Everything is wrong.
Any ideas? Thank you.
Code:

#include <GPRS_Shield_Arduino.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <SD.h>
#include <TMRpcm.h>
#include "SPI.h"

#define SD_ChipSelectPin 10
#define PIN_TX    7
#define PIN_RX    8
#define BAUDRATE  9600
#define MESSAGE_LENGTH 20

GPRS gprs(PIN_TX, PIN_RX, BAUDRATE);
TMRpcm tmrpcm;

char telefon[] = "999999999";
//char *s = NULL;
char englishMessage[] = "Hlas6en.wav";
char czechMessage[] = "Hlas6cz.wav";//"Hlas6cz.wav";
char gprsBuffer[64];
//char in_number[16] = {0};

unsigned long englishMessageTime = 11000;
unsigned long czechMessageTime = 11000;

int callRetry = 2; //pocet pokusu opakovaneho telefonatu
//int i = 1;
//int inComing = 0;

bool callPrev = false;
bool callAct = false;
bool call = false;

uint8_t PIN_RST = 2;
int PIN_INPUT = 4;
//int LANGUAGE_INPUT = 6;
bool languageSwitch = HIGH;

void setup()
{
  pinMode(PIN_INPUT, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

  Serial.begin(BAUDRATE);
  //delay(10000); //NECHAT!

  while (!gprs.init())
  {
    Serial.println("SIM 900 - INIT ERROR");
    gprs.powerReset(PIN_RST);
    delay(7000);
  }

  while (!SD.begin(SD_ChipSelectPin))//SD_ChipSelectPin
  {
    Serial.println("SD fail");
    delay(1000);
    //return;
  }
  Serial.println("Zapnuto.");
  tmrpcm.speakerPin = 9;
  tmrpcm.setVolume(5);
  //sim900_clean_buffer(gprsBuffer, 32);
  //gprs.callUp(telefon);
  //languageSwitch = digitalRead(3);
}

void loop() {
  if ((gprs.readable()) || call)
  {
    sim900_read_buffer(gprsBuffer, 32, DEFAULT_TIMEOUT);
    Serial.print(gprsBuffer);
    if (NULL != strstr(gprsBuffer, "OK"))
    {
      Serial.println("Hovor prijat.");
      playAudio();
      Serial.println("Zprava prehrana, pokladam.");
      gprs.hangup();
      callRetry = 2;
    }
    else if (NULL != strstr(gprsBuffer, "RING"))
    {
      Serial.println("Prijimam prichozi hovor.");
      gprs.answer(); //zvednuti telefonu v pripade prichoziho hovoru
      callRetry = 2;
    }

    else if ((NULL != strstr(gprsBuffer, "BUSY")) || call)
    {

      if (callRetry == 0)
      {
        callRetry = 2;
        Serial.println("Nedovolal jsem se.");
      }
      else if ((callRetry > 0) && (!call))
      {
        Serial.print("Zbyva pocet pokusu:");
        Serial.println(callRetry - 1);
        gprs.callUp(telefon); //Opakovane volani v pripade polozeni
        callRetry--;
      }
      else if ((callRetry == 2) && (call))
      {
        gprs.callUp(telefon);
        Serial.println("Volam");
      }
      call = false;
    }
    //smazani bufferu
    sim900_clean_buffer(gprsBuffer, 32);
  }
  callPrev = callAct;
  callAct = !digitalRead(PIN_INPUT);
  //languageSwitch = digitalRead(3);
  call = !callPrev && callAct;
  //languageSwitch=digitalRead(LANGUAGE_INPUT);
  delay(1000);
  Serial.println(call);
  //Serial.println(languageSwitch);
}

void playAudio()
{
  bool languageSwitch = digitalRead(3); //PROBLEM!!!
  tmrpcm.speakerPin = 9;
  if (!SD.begin(SD_ChipSelectPin))//SD_ChipSelectPin
  {
    Serial.println("SD fail");
    return;
  }
  Serial.println("Prehravani zpravy.");
  tmrpcm.setVolume(5);
  if (languageSwitch==HIGH)
  {
    Serial.println("Prehravam zpravu v cestine");
    tmrpcm.play(czechMessage);//czechMessage
    delay(czechMessageTime);
  }
  else
  {
    Serial.println("Prehravam zpravu v anglictine");
    tmrpcm.play(englishMessage);//englishMessage
    delay(englishMessageTime);
  }
  return;
}

How is the button connected to the Arduino? Do you have a pullup/down resistor, can you show a schematic?

As you can see, the pin is initialized in pinmode input_pullup so if there is nothing connected it should be all time high. And it is. If I use println with the pin state it represents the correct state ,it just does not play the message from SD.

But you said you execute the tmrpcm.play(czechMessage); yourself it does play the sound, so only inside playAudio() the digitalRead doesn't work? Is it stuck to always the same value or random?

It doesn't matter where the digital read is. If it is present in the loop or inside the playAudio() function. If it is present anywhere the message - sound is not playing. If you delete the digitalRead sound is playing properly.

Otherwise the digitalRead is working properly - high on unpressed button, low on pressed button. It just mess up the play of the audio message.