text:
ESP32 SPI Mutual Communication
I have two ESP32 cards. I want to set one of these cards as Master and the other as Slave and communicate via SPI. I have done this before on Arduino Uno, but I cannot do this on ESP32.
Below are my Master and Slave codes that I have prepared simply. I can't get what I want in any way. Can anyone help?
Master Code:
#include <SPI.h>

#define CS_PIN 5  // Choose the appropriate pin for Chip Select (CS)

void setup() {
  Serial.begin(115200);
  SPI.begin();
}

void loop() {
  char dataToSend = 'A';

  digitalWrite(CS_PIN, LOW); // Start communication with the slave
  SPI.transfer(dataToSend); // Send data to the slave
  digitalWrite(CS_PIN, HIGH); // End communication with the slave

  delay(2000); // Delay for demonstration purposes
}

Slave Code:
#include <SPI.h>

#define CS_PIN 5  // Choose the appropriate pin for Chip Select (CS)

void setup() {
  Serial.begin(115200);
  SPI.begin();
}

void loop() {
  if (digitalRead(CS_PIN) == LOW) {  // Check if CS (Chip Select) is LOW, meaning the device is selected
    char receivedData = SPI.transfer(0); // Read received data from the master

    // Display received data on the serial monitor
    Serial.println("Received Data: " + String(receivedData));

    delay(1000);  // Optional delay for demonstration purposes
  }
}

New Code - New Problem:
I tried to adapt the codes at https://microcontrollerslab.com/esp32-spi-communication-tutorial-arduino/. From what I understand it uses the following pins for SPI: MISO-12; MOSI-13; SCLK-14; SS-15.
I set my connections the same way, but I cannot get the output I expected from the Slave. It remains waiting at the slave.wait line.
Master Code:
#include <SPI.h>

// Define ALTERNATE_PINS to use non-standard GPIO pins for SPI bus

  #define HSPI_MISO   MISO
  #define HSPI_MOSI   MOSI
  #define HSPI_SCLK   SCK
  #define HSPI_SS     SS

static const int spiClk = 1000000; // 1 MHz

//uninitalised pointers to SPI objects
SPIClass * hspi = NULL;

void setup() {
  //initialise instance of the SPIClass attached to HSPI
  hspi = new SPIClass(HSPI);

  //initialise hspi with default pins
  //SCLK = 14, MISO = 12, MOSI = 13, SS = 15
  hspi->begin();

  pinMode(HSPI_SS, OUTPUT); //HSPI SS
}

// the loop function runs over and over again until power down or reset
void loop() {
  hspi_send_command();
  delay(100);
}

void hspi_send_command() {
  byte data_on = 0b00000001; // data 1 to turn on LED of slave
  byte data_off = 0b0000000; // data 0 to turn off LED of slave

  hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  digitalWrite(HSPI_SS, LOW);
  hspi->transfer(data_on);
  digitalWrite(HSPI_SS, HIGH);
  hspi->endTransaction();

  delay(1000);

  hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  digitalWrite(HSPI_SS, LOW);
  hspi->transfer(data_off);
  digitalWrite(HSPI_SS, HIGH);
  hspi->endTransaction();
  delay(1000);

}
*/

Slave Code:
#include <ESP32SPISlave.h>

ESP32SPISlave slave;

static constexpr uint32_t BUFFER_SIZE {32};
uint8_t spi_slave_tx_buf[BUFFER_SIZE];
uint8_t spi_slave_rx_buf[BUFFER_SIZE];

#define LED 2

void setup() {
    Serial.begin(115200);
    delay(2000);
    pinMode(LED, OUTPUT);
    // begin() after setting
    // HSPI = CS: 15, CLK: 14, MOSI: 13, MISO: 12 -> default
    // VSPI = CS:  5, CLK: 18, MOSI: 23, MISO: 190
    slave.setDataMode(SPI_MODE0);
    slave.begin();
    // slave.begin(VSPI);   // you can use VSPI like this

    // clear buffers
    memset(spi_slave_tx_buf, 0, BUFFER_SIZE);
    memset(spi_slave_rx_buf, 0, BUFFER_SIZE);
}

void loop() {
    // block until the transaction comes from master
    Serial.println("Initialize...");

    slave.wait(spi_slave_rx_buf, spi_slave_tx_buf, BUFFER_SIZE);

    Serial.println("*********************");

    // if transaction has completed from master,
    // available() returns size of results of transaction,
    // and buffer is automatically updated
    char data;
    while (slave.available()) {
        // show received data
         Serial.print("Command Received: ");
         Serial.println(spi_slave_rx_buf[0]);
         data = spi_slave_rx_buf[0];
         slave.pop();
    }
    if(data == 1 )
    {
        Serial.println("Setting LED active HIGH ");
        digitalWrite(LED, HIGH);
    }
    else if(data == 0 )
    {
        Serial.println("Setting LED active LOW ");
        digitalWrite(LED, LOW);
    }
}

For ESP32, unless the exact board variant is specified, by default the macros for MISO, MOSI, SCK and SS are defined as follows and are used for VSPI(i.e. SPI0):
static const uint8_t SS    = 5;
static const uint8_t MOSI  = 23;
static const uint8_t MISO  = 19;
static const uint8_t SCK   = 18;

This can be seen in the source code and HSPI is automatically configured to use SCLK 14, MISO 12, MOSI 13 and SS 15 when SPI.begin() is called, see this part of the source code.
Since you defined HSPI_SS as #define HSPI_SS SS, when you do pinMode(HSPI_SS, OUTPUT);, you are actually setting pin 5 as output, not the pin 15 that you thought it was.
There are two ways to properly set up the HSPI port.

What you can do is to define the macros as follows and call hspi->begin(); by passing your configuration:

#define HSPI_MISO   12
#define HSPI_MOSI   13
#define HSPI_SCLK   14
#define HSPI_SS     15

void setup() {
  hspi = new SPIClass(HSPI);
  hspi->begin(HSPI_SCK, HSPI_MISO, HSPI_MOSI, HSPI_SS);
  // rest of your setup code
}

As you can see from the source code shown in the above link, if you don't explicitly pass the pins as parameters when calling SPI.begin(), the library will automatically assign the pins based on whether VSPI is used (SCLK 18, MISO 19, MOSI 23, SS 5), or HSPI is used (SCLK 14, MISO 12, MOSI 13 and SS 15). So all you need to define is your HSPI_SS pin:

#define HSPI_SS     15

void setup() {
  hspi = new SPIClass(HSPI);
  hspi->begin();
  // rest of your setup code
}

Thank you so much. I managed to send a string expression. Below you can see the Slave-Master codes that send messages from Master to Slave using the "Hello From Master" string.

You can see the Slave-Master codes that send messages from Master to Slave using the "Hello From Master" string.
Master Code:
#include <SPI.h>

#ifdef ALTERNATE_PINS
  #define VSPI_MISO   19
  #define VSPI_MOSI   23
  #define VSPI_SCLK   18
  #define VSPI_SS     5
#else
  #define VSPI_MISO   MISO
  #define VSPI_MOSI   MOSI
  #define VSPI_SCLK   SCK
  #define VSPI_SS     SS
#endif

static const int spiClk = 1000000; // 1 MHz

char input;

const int size_arr = 25;
char buf[size_arr];
String sendData = "Hello from Master";

//uninitalised pointers to SPI objects
SPIClass* vspi = NULL;

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

    vspi = new SPIClass(VSPI);

#ifndef ALTERNATE_PINS
    vspi->begin();
#else
    vspi->begin(VSPI_SCLK, VSPI_MISO, VSPI_MOSI, VSPI_SS);
#endif

    pinMode(VSPI_SS, OUTPUT); //HSPI SS

    vspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
}

void loop() {
    input = Serial.read();

    if(input == 's'){
      sendData.toCharArray(buf, size_arr);
      spi_transmis(VSPI_SS, buf);
    }
    delay(50);
}

void send_spi(int selectPin, byte pram) {
    digitalWrite(selectPin, LOW);
    vspi->transfer(pram);
    digitalWrite(selectPin, HIGH);
    vspi->endTransaction();
    delayMicroseconds(75);
}

void spi_transmis(int selectPin, char buf[]) {
  for (int i = 0; i < size_arr; i++) {
    send_spi(selectPin, buf[i]);
  }
  send_spi(selectPin, '\n');
}

Slave Code:
#include <ESP32SPISlave.h>

ESP32SPISlave slave;

static constexpr uint32_t BUFFER_SIZE { 1 };
uint8_t spi_slave_tx_buf[BUFFER_SIZE];
uint8_t spi_slave_rx_buf[BUFFER_SIZE];

const int size_arr = 151;
char buf[size_arr];

volatile int pos = 0;
volatile bool active;
volatile bool process;

String received;

void setup() {
    Serial.begin(115200);
    slave.setDataMode(SPI_MODE0);
    slave.begin(VSPI);

    memset(spi_slave_tx_buf, 0, BUFFER_SIZE);
    memset(spi_slave_rx_buf, 0, BUFFER_SIZE);
}

void loop() {
    recvHandle();
    spiHandler();
}

void spiHandler() {
  slave.wait(spi_slave_rx_buf, spi_slave_tx_buf, BUFFER_SIZE);

  while (slave.available()) {
      char c = spi_slave_rx_buf[0];
      if (c == '\n') {
        buf[pos] = '\0';
        process = true;
      } else {
        buf[pos++] = c;
      }
      slave.pop();
  }
}

void recvHandle() {
  if (process) {
    received = String(buf);
    process = false;
    pos = 0;
    Serial.println(received);
    delayMicroseconds(20);
  }
}


text:
ESP8266 unresolved mDNS host in .local domain
I am trying to implement a mDNS for esp8266 in Arduino IDE following this guide.
https://tttapa.github.io/ESP8266/Chap08%20-%20mDNS.html
I cannot get the esp8266.local name to work - when i ping it it returns an error unresolved host and putting it in a browser also does not resolve...
The IP address does resolve though. Any advice would be greatly appreciated. I am using Mac OS High Sierra and have seen that many people have experienced this problem on both windows and mac but there does not seem to be a solution yet.
Any ideas?
Thanks x

Post your serial output. Make sure the device is getting an ip address on the network.

