body:
I'm a beginner in using NRF24L01 tranceiver module. I tried sending a simple "Hello world" using Arduino Nano and a Arduino UNO with the use of two NRF24L01 modules. I don't get any output in the serial monitor at the receiver side. I checked the wire connection numerous times. Also checked the baud rate of both receiver code and the serial monitor are same and adddresses of the tranceiver code and the receiver code are same. Looking for a solution. Thanks in advance.

This is my tranceiver code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    RF24 radio(7, 8); // CE, CSN
    const byte address[6] = "00001";
    void setup() {
      radio.begin();
      radio.openWritingPipe(address);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();
    }
    void loop() {
      const char text[] = "Hello World";
      radio.write(&text, sizeof(text));
      delay(1000);
    }

And this is my Receiver code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    RF24 radio(7, 8); // CE, CSN
    const byte address[6] = "00001";
    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.openReadingPipe(0, address);
      radio.setPALevel(RF24_PA_MIN);
      radio.startListening();
    }
    void loop() {
      if (radio.available()) {
        char text[32] = "";
        radio.read(&text, sizeof(text));
        Serial.println(text);
      }
    }

title: NRF24L01 Transmission Problems between Arduino UNO and Arduino Nano

Answers: 4

body:
I had the same problem and when I tried the isChipConnected () function, it told me that one of the nrf24l01 was not connected to the SPI and I assumed that one was bad. I bought 2 nrf24l01 with antenas and they work well (mostly). ( [Here is the link to the library reference][1]. Also, make sure you are using the TMRh20 version of the library, [This one][2]. This is more updated and better as far as I'm aware.

Like everyone would suggest, try to solder a 10uF capacitor between GND and VCC (that module requires more power sometimes). And the last thing I tried was to use one of this socket adaptors for the 2 modules [here][3] to use the 5v output from the arduino since it can deliver more mA and thus the module can work better.
This guide help me a little bit, I'll drop it [here][4]
I don't see anything wrong in the code, but I'm a newbie like you so (It seems we are using the same adress in our codes)

  [1]: https://tmrh20.github.io/RF24/classRF24.html#ac224c55270d26dbe7b4f3492ea3056b5
  [2]: https://tmrh20.github.io/RF24/index.html
  [3]: https://es.aliexpress.com/item/4000581444984.html?src=google&src=google&albch=shopping&acnt=631-313-3945&isdl=y&slnk=&plac=&mtctp=&albbt=Gploogle_7_shopping&aff_atform=google&aff_short_key=UneMJZVf&&albagn=888888&albcp=9866812513&albag=101880764522&trgt=896505316494&crea=es4000581444984&netw=u&device=c&albpg=896505316494&albpd=es4000581444984&gclid=CjwKCAjwltH3BRB6EiwAhj0IUCfw4KSDmSKgvcsDt2Mr-7kaVs6966bjcXevAQOEUn091gvA0wYaCBoCiI0QAvD_BwE&gclsrc=aw.ds
  [4]: https://forum.arduino.cc/index.php?topic=421081

body:
You can also try using the NRFLite library. It is a lot easier to use. Also make sure you have a minimum of 3.3V and 0.5A power at the radio pin. If not, it may not transmit.

Here is a TX and RX example of sending text using the NRFLite. It worked perfectly for me!

TX:
```
/*

Demonstrates sending and receiving packets of different length.

Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND

*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 1;
const static uint8_t DESTINATION_RADIO_ID = 0;
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket1
{
    uint8_t FromRadioId;
    uint8_t Counter;
};

struct RadioPacket2
{
    uint8_t FromRadioId;
    char Message[31];    // Note the max packet size is 32, so 31 is all we can use here.
};

NRFLite _radio;
RadioPacket1 _radioData1;
RadioPacket2 _radioData2;

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

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }

    _radioData1.FromRadioId = RADIO_ID;
    _radioData2.FromRadioId = RADIO_ID;
}

void loop()
{
    // Pick a number from 0 - 60,000.
    uint16_t randomNumber = random(60001);

    if (randomNumber > 30000)
    {
        // Send RadioPacket1.

        _radioData1.Counter++;

        Serial.print("Sending ");
        Serial.print(_radioData1.Counter);

        if (_radio.send(DESTINATION_RADIO_ID, &_radioData1, sizeof(_radioData1)))
        {
            Serial.println("...Success");
        }
        else
        {
            Serial.println("...Failed");
        }
    }
    else
    {
        // Send RadioPacket2.

        // Create a message and assign it to the packet.
        // Strings need to be converted to a char array and note they cannot be longer
        // than 31 characters since that is the size of _radioData2.Message.
        String msg = "Hello " + String(randomNumber);
        msg.toCharArray(_radioData2.Message, msg.length() + 1);

        Serial.print("Sending '");
        Serial.print(msg);
        Serial.print("'");

        if (_radio.send(DESTINATION_RADIO_ID, &_radioData2, sizeof(_radioData2)))
        {
            Serial.println("...Success");
        }
        else
        {
            Serial.println("...Failed");
        }
    }

    delay(1000);
}
```

RX:
```
/*

Demonstrates sending and receiving packets of different length.

Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND

*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 0;
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket1
{
    uint8_t FromRadioId;
    uint8_t Counter;
};

struct RadioPacket2
{
    uint8_t FromRadioId;
    char Message[31];    // Note the max packet size is 32, so 31 is all we can use here.
};

NRFLite _radio;
RadioPacket1 _radioData1;
RadioPacket2 _radioData2;

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

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }
}

void loop()
{
    // 'hasData' returns the size of the packet that was received, or 0 if there is no data.
    uint8_t packetSize = _radio.hasData();

    if (packetSize == sizeof(RadioPacket1))
    {
        _radio.readData(&_radioData1);

        Serial.print("Received ");
        Serial.print(_radioData1.Counter);
        Serial.print(" from radio ");
        Serial.println(_radioData1.FromRadioId);
    }
    else if (packetSize == sizeof(RadioPacket2))
    {
        _radio.readData(&_radioData2);

        String msg = String(_radioData2.Message);

        Serial.print("Received '");
        Serial.print(msg);
        Serial.print("' from radio ");
        Serial.println(_radioData2.FromRadioId);
    }
}
```
```

body: @Erick Navarrte @dragonflyrobotics Thank you so much for your response, I've tried each an every option you've mentioned, but for an unknown reason it didn't work out for me. Then I researched more on and found out the NRF24L01 base module.This NRF24L01 base module help you to fix 8 pin NRF24L01 series RF module without any problem. And also this module comes with 3.3V regulator and a built in capacitor and easy pin connection to connect PIC or arduino. Using NRF24L01 module and NRF24L01 base module I was successfully able to transmit data.Thanks again for taking time in answering, highly appreciate it.

body:
I use Chinese clone nRF24L01. It has very narrow voltage tolerance. My Arduino is also clone.
The 3.3V output voltage was 3.27. The nRF24L01 was not working.  I added a 3 terminal regulator between Arduino 5V output pin and nRF24L01. The voltage was 3.303V.
Then nRF24L01 was working normally.

```c++
///////////////////////////////////////////////
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);
const byte rxAddr[6] = "00001";
void setup()
{
  radio.begin();
  radio.setRetries(15, 15);
  radio.openWritingPipe(rxAddr);
radio.stopListening();
pinMode(4,OUTPUT);
}
void loop()
{
  const char text[] = "Kawasaki_JP";
  radio.write(&text, sizeof(text));

  delay(1000);
}
////////////////////////////////////////////////

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);
const byte rxAddr[6] = "00001";
void setup()
{
  Serial.begin(9600);
  while (!Serial);
  radio.begin();
  radio.openReadingPipe(0, rxAddr);
   radio.startListening();
}
void loop()
{
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

////////////////////////////////////////////
```
library ;  https://downloads.arduino.cc/libraries/github.com/TMRh20/RF24-1.4.0.zip


body:
so I've got myself a Arduino Pro Micro ATmega32U4 5V 16MHz and my PC (Win10 64bit) won't recognize it.
So, after I firstly plugged it in, it was detected as a Leonardo, rather than a Pro Micro, afterwards I installed hte drivers as noted by Sparkfun, and added the board to the IDE. Afterwards, my Arduino got detected as an unknown device where I can't use it anymore. I tried installing the drivers as given by sparkfun over the "unknown device" and no luck by trying, I always get an error saying that Windows has already the best drivers for it already installed.

And later, I uninstalled the "uknown device" in hope that it will re-install itself upon pluggin it back it, and it actually disappeard totally and got repalced by "Unknown USB Device (Device Descriptor Request Failed)" under USB controllers in the Device manager.

And I'm stuck here. In the IDE, the Pro Micro is detected as being on "COM1" no matter what COM port it really is, or is it even plugged it at all. Uploading a code results in the bar being filled up and "Uploading..." message, while maybe after a few minutes a very long error pops up without anything specific since you can plug out the board and get the same error.

I also tried a different PC with Windows 7 64bit on it, and instead of getting recognized as a Leonardo, this time it came straight to becoming a "Unknown device". I tried installing drivers multiple times with no luck, also again tried manually overiding the drivers in the Device manager and it always says that the best drivers are already installed.

I'm really stuck here.
Pics of  the board: https://postimg.cc/gallery/rwCDRfv

title: Arduino Pro Micro not recognized by PC

Answers: 2

body: It was wrong of you to try and install the driver as this board SHOULD be recognized as Leonardo. I would try to reinstall the Arduino IDE, it will also reinstall the drivers (hopefully)

body:
I got similar problem, I was trying to burn some HEX files and somehow, my windows wasn't able to recognize my atmega32u4 anymore, not even in Device Manager. I found that the bootloader was "bricked", and to fix it, you need to burn a valid HEX file, like the simplest led blink code. I've done that by the prompt command, using avrdude. So you reset twice, and you have 8 seconds to upload the hex file. It's faster doing that with prompt command than arduino software. After I uploaded the LED blink code successfully, the windows naturally recognized my atmega32u4 instantly, I could identify it in Device Manager as PCOM 4 since then. So you need to revive your bricked atmega's bootloader.
I guess there's nothing to do with the drivers in this case.


body:
Hello Arduino Stack Exchange,

I have an an `enum` instance called `state`:

```lang-C
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;
States state = SLEEP;
```

I would like to convert the value of `state` to a `String` so I can serially print it using `Serial.println()`.

Currently, when I type `String(state)`, I get a value `0`, `1`, etc.  I suppose this corresponds with the index of the `enum`'s key.

How can I get it to return `"SLEEP"`, `"AWAKE"`, etc.?

title: Getting enum name from enum instance

Answers: 1

body:
You can print the value as it is:
```
Serial.println(state);
```
This will print the the ordering number of the enum, but you can specify the value as any number **or char**.
```
enum States
{
  SLEEP = 'S',
  AWAKE = 'A',
  CRAZY = 'C'
};
```
Now if you print it with cast to char `Serial.println((char) state);` it will print a character, which in my opinion is much better then some number.

If you want to convert the enum values identifiers to strings you can do it with a preprocessor macro.
```
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;

#define IDNAME(name) #name
const char* stateNames[] = {IDNAME(SLEEP), IDNAME(AWAKE), IDNAME(CRAZY)};
```
I don't think this is better then to print the char values. To do a pretty print it is better to use descriptions.
```
const char* stateStr[] = {"Sleep", "Awake", "Undefined"};
Serial.println(stateStr[state]);
```


body:
I bought and E-Ink display from waveshare and it came with such a “driver hat”: https://www.waveshare.com/wiki/E-Paper_Driver_HAT#Display_Config_Switch

I am wondering what exactly is the role of this component? Why can’t I directly connect the cables from the display to the GIPO pins and drive the display without the driver hat - given the right software?

(I am also happy to get a pointer to a better forum to ask in if this here isn’t the right place.)

title: Possible to drive Waveshare E-ink without driver hat?

Answers: 1

body:
No, you need the hat, or something equivalent. Turn it over. You see all those components? They exist to generate the right voltages for the ePaper display. Without those it won't work.

Sure, you can recreate it from [the schematic](https://www.waveshare.com/w/upload/8/87/E-Paper-Driver-HAT-Schematic.pdf), but why bother when you have it already?


body:
On my Arduino Uno, when I'm not using the serial everything seems in order:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

    void setup()
    {
        // put your setup code here, to run once:
        lcd.begin(16, 2);
        lcd.clear();
        lcd.print("Prints");
        lcd.setCursor(0, 1);
        lcd.print("Well");
    }

    void loop()
    {
        delay(1000);
    }

However the moment I open the serial port with:

    Serial.begin(9600);

The problem starts.

Clearing the LCD does not clear it but prints a character with 4 horizontal lines. Trying to move the cursor will print a different  unrecognisable character. Sending things to the Arduino via the Serial port prints gibberish on the LCD.

[![character with 4 horizontal lines][1]][1]

Any idea why? Is there a way to work with the LCD and the serial port simultaneously? I require the serial port in order to control the Arduino from NodeJS.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

    void setup()
    {
        // put your setup code here, to run once:
        lcd.begin(16, 2);
        lcd.clear();
        lcd.print("Prints");
        lcd.setCursor(0, 1);
        lcd.print("Well");

        Serial.begin(9600);

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

    void loop()
    {
        lcd.clear(); // This will print 4 horizontal lines character instead of clearing
        delay(500);
    }

  [1]: https://i.stack.imgur.com/hj5aN.png

title: Liquid Crystal LCD and serial monitor not playing well together

Answers: 1

body:
On an UNO pin 1 is one of the hardware serial pins.  You can’t use pin 0 or pin 1 for other things if you are using Serial in your code.

Even if you aren’t using Serial, you use pins 0 and 1 when uploading your code and having other things connected can mess up that process.  It’s generally advisable to stay away from pins 0 and 1 unless you absolutely must use them.


body:
I tried to make a car that moves using a 4x4 keypad.
Pressing "12" unlocks the car and sets the motors to move forward. After that, if I press 4, the speed of the left motor is reduced to half allowing the motor to turn left, and vice versa for right wheel when key 6 is pressed.

Here is the code:

```
#include <Key.h>
#include <Keypad.h>

char* startCar = "12";
int position = 0, state = 0;

/*
 * state 0: off
 * state 1: forward
 * state 2: backward
 *
 */

const byte rows = 3;
const byte cols = 3;
char keys[rows][cols] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'}
};

byte rowPins[rows] = {2,3,4};
byte colPins[cols] = {PD7, PD6, PD5};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);

int a=12,b=11,c=10,d=9;
void setup()
{
  pinMode(a,OUTPUT);
  pinMode(b,OUTPUT);
  pinMode(c,OUTPUT);
  pinMode(d,OUTPUT);
  Serial.begin(9600);
  setLocked(true);
}

void loop()
{
  char key = keypad.getKey();
  Serial.print(key);
  if (key == '9')
  {
    position = 0;
    setLocked(true);
  }
  if (key == startCar[position])
  {
    position ++;
  }
  if (position == 2)
  {
    setLocked(false);
  }
  if(state)
  {
    if(key=='2')
     {
      //Move forward
        state = 1;
        runmotors(255,0,0,255);
     }
     if(key=='8')
     {
      //Move backward
        state = 2;
        runmotors(0,255,255,0);
     }
    if(key == '4')
    {
      if(state == 1)
      {
        runmotors(127.5,0,0,255);
      }

      else if(state==2)
        runmotors(0,127.5,255,0);
    }
    if(key == '6')
    {
      if(state == 1)
        runmotors(255,0,0,127.5);
      else if(state==2)
        runmotors(0,255,127.5,0);

    }
  }
  delay(100);
}

void setLocked(int locked)
{
  if (locked)
  {
    state = 0;
    runmotors(0,0,0,0);
  }
  else
  {
    state = 1; // Moves forward
    runmotors(127.5,0,0,255);
  }
}
void runmotors(int s1,int s2,int s3,int s4)
{
  analogWrite(a,s1);
  analogWrite(b,s2);
  analogWrite(c,s3);
  analogWrite(d,s4);
}
```

Everything works perfectly, except for the fact that when the state is 1, i.e. car is running forward, and I press 4 the left motor completely stops instead of reduced speed. The LED on the motor driver shield which shows whether a motor is running or not also goes off.
It is not a fault of the motor shield or the arduino as it worked when I test it individually with the motors (i.e. without the keypad etc).

Here is a photo of the shield:
[![Arduino motor driver shield][1]][1]

Although my problem is not quite visible in this, but here is a video of the car: https://www.youtube.com/watch?v=bq19gNOL8Pg

  [1]: https://i.stack.imgur.com/oSR1C.jpg

title: Motor does not work for a specific case when programming with L293D motor driver shield

Answers: 1

body:
On an UNO only certain pins are capable of PWM.  Pin 12 is not one of them.  When you try to call analogWrite with pin 12 it will recognize this and will simply call digitalRead for you with HIGH or LOW depending on whether your input is greater than 127.

With most motor controllers you can use one pin as a direction pin and the other as a PWM pin.  So to go one direction you set pin 12 HIGH and do inverted PWM on 11 (if those indeed go to the same motor I didn't look at your shield).  To go the other direction you write LOW on 12 and PWM on 11.

The motor turns when one pin is HIGH and the other is LOW.  When you set pin 12 high then PWM pin 11, whenever 11 is LOW in the PWM cycle it is turning the motor on and when it is HIGH it is turning it off.  So to make it run you might have to PWM 0 for go and 255 for stop.  Sometimes your PWM is on the enable line and then you still use 255 for go and 0 for stop.  It just depends on how things are wired.

When pin 12 is set to LOW then the motor is on when 11 is at the high part of the PWM cycle and off when it's low so you use 255 for go and 0 for stop.  But the whole time pin 12 doesn't have to change.

Now I am not 100% sure that this is the case with your particular motor controller, I'm more of a coder than a hardware guy.  But I've written enough code for motor controllers to know that you usually either need two direction lines and one PWM line or one direction and one PWM.  If that's not the case here then we can let someone else work on why.


body:
Here is the code
```
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <SoftwareSerial.h>

#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME680 bme; // I2C
//Adafruit_BME680 bme(BME_CS); // hardware SPI
//Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO,  BME_SCK);

SoftwareSerial gpsSerial(5, 11); // RX, TX (TX not used)
const int sentenceSize = 80;
char sentence[sentenceSize];

void setup() {
  Serial.begin(9600);
  while (!Serial);
  Serial.println(F("BME680 test"));
  gpsSerial.begin(9600);

  if (!bme.begin()) {
    Serial.println("Could not find a valid BME680 sensor, check wiring!");
    while (1);
  }

  // Set up oversampling and filter initialization
  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_2X);
  bme.setPressureOversampling(BME680_OS_4X);
  bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
  bme.setGasHeater(320, 150); // 320*C for 150 ms
}

void loop() {

 static int i = 0;
  if (gpsSerial.available())
  {
    char ch = gpsSerial.read();
    if (ch != '\n' && i < sentenceSize)
    {
      sentence[i] = ch;
      i++;
    }
    else
    {
     sentence[i] = '\0';
     i = 0;
     displayGPS();
    }
  }
}

void displayGPS()
{
  char field[20];
  getField(field, 0);
  if (strcmp(field, "$GPRMC") == 0)
  {
    Serial.print("Lat: ");
    getField(field, 3);  // number
    Serial.print(field);
    getField(field, 4); // N/S
    Serial.print(field);

    Serial.print(" Long: ");
    getField(field, 5);  // number
    Serial.print(field);
    getField(field, 6);  // E/W
    Serial.println(field);
  }
}

void getField(char* buffer, int index)
{
  int sentencePos = 0;
  int fieldPos = 0;
  int commaCount = 0;
  while (sentencePos < sentenceSize)
  {
    if (sentence[sentencePos] == ',')
    {
      commaCount ++;
      sentencePos ++;
    }
    if (commaCount == index)
    {
      buffer[fieldPos] = sentence[sentencePos];
      fieldPos ++;
    }
    sentencePos ++;
  }
  buffer[fieldPos] = '\0';

  if (! bme.performReading()) {
    Serial.println("Failed to perform reading :(");
    return;
  }
  Serial.print("Temperature = ");
  Serial.print(bme.temperature);
  Serial.println(" *C");

  Serial.print("Pressure = ");
  Serial.print(bme.pressure / 100.0);
  Serial.println(" hPa");

  Serial.print("Humidity = ");
  Serial.print(bme.humidity);
  Serial.println(" %");

  Serial.print("Gas = ");
  Serial.print(bme.gas_resistance / 1000.0);
  Serial.println(" KOhms");

  Serial.print("Approx. Altitude = ");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println(" m");

  Serial.println();
  delay(2000);
}
```

title: Can anyone find out why when I run this code for a GPS and BME680 sensor I have no errors but nothing happens

Answers: 0


body:
I am really new to coding and building stuff, so forgive me if it is anything offensive.i have been trying to convert my PS2 dualshock controller to USB using arduino. there is a library called ps2x that i can use to read the data and Joystick.h library to send it over USB-HID.
i just want to know if this is efficient code, if not how can i improve it.

This is the loop:
```void loop() {

 ps2x.read_gamepad(); //This needs to be called at least once a second
                        // to get data from the controller.

  Joystick.setXAxis(ANALOGSTATE1); //Joystick.setButton(-127 to 127); 0 is center
  Joystick.setYAxis(ANALOGSTATE2);
  Joystick.setZAxis(ANALOGSTATE3);
  Joystick.setThrottle(ANALOGSTATE4); //This one is different, (0 to 255) 127 is center

  Joystick.setButton(0, DIGITALSTATE1); //Joystick.setButton(0-31, 0-1);
                                        //Joystick.setButton(Select Button to Use, Specify ON/OFF of Button);
  Joystick.setButton(1, DIGITALSTATE2);
  Joystick.setButton(2, DIGITALSTATE3);
  Joystick.setButton(3, DIGITALSTATE4);
  Joystick.setButton(4, DIGITALSTATE5);
  Joystick.setButton(5, DIGITALSTATE6);
  Joystick.setButton(6, DIGITALSTATE7);
  Joystick.setButton(7, DIGITALSTATE8);
  Joystick.setButton(8, DIGITALSTATE9);
  Joystick.setButton(9, DIGITALSTATE10);
  Joystick.setButton(10, DIGITALSTATE11);
  Joystick.setButton(11, DIGITALSTATE12);
  Joystick.setButton(12, DIGITALSTATE13);
  Joystick.setButton(13, DIGITALSTATE14);
  Joystick.setButton(14, DIGITALSTATE15);
  Joystick.setButton(15, DIGITALSTATE16);

if(ps2x.ButtonPressed(PSB_TRIANGLE)) {
  DIGITALSTATE1 = 1;
}
  else if (ps2x.ButtonReleased(PSB_TRIANGLE)){
  DIGITALSTATE1 = 0;
}
if(ps2x.ButtonPressed(PSB_CIRCLE))
  {
    DIGITALSTATE2 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_CIRCLE)){
    DIGITALSTATE2 = 0;
  }
if(ps2x.ButtonPressed(PSB_CROSS))
  {
    DIGITALSTATE3 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_CROSS)){
    DIGITALSTATE3 = 0;
  }
if(ps2x.ButtonPressed(PSB_SQUARE))
  {
    DIGITALSTATE4 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_SQUARE)){
    DIGITALSTATE4 = 0;
  }
if(ps2x.ButtonPressed(PSB_PAD_RIGHT))
  {
    DIGITALSTATE5 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_RIGHT)){
    DIGITALSTATE5 = 0;
  }
if(ps2x.ButtonPressed(PSB_PAD_UP))
  {
    DIGITALSTATE6 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_UP)){
    DIGITALSTATE6 = 0;
  }
if(ps2x.ButtonPressed(PSB_PAD_LEFT))
  {
    DIGITALSTATE7 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_LEFT)){
    DIGITALSTATE7 = 0;,
  }
if(ps2x.ButtonPressed(PSB_PAD_DOWN))
  {
    DIGITALSTATE8 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_DOWN)){
    DIGITALSTATE8 = 0;
  }
if(ps2x.ButtonPressed(PSB_L1))
  {
    DIGITALSTATE9 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_L1)){
    DIGITALSTATE9 = 0;
  }
if(ps2x.ButtonPressed(PSB_L2))
  {
    DIGITALSTATE10 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_L2)){
    DIGITALSTATE10 = 0;
  }
if(ps2x.ButtonPressed(PSB_R1))
  {
    DIGITALSTATE11 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_R1)){
    DIGITALSTATE11 = 0;
  }
if(ps2x.ButtonPressed(PSB_R2))
  {
    DIGITALSTATE12 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_R2)){
    DIGITALSTATE12 = 0;
  }
if(ps2x.ButtonPressed(PSB_L3))
  {
    DIGITALSTATE13 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_L3)){
    DIGITALSTATE13 = 0;
  }
if(ps2x.ButtonPressed(PSB_R3))
  {
    DIGITALSTATE14 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_R3)){
    DIGITALSTATE14 = 0;
  }
if(ps2x.ButtonPressed(PSB_START))
  {
    DIGITALSTATE15 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_START)){
    DIGITALSTATE15 = 0;
  }
if(ps2x.ButtonPressed(PSB_SELECT))
  {
    DIGITALSTATE16 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_SELECT)){
    DIGITALSTATE16 = 0;
  }

  ANALOGSTATE1 = map(ps2x.Analog(PSS_LX), 0, 255, -127, 127);
  ANALOGSTATE2 = map(ps2x.Analog(PSS_LY), 0, 255, -127, 127);
  ANALOGSTATE3 = map(ps2x.Analog(PSS_RX), 0, 255, -127, 127);
  ANALOGSTATE4 = (ps2x.Analog(PSS_RY));

}```

title: How do i efficiently write this code for PS2 controller to USB convertion sketch for Arduino Pro Micro?

Answers: 0


body:
In my application Arduino Due is configured as master and instead of the actual slave device I am making use of Arduino Uno as Slave.I will share the Master code which I have worked out. Can Anyone please help me with respect to slave code of Arduino Uno to display the data in serial monitor at slave side. Any Help With respect to this aspect will be greatly greatly appreciated.

    #include <SPI.h>

    SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
    const uint8_t ss = 10;

    void setup() {
      pinMode(ss, OUTPUT);

      SPI.begin();

      digitalWrite(ss, LOW);
      SPI.beginTransaction(mySettting);
      SPI.transfer(0x00);
      SPI.transfer(0x25);
      SPI.transfer(0x1C);
      SPI.endTransaction();
      digitalWrite(ss, HIGH);
    }

    void loop() {
    }

----------

Thanks for the reply.
Referring to the code attached below at the slave side as you have mentioned that HEX to be displayed in serial monitor window, Do I need to add the HEX at the master side I mean Do I need to load the Hexadecimal data (0x00251C) into HEX buffer??

Thanks in Advance

    #include <SPI.h>

    SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
    const uint8_t ss = 10;

    void setup() {
      pinMode(ss, OUTPUT);

      SPI.begin();

      digitalWrite(ss, LOW);
      SPI.beginTransaction(mySettting);
      SPI.transfer(0x00);
      SPI.transfer(0x25);
      SPI.transfer(0x1C);
      SPI.endTransaction();
      digitalWrite(ss, HIGH);
    }

    void loop() {
    }

title: SPI Slave Programming for Arduino

Answers: 1

body:
SPI.h library by default only support Master mode, the `SPI.begin()` will automatically set slave select (ss) pin to HIGH whether you have `pinMode(ss, OUTPUT)` in your setup() code or not and set the Arduino as an SPI master. This can be see on SPI library [source code](https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/SPI/src/SPI.cpp#L36-L51).

As the SPI library does not contain the functionality for slave mode, in order to use Arduino as a Slave, you will need to do some customised setup, mainly on 1) setting MISO as OUTPUT for slave to send data; 2) enable slave mode by setting the SPCR register; 3) enable interrupt when data is received. Here is an example for an SPI slave on Arduino.

    #include<SPI.h>

    volatile boolean received;
    volatile byte receivedData;

    ISR (SPI_STC_vect)        //Inerrrput routine function
    {
      receivedData = SPDR;   // Get the received data from SPDR register
      received = true;       // Sets received as True
    }

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

      pinMode(MISO,OUTPUT);   //Sets MISO as OUTPUT
      SPCR |= _BV(SPE);       //Turn on SPI in Slave Mode
      received = false;
      SPI.attachInterrupt();  //Activate SPI Interuupt
    }

    void loop()
    {
      if(received) {
        SPDR = receivedData;    // send back the received data, this is not necessary, only for demo purpose
        received = false;
        Serial.print(receivedData, HEX);
      }
    }


body:
hi i wrote a code(i modified it actually, please forgive me, im in a mess please help me if you can) for my esp8266 to serial communicate with at tiny 85 ,it will monitor switch state and publish accordingly. now i want to write a code where it wont publish but whenever the serial is available i want it to directly take it and digital write in void callback.
```
//ItKindaWorks - Creative Commons 2016
//github.com/ItKindaWorks
//
//Requires PubSubClient found here: https://github.com/knolleary/pubsubclient
//
//ESP8266 Simple MQTT light controller

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

int LED3 = 12;
int LED4 = 14;
int LED2 = 13;
int LED1 = 15;

bool switch1;
bool switch2;
bool switch3;
bool switch4;
char data ;
// the number of the pushbutton pin

//EDIT THESE LINES TO MATCH YOUR SETUP

#define MQTT_SERVER "192.168.0.223"
const char* ssid = "TACHYON_HOME";
const char* password = "qwertyui";

//LED on ESP8266 GPIO2

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

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

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

    delay(100);

    // We start by connecting to a WiFi network

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

    WiFi.begin(ssid, password);

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

    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

}

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

  //maintain MQTT connection
  client.loop();

  //MUST delay to allow ESP8266 WIFI functions to run
  delay(10);
   if (Serial.available()>0) /* If data available at serial port, enter if loop */
  {
    data = Serial.read(); /* Read data present at serial port */
    /* Print string with \r\n */
    Serial.print(data); /* Print data received */
    if (data == 'q') {
      client.publish(lightTopic,"1");

    }
else  if (data == 'w') {
      client.publish(lightTopic,"0");
    }
 else  if (data == 'e') {
      client.publish(lightTopic1,"1");
    }
    else if (data == 'r') {
      client.publish(lightTopic1,"0");

    }
     else if (data == 't') {
      client.publish(lightTopic2,"1");

    }
     else if  (data == 'y') {
      client.publish(lightTopic2,"0");

    }
     else if (data == 'u') {
      client.publish(lightTopic3,"1");

    }
     else if  (data == 'i') {
      client.publish(lightTopic3,"0");

    }

  }
}

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

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

 if(topicStr.equals(lightTopic)){

   if(payload[0] == '1'){
      digitalWrite(LED1 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED1 , LOW);
    }
 }
 if(topicStr.equals(lightTopic1)){

   if(payload[0] == '1'){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED2 , LOW);
    }
 }
 if(topicStr.equals(lightTopic2)){

   if(payload[0] == '1'){
      digitalWrite(LED3 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED3 , LOW);
    }
 }
  if(topicStr.equals(lightTopic3)){

   if(payload[0] == '1'){
      digitalWrite(LED4 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED4 , LOW);
    }
  }

}

void reconnect() {

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

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

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

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

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

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

      }

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

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

  String result;

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

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

  return result;
}

//////////////////i want to write some thing like///////////////////////////////////////
////////////////////////////////
if(topicStr.equals(lightTopic1)||Serial.available()>0){

   if(payload[0] == '1'|| data =q){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'|| data = w){
      digitalWrite(LED2 , LOW);
    }
/////////////////////////////////////////
```

title: How to get data out of loop?

Answers: 1

body:
So you want your program to react to both MQTT and serial messages. You
wrote this snippet:

```cpp
if (topicStr.equals(lightTopic1) || Serial.available() > 0) {
    if (payload[0] == '1' || data = q) {
        digitalWrite(LED2, HIGH);
    }
    else if (payload[0] == '0' || data = w) {
        digitalWrite(LED2 , LOW);
    }
    // ...
}
```

Other than a couple of syntactic problems (you mean `data == 'q'`, not
`data = q`), the logic is not appropriate. This is because:

* The test `payload[0] == '1'` only makes sense in the context of
  parsing an MQTT message, otherwise `payload` cannot be meaningfully
  defined.
* For the same reason, the test `data == 'q'` only makes sense in the
  context of parsing a serial command.

Since MQTT and serial use completely different commands, you will have
to handle them independently. You can keep the MQTT callback as is, and
implement the parser for the serial commands. Maybe something like:

```cpp
if (Serial.available()) {
    char command = Serial.read();
    Serial.print(command);  // echo to the serial port
    switch (command) {
        case 'q':
            digitalWrite(LED1, HIGH);
            break;
        case 'w':
            digitalWrite(LED1, LOW);
            break;
        // ...
    }
}
```

Alternatively, use an `if ... else if ...` chain if you are not
comfortable with the `switch` syntax.

I personally would rather store the topic names, LED pins and serial
commands in an array of structs, and loop through the array in both the
MQTT callback and the serial parser. But I assume that may be too
advanced for your current programming level, so maybe just stick with
the simple, albeit verbose solution.


body:
When using the deep sleep functionality on several ESP-01 boards, the boards require two resets in order to wake up properly (regardless of whether the resets are done by manually bridging the rst pin or by soldering a wire to do it from an interrupt). The boards do wake up and print some text automatically, but they do not run their firmware/code.

```c
#include <ESP8266WiFi.h>
void setup() {
    Serial.begin(74880);
    Serial.print("\n--------------STARTING----------------\n");

    //pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    //digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off (gpio @ high= off)

    delay(500);
    ESP.deepSleep(2000000, WAKE_RF_DEFAULT );
}

void loop() {
}
```

I have not been able to just wake the board and run the code like most examples on the web intend to work, so I suppose the problem is not with this code.

On a successful wake up, the serial output looks like this:

```
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld

--------------STARTING---------------
```

After the first reset, the board does indeed wake up, but it does not run it's code. It only prints this
```
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)
```

And then hangs there. After another reset, it successfully runs it's code.

This issue persists across all the esp 01 boards i own, and i have tried pulling UP and DOWN almost every combination of pins recommended. The line that is printed in the fauly cases does indeed say it is booting in the right mode, but still the code does not run, nor mine nor the one that runs before mine

title: ESP-01 does not run code after Deep Sleep

Answers: 1

body:
What sasso is describing is classic Deep Sleep Zombie mode. There's someone else here with ESP-01 boards with the same issue.  I'd bet you got your boards in blister packs from Inland.  I didn't see any ESP-01 boards from Inland at my local computer store, only ESP-01S, and that one works with Deep Sleep just fine.  I only bought the one for a test.  I believe it's the Flash chip, but we haven't proven that yet.  I have plenty of Winbond flash in case I find a board that goes zombie, and can prove or disprove my theory.  I have 8 different types of boards and modules, and all come out of Deep Sleep correctly.

edit: If the pic at Ali is correct, the Puya Flash shouldn't be causing an issue, presuming it's real and not a clone.  Half the time the pics are only 'representative examples' of what they ship.  The ESP8266 Arduino core has supported Puya for a while now.  Also, on sober reflection the Inland package I bought said ESP-01S, and it's actually an ESP-01 (false advertising).  I looked closer and didn't see the pull-up resistors. :-(

If you're powering it from that USB programmer board, it should work.  If you have a separate 3.3V supply, I'd be suspicious of the supply.  The current spikes as the ESP is booting will cause many switching supplies to drop below 2V briefly, and the ESP goes insane.  Without having a zombie in front of me, I'm at a loss to go a lot further as my 'scope leads aren't that long.


body:
I'm trying to create a function that will take a String as an input, and at every 20 characters, it will instert "\n" so that the string doesn't go off the side of my screen (I'm using an oled with the [SSD1306Ascii library][1]).

This is my code so far, but when I run it nothing appears on the screen (I have another part of the code which passes the string to the funtion):

    String message = "";
    String newMessage = "";

    void printMessage(String message) {
      oled.clear();
      if(message.length() > 20) {
        current = 20;
        while(current < message.length()) {
          newMessage = message.substring(current-20, current) + "\n";
          newMessage = newMessage + message.substring(current+1);
          current+20;
        }
        oled.println(newMessage);
      }
      else {
        oled.println(message);
      }
    }

  [1]: https://github.com/greiman/SSD1306Ascii

title: Add char at intervals in a String

Answers: 2

body:
I think that your implementation is fundamentally flawed. In the while loop, when you assign `newMessage` to a `message.substring` you are discarding all the work done in the previous iterations.

Also I would recommend keeping the splitting and the printing separated. The `operator +=` also is very handy here. This code (untested) should implement your original idea in a correct way

    String splitMessage( const String & message, const unsigned limit) {
      String newMessage = "";
      unsigned i = 0;
      while ( i+limit < message.length() ) {
        newMessage += message.substring(i, i+limit);
        newMessage += '\n';
        i += limit;
      }
      newMessage += message.substring(i);
      return newMessage;
    }

Then you can do:

    whatever.println(splitMessage(myMessage, 20));

----

Note that I retained the use of `String` from your original implementation, although, being in an embedded environment, it is likely better to avoid it in favor of stack-allocated c-strings.

I have found a substantial amount of pretty enlightening information in the various answers to this question: https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino

body:
One issue with both your failed implementation and the previous answer
is that they do loads of dynamic allocations and copies. Every time you
use the String’s `+` or `+=` operators you are allocating heap memory
for a brand new String, copying the original character data into the
newly allocated space, and eventually destroying the original Strings
when you don’t need them anymore.

The simplest way to avoid all these copies and allocations is to _not_
build the String you want. Instead, just `write()` the pieces one after
the other on the display. Here is a zero-copy, zero-dynamic allocation
solution:

```cpp
void printMessage(const char *message) {
    size_t length = strlen(message);
    while (length > 20) {
        oled.write(message, 20);
        oled.write('\n');
        message += 20;  // point to the rest of the message
        length  -= 20;  // remaining length
    }
    oled.write(message);
}
```

Note that the method `Print::write(const char *, size_t)` is used here
to print a slice of the message without ever building it as a string in
memory.

On these memory-constrained devices it is always preferable to avoid
heap allocation, and thus `String` objects. However, if for whatever
reason you _really_ need to print a `String` object, then you can use
the following overload to print it’s internal buffer without making any
extra copy:

```cpp
void printMessage(const String &message) {
    printMessage(message.c_str());
}
```


body:
I have 3 NodeMCU 1.0 12E ESP8266 boards.

**Issues**

Two of them require me to unplug and replug in the boards every time I want to flash code, and nothing appears on the serial output with this simple blink modified sketch I've shown below on those same boards. I don't have any special pin configurations on either of these boards, I simply have the NodeMCU boards connected to the PC through MicroUSB. The other board has no issues with uploading and displaying serial output also with no special pin configurations.

```
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  Serial.begin(115200);
  pinMode(4, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  Serial.println("ON");
  digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  Serial.println("OFF");
  digitalWrite(4, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}
```

Interestingly enough, the LED connected to the corresponding PIN behaves correctly, which would indicate flashing the code works fine, but serial output doesn't work on 2 of the boards.

**What I've tried**

- Making sure the baud rate of the serial monitor is 115200.

- Tried the sketch with different baud rates.

- Made sure the correct board and ports are being recognized.

- I have tried using certain pin configurations on some of my boards, (grounding GPIO pin 0, connecting Rx and Tx, etc), but like I said, I don't do this in general when uploading code. Maybe the ESP8266 requires some sort of initialization process that I haven't done?

I can't tell if my other two boards are defective or if I need to take extra steps for the two boards that are acting strange. Has anyone here experienced something like this?

Thanks

title: Serial Output on ESP8266 doesn't work on 2/3 of my boards

Answers: 0


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

Thanks!

title: Connecting microSD reader and e-paper display to Nano at the same time?

Answers: 1

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


body:
hi there im using arduino uno + usb host shield and i have taken the readings from the usb mouse in this line of code : x =  mi->dX;
and the x output is the speed of the mouse x coordinates
and i wanna make it thru an analog  reading from 0 to 1023 i should do a constrain and a map
then i send the data thru i2c comm and recieve them with a slave code and display them but the mouse on the screen is moving always when i give the mouse a left move the mouse moves always to left and when i gave the mouse roght it moves to the right always without stopping the cursor as if im giving it a speed direction + or - .

this is the master code :

```

#include<Wire.h>
#include <hidboot.h>
#include <usbhub.h>
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif
int x; // mouse x
int y; // mouse y
int y1;
int x1;
int l,r;
int x11,y11;
class MouseRptParser : public MouseReportParser
{
protected:
void OnMouseMove (MOUSEINFO *mi);
void OnLeftButtonUp (MOUSEINFO *mi);
void OnLeftButtonDown (MOUSEINFO *mi);
void OnRightButtonUp (MOUSEINFO *mi);
void OnRightButtonDown (MOUSEINFO *mi);
void OnMiddleButtonUp (MOUSEINFO *mi);
void OnMiddleButtonDown (MOUSEINFO *mi);
};
void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{
x =  mi->dX;
//x = constrain(x, 0, 1023);

Serial.println(x);

y =  mi->dY;
//y = constrain(y, 0, 1023);

Serial.println(y);

};
void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi)
{
Serial.println("L Butt Up");
l=0;
};
void MouseRptParser::OnLeftButtonDown (MOUSEINFO *mi)
{
Serial.println("L Butt Dn");
l=1;
};
void MouseRptParser::OnRightButtonUp (MOUSEINFO *mi)
{
Serial.println("R Butt Up");
r=0;
};
void MouseRptParser::OnRightButtonDown (MOUSEINFO *mi)
{
Serial.println("R Butt Dn");
r=1;
};
void MouseRptParser::OnMiddleButtonUp (MOUSEINFO *mi)
{
Serial.println("M Butt Up");
};
void MouseRptParser::OnMiddleButtonDown (MOUSEINFO *mi)
{
Serial.println("M Butt Dn");
x = 90;
y = 90;
};

USB Usb;
USBHub Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE> HidMouse(&Usb);

uint32_t next_time;

MouseRptParser Prs;

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

Wire.begin();       //Begins I2C communication at pin (A4,A5)

Serial.begin(115200);
#if !defined(__MIPSEL__)
while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
Serial.println("Start");

if (Usb.Init() == -1)
Serial.println("OSC did not start.");

delay( 200 );

next_time = millis() + 5000;

HidMouse.SetReportParser(0, &Prs);
}

void loop()
{
Usb.Task();
Wire.beginTransmission(8);
Wire.write(x);
Wire.write(y);
//Wire.write(l);
//Wire.write(r);

Wire.endTransmission();
delay(10);

}

```

and the output is speed direction of x and y :

0
0
0
1
1
2
3
4
5
66
66
78
99
102
113
22
3
0
and this is the slave code :
```
#include<Wire.h>
int x,y,l,r;
#include <Mouse.h>                                                                               // Analog output of vertical joystick pin

void setup() {
Serial.begin( 115200 ); // start serial for output
Wire.begin(8);
Wire.onReceive(receiveEvent);
Mouse.begin(); //Init mouse emulation
}

void receiveEvent( int bytes )
{

x = Wire.read();
y = Wire.read();
//l = Wire.read();
//r = Wire.read();
delay(10);
}

void loop() {

Mouse.move(x, y, 0); // move mouse on y axis
delay(10);
}
```
anyone could help please i think the problem is i should ask the current position  and the next postion and if it was not zero move the mouse otherwise if it is 0 do not move

title: leonardo mouse readings

Answers: 0


body:
So I bought What I tought was a DOIT Wifi-TTL and after a few bad manipulations I wiped the firmware...
That means the leds are not turning on anymore and I see no activity on it when I connect to it with a USB-TTL...

The FCC ID on it says 2al3b-esp-m that seams to indicate a ESP-8285
(https://fccid.io/2AL3B-ESP-M/User-Manual/User-Manual-3413969)

I tried to flash it with Arduino ESP8285 samples and it flash right but I can't figure how / where I could retrieve the functionality that I had in the pas (login the the web server of it and interact with the TTL...

```
esptool.py v2.8
Serial port COM6
Connecting....
Chip is ESP8285
Features: WiFi, Embedded Flash
Crystal is 26MHz
MAC: 84:0d:8e:41:22:82
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 1MB
Compressed 280400 bytes to 205882...
Wrote 280400 bytes (205882 compressed) at 0x00000000 in 18.3 seconds (effective 122.7 kbit/s)...
Hash of data verified.

Leaving...
```

title: Trying to recover my TTL-Wifi

Answers: 0


body:
I have a Trinket M0 which has three pins capable of capacitive touch, A0, A3, and A4. When using CircuitPython on these boards you can use the [CapTouch](https://learn.adafruit.com/adafruit-trinket-m0-circuitpython-arduino/circuitpython-cap-touch-2) Library. But as far as I can tell this does not exist for use in Arduino mode. Does anyone know how to get these pins to pick up capacitive touch? I've tried the Adafruit_FreeTouch library, but with zero documentation, it's not very user friendly. I thought I had it working with two pins, but whenever both pins detect capacity, the capacity is divided between them, so both pins report about the same capacity.

Any help would be greatly appreciated.

This question does seem like a duplicated of https://arduino.stackexchange.com/questions/43663/built-in-capacitive-touch-detection-with-samd21-development-board-arduino-zero but there was never a solution.

Thanks!

title: How to use capactive touch on Adafruit board in Arduino mode?

Answers: 1

body:
Example code for capacitive touch on Trinket M0.  Note: make sure to install the Adafruit FreeTouch library.

    // touch - Capacitive touch demo using FreeTouch. Trinket M0 version.
    // Note: the pin silkscreened 1 is Analog Pin 0.

    #include "Adafruit_FreeTouch.h"

    Adafruit_FreeTouch qt_1 = Adafruit_FreeTouch(A0, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);

    void setup()
    {
      // Initialize A0 as a touch sensor
      if (! qt_1.begin())
        Serial.println("Failed to begin qt on pin A0");
    }

    void loop()
    {
      int counter, result = 0;
      counter = millis();
      result = qt_1.measure();
      Serial.print("QT 1: "); Serial.print(result);
      Serial.print(" (");  Serial.print(millis() - counter); Serial.println(" ms)");
      Serial.println("\n*************************************");
      delay(200);
    }

Information about the parameters for the constructor can be found at: https://forums.adafruit.com/viewtopic.php?f=8&p=610501  and are paraphrased below incase the link goes dead.

The parameters for the constructor are:

p - The input pin connected to the sensor.

t - How much to oversample the input.  One of the following:

    OVERSAMPLE_1
    OVERSAMPLE_2
    OVERSAMPLE_4
    OVERSAMPLE_8
    OVERSAMPLE_16
    OVERSAMPLE_32
    OVERSAMPLE_64

Oversampling is a process of taking several measurements, finding the average, and reporting that instead of the actual readings. It's way of reducing noise, but also improves the accuracy of the measurement. The average value of noise is zero (if it wasn't, it would be a source of free energy), so the more readings you add together, the closer the noise error in the measurements approaches zero.

There's another side-effect of adding noise to measurements though: it dithers the sensor output around the real input value. If I have a window comparator that only measures "below 1v" and "above 2v", and feed it a signal at 1.1v plus a couple of volts of noise, I can expect to see about ten "below 1v" outputs for every one "above 2v" output. The noise pushes the signals above and below the thresholds, but vanishes if I take the average of a large enough sample. Statistically, getting a 10:1 improvement in resolution like that would take about 64 readings to make the noise error small enough to ignore.

Oversampling takes longer though, so there's always a tradeoff between how much you can do and how long the signal will remain stable.

r - The value of the resistor that will discharge the touch pad.  One of the following:

    RESISTOR_0
    RESISTOR_20K
    RESISTOR_50K
    RESISTOR_100K

f - Frequency mode.  One of the following:

    FREQ_MODE_NONE
    FREQ_MODE_HOP
    FREQ_MODE_SPREAD
    FREQ_MODE_SPREAD_MEDIAN

For systems that take repeated measurements, there's one kind of noise that doesn't average to zero: noise that occurs at the same frequency as the sampling rate. There are all sorts of videos that show the effect of a camera being in sync with the thing it's recording.. this one is especially nice:   https://www.youtube.com/watch?v=uENITui5_jU

For capacitive sensors, things like induced signal from fluorescent lights can create noise, and if the lamp frequency is just slightly off of your sampling frequency, the touch system will think it looks like a series of touches.

(If you have an oscilloscope, hold the tip of a probe between your fingers and put your hand within a foot or so of a fluorescent light.)

One way to prevent that is to change the sampling frequency. You can shift it up and down in a predictable pattern, hop from one frequency to another, or add some random jitter. Atmel's QTouch library supports all those options, but 'NONE' (fixed frequency readings) is the simplest.


body:
I have made a simple circuit having an IR receiver and a Servo motor. Here is the diagram:

[![arduino circuit][1]][1]

Red wire: power

Black wire: ground

Orange wire: digital signal

And here's the code:
```
#include <Servo.h>
#include <IRremote.h>
int receiver = 13;
IRrecv irrecv(receiver);
decode_results results;
Servo myServo;
int pos = 0;
void setup() {
  // put your setup code here, to run once:
  myServo.attach(9);
  Serial.begin(9600);
  irrecv.enableIRIn();
  myServo.write(0);
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (irrecv.decode(&results)){

    if (results.value== 0xC0000C){
      for (pos = 0; pos <= 90; pos += 10) {
        // in steps of 1 degree
        myServo.write(pos);
        delay(15);
      }
      for (pos = 90; pos >= 0; pos -= 10) {
        myServo.write(pos);
        delay(15);
      }
    }
  }
  irrecv.resume();
  delay(100);
}
```
It rotates the motor 90 degree and back when a button on a remote is clicked.

Here comes the problem: This is working perfectly when connected to my PC, but it doesn't when I connect it with my 9-volt (cuboid shaped) battery. The lights on the Arduino board still light up, but the circuit does nothing when I press the remote button.

I have also observed that the servo vibrates a little bit, but doesn't move.

Is this a problem in my circuit, or is it just that my battery power is low?

[1]: https://i.stack.imgur.com/bPCPN.png

title: Circuit not working with 9 volt battery

Answers: 1

body:
A 9V battery has both low peak current and low total power (low mAh rating). It is not a good choice for any circuit that draws more than ≈100 mA. (I pulled that number out of thin air, but it's probably a decent guess)

Build a battery pack from 6 AA alkaline cells instead. That will provide enough peak current. Or for much longer run-time, use 6 D sized cells.


body:
I had been trying to make Arduino Fire Fighter Robot but facing several problems in interfacing 3 flame sensors and servo together. When I upload the following code( Which I had posted at the end of my writing) my robot goes backward and detects flame at the front sensor and displays " Flame on Front" on 16x2 LCD display and the 5v  pump pumps out water and the red LED blinks. But I want that my robot will work in the following way- Initially, my robot will be at rest. There are 3 sensors attached at the front part of the robot. And there is a SG90 servo for rotating the water tank( in this tank there is a 5v pump motor and the pump motor will pump out water from this tank). When any one of the three flame sensors  will detect flame then the servo will rotate in that direction and when the front flame sensor detects fire , the servo will be in 90-degree angle and water will be pumped out. LCD will display the status of the flame sensors. But the robot is not working properly. I am not able to interface 3 flame sensors and servo together. My robot is not working according to my expectation as I had said before.

    int pos = 0;
    boolean fire = false;

    #include <LiquidCrystal.h>
    int Contrast=20;// for adjusting the brightness of the LCD , 20 is selected for the contrast of LCD
    LiquidCrystal lcd(30,31,32,33,34,35);
    int buzz= 38; //for led or buzzer
    #define Left_S 9 // left sensor
    #define Right_S 8     // right sensor
    #define Forward_S 23  //forward sensor
    #define LM1 52 //for pump motor
    #define LM2 53 //for pump motor
    #define IN1 5   //for motor
    #define IN2 4  // for motor
    #define IN3 3      //for motor
    #define IN4 22     // for motor
    //int flame_pin1 = HIGH ;
    int LEDR= 36; // for danger signal
    int LEDB=37;// for safe signal

    void setup ( )  {
       analogWrite(6,Contrast);
         lcd.begin(16, 2);
          pinMode(Left_S, INPUT);
      pinMode(Left_S, INPUT);
      pinMode(Right_S, INPUT);
         pinMode (Forward_S,OUTPUT);
         pinMode (LEDB,OUTPUT);
     pinMode(LM1, OUTPUT);
     pinMode(LM2, OUTPUT);
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(IN3, OUTPUT);
      pinMode(IN4, OUTPUT);
      pinMode( buzz,OUTPUT );
      pinMode(LEDR,OUTPUT);
      pinMode(LEDB, OUTPUT);
     // pinMode ( flame_sensor_pinM , INPUT );
      //Serial.begin ( 9600 );
       myservo.attach(25);
      myservo.write(90);
    }
     void put_off_fire()
    {
        delay (500);

        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, HIGH);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, HIGH);

       digitalWrite(LM1, HIGH);
       digitalWrite(LM2, LOW);
       delay(500);

        for (pos = 50; pos <= 130; pos += 1) {
        myservo.write(pos);
        delay(10);
      }
      for (pos = 130; pos >= 50; pos -= 1) {
        myservo.write(pos);
        delay(10);
      }

      digitalWrite(LM1,LOW);
      digitalWrite(LM2,LOW);
      myservo.write(90);

      fire=false;
    }

    void loop ( ){
       myservo.write(90); //Sweep_Servo();

        if (digitalRead(Left_S) ==1 && digitalRead(Right_S)==1 && digitalRead(Forward_S) ==1) //If Fire not detected all sensors are zero
        {
        //Do not move the robot
        lcd.setCursor(0, 1);
          lcd.print("No flame");
        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, HIGH);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, HIGH);
        digitalWrite(LEDR,LOW);
        digitalWrite(LEDB,HIGH);
        digitalWrite(buzz,LOW);
        }

        else if (digitalRead(Left_S) ==0) //If Fire is straight ahead
        {
        //Move the robot forward
        lcd.setCursor(0, 1);
          lcd.print("Flame on Left");
        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, LOW);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN2, LOW);
        digitalWrite(LEDR,HIGH);
        digitalWrite(LEDB,LOW);
        digitalWrite(buzz,HIGH);
        fire = true;

        }
        else if (digitalRead(Forward_S) ==0) //If Fire is straight ahead
        {
        //Move the robot forward
        lcd.setCursor(0, 1);
          lcd.print("Flame on front");
        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, LOW);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN2, LOW);
        digitalWrite(LEDR,HIGH);
        digitalWrite(LEDB,LOW);
        digitalWrite(buzz,HIGH);
        fire = true;

        }

        else if (digitalRead(Right_S) ==0) //If Fire is to the right
        {
        //Move the robot right
        lcd.setCursor(0, 1);
          lcd.print("Flame on Right");
        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, HIGH);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, LOW);
        digitalWrite(LEDR,HIGH);
        digitalWrite(LEDB,LOW);
        digitalWrite(buzz,HIGH);
        fire= true;
        }

         delay(300); //Slow down the speed of robot

         while (fire == true)
         {
          put_off_fire();
         }
    }

title: Problem on interfacing 3 flame sensors and servo to Arduino Fire Fighter

Answers: 1

body:
If you format your code correctly, the code becomes less cluttered and the problem becomes more visible.

Also, if you think about the `if` statements, there is no need to check for `no fire` for all three sensors at the same time. If none of the three sensors see fire, then the only possibility that is left, is `no fire`.

Another thing, you have no `digitalWrite(IN1, LOW);` and no `digitalWrite(IN3, LOW);` in your code. You could put `digitalWrite(IN1, HIGH);` and `digitalWrite(IN3, HIGH);` in `setup()`

Here is your code rewritten and formatted.

Couple of unnecessary duplications are tagged.

There is no reason to use `while (fire == true)` because `put_off_fire()` clears the `fire` flag

Also, for future programs, `while (fire == true)` is a redundant form because it is same as `while (fire)`

Have a really close look at the `if` statement blocks.

You used copy&paste when writing the code, but you forgot to make changes.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(30, 31, 32, 33, 34, 35);

    #define Left_S       9                       // left    sensor
    #define Right_S      8                       // right   sensor
    #define Forward_S   23                       // forward sensor

    #define LM1         52                       // for pump motor
    #define LM2         53                       // for pump motor

    #define IN1          5                       // for motor
    #define IN2          4                       // for motor
    #define IN3          3                       // for motor
    #define IN4         22                       // for motor

    //int flame_pin1 = HIGH ;

    int LEDR     = 36;                           // for danger signal
    int LEDB     = 37;                           // for safe signal
    int buzz     = 38;                           // for led or buzzer
    int pos      =  0;
    int Contrast = 20;                           // for adjusting the brightness of the LCD , 20 is selected for the contrast of LCD

    boolean fire = false;

    void setup() {

        analogWrite(6, Contrast);

        lcd.begin(16, 2);

        pinMode( Left_S            , INPUT  );
        pinMode( Left_S            , INPUT  );
        pinMode( Right_S           , INPUT  );

        pinMode( Forward_S         , OUTPUT );
        pinMode( LEDB              , OUTPUT );   // xxxxxxxxxxxxx        duplicate

        pinMode( LM1               , OUTPUT );
        pinMode( LM2               , OUTPUT );

        pinMode( IN1               , OUTPUT );
        pinMode( IN2               , OUTPUT );
        pinMode( IN3               , OUTPUT );
        pinMode( IN4               , OUTPUT );

        pinMode( buzz              , OUTPUT );

        pinMode( LEDR              , OUTPUT );
        pinMode( LEDB              , OUTPUT );   // xxxxxxxxxxxxx        duplicate

    //  pinMode( flame_sensor_pinM , INPUT  );

    //  Serial.begin ( 9600 );

        myservo.attach(25);
        myservo.write(90);
    }

    void put_off_fire() {

        delay (500);

        digitalWrite(IN1, HIGH);
        digitalWrite(IN2, HIGH);
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, HIGH);

        digitalWrite(LM1, HIGH);
        digitalWrite(LM2, LOW );
        delay(500);

        for (pos = 50; pos <= 130; pos += 1) {
            myservo.write(pos);
            delay(10);
        }

        for (pos = 130; pos >= 50; pos -= 1) {
            myservo.write(pos);
            delay(10);
        }

        digitalWrite(LM1, LOW);
        digitalWrite(LM2, LOW);

        myservo.write(90);                       // xxxxxxxxxxxxx        duplicate

        fire = false;                            // xxxxxxxxxxxxx        not needed
    }

    void loop() {

        myservo.write(90);                       // xxxxxxxxxxxxx        duplicate
    //  Sweep_Servo();

        lcd.setCursor(0, 1);

        fire = true;                             // preset the state (gets cleared when no fire is detected

        if (digitalRead(Left_S) == 0) {          // If Fire is straight ahead

            lcd.print("Flame on Left");

            digitalWrite(IN1 , HIGH);            // Move the robot forward
            digitalWrite(IN2 , LOW );
            digitalWrite(IN3 , HIGH);
            digitalWrite(IN2 , LOW );
        }

        else if (digitalRead(Forward_S) == 0) {  // If Fire is straight ahead

            lcd.print("Flame on front");

            digitalWrite(IN1 , HIGH);            // Move the robot forward
            digitalWrite(IN2 , LOW );
            digitalWrite(IN3 , HIGH);
            digitalWrite(IN2 , LOW );
        }

        else if (digitalRead(Right_S) == 0) {    // If Fire is to the right

            lcd.print("Flame on Right");

            digitalWrite(IN1 , HIGH);            // Move the robot right
            digitalWrite(IN2 , HIGH);
            digitalWrite(IN3 , HIGH);
            digitalWrite(IN4 , LOW );
        }

        else {                                   // fire was not detected by any of the sensors

            fire = false;

            lcd.print("No flame");

            digitalWrite(IN1 , HIGH);            // Do not move the robot
            digitalWrite(IN2 , HIGH);
            digitalWrite(IN3 , HIGH);
            digitalWrite(IN4 , HIGH);
        }

        delay(300);                              // Slow down the speed of robot

        if (fire) {

            digitalWrite(LEDR, HIGH);            // do fire lights
            digitalWrite(LEDB, LOW);
            digitalWrite(buzz, HIGH);

            put_off_fire();
        }

        else {

            digitalWrite(LEDR, LOW );            // do nofire lights
            digitalWrite(LEDB, HIGH);
            digitalWrite(buzz, LOW );

        }
    }


body:
i have a dragino lg01-p lora gateway to which i successfully communivate through lora with an arduino and i can program it through network as expected and seen in its manual with the demo client-server code. However, when i try to open the serial monitor on the side of the dragino, i get this:

Unable to connect: retrying (1)...

Unable to connect: retrying (2)...

Unable to connect: retrying (3)...

Unable to connect: retrying (4)...

Unable to connect: is the sketch using the bridge?

I need to have the serial communication cause i made a little app in C# which gets the data from a COM port. I also tried with Console instead of serial, but still didn't get any results back. This is the code, exactly as is in the examples no the manual

```
#include <SPI.h>
#include <RH_RF95.h>

// Singleton instance of the radio driver
RH_RF95 rf95;

int led = A2;
float frequency = 868.0;

void setup()
{
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  Serial.println("Start Sketch");
  if (!rf95.init())
    Serial.println("init failed");
  // Setup ISM frequency
  rf95.setFrequency(frequency);
  // Setup Power,dBm
  rf95.setTxPower(13);
  // Defaults BW Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
  Serial.print("Listening on frequency: ");
  Serial.println(frequency);
}

void loop()
{
  if (rf95.available())
  {
    // Should be a message for us now
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);
    if (rf95.recv(buf, &len))
    {
      digitalWrite(led, HIGH);
      RH_RF95::printBuffer("request: ", buf, len);
      Serial.print("got request: ");
      Serial.println((char*)buf);
      Serial.print("RSSI: ");
      Serial.println(rf95.lastRssi(), DEC);

      // Send a reply
      uint8_t data[] = "And hello back to you";
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent a reply");
      digitalWrite(led, LOW);
    }
    else
    {
      Serial.println("recv failed");
    }
  }
}
```

title: Dragino lg01-p problem with serial monitor

Answers: 1

body:
Found it so i will share my problem here to help someone else!

Apparently ```Bridge``` funcions work better for this device if you include ```Process.h``` rather than ```Bridge.h```.


body:
So I wanna build something which, when it receives a remote signal, presses the spacebar on my laptop keyboard. I tried using the Keyboard.press() but it is available only for Leonardo. Is there any way I can use it in my Uno, without having to mess with the firmware?

If not, what else can I use to accomplish my goal?

title: How can I make my Arduino Uno press Space on my laptop keyboard?

Answers: 2

body:
if you have some knowledge in Java or Python you can interface your Arduino board to PC, through Arduino's SerialPort.
When Arduino sends a byte, for example, 0xAB, your Java or Python script sends a fake key-press event.
I hope this can help. Good luck!

body:
On Windows you can use a serial to keyboard redirector like [this one][1]

It can start with windows, Im using it for a long time without any issues.
[![enter image description here][2]][2]

  [1]: http://www.priority1design.com.au/datasnip.html
  [2]: https://i.stack.imgur.com/I8YhV.png


body:
I am trying to setup waveshare 7.5 display (Waveshare_7_5) with esp32 e-paper driver using [ESP32-e-Paper-Weather-Display][1]

My code is here https://pastebin.com/raw/2zQDe9a9, have corresponding `owm_credentials.h`, installed `GxEPD2` & `U8g2_for_Adafruit_GFX`

Code gets uploaded to esp32 driver board using Arduino IDE, but Getting following in serial monitor & no display on e-paper

    Busy Timeout!
    Busy Timeout!
    Busy Timeout!
    Busy Timeout!
    Entering 1675-secs of sleep time
    Awake for : 44.518-secs
    Starting deep-sleep period...

What is wrong here ?

  [1]: https://github.com/G6EJD/ESP32-e-Paper-Weather-Display

title: esp32 e-paper driver not working

Answers: 0


body:
Facing an issue while writing a large value *(like 2000-5000)* to EEPROM using `EEPROM.put().`

For example, While writing 2000 values to address 5 of EEPROM. Some junk values are written automatically to a nearby address (address 4, 6, 7...).

*Note : Not trying to write an array of 2000 elements*

Board Used : Arduino Uno (Atmega328P)

Q1 : What is the typical range of a each address by using `EEPROM.put()` . Like `EEPROM.write()` has range limit of 0-255.

Q2 : How to write large value EEPROM addresses without effecting the nearby address.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/QVF7b.jpg

title: Junk values in EEPROM. while writing large values

Answers: 1

body:
It depends on what type of variable you have.  If you have single byte variables like byte or char then it is one value to one address.  But if you have an int value like:

    int x = 2000;

then try to store that in EEPROM that will take 2 bytes because an int is 2 bytes in size.  So if you write that to address 5 it will take 5 and 6 to write it.

If you write a long or a float, they are 4 bytes, so they will take 4 address slots in the EEPROM each.

If you just write EEPROM.put(5, 2000); then the 2000 gets seen as either int or long depending on how the code is written.  I don't remember.  But you certainly can't fit 2000 into a byte so it's going to have to take more than one.


body: My friends Uno went in washer. I gave it a week to dry and when i plug it in, it works. But when I shake I hear something shaking around inside it. What do I hear shaking around?

title: Uno went in washer and when I shake I hear something shaking around. What do I hear?

Answers: 1

body: It could be the USB port, barrel jack port, or most likely the pin header. The pin headers are a plastic shell with a two-point prong thing that goes in it. the pin could have desoldered when in the washer. check the pin headers. It might also be the inside of capacitors but that is highly unlikely.


body: How do you use Atmega328p-PU from an Uno, on a breadboard without a crystal?

title: How to use Atmega328p-PU from an Uno, on a breadboard without a crystal

Answers: 2

body: You can use another IC like the 555 timers as an external oscillator.

body:
If you buy your ATmega as supplied by Microchip, through one of the
large electronic parts resellers, it will come with its default fuse
configuration:

* clock source: internal 8 MHz RC oscillator
* clock prescaler enabled at ÷8, yielding a 1 MHz system clock
* bootloader disabled

You could use it in this configuration, but you will probably want to
disable the prescaler. This can be done by changing the right fuse or,
alternatively, by some code running early in `setup()`. Note that, with
no bootloader, you will need an ISP programmer in order to load the
code. If you want the convenience of serial downloading (i.e. you would
use an FTDI cable rather than an ISP programmer), you will have to burn
the bootloader using an ISP programmer, and adjust the fuses to enable
it and set its size.

If you take the ATmega from an existing Uno board, or buy one
preconfigured with the bootloader, the fuses will be set differently:

* clock source: external crystal
* clock prescaler disabled
* bootloader enabled and sized to 0.5 KiB

In this case you will have to change the clock source.

In any case, you would tell the IDE you are using an Arduino Fio, or a
Pro or Pro Mini with a 328P clocked at 8 MHz. And you will need an
ISP programmer to load either your program or the bootloader. You could
use an Arduino running the “Arduino as ISP” firmware for this.

Check the datasheet for the details on configuring the fuses. You can
also use one of the online fuse calculators, like [this one][1] or [this
one][2].

[1]: https://www.engbedded.com/fusecalc
[2]: https://eleccelerator.com/fusecalc/


body:
It would be kind of push notification or something like that probably.
I can first connect to server and send it any data for "registration"...

I found many examples with websockets but all of them was about ESP8266 is like "server". That's not this case...

title: Is it possible to send data from internet server to ESP8266 behind proxy or regular requests from ESP8266 are required?

Answers: 1

body:
It seems evident that you don't want your ESP8266 running as a server of any kind. That's understandable given that server programs consume a fair amount of system resources (CPU, RAM, etc.) that are in short supply. That means you'll have to use your ESP8266 as a **client** and this means either

1) **Polling** - where the ESP8266 repeatedly connects to your "internet server" to explicitly ask for information at frequent intervals. Your internet server would have to be able to collect information in batches and hang onto it until your ESP8266 connects again to request the information.

2) **Socket connections** - where your ESP8266 maintains a consistent [socket connection](https://en.wikipedia.org/wiki/Network_socket) to your "internet server." Note that the HTTP protocol relies on socket connections, but clients open a socket connection, request a web page and its images, CSS, etc., then disconnects the socket. You can also use sockets at a more basic level as a bytestream. This programming can be tricky, but ESP8266 does have examples of TCP socket communication like [WiFiClient](https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino) and [ethernet client](https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/examples/TelnetClient/TelnetClient.ino).

Client approaches have a variety of headaches:
* server has to hang on to information until the client comes back to retrieve it
* you have to work up some kind of data structure to track which information has been handled and which work must still be done
* latency issues -- i.e., what happens when there's a delay in processing information.

Server approaches also have challenges:
* server programs can be tricky to write so that they keep running. a single exception or fatal error can crash the program
* server programs are vulnerable to DDoS or other attacks, and can easily overwhelm a small device like ESP8266
* firewall and networking issues -- depending on how this device connects to the internet, it may or may not have a consistent IP address where it can be found, the ISP that connects it may not allow incoming connections for the ports that it listens on, etc.


body:
I am a Computer Engineering Undergrad, currently in a cryptography(computer security) course, and I was assigned to do projects about implementing µNaCl library onto Arduino. I currently own a nodemcu esp32 which serves as my device, and I have been searching for µNaCl libraries on the web, but the only thing I found was µNaCl library for AVR devices (based on the makefile of the library, i can see that it's designed for atmega128 and atmega2560). So my question is, is it possible to implement some library meant for AVR on my nodemcu? I mostly do my job with arduino libraries, and have never experimented with avr libraries on arduino, and especially considering my nodemcu is not using atmega-based architecture either, I kinda doubted it. And is the solution to my problem (if it's not possible to use avr based library on arduino) to go purchase a atmega128/atmega2560 and code on atmel studio?

Library: https://munacl.cryptojedi.org/atmega.shtml

Sorry for the long question, kinda desperate here.

title: Is it possible to implement old AVR library onto arduino (specifically, NodeMCU esp8266)

Answers: 0


body:
I have just about completed my first Arduino project using an Arduino Uno board, but is that what I use inside the finished device? I figured I’d keep the Uno for future projects and have something else controlling the finished product. Are you supposed to just keep purchasing the Uno board every project?

I just got it a couple of days ago so I’m not very familiar with any of it. If that is the case do you use the batter for power since I can’t have it connected to my laptop once it’s done.

title: What do you do when you finish a project?

Answers: 2

body:
What you can do is:

- Buy the main IC (Atmel 328P)
- Use some external components to get it working (like a crystal). Check this on a breadboard to see if it works (and check.
- Buy a case to put it in
- Buy some protoboard or PCB to solder it on (or use a footprint)
- For power, use some components (voltage regulator) or an adapter, or battery, whatever you need. Make sure you check this on a breadboard before you solder it.

If you want to read more about the subject, search for 'prototyping'.

body:
There are many options, so it all ends up depending on your personal
preferences:

* You could indeed dedicate this Arduino to this project, and buy a new
  one for the next project. This may be the simplest solution, if not
  the cheapest. Just make sure you are not using a breadboard for the
  other parts. A “proto-shield” may be a good option for soldering the
  rest of your circuit in a permanent form.

* You may replace the Uno with a smaller Arduino, like the Micro (but
  beware it uses a different MCU) or a Pro Mini clone (same MCU). These
  smaller boards can then be soldered onto a PCB using standard 0.1” pin
  headers.

* You could buy a cheap clone, test it to make sure it works as intended
  on this particular project, and dedicate the real one for further
  prototyping.

* You could get a bare ATmega328P plus crystal and caps and put them,
  together with the rest of your circuit, onto a perf-board or a
  strip-board. C.f. Michel Keijzers’ answer. Note that if your program
  can run happily off a somewhat inaccurate 8 MHz clock, you can
  use the MCU's internal oscillator instead of a crystal.

* If your program is far from using all the resources of the Uno, you
  may consider a smaller MCU. The ATtiny85 is a popular “minimalistic”
  choice. Make sure an Arduino core is available for it, unless you want
  to program all low-level.

* For the most professional result, you could design and order a real
  PCB for your whole circuit, including the MCU.


body:
From this [tutorial][1]  I'm able to nicely program an ATmega328 using SPI raspberry GPIO pins. However, when I try the same steps with  ATmega4809, `avrdude` seems not having instructions and outputs the following:

    program enable instruction not defined for part "ATmega4809"

So, how do I program ATmega4809 chip from Raspberry?

  [1]: https://learn.adafruit.com/program-an-avr-or-arduino-using-raspberry-pi-gpio-pins

title: How to program ATmega4809 from Raspbeery GPIO

Answers: 1

body:
The ATMega4809 uses UPDI (Unified Programming and Debugging Interface) for programming, not ICSP like the older ATMega328P. You need a UPDI programmer.

There is a project [jtag2updi](https://github.com/ElTangas/jtag2updi) which you can run on an Uno that turns it into a JTAG to UPDI adaptor which is then compatible with `avrdude -c jtag2updi ...`.


body:
hello guys i want to ask about 2 things
first one is i'm connecting and arduino uno attached to a usb host sheild and transferring data of a mouse coordinates to 10 arduino leonardo
i'm using the standard speed 100
normal mode
my wires is all about 10 cm long
1) i need to speed up the comm to fast mode
how to make this ? and the line of code where to put it in the code and in the master or slave ?

2) what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ? does it needs to disable it and put my own pull up resistors ?
i’m using wire library

title: i2c high speed and pull-up resistors

Answers: 1

body:
> i need to speed up the comm to fast mode how to make this

```
Wire.setClock(400000);
```

> and the line of code where to put it in the code

Just after `Wire.begin()` in `setup()`.  `Wire.begin()` sets the speed to 100,000 and you need to then override that afterwards to set it to 400,000 (or whatever speed you want to run at).

> and in the master or slave ?

In the master, since it's the master that generates the clock.

> what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ?

Yes, but they're too high for reliable I2C operation. You should add your own resistors in the region of 1kΩ.

> does it needs to disable it and put my own pull up resistors ?

No, yours will just be in parallel with them, with the net result of a small reduction of overall resistance.


body:
i have a small project where i just sucessfully destroyed my frist of 5 Digisparks (Attiny85).
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/SEG3m.jpg
In the Picture you see the Cirucit. I have 2 Liion cells connected in series to get high enough voltage to step it down to constant 5V. To these 5V some Neopixels and a Digispark controller are connected which will set the color for the Neopixels. A0 and A1 measure the Voltage of the Cells to signal the user if the Voltage is to low so it can manually be switched of.
While prototyping it i didnt have the 10k resistors in there.

Now what happend: While connecting the cells after each other the Controllers LEDs already lit up with the Frist cell. I guess it was powered trough the A0 pin (again i didnt have the 10k resistor in there),  so i guess the internal IO Protection diodes conductet the voltage trough and this way the controller got damanged. Since this happend it wont turn on Anymore.

The problem: since i have really small space i cant use a multiple pole switch to also remove the voltage from the IO pins and therefore i will always have voltage von A0 and A1 while there is no 5V Supplyvoltage. I would guess that the Series resistance on the pin would be enough to Limit the current trough them and this way protect the controller from damange. But i dont really have experience with that and hope that you guys can give me some hints what could also be a problem or what could help :) I really dont want to destroy a second one xD

Thanks in advance and have a nice day :)

title: Continuous voltage on IO Pins while 5V is not Connected?

Answers: 3

body:
As a general rule, you should not apply a higher voltage to the logic pins of digital ICs than you do to their power pin. This means that if you disconnect power, you must also shut off voltage to the logic pins.

Failure to follow that rule will often destroy an IC.

I don't know about the specifics of the inputs on your DigiSpark. 10K resistors will certainly lower the current that is able to flow into those pins, but you would still be breaking the "don't put more voltage into an input pin than you put into the VIN pin" rule.

body:
For this I would recommend isolating the power from the batteries with P-channel MOSFETs and only switching them on when you want to sample the voltage. This means that there is no power consumption at all (aside from an absolutely minuscule leakage current) when turned off.

The whole setup would require 4 MOSFETs - two P-channel and two N-channel. They don't need to be big, since the currents involved are very small, but they do need to have "logic level" thresholds, ideally < 1.5V (-1.5V for the P-channel).

The basic circuit looks like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/hHWrO.png)

<!-- End schematic -->

The circuit is made up of two identical segments - M1+M3 and M2+M4.  The operation is fairly straightforward:

* M1 (M2) is kept in the OFF state by R1 (R2) pulling the gate up to source.
* M3 (M4) can pull the gate of M1 (M2) LOW turning it on and allowing current to flow
* Any GPIO pin (D7 in this example) can control both M3 and M4 together
* R5 keeps M3 (M4) off when there is no power - otherwise it floats.
* R3/R4 are your existing voltage divider.

The purpose of M3 and M4 is to both turn the GPIO (D7) into "open drain" so that it's either pulling down or floating high (rather than driving high at 5V) and to isolate the two pullup gate voltages. The same effect could be achieved by two diodes and one MOSFET but it's simpler to just use two MOSFETs and not have to get diodes as well.

body:
If all you are doing with A0/A1 is 'signalling the user that the voltage is too low for continued operation', then consider the following:

 - remove the lead from the top of the lower battery entirely
 - instead of the 1/1 voltage divider, use something like 10/1 (i.e. a 680K on top and a 68K on the bottom to provide a large series resistance (making the steady-state current drain on the battery negligible).  This will also put the nominal full-charge voltage as measured at the ADC input well within the DC voltage range of the Digispark at a small cost in accuracy.  The specs for the ATiny85 ADC input impedance is something like 100 MegOhms, so the accuracy drop from using a 680K series resistor shouldn't be more than a few percent.  Use a variable power supply to calibrate the A/D setup so your controller will alert the user when the battery stack gets low.  If you don't have a variable power supply, consider something like [this][1]

Frank

  [1]: https://www.fpaynter.com/2020/06/lab-power-supply/


body:
I'm so confused by the ADS2750 [datasheet][1] here, I can't seem to figure the proper bit shift to read data from bits 15-27 properly. I'm not even sure what some of the acronyms mean on page 23 table 1. I get that the first 15 bits are empty while the ADC takes a reading and then the last 12 bits for the 12 bit ADC are the value from that ADC that matches the SPI A or B input. Would someone be willing to explain to me how you would read data based on this datasheet using information from table 2 page 24?

My hardware set up to ADC7250
VCC 5 Volts

 - D5 SS fro Both SPI & SPI1
 - D13 SCK for Both SPI & SPI1
 - D11 MISO SPI_A from ADC
 - D4 MISO SPI_B from ADC
 - No MOSI connected

I'm not sure what to send in the `SPI.Transfer(0x00)`. I'm also not sure if I'm setting up the modes properly, `SPISettings settings(24*MHZ, MSBFIRST, SPI_MODE1);` as I not 100% on the clock speed. I also I'm confused if this is LSB or MSB as the datasheet has two conflicting notes, the transfer function used LSB and then two paragraphs say "MSBs of ADC_A and ADC_B are output"

I'd love some help decoding this data sheet and getting a script that can read data from this chip using both SPI and SPI1 simultaneously.

Working on only reading SPI first the will add SPI1.

    unsigned int readRegister(byte thisRegister, int bytesToRead);

    const int CS_ADC_ISOLATOR = D5;
    __SPISettings settings(24*MHZ, MSBFIRST, SPI_MODE0);
    const int buffersize = 30;
    unsigned char dataBuffer [buffersize];
    const byte READ = 0x22;

    // setup() runs once, when the device is first turned on.
    void setup() {
      Serial.begin(115200);
      pinMode (CS_ADC_ISOLATOR, OUTPUT);
      digitalWrite (CS_ADC_ISOLATOR, HIGH);
      SPI.begin();
      SPI1.begin();
    }

    // loop() runs over and over again, as quickly as it can execute.
    void loop() {
        digitalWrite (CS_ADC_ISOLATOR, LOW);
        SPI.beginTransaction(settings);
        for(unsigned char i = 0; i < buffersize; i ++)
        {
            dataBuffer[i] = SPI.transfer(0x00 << 14);
        }
        digitalWrite (CS_ADC_ISOLATOR, HIGH);
        SPI.endTransaction();
        for(unsigned char n = 0; n < buffersize; n ++)
        {
            Serial.print(dataBuffer[n]);
        }
        Serial.print("::");
    }

  [1]: https://www.ti.com/lit/ds/symlink/ads7250.pdf?ts=1593499080691&ref_url=https%3A%2F%2Fwww.ti.com%2Fproduct%2FADS7250%3Fdcmp%3Ddsproject%26hqs%3Dsw%26

title: TI ADS7250 Read From SPI and SPI1 Simultaneously

Answers: 1

body:
You can't use the normal SPI library for communicating with this device properly. Well, you *can*, but you will only be able to use one channel - the other will be completely ignored.

SPI only works on one MISO pin - you need two.  There are two other types of "SPI" that are used by devices, most notably SPI flash chips: DSPI and QSPI (dual SPI and quad SPI). You want DSPI.

Unfortunately the Arduino doesn't do DSPI, so you will have to "bit bang" it, which means manually manipulating the IO pins to create your own SPI signals in software.

Now... on to the datasheet:

The important part is the timing diagram on page 9. From that you can see that you just send 32 clock pulses and the chip responds, after 15 pulses, with the data.

So if you just do 4 8-bit transfers back-to-back then you get the data. It doesn't matter what you "send" in those transfers since the MOSI pin isn't connected to anything.

As far as speed goes, 24MHz is the *maximum* speed that it will run at. The actual speed is dictated by the Arduino and how fast you manipulate the SCK pin. That can be as slow as 1x10<sup>-1000</sup>Hz if you really want.

Data should be read on the falling edge of SCK.

So you could write a little routine that looks like:

```
uint32_t resa = 0;
uint32_t resb = 0;

pinMode(SCK, OUTPUT);
pinMode(SDI_A, INPUT);
pinMode(SDI_B, INPUT);
pinMode(CS, OUTPUT);
digitalWrite (CS, HIGH);

digitalWrite (CS, LOW);
for (int i = 0; i < 32; i++) {
    digitalWrite(SCK, HIGH);
    digitalWrite(SCK, LOW);
    resa <<= 1;
    resb <<= 1;
    resa |= digitalRead(SDI_A);
    resb |= digitalRead(SDI_B);
}
digitalWrite (CS, HIGH);

Serial.print("A: "); Serial.println(resa);
Serial.print("B: "); Serial.println(resb);
```

So for 32 iterations you pulse the clock HIGH then LOW, then shift each result 1 bit to the left, and then add in the newly read bit into the lowest bit position.

You could speed up operation by using [direct port manipulation](https://www.arduino.cc/en/Reference/PortManipulation) and avoiding the slow `digitalWrite()` and `digitalRead()` functions.