text:
expected '}' at end of input
hi i am getting this error, im guessing i have a bracket missing or one in the wrong place.  any help is appreciate, still new at this. thank you
(code bellow)
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <XBOXRECV.h>

Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x40);

USB Usb;
XBOXRECV Xbox(&Usb);

// our servo # counter
// You can change the value from 0 to 15 (servo 1 through 16)
uint8_t util1servo = 0;
uint8_t util2servo = 1;
uint8_t ldoorservo = 2;
uint8_t rdoorservo = 7;
uint8_t sdoorservo = 3;
uint8_t mdoorservo = 8;

//Servo limits definition.
//You will have to figure out which numbers match your servo be carefull with these,
//it can break your servo if you go beyond the limits. The ones listed here are for my own setup
#define UTIL1MIN  150 // Close position of the Top Utility arm
#define UTIL1MAX  310 // Open position of the Top Utility arm
#define UTIL2MIN  140 // Close position of the Bottom Utility arm
#define UTIL2MAX  300 // Open position of the Bottom Utility arm
#define LDOORMIN  390 // Close position of the Left door
#define LDOORMAX  550 // Open position of the Left door
#define RDOORMIN  555 // Close position of the Right door
#define RDOORMAX  360 // Open position of the Right door
#define SDOORMIN  492 // Close position of the Small door
#define SDOORMAX  200 // Open position of the Small door
#define MDOORMIN  550 // Close position of the Mid door
#define MDOORMAX  380 // Open position of the Mid door

//Status for each door open/close
int LDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int RDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int SDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int MDOORSTATUS = 0; // Status 0 = Closed, 1 = Open

void setup() {

   pwm1.begin();

  pwm1.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

  Wire.begin();

}

void loop() {

//Left door
if (Xbox.getButtonClick(LEFT, 0)){
  if (Xbox.getButtonPress(R1, 0)) {
    if(LDOORSTATUS == 0){
          for (uint16_t lpulselen = LDOORMIN; lpulselen < LDOORMAX; lpulselen++){
          pwm1.setPWM(ldoorservo, 0, lpulselen); //Open the door
          delay(1);
          }
          LDOORSTATUS = 1;
          }
        else if (LDOORSTATUS == 1){
             for (uint16_t lpulselen = LDOORMAX; lpulselen > LDOORMIN; lpulselen--){
             pwm1.setPWM(ldoorservo, 0, lpulselen); //Close the door
             delay(1);
             }
             LDOORSTATUS = 0;
     }

Auto-format in the IDE is your friend...

You should edit your question, select the code, and press the {} code formatting button.

downvote because you are asking for help with sloppily formatted code

Auto-formatting produced the following - look at your loop() function and you'll see the problem:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <XBOXRECV.h>

Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x40);

USB Usb;
XBOXRECV Xbox(&Usb);

// our servo # counter
// You can change the value from 0 to 15 (servo 1 through 16)
uint8_t util1servo = 0;
uint8_t util2servo = 1;
uint8_t ldoorservo = 2;
uint8_t rdoorservo = 7;
uint8_t sdoorservo = 3;
uint8_t mdoorservo = 8;

//Servo limits definition.
//You will have to figure out which numbers match your servo be carefull with these,
//it can break your servo if you go beyond the limits. The ones listed here are for my own setup
#define UTIL1MIN  150 // Close position of the Top Utility arm
#define UTIL1MAX  310 // Open position of the Top Utility arm
#define UTIL2MIN  140 // Close position of the Bottom Utility arm
#define UTIL2MAX  300 // Open position of the Bottom Utility arm
#define LDOORMIN  390 // Close position of the Left door
#define LDOORMAX  550 // Open position of the Left door
#define RDOORMIN  555 // Close position of the Right door
#define RDOORMAX  360 // Open position of the Right door
#define SDOORMIN  492 // Close position of the Small door
#define SDOORMAX  200 // Open position of the Small door
#define MDOORMIN  550 // Close position of the Mid door
#define MDOORMAX  380 // Open position of the Mid door

//Status for each door open/close
int LDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int RDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int SDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
int MDOORSTATUS = 0; // Status 0 = Closed, 1 = Open

void setup() {

  pwm1.begin();

  pwm1.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

  Wire.begin();

}

void loop() {

  //Left door
  if (Xbox.getButtonClick(LEFT, 0)) {
    if (Xbox.getButtonPress(R1, 0)) {
      if (LDOORSTATUS == 0) {
        for (uint16_t lpulselen = LDOORMIN; lpulselen < LDOORMAX; lpulselen++) {
          pwm1.setPWM(ldoorservo, 0, lpulselen); //Open the door
          delay(1);
        }
        LDOORSTATUS = 1;
      }
      else if (LDOORSTATUS == 1) {
        for (uint16_t lpulselen = LDOORMAX; lpulselen > LDOORMIN; lpulselen--) {
          pwm1.setPWM(ldoorservo, 0, lpulselen); //Close the door
          delay(1);
        }
        LDOORSTATUS = 0;
      }


text:
Why am I getting this error- "exit status 1 expected ';' before '{' token "
void setup()
{

  pinMode{13, OUTPUT};

}

void loop() {

  digitalWrite{13, HIGH};

}

Use digitalWrite(13,HIGH); rather than curly brackets, and do the same for pinMode

Why ard you using {} brackets after function name?

Try parentheses instead of curly braces:
void setup() {

pinMode(13, OUTPUT);

}

void loop() {

digitalWrite(13, HIGH);

}

It's funny and nonsense, but pinMode;  {  ...  is formally correct. That makes error messages hard to understand.

The solution is already give, but here an explanation:
{ and } are used to group multiple statements together, either for a function, if, while, for loop and so on.
E.g.
if (i == 1)
{
  // Statement 1
  // Statement 2
}

or a function
void f()
{
  // Statement 1
  // Statement 2
}

( and ) are used to specify parameters:
void f(int a, int b)
{
  ...
}

A function with two parameters.
When calling this function, the following is used:
f(1, 2);

Calls function f with a = 1, and b = 2.
So in general: { and } is for grouping statements, ( and ) for parameters.

{} is also used in initializer syntax, which might lead to other confusing error messages for incorrect code.

@AnT True, I didn't make a complete list to make my answer not overly difficult for beginners. {} is also used for begin/end of a class as other example.

I made same mistake when I started working with C
you have
pinMode{13, OUTPUT};

which should be
pinMode(13, OUTPUT);

the curly brackets are basically for Start and End of a function.
Bill

source: Stack Exchange

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

sort: votes


text:
How to use while loop in arduino for infinte loop
I am doing code of esp while switching hotspot for connecting esp i am getting some problem .
I am using this line of code:
while ((!esp.find("WIFI ")) || (!esp.find("+CWJAP:3")));

but it is not working. Anybody please give me alternate how to use this type of looping.

What exactly is "not working".  Can you explain?  Otherwise it is hard, if not impossible, to help.

The find method reads the characters until the searched string is found or a timeout interval is passed.
In your case if the connection is not successful, the first find will not find "WIFI" and will read all the input including the "+CWJAP:3", then on timeout it returns false. The second find will wait until timeout and then return false.

so what i can do i have to wait until WIFI or +CWJAP=3 is come on serial monitor

read the lines returned by AT firmware into a buffer and compare the content of the buffer with expected strings. or use the WiFiEsp library, which handles the AT commands and responses for you

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


text:
atmega328: external crystal oscillator and uart
I need an clearity about external crystal oscilator. I got communication between esp32 and atmega8/88/328 processor, I use atmega wih internal oscillator and looks like it have problem with serial communication (some time it lose data, or replace it with nonsences).
So i have read that should use extercal crystal oscillator to achieve stable uart communication.
Question is that, what frequency to choose, and how that gonna effect uart, and atmega processor lifetime. I know if choose 16mhz processor gonna run faster, but assume it life time will decrease compated with 1mhz or 8mhz.
What about uart, which one of those frequences are best for it, or it make no difference?

the lifetime of your atmega won't be affected. you just need to make sure if the atmega is meant to run at that frequency. Regarding your uart? you need to make sure that you adjust the prescaler so the baudrate remains correct.

There are some specific crystal oscillator frequencies named 'UART friendly'. Using these frequencies would lower % error in UART communications. Please refer to the table in the datasheet, in chapter named "BAUD rate settings" (datasheet of ATMega328: '24.11. Examples of Baud Rate Setting'). There are tables to show error percentage. What to look at is "Error" column. fosc is selected oscillator/crystal frequency. For succesful UART communication you aim for less than 3.5% Error.
 Your crystal speed should depend on your desired communication speed, for example for me the preferred ones are 11059200Hz or 1843200Hz.

or below:

With raising frequency you may expect power consumption and the chip's temperature rise, anyway I wouldn't worry too much about life shortening. More important here would be power consumption rise.
 Do you want the chip(device) to be battery powered? To save on energy you can also consider lower frequencies like 1.8432MHz or 3.6864MHz.

1.84mhz is uart friendly for almost all rates, but In arduino ide there is no such frequency to select


text:
Pass structure pointer as an argument to a function in c
I am developing a code in which I need to pass a structure pointer value to a function as a parameter. I am calling function "proto485Compare()" in "RS485TaskSlave()". "rs485Msg" contains my data for which I need to verify for checksum, I am checking it in "RS485TaskSlave()" using "if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message)))" but it is showing error on this line.
Please help me to get the values of "rs485Msg" & check for checksum on this line
Below is my code snippet:
 typedef struct
    {
      uint8_t AB;     ///< Address byte (Start byte)
      uint8_t CB;     ///< Command (index) "ASCII-byte"
      uint8_t SI;     ///< Action (sub index) "ASCII-byte"
      uint8_t PH1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
      uint8_t PH0;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
      uint8_t PL1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
      uint8_t PL0;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
      uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
      uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
    } rs485_message_t;

    uint8_t proto485ValidCheckSum(rs485_message_t message)
    {
      uint8_t rawChecksum = (message.CB - OFFSET_ASCII) + (message.SI - OFFSET_ASCII) +
        (message.PH1 - OFFSET_ASCII) + (message.PH0 - OFFSET_ASCII) +
          (message.PL1 - OFFSET_ASCII) + (message.PL0 - OFFSET_ASCII);

      uint8_t res = (((rawChecksum & 0xF0) >> 4) + OFFSET_ASCII) == message.CS1 &&
        ((rawChecksum & 0x0F) + OFFSET_ASCII) == message.CS0;

      return res;
    }

    void RS485TaskSlave(void *p_arg) //b - RS485 communication Task
    {
        uint8_t res;
        rs485_message_t rs485Msg;
        uint8_t command, action, value;

        (void)p_arg;
        while(1)
        {
          res = driver485Read((uint8_t *)&rs485Msg, RS485_MSG_LENGTH);
          if(RS485_MSG_LENGTH == 9)
         {
            res =  proto485Compare((uint8_t *)&rs485Msg, command, action, value);
         }
        }
    }

    int16_t proto485Compare(uint8_t* message, uint8_t* comparec, uint8_t* comparea, uint8_t* comaprev)
    { int j = 0;
      rs485_message_t rs485Msg;
      char res;
      uint8_t FWmsg[9] = {0x09,0x31,0x30,0x30,0x30,0x30,0x33,0x30,0x34};
      uint8_t arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

     if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message))) //
/*GETTING ERRORVON THIS LINE please help how to pass message value to verify checksum at this line*/
      {
      printf("compare command..........");

        for (j=0; j<9; j++)
        {
          arduinodata[j] = message[j];
          printf("%d ",arduinodata[j]);
        }
        printf("\n");

        if(compareArray(FWmsg,arduinodata,7)==0)
        {
          uint8_t add, fwc, fwa;
          uint16_t fwv;
          res = GetABFWversion(&add, &fwc, &fwa, &fwv);
          res = proto485OnlyWrite(add,fwc, fwa, fwv);
        }
      }
      else
      {
        printf("Arrays have different elements.\n");
      }
      return res;
    }

Remove your casting, and change your message parameter to be rs485_message_t *:
int16_t proto485Compare(rs485_message_t * message, uint8_t* comparec, uint8_t* comparea, uint8_t* comaprev) {
    int j = 0;
    rs485_message_t rs485Msg;
    char res;
    uint8_t FWmsg[9] = {0x09,0x31,0x30,0x30,0x30,0x30,0x33,0x30,0x34};
    uint8_t arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

    if(proto485ValidCheckSum(message))) { ...

And when you call it, simply:
res =  proto485Compare(&rs485Msg, command, action, value);

To get at the individual bytes you can then cast a new variable:
uint8_t *messageAsBytes = (uint8_t *)message;

Then you can use:
messageAsBytes[i]

etc.
However another cleaner way is to create a union in your structure:
struct rs485_message_t {
    union {
        uint8_t bytes[9];
        struct {
            uint8_t AB;     ///< Address byte (Start byte)
            uint8_t CB;     ///< Command (index) "ASCII-byte"
            uint8_t SI;     ///< Action (sub index) "ASCII-byte"
            uint8_t PH1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
            uint8_t PH0;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
            uint8_t PL1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
            uint8_t PL0;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
            uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
            uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
        };
    };
};

So you can now access message->CS0, etc, as well as message->bytes[3].
You should also pass a pointer when you call proto485ValidCheckSum - purely to save memory.
uint8_t proto485ValidCheckSum(rs485_message_t *message)
{
  uint8_t rawChecksum = (message->CB - OFFSET_ASCII) + (message->SI - OFFSET_ASCII) +
    (message->PH1 - OFFSET_ASCII) + (message->PH0 - OFFSET_ASCII) +
      (message->PL1 - OFFSET_ASCII) + (message->PL0 - OFFSET_ASCII);

  uint8_t res = (((rawChecksum & 0xF0) >> 4) + OFFSET_ASCII) == message->CS1 &&
    ((rawChecksum & 0x0F) + OFFSET_ASCII) == message->CS0;

  return res;
}

And again call it with a pointer, which the first block of code does anyway.
In general, it's better to pass a single pointer to a struct around from function to function instead of cloning it each time.
You can also use "pass by reference" if you like, but I find it's better to stick to pointers when passing something around alot like this.

Thank you for reply, I have made above mentioned changed & run the code it is showing below errors....   1) on line  "if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message)))" it gives "type name is not allowed" and on line " arduinodata[j] = message[j];" it shows that "a value of type "rs485_message_t" cannot be assigned to an entity of tpe "uint8_t" "

@swanand Read my first code block and compare it to yours.

Sorry my bad, i have changed for message element reading it is working fine but I am still getting error on line " if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message)))" t gives "type name is not allowed" Please inform If I am doing something wrong....

@swanand Read my first code block and compare it to yours.

Thank you so much once again for providing guidance......


text:
Uno Wifi Rev2 - sending program via WIFI
My new Uno wifi rev2 just arrived and I have one problem.  At the beggining I connected my board via USB and tested with example blink program from WifiNiNA and It worked fine.  When program is runned and I plug in DC power suply and take off USB, my program is still working. And here is my problem. I'm wondering how I can send program/sketch to my arduino without usb just through WIFI. Is it possible? How I can do it?

two different unrelated questions ... please delete the one about the RGB LED and post separately

Does this answer your question? https://arduino.stackexchange.com/questions/70774/make-ota-work-with-arduino-uno-wifi

sad is, almost a year later the answer there is still valid. while there is a progress they still didn't publish the OTA update for Uno WiFi Rev 2.


text:
how to serially off leds in an esp running mqtt
hi im using at tiny 85 to monitor dc switches and to serial print with this code
below to esp8266 with local broker to turn leds on and off but its only working through mqtt but not with physical switches which are connected to at tiny 85. please help this is my mqtt code
//////at tiny code///
#include <SendOnlySoftwareSerial.h>

SendOnlySoftwareSerial myserial (4);  // Tx pin

int sw1 = 0;
int sw2 = 1;
int sw3 = 2;
int sw4 = 3;

int sta1 = 0;
int sta2 = 0;
int sta3 = 0;
int sta4 = 0;

bool st1 = false;
bool st2 = false;
bool st3 = false;
bool st4 = false;
void setup () {

  myserial.begin(9600);
  pinMode(0, INPUT);
  pinMode(1, INPUT);
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, OUTPUT);

  }
void loop ()
{
  sta1 = digitalRead(sw1);
  sta2 = digitalRead(sw2);
  sta3 = digitalRead(sw3);
  sta4 = digitalRead(sw4);
  if (sta1 == HIGH && st1 == false){
    myserial.println("sw1 on");
    st1 = true;
    delay(1);
  }
    else if (sta1 == LOW && st1 == true){
      myserial.println("sw1 off");
      st1 = false;
      delay(1);
    }

   if (sta2 == HIGH && st2 == false){
    myserial.println("sw2 on");
    st2 = true;
    delay(1);
  }
    else if (sta2 == LOW && st2 == true){
      myserial.println("sw2 off");
       st2 = false;
      delay(1);
    }

   if (sta3 == HIGH && st3 == false){
    myserial.println("sw3 on");
     st3 = true;
    delay(1);
  }
    else if (sta3 == LOW &&  st3 == true){
      myserial.println("sw3 off");
       st3 = false;
      delay(1);
    }
   if (sta4 == HIGH &&  st4 == false){
    myserial.println("sw4 on");
    st4 = true;
    delay(1);
  }
    else if (sta4 == LOW&& st4 == true){
      myserial.println("sw4 off");
      st4 = false;
      delay(1);
    }

}

//////esp mqtt code///////
//ItKindaWorks - Creative Commons 2016
//github.com/ItKindaWorks
//
//Requires PubSubClient found here: https://github.com/knolleary/pubsubclient
//
//ESP8266 Simple MQTT light controller

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

int LED3 = D2;
int LED4 = D4;
int LED2 = D3;
int LED1 = D5;

String data ;
// the number of the pushbutton pin

//EDIT THESE LINES TO MATCH YOUR SETUP

#define MQTT_SERVER "192.168.43.223"
const char* ssid = "kuro";
const char* password = "qwertyui";

//LED on ESP8266 GPIO2

char* lightTopic = "/test/light1";
char* lightTopic1 = "/test/light2";
char* lightTopic2 = "/test/light3";
char* lightTopic3 = "/test/light4";

WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length);
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
  //initialize the light as an output and set to LOW (off)
  Serial.begin(9600);
  pinMode(LED3 , OUTPUT);
  pinMode(LED4 , OUTPUT);
  pinMode(LED1 , OUTPUT);
  pinMode(LED2 , OUTPUT);

    delay(100);

    // We start by connecting to a WiFi network

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

    WiFi.begin(ssid, password);

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

  if (Serial.available()>0) /* If data available at serial port, enter if loop */
  {
    data = Serial.readStringUntil('\n'); /* Read data present at serial port */
    /* Print string with \r\n */
    Serial.println(data); /* Print data received */
  }
    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

}

void loop(){
  //reconnect if connection is lost
  if (!client.connected() && WiFi.status() == 3) {reconnect();}

  //maintain MQTT connection
  client.loop();

  //MUST delay to allow ESP8266 WIFI functions to run
  delay(10);
}

void callback(char* topic, byte* payload, unsigned int length)
{
  //convert topic to string to make it easier to work with
  String topicStr = topic;

  //Print out some debugging info
  Serial.println("Callback update.");
  Serial.print("Topic: ");
  Serial.println(topicStr);

 if(topicStr.equals(lightTopic)||Serial.available()){

   if(payload[0] == '1' || data.equals ("sw1 on")){
      digitalWrite(LED1 , HIGH);
    }

    else if (payload[0] == '0'|| data.equals ("sw1 off")){
      digitalWrite(LED1 , LOW);
    }
 }
 if(topicStr.equals(lightTopic1)||Serial.available()){

   if(payload[0] == '1'|| data.equals ("sw2 on")){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'|| data.equals ("sw2 off")){
      digitalWrite(LED2 , LOW);
    }
 }
 if(topicStr.equals(lightTopic2)||Serial.available()){

   if(payload[0] == '1'|| data.equals ("sw3 on")){
      digitalWrite(LED3 , HIGH);
    }

    else if (payload[0] == '0'|| data.equals ("sw3 off")){
      digitalWrite(LED3 , LOW);
    }
 }
  if(topicStr.equals(lightTopic3)||Serial.available()){

   if(payload[0] == '1'|| data.equals ("sw4 on")){
      digitalWrite(LED4 , HIGH);
    }

    else if (payload[0] == '0'|| data.equals ("sw4 off")){
      digitalWrite(LED4 , LOW);
    }
  }

}

void reconnect() {

  //attempt to connect to the wifi if connection is lost
  if(WiFi.status() != WL_CONNECTED){
    //debug printing
    Serial.print("Connecting to ");
    Serial.println(ssid);

    //loop while we wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    //print out some more debug once connected
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }

  //make sure we are connected to WIFI before attemping to reconnect to MQTT
  if(WiFi.status() == WL_CONNECTED){
  // Loop until we're reconnected to the MQTT server
    while (!client.connected()) {
      Serial.print("Attempting MQTT connection...");

      // Generate client name based on MAC address and last 8 bits of microsecond counter
      String clientName;
      clientName += "esp8266-";
      uint8_t mac[6];
      WiFi.macAddress(mac);
      clientName += macToStr(mac);

      //if connected, subscribe to the topic(s) we want to be notified about
      if (client.connect((char*) clientName.c_str())) {
        Serial.print("\tMTQQ Connected");
        client.subscribe(lightTopic);
        client.subscribe(lightTopic1);
        client.subscribe(lightTopic2);
        client.subscribe(lightTopic3);

      }

      //otherwise print failed for debugging
      else{Serial.println("\tFailed."); abort();}
    }
  }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

Maybe you should add some code to the ESP8266 that reads from serial and does something depending on what has been read?

shouldn't the code for reading Serial be in loop(), not in setup()?

Majenko is right, you just don't have any code, that would read and process serial input on the ESP (besides the bit in setup, which is only called once at startup), thus it will not react to serial data. The solution: Program the ESP to read the serial data and process it. Then you can write code, that reacts to serial data

hi thank you everyone, so i wrote another code to just print and blink an led, its printing fine but not turning the led on/off ```String command;
int led = 3;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
if(Serial.available()>0){
command = Serial.readString();
Serial.print(command);
    if(command.equals ('sw4 on')){
        digitalWrite(led , HIGH);
    }
    else if(command.equals ('sw4 off')){

        digitalWrite(led , LOW);
    }

}

}```

' is for char. use ". the text sent from atiny with println ends with \r\n so it is not equal to "sw4 on".

thank you so much juraj that must be it now i got it working


text:
Connecting microSD reader and e-paper display to Nano at the same time?
Pretty much as the question states, I'm wondering if it's possible to connect (this: https://www.waveshare.com/7.5inch-HD-e-Paper-HAT.htm ) 7.5" e-paper display that has raspberry pi HAT and an SD card reader to Arduino nano/micro for reading images off SD and displaying on the screen. I'm an novice and a not sure if i can use the same pins for multipurpose
Thanks!

Did you read the warning about the Arduino Uno on that page? This goes for the Nano as well. That said, yes, it's probably technically possible.if you can find a suitable library and you can overcome the memory limits stated on the product page and the fact that you have to share the SPI bus between two devices. I really don't recommend it for a novice. You're probably better of with a shield designed for and supported by the Arduino.

The SPI sharing part is the one that I'm mostly confused about. Also if i go with a shield, that would limit me to arduino UNO

The physical difference between Uno and Nano is the least problem. RAM problem already inhibits using a Nano/Uno with that 880×528 display. Using an SD reader alone takes at least half of the Uno/Nano RAM. A Jetson Nano is not an Arduino Nano.

What would be the ideal solution (not limited to arduino) to use the display and sd card together, using least amount of power, meaning no power wasted on any other processes?

Sharing an SPI bus should not be a problem If you design it well. The MISO, MOSI, and SCLKs can be connected to both devices, the Chip Selects (CS) need to be separate. This is the way many commercially available shields (for example the Arduino Ethernet shield with Ethernet / SD card or many TFT shields with TFT / Touch interface and SD card combined on one SPI bus) work,

No. Even the e-Paper alone is not usable by an Arduino Nano.


text:
Addressing EACH of the 3x3x3 LEDs separately
I read a few 3x3x3 LED tutorials, e.g. let us take this one:
http://www.instructables.com/id/Making-an-Arduino-3X3-LED-Cube-in-Less-Than-30-Min/?ALLSTEPS
As far as I understand, you can address any of the 3x3 light columns:
*  *  *       1  2  3
*  *  *       4  5  6
*  *  *       7  8  9

and each of the three vertical layers:
top
middle
bottom

But can I address each of the 27 leds separately? In other words, can I light up:
1+  2   3         bottom layer
4   5+  6
7   8   9

1   2+  3         middle layer
4+  5   6
7   8   9

The link to the code in the Instructables article doesn't work - can you please edit your question to include it?

@DenisKulagin You should also take a look at "addressable" leds. You chain them, can address each of them individually and are RGB. Instead of 3 cathodes and one anode or vice versa, they all have their own little chip aboard and they can be "programmed". You can chain their data pins so you would just need 1 pin of the arduino to control them.

@larzz11 Those are totally cool. But if you want to play around with Arduino, cubes are good as well)

@DenisKulagin Not sure what you mean, I would think that making a cube out of addressable leds would be easier than making it with regular LEDs.

@larzz11 Are you talking of a led strip or individual addresable LEDs?

I am talking about individual addressable LEDs, but such a led strip is made of individual addressable leds....

3 * 3 * 3 = 27
The easy/overkill way
You could do this by assigning a pin to every LED (on an arduino Mega)
The overkill way
Use shift registers, almost any arduino will do.
The shift register will set it's outputs according to the amount of high/low signals being clocked in.
In theory, you can address an infinite amount of LED's (only limited by space, time or funds).
Breaking it down
You can break it down, so that you control each layer at once.
Effectively you only drive 9 LED's (1 layer).
And attach a transistor to the negative side of the layer.
This way you can choose a LED with the positive side, and a layer with the negative (per layer) control.
Switching these layers rapidly, will make the changes invisible to the eye. So it seems that the LED's are on all the time.
To infinity
Combine the overkill way (shift registers) with breaking it down (to reduce cost/size) and you'll be able to create a (somewhat) scalable design.
There are an awfull lot of tutorials, I suggest you choose one you can understand, try to make a smaller cube, and scale up from there!
Scaling issues

You'll need a better powersupply for each series of LED's you add.
Costs.
Processing time, the arduino might not be able to clock the signals fast enough, making it visible for eyes. (depends on the amount of LED's)

Be sure to check/measure/calculate these things along the project.

No, the three transistors are there to select the layer you want to control. At every moment only ONE layer can be on. But if you switch through controlling these layers fast enough, you can create the illusion of having multiple leds on even across layers. THis is because the human eyes are just not capable of seeing lights flashing at a high rate.
TL;DR
No you can't address them individually, but you can create the illusion that you can.

I got the idea, it might work!

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


text:
Double clap sensor not working as intended
I have this double clap sensor code written, it seems it would work but it seems to trigger the double clap even on a single clap, any ideas?
int soundSensor = A1;
int relay = A2;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
int claps = 0;
long detectionSpanInitial = 0;
long detectionSpan = 0;
boolean clapState = false;
int doubleClap = 0;

//Light sensor
int photocellPin = A0;     // the cell and 10K pulldown are connected to a0
int LEDbrightness;

//int delayValue = 100;
int photoSensor = 0;

// sound sample
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;

//other
boolean isRelaysOn = false;
void setup() {
  pinMode(soundSensor, INPUT);
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  turnRelayOff();
  Serial.begin(9600);
}

boolean state = false;
boolean lastState = true;
boolean lightTurnedItOff = false;
void loop() {

  /////////////
  // photo sensor
  ////////////////////

  photoSensor = analogRead(photocellPin) > 623;

  /////////////
  // clap sensor
  /////////////////////
  double sensorState = getSoundLevel();
  Serial.println(sensorState);
  double threshold = .2;

  if (sensorState > threshold)
  {
    if (claps == 0)
    {
      detectionSpanInitial = detectionSpan = millis();
      claps++;
    }
    else if (claps > 0 && millis()-detectionSpan >= 50)
    {
      detectionSpan = millis();
      claps++;
      Serial.println(" CLAP ADDED!!!!");
    }
  }

  if (millis()-detectionSpanInitial >= 400){

    if (claps == 2)
    {
      claps++;
      doubleClap = 1 - doubleClap;
      state = !state;
      Serial.println("TWO claps!");

      if(lastState == state ){
        relayControl(doubleClap);
        lastState = !lastState;
      }
    }
    claps = 0;
  }

  if(isRelaysOn == true && photoSensor == 1){
    turnRelayOff();
    lightTurnedItOff = true;
  }
  if(isRelaysOn == true && photoSensor == 0 && lightTurnedItOff == true){
    turnRelayOn();
    lightTurnedItOff = false;
  }

}

void relayControl(int doubleClap){
  /////////////
  // relay control
  /////////////////////

  if(doubleClap == 1){
    turnRelayOn();
    Serial.println("on");
    isRelaysOn = true;

  }
  else{
    turnRelayOff();
    Serial.println("off");
    isRelaysOn = false;
  };

}

void turnRelayOn(){
  int delayAmount = 100;
  digitalWrite(relay, LOW);
  delay(delayAmount);
  digitalWrite(relay2, LOW);
  delay(delayAmount);
  digitalWrite(relay3, LOW);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  delay(100);
  digitalWrite(relay4, HIGH);
  delay(100);
  digitalWrite(relay4, LOW);
}

void turnRelayOff(){
  digitalWrite(relay, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
}

double getSoundLevel(){

  unsigned long startMillis= millis();  // Start of sample window
  unsigned int peakToPeak = 0;   // peak-to-peak level

  unsigned int signalMax = 0;
  unsigned int signalMin = 1024;

  // collect data for 50 mS
  while (millis() - startMillis < sampleWindow)
  {
    sample = analogRead(soundSensor);
    if (sample < 1024)  // toss out spurious readings
    {
      if (sample > signalMax)
      {
        signalMax = sample;  // save just the max levels
      }
      else if (sample < signalMin){
        signalMin = sample;  // save just the min levels
      }
    }
  }
  peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
  double volts = (peakToPeak * 3.3) / 1024;  // convert to volts

  return volts;
}

Serial monitor:

0.02
  0.02
  0.02
  0.02
  0.01
  0.01
  2.20
  0.30  CLAP ADDED!!!!
  0.13
  0.09
  0.04
  0.02
  0.02
  0.01
  0.02 TWO claps! on
  1.11
  0.06
  0.05
  0.07
  0.15
  0.10
  0.03
  0.10
  0.06
  0.03
  0.04
  0.06

Other than this being a possible duplicate of your other question. Could you also give more info like a copy of the serial monitor for one loop when you have clapped. Also try moving else if (sample < signalMin){ signalMin = sample; } out of the if(sample <1024) as you will never enter that else if statement and peaktopeak will always be greater than your threshold.

It would help if you described your intended logic better.  There are a bunch of state variables (state, lastState, doubleClap) and several timeouts; deciphering your intent from code which doesn't accomplish that intent is extra work and error prone.

@RSM The else is not hard to enter; consider the first two samples 600, 500.  Both are < 1024.  The first will set signalMax=600, the second will set signalMin=500.  There is a different logic error however, which could be fixed by removing "else" so there are two if statements, one setting signalMax and one setting signalMin; the thing is, the first value should trigger both if statements.  Otherwise (with the else) consider what happens with samples 100,300,700,900 - each one sets signalMax, but signalMin is never set and retains the dummy 1024 value for a span of -124 instead of 800.

@RSM I added the serial monitor.

What you probably want to track is something more like:

high sound period of highMin to highMax ms
low sound period of lowMin to lowMax ms
high sound period of highMin to highMax ms
low sound period of at least lowDone ms (no max needed)

Anything not meeting those time bounds is not two claps, reset state and timers.  If you get to the end of the fourth step, accept as two claps.
I have not tested timing of claps to estimate the periods needed; you need to tweak that with the hardware you are actually using; for example, different microphones may ring for different times after a sharp clap impulse.
States could be:

waiting for start of first clap (sample until > threshold)
waiting for end of first clap (sample until < threshold or timeout)
waiting for start of second clap (sample until > threshold or timeout)
waiting for end of second clap (sample until < threshold or timeout)
got second clap

If your first clap rings for more than 50ms, the program counts it as a second clap.  After detecting a clap, you need to wait for the sound to die down before you start listening for a second clap.

I have noticed that you have used analogue inputs as your digital outputs by connecting relays to them.
I think this is wrong. You should connect your digital signals to the digital pins.

It really doesn't matter that much.

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


text:
How can I pass a char array as the parameter to a function?
I am creating a menu for adjusting system variables.
The menu is made up of pointers like so:
char* options4[] = {"hMin1", "hMax1", "refr1", "fSpeed1"};

I want to pass the selected string as the parameter for an 'adjust' function for use in some conditional logic and for display on a HCMAX7219 7 segment display. Here's what I've got:
int option = 0;
float variable = 82.0;

if(Serial.available() > 0) {
  key = Serial.read();
  if(key == back) {
    return;
  } else if(key == fwd) {
    float newVar = adjust(String(options4[option%4]), variable);
  } else if(key == down) {
    option++;
  } else if(key == up) {
    option--;
  }
}

float adjust(char* str, float var) {
  ...do some stuff...
  display.print7Seg(str, 8);
  EDIT: forgot this call..
  display.print7Seg(var, 1, 4);
  ...do stuff to var...
  return var;
}

The library function takes (char[] TextString, unsigned int Offset) as it's parameters.
EDIT: the library also has functions print7Seg(long number, byte decimalPlace, unsigned int Offset) and print7Seg(long number, unsigned int Offset)
Now I'm new to pointers, but I can see that I am passing a pointer to my adjust function, and expecting it to dig out a char array from memory. I can't see any problems with that, though I may be missing something. When I try to compile, the IDE just crashes with exit status 84; so no debug info.
Am I going about this the wrong way?

There are one or two things missing in your code. Where is setup() and loop()? Or is it just a snippet?
But answer to the question first. This is not right:
newVar = adjust(String(options4[option%4]), variable);

Should be:
newVar = adjust(options4[option%4], variable);

You want to index the vector of strings and pass one of the elements to the function.
Cheers!

It is just a snippet yeah. The full code is about 300 lines so thought I'd try to keep it brief. There are 12 variables to adjust so a generic function is what I'm aiming for.
You're absolutely right about the typecasting on the function call, I didn't spot that.
I've commented that line out for compilation, as I'm yet to think of a way of assigning the variable, so that's not the cause.
Thanks for the spot though.

Do you mean the cause of the IDE crash?

Yeah, the cause of the IDE crash could be linked to a problem in the code.

Then you will have to post all the code and tell us about the Arduino IDE version, board, etc. Have you turned on the "Show verbose output during:" in the IDE Preferences? Collect as much info as possible before the crash of the IDE.

And I would also suggest changing the title of this post??

I think the cause of the crash was an attempt by the library to treat a float as a long. I don't know a whole lot about the compilation process, but changing this seems to have solved the problem.. it compiles at least.

Let us continue this discussion in chat.

Ah .. ok I've just figured it out..
This is a legitimate way to pass char arrays to functions.
The original char* options4[] array is just an array of pointers to char arrays in memory, so passing one of these pointers to a function works fine.
The culprite was actually my float parameter, I was trying to make a library function call with a float to this function: print7Seg(long number, byte decimalPlace, unsigned int Offset).
This is what was causing the IDE to crash.
I got around it by having an int version of each of the variables I need to set. Then typecasting and dividing by a float to get variables that will be used in the main program. like so:
int hMin1Int = 820;
float hMin1 = (float)hMin1Int / 10.0;
int hMax1Int = 880;
float hMax1 = (float)hMax1Int / 10.0;
int refr1 = 30; //minutes
int fSpeed1 = 128;

I was then able to change my function to accept an int, the library function, so far, seems to be ok treating an int as a long, but if not I can just make all my ints longs:
int adjust(char* str, int var) {
  ...do some stuff...
  display.print7Seg(str, 8);
  display.print7Seg(var, 1, 4);
  ...do stuff to var...
  return var;
}

I was asking the wrong question!
Still I hope this will be useful to someone, so I will leave it up. Thanks for the response Mikael Patel.
Moral of the story, know your library.


text:
Is it safe to place a capacitor across vin and gnd?
I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.
The ATX is gated by a relay on its DC side and seems to cause enough of a current drain that it causes the Arduino to reset.
I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?
Standard?
EDIT:
Here's a very basic sketch..

12V Transformer powers arduino on VIN/GND pins, other pins are 5V, GND and control for relay

If you directly drive the relay from an Arduino pin (as it seems on the provided drawing), then you should probably consider using a transistor (or a MOSFET) to drive it. Finally, don't forget to use a flyback diode to avoid ruining your Arduino because of high flyback voltage.

I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.

I don't entirely follow that wording. Please draw a picture.

I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?

470µF is fine. In this situation the bigger the better. If 470µF fixes it then 470µF is fine. Don't be afraid of going higher though. I have 3,300µF capacitors here that are commonly used for similar purposes.
What you have implemented is called a reservoir capacitor and is a common use for large value capacitors like that.

Perfect..That makes sense. Thanks.  reservoir eh! Hope the drawing makes the first statement clearer.


text:
Voltage divider producing unexpected voltage
I'm trying to run a neopixel strip and an arduino from the same power supply using a voltage divider to get 5V to the strip.
Here are the values for my voltage divider:
R1 = 1500 Ω
R2 = 1000 Ω
Vin = 12 V
resulting in:
Vout = Vin*(R2/(R1+R2)) = 12*(1000/(1500+1000)) = 12*(1000/2500) = 12*0.4 = 4.8
When the divider is connected at its inputs but not at its outputs, I measure the expected 4.8V across R2. But as soon as I connect the neopixels, I only get about 1.6V.
Could anybody explain this || Suggest a possible solution?

You cannot use a voltage divider to supply power. It does not work. It can not work. Learn Ohm's Law and you will know why it can not work. Use a voltage regulator.

I guess that would be a power limitation of the resistors. Unable to take the current load. That's a great shame, I would like to be able to construct a functional level shifter from compon components. Thanks for pointing me towards a voltage regulator.

It is not a power limitation. It is Ohm's Law. Edgar's answer tells you why in brief.

hmm .. rookie mistake. I certainly belive that it's not possible, but I don't understand why... I have some reading to do.

I should point out here that NeoPixels can draw up to 60 mA each at full brightness. You need quite a hefty 5V power supply to power a lot of them. I suggest a suitable 5 volt DC regulated wall-wart (or similar) rated at a few amps. Even only 20 of them will require 1.2 amps.

Since you are connecting your pixel strip in parallel with R2, the
correct formula is
Vout = Vin × (R2∥Rp) / (R1 + (R2∥Rp))

Where Rp is the resistance of the pixel strip and
R2∥Rp = R2 × Rp / (R2 + Rp)

is the combination of R2 and Rp in parallel. From this you can see that
an output voltage of 1.6 V is consistent with a strip resistance of
300 Ω.
This is, however, somewhat oversimplified, as the I(V) characteristic of
the LED strip is probably non-linear, thus not really equivalent to a
resistor.

Thank you, that explains the output nicely. Though I'm not familliar with this use of '||' double pipe.

@xeuari It means "In parallel with"

@xeuari: It's not a doubled pipe character: it's single character, namely U+2225 PARALLEL TO. Compare: “||” vs. “∥”.

authors: ฆอยรูดิน คมขํา


text:
Have I fried the voltage input on my Arduino Nano?
I tried using my Arduino Nano in a circuit, switched on power to the circuit and heard a crack and smelt a bit of burning - something shorted.
I have plugged my Arduino into my PC with a USB, the light comes on - it's detected by my PC, so it's not fried completely.
However, when I try powering the Arduino with a 12V 2A wall adaptor (it was working with that before) no lights. Is it possible I somehow fried the voltage input or ground pins - or the voltage regulator (if it has one)?

the usb chip is different than the workhorse chip; you can fry one but not the other. usually, the uart survives (if anything does) in my experience.

Did you try uploading a simple sketch (e.g. blink) to check whether the microcontroller is still working?

12V, 2A through a shorted LDO? Yes. It's toast, or something else in the power path (diode?) is toast.
If you are good at soldering you could maybe replace the component, but probably easier to just use a 5v supply instead.


text:
Arduino with stepper motor
I'm trying to control a stepper motor for my FYP with an Arduino Mega. I tried code form examples, stepper one revolution. It worked when I uploaded it but if i turn the power off during the half position of a revolution, then next time I turn on the supply it first moves that portion backwards then it works according to the program. I want that when I turn on the power supply it should move according to the code and forget the last movement. Can anybody help me on this issue?

Please post your code so that others can see how it's written and provide help/advice.

A stepper motor doesn't have any mechanical "steps" as such. When powered off, a stepper is free-wheeling. When you power it up - energize a set of set of coils - the rotor will move to the nearest of several positions corresponding to whichever coils are energized. Thus, it doesn't retain its position across a power-down; your code has to "find it" each time. Usually that involves driving it until the attached mechanism trips an optical or mechanical switch, giving the software a reference-point. Your other option is to apply a holding current (less than the stepping current) to the presently energized coils and not completely power down the motor's power supply when the rest of the system powers down. The software would have to save the motor position before the power down in a non-volatile memory, such as EEPROM, where it can retrieve it again at the next power-up.


text:
ESP8266 doesn't connect to WiFi
I'm using an ESP8266 with the following pin configuration and it doesn't connect to my WiFi. The blue light on the ESP module is on and my LED is on. That's it.

VCC - 3.3v
GND - GND
CH_PD - 3.3v
GPIO 0 - GND
GPIO2 - LED

I'm using a 1,000 mah 3.7 LiPo battery for this.
Here's my Arduino code. I'm following a tutorial from nyl.io.
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

const char* ssid     = "sukkaa";
const char* password = "123456789123";
const char* host     = "www.sukkzzesp.tk"; // Your domain
String path          = "esp\light.json";
const int pin        = 2;

void setup() {
  pinMode(pin, OUTPUT);
  pinMode(pin, HIGH);
  Serial.begin(115200);
  delay(10);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  int wifi_ctr = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: " + WiFi.localIP());
}

void loop() {
  Serial.print("connecting to ");
  Serial.println(host);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  client.print(String("GET ") + path + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: keep-alive\r\n\r\n");
  delay(500); // wait for server to respond
  // read response
  String section="header";
  while(client.available()) {
    String line = client.readStringUntil('\r');
    // we’ll parse the HTML body here
    if (section=="header") { // headers..
      Serial.print(".");
      if (line=="\n") { // skips the empty space at the beginning
        section="json";
      }
    } else if (section=="json") { // print the good stuff
      section="ignore";
      String result = line.substring(1);
      // Parse JSON
      int size = result.length() + 1;
      char json[size];
      result.toCharArray(json, size);
      StaticJsonBuffer<200> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success()) {
        Serial.println("parseObject() failed");
        return;
      }
      // Make the decision to turn off or on the LED
      if (strcmp(json_parsed["light"], "on") == 0) {
        digitalWrite(pin, HIGH);
        Serial.println("LED ON");
      } else {
        digitalWrite(pin, LOW);
        Serial.println("led off");
      }
    }
  }
  Serial.print("closing connection. ");
}

Pls help me with this error. Thanks.

with io 0 LOW esp8266 goes into bootloader mode

Hi Juraj I removed GPIO 0 from GND and still the same results. Not connecting and theres a small hum coming from the esp chip

you power it with 3.7 V?


text:
Turn led on after ringing once, off after two rings when hung up SIM800
I'm trying to make something that has one led and a gsm module which is SIM800L, I'm using seeeduino GPRS library.
What I'm trying to do is that when I call the GSM module and hung up after ringing once (about 2 seconds of ringtone) the led turns on, and when I call again and hang up after the second ringing sound (about 5 seconds of ringtone) the led turns off;
Note that the SIM800 module when starts receiving a call it prints on the serial every ringing period (about 2.5sec):

RING
{number 0664xxxxx}

then it shows up again telling, 2 times for one rington, 3 times for two ringtons, and when I stop calling the GSM the module prints:

NO CARRIER

Here's my code as start:

#include <SoftwareSerial.h>
String inData;
char incomingByte;
//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8

//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(9600);
  delay(1000);

  Serial.println("Setup Complete!");
}

void loop() {
  //Read SIM800 output (if available) and print it in Arduino IDE Serial Monitor
  if(serialSIM800.available()){
    Serial.write(serialSIM800.read());
    incomingByte = serialSIM800.read();
    inData += incomingByte;
  }

if(inData != "")
   {
     if (inData.indexOf("RING") >= 0) {
      delay(4000);
      serialSIM800.println("ath"); // Hang up at command
      inData = "";
     }
  }

  //Read Arduino IDE Serial Monitor inputs (if available) and send them to SIM800
  if(Serial.available()){
    serialSIM800.write(Serial.read());
  }
}

I did this code so it hangs up 4 seconds after calling printing the message "RING", but it didn't work, can you please help guys, thanks!

If it didn't work, what did it do? What do you see in the serial monitor?


text:
Hiding WLAN password when pushing to GitHub
I have started to use GitHub to store Arduino code. However some of my code uses the SSID and password for my WLAN which I don’t want published.
A common way of handling this in non-embedded programming is to use a configuration file, but that doesn’t seem to be a viable approach in programming the Arduino. I’m currently just commenting out the sensitive information before pushing it to GitHub, but one day I’m sure I’ll forget.
Is there another – better - way of handling this?

Sure you can use a config file. It's called a "header" file, and you just #include it in your sketch.
[config.h (not pushed)]

const char *password = "DOD982yp398fhgpwbn09tupf0p04";

[sketch.ino (pushed)]

#include "config.h"

// Now you can use the password variable.

Another method, which is better if you have multiple files in your sketch, is to use #define instead of variables in your header file:
[config.h]

#define WIFI_PASSWORD "348r0yp80ytwp85tpj8yjp98y97t8t"

[sketch.ino]

#include "config.h"

const char *password = WIFI_PASSWORD;

Of course! It never occurred to me to use a header file in this way. Many thanks for the answer.

One thing to watch is if you have multiple files in your sketch and you include that config file in each you will get errors about multiple definitions. In that case it's probably better to use #define instead of defining the variables directly.  I'll post an example.

You could commit the following file into your project, named
credentials.h:
// Replace with your actual SSID and password:

#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

Near the beginning of your sketch, you add:
#include "credentials.h"

const char ssid[] = WIFI_SSID;
const char password[] = WIFI_PASSWD;

Now, you can edit credentials.h to add your real SSID and password, and
go on with your normal git workflow, with one exception: never
git add credentials.h again, nor git commit -a.
Now, git will always remind you that credentials.h has been modified and
is not staged for commit. It will do so even if you add the file to your
.gitignore. If you always review your changes before committing, this is
only a minor inconvenience. If, on the other hand, you tend to
git commit -a without reviewing what you are committing, then this
solution is likely not for you.

Edit: An idea I got from reading Chris Stratton's comments. If
you use a Makefile in your own workflow (this has already been discussed
in this site a few times), you could commit this credentials.h to your
repo:
#ifndef CREDENTIALS_H
#define CREDENTIALS_H

// Replace with your actual SSID and password:
#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

#endif

Make a copy of this file named true-credentials.h and put the real
credentials there (but do not rename the include guard). Then add to
your Makefile
CFLAGS += -include true-credentials.h

Keep true-credentials.h and the Makefile out of the repo. You can add
them to your .gitignore or, better yet, to .git/info/exclude.
Now you have a compilable version with dummy credentials in the
repository, you have the true credentials when you compile on your own
machine, and git does not bother you about credentials.h being changed.

Interesting points and thanks. Looks like I am going to have to be more careful in how I use git.

This is a better solution, however, no, git will not tell you about changes to files in .gitignore unless you explicitly add them.  And adding a file explicitly excluded by .gitignore typically requires adding with a force flag.

@ChrisStratton: In my test, I added and committed the dummy credentials.h, then modified the file and added it to .gitignore. Git kept telling me “Changes not staged for commit: modified: credentials.h”. My point was to have a compilable version on the repo, hence the dummy credentials.h added there.

If you commit a dummy version, yes.  You may want to give the dummy version a different name, like credentials.h.CUSTOMIZE_ME or something, and perhaps back it up with a #ifndef #error giving instructions to make a copy without the suffix and edit.

Actually, nevermind, my idea won't work since the #include will fail without the custom message.  Really shows the primitiveness of the Arduino IDE compared to something permitting a sensible project file or a custom Makefile.

Eventually settled on the approach of adding the credentials.h reference to the .git/info/exclude file and having  a dummy credentials_CUSTOMIZE_ME.h file tracked by git (as explained above).  Also, added a README.md file to explain everything. Not using a Makefile at the moment, but that may change. Many thanks all for your help.

Building upon the shoulders of giants I took Edger Bonet's answer and used a slightly different twist.  I went this route because I don't use a makefile and found this solution works well for me in my project.
I created a placeholder credentials.h file with the following info (Edger's answer).
#ifndef CREDENTIALS_H
#define CREDENTIALS_H

// Replace with your actual SSID and password:
#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

#endif

I further added the reference to this new file in the .ino file.
#include "credentials.h"

const char ssid[] = WIFI_SSID;
const char pass[] = WIFI_PASSWD;

Now the twist.. I excluded the file from being checked for changes using the --assume-unchanged command.

git update-index --assume-unchanged credentials.h

You can then modify the credentials.h file and wont be prompted to add it to github.
Note, to re-check the file use --no-assume-unchanged.

Kudos for the --assumed-unchanged tip!


text:
tinygps abnormal behaviour with EM408 gps
I have an Arduino Duemilanove and em408.
My code is this:

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

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPS gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

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

void loop()
{
  while (ss.available())
  {
    char c = byte(ss.read());
    // Here i tried Serial.write(c); and i succesully saw the NMEA data in my serial monitor
    if (gps.encode(c))
    {
      long lat, lon;
     unsigned long fix_age;
    gps.get_position(&lat, &lon, &fix_age);
    if (fix_age == TinyGPS::GPS_INVALID_AGE )
      Serial.println("No fix ever detected!");
    else if (fix_age > 2000)
      Serial.println("Data is getting STALE!");
    else
      Serial.println("Latitude and longitude valid!");

      Serial.print("Lat: ");
      Serial.print(lat);
      Serial.print(" Lon: ");
      Serial.println(lon);

    }
    else Serial.println("No data!");
  }
}

My output is this:
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
No data!
Latitude and longitude valid!
Lat: 32758239
 Lon: 15637489
No data!
No data!
No data!
No data!
No data!
No data!
No data!

And then i continue getting No data! forever...
So...

Why does gps.encode() only manage to return true only 1 time? I have gotten the raw data from the gps (the commented code on my code snippet) and it's ok. Why it returns true only one time?
Why the longitude/latidude data is like this? As far as i know, this isnt valid, correct?

EDIT:
Also tried with TinyGPS++.. but no luck in encoding too...
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

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

void loop()
{
  while (ss.available()>0)
  {
    char c = byte(ss.read());
    // Here i tried Serial.write(c); and i succesully saw the NMEA data in my serial monitor
    if (gps.encode(c)) //i previously used if(gps.encode(ss.read())); but no luck then
    {
      Serial.print(F("Location: "));
  if (gps.location.isValid())
  {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid())
  {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.println();

    }
    else Serial.println("No data!");
  }
}

New code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

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

char clat[11];
char clng[11];

void loop()
{
    //if (buttons || tilt) {
    //if (buttons & BUTTON_SELECT) {

        bool isGpsLocationValid = false;
        do
        {
            while (ss.available()>0)
            {
                char c = byte(ss.read());
                if (gps.encode(c)) //i previously used if(gps.encode(ss.read())); but no luck then
                {
                    if (gps.location.isValid())
                    {
                        dtostrf(gps.location.lat(), 11, 6, clat);
                        dtostrf(gps.location.lng(), 11, 6, clng);
                        //send-print
                        //delay (just in case multiple bumps)
                        isGpsLocationValid = true;
                    }
                }
             }
        } while (isGpsLocationValid == false);
        Serial.write(clat);
        Serial.println();
        Serial.write(clng);
       //}
    //}
}

EDIT: The newest code i have posted works 100%!
So if you have similar problems with that aweful gps, use this!
Apparently, TinyGPS and TinyGPS++ don't work well with this gps.
To be precice, there is a problem with the gps.encode(c) function.
So using if (gps.encode(c)) most of the times returns false, except some rare occasions which returns true and then you can do some processing...
My last code takes care of that problem by checking continuously, using a do...while loop.
If if (gps.location.isValid()) returns true, which means i have valid data, then i do the processing i want and end the do...while loop.

Your code doesn't seem to output "No data!" at any point. Is it supposed to be "Not encoded data!"?

Ok yeah. I modified the code

Try to change the baud rate of Serial.begin() to 4800 and in the serial monitor change the same.

Are you doing this indoors? Are you sure you have a GPS lock? You get NMEA data even without a lock, but they're empty NMEA data-frames.

Man, i know. I use it ourdoors. Get valid NMEA data (saw the coordinates on the raw data). Tried every combination of baud rate. Tried different permutations like
char c = byte(ss.read());
char c = ss.read();
int  c = byte(ss.read());
int  c = ss.read(); //best
byte c = byte(ss.read());
byte c = ss.read();
Noone can give me an answer, its ridiculous. Tried on arduino official foum, ene emailed the creator of TinyGPS and TinyGPS++...

If you're getting proper, locked GPS data if you output the raw NMEA stream, apparently there is an issue in the TinyGPS library, possibly as a result of an interaction with your particular GPS. Welcome to the world of open source. The TinyGPS library is a project someone did in their spare time, and released for free. They do not have to bother to support it at all. Since the source is available why don't you try to fix it yourself?

Try having tinyGPS parse the serial messages from the PC and then sending a valid NMEA string in the serial monitor yourself. That way you can be sure if the issue is with the library, or the GPS.

If you've solved the problem, could you post the solution as an answer? That will make it easier for future visitors to find. Thanks!

The newest code i have posted works 100%! So if you have similar problems with that aweful gps, use this!
Apparently, TinyGPS and TinyGPS++ don't work well with this gps. To be precice, there is a problem with the gps.encode(c) function.
So using if (gps.encode(c)) most of the times returns false, except some rare occasions which returns true and then you can do some processing...
My last code takes care of that problem by checking continuously, using a do...while loop. If if (gps.location.isValid()) returns true, which means i have valid data, then i do the processing i want and end the do...while loop.
NOTE: This code is for TinyGPS++ library. Same theory will work for TinyGPS too of course...
Here it is:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

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

char clat[11];
char clng[11];

void loop()
{
    bool isGpsLocationValid = false;
    do
    {
        while (ss.available()>0)
        {
            char c = byte(ss.read());
            if (gps.encode(c)) //i previously used if(gps.encode(ss.read())); but no luck then
            {
                if (gps.location.isValid())
                {
                    dtostrf(gps.location.lat(), 11, 6, clat);
                    dtostrf(gps.location.lng(), 11, 6, clng);
                    isGpsLocationValid = true;
                }
            }
        }
    } while (isGpsLocationValid == false);
    Serial.write(clat);
    Serial.println();
    Serial.write(clng);
}

Are you sure about while (isGpsLocationValid = false);? That should be while (isGpsLocationValid == false);, otherwise, you won't ever go out of this while loop!

oops, good observation

Thaks very much!!!
You have already given me the solution for my problem, I`ve been trying to get this data for 3 days!!
When I was using just the GPS module, it was fine, I could get the data, but when I tried to use GSM module + GPS, I could not get the data from GPS!! U gave me the solution
bool isGpsLocationValid = false;
        do
        {
            while (ss.available()>0)
            {
                char c = byte(ss.read());
                if (gps.encode(c)) //i previously used if(gps.encode(ss.read())); but no luck then
                {
                    if (gps.location.isValid())
                    {
                        dtostrf(gps.location.lat(), 11, 6, clat);
                        dtostrf(gps.location.lng(), 11, 6, clng);
                        isGpsLocationValid = true;
                    }
                }
             }
        } while (isGpsLocationValid == false);
        Serial.write(clat);
        Serial.println();
        Serial.write(clng);

Congratulations!!
Brazilian Hugs for you ; )

No problem... Just vote up my post, if you found it useful (becauce its -3 at the moment)

Is the conversion to byte what solves the issue? Because otherwise it doesn't make sense that this would work and the old code not since you still have to get through the encoding in order to execute the body of the IF.


text:
Sending binary data to Matlab via serial
I would like to exchange data via Xbee. I've set up a communication based on strings between the Arduino and a Matlab software.
Unfortunately this kind of communication isn't enough robust and sometimes messages aren't delivered correctly. So I decided to move to the binary communication.
The problem:
I'm not able to send binary data from the Arduino to the computer.
Let's say we want to send the decimal value 17 which is 0x11 in hex if we receive 16 from Matlab.

[...]
SoftwareSerial xbee(pinRx, pinTx);
void setup()
{
  Serial.begin(BaudRateSerial);
  xbee.begin( BaudRateXbee );
}
[...]
void loop()
{
 while(xbee.available())
  {
    getData = xbee.read();
    Serial.println();
    Serial.print("Received: ");
    Serial.print(getData,HEX);
    Serial.println();
    if(getData == 16)
    {
      // First attempt
      //uint8_t s = 17;
      //xbee.write(s);  -> Fail
      // Second attempt
      //xbee.write(0x11);  -> Fail
      // Third attempt
      byte message[] = {0x11, 0x11};
      xbee.write(message, sizeof(message));
    }
  }
}

In the third attempt I tried sending an array of bytes and noticed that the received values were different.
byte message[] = {0x11, 0x11};

xbee.write(message, sizeof(message));

The Matlab software sends data correctly. I used the fwrite function as follows fwrite(xbee,hex2dec('10')); and the fread function to receive the ack which:

reads binary data from the device connected to the serial port object,
  obj, and returns the data

Matlab relevant code:
fwrite(xbee,hex2dec('10'));
disp('Ack Requested...')
ack = fread(xbee);
disp(ack);
if (ack == 17)
     % communication established
end

I've also tried using XC-TU to monitor traffic on Serial port (blu values are sent from the PC, red ones are received from the Arduino) and as you can see red values are different and none of them is equivalent to 17! What am I missing?

what is the range of your number?

I think the problem is in Matlab. You send data from string so String a = "1"; is byte 31. Make a debug, add Serial.println(getData,HEX); and see what are you getting

The range is +/- 5000. I am able to receive data from Matlab. I've done the test with XC-TU to see the hex values sent from Arduino and as you can see, the boards sends every time different values. (Red ones) XC-TU and matlab receive the same data.

xbee.write(message, sizeof(message)); this shows in MatLab as 75,70??? Not sure but try to check baud rates or so. I just can't see what is wrong..

Yes exactly. Every time I click a button in MATLAB, it sends 16. Arduino receives it and responds with 17 twice. The values sent are completely different from each other. It doesn't make sense... Is the software serial library the problem?

Add Serial.println(getData,HEX); after getData = xbee.read(); and say what you get

The value displayed on the serial monitor is 16

Ok, now it works. It was because of a previous sketch uploaded. There were bytes stored in the buffer. The values I was receiving belonged to an old buffer. Maybe xbee.flush() should do the job

if you can read "17" in the serial monitor you sent the characters "1" and then "7", not the binary number 17.

narutov6 please clear your question and problem. From now it is hard to unerstand what is wrong. Be more detail and eliminate all unnecessary parts


text:
How to communicate with ESP8266 ESP01 by sending data through softwareserial on Arduino Uno?
I am able to send AT commands when connecting to the software through the TX/RX pins (1, 0) and the ESP01 communicates perfectly. However, as soon as I start doing that same thing with code I can't get the ESP01 to respond whatsoever. All I'm trying to do is get an OK back from the serial monitor. I changed the baudrate on the ESP01 as well as my serial monitor from 115200 to 9600, 19200 using this command:
AT+UART_DEF=9600,8,1,0,0
Troubleshooting steps taken:

Tried upping the voltage in case it wasn't getting enough current.
Tried different ESP01s.
Tried switching TX and RX pins.
Tried using different pins on the Uno (2 and 3, 10 and 11, 7 and 8).
tried changing myESP.println("AT"); to myESP.write("AT\n\r");.

Nothing works. I've done a ton of research and I haven't found anything wrong with what I'm doing, do you guys have any ideas?
#define TX 3
#define RX 2
String ssid = "*****";
String password = "******";

#include "SoftwareSerial.h"

SoftwareSerial myESP(RX,TX);

void setup() {
  pinMode(RX, INPUT);
  pinMode(TX, OUTPUT);
  myESP.begin(19200);
  Serial.begin(19200);
}

void loop() {
  myESP.println("AT");
  delay(5000);
}

Schematic is as follows:
TX -> pin 3
RX -> pin 2
Vcc -> 3.3v
GND -> Ground
CH_PD -> Vcc

How about this:
void loop() {
  while(Serial.available() > 0) {
     myESP.write(Serial.read());
  }
  while(myESP.available() > 0) {
     Serial.write(myESP.read());
  }
}

That code will continue to load data to and from the software serial not just one byte. You can also use string concatenation:
String data = "";
while(Serial.available() > 0) {
   data += Serial.read();
}

Or arrays:
int data_max = 4096;
int data_size = 0;
char data[data_max];
while(Serial.available() > 0) {
   if(data_size < data_max) data[data_size++] = Serial.read();
}

Please explain in your answer how this solves the problem. That way future viewers know how to solve this issue and why it fixes the problem.

Alright so I figured out my issue. Here's the answer for anyone with this problem in the future.

Remove pinMode(RX, INPUT);
and pinMode(TX, OUTPUT);.
SoftwareSerial isn't going to relay the response back, so you have to program a response in, that's why sending "AT" by itself to the serial port is pointless.

"SoftwareSerial isn't going to relay the response back"? Not clear what you were expecting, but @jdwolf's example of two while loops is the correct way to communicate from the Uno's terminal to an Uno-connected serial device. ESPs do indeed respond back and SoftwareSerial does collect that response for you. What do you mean by "you have to program a response in"?

RX from Arduino goes to TX on EXP, and
TX from Arduino goes to RX on ESP, BUT
Why not just put ESP01 in program mode and upload adruino code directly to it doing away with the AT commands


text:
Is it possible to increase the voltage on 3.3v output to 5v on an ESP board to power a DC motor?
I am trying to use an ESP32s controller connected to an RC car DC motor. I found that when using my Arduino this is easily accomplished, and I can see that my output pin produces 5v for the motor to spin. My ESP32, however, only produces 3.3v, so of course the motor does not spin. Do I need to use a motor driver board, transistors, or will the ESP32 simply not work in this scenario?
Thanks in advance.

where are you measuring 1.8v?

I wrote a simple sketch in my ide that pushes High and low voltage to one of my esp's output pins, with a 1 second delay in between each.

If you are measuring 1.8v, you are loading the pin beyond it's designed capability.

yes I should be using a resistor, it was a quick test.

You should not power a motor from a micro-controller, period, regardless if that is an ATmega or an ESP32.
Instead, you need to use a motor driver circuit - this isn't really so much about voltage amplification, as it is about current amplification. The actual I/O output voltage of your ESP32 is likely very close to 3.3v. If you are measuring 1.8v, that is only because you motor is loading the pin so heavily (and improperly) that the voltage sags.
Without the specs of your motor, it's not really possible to provide any specific advice. But you should seek an FET-based solution, not one based on bipolar transistors.  The old bipolar L293D, L298, etc parts are horribly lossy and extremely unsuited to low voltages motors. In some low-voltage, low-current cases, the FET-based TB6612FNG can be a good solution - but again, this depends entirely on the unstated requirements of your motor. Typically only very lightweight or weak "RC cars" could use such drive, for more serious ones you should look at hobby-grade Electronic Speed Controller (ESC) modules, or their equivalent circuitry.
These motor driver chips will have two supply inputs. One supplies the logic and would typically share the microcontroller's supply voltage. The other supplies the motors - it might in light duty cases be whatever is supply the microcontroller's regulator, but in more power-hungry cases would often be a unique supply. Both grounds should be connected together and connected to the microcontroller's ground, but in such a way that the ground current for the motors flows directly from the power supply, and never through the microcontroller board.

What I'm actually trying to do, is use an existing circuit's motor driver, and use the esp, to send the signals to it. The existing circuit has it's own 4.8 bat, and I have identified and soldered into the circuit at each point to send power to dc motor(s) L/R/B/F and an additional extended ground wire.  The esp is has its own power and will be the controller. I saw another post where someone was doing this but with an arduino uno (which works). Here are the pictures to the circuit before I soldered into it: https://1drv.ms/f/s!ApWkEol-uDERpBrBrpQp76IVMDuo

To have a valid question, you need to include the input specifications of what you are driving in the body of your question.  External links aren't really acceptable for critical parts of the problem statement.

Ok. Thanks for your answers. I think I figured out my problem.

I figured out my issue. I was only getting 1.8v output because I was testing my lead after a led light I had plugged in. Once I removed the led, my voltage went to 3.3v, which was expected.

Then your LED was improperly connected.  Likely you forgot the current limiting resistor, or else you chose an LED and LED current which exceeded the capability of the ESP32.

Hi Chris, I was being lazy and just forgoing the resistor to test it quickly. Thanks


text:
Measure an AA battery?
If I'm going to measure an AA battery (about 1.5 v) with a USB-powered Arduino, I will connect the battery's +ve terminal to the A0 pin. Shall I connect the -ve terminal to the gnd pin too?

Is the AA battery under any kind of load, or just connected directly to the Arduino and nothing else?

Yes you could although this means you're measuring in relation to the Arduino's logic voltage, which is slightly below 5v (due to a diode's voltage drop) or the voltage of vref.

Ok, after connecting arduino reads 234 (1.143 v), and multimeter reads 1.116 v. Is that because of arduino logic? how to fix that?

Try measuring the 5V pin on the Arduino. The USB on a computer is rarely exactly 5V. You might have to do some calibration.

@jdwolf USB-VCC goes through a mosfet (T2 on the schematic), not a diode. Rds(on) is about 70 mOhm, so only a 35mV drop if the board uses the maximum 500mA that USB can supply.

I would use the internal voltage reference of 2.56V, and a protection resistor of about 1k or 4k7 to A0.

@Jot What's the "protection resistor" supposed to be protecting against?

@Majenko, for minimal protecting of the internal clamping diodes. A mistake with a 6, 9 or 12V battery is easily made. Even with a 1.5V battery there could be a problem when the Arduino is turned off and the battery is still connected. Or when the battery is connected in reverse. You know, better be safe than sorry, especially for a beginner.

@Jot That is true, yes.


text:
How to create a 1-hour timer with an ATtiny13A microcontroller?
I want to control an AC load such that it powers on for 1 minute, then turns off for 1 hour, then on again for 1 min, and so on, in a loop.
I just modified the blink sketch to do:

Turn A1 on
Then delay for 60,000 ms
Then turn A1 off
Then delay for 3,600,000 ms (3,600 sec, or 1 hour)

...but it doesn't seem to work.
It looks like the LED connected to A0 turns on but instead of turning off after 1 min, it turns off after 8 min 30 s.
Any suggestions?

I rectified the sketch. Now it takes 1 sec as actual 1 sec. I chose 1 MHz clock in IDE.
int ledPin =  A3; // the number of the LED pin
int ledState = HIGH; // ledState used to set the LED
unsigned long previousMillis = 0; // will store last time LED was updated
unsigned long OnTime = 60000; // milliseconds of on-time
unsigned long OffTime = 10000; // milliseconds of off-time

void setup()
{
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // check to see if it's time to change the state of the LED
  unsigned long currentMillis = millis();

  if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
  {
    ledState = LOW;  // Turn it off
    previousMillis = currentMillis; // Remember the time
    digitalWrite(ledPin, ledState); // Update the actual LED
  }
  else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
  {
    ledState = HIGH;  // turn it on
    previousMillis = currentMillis; // Remember the time
    digitalWrite(ledPin, ledState); // Update the actual LED
  }
}

Then it turns on for 1 sec and then turns off for 1 sec, then randomly turns on at 30 sec or 1 min 30 sec. I want to turn it on for 1 min every hour.
I tried the Blink sketch modified as follows:
void setup() {
  pinMode(A3, OUTPUT);
}

void loop() {
  digitalWrite(A3, HIGH);
  delay(60000);
  digitalWrite(A3, LOW);
  delay(900000);
}

But it still turns on for 1 min and turns off for 1 min.
I also tried this:
void setup() {
  pinMode(A3, OUTPUT);
}

void loop() {
  digitalWrite(A3, HIGH);
  delay(60000);
  digitalWrite(A3, LOW);
  delay(3.6e+6);
}

No matter what I do on time and off time, it always remains the same.
I wanted to know one thing: can I set a 1-hour off and 1-min on timer using ATtiny13A or not?
I tried 1.2 MHz, 1 MHz, all clocks in the IDE, nothing seems to work.

What are you running this on?

Are you sure, that the Attiny is running at the frequency, that you think it runs? I once had my Attiny85 configured for 1MHz instead of the 8MHz, that I was expecting, so I wondered why my code was running 8 times slower.

How fast does the LED blink when you run the original and unchanged blink sketch?

Its about 8.4 seconds

Sounds like ChrisL nailed it. Your attiny13a is running at 1 MHz instead of 8.

How are you programming the ATtiny? Which programmer and board manager do you use?

I use arduino mega as isp attiny on breadboard

Please post your exact code. What are your variable types? int, for example, can only hold up to 32767 ms, NOT 3600000 ms! It is 2 bytes on AVR microcontrollers. That means unsigned int only holds up to 65535 ms.

Please move all your answers that are additions to your question to your question, then delete all your answers that aren't answers. It's okay to write an answer to your own question, but if you're just trying to improve your question, edit your question and add directly to your question instead.

As the unchanged blink sketch blinks with 8.4 seconds, I think my assumption is right. The clock of the Attiny is running 8 times slower, than the code thinks.
When you have installed the Attiny core, there should be a menu entry for the clock frequency. Most likely the standard is 8MHz. But having 8MHz set does not mean, that the Attiny is using 8MHz. To choose between different clock sources and frequencies, you must change the fuses of the microcontroller (which are just some bits of special non-volatile memory in the chip, that set special hardware configuration; more information in this question). This is done, when you burn the bootloader to the chip. That's the easy version. Alternatively you can use the avrdude command directly to set the fuses. That's the advanced way.
Currently the fuses of your Attiny seem to be set to the 1MHz internal clock. But the compiler uses the frequency, that you have chosen in the menu, hence 8MHz internal clock. So the compiler thinks, that the chip runs at 8MHz and thus generates the timing code for this execution speed. But your chip is currently 8 times slower, than the compiler thinks.
TL;DR: Burn the bootloader onto the chip to let the Arduino IDE set the right fuses for your clock frequency.

I doubt an ATtiny13a is large enough for a bootloader, having only 1K of Flash / program memory. My experience with ATtinyCore (which does not support the tiny13 AFAIK) is that it correctly sets the fuses when choosing the "burn bootloader" option even when, in the board settings, the "ATTiny XX (No Bootloader)" option is chosen.

Attiny13 has very as in very small memory. So if you want it to crunch stuff which seems to be easy for other mcu, it might not have enough memory for it. It cannot for example consistently carry out millis() like in:
long timeStart = millis();
.
.
.
if (timeIsUp=0 && millis()-timeStart=>60000)
.
.
.
The most that that code will loop is less than 50 seconds in my experience.
As a workaround I was able to make attiny13 keep track of time for more than 10 minutes by using only integers and using count. The count being incremented after 10seconds. So example:
for (int i=0; i>10; i++){
delay(10000);
count++;
Then you can use count to keep track of time that has elapsed.
Using millis() is very heavy for attiny13.

The code you wrote should work as expected. If it doesn't, I suspect
there is something broken in the Arduino core you are using. However,
such a trivial task can very easily be programmed in plain C, at the
avr-libc level:
#define F_CPU 1000000  // 1 MHz
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRB |= _BV(PB3);  // PB3 as output
    for (;;) {
        PORTB |= _BV(PB3);   // PB3 high
        _delay_ms(60e3);     // 1 min
        PORTB &= ~_BV(PB3);  // PB3 low
        _delay_ms(3.6e6);    // 1 h
    }
}

I would compile it with:
avr-gcc -mmcu=attiny13a -Os -Wall -Wextra 1h-timer.c -o 1h-timer.elf

See the Port Registers Arduino tutorial for the meaning of the
macros used here. You can tweak F_CPU to fine-tune the delays, in case
your ATtiny clock is not quite 1 MHz.


text:
How to add if condition in RFID example?
Using an Arduino Mega 2560 and PN532 NFC/RFID module, I want to be able to scan a card and see if its value is (0xF0, 0x21, 0x5D, 0xA7). It should print "accepted" in the serial monitor.
However during compilation it keeps telling me:
iso14443a_uid:99:11: error: expected primary-expression before ']' token

if (uid[] = {0xF0, 0x21, 0x5D, 0xA7}){
        ^

exit status 1 expected primary-expression before ']' token

This is my code:
/**************************************************************************/
    /*!
        This example will attempt to connect to an ISO14443A
        card or tag and retrieve some basic information about it
        that can be used to determine what type of card it is.
    Note that you need the baud rate to be 115200 because we need to print
    out the data and read from the card at the same time!

    To enable debug message, define DEBUG in PN532/PN532_debug.h

*/
/**************************************************************************/

/* When the number after #if set as 1, it will be switch to SPI Mode*/
#if 0
  #include <SPI.h>
  #include <PN532_SPI.h>
  #include "PN532.h"

  PN532_SPI pn532spi(SPI, 10);
  PN532 nfc(pn532spi);

/* When the number after #elif set as 1, it will be switch to HSU Mode*/
#elif 0
  #include <PN532_HSU.h>
  #include <PN532.h>

  PN532_HSU pn532hsu(Serial1);
  PN532 nfc(pn532hsu);

/* When the number after #if & #elif set as 0, it will be switch to I2C Mode*/
#else
  #include <Wire.h>
  #include <PN532_I2C.h>
  #include <PN532.h>
  #include <NfcAdapter.h>

  PN532_I2C pn532i2c(Wire);
  PN532 nfc(pn532i2c);
#endif

void setup(void) {
  Serial.begin(115200);
  Serial.println("Hello!");

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // Set the max number of retry attempts to read from a card
  // This prevents us from waiting forever for a card, which is
  // the default behaviour of the PN532.
  nfc.setPassiveActivationRetries(0xFF);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println("Waiting for an ISO14443A card");
}

void loop(void) {
  boolean success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

  if (success) {
    Serial.println("Found a card!");
    Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("UID Value: ");
    for (uint8_t i=0; i < uidLength; i++)
    {
      Serial.print(" 0x");Serial.print(uid[i], HEX);
    }
    Serial.println("");
    // Wait 1 second before continuing
    delay(1000);
  }
  else
  {
    // PN532 probably timed out waiting for a card
    Serial.println("Timed out waiting for a card");
  }
  if (uid[] = {0xF0, 0x21, 0x5D, 0xA7}){
    Serial.println("Success");
    }
}

= is assignment operator. you can't use constant initialization to assign a value to a variable. In if condition usually a comparison operator is '==' is used and it can't be used to compare arrays

well, it same if i use == and if i can't compare arrays so what is the right way to make that happens like if the card serial / uid is what i want to give access and print success is there a way to do that?

You have to compare each value in the array once at a time. Like if( uid[0]== 0xF0 && uid[1]==0x21 && ...)

Can you recommend a course for me that can get me to that as fast as i can, I've less than 3 months to get that project done, I've no idea about arduino or c++ my college put me in this situation i didn't even studied anything about electronics or even c++

@AbdalrahmanGamal, lol, i am very curious .... you used the statement I wanna in your post .... i have seen a lot of people use it .... i am wondering, how did you learn the word wanna? .... it not a word in the English language, by the way ... the statement should be I want to

As has been noted in the comments you can't compare arrays like that. Instead you have to iterate through each entry and compare the individual elements.
If it's just a few entries, then you can do it manually:
if ((uid[0] == 0xF0) && (uid[1] == 0x21) && (uid[2] == 0x5D) && uid[3] == 0xA7) {
    // ...
}

If your values are both in arrays then you can use the memcmp() function to compare them:
uint8_t compare[] = {0xf0, 0x21, 0x5d, 0xa7};

if (memcmp(uid, compare, 4) == 0) {
    // ...
}

memcmp returns 0 if the two arrays match up to the number of bytes given (4 in this case), or a negative or positive number if the one is "less than" or "more than" the other.