There is a known bug in the example code you are using.  The author has been notified on github but has apparently chosen to not update their published code.
You need to add the following line to the loop() { } ; section of the code :    MDNS.update();
 void loop() {
    MDNS.update();
 }

Once you do that. it should start working. And without that there is not way to get it working.
Adding this comment for anyone following and searching for a solution to this same problem.

source: Stack Exchange

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

sort: votes


text:
How i convert to Arduino Mega?
i need using OV7670 camera on my arduino mega, and i found this site have tutorial using ov7670 camera, but in this tutorial they use arduino Uno. if i'm using arduino Mega2560, what i need to do? do i have to change their code and pin connection ?
here is the link
https://www.instructables.com/id/OV7670-Arduino-Camera-Sensor-Module-Framecapture-T/?amp_page=true

Yes, you will have to change the code to match the Mega pinout.
Because the program need to run quite fast, and the Arduino functions
digitalRead() and digitalWrite() are dead slow, the author of the
program used direct port access for performing the raw IO.
For example:
    //Wait for vsync it is on pin 3 (counting from 0) portD
    while(!(PIND&8));//wait for high
    while((PIND&8));//wait for low

This is testing pin PD3 (8 is 23), which on the Uno is
digital 3, but on the Mega is digital 18. The same code could
be written in a portable fashion:
    //Wait for vsync it is on pin 3 (counting from 0) portD
    while (digitalRead(3) == LOW);   //wait for high
    while (digitalRead(3) == HIGH);  //wait for low

but it would probably be too slow.
Note also that here:
    UDR0=(PINC&15)|(PIND&240);

the program takes advantage of the particular pin mapping of the Uno in
order to read 8 inputs with only two port reads (4 bits on
port C and 4 bits on port D). You could do even better on the Mega
if you use pins A8 through A15 for the data bus, and then read the whole
8-bit word as PINK.
There may be some other differences between the Uno and the Mega that
need to be taken into account, but the pin mapping is the only one that
is obvious to me just by quickly going through the code.

hello,
you said that
"..which on the Uno is digital 3, but on the Mega is digital 18."
how do you know on the Mega is Digital Pin 18?
and i still don't understand about use pins A8 through A15 and read the word as PINK

@IbnumRichaflor: Re “how do you know [...]”: Google “Arduino Uno pinout” and “Arduino Mega pinout”. Re “use pins A8 through A15 and read the word as PINK”: Pins A8 – A15 (Arduino labeling) are PK0 – PK7 (manufacturer's labeling), collectively known as “port K”.

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


text:
Getting constant PWM value based on user input from serial monitor
I am trying to get a constant PWM value from the PWM pin based on the user input. For example: the user hits 1, the output PWM value is 100, if it is 2 the output would be 200. This will continue till the user enters a new number.
The issue I am having with my code is when I enter a number, the output of the PWM goes to that value for about a second and then goes back to 0. Can you please let me know what I am missing?
// Sketch: Blinking two LEDs by user
int test_pin=2; // declare pin10 as ledpin
int PWMvalue; // variable to store the number of blinks
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  Serial.println("What is the new speed?"); //Prompt User for Input
 while (Serial.available() == 0) {
    // Wait for User to Input Data
  }
  PWMvalue = Serial.parseInt(); //Read the data the user has input

  if (PWMvalue==0)
  {
    analogWrite(test_pin,0);
    }
    else if (PWMvalue==1)
    {
      analogWrite(test_pin,100);
      }
      else if (PWMvalue==2)
    {
      analogWrite(test_pin,200);
      }
      else if (PWMvalue==3)
    {
      analogWrite(test_pin,300);
      }
      else if (PWMvalue==4)
    {
      analogWrite(test_pin,400);
      }
      else if (PWMvalue==5)
    {
      analogWrite(test_pin,500);
      }
      else if (PWMvalue==6)
    {
      analogWrite(test_pin,600);
      }
      else if (PWMvalue==7)
    {
      analogWrite(test_pin,700);
      }
      else if (PWMvalue==8)
    {
      analogWrite(test_pin,800);
      }
      else if (PWMvalue==9)
    {
      analogWrite(test_pin,900);
      }
      else
    {
      analogWrite(test_pin,1023);
      }

  Serial.print("The user has choosen the number:");
  Serial.println(PWMvalue);
  Serial.println(" ");
}
```

I am using Arduino MKR NB 1500. I am using PWM pin 2

set Line ends to none in Serial Monitor.  line ending counts into available(). readInt waits one second for number, then it returns 0.

setting the line ends to none worked. Thanks Juraj!

why have you not included the serial console printout?

You wait for user input with a while (Serial.available() == 0), the you read the input with Serial.parseInt(). parseInt will wait a second for digits. It will end on a non digit character or timeout and return the number corresponding to received digits. If no digits were received a 0 is returned.
Serial Monitor has Line end setting. If there is some line ending selected, it will send line ending character(s).
Your waiting loop while (Serial.available() == 0) will end on line ending character which followed the number processed in previous loop. parseInt will not find a digit so it times out after a second and returns a 0, which causes setting the PWM to 0.


text:
Can bool variable be NULL
I want to know if bool variable can be null, or it must have to be true or false:
Base on Arduino description:
A bool holds one of two values, true or false. (Each bool variable occupies one byte of memory.)

A bool value must be either 0 or 1, or false and true respectively. It is undefined behavior for it to be any other value. When assigning a value to a bool, the compiler will automatically force it to be 0 if it is already 0, or 1 if it is not.
However, as it is a full byte, it is possible to store another value. As mentioned before, however, this is undefined behavior. This means that if it ever happens, or will absolutely happen, the program can do anything: for example, crash the program, output random data, or act like it's truthy, falsy, or both! In fact, that can (again, no guarantees) happen if you store the value 2:
#include <cstdio>

int main() {
    union b_c {
        unsigned char c;
        bool b;
    };
    b_c c;
    c.c = 2;

    if(c.b) puts("true!");
    if(!c.b) puts("false!");
}

(this is designed to run on a computer, but the same thing could happen on an Arduino). Check out what happens when you run it: it outputs both true! and false!! This obviously doesn't make sense, but because we violate the rules by making a bool 2, we loose all guarantees.

So, how is this relevant to your question? There's no valid value a bool can store other than true and false. In C++, null is defined as "an integer literal with value zero". So, if you were to assign null to a bool, it would be stored as false. If you want a separate null value, you're better off using another type that takes up a single byte (e.g. unsigned char or uint8_t, same thing) and storing e.g. 0 for false, 1 for true, and 2 for null.

just want to know if i am correct or not that bool is single bit can only hold 0 or 1

@Shahreza yes, you can only store a 0 or 1 in a bool, i.e. a single bit. However, because you can't address single bits, each bool takes up a full byte, even though you can't use the other 7 buts.

Depending on the compiler's implementation, a bool can also be as wide as an int. There is no guarantee that it takes just 8 bits (chapter 8.3.3 in the C++17 standard). However, some systems support bit accesses (8051 microcontroller, for example), and some compilers for these support 1-bit bools.

A boolean test doesn't look only at bit 0 in most implementations; rather, it may look at the entire variable and test it's "zero-ness. Zero == false; non-zero == true. That still doesn't leave any values for a third distinct meaning (such as NULL). If you need that, an enum would be a better choice.

A bool is literally that - a boolean value. So either 1 or 0 - true or false.
In C only pointers can be NULL. Every other primitive type is a value, and NULL is not a value.


text:
How to put the inputs in array?
I face a problem and I really need help.
For my Arduino project, I'm using RFID reader with tags.
The story is, I have a desired arrangement for the cards and I defined it as an array called desired[]= {.... , .... ,....}
Then, I want my RFID reader to read the real sequence of the cards and Arduino will tell me if the sequence is right or wrong.
My real problem is, how to put the input which will come from the reader in my empty array real[2];
My code is:
#include <SPI.h> //// Library
#include <MFRC522.h> // Library
constexpr uint8_t RST_PIN = 9;     // Configurable, see typical pin layout above
 constexpr uint8_t SS_PIN = 10;     // Configurable, see typical pin layout above
 MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance
String Desired[]={ "f01ca379" ,"60d7a1a5" , "64d7a3a6"};
String Real[2];

void setup() {
Serial.begin(9600);                                           // Initialize
serial communications with the PC
SPI.begin();                                                  // Init SPI bus
mfrc522.PCD_Init();                                              // Init MFRC522 card
 }

   String readUID() {
  String readUID = "";
  for (byte i = 0; i < mfrc522.uid.size; i++) {
     readUID = readUID + (mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
    readUID = readUID + String(mfrc522.uid.uidByte[i], HEX);
          }
            mfrc522.PICC_HaltA();
       return readUID;
      }

void loop() {
 if ( ! mfrc522.PICC_IsNewCardPresent()) {
return; }
 if ( ! mfrc522.PICC_ReadCardSerial()) {
return; }
String UID = readUID();
if (UID == "f778f19"){
******************************************
******************************************
     }
 }

I used f01ca379 card as a master card only to start the loop.
in the {*************} I need to complete the code in order to save the input in my Real Array, then to compare it with the desired array and decide if the real arrangement matched with the desired one.with tags

why do you need to put the scanned card number into an array? .....  why don't you simply compare the card numbers as you scan them?

The first problem is, how to decide the number of card scanned without using an array?  Because I want the reader to stop after scanning 3 cards, and do the process again.  Also, what command I have to use in order to compare without an array? Because when RFID reader scan the first item, i want to compare it with first number in array, second time of scanning, comparing with second number in desired array.... Etc.  Please help me how it comes?

there is no number of card scanned ..... there is  number of card being checked ...... why would you continue to check all three cards if the first one does not match?  ........ do this with playing cards first (or with pieces of paper)

For my project, I need to check all three cards ... even if the first one doesn't match, I need to check the rest of them, and that's the problem. Also, in the real case it's not only 3, I just chose 3 to start writing the logic.


text:
What is RSR 09TI chip?
There is a chip on Arduino UNO board which I can not find anything about. It is labeled RSR 09TI. It is placed near other power related components (see the image), but what is its purpose on the board?

Looks like the power regulator from +5V to +3.3V. See here component U2. Do you have a multimeter to measure the pins with regards to GND? There should be GND, +5V and +3.3V on there if I'm right.

@MaximilianGerhardt I don't have any UNO at hand right now, but I'd guess that the 5V -> 3V3 regulator is the guy at the lower right red corner on the image (looks like smaller brother of the 20V -> 5V guy)

I believe that is the dual op-amp that is used for both monitoring VIN to enable/disable the USB power, and as a buffer for the LED on pin 13.
In the schematic it's U1, and is an LM358.

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


text:
Power Arduino controlled by another Arduino by MOSFET
I would like to control power to Arduino B from signal of digital pin from Arduino A.
I use IRFZ44N MOSFET as switch and +12V DC source. The Arduinos have common ground. The connection is:

Gate: signal from Arduino A (+5V or 0V)
Source: +12V
Drain: Vin of Arduino B

At this settings Arduino B is powered regardless of the value on the gate. What am I doing wrong and how should I change the settings to get the desired result? I know I misunderstand how the transistor works, please show me the correct approach.

share your schematic here and sketch using to control the gate voltage.

That mosfet has a body diode between the Source and Drain. So this diode will always let current though, no matter what the voltage is at the Gate. That N-channel mosfet isn't ideal for high-side switching. It would require additional circuitry, and even an extra power source as far as I can see. It's a lot easier to do low-side switching. That is; switching the GND instead of 12V.

@Gerben you mean to connect +12V directly to the Vin of Arduino B, Source of the N-MOSFET to ground and Drain to GND pin of Arduino B? Can the signal from Arduino A to the Gate switch the power correctly then?

Yes, that's what I meant. But you have to be careful if you have any other connections between the two Arduinos (for example a wire between TX and RX of the two Arduinos).

@Gerben indeed, I just fired up two GPIOs: to set the pin to LOW and close the transistor gate was not the brightest idea. Is there any simple solution to prevent damage when the GND pin accidentaly disconnects?

Adding a resistor will help. It will limit the current. The other thing to do is set any OUTPUT pins to INPUT, before turning of the power to the second Arduino. (You can also set them to HIGH, but I prefer the safety of setting it to INPUT). That way no current can flow from the second arduino, though the internal clamping diodes in the Arduino's MCU, to the LOW OUTPUT pin of the first Arduino.

You have an N-channel MOSFET. That is not suitable for switching the 12V supply of an Arduino.
Instead you need a P-channel MOSFET which has the gate pulled up to 12V using a resistor, and then an N-channel logic level MOSFET which is used by the Arduino to pull the gate of the P-channel MOSFET LOW to turn it on.
Something like:

simulate this circuit – Schematic created using CircuitLab
When the GPIO is HIGH it turns M2 on. This pulls the gate of M1 down, turning it on. When GPIO is LOW, or not actively being driven (thus being pulled down by R2), M2 is off. This allows the gate of M1 to be pulled up to +12V by R1, switching M1 off.

Thank you for the nice design. Would it be possible to pull the M1 gate to just +5V and open it by writing LOW to GPIO? (Without M2)

No. That is why you have m2 in the circuit. M1 has to be pulled to 12v. That's how a MOSFET works.

@JanTuroň A P-channel MOSFET's "threshold" voltage is the voltage of the gate below that of the source. It's listed in datasheets as a negative voltage. With the source at 12V the gate has to be at the source voltage to be fully off, or below 12V minus the threshold voltage to be on.  You can turn it on, but never off, if you can't get the gate up to (or very near) the source voltage.


text:
SIM800L always returns +CREG: 0,2
I'm using a SIM800L module, and I am checking the status of my network with the AT+CREG? command.
However, it always returns the same 0,2:
0 -> disable network registration unsolicited result code

2 -> not registered, but ME is currently searching a new operator to register to

How do I activate 2G or 3G network?

It can take a while to register - sometimes several minutes. Have you left it after power-up for enough time?
If your operator has no signal in your area it will never register. National roaming is normally disabled. If you have national roaming available you will have to manually connect to another operator.
Check that your modem can see your operator with AT+COPS=?

I can see the operators list with command AT+COPS=?. But I can't register on them!

Do you need a pin for the simcard?

Not, I have pin. I can't connect to a network!

authors: Георгий Глухих

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


text:
Making WiFi hotspot for 3G network sharing controlled by Arduino
I am trying to make a WiFi internet network from 3G using Arduino as access control. I need the Arduino to act as server and control users, consumption, and connection speed. (When users connect to the WiFi, they have to enter a passcode in a webpage to use internet for a limited time,  or limited data.)
So is this possible? I still did not try anything because I can not afford to buy many objects and fail to make it work.
I am thinking of using a 3G shield and a WiFi shield, or a router connected to 3G dongle connected to an Arduino via ethernet, or a 3G shield Arduino to ethernet shield to WiFi router.
I don't know if any of these can work, so I really appreciate any guidance.

Not a chance, I am afraid (you were right not to buy things yet). Things like the 3G shield and WiFi shield don't work in the way that is needed for a WiFi hotspot like that. You're better off with a Raspberry Pi and a 3G USB dongle and run hostapd along with the other software needed for your project - things like apache, etc.
You may be able to do it with the Linux portion (OpenWRT) of an Arduino Yun with a USB 3G dongle attached, but it would be sluggish. Best to stick to something with enough processing to do what you want, which means a Raspberry Pi or similar.

What you want (on at least an ARM board) is a captive portal, which catches and releases new users if and only if they pass the required challenge. There are numerous software packages for this. If you use a pi, and need to do something with the GPIO pons, have a look at the WiringPi project, which is much nicer than python's silliness. 'Inspired by Monty Python' ... indeed.


text:
Upload sketch remotely through a serial-IP-serial connection
I tried different times to use socat and ser2net in order to upload a sketch to an Arduino Uno (connected to a PC) from my laptop, unsuccessfully. Can anyone teach me how to achieve this goal? I use Linux.

have not tried it so I wont call it an answer. I see that avrdude support TCP interface. I would try it manually first. Turn on verbose and compile it, find the avrdude command in the verbose. Then go to the output temp directory and issue it manually but replacing the ttyS with the TCP interface with IP and Socket of your ser2net, as found in the avrdude help.

Ok, but after that, there is no way to set in Ecipse Arduino Plugin avrude in order to reach an Arduino through IP... or not? :)

I've been searching through the net for some days, in order to discover how I could easily upload a sketch to an Arduino that is not phisically connected to my PC, but instead that is connected to an another one, that belongs to the same LAN. I mean:
PC1-SERVER
Arduino Uno is connected to this PC with classic USB cable.
This PC is running Ubuntu linux, and sees Arduino as a serial port /dev/ttyACM0.
PC2-CLIENT
This is the PC where I create and compile the sketch.
I want to upload the sketch to the Arduino Uno described above (so, connected to SERVER, port /dev/ttyACM0)
SOLUTION:
server-side commands:
Code:
sudo apt-get install ssh-server ser2net

sudo passwd root    (to set the root password)

sudo reboot

client-side commands (assuming 192.168.0.7 as IP address of SERVER):
Code:
ssh -L 8086:localhost:8086 root@192.168.0.7 \
'/usr/sbin/ser2net -d -C "8086:raw:600:/dev/ttyACM0:115200 NONE 1STOPBIT \
8DATABITS -XONXOFF LOCAL -RTSCTS HANGUP_WHEN_DONE "'

you can then upload sketches to arduino doing this:
Code:
avrdude -C /path/to/avrdude.conf -p atmega328p -c arduino -P net:localhost:8086 -U flash:w:/path/to/file.hex:i

NOTE:
In Eclipse, if you are using the arduino plugin, just place "net:localhost:8086" in the configuration panel, where "port:" field is required.
This solution was also posted on arduino forum.

You can use an ethernet to ttl adapter and then install a virtual com software.
What i did was the following.
I used an ethernet to 232 converter,  and tweaked the board as you can see in the attached photo, I removed the 232 chip and jumpered the ttl directly to the output.
Then I installed USR-VCOM and set a virtual com port that shows in the arduino ide, it works without any software /boot changes
I am not sure how to remote reset the arduino....  Probably someone else knows.

One of the 232 signal lines like DTR or could work like a reset. You could also make your Arduino reset if it receives a specific message, and the send the code.

"You could also make your Arduino reset if it receives a specific message" yes, the only problem is that the standard Arduino bootloaders such as optiboot are not activated after a watchdog reset so you would either need to modify the bootloader or do a hardware reset.

Basically it would require another bootloader.
You might want to check this out:
http://playground.arduino.cc/Code/TFTPBootloader1
Programming through serial
I don't have the intention to advertise a product, but I worked with an Lantronix xport which was able to receive serial information (or a telnet session) over ethernet. You might want to look into cheaper models of other manufacturers (that do not use modem like commands) you should look for ethernet to serial converters.
It should be compatible  with: http://blog.solutions-cubed.com/programming-the-arduino-uno-with-a-serial-port/
You might also connect to another PC over ethernet which then programs the arduino
This would require another PC, but can be fairly easy to set up, but cumbersome to use. You could use teamviewer or another remote desktop. Find a way to send your code (or completely program it at the other pc) and then execute the program command. You might even check if it's possible to use an raspberry PI instead of a full PC (always wanted to try this).
Use an arduino to program your arduino
You might use an arduino that receives code and then uploads it to another arduino. Not sure how that works out. Or how to get the code on the first arduino. Should work fine if you've got something like a modificated arduino webserver running.
Also details on programming arduino can be found here:
http://www.arduino.cc/en/Tutorial/ArduinoISP

Well, you've given me an idea. X tunneling through SSH connection to host, were arduino is connected, than invoke the IDE and use it remotely.

Yup, my answer was just some "brainstorming" if I re-read them, most of them wouldn't really work or just barely. But they indeed give a view on the possibilities. Creating a custom solution, to fit your needs would indeed be the best. If you want to not use another PC, you should check on how an arduino is programmed, how to send the program over ethernet and how to mimic the programming on the other side.
But establishing a connection with a PC over ethernet, and than program it through that would be the best, but a lot of options are possible here also.


text:
Stepper motor is not working according to code
#include <Stepper.h>
#define STEPS_PER_MOTOR_REVOLUTION 32
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 480  //2048
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);
int Steps2Take;
int dirpin=8;
int steppin=9;
int buttonApin=2;
int buttonBpin=3;

void setup() {
  pinMode(dirpin,OUTPUT);
  pinMode(steppin,OUTPUT);
  pinMode(buttonApin,INPUT);
  pinMode(buttonBpin,INPUT);
}

void loop() {
  int valA=digitalRead(buttonApin);
  int valB=digitalRead(buttonBpin);
  if(valA==HIGH) {
    digitalWrite(steppin,HIGH);
    digitalWrite(dirpin,LOW);
    small_stepper.step(40000);
    delay(1000);
  }
  if(valB==HIGH) {
    digitalWrite(steppin,HIGH);
    digitalWrite(dirpin,LOW);
    small_stepper.step(-40000);
    delay(1000);
  }
  if((valA==LOW)&&(valB==LOW)) {
    digitalWrite(steppin,HIGH);
    digitalWrite(dirpin,LOW);
    small_stepper.step(0);
  }
}

Here I have written this code to rotate stepper motor. When the input on digital pin 2 becomes high, then the motor should rotate clockwise. When the digital pin 3 becomes high, it should rotate in a different direction. When the input on both pins is low, the motor should not move.
But with this code the motor is moving continuously even if you apply high input to digital pins.
Please suggest how to fix this problem. For input signal I am taking signal from relays: if relay is in on condition, it should give a high signal and vice versa.

I think its better to use count function .. you need to test yor stepepr motor first ..here the code to test .. i hope its will help :)
#define IN1  50
#define IN2  51
#define IN3  52
#define IN4  53
int Steps = 4096; //4096(full rotation 360 degree )
int cstep = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);

 Serial.println("Enter character for control option:");
 Serial.println("h : anticlockwise");
 Serial.println("i : clockwise");
 }

 void loop()
{

   if (Serial.available()>0)
   switch(Serial.read())
 {
   case 'h':
   Serial.println("anticlockwise");
   for(int x=0;x<Steps;x++)
{

     step1();
     delayMicroseconds(1000);
}
  break;

   case 'i':
   Serial.println("clockwise");
     for(int x=0;x<Steps;x++)
   {

       step2();
       delayMicroseconds(900);
   }

   //delay(1000);
    break;

  }

  }

   void step1()
  {
    //stepp
    switch(cstep)
 {
   case 0:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, HIGH);
 break;
 case 1:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, HIGH);
 digitalWrite(IN4, HIGH);
 break;
 case 2:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, HIGH);
 digitalWrite(IN4, LOW);
 break;
 case 3:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, HIGH);
 digitalWrite(IN3, HIGH);
 digitalWrite(IN4, LOW);
 break;
 case 4:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, HIGH);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, LOW);
 break;
 case 5:
 digitalWrite(IN1, HIGH);
 digitalWrite(IN2, HIGH);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, LOW);
 break;
 case 6:
 digitalWrite(IN1, HIGH);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, LOW);
 break;
 case 7:
 digitalWrite(IN1, HIGH);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, HIGH);
 break;
 default:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, LOW);
 break;
 }

 cstep=cstep+1;
 if(cstep==8)
  {cstep=0;}
 }

  void step2()
{
//stepp
switch(cstep)
{
 case 0:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, HIGH);
 break;
 case 1:
 digitalWrite(IN1, HIGH);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, HIGH);
 break;
 case 2:
 digitalWrite(IN1, HIGH);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, LOW);
 break;
 case 3:
 digitalWrite(IN1, HIGH);
 digitalWrite(IN2, HIGH);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, LOW);
 break;
 case 4:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, HIGH);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, LOW);
 break;
 case 5:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, HIGH);
 digitalWrite(IN3, HIGH);
 digitalWrite(IN4, LOW);
 break;
 case 6:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, HIGH);
 digitalWrite(IN4, LOW);
 break;
 case 7:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, HIGH);
 digitalWrite(IN4, HIGH);
 break;
 default:
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, LOW);
 break;

 }

  cstep=cstep+1;
 if(cstep==8)
 {
  cstep=0;
  //Serial.println("habis");

  }
 }

copy the code that i was give .. change the pin of stepper motor to your own pin .. then upload to the arduino board and see waht happend at serial monitor

Disclaimer: I've never used this library.  The following is my thoughts from looking at the code.
This example seems to do basically what you want.  It doesn't seem to be necessary to do any digitalWrites yourself - you just need to call call .step(x).
There also doesn't seem to be any need to anything in the "do nothing" case - you don't need to tell it not to step, as far as I can see.
I couldn't work out why you were stepping 40000 steps at a time.  I've changed it to 1.  You can change it back if I missed something.
Also note I've used else if so that if both inputs are high, the motor doesn't go forward AND backwards.  Maybe that's the behaviour you want, and if not, again, you can change it.
#include <Stepper.h>
#define STEPS_PER_MOTOR_REVOLUTION 32
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);
int buttonApin=2;
int buttonBpin=3;

void setup()
{
    pinMode(buttonApin,INPUT);
    pinMode(buttonBpin,INPUT);
}

void loop()
{
    int valA=digitalRead(buttonApin);
    int valB=digitalRead(buttonBpin);
    if(valA==HIGH)
    {
        small_stepper.step(1);
        delay(1000);
    }
    else if(valB==HIGH)
    {
        small_stepper.step(-1);
        delay(1000);
    }
}

Does the relay actually connect the pin to ground when it is off?  Or does it leave the input floating?  If it leaves it floating then you should use a pull-down resistor to make sure the pin actually sees ground and not stray interference.
If you can rewire the relays you can use an active low configuration and save the resistor since the Arduino has built-in pullup resistors.


text:
As a novice, how do I program my Atmega328p?
I bought a board which the above MCU is the atmega328p. Since I haven't used atmel MCU before, now it's a bit confusing. Are the ATMEGA and STM32 programmers not universal? What programming methods can this chip support? Is there serial programming or SWD programming? Need help. Many thanks!

"Are the ATMEGA and STM32 programmers not universal?" No, one is via ISP and the other one is SWD / JTAG, they are different. Most of the times the ATMega chip on maker boards comes preprogrammed with a bootloader that allows it to be flashed via serial (Optiboot). Using the Arduino IDE with the board "Uno" selected will work then. Otherwise, you need to construct a ISP programmer if you do not have one. See https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoISP.

I bought a board - which board? Link to it?

Are the ATMEGA and STM32 programmers not universal?

They are not the same. As far as I know their programming arrangements are completely distinct.

What programming methods can this chip support?

Traditional AVR In-Circuit-Serial-Programming (ICSP) using a 2x3 header pin connector and one of a variety of programmers such as the STK500 which has low-cost clones like the Pololu AVR programmer (less than $10). These programmers typically connect to a PC's USB port and can be used either with the software development tools from Atmel (now Microchip) or using the Arduino integrated development environment (IDE) which uses a program named avrdude to communicate with the ATMega328P (or other AVR family MCUs). ICSP is sometimes called In System Programming (ISP). It uses the MCU's SPI interface and you have to be careful what other circuitry is attached to those pins when you program the device.

Serial-port programming by communicating with a pre-loaded "bootloader" program installed in the ATMega328P. This is the normal way to use the Arduino IDE but it depends on having that bootloader installed. Most bare ATMega328Ps are sold without this bootloader installed. All "Arduino" boards will have a bootloader installed in their MCU and many will have a serial-to-USB interface on-board so that the board can be plugged in to a PC directly. Otherwise you would need a USB-to-Serial interface like the Adafruit FTDI friend or many others.

There is also a high-voltage programming method but that isn't something a novice would need to use. I believe it is most often needed when you have configured the MCU in such a way that the above methods cannot be used. For example after having disabled the reset pin so it can be used as an IO pin that can be pulled to GND without resetting the MCU.
You can use an Arduino to emulate a programmer and use that to program boards that lack a USB serial interface. This is called Arduino as ISP
Microchip's newer generation of AVR MCUs use a different programming method than ICSP called UPDI.

What programming methods can this chip support? Is there serial programming or SWD programming?

The Arduino IDE (a free download) supports programming in C++. The IDE pre-processes your code (which they call a "sketch") slightly but it is still C++.
You can drop into assembler if you absolutely must, but the C++ compiler does a good job of producing efficient code, almost always.
With the assistance of a serial interface (many Arduinos, like the Uno, have one built-in connected to a USB interface) you can quickly and easily upload your code. The wherewithal to do that is built into the IDE.


text:
What should I do with stackOverflow in compile error?
I don't have port, but when I want to compile my code (even empty files),
I encounter this error:
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

The code is:
int LED_red=4;
int LED_yellow =2;
int green =0;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED_red,OUTPUT);
  pinMode(LED_yellow,OUTPUT);
  pinMode(green,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(LED_red,HIGH);
  digitalWrite(LED_yellow,LOW);
  digitalWrite(green ,LOW);
  delay(5000);
  digitalWrite(LED_yellow,HIGH);
  digitalWrite(LED_red,LOW);
  digitalWrite(green,LOW);
  delay(5000);
  digitalWrite(green,HIGH);
  digitalWrite(LED_yellow,LOW);
  digitalWrite(LED_red,LOW);
  delay(5000);
}

Sketch uses 998 bytes (3%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

I want a hex address for cordinate this code with Proteus, but it doesn't compile and dosn't give me hex address.

I don't think that's an error.  It looks like the report regarding how much of the target processors resources you are using.  From the looks of it, you program is very small and will most certainly fit the target processor you have chosen.

Where is the Stack Overflow you mention in your question title? As others noted, your “error” is just a summary generated after successfully compiling your code and not an actual error.

What is the exact issue? As has been mentioned many times, your code compiles fine according to the output you’ve shown. You are not showing us any evidence of a problem. What does “I want hex address for cordinate this code with Proteus” mean? What hex address? Are you trying this with Proteus or with the Arduino IDE?

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

This is not an error message. Rather, it's a message that results from a successful compile of your empty programme.

Sketch uses 998 bytes (3%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

Neither is this an error message. Rather, it's a message that results from a successful compile of your more substantial programme.
To export the HEX file from the Arduino IDE for Proteus, go to:

Menu bar -> Sketch -> Export compiled Binary

The short-cut is Ctrl+Alt+S.
You will find the .hex file in the same directory as your sketch.

Tanks a lot , your answer was so useful for me!

@dorsa, thanks. If it answers your question, be sure to accept it by clicking on the tick to left of it.

There is nothing to do.
What you are seeing is not an error. It is merely an informational message telling you how much of the available resources your sketch is using. Since it is using far less than the maximum available (as you would expect from an empty sketch) you have no problem.
You only need to worry about those figures when the "amount left" gets too small.

tanks a lot , but I want a hxe address for زcordinate this code with Proteus but it doesnt compile and dosent gove me hxe address ; can you tell me what should I do please?

@dorsa What code? What exactly are you trying to do?

int LED_red=4;   int LED_yellow =2; int green =0;
void setup() {
pinMode(LED_red,OUTPUT);
pinMode(LED_yellow,OUTPUT);
pinMode(green,OUTPUT);
}
void loop() {
digitalWrite(LED_red,HIGH);
digitalWrite(LED_yellow,LOW);
digitalWrite(green ,LOW);
delay(5000);
digitalWrite(LED_yellow,HIGH);
digitalWrite(LED_red,LOW);
digitalWrite(green,LOW);
delay(5000);
digitalWrite(green,HIGH);
digitalWrite(LED_yellow,LOW);
digitalWrite(LED_red,LOW);
delay(5000);
}

@dorsa Please, don't post code in comments. Edit your question and provide all the information. Including what actual error you get when you try and compile.

Ok ,I do it ; do you have any idea about this ?

@dorsa There still is no error. What is your actual problem?

What you are seeing is not an error.
Although your sketch is empty, there is Arduino framework code that gets created with it. This code actually calls your setup() and loop() functions so things operate as you would expect. It was designed this way to make it eaiser to get started.

thanks but I do not know what to do , can you help me again please and told me what to fo

@dorsa, you don’t have to do anything except upload your code to Arduino. Please follow a tutorial that explains the basics of how the Arduino IDE works, such as this one.

You can change the processor settings from Tools-->Processor-->Atmega328P(Bootloader). It solved my problem.

Please explain how this solves the "problem". What was your error message?


text:
Can't type backslash (\) with Keyboard library
I'm trying to make a macro keyboard, where I can press a single button and it will open programs for me.
I'm trying to type this, for example: "c:\windows"
but it gets typed out like this: cÑ}windows
I tried using double backslash (\), but it still isn't working
#include <HID-Project.h>
#include <HID-Settings.h>

#include <Keypad.h>

#define L_ALT KEY_LEFT_ALT
#define TAB KEY_TAB
#define WIN KEY_LEFT_GUI
#define ENTER KEY_RETURN

const byte FILAS = 4;
const byte COLUMNAS = 4;
//define the cymbols on the buttons of the keypads
char Keys[FILAS][COLUMNAS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte pinesFilas[FILAS] = {9, 8, 7, 6};
byte pinesColumnas[COLUMNAS] = {5, 4, 3, 2};

char TECLA;

Keypad teclado = Keypad( makeKeymap(Keys), pinesFilas, pinesColumnas, FILAS, COLUMNAS);

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

void loop() {
  TECLA = teclado.getKey();

  if (TECLA) {

    switch (TECLA) {
      case '1':
        Serial.print("Tecla 1 presionada");
        break;
      case '2':
        Serial.print("Tecla 2 presionada");
        break;
      case '3':
        Serial.print("Tecla 3 presionada");
        break;
      case 'A':
        Serial.print("Tecla A presionada");

        break;
      case '4':
        Serial.print("Tecla 4 presionada");

        Keyboard.press(WIN);
        Keyboard.write('r');
        Keyboard.release(WIN);
        delay(100);
        Keyboard.print("C:\Program Files (x86)\AIMP\AIMP.exe");   //Here's the problem
        //Keyboard.write(ENTER);
        break;
      case '5':
        Serial.print("Tecla 5 presionada");
        break;
      case '6':
        Serial.print("Tecla 6 presionada");
        break;
      case 'B':
        Serial.print("Tecla B presionada");
        break;
      case '7':
        Serial.print("Tecla 7 presionada");
        break;
      case '8':
        Serial.print("Tecla 8 presionada");
        break;
      case '9':
        Serial.print("Tecla 9 presionada");
        break;
      case 'C':
        Serial.print("Tecla C presionada");
        break;
      case '*':
        Serial.print("Tecla * presionada");
        break;
      case '0':
        Serial.print("Tecla 0 presionada");
        break;
      case '#':
        Serial.print("Tecla # presionada");
        break;
      case 'D':
        Serial.print("Tecla D presionada");
        break;
    }
  }
}

That sounds like you have a different keyboard layout set up at your PC than the Keyboard library has. I think it uses the standard US layout.

You have to keep in mind that the Arduino doesn't send characters to the
computer. Instead, it simulates key presses, and the computer has to
translate those into characters, according to some keyboard layout. By
default, the Keyboard library assumes the US keyboard layout.
If you are using another layout, you have to tell the library when
initializing it. E.g.
Keyboard.begin(KeyboardLayout_es_ES);

would work with a Spanish keyboard layout.
C.f. the documentation of Keyboard.begin().
If you are using an unsupported layout, you may need to write your own
layout file and add it to the library. You may then contribute it
upstream so that it becomes part of future versions of the Keyboard
library.
Alternatively, you could switch your layout to US in your OS.
PS: The Keyboard library only supports international keyboard
layouts since version 1.0.3, released on 2021-11-04.


text:
Problem reading in Arduino serial port with 5K potentiometer
I have written code to see values of a 5K potentiometer from 0 to 1023. Whenever I rotate the knob, the value should change from 0 to 1023. I have connected the potentiometer to the Arduino's pin A1, but there is a problem with readings. Whenever I am rotating the potentiometer's knob, the serial port is only showing 1023. Please help.
void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A1);
  Serial.println(sensorValue);
  delay(500);
}

Please show your actual wiring.

It sounds like it might be a wiring problem. Check that you have the potentiometer connected correctly. Your circuit should look something like this:

I have checked connections there is no problem with them . i dont have an idea why its only showing 1023 value .i interchanged the voltage and gnd then it showed 0 in serial port.

@shwetashrama: If your wiring is correct (which I doubt), then your potentiometer is broken.

is there any specification which one has to keep in mind while choosing a potentiometer like current rating etc.

@shwetashrama Not for applications like this. Try connecting a multi-meter across the terminals of the potentiometer to check the resistance, and verify that it changes as expected when you rotate the knob.

i have checked resistance and voltage both ,there is no problem with them

Disconnect the pot and take some readings. You should get some random values near zero. That would mean you're not connecting the leads right or the swinger is stuck at one end.


text:
Reading updated serial data from ESP8266
I have connected my ESP8266 to my Arduino Uno on pin 2 & pin 3 as RX & TX. I adjusted the baud rates and I have no issue receiving the data from the ESP8266.
The ESP8266 gets connected as a client to a server and grabs the likes count of a Facebook page. The data on the ESP8266 serial port is updated correctly every time the ESP sends a get request to the server to get the updated likes count of a particular Facebook page.
Unfortunately I'm not receiving this updated likes count on my Arduino serial port. I'm always receiving the same likes count. I have to close the serial window and open it again to receive the new count. Or reset the Arduino itself to receive the new likes count.
So why isn't it posting the latest likes count sent from the ESP to the Arduino instantly without having to reset the Arduino? Maybe I have an issue in the void loop().
Because I display this data on an external display and I need it to be updated without me needing to reset the Arduino every time to receive the latest count.
void loop() {
  char c;
  while (esp8266.available() && c != '\n') {
    c = esp8266.read();
    response += c;
  }
  //If end of line
  if (c == '\n') {
    //Getting the likes string only
    if(likes = response.substring(response.indexOf("Likes:")+6, response.indexOf("::"))) {
      //Filtering some unneeded strings
      if((strstr(likes.c_str(), "URL")) == NULL) {
        currentLikes = atol(likes.c_str());
        Serial.print(currentLikes);
        //Printing likes count on serial port
      }
      Serial.println();
    }
  }
}

Please could you explain what you've done here: if(likes = response.substring(response.indexOf("Likes:")+6, response.indexOf("::")))

If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Thank you everyone I had to just clear the response string every time.
I have just added response = ""; after the Serial.print(currentLikes);


text:
Arduino using Ethernet shield WebClient example code is not working
I'm using an Arduino Uno and Ethernet shield with the WIZnet chip W5100. The WebServer code example is working. DHCP is working, the Ethernet shield is receiving an IP address from the Linksys modem "router" and everything is fine.
But I cannot connect to a web site using the WebClient code. I found out that client.connect(server, 80); is returning -1 "Time_OUT" and it is supposed to return 1 according to the Arduino Ethernet library.
I tried connecting to different websites. I tried assigning an IP address manually, not using DHCP. I tried making pin 4 of the SD memory card SPI to output pinMode(4, OUTPUT); digitalWrite(4, HIGH); But it doesn't work. I get on my Serial line connection failed or it returns "connected" then "Disconnecting..." immediately after because client.connect has returned -1.
The example code I'm using:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x28, 0xAD, 0xBE, 0xEF, 0xB9, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:

  Serial.println("connecting...");
  delay(2000);
  Serial.println(Ethernet.localIP());

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.print(client.connect(server,80));
    Serial.println();
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

This is my output:

Using a local server IP address like my router's IP address, the connection works. But the issue is mainly in the WAN. Any help would be appreciated.

Have you tried using numeric server IP address (i.e. server(74,125,232,128))?

Also, Serial.print(client.connect(server,80)); seems to establish a second connection without using the first one. Did you want to print a string on the terminal instead of actually running the function?

Don't cross post

@gre_gor i didn't know about the Arduino stackexchange is already found i will delete it from stackOverFlow.

This doesn't look right:
if (client.connect(server, 80)) {
    Serial.print(client.connect(server,80));
    ...

If the first call to client.connect() succeeds, you call it again immediately, and the error message you're seeing comes from that second call. This really is not surprising — I can't imagine a scenario in which that would actually work.
What you really want is something more like:
if (result = client.connect(server, 80)) {
    Serial.print(result);
    ...

That's strange ... I could've sworn that you said it wasn't working. My bad. In that case, we'll send this over to Arduino.SE where they might be able to help you with the details of that particular library.

Thanks Dave. I tried also using the ip address i get no result at all from the client.connect() so connection fails.

Have you tried getting the result code like he suggested? Using the IPAddress and not the string, if it still doesn't connect and nothing is printed, then it means connect() returns 0. Try opening the EthernetClient source and adding a few print()s in connect() to find out the exact condition that causes the 0 return code. Though this looks like a connection issue since getHostByName() is failing just like connect(). You sure your modem is connected to the net?

@TisteAndii thanks for your help. The issue was in the mac address. Because my shield has no mac address and i was using a well known manufacturer mac address so it wasn't completing the connection with the google server and it was dropping it.

I resolved my problem:
The problem was in the mac address itself. When i used the mac address given by the example itself the connection didn't fail and client.connect() returned 1.
I used this mac address instead of the one in the code above:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };


text:
Controlling multiple 24V solenoids with Arduino
I'm building a pump for which I need 4 medium strength solenoids (20-50N). 24V is probably the minimum I will need to put through them, but this is something I need to test, once I've got them working. At 24V they draw 400mA.
I've found various posts with very useful info, especially https://playground.arduino.cc/Learning/SolenoidTutorial and https://forum.arduino.cc/index.php?topic=417030.0
Will the attached sketch below work for one? If so what resistance should R1 be?
And if so can you see any problems with hooking up 4 working at different intervals?
The power supply is an LRS-350-24RS, and the Mosfet has a max gate source voltage of 35V. The 5v-24v optocoupler is off ebay -  https://www.ebay.co.uk/itm/152904980799
Many thanks for your help!!

Did you draw that schematic?

The resistor should be on the other (left) side of the optoisolator. The diode parallel to the solenoid should be the other way around.

I also think you need a pull down resistor on the gate of the mosfet.

You are attempting to source current into the MOSFET gate to turn it on? Then the transistor in the Opto is upside down.

@ Majenko Yes, but based closely on what I've seen from other posts

@ Crossroads OK cheers

No, it won't:

The diode D1 is backwards.
The opto-coupler is wired completely wrong.

You don't actually need the opto-coupler as long as the threshold voltage of the MOSFET is low enough for the Arduino to switch.  However if you do want (or need) to use it you should wire it like this:

simulate this circuit – Schematic created using CircuitLab
R1 is a pull-down that keeps the MOSFET off when not being turned on (just like with a button). The value doesn't matter much.  R2 is a resistor just like you use for any LED with an Arduino.  D1 must be connected reverse biased or it will just short out your solenoid. The opto-coupler must be connected with the transistor the right way around or it will not work (or melt, or create a black hole...)
To ditch the opto-coupler you can just treat it like any other load on the Arduino (as long as the MOSFET's threshold voltage VGS is below 4V):

simulate this circuit

@ Majenko OK cheers for that. Surely you need the optocoupler for this to work, as the Ardunio cannot take 24V, so where would you return the Arduino signal to the MOSFET back to?

Why would it be "taking" 24V?

Is there any reason for using a schottky diode, instead of a regular diode?

@Gerben They tend to have faster switching from reverse to forward bias, making them absorb the back-EMF better.

@Gerben "The most important difference between the p-n diode and the Schottky diode is the reverse recovery time (trr), when the diode switches from the conducting to the non-conducting state. In a p–n diode, the reverse recovery time can be in the order of several microseconds to less than 100 ns for fast diodes. Schottky diodes do not have a recovery time, as there is nothing to recover from (i.e., there is no charge carrier depletion region at the junction). The switching time is ~100 ps for the small-signal diodes, and up to tens of nanoseconds for special high-capacity power diodes. ...

With p–n-junction switching, there is also a reverse recovery current, which in high-power semiconductors brings increased EMI noise. With Schottky diodes, switching is essentially "instantaneous" with only a slight capacitive loading, which is much less of a concern." -- Wikipedia

Thank you for the information. Guess I will be using schottky diodes in the future as flybacks.

You don't need a pulldown resistor if you're driving the MOSFET from an Arduino; the Arduino's output is CMOS. You DO need to be sure that your MOSFET's input capacitance isn't so big that it overwhelms the Arduino's output stage, though. Otherwise, it represents a short-circuit until it's charged.

@TDHofstetter The pulldown resistor is there because the Arduino's GPIOs default to INPUT (Hi-Z) so the input to the MOSFET is floating until it's actively driven by the Arduino - and there is a delay at startup caused by the bootloader, so there's a couple of seconds where the relay could trigger erroneously at power up.

#Majenko True and good point, except that the MOSFET's gate would have leaked down long ago (they do leak) unless we're rebooting the Arduino immediaely after shutting it down with the MOSFET gate high, leaving no time for it to leak down. Very remote possibility, but a possibility.

The MOSFET, to be driven from Arduino directly, needs to have a Logic Level gate.
I've been using AOD514. Logic level gate, Low Rds, rated for 30V.
https://www.digikey.com/product-detail/en/alpha-omega-semiconductor-inc/AOD514/785-1357-1-ND/3060919
SMD only, they seem to have cancelled their thru-hole line of parts that I used to use.
I have up to 32 of them on a board with the gates driven by 74HC595 shift registers for driving 1A loads (only limited by trace widths, not the transistors), with diodes added at the coil if needed.
http://www.crossroadsfencing.com/BobuinoRev17/

Ah great thanks. I hadn't cottoned on when Majenko mentioned this above. Have now read up and will change to this LogicFET https://docs-emea.rs-online.com/webdocs/0791/0900766b8079135d.pdf .


text:
Best way to power an Arduino using the Vin pin
I have a powerbank rated 5v. The battery is actually 3.6v, powering the built-in SMPS to give out 5v. I have stripped one end of the USB cable coming from the power bank, powering a motor driver and the Arduino in parallel. The positive end of the power bank, which is 5v, is going into the Arduino and the motor driver IC's Vcc.
I heard that 5v is not enough to drive the Arduino from the Vin pin. And there is only one power out from the powerbank, so directly connecting the Arduino through the USB would leave nothing to drive the motor driver IC.
A USB splitter would be the obvious solution, but is there anything else I can do? The power source has to be mobile. Can I power the Arduino through the Vin with those 9v batteries commonly used in electronics hobby projects?

"I heard that 5v is not enough to drive the arduino from the Vin pin." Where did you hear that?

You want to be careful, depending on the model Arduino has a voltage regulator or hasn't. I can never remember what the exact pin names are ... But one that comes with a voltage regulator also has a pin for 5V ... or 3V3 ... You really want to read the documentation that comes with your exact model.

Can't recall the first one to come up with the sentence: Arduino is the brains, not a power plant.

What it wrong with connecting it straight to the 5v pin? Even better, why not connect to the, say, usb port on the arduino? Just connect it to the usb port, and connect the motor to the 5v pin of the arduino.

@Jippie - you are simply wrong here.  The Vin pin is the input to the regulator, something the poster was well and accurately aware of before you wasted a bunch of comments disputing that.  Frankly they are quite justified in being annoyed by your behavior!

The solutions can be 1) plug the arduino USB cable and then use the +5V pin to power the motor (if the motor needs a low current, since you can source at most 400-450mA this way) 2) power the arduino from the +5V pin (and put a capacitor on it, but note that you are bypassing the fuse this way) 3) strip a USB cable, attach the motor to the two power wires and make a Y cable yourself.

You have a powerbank which has a USB output, right? Why not just plug a cable from that into the Arduino USB port? That will connect the 5V directly into the 5V pin of the Arduino (probably via a switching MOSFET). Then you can connect to your motor driver from the 5V pin on the Arduino (and Gnd of course). There may be some limitations on how large a motor you can drive (based on the capacity of the power bank, and to an extent also the thickness of the traces on the Arduino board).
As others have commented, Vin is not intended for that purpose (ie. to supply 5V). You should supply 7V or more to Vin to force the switching MOSFET to disconnect the USB input. In your case you don't have 7V from the powerbank.

Here is how the Uno Rev3 power system works:

The input jack (circled in blue) goes through a diode (D1) to the Vin line.
Vin then goes through the 5V voltage regulator (U1) to provide +5V.
However on the top left you see 2 x 10K resistors (RN1A and RN1B) which make a voltage divider from Vin to Gnd. This is compared to the output of the 3.3V voltage regulator by U5A op-amp (circled in red). If higher, then T1 (circled in green) will turn off, disconnecting USBVCC from the +5V line. If lower, then USBVCC is connected to +5V. The nett effect is that if Vin in greater than 6.6V (because of the voltage divider) then the circuit chooses to use Vin, otherwises it uses USBVCC (USB power).
That's why they recommend to use 7V or more into Vin.
Note that you lose around 0.7V through the diode, which is why you need something like 7.3V at the input jack to allow for the loss of the 0.7V before the op-amp compares it to 6.6V.

the loads on the motor driver are too heavy to be powered from the arduino.

What are those loads (in mA)? The powerbank might not be able to provide it either.

about 1 amp each,2 motors.although the power bank may not be able to fulfil the required power but  the powerbank's smps will protect the battery...on the other hand if i do the same with the 5v arduino pin it will straight away damage it (from drawing too much current)..am I right?

I had this problem last year when I needed to power a prototype using a LiPo battery which supplies only 3,2 up to 3,7V (and up to 4,2V when charging).
My way of solving the problem was to use a voltage boost module. Boost circuits are a kind of circuit where you the inertial properties of passive components to elevate (or attenuate) DC voltage levels.
But you don't need to worry about the math behind use, there is modules like the MT3608 which will supply your circuit up to 28V starting from as little 2V, check the datasheet.

That is true, you can't power the Arduino with 5V from VIn.
If you have a constant 5V and you are confident that no major spikes are going to happen, then you might as well connect it to the Arduino's 5V pin.
Other wise, you need at least 7V power the Arduino from the VIn pin. Some say you can put in 6V, but that is just from test. The 7V is more reliable. Thus, you can power the Arduino with a 9V battery is you wish.


text:
How to flash an ATmega directly without a dedicated flashing device?
An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP).
I tried to flash the program into the microcontroller by saving the machine code to a MicroSD card that I then attached to the microcontroller. I figure we can use the USB SPI reader to test the program without dedicated device like USBtiny.
But I suspect that the compiler is just producing the hex file and then the USB will translate it to machine code.
Was I thinking wrong?
If the compiler loads the machine code through the USB programmer to microcontroller so don't we just need a MicroSD USB to program it?

Your initial assumption "An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP)." is wrong.
The C compiler converts the source code into assembly language. It is then passed to an assembler which converts it to object code. The linker then creates an ELF file from it all. That is then converted into a HEX file using objdump.
That HEX file is then loaded by another program, avrdude, which knows how to control the USB-connected programming device. That device then issues special instructions to the chip through the ISP port to copy the data loaded from the HEX file into the memory of the chip in the right way.
It's quite a complex procedure and you require some active component in the mix to do the job. Just connecting an SD card and hoping it will work is, I am sorry to say, a laughable concept. You require something that a) understands how to read data from an SD card and can interpret it, and b) knows how to program an ATMega through ISP.
It is possible to create something that does that, using another chip, such as another ATMega, and writing the software to do it. If you feel adventurous, of course. You would basically have created a stand-alone programmer, which has advantages when you want to do field upgrades, but is pointless when you are sat at your desk developing software.

thank you,i didn't know how the compilers in common market do.However,writing the raw data or file format to microSD to run in ATmega has been done by many developers.

The compiler doesn't do that, a separate program does that.  For most ATMegas and most people, the program that does this is called avrdude.  It interfaces with your ISP and transfers the code when you give it appropriate settings.  See here:
http://www.ladyada.net/learn/avr/avrdude.html
So you get the hex from your compiler, and send that through avrdude to the chip using your ISP.  At no point is the MicroSD necessary.  FWIW, the ATMega must have its code loaded into its flash memory.  It cannot run code from the Micro SD.

the developers in the world have finished projects to run external program in MicroSD,all the source code doesn't need to be compiled before runtime,i can put the source code into a library,re flashing it on board or running a virtual machine.


text:
Multiple I2C sensors with the same address
I am trying to find the simplest way to connect multiple (preferably around 10-20) IMU sensors to one controller. There are two constraints: sampling at 60Hz and reasonably simple wiring as I want to put it on clothes.
I am totally new to the Arduino world, please let me know what other details I should provide.
It seems that just having multiple IMUs on the I2C bus would work great, but they usually all come with the same address.
So, the solutions I found so far:

Using several different IMUs from different companies - hard to find 20 of them
Using a multiplexer - requires star-like wiring topology.
Using multiple controllers - inefficient and doesn't seem right.

For now, the solution with a multiplexer seems to me the most reasonable, but is there any other way I am missing? Can I somehow produce IMUs with, say, 16 different addresses and wire them all together to one I2C?
Thanks for your help!

See also http://arduino.stackexchange.com/questions/18790/how-to-set-address-for-using-more-than-mpu9250/18793#18793

If you're using MPU6050 IMUs, there's an easy trick: put them all on the I2C bus, and connect each IMU's AD0 pin to a separate digital pin on the Arduino[*]. When you want to read from a specific IMU, set all AD0s to HIGH, except the one you want to read to LOW. All the IMUs with AD0 set to HIGH with have an I2C address of 0x69, whereas the only one on LOW will have an address of 0x68.
If you want to read them all, you just go through a loop and set the one you want to LOW, the others to HIGH, and you're set.
[*] If you want 20 IMUs, you'd better get a Mega, or, even better, a Maple. Small form factor, quite a bit of oomph, lots of pins and flash, and some clones cost next to nothing; eg Itead sells Maple clones for 6 bucks. ElecFreaks sells them for 9 bucks. You could use the 16 pins at the bottom for the AD0s.
This trick works with any kind of I2C device that has a customizable address scheme through one or more pins. I do that with AT24Cxx EEPROMS, which have a 0x50-57 address range. When you want to have more than eight chips, setting all but one to 0x50 and one to 0x51 solves the problem pronto.
Reference: https://github.com/PaulStoffregen/FreeIMU_original/blob/master/documents/PS-MPU-6000A-00v3.4.pdf

That's a pretty clever idea!

And coming from you, that's a nice compliment, Nick!

A minor extension -- for adding more devices, using a shift register like the 74HC595 to 'drive' those A0 pins. Daisychained, you could get 32 (and maybe more) for the cost of just 3 pins on the microcontroller -- with SDA and SCL, a total of 5 uC pins to manage 32 MPUs.

You can also get I2C Multiplexers such as the TCA9545A that can split one I2C line into 4 buses. I have connected up to 9 MPU9150 on one line with that.

Another way is to use a software emulation of the I2C interface so that any of the digital I/O pins may act as an I2C pin. One well-written library you can use for this is SoftWire by Steven Marple. It can be installed via the Arduino Library Manager or directly from its GitHub repository here.
With this, you can select arbitrary pairs of pins to act as SDA and SCL for each I2C device and then you can communicate with each device individually.
Note that with this method, you need two digital pins for each I2C device. In that sense, I believe @dda's answer is the best in regard to these IMUs in question.


text:
Sensors go crazy on external power
For few days, I am trying to figure out, why my sensors do not work on external power. I bought NodeMCU along with couple different sensors etc. I was happily working with them, connecting them one by one to the 3.3v pin in the NodeMCU board, programming each of them. Everything was working as expected. After I have finished, I decided it's time to use them all at once, but I knew, that for that to work, I need to provide them with enough power, as USB probably won't be enough (plus, when I'm done, I don't plan to use USB to power the system anyway). I have a module that converts 230v AC into 5v DC, and then I am stepping it down to 3.3v in order to power the sensors. After checking with multimeter, the voltages are ok, and so is the current.
My problem is, that the sensors give completely random data (most of the time they don't give any information, but once in a while they send something like 1000 times the normal value). Below you can see the schematic that I use. Can you please help me figure this out?
Edit: I would just like to add - I did try to run NodeMCU solely on the Ext. Power - the circuit looked exactly as below, I just connected positive output of 3.3v power source, to the 3.3v connector on NodeMCU. The board was working (I was able to control the onboard LED via WiFI), but the sensor did not. I then reconnected the sensor from external power, to NodeMcu 3.3v, and it (the sensor) worked... I have no idea why.

simulate this circuit – Schematic created using CircuitLab

I did connect them (NodeMCU GND <-> Ext. Power GND) permanently, to test if the sensors will start working. They still were behaving randomly, so I removed that connection.

@ojek https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/

@Majenko: Thanks. I did read about common ground before. That's why I decided to power the whole system only by "Ext. Power 3.3v" (so no USB). And it still behaves the same way - sensor Vin/GND connected to NodeMCU works, but when I connect them to Ext. Power it stops working.

I have fiddled with it a little more. Turns out, that the resistor I was putting in the circuit was the cause of failure - the sensor did not have enough power.
Now this is very weird to me, as the sensor is rated at 190uA max, and it is not working on this current. Only after I removed the resistor (so the current was around 800mA) it started operating as it should have.

Sorry I don't have reputation for a comment but this might be of help.
You didn't specify if the sensor was a breakout board. If it is then the board may already have the resistor in place, which is why removing it worked.
Now if you had the resistor in place when it was also connected to the nodeMCU, then perhaps power from it was high enough to still generate a stable operating condition (not familiar with nodeMCU) but more likely you have a power supply issue.

Is it a module and does it have resistor on board.
was the 27k resistor only in circuit on external power.

If the answer was yes to the above that is probably the issue.
If they are not the cause, my next check would be your external power. It could need calibration, power spikes/ripples etc but the easiest thing to do is put in a smoothing capacitor in circuit after your power supply.
Probably about 20-30% of my sensor issues are resolved by this. Another 60% are solved by fixing my screw ups and assumptions.

Ugh I just realized you were talking about the current the sensor draws. I had a brain dump (assumptions will be the death of me). You need to just get rid of the resistor. The sensor, if voltage is right will only draw what it needs. I'm guessing you didn't have it in circuit before you went to external power.

I feel really bad for an answer that made such a bad assumption. My apologies. Let me know if you work out the cause.


text:
Arduino program to Blink L LED when input matches a set pattern
I have written a code that is supposed to blink the LED on PB5 pin, when a sequence of input matches a 4 digit password input from a keypad.But the program doesn't appears to be working as expected.
keypadGetKeyPressed() returns a char output of the keypad
and I want to blink led on PB5 /13 PIN
lcd.h has used PORTB is it because of that
        #include <avr/io.h>
        #include <util/delay.h>

        #include "lcd.h"
        #include "keypad.h"

        #include <string.h>

        int main(void) {

            // Password
            char password[4]="5678";

            char keyPressed, oldKeyPressed = 0;
            lcdInit();
            keypadSetupPins();

            lcdWriteCommand(DISPLAY_ON | BLINK | UNDERLINE);
            lcdWriteCommand(CLEAR_DISPLAY);

            char p1 = '1';
            char p2 = '2';
            char p3 = '3';
            char p4 = '4';
            char p5 = '5';

            //Sets the digital pin Pb5 or 13 as Output
            DDRB |= (1<<PB5);
            //Sets LED initially as ON, put ~ before the ( to set it off initially
        //  DDRB |= (1<<PB5);

            // to count matched character
            int count=0;
            char message[]="Logged In";
            while (1) {

                keyPressed = keypadGetKeyPressed();
                if(keyPressed==password[count]){
                    count+=1;
                }
                else{
                    //if next char doesn't match reset counter
                    count= (keyPressed==password[0])?1:0;
                }
                if(count==4){
                    //Call the required function to toggle LED
                     count=0;

                     PORTB |= ~(1<<PB5);
                    _delay_ms(1000);
                    // Turn led off by setting corresponding bit low in the PORTB register.
                    PORTB |= ~(1<<PB5);

                    _delay_ms(500);
                    lcdWriteString(message);

                }

                if (keyPressed != 0 && (keyPressed != oldKeyPressed))

                {
                    lcdWriteChar(keyPressed);
                }

                oldKeyPressed = keyPressed;

                _delay_ms(20);

                if (keyPressed == p1 ) {

                    lcdWriteString("done");
                }

            }

        }

keypad.h file
            #ifndef KEYPAD_H_
            #define KEYPAD_H_

            #include <avr/io.h>

            #define NUM_COLS    3
            #define NUM_ROWS    4

            #define COL_DIR     DDRB
            #define COL_PORT    PORTB
            #define COL_1_PIN 2
            #define COL_2_PIN   3
            #define COL_3_PIN   4

            //NB it is important that the row pins all trigger the same
            //Pin change interrupt - see p70 of the datasheet
            #define ROW_DIR     DDRC
            #define ROW_INPUT   PINC
            #define ROW_PORT    PORTC  //for pullups

            #define ROW_1_PIN   0
            #define ROW_2_PIN   1
            #define ROW_3_PIN   2
            #define ROW_4_PIN   3

            /*
             * Set up the keypad pin directions, enable the pin change interrupt
             * and drive the column pins low.
             */
            void keypadSetupPins(void);

            /*
             * Scan the keypad to determine which key is pressed.
             * Returns 0 if no key pressed and returns ascii code if key pressed.
             * Sets all the cols to low when done.
             */
            char keypadGetKeyPressed(void);

            #endif /* KEYPAD_H_ */

keypad.c file
         * Set up the keypad pin directions, pull up resistors
         * and drive the column pins low.
         */
        void keypadSetupPins(void)
        {
            //Set column pins as output pins
            COL_DIR |= ( (1<<COL_1_PIN) | (1<<COL_2_PIN) | (1<<COL_3_PIN) );

            //Set rows pins to be inputs
            ROW_DIR &= ~( (1<<ROW_1_PIN) | (1<<ROW_2_PIN) | (1<<ROW_3_PIN) | (1<<ROW_4_PIN) );

            //Enable Pullups on row pins
            ROW_PORT |= ( (1<<ROW_1_PIN) | (1<<ROW_2_PIN) | (1<<ROW_3_PIN) | (1<<ROW_4_PIN) );

            //Send out three 0's on COLs
            COL_PORT &= ~( (1<<COL_1_PIN) | (1<<COL_2_PIN) | (1<<COL_3_PIN) );

        }

        /*
         * Scan the keypad to determine which key is pressed.
         * Returns 0 if no key pressed and returns ascii code if key pressed.
         * Sets all the cols to low when done.
         */
        void passwordString(char string[])
        {
            int i = 0;

        }

        char keypadGetKeyPressed(void)
        {
            char retVal = 0;
            uint8_t rowPins;

            //Send 011 on the cols
            //Send out 0 on col 1

            COL_PORT &= ~(1<<COL_1_PIN);
            //Send out 11 on cols 2 and 3
            COL_PORT |= ( (1<<COL_2_PIN) | (1<<COL_3_PIN) );

            //CRUCIAL - delay to allow values to propagate to the rows
            _delay_us(1);

            //Read PIN reg and copy into var
            rowPins = ROW_INPUT;

                //Test row 1
                if( !(rowPins & (1<<ROW_1_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                //there is a 0 on row 1 pin => Key 1 is pressed
                retVal = '1';
                }

                //Test row 2
                if( !(rowPins & (1<<ROW_2_PIN)) ) //if the ROW_2_PIN in the ROW_INPUT reg is NOT high
                {
                //there is a 0 on row 1 pin => Key 4 is pressed
                retVal = '4';
                }

                //Test row 3
                if( !(rowPins & (1<<ROW_3_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '7';
                }

                //Test row 4
                if( !(rowPins & (1<<ROW_4_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '*';
                }

            COL_PORT &= ~(1<<COL_2_PIN);
            //Send out 011 on cols 2 and 3
            COL_PORT |= ( (1<<COL_1_PIN) | (1<<COL_3_PIN) );

            //CRUCIAL - delay to allow values to propagate to the rows
            _delay_us(1);

            //Read PIN reg and copy into var
            rowPins = ROW_INPUT;

                //Test row 1
                if( !(rowPins & (1<<ROW_1_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 1 is pressed
                    retVal = '2';
                }

                //Test row 2
                if( !(rowPins & (1<<ROW_2_PIN)) ) //if the ROW_2_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 4 is pressed
                    retVal = '5';
                }

                //Test row 3
                if( !(rowPins & (1<<ROW_3_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '8';
                }

                //Test row 4
                if( !(rowPins & (1<<ROW_4_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '0';
                }

            COL_PORT &= ~(1<<COL_3_PIN);
            //Send out 011 on cols 2 and 3
            COL_PORT |= ( (1<<COL_1_PIN) | (1<<COL_2_PIN) );

            //CRUCIAL - delay to allow values to propagate to the rows
            _delay_us(1);

            //Read PIN reg and copy into var
            rowPins = ROW_INPUT;

                //Test row 1
                if( !(rowPins & (1<<ROW_1_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 1 is pressed
                    retVal = '3';
                }

                //Test row 2
                if( !(rowPins & (1<<ROW_2_PIN)) ) //if the ROW_2_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 4 is pressed
                    retVal = '6';
                }

                //Test row 3
                if( !(rowPins & (1<<ROW_3_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '9';
                }

                //Test row 4
                if( !(rowPins & (1<<ROW_4_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '#';
                }

                return retVal;
          }

lcd.h file
            #ifndef LCD_H_
            #define  LCD_H_

            #include <avr/io.h>
            #include <util/delay.h>

            //If nibble mode is enabled it is assumed that D4->D7 on the LCD
            //are connected to pins 0->3 of the data port.
            #define USE_NIBBLE_MODE    0  //0 for false, 1 for true
            #define LINE_MODE          0 //0 for ONE line mode, 1 for TWO line mode

            #define LCD_CONTROL_PORT   PORTB
            #define LCD_CONTROL_DIR    DDRB
            #define RS_PIN             PORTB0
            #define E_PIN              PORTB1

            #define LCD_DATA_PORT      PORTD
            #define LCD_DATA_DIR       DDRD

            #define CLEAR_DISPLAY       0x01
            #define DISPLAY_CURSOR_HOME 0x02
            #define DISPLAY_ON          0x0C
            #define DISPLAY_OFF         0x08
            #define UNDERLINE           0x02    //OR this with DISPLAY_ON
            #define BLINK               0x01    //OR this with DISPLAY_ON
            #define ONE_LINE_MODE       0x34
            #define TWO_LINE_MODE       0x38
            #define SET_ADDRESS         0x80    //You must OR the appropriate address with this
            #define DISPLAY_SHIFT_LEFT  0x18
            #define DISPLAY_SHIFT_RIGHT 0x1C
            #define CURSOR_SHIFT_LEFT   0x10
            #define CURSOR_SHIFT_RIGHT  0x14

            void lcdInit(void);

            void lcdWriteCommand(uint8_t command);

            void lcdWriteChar(char ch);

            void lcdWriteString(char string[]);

            #endif  /* LCD_H */

lcd.c file
            #include "lcd.h"

            /***********************************************************
             * This function sets th direction of the pins that are
             * connected to the LCD.
             * The code makes use of the #defined names in lcd.h so that
             * if the pins connected to the LCD change only lcd.h needs
             * to be changed and not the code in this file.
             *
             * This function is complete.
             **********************************************************/
            void lcdInit(void)
            {
                //set direction of control pins to be outputs
                LCD_CONTROL_DIR |= (1<<RS_PIN);
                LCD_CONTROL_DIR |= (1<<E_PIN);

                //Set direction of data port pins to be outputs
                LCD_DATA_DIR |= 0xFF;
            }

            /****************************************************
             * Sends a a single command to the LCD
             * Takes care of the register selection,
             * placing data on the data pins and toggle of E pin
             *****************************************************/
            void lcdWriteCommand(uint8_t command)
            {
                PORTB &= ~(1<<RS_PIN);

                PORTD = command;

                PORTB |= (1<<E_PIN);

                _delay_us(2); //lcd boot delay

                PORTB &= ~(1<<E_PIN);

                _delay_ms(2);
            }

            /****************************************************
             * Sends a a single ascii char to the LCD
             * Takes care of the register selection,
             * placing data on the data pins and toggle of E pin
             *****************************************************/
            void lcdWriteChar(char ch)
            {
                PORTB |= (1<<RS_PIN);

                PORTD = ch;

                PORTB |= (1<<E_PIN);

                _delay_us(2); //lcd boot delay

                PORTB &= ~(1<<E_PIN);

                _delay_ms(2);
            }

            /****************************************************
             * Writes a string to the LCD
             * Steps through the string passed as a parameter and
             * calls lcdWriteChar() to send each character of the
             * string
             *****************************************************/
            void lcdWriteString(char string[])
            {
                int i = 0;

                while (string[i] != '\0')
                {
                    lcdWriteChar(string[i]);
                    i++;
                }
            }

Please define "not work as expected". What does it do?

the program does not blink on input sequence match with the password  and does no display the message to the lcd screen

Does not look like your key debouncing is very robust.  Likely you are sensing numbers like "5555566677777777888".

my approach is based on the code in https://repl.it/NAeo/0  and I need it for small input sequences like say 200 inputs

I am supposed to use only pure C for this work

The following proposed code:

corrects the worst of the logic problems
eliminates unused/unnecessary local variables
performs the desired function
keeps data declarations local to where they are used
expects the keypad input function to perform the majority of the key debouncing.

and now the proposed code:
    #include <avr/io.h>
    #include <util/delay.h>

    #include "lcd.h"
    #include "keypad.h"

    #include <string.h>

    int main(void)
    {
        // Password
        char password[5]="5678";  // 5 to allow for trailing NUL byte

        char oldKeyPressed = 0;

        lcdInit();
        keypadSetupPins();

        lcdWriteCommand(DISPLAY_ON | BLINK | UNDERLINE);
        lcdWriteCommand(CLEAR_DISPLAY);

        //Sets the digital pin Pb5 or 13 as Output
        DDRB |= (1<<PB5);
        //Sets LED initially as ON, put ~ before the ( to set it off initially
        //  DDRB |= (1<<PB5);

        size_t count = 0;

        for( size_t i=0; i< strlen( password ); i++ )
        {
            char keyPressed = keypadGetKeyPressed();

            if(keyPressed==password[count])
            {
                count+=1;
            }

            else
            {
                count = 0;
            }

            if( count == strlen( password ) )
            {
                char message[] = "Logged In";

                //Call the required function to toggle LED
                PORTB |= ~(1<<PB5);
                _delay_ms(1000);
                // Turn led off by setting corresponding bit low in the PORTB register.
                PORTB &= ~(1<<PB5);

                _delay_ms(500);
                lcdWriteString(message);
            }

            // this code block should (probably) only be for debug
            if (keyPressed != 0 && (keyPressed != oldKeyPressed))
            {
                lcdWriteChar(keyPressed);
            }

            // debounce the keypad
            oldKeyPressed = keyPressed;
            _delay_ms(20);

            // method of exiting the program before fully logged in
            if (keyPressed ==  '1' )  // so '1' cannot be part of the password
            {
                lcdWriteString("done");
                break;
            }
        }
    }