message:
Can I connect a DS3231 and an MPU6050?

Can I connect a DS3231 and an MPU6050 by an Arduino Mega 2560? I have connect it:

    MPU 6050               Arduino Mega 2560
    SDA           =        SDA
    SCL           =        SCL
    GND           =        GND
    VCC           =        5V

And I have connected DS3231 to SDA and SCL beside AREF pin:

    DS3231               Arduino Mega 2560
    SDA           =        SDA
    SCL           =        SCL
    GND           =        GND
    VCC           =        5V

The problem is when I connect both of them MPU6050 prints nan, after opening the DS3231 pin from the arduino, MPU6050 prints the correct angles.
Can someone please help me?

Code:

    #include "MPU6050.h"
    #include "Wire.h"
    #include <DS3231.h>
    MPU6050 accelgyro;
    int16_t ax, ay, az, gx, gy, gz;

    DS3231 rtc(SDA, SCL);

    double timeStep, time, timePrev;
    double arx, ary, arz, grx, gry, grz, gsx, gsy, gsz, rx, ry, rz;

    int i;
    double gyroScale = 131;

    void setup() {
      Wire.begin();
      accelgyro.initialize();
      Serial.begin(9600);
      rtc.begin();
    }

    void loop() {
      timePrev = time;
      time = millis();
      timeStep = (time - timePrev) / 1000;
      accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
      gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;
      arx = (180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
      ary = (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
      arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);
      if (i == 1) {
        grx = arx;
        gry = ary;
        grz = arz;
      }
      else{
        grx = grx + (timeStep * gsx);
        gry = gry + (timeStep * gsy);
        grz = grz + (timeStep * gsz);
      }
      rx = (0.1 * arx) + (0.9 * grx);
      ry = (0.1 * ary) + (0.9 * gry);
      rz = (0.1 * arz) + (0.9 * grz);
      Serial.print("X axis == ");
      Serial.println(arx);
      Serial.print("Y axis == ");
      Serial.println(ary);
      Serial.print("Z axis == ");
      Serial.println(arz);
      Serial.println(rtc.getTimeStr());
      i = i + 1;
      delay(1000);
    }

body:
The DS3231 library you are using works (for some bizarre reason) exclusively with its own internal bit-bang implementation of I2C. This cannot be used on the same pins as the hardware Wire library which the MPU6050 uses.

Either move the DS3231 to a different pair of pins, or find a better DS3231 library that uses the Wire library for communication.


sender: user

sender: assistant

body:
Yes. Using i2c, you need to change the address of the MPU6050 because the default is (0x68) which is also the default and only address the DS3231 can use.

Example of changing the address from a personal sketch:

MPU6050 mpu(0x69);

So try:

MPU6050 accelgyro(0x69);


message:
How to interface MPU9250 and NodeMcu?

I am trying to send MPU sensor data to Pubnub IOT platform but not able to do it since there is some unknown problem. There is no error in code but following issue pops up in com port:-

[![COM PORT Results][1]][1]

It looks like sensor reading needs to be in JSON Format but no sure how to do it. I Just need it in raw imu sensor reading for now so how do i get it.

Here is the code:

    #include <ESP8266WiFi.h>
    #define PubNub_BASE_CLIENT WiFiClient
    #include <PubNub.h>
    #define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
    #include "MPU9250.h"

    const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
    const char *pass =  "786110786";

    const char * pubkey = "my key";
    const char * subkey = "my key";

    const char * pubchannel = "demo_keyset";
    const char * subchannel = "demo_keyset";

    MPU9250 IMU(Wire,0x68);
    int status;

    void setup() {
        /* For debugging, set to speed of your choice */
        Serial.begin(115200);

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

           WiFi.begin(ssid, pass);
           while (WiFi.status() != WL_CONNECTED)
              {
                delay(500);
                Serial.print(".");
              }
          Serial.println("");
          Serial.println("WiFi connected");

        /* Start the Pubnub library by giving it a publish and subscribe
           keys */
        PubNub.begin(pubkey, subkey);

        while(!Serial) {}

      // start communication with IMU
      status = IMU.begin();
      if (status < 0) {
        Serial.println("IMU initialization unsuccessful");
        Serial.println("Check IMU wiring or try cycling power");
        Serial.print("Status: ");
        Serial.println(status);
        while(1) {}
      }
    }

    void loop() {
        // read the sensor
      IMU.readSensor();
      // display the data
      Serial.print(IMU.getAccelX_mss(),6);
      Serial.print("\t");

        /* Publish message. You could use `auto` here... */
        PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");
        if (!pclient) return;
        PublishCracker cheez;
        cheez.read_and_parse(pclient);
        /** You're mostly interested in `outcome()`, and,
            if it's "failed", then `description()`.
        */
        Serial.print("Outcome: "); Serial.print(cheez.outcome());
        Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
        Serial.print("description: "); Serial.println(cheez.description());
        Serial.print("timestamp: "); Serial.println(cheez.timestamp());
        Serial.print("state: "); Serial.print(cheez.state());
        Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
        pclient->stop();

        /* Wait for news. */
        PubSubClient *sclient = PubNub.subscribe(subchannel);
        if (!sclient) return; // error
        String msg;
        SubscribeCracker ritz(sclient);
        while (!ritz.finished()) {
            ritz.get(msg);
            if (msg.length() > 0) {
                Serial.print("Received: "); Serial.println(msg);
            }
        }
        sclient->stop();

        delay(1000);
    }

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

What do you guys think?

body:
The error you're reporting is coming from your call to `PubNub.publish()`. You could have diagnosed the problem by taking outputting and inspecting what you were passing to it.

Your line:

    PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");

is not going to work. You're sending the string `"String(IMU.getAccelX_mss())"` to PubNub rather than the value of `IMU.getAccelX_mss()` as a `String`. Take the quotes off it:

    PubNonSubClient *pclient = PubNub.publish(pubchannel, String(IMU.getAccelX_mss()));

If for some reason the number has to be returned as a string, the code would look like:

    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"" + String(IMU.getAccelX_mss()) + "\"");


message:
Connecting multiple MAX30100/30102 via I2C

I want to connect multiple (up to 4) MAX30100 or MAX30102 oximeter sensors to an Arduino via I2c. But I could not find a solution to change/assign the I2C address.

[implementing-pulse-oximeter-using-max30100][1]

[datasheet MAX30100][2]

  [1]: https://morf.lv/implementing-pulse-oximeter-using-max30100
  [2]: https://datasheets.maximintegrated.com/en/ds/MAX30100.pdf

body:
LTC4316 is what you need. I haven't used it yet, but I know it from a project that did: [mocap][1]. It is an I2C translator IC.

Of course, if you need those ICs to be far away from each other, use a uC (or a separate Arduino) with all of those, and connect them with a different protocol!

  [1]: https://hackaday.io/project/27519-motion-capture-system-that-you-can-build-yourself


body: Nyos's suggestion of an I2C address translator is the ticket. I hadn't heard of these chips before, so I started searching. I found that the one they recommended may be being phased out. It also looks like it's surface-mounted. I found a TI data sheet that lists a DIP package chip TCA9548APW that lets you map up to 8 I2C devices to different addresses. You might want to check those out as an alternative.


body:
Is there any other way of solving this issue?
I do not want to increase Hardware dependency.

I found out this article - which lets you use multiple i2c devices with the same address by employing different data lines: https://bitbanksoftware.blogspot.com/2019/01/controlling-lots-of-oled-displays-with.html

The Github source: https://github.com/bitbank2/Multi_BitBang

To my knowledge, I, either have to implement this library my own way or us the TCA9548APW chip as described by @Duncan C in the above answer


message:
Powering 150 WS2812B LED strips

I just bought an Elegoo Uno R3 today and delved into programming Arduinos. For my first project I'd like to power a 5m LED strip (30 LED/m). I've learned that an individual neopixel needs around 60 mA, and i'm gonna assume this means that to power all 150, I need 9A. I'm extremely new to all this (and electrical stuff in general) and not exactly sure how to go on about giving 9A worth of power to the strips and the Arduino. Any help to get me on the right track would be appreciated.

body:
Your math looks right to me. You need a 9A power supply if you're going to drive all 150 LEDs at 0 brightness on all 3 channels.

I'd suggest using a separate 500mA 5V regulated power supply for the Arduino. Switching 9A of load on and off on the LED power supply is going to cause quite a bit of variation in the voltage on that 9A supply, and the simplest way to keep the power supply to the Arduino clean is to make the 2 power supplies completely different.


body: Connect the power supply in multiple places to the LED strip. The two ends and the middle at least. That will keep all the current from having to flow thru all of the strip.  If try to power it from just one end, the power traces in the strip might act as a fuse and blow open. Or it might survive, but act like a low-ohm resistor and the chips farther down the string will see less voltage (because voltage down the trace = current x resistance) and may appear dim, or act weirdly, or not turn on at all.


message:
Help decrypting AES string from arduino rf module in python

Please excuse any glaring errors in my code, I'm new to both C and python.

I'm trying to send an encrypted message from my arduino uno via a DHT22 sensor and an rf module using the radiohead ask and AESlib libraries to a raspberry pi with a usb RTL-SDR using the rtl_433 library and a python script.

I think (but I could very well be wrong) I have the Arduino side working properly and it feels as though I'm pretty close on the python side, however I don't seem to be decrypting the message properly.

An example of the string before being encrypted might be:

"55.55,24.99,0001"

Here is the code on the Arduino side:

#include <AESLib.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "DHT.h"
#include <RH_ASK.h>
#include <Base64.h>

#define DHTPIN 2

#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
RH_ASK driver;

bool takeSensorReading = true;
float h;
float t;
String str_humid;
String str_temp;
String str_out;
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
char data[32];
char endChar[1] = "Ʊ";

void setup() {
  driver.init();
  dht.begin();
  Serial.begin(9600);
}

void loop() {
  delay(5000);

  int messagelength = sizeof(str_out);
  byte plain[messagelength];

  h = dht.readHumidity();
  // Read temperature as Celsius
  t = dht.readTemperature();

  // Convert Humidity to string
  str_humid = String(h, 2);

  // Convert Temperature to string
  str_temp = String(t, 2);

  // Combine Humidity and Temperature
  str_out = str_humid + "," + str_temp + ",0001";

  str_out.toCharArray(data, 32);
  aes256_enc_single(key, data);

  /*aes256_dec_single(key, data);*/
  Serial.println(data);
  int encryptedStringLength = sizeof(data);

  int encodedLength = Base64.encodedLength(encryptedStringLength);
  char encodedString[encodedLength];
  Base64.encode(encodedString, data, encryptedStringLength);
  Serial.print("Encoded string is:\t");
  Serial.println(encodedString);

  driver.send(strcat( (uint8_t *)encodedString, endChar ), 33);
  driver.waitPacketSent();

  takeSensorReading = !takeSensorReading;
}

and here is the python code:

import subprocess
import json
import base64
from Crypto.Cipher import AES

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]

def print_no_newline(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()

def decrypt(enc):
    private_key = str(bytearray([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]))
    iv = enc[:16]
    cipher = AES.new(private_key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(enc[16:]))

p = subprocess.Popen(['rtl_433', '-f', '433720000', '-F', 'json'],stdout=subprocess.PIPE,bufsize=1)
# rtl_433 -f 433720000 -F json
try:
    for line in iter(p.stdout.readline, ""):
        lineStripped = str(line).strip()
        try:
            jsondata = json.loads(lineStripped)
            time = jsondata["time"]
            payload = jsondata["payload"]
            if len(payload) == 33:
                payloadstring = ''
                for a in range(len(payload)):
                    payloadstring += chr(payload[a])
                payloadstring += "AAAAAAAAAA="
                print payloadstring
                encrypted = base64.b64decode(payloadstring)
                print encrypted
                decrypted = decrypt(encrypted)
                print decrypted
        except Exception as err:
            print "oh no, something went wrong"
            print("error: {0}".format(err))
except KeyboardInterrupt:
    p.kill()

p.wait()
p.stdout.close()

Here is an example of the erroneous output of the decrypt function:

"@g�އ�6S���25zD"

Any help you could give me in decoding the message from the Arduino in the python script would be really appreciated.

Thanks

Richard

*EDIT

I thought if it helps I could provide a bit more context around the transmission stages that the message goes through:

After the initial data string is constructed from the temperature and humidity sensor eg "55.55,24.99,0001" that 16 byte message is added to a 32 byte char array and encrypted using the aes128_enc_single method. The encrypted message is then base63 encoded The encrypted char array is then combined with an extra unencrypted character "Ʊ" (which I thought I could use to crudely validate the message) and sent via the radiohead ask send method:

`driver.send(strcat( (uint8_t *)encodedString, endChar ), 33);`

On the pyhton/reciever end I run a sub process `rtl_433 -f 433720000 -F json`

and listen for the output line by line. A example of the output of the rtl_433 command would look something like this:
`{"time": "2019-03-05 00:00:00", "model": "RadioHead ASK", "len": 33, "to": 255, "from": 255, "id": 0, "flags": 0, "payload": [111, 110, 109, 57, 120, 86, 52, 79, 121, 78, 71, 52, 48, 122, 117, 88, 67, 52, 77, 118, 85, 81, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65], "mic": "CRC"}`

rtl_433 converts the message into an array of ASCII or Unicode characters.

I have then tried to convert the characters in the recieved array back into standard characters:
`payloadstring += chr(payload[a])`
added padding to the message:
`payloadstring += "AAAAAAAAAA="`
then base64 decoded the result:
`encrypted = base64.b64decode(payloadstring)`
and then finally decrypt that:
`decrypted = decrypt(encrypted)`

Hopefully that info might be helpful in flagging up where I have gone wrong.

body:
By inspection only:

You are using an Initialization Vector and CBC mode in your Python code, but no IV and single block encryption in your Arduino code.

I think if you use MODE_ECB in your Python it will ignore the IV and match the Arduino code.

From a look at the [AESLib github][1] it appears your key should be exactly 16 bytes - yours is 32. I haven't looked at the code to see whether it will just ignore the rest, but the Python code definitely won't, so you should probably do what it says and use 16, and adjust your Python code to match.

Since the above wasn't enough to get it working, I would suggest divide-and-conquer: Use an online AES-128 encyrptor/decryptor such as [aesencryption.net][2] or [encode-decode.com][3] or [infoencrypt.com][4] to validate and cross-check your Arduino encryption and Python decryption functions. With a bit of luck you can at least fix them one-by-one, against a known-good reference.  Perhaps with a bit of fiddling you may be able to work out where it's going wrong.

I presume the humidity value may not change much, and I have a feeling that sending several messages with the same start can substantially weaken the encryption but I'm no crypto expert and perhaps it's still adequate for your purposes.

  [1]: https://github.com/DavyLandman/AESLib/blob/master/README.md
  [2]: https://aesencryption.net/
  [3]: https://encode-decode.com/aes128-encrypt-online/
  [4]: https://www.infoencrypt.com/


message:
How to use the ESP32 WROOM GPIOS above #18 with arudino ide?

I am using the Arduino IDE version 1.8.8 I am trying to control an [ESP32-wroom][1]. The gpios for pins 16 and 17 are working. I have some relays on GPIO's 18 and 19 that I'd also like to be able to control. I also have no control over GPIO's that are over 17 I've tried 18 through 27 and I can't toggle them.

    #define relayPin3 18
    #define relayPin4 19

    int relayflag = 0;
    void loop() {
      delay(1000);
      if (relayflag == 0){
        digitalWrite(relayPin3, LOW);
        digitalWrite(relayPin4, HIGH);
        relayflag =1;
      }
      else
      {
        digitalWrite(relayPin3, HIGH);
        digitalWrite(relayPin4, LOW);
        relayflag = 0;
      }

    }

I noticed that GPIO's 18 and 19 are also shared with spi ports.

Does the digitalWrite command work for any GPIO or is it in use by another library? Is there some other command to get access to the GPIO's I need to use? Some library I need to modify.

[![enter image description here][2]][2]

  [1]: https://www.espressif.com/sites/default/files/documentation/esp32-wroom-32_datasheet_en.pdf
  [2]: https://i.stack.imgur.com/Wz3bn.png

body:
Found the answer, albeit a simple one. This is my first go around with arudino so it will look ridiculous to those who program microprocessors (including myself)

You need to declare the pin to be an output before use. The inconsistent thing is, this only happens sometimes. For some of the pins you don't need to use pinMode for them to work.

      pinMode(relayPin1, OUTPUT);


message:
Using two leds with one push button

How can I make the code of this project where I will press one time a button,  to turn on the first led (and turn off second led) and when other one press to turn on second led (and turn off the first led).

body:
You can do this by keeping the 'state' saved in a variable.
Depending on it's [state][1], the button will have a different effect.

After this effect, the state is updated, so that next iteration it will behave according to the other state.

    state = led1
    if(buttonpressed){
       if(state == led2){
         led1On();
         led2Off();
         state = led1;
       }else{
         led1Off();
         led2On();
         state = led2;
       }
    }

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine


message:
Can I program an ATtiny87 with Arduino

I have a project, and I want to use an ATtiny167(ATtiny87), I know that an Arduino can progam ATtiny84 (84/44/24), ATtiny85 (85/45/25), and ATtiny2313 (4313). **but I don't know if it can program an ATtiny87?**

thank you for your help.

body:
There is a json for ATtiny 167 at https://playground.arduino.cc/Main/ArduinoOnOtherAtmelChips

So add that json to your preferenses.


message:
How to get the weather kit with anemometer working using arduino (UNO)?

I tried to build a weather station with anemometer and My setup is,
[SwitchDoc Labs' anemometer kit](https://shop.switchdoc.com/collections/weather/products/weatherrack-anemometer-wind-rain-for-weatherpiarduino-weatherplus-raspberry-pi-arduino) (which is equivalent to [sparkfun anemometer kit](https://www.sparkfun.com/products/8942)) connected to the [grove weather-pi board](https://shop.switchdoc.com/collections/weather/products/the-weather-board-w-grove-interface-board-for-weather-instruments-for-raspberry-pi-arduino) with [rtc clock DS3231](https://www.amazon.com/Universal-Solder-DS3231-Arduino-EEPROM-Battery/dp/B07BCPRH6F) installed on which is connected to [arduino UNO](https://store.arduino.cc/usa/arduino-uno-rev3).

According to http://www.switchdoc.com/wp-content/uploads/2016/07/WeatherBoard_CurrentSpecification.pdf and their official tutorial https://www.switchdoc.com/2015/01/weather-arduino-weatherpiarduino/, if I use grove weather-pi board's JP2 connections to connect to the UNO/Mega2560 board then it suggests as following (in my case its UNO)

diagram 1 ![1][1]
diagram 2 ![2][2]

    GroveWeatherPi_board Mega  Uno  Units
        JP2/1 ->         A0   A0  WindVane
        JP2/2 ->         D2   D3  RainBucket
        JP2/3 ->         D5   D2  Anemometer
        JP2/4 ->         GND   GND  GND

And the supposedly working sketch/library is https://github.com/switchdoclabs/SDL_Weather_80422 which only compiles on arduino-IDE without issue if I use the fork https://github.com/soligen2010/Adafruit_ADS1X15 instead of the original https://github.com/adafruit/Adafruit_ADS1X15 with it but even then the wind-speed and wind-direction unit or to say the whole anemometer part just do not work or in other words, do not give any reading. I have tested the units individually up to the arduino pins with LED light on breadboard, they are sending signals/responding and also mounted the whole project on a Mega2560 as well but results remained unchanged.

I am assuming the pin-outs defined in the https://github.com/switchdoclabs/SDL_Weather_80422 are messed up then but how to redefine it in the sketch/library because in the ino sketch file, these are the pin-out definitions for primarily Mega2560

    #define pinLED     13  // LED connected to digital pin 13
    #define pinAnem    18  // Anenometer connected to pin 18 (not used in the diagram!) - Int 5 - Mega   / Uno pin 2
    #define pinRain    2   // Anenometer connected to pin 2 - Int 0 - Mega   / Uno Pin 3
    #define intAnem    5   // int 0 (check for Uno), according to the above two diagrams' comparison, for UNO this pin also goes to the pin 2
    #define intRain    1   // int 1 (not used in the diagram! Then why? Its a TX pin)

Where the pinAnem and intAnem both indicates pin 2 for UNO according to the above two diagrams.

When I connect the I2C vcc pin from grove-weather-board to UNO's 5 volts instead of 3.3 volts as shown, the wind direction gets fixed but still no wind-speed reading.

So what are the corrections I need to do in the [SDL_Weather_80422 library](https://github.com/switchdoclabs/SDL_Weather_80422) or in the connection diagram in this case?

[1]: https://i.stack.imgur.com/5bkUW.png
[2]: https://i.stack.imgur.com/cX8c4.png

body:
According to the above setup only rain bucket unit works.

And as [jsotola](https://arduino.stackexchange.com/users/40318/jsotola) mentioned both the anemometer and the rain bucket sensors are simple switches, so a simple sketch can be written that reads the switch state and light LED (pin13) if the switch is activated and turns off LED if switch is not activated and that can be done for each of the switches separately.

But instead I took a shortcut.

Fixes:

1. The wind vane part (on analog pin A0) starts working only when I connect the I2C vcc pin to ***5 volts*** pin instead of 3.3 volts pin of UNO.

2. Had to ditch the https://github.com/switchdoclabs/SDL_Weather_80422 library's wind_speed reading method and adopting and merging into the http://cactus.io/hookups/weather/anemometer/davis/hookup-arduino-to-davis-anemometer-wind-speed code and adding up the wind_gust function from https://github.com/sparkfun/Weather_Shield/blob/master/Firmware/Weather_Shield_Weather_Station_V12/Weather_Shield_Weather_Station_V12.ino makes the anemometer with rain-bucket with the exact same setup fully functional.


message:
First Arduino Uno - Immediate Problems

I'm new to Arduinos but researched thoroughly before buying one. Just for context I'm an IT Professional with 20 years in the game, I'm comfortable with Linux/Unix, Windows, Raspberry Pi's, electronics, hardware, software and monitoring/switching COM ports.

I've purchased my first Arduino (actually a Elegoo Uno R3 clone) and have just tried it out of the box connected to two different systems; one Windows 7 64bit Enterprise the other Kubuntu. Despite having the correct COM port selected on both I'm getting similar error messages:

    **avrdude: ser_open(): can't open device "\\.\COM15": The system cannot find the file specified.**

or

    **avrdude: ser_open(): can't open device "\\.\COM6": Access is denied.**

    Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Yes I have tried different COM ports.

Yes I have tried turning off Firewalls

Yes I have tried different USB cables.

I have a solid green LED and a intermittently blinking orange LED.

The suggested Troubleshooting guide + many Forum Threads do not seem to cover this exact error I'm encountering - well they do but they tend to be people with the simple issue of them not selecting the correct COM port or having the same COM port tied up with another task. Then choose the correct port and it works. I'm confident I have the correct COM port and when I click Get Board Info it pulls down the correct board information and serial number etc.

On the Linux system I was seeing a similar behavior with slightly different wording: Permission Denied

On my Windows 7 system I run as a Standard User (as one should, not as an Administrator), but regardless I have tried running the Arduino application normally and as an Administrator user but it has the same result. And it seems strange that it encounters the same style of error across multiple different operating systems.

Have I just been really unlucky and got a dud for my first Arduino or am I missing something obvious?

Thanks for your time and help.

body:
On Linux "Permission Denied" generally means one of two things:

1. You're not in the `dialout` group (or you haven't logged out and logged in since), or
2. Something else is using the serial port.

For 1:

    sudo usermod -a -G dialout ashley
    <log out or reboot>

For 2:

The most common culprit is `ModemManager`. The simplest cure is to uninstall it:

    sudo apt-get remove modemmanager


message:
Electric meter with Arduino and RS485 module

I'm a Arduino newbie. I have an Electric meter with an RS485 output. I want to get the MeterID value over the RS485 module and the Arduino. I just have document from manufacturer.

    Sent by computer : 68 99 99 99 99 99 99 68 01 02 67 F3 C3 16.
    Return from meter : FE 68 99 99 99 99 99 99 68 81 08 67 F3 A6 9B 34 4B 33 33 6F 16.

My Arduino code:

    #include <SoftwareSerial.h>

    #define SSerialRX        10
    #define SSerialTX        11
    #define SSerialTxControl 3
    #define RS485Transmit    HIGH
    #define RS485Receive     LOW

    SoftwareSerial RS485Serial(SSerialRX, SSerialTX);
    byte request[] = {0x68, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x68, 0x01, 0x02, 0x67, 0xF3, 0xC3, 0x16};
    int byteRead;

    void setup()
    {
      Serial.begin(9600);
      RS485Serial.begin(1200);
      pinMode(SSerialTxControl, OUTPUT);
      digitalWrite(SSerialTxControl, RS485Receive);
      delay(20);
      Serial.println("Get Meter Address App");
    }
    void loop()
    {
      digitalWrite(SSerialTxControl, RS485Transmit);
      RS485Serial.write(request, sizeof(request));
      delay(2000);
      digitalWrite(SSerialTxControl, RS485Receive);
      delay(2000);
      if (RS485Serial.available())
      {
        byteRead = RS485Serial.read();
        Serial.println(byteRead, HEX);
      }
    }
Serial Monitor show:
[![enter image description here][1]][1]

I'm using combo like this topic [modbus-rtu-controller-monitoring-with-arduino-and-rs485-module][2]. My code is in C# below. I used the code before and it worked fine, but on the computer I use a COM port (Baudrate 1200, data 8bits, Parity EVEN, Stopbit 1) with an RS485-R232 converter:

    #Send data
    dataOUT = WriteData("68 99 99 99 99 99 99 68 01 02 67 F3 C3 16");
    serialPort_Meter.Write(dataOUT, 0, dataOUT.Length);

    #WriteData method
    private static byte[] WriteData(string hex)
    {
    return hex.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
    }

    #Read data
    private static string ReadData(SerialPort serial)
    {
    byte[] buffer = new byte[serial.BytesToRead];
    serial.Read(buffer, 0, buffer.Length);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < buffer.Length; i++)
    sb.AppendFormat("{0:X2} ", buffer[i]);
    return sb.ToString();
    }

  [1]: https://i.stack.imgur.com/CM66Q.jpg
  [2]: https://arduino.stackexchange.com/questions/50645/modbus-rtu-controller-monitoring-with-arduino-and-rs485-module

body:
Using [readBytes][1] would do the same as your C# code. `readBytes` is blocking. It will wait for every byte until timeout. Default timeout is 1 second. If the count of bytes is smaller then the size of the buffer, it will wait a second after the last byte received. You can set the timeout with `RS485Serial.setTimeout(500);` (500 milliseconds for example).

    void loop()
    {
      digitalWrite(SSerialTxControl, RS485Transmit);
      RS485Serial.write(request, sizeof(request));
      RS485Serial.flush();
      digitalWrite(SSerialTxControl, RS485Receive);
      int recvLen = RS485Serial.readBytes(buffer, sizeof(buffer));
      for (int i = 0; i < recvLen; i++) {
        Serial.println(buffer[i], HEX);
      }
    }

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/stream/streamreadbytes/


message:
Arduino analogRead fluctuates from sensor unless USB connected

I have an Arduino connected to a 4-20 mA sensor through a current to voltage converter. When connected to the power supply the sensor reading fluctuates, as soon as I also connect it to a USB port it stabilizes and gives a correct reading (tested with other reader).

My main code is:

```c++
#include <Arduino.h>
#include "Display.h"

#define MINIMUM_DEWPOINT -100
#define MAXIMUM_DEWPOINT 20
#define AVG_READING_SIZE 20

float dewPoint;
uint8_t recordIndex = 0;
uint16_t analogReadingValue[20];
int sensorMin = 0;
int sensorMax = 1023;
int sensorValue = 0;

void setup()
{
 Serial.begin(9600);
 Display::init();

 for(uint8_t i = 0;i<AVG_READING_SIZE;i++)
 {
  analogReadingValue[i] = 0;
 }
}

uint16_t getAvg(uint16_t *arr,uint8_t numberOfElements)
{
 uint32_t sum = 0;
 for (uint8_t i = 0 ; i < numberOfElements ; i++)
 {
  sum += arr[i];
 }
 return  (uint16_t)(sum / numberOfElements);
}

void loop()
{
 analogReadingValue[recordIndex] = analogRead(A0);
 dewPoint = map(getAvg(analogReadingValue,AVG_READING_SIZE), sensorMin, sensorMax, MINIMUM_DEWPOINT, MAXIMUM_DEWPOINT);
 recordIndex++;

 if(recordIndex==AVG_READING_SIZE)
 {
  recordIndex = 0;
 }

 Display::displayDewpoint(dewPoint);
 Serial.println(dewPoint);
 Serial.println(getAvg(analogReadingValue, AVG_READING_SIZE));
 delay(2000);
}
```

My circuit diagram is:
[![enter image description here][1]][1]

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

body: Apparently 5V reference on the 5V pin was the issue as 5V was only supplied to the Vin pin and it was referencing to 0V. Swapping the power supply from Vin to 5V solved the issue


body: You need a decoupling ceramic capacitor between A0 and GND. 100nF should work just fine.


message:
How to upload sensor data on pubnub IOT with JSON Format?

I am trying to send MPU9250 sensor data to Pubnub IOT platform using node mcu, but not able to do it since the sensor data is not in JSON format. I know about publishing string but don't know about variable.

About Pubnub Library - https://github.com/pubnub/arduino

This is the part which I need help in:-

    IMU.readSensor();

    PubNonSubClient *pclient = PubNub.publish(pubchannel, IMU.getAccelX_mss());

But above line has error so how do i send imu sensor data to pubnub? All connections are right and sensor is working since I tested it.

body:
This is the format which helped me to upload the data successfully. I didn't knew what JSON format was and got stuck. In case if someone stumbles on a similar problem.

    char buf[5] = {};

    sprintf(buf, "\"%d\"", IMU.getAccelX_mss());

    PubNonSubClient *pclient = PubNub.publish(pubchannel, buf);


message:
Light Sensor - how to wait for specific setting then continue on Leonardo?

I have an analog light sensor working on my Micro Pro Leonardo board. I want to reach a part of my code which include keyboard presses where it monitors to see when an LED flashes and then continues the code from there.

Could someone give me a code example of how I can do that?

Currently I'd have something like....

      Keyboard.write(KEY_RETURN);
      delay(800);
      Keyboard.write(KEY_TAB);
      delay(150);
      Keyboard.write(KEY_TAB);
      delay(150);
      Keyboard.write(' ');
        }

    //Code here to wait until LED flashes, registers as 30 or less on the light sensor. Then carry on with code below once this happens

      BootKeyboard.press(KEY_LEFT_GUI);
      BootKeyboard.press('r');
      delay(40000);
      BootKeyboard.releaseAll();
etc

I know the light sensor is `AnalogValue = analogRead(A0);` and I assume it's some kind of "If" statement which loops until the value because less than what is defined but have no idea how this would be written.

body:
One method:

while (analogRead(A0) < setting){
// sit in this loop taking readings until get one that is >= to setting
}


message:
Gps with Lora (E32 433T30D)

I want to receive data from GPS Neo 6m to Arduino and want to sent through LoRa (E32 433T30D).

GPS RECEIVE AND LORA SEND code

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

    static const int RXPin = 4, TXPin = 5;
    static const int loraRXPin = 2, loraTXPin = 3;
    static const uint32_t GPSBaud = 9600;
    static const uint32_t loraBaud = 9600;

    // The TinyGPS++ object
    TinyGPSPlus gps;

    // The serial connection to the GPS device
    SoftwareSerial ss(RXPin, TXPin);
    SoftwareSerial lora(loraRXPin, loraTXPin);

    void setup(){
      Serial.begin(9600);
      ss.begin(GPSBaud);
      ss.println("KATHE");
      lora.begin(loraBaud);
      lora.println("ASHOK");
    }

    void loop() {
      // This sketch displays information every time a new sentence is correctly encoded.
      while (ss.available() > 0){
        gps.encode(ss.read());
        if (gps.location.isUpdated()){
          ss.listen();
          Serial.print("Latitude= ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(" Longitude= ");
          Serial.println(gps.location.lng(), 6);
          lora.listen();
          lora.print("Latitude= ");
          lora.print(gps.location.lat(), 6);
          lora.print(" Longitude= ");
          lora.println(gps.location.lng(), 6);
        }
      }

      }

    LORA RECEIVE CODE is

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2,3); // RX, TX

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

      Serial.println("Goodnight moon!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      mySerial.println("Hello, world?");
    }

    void loop() { // run over and over
      if (mySerial.available()) {
        Serial.write(mySerial.read());
        //Serial.println(" ");
      }
      if (Serial.available()) {
        mySerial.write(Serial.read());

      }
    }

Here I'm not getting gps data to the LoRa receiver.
Please help me to overcome this problem.

body:
Lora we can connect directly to the arduino serial ports(0,1)- Lora Tx is connected to the arduino Rx and Lora Rx is connected to the arduino Tx. (this is for receiving data from arduino and must be connected these pins after uploading the code).
(2,3) of other arduino to receive data to arduino from Lora.
For sending there is no code like Bluetooth. And for receiving the following code helps you..

#include <SoftwareSerial.h> SoftwareSerial mySerial(2,3); // RX, TX void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native j for the SoftwareSerial port mySerial.begin(9600); mySerial.println("Hello, world?"); } void loop() { // run over and over if (mySerial.available()) { Serial.write(mySerial.read()); //Serial.println(" "); } if (Serial.available()) { mySerial.write(Serial.read()); } }


message:
nRF24L01 - leaves out end characters during transmission

This is my Master's code.

    #include <nRF24L01.h>
    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>

    RF24 radio(7, 8);

    const byte address[6] = "00001";
    char text[20] = "";
    int flag;
    char *p;
    int i;

    void print();
    void read();
    void rfwrite();
    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.setDataRate(RF24_1MBPS);
      radio.setChannel(1);
      radio.openWritingPipe(address);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();

      flag = 0;
      p = text;
    }

    void loop() {

      if (Serial.available()) {
        read();

      }
      if (flag) {
        print();
        rfwrite();

      }

    }

    void print() {
      Serial.println(text);
      flag = 0;
    }

    void read() {
      p = &text[0];
      for (i = 0; Serial.available(); p++, i++) {
        *p = Serial.read();
      }
      text[i + 1] = '\0';
      flag = 1;
    }

    void rfwrite() {

      radio.startWrite(text, strlen(text)+1);

    }

Slave code:

    #include <nRF24L01.h>
    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>

    RF24 radio(7, 8); //ce,csn

    const byte address[6] = "00001";
    char text[20] = "";
    int  i;

    void write_to_array();
    void print();
    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.setDataRate(RF24_1MBPS);
      radio.setChannel(1);
      radio.openReadingPipe(0, address);
      radio.setPALevel(RF24_PA_MIN);
      radio.startListening();
    }

    void loop() {
      while (radio.available()) {

        write_to_array();
        print();

      }

    }

    void write_to_array() {
      radio.read(text, strlen(text)+1);

    }

    void print() {
      Serial.println(text);

    }

I edited the code and made it with an array like @Kwasmich said. But now some end characters are not getting printed. When I type `1234567890-=` into the transmitter, only `1234567890-` gets printed. When I type a new set of characters following that, the missing `=` gets printed. Also, this happens only on the second transmission after I upload the code to the Arduino. The first set of characters are received and printed correctly. How do I fix this? Will flushing the buffer help(I doubt this because the first transmission is received correctly)?

body:
**This is not a proper solution explaining why the issue occurred in the first place but merely a workaround to anyone encountering the same problem.**

There is another function in the RF24 library called startWriting(). The description in the library was not clear about the differences between this and write(). But I noticed that the last character was missing with the use of startWriting(). So I simply changed

    radio.read(&text, sizeof(text));
in the master to

     radio.read(&text, sizeof(text+1));
and voila!
The code now does its intended purpose!!


body:
You are riding on a wave of undefined behavior. sizeof returns the size of the underlying type. In your case char. Which is 1. What you really need is the propper allocated array `char text[32] = ""` and the required length of the string using `strlen(text) + 1`. +1 to also transmit the nul terminator of the string.

The maximum string Length that can be transmitted using nRF24L01 is 32 bytes. Because of the mandatory nul termination of a string you can send at most 31 characters as a valid string.

Fun fact: The same limitation of 31 characters applies to file name langths on the classic Mac OS at least up to 7.x and also on the Amiga DOS/Workbench.


message:
Ultrasonic sensor underwater calibration

Does anyone knows how to calibrate AJ-SR04M using the Arduino? I am working on AUV. underwater reading from current code; it is giving continuous 20cm while moving inches. [http://shop2.hanjindata1.cafe24.com/product/aj-sr04m-ultrasonic-ranging-module/206/][1]

  [1]: http://shop2.hanjindata1.cafe24.com/product/aj-sr04m-ultrasonic-ranging-module/206/

body:
If I understand your question correctly, your problem is probably that the working range of the [AJ-SR04M][1] sensor is **20cm - 500cm**.

The sensor uses the same transducer to create the sound pulse and to listen for the echo.  It needs time to switch from one mode to the other, which explains why your sensor can't measure distances of less than 20cm.

The speed-of-sound in water is about 5x the speed of sound in air.  More specifically, at 20 degrees Celsius the speed-of-sound in air is approximately 343 meters per second, while the speed-of-sound in water is approximately 1482 meters per second.

This will cause the sensor to 'under-report' the distance in water.  The minimum distance will also be approximately 5x the minimum distance in air.

As an aside, you will also need to make allowance for the differences in the characteristic impedance and absorption between sound and water.

It's worth reading the paper [Underwater Sound][2] by P. Vigoureux (Proceedings of the Royal Society of London. Series B, Biological Sciences, Vol. 152, No. 946) for a discussion of all the factors involved.

  [1]: https://www.santy.cz/senzory-c24/arduino-hc-sr04-modul-vzdalenost-mereni-vodotesny-waterproof-i320/
  [2]: https://www.jstor.org/stable/75361?seq=1#page_scan_tab_contents


message:
Can you use an Arduino to control the output current and voltage of a DC/DC converter?

I am using an arduino to create a device that outputs a specific current and voltage. I was wondering if there are any devices out there such as dc/dc buck boost converters that can be controlled by arduino to output desired powers. I am looking for something rated for at least 50 watts  that can carry at least 3 amps of current.

Thank you all in advance!

body:
Yes, and it's actually far simpler than most realize. I've tried digitpots, but they are quite un-linear and only handle 5v, unless you spend $$$. Early on, i had soldered an LDR in parallel to a buck converter's adjustment pot, and fed that PWM. It worked to somewhat adjust the vout, but had a lot of ripple and was not linear. I had gotten an MCU-controlled linear PSU going, that wasn't too hard, but i always wanted a buck. Just recently, i've found an awesome method and built several MCU-controlled SMPSs.  You don't have to have any special parts or de-solder anything!

Basically, you:

  * use a buck/boost (or dual) with a built-in V-adj potentiometer.
  * use a lowpass to convert the MCU's PWM output into a 0-vcc signal.
  * feed smoothed PWM voltage to a unity gain opamp to buffer available current.
  * create a common ground between MCU and SMPS.
  * feed the buffered 0-vcc control through a resistor into the pot's wiper, ~200-1k.
  * the amount of "injected" voltage will be inversely proportional to the SMPS's output voltage.

Since most SMPS's feedback is in the area of 1-2.5v, the 0-3.3/5v output of the MCU works well to provide or take away feedback from the regulator. The best part about this scheme is that output voltage regulation is maintained by the SMPS's hardware, the MCU just sets an offest. In short, you can set it to 10v via the MCU, attach a big load, and the voltage stays at 10v!

I've used this technique on the xl4005 and the xl4015, but i would imagine it would work for just about any common driver package.


message:
My ESP8266 web server is only displaying text, even after ensuring content type is text/HTML

So I just got my two ESP8266/ESP-12E WiFi development boards in the mail as I am trying to set up a few home automation devices in my house. I've gotten much further than I thought I would today, considering this is my first foray into working with circuits that involve microprocessors/WiFi, but I've run into a problem that I can't find a solution to myself.  Forgive me if there is another question similar to this, but I could not find it and this seems like the best place to ask.

I am using a tutorial/template program that Rui Santos from Random Nerd Tutorials was kind enough to create ( https://randomnerdtutorials.com/esp8266-web-server/ ), and although we have (as far as I can tell) identical boards, operating systems and Arduino code, I keep getting an HTML page that is text only, with none of the CSS or HTML elements showing.  It should look like this:

[![expected outcome][1]][1]

However, I am getting a page that looks like this:

[![outcome][2]][2]

His serial monitor is giving this response:

[![his serial monitor][3]][3]

My serial monitor is giving me this response:

[![my serial monitor][4]][4]

  [1]: https://i.stack.imgur.com/5d5OA.png
  [2]: https://i.stack.imgur.com/531q1.png
  [3]: https://i.stack.imgur.com/jgXDf.png
  [4]: https://i.stack.imgur.com/hkodX.png

I've tried putting `client.println("Content-type:text/html");` in a few places to see if it would help display the page, but to no avail.  Any help with getting this little program/website running would be greatly appreciated.

Thanks for your time!

body:
Don't use the low-level tools to handle http, use the built-in http tools. They  make creating http responses trivial. No more concatenating headers or worrying about client status; it provides a nice clean function ex:` server.send(404, "text/plain", message);` and nice subscription method: `server.on()`.

Checkout its usage on one of the Arduino ESP8266's built-in examples:
https://github.com/esp8266/ESPWebServer/blob/master/examples/HelloServer/HelloServer.ino


body:
The use of HTTP here is fairly straight forward so I think printing out your own HTTP headers is OK, you just need to be very specific with the order and send exactly what the browser expects. Without seeing your code, my guess is that you're sending out a blank line to the client somewhere prior to the 'Content-type: text/html' line being sent or that you're not printing an empty blank line somewhere after the Content-type line is being sent. If your browser (the client) doesn't receive the HTTP protocol commands that it expects in the order that it expects, then it will default to displaying EVERYTHING you send it as either plain text or an HTML document. To illustrate exactly what is supposed to be sent to the browser in this example:

    HTTP/1.1 200 OK
    Content-type:text/html
    Connection: close

    <HTML>....

Note that there should be a empty line printed out after the Connection: close line and before you send any HTML. There should be nothing else sent to the client prior to the HTTP/1.1 200 OK line being sent and before your HTML code starts. If you don't follow the protocol, your browser will probably default to displaying everything plain text as you're seeing.

Something else I noticed in the example code, there is no space between Content-type: and text/html. This is unusual, but I guess it [doesn't break the protocol][1] and Firefox and Chrome handle it ok in my testing. Still, it could cause issues if a browser doesn't handle that properly so you might just try adding a space between the header and it's value.

  [1]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2


message:
Serial.read() doesnt work in IF statement

I am working with an XBee module, so naturally, I started my void loop with AT command testing.

    void loop() {
        digitalWrite(Sleep_Rq,LOW);

A +++ with a guard time of 1 sec before and after it, sets xbee module in command mode.

    delay(1000);
    xbeeSerial.write("+++");              // Enter Command Mode
    delay(1000);

This part of the code, puts the serial data into string variable x in the form of a String.

    while(xbeeSerial.available()) {
        x = xbeeSerial.readString();
    }

Serial.println() is returning OK onto the serial monitor.

    Serial.println(x);

But when I compare x with OK nothing happens, 1 doesn't appear on the serial monitor.

    if(x=="OK")
      {
       Serial.println(1);
      }
    }
I tried swapping "OK" with 4F4B (ascii equivalent of OK), 20299 (decimal value). I also  tried changing datatype of x from String to word and compared x with 0100111101001011.
I also tried changing the IF condition as,

    if(Serial.println(x)=="OK")
        {
         Serial.println(1);
        }
and many more techniques with no luck to be found.

body:
Your problem is that you are assuming that all you see in the Serial Monitor is all there is. You see "OK", so you expect to compare the text that comes in with "OK".

However it's not. Serial communication (at least, text based serial communication) generally includes some kind of line ending marker. That could be any combination of Carriage Return (`\r`) and/or Line Feed (`\n`). Different devices use different combinations.

As it turns out the XBee uses '\r' as the line ending marker.

There are two ways of dealing with it:

1. Include the line ending in your comparison (`"OK\r"`), or better,
2. Incorporate the line ending in the reading.

The second point there involves the use of `readStringUntil()`:

    String x = xbeeSerial.readStringUntil('\r');

That is a more reliable way of reading the response since it reads everything up to the line ending, rather than reading until it times out with nothing else to read. You should find your whole program runs smoother with that method.


message:
Need help combining two sketches (HC05 and temperature)

I have a project where I have to combine 4 sensors and get data wireless via Bluetooth (HC05). I just want help with combining just 1 sensor sketch and the Bluetooth sketch. I want the data from the temperature sensor to be displayed on my phone.

Temperature sensor code:

    #include <OneWire.h>
    #include <DallasTemperature.h>

    #define ONE_WIRE_BUS 2

    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    void setup(void)
    {
      // start serial port
      Serial.begin(9600);
      Serial.println("Dallas Temperature IC Control Library Demo");

      // Start up the library
      sensors.begin();
    }

    void loop(void)
    {
      // call sensors.requestTemperatures() to issue a global temperature
      // request to all devices on the bus
      Serial.print(" Requesting temperatures...");
      sensors.requestTemperatures();
      Serial.println("DONE");

      Serial.print("Temperature is: ");
      Serial.print(sensors.getTempCByIndex(0));
      delay(1000);
    }

    Bluetooth code:

    #include <SoftwareSerial.h>
    SoftwareSerial BT(11, 10);
    int ledPin = 8;
    int state = 0;

    void setup()

    {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
    BT.begin(9600);
    }

    void loop() {
      if(BT.available() > 0){
      state = BT.read();

      }
        if (state == '0'){
          digitalWrite(ledPin, LOW);
          BT.println("LED: OFF");
          state = 0;
        }
        else if (state == '1'){
          digitalWrite(ledPin, HIGH);
          BT.println("LED: ON");;
          state = 0;

        }
    }

body:
Instead of writing it all out, I give some tips:

- First combine the content of both `setup` functions. You can remove duplicate lines (e.g. `Serial.begin(9600);` is needed only once. Keep the order in a logical way.

- Than combine the content of both `loop` functions. However, the delay could cause a problem. Replace this by keeping a variable with the current time, and check when it's at least a second ago you checked the temperature sensor, if so, measure the sensor (and update the variable to the current time).

So you get something like:

    unsigned long lastSensorMeasurement;

    void setup()
    {
       // Combination of both setup functions

       lastSensorMeasurement = millis();
    }

    void loop()
    {
       // Process sensor
       if (lastSensorMeasurement + 1000 >= millis())
       {
          // Code for sensor as in loop
       }

       // Process Bluetooth
       // Code for bluetooth as in loop
    }


message:
Too little current to trigger a relay?

I try to use [this relay][1] with a Arduino Mega. I connected with jumper cables

 - 5V pin to DC+,
 - GND to DC- and
 - Digital Pin 13 (because its a lucky number) to IN.

The power LED from the relay is lighting green.

I run this code, which should trigger the relay every 3s for 3s:

    int pinOut = 13;

    void setup() {
      pinMode(10, OUTPUT);
    }

    void loop() {
      digitalWrite(pinOut, LOW);
      delay(3000);

      digitalWrite(pinOut, HIGH);
      delay(3000);
    }

When initializing the sketch, the red light (from the relay) is flashing and the relay is clicking. But afterwards nothing happens.

With my multimeter I check the currents:

 - 5V to GND = ~5V
 - Pin13 to GND, when not connected to relay = ~4.7V
 - Pin13 to GND, when connected to relay = ~1.2V

The relay needs 5V and 5mA triggering current. I don't think the Arduino is not suited, since they promote the relay Arduino.

Any ideas? Do I need some kind of resistor? Or is the USB port from the laptop not sufficient? I used two different Arduino Mega's with two different relays. By the way i don't have a big background in electric.

  [1]: https://www.banggood.com/2Pcs-5V-1-Channel-Level-Trigger-Optocoupler-Relay-Module-For-Arduino-p-1366337.html?cur_warehouse=CN

body:
You are using pin 13, but you set pin 10 as an OUTPUT.

`pinMode(10, OUTPUT);`

Try changing that to

`pinMode(pinOut, OUTPUT);`

PS by not setting pin 13 to OUTPUT, `digitalWrite(pinOut, HIGH);` enables the internal pull-up, instead of "connecting" it to 5V. The internal resistors are around 35kOhm. So pulling a bit of current through them will result in a lower voltage at the pin.


message:
Digispark ATtiny 85 - not recognised as HID device

I am trying to create auto-username-writer with Digispark ATtiny 85. I have a pretty simple sketch:

    #include <DigiKeyboard.h>
    void setup() {
    }
    void loop() {
        DigiKeyboard.sendKeyStroke(0);
        DigiKeyboard.delay(100);
        DigiKeyboard.sendKeyStroke(76, MOD_ALT_RIGHT | MOD_CONTROL_LEFT); //ctrl+alt+del
        DigiKeyboard.delay(2000);
        DigiKeyboard.print("username");
        DigiKeyboard.sendKeyStroke(0x2B); //tab

        for (;;) {}
    }

When I upload the code via Arduino IDE into the device (Board: Digispark (Default - 16.5MHz), it finishes successfully, it is recognised as a HID device and immediately performs all the tasks. But when I disconnect it and connect it again (to my PC or any other PC) it is recognised as Digispark Bootloader and does not do anything.

I have tried it in Arduino IDE 1.8.8 and in Arduino IDE 1.6.5 and I have no idea why it is only recognised right after upload. I have two ATtinys and both do the same behaviour.

Can someone help me, please?

EDIT:
I tried adding `digitalWrite(1, HIGH);` to detect, whether the sketch even runs and it turned out it does not even run (except after the upload)...

body:
After five seconds, which is when the bootloader should switch to running your code, how does it show up in the list of usb devices (`lsusb` in Linux, Device Manager in Windows, etc.)

The original Digispark was a bit temperamental when plugged into USB 3 ports. If you are plugging it into one, try using a usb2 hub and plugging it into the hub instead.

Also, did you get this from Digistump, or is it a knock-off?


body: I hope I'm not too late here, but I believe you may need to update the bootloader.  Could you try the instructions here? https://www.iot-experiments.com/micronucleus-bootloader-upgrade/  I happened to be reading through this guide: https://hackernoon.com/low-cost-usb-rubber-ducky-pen-test-tool-for-3-using-digispark-and-duck2spark-5d59afc1910 and the troubleshooting section there sounds like the issue you're having.


body:
Same here,

I am new user so not saying this is the correct way.

I now includes "digiKeyboard.update();" and "digiKeyboard.delay(1000);". both at top ,both to trigger usb signal many many times to the host.

the "digiKeyboard.sendKeyStroke(0);" does not work every time.


message:
Power external daughter board from Arduino only powered by USB?

Been searching for an answer, but I see lots of talk about it, but not clear answers. Can somebody clarify this? If I power the Arduino only via USB, can I put a small daughter board? and power it from the Power connector(5V)

**Update:**

   Thanks for the answers I'm using a Genuino UNO and it does power the daughter board my meter was kaputt, got a good one and it is fine even hooked a breadboard circuit to the 5V and GND and it works!!!

body:
Yes. USB is limited to 500mA, the Arduino like an Uno has a 500mA fuse to protect the USB source.

The Arduino itself can use 25-50mA of that, or more depending on what you have connected to the IO pins.


message:
Arduino security

My question is how secure can I make an Arduino? The project I am working on would put the Arduino out in the public (school campus inside a trash can to sense how much trash is in it) and I want to make sure random people can't access it and mess/change the code. Any suggestions would be helpful.

It will also be connected to the network and be sending data to a database.

body: Software security features are not available in Arduino. However if you want to prevent people from flashing a new code to some extent, you can desolder the USB pins or use a version of Arduino like ProMini, that requires external USB connector for coding.


body:
If I understand your question, then you want ensure, that nobody is able read and change your code to see, what are you doing and to send you fake data from that Arduino.

What are problems here:

* It can be stolen (eventually with the entire trash bin) - means no fake data and no data
* It can be vandalised/destroyed in matter of minutes (max) - again no (real/fake) data
* The arduino can be reprogrammed by normal way (via bootloader) and send fake data - you can prevent that by changing the bootloader
* Arduino can be read and reprogrammed by ISP and send fake data - you can lock it (by setting SPIEN) to prevent both reading its memory and to reprogramming it this way
* the lock can be cleaned and chip erased and reprogrammed (but not read) by Chip Erase command from High Voltage programming. You can make it more difficult, if needed pins are attached to some devices or ground/power.
* the chip can be desoldered, reprogrammed and soldered back to avoid problems with connected devices.
* also the whole Arduino can be swapped with already tampered Arduino
* another Arduino can be atached to the net to inject fake data (and maybe prevent the original from normal transfers by interference)
(so it have problems with physical security)

To mess with your data (send fake) such program need to be able send data in (somehow) correct format over the net. Without source code or at least the code in Arduino the format of the data could still be sniffed from transmissions and deciphered (but it is difficult task to do) and you can employ some crytography to make it even harder (but it would eat a lot of memory and computing power from your code).

----

Well, in practical life your problem is stolen/vandalised arduino and simple attacks, which can be blocked by locking the Arduino fuses and bootloader (but you would have hard time put update there after locking it) and using some cryptography.


message:
Not able to convert String to Integer when receiving data from pubnub?

I did managed to upload mpu9250 sensor data on PubNub and nodeMcu but not able to use the received data to control servo

Look at the Port reading and see that servo angle is still showing '0'

[![COM PORT Reading][1]][1]

Code:-

    IMU.readSensor();
    char buf[500] = {};
    int imu = IMU.getAccelX_mss() * 10;

    sprintf(buf, "\"%d\"", imu);

    Serial.print(buf);

    PubNonSubClient *pclient = PubNub.publish(pubchannel, buf);
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);

    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */

    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    Serial.print("IMU Reading: "); Serial.println(IMU.getAccelX_mss());

    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
            pos = msg.toInt();
            Serial.print("value of servo angle: "); Serial.println(pos);
            myservo.write(pos);
        }

    }
    sclient->stop();

    delay(1000);

How do I convert a string to integer so that it can be used in servo?

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

body:
This is the code which worked for me:-

            msg.remove(0,1); msg.remove(msg.length());
            pos = msg.toInt();
            Serial.print("value of servo angle: "); Serial.println(pos);
            myservo.write(pos);

I had to remove this character (" ") by using msg.remove(0,1) & msg.remove(msg.length()) that removes starting and ending string.


message:
How to read analog pins from a second Arduino

I've run out of analog pins on Arduino Uno and don't have time to order new parts. I've heard you can connect two Arduinos and I have access to another UNO. If I did that, could I read the analog pins of the second Uno on the first one?

I'm planning to control 7 servos with separate potentiometers.

body:
Yes that is possible, you can even use as many Arduino's as you want and send the information to one 'master' Arduino to process the data.

What you need is a way to communicate between them. Depending on distance, speed and reliability, you can chose for Serial, I2C, SPI or more 'exotic' solutions like CAN(bus), RS485 or even wireless methods (with nRF modules).

Some have a simple protocol, for others you might have to make it yourself.

Also think of the processing, you want to do the processing on the main device, or to process as much as possible on the 'slave' Arduinos and send it to the main device.

(Btw, I talk about Master/Slaves), these are not official terms, but meant as example. For example, with CAN, you can send message from any Arduino to any other. With Serial, you can send from 1 Arduino to 1 other.

If you have 2 Arduino's, probably Serial is the easiest.


message:
Door control with Arduino and limit switches

I want to make a door with two limit switches and three buttons: one for stop and the other two for open and close. I run into a problem with the code with the start buttons and the limit switches. I can't make the code because I'm a beginner. Please can somebody help me with some code or something like that?

I'll appreciate it if you help me, because it's for my school project:)

body:
You will need to write code to

1. Control a motor. Likely a DC motor with two way control. This can be done with four MOSFETs and several diodes or much better, one H bridge IC. Your code will need to determine which one of two lines going to the dc motor is getting connected to the positive rail, and which one to the negative/ground, or both disconnected, using the three buttons you described.
2. You will need to write code that monitors the limit switches. I would suggest you use interrupts for these. One pin goes to ground, the other goes to the Arduino interrupt pin. You can use attachInterrupt() function to write functions that execute right away. Make sure you read up on which pins on your Arduino will support interrupts.
3. You will need to stop the motor movement either directly or by throwing a switch using the interrupt (or whatever detection method you use for the limit switch).

*one special consideration is that any variables that you use inside of interrupt functions should be marked as volatile, so `int myVar;` becomes `volatile int myVar;`
*also don't use Serial.print or millis() inside of your interrupt functions if can avoid it.

----------

From here Google 'Arduino switch' and work on an implementation of limit switches separately. If you want to, Google 'Arduino Interrupts' and improve your implementation to use interrupts. Next, Google 'DC motor bidirectional control Arduino'. Work on it standalone. Once both work separately, combine into a single project.

Let me know as you go through these if you have specific questions, and I would be happy to help you learn how to build it using the components you have.


message:
Can't flash ESP 32 Wroom

[![esp devboard v1][1]][1]

I have a new ESP32 Wroom attached to my USB and it shows up in the settings on my mac:

[![device][2]][2]

I do have another ESP thing from sparkfun which I can access via  `/dev/cu.usbserial-DN02N1D8`. This device I can flash without problems or read its mac address using `esptool.py`.

    Connecting........_____....._____....._____....._____....._____....._____....._____

So I wonder how I can flash the ESP32.

**Update**: Added a picture of my board.

  [1]: https://i.stack.imgur.com/8DqaW.jpg
  [2]: https://i.stack.imgur.com/kgzN0.png

body:
I did fix the problem now.

My mac has USB-C and I was using a single USB-C to USB Dongle. And the serial port never showed up on my mac:

    crw-rw-rw-  1 root  wheel   18,   5 Mar  8 10:53 /dev/cu.Bluetooth-Incoming-Port
    crw-rw-rw-  1 root  wheel   18,   7 Mar  8 10:53 /dev/cu.Heinz-WirelessiAP
    crw-rw-rw-  1 root  wheel   18,   3 Mar  8 10:53 /dev/cu.MALS
    crw-rw-rw-  1 root  wheel   18,   1 Mar  8 11:02 /dev/cu.SOC

As soon as I used the Satechi USB Dock the Silicon Labs USB to UART port showed up in the list:

    [...]
    crw-rw-rw-  1 root  wheel   18,  13 Mar  8 11:04 /dev/cu.SLAB_USBtoUART

I can now communicate with the ESP32:

    esptool.py --port /dev/cu.SLAB_USBtoUART read_mac

    esptool.py v2.6
    Serial port /dev/cu.SLAB_USBtoUART
    Connecting........___
    Detecting chip type... ESP32
    Chip is ESP32D0WDQ6 (revision 1)
    Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
    MAC: XXXXXXXXX
    Uploading stub...
    Running stub...
    Stub running...
    MAC: XXXXXXX
    Hard resetting via RTS pin...

Please note that if you'll need the [Drivers for the USB to Serial Chip from Silabs](https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers).

If you do not see the device showing up you'll need to load the kernel extension:

    sudo kextload /Library/Extensions/SiLabsUSBDriver.kext/

After this you might to confirm the extension in the Privacy section of the mac settings. See [this forum post](https://www.silabs.com/community/interface/forum.topic.15.15.html/cp120x_vcp_driverno-G1Bu) for reference.


body:
**Flash ESP WROOM 32**

kindly refer the link :
   https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html#


message:
How do I make the letters on my Arduino LED matrix scroll faster?

```
////*************************************************************************
////----------------1.开发环境:Arduino IDE or Visual Studio 2010----------------
////----------------2.使用开发板型号：Arduino UNO          ----------------
////----------------3.单片机使用晶振：16M              ----------------
////----------------4.店铺名称：大学生电子商铺/小强电子设计  ----------------
////----------------5.淘宝网址：Ilovemcu.taobao.com   ----------------
////----------------     52dpj.taobao.com                ----------------
////----------------6.作者：神秘藏宝室       ----------------
////***********************************************************************

#include <Arduino.h>

//IO配置
#define LEDARRAY_D 5
#define LEDARRAY_C 6
#define LEDARRAY_B 7
#define LEDARRAY_A 8
#define LEDARRAY_G 9
#define LEDARRAY_DI 10
#define LEDARRAY_CLK 11
#define LEDARRAY_LAT 12

#define led 13

#define Display_Num_Word 2    //液晶能显示的汉字个数

unsigned char Display_Buffer[8];
unsigned char Display_Swap_Buffer[Display_Num_Word][32]={0};     //显示缓冲区
bool Shift_Bit = 0;
bool Flag_Shift = 0;
unsigned char Timer0_Count = 0;
unsigned char temp = 0x80;
unsigned char Shift_Count = 0;
unsigned char Display_Word_Count = 0;

#define Num_Of_Word 33
const unsigned char Word[Num_Of_Word][32] =
{
0xFF,0xFF,0xFF,0x07,0xBB,0xBB,0xBB,0x87,0xBB,0xBD,0xBD,0xBD,0xBB,0x07,0xFF,0xFF,/*"B",0*/
0xFF,0xFF,0xFF,0xC7,0xBB,0x7D,0x7D,0x7D,0x7D,0x7D,0x7D,0x7D,0xBB,0xC7,0xFF,0xFF,/*"O"*/
0xFF,0xFF,0xFF,0x83,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0x83,0xFF,0xFF,/*"I",0*/
0xFF,0xFF,0xFF,0x1F,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0x01,0xFF,0xFF,
0xFF,0xFF,0xFF,0xC1,0xBD,0xBD,0xBF,0xDF,0xE7,0xFB,0xFD,0xBD,0xBD,0x83,0xFF,0xFF,/*"S"*/
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0x03,0xBD,0xBD,0xBD,0x83,0xB7,0xB7,0xBB,0xBB,0xBD,0x1C,0xFF,0xFF,/*"R",0*/
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0x83,0xBD,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBD,0x83,0xFF,0xFF,
0xFF,0xFF,0xFF,0x1F,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0x01,0xFF,0xFF,
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0x03,0xBD,0xBD,0xBD,0x83,0xB7,0xB7,0xBB,0xBB,0xBD,0x1C,0xFF,0xFF,/*"R",0*/
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xC1,0xBD,0xBD,0xBF,0xDF,0xE7,0xFB,0xFD,0xBD,0xBD,0x83,0xFF,0xFF,/*"S"*/
0xFF,0xFF,0xFF,0x83,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0x83,0xFF,0xFF,/*"I",0*/
0xFF,0xFF,0xFF,0xC3,0xBB,0xBB,0x7F,0x7F,0x7F,0x71,0x7B,0xBB,0xBB,0xC7,0xFF,0xFF,/*"G",0*/
0xFF,0xFF,0xFF,0xBF,0x83,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xC7,0xBB,0x7D,0x7D,0x7D,0x7D,0x7D,0x7D,0x7D,0xBB,0xC7,0xFF,0xFF,/*"O"*/
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0x01,0x6D,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xC7,0xFF,0xFF,/*"T",0*/
0xFF,0xFF,0xFF,0x18,0xBD,0xBD,0xBD,0xBD,0x81,0xBD,0xBD,0xBD,0xBD,0x18,0xFF,0xFF,/*"H",0*/
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0x07,0xBB,0xBB,0xBB,0x87,0xBB,0xBD,0xBD,0xBD,0xBB,0x07,0xFF,0xFF,/*"B",0*/
0xFF,0xFF,0xFF,0x1F,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0x01,0xFF,0xFF,
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0x83,0xBD,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBD,0x83,0xFF,0xFF,
0xFF,0xFF,0xFF,0xBE,0xBD,0xBB,0xB7,0xB7,0xBB,0xBB,0xBD,0xBD,0xBE,0xBE,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0x07,0xBB,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBD,0xBB,0x07,0xFF,0xFF,/*"D",0*/
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0xEF,0xEF,0xE7,0xD7,0xD7,0xDB,0xC3,0xBB,0xBD,0xBD,0x18,0xFF,0xFF,/*"A",0*/
0xFF,0xFF,0xFF,0x01,0x6D,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xEF,0xC7,0xFF,0xFF,/*"T",0*/
0xFF,0xFF,0xFF,0x18,0xBD,0xBD,0xBD,0xBD,0x81,0xBD,0xBD,0xBD,0xBD,0x18,0xFF,0xFF,/*"H",0*/
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,/*" Space",0*/
0xFF,0xFF,0xFF,0xDF,0xD7,0xB7,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xBE,0xBD,0xBB,0xB7,0xB7,0xBB,0xBB,0xBD,0xBD,0xBE,0xBE,0xFF,0xFF,
0xFF,0xFF,0xFF,0x83,0xBD,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBD,0x83,0xFF,0xFF,
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0x81,0xFF,0xFF,
0xFF,0xFF,0xFF,0x81,0xBF,0xBF,0xBF,0x83,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xFF,0xFF,
0xFF,0xFF,0xFF,0x1F,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0xBF,0x01,0xFF,0xFF,
};
void setup()
{
 pinMode(LEDARRAY_D, OUTPUT);
 pinMode(LEDARRAY_C, OUTPUT);
 pinMode(LEDARRAY_B, OUTPUT);
 pinMode(LEDARRAY_A, OUTPUT);
 pinMode(LEDARRAY_G, OUTPUT);
 pinMode(LEDARRAY_DI, OUTPUT);
 pinMode(LEDARRAY_CLK, OUTPUT);
 pinMode(LEDARRAY_LAT, OUTPUT);

 Clear_Display();
}

void loop()
{
 unsigned int i;
 for(i = 0;i<30;i++)
 {
  Display(Display_Swap_Buffer);
 }
 Display_Word_Count = Shift_Count/16;    //计算当前显示第几个字
 Calc_Shift();

 Shift_Count++;

 if(Shift_Count == (Num_Of_Word+Display_Num_Word)*16 )    //移动次数
 {
  Shift_Count = 0;
 }
}

//************************************************************
//清空缓冲区
//************************************************************
void Clear_Display()
{
 unsigned char i,j;
 for(j = 0 ; j < Display_Num_Word; j++)
 {
  for(i = 0 ; i < 32 ;i++)
  {
   Display_Swap_Buffer[j][i] = 0xff;    //0=显示  1=不显示
  }
 }
}

//************************************************************
//计算移动数据，存在在缓冲器
//************************************************************
void Calc_Shift()
{
 unsigned char i;

 for(i = 0;i < 16;i++)
 {
  if((Display_Swap_Buffer[0][16+i]&0x80) == 0)         //每行第一个字节移位
  {
   Display_Swap_Buffer[0][i] = (Display_Swap_Buffer[0][i] << 1)&0xfe;    //最低位清零
  }
  else
  {
   Display_Swap_Buffer[0][i] = (Display_Swap_Buffer[0][i] << 1)|0x01;   //最低位置一
  }

  if((Display_Swap_Buffer[1][i]&0x80) == 0)         //每行第二个字节移位
  {
   Display_Swap_Buffer[0][16+i] = (Display_Swap_Buffer[0][16+i] << 1)&0xfe;    //最低位清零
  }
  else
  {
   Display_Swap_Buffer[0][16+i] = (Display_Swap_Buffer[0][16+i] << 1)|0x01;   //最低位置一
  }

  if((Display_Swap_Buffer[1][16+i]&0x80) == 0)         //每行第三个字节移位
  {
   Display_Swap_Buffer[1][i] = (Display_Swap_Buffer[1][i] << 1)&0xfe;    //最低位清零
  }
  else
  {
   Display_Swap_Buffer[1][i] = (Display_Swap_Buffer[1][i] << 1)|0x01;   //最低位置一
  }

  if(Shift_Count < 8 && Display_Word_Count < Num_Of_Word)
  {
   Shift_Bit = Word[Display_Word_Count][i]&temp;
  }
  else if(Shift_Count < 16 && Display_Word_Count < Num_Of_Word)
  {
   Shift_Bit = Word[Display_Word_Count][16+i]&temp;
  }
  else
  {
   Shift_Bit = 1;      //把字移出缓冲区
  }

  if( Shift_Bit == 0)              //后8位移位
  {
   Display_Swap_Buffer[1][16+i] = (Display_Swap_Buffer[1][16+i] << 1)&0xfe;   //最低位清零
  }
  else
  {
   Shift_Bit = 1;
   Display_Swap_Buffer[1][16+i] = (Display_Swap_Buffer[1][16+i] << 1)|0x01;  //最低位置一
  }

 }
 temp = (temp>>1)&0x7f;
 if(temp == 0x00)
 {
  temp = 0x80;
 }
}
//************************************************************
//num为字数  dat[][32]为字模的名称
//*************************************************************
void Display(const unsigned char dat[][32])
{
 unsigned char i;

 for( i = 0 ; i < 16 ; i++ )
 {
  digitalWrite(LEDARRAY_G, HIGH);  //更新数据时候关闭显示。等更新完数据，打开138显示行。防止重影。

  Display_Buffer[0] = dat[0][i];
  Display_Buffer[1] = dat[0][i+16];
  Display_Buffer[2] = dat[1][i];
  Display_Buffer[3] = dat[1][i+16];

    Display_Buffer[4] = dat[2][i];
    Display_Buffer[5] = dat[2][i+16];
    Display_Buffer[6] = dat[3][i];
    Display_Buffer[7] = dat[3][i+16];

    Send(Display_Buffer[7]);
    Send(Display_Buffer[6]);
    Send(Display_Buffer[5]);
    Send(Display_Buffer[4]);

  Send(Display_Buffer[3]);
  Send(Display_Buffer[2]);
  Send(Display_Buffer[1]);
  Send(Display_Buffer[0]);

  digitalWrite(LEDARRAY_LAT, HIGH);     //锁存数据
  delayMicroseconds(0.1);

  digitalWrite(LEDARRAY_LAT, LOW);
  delayMicroseconds(0.1);

  Scan_Line(i);      //选择第i行

  digitalWrite(LEDARRAY_G, LOW);

  delayMicroseconds(100);;  //延时一段时间，让LED亮起来。
 }
}

//****************************************************
//扫描某一行
//****************************************************
void Scan_Line( unsigned char m)
{
 switch(m)
 {
  case 0:
   digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, LOW);
   break;
  case 1:
   digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, HIGH);
   break;
  case 2:
   digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, LOW);
   break;
  case 3:
   digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, HIGH);
   break;
  case 4:
   digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, LOW);
   break;
  case 5:
   digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, HIGH);
   break;
  case 6:
   digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, LOW);
   break;
  case 7:
   digitalWrite(LEDARRAY_D, LOW);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, HIGH);
   break;
  case 8:
   digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, LOW);
   break;
  case 9:
   digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, HIGH);
   break;
  case 10:
   digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, LOW);
   break;
  case 11:
   digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, LOW);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, HIGH);
   break;
  case 12:
   digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, LOW);
   break;
  case 13:
   digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, LOW);digitalWrite(LEDARRAY_A, HIGH);
   break;
  case 14:
   digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, LOW);
   break;
  case 15:
   digitalWrite(LEDARRAY_D, HIGH);digitalWrite(LEDARRAY_C, HIGH);digitalWrite(LEDARRAY_B, HIGH);digitalWrite(LEDARRAY_A, HIGH);
   break;
  default : break;
 }
}

//****************************************************
//发送数据
//****************************************************
void Send( unsigned char dat)
{
 unsigned char i;
 digitalWrite(LEDARRAY_CLK, LOW);
 delayMicroseconds(0);;
 digitalWrite(LEDARRAY_LAT, LOW);
 delayMicroseconds(0);;

 for( i = 0 ; i < 8 ; i++ )
 {
  if( dat&0x01 )
  {
   digitalWrite(LEDARRAY_DI, HIGH);
  }
  else
  {
   digitalWrite(LEDARRAY_DI, LOW);
  }

  digitalWrite(LEDARRAY_CLK, HIGH);    //上升沿发送数据
   delayMicroseconds(0);;
  digitalWrite(LEDARRAY_CLK, LOW);
   delayMicroseconds(0);;
  dat >>= 1;

 }
}
```

body:
You have 30x loop calling Display() that inside a 16X loop calls eight Send() that inside an 8x loop makes three digital writes each taking at least 2us to complete. At a minimum, only digitalWrite takes 180ms in one pass.

Use SPI if possible or search Google for "arduino speed up digitalWrite" , [here][1] is a good article on this.

Also unrolling the 8x loop inside Send() like this can spare some ms:

       if( dat&0x01 ) digitalWrite(LEDARRAY_DI, HIGH);
       else digitalWrite(LEDARRAY_DI, LOW);
       digitalWrite(LEDARRAY_CLK, HIGH);               //上升沿发送数据
       delayMicroseconds(0);;
       digitalWrite(LEDARRAY_CLK, LOW);
       delayMicroseconds(0);
       if( dat&0x02 ) digitalWrite(LEDARRAY_DI, HIGH);
       else digitalWrite(LEDARRAY_DI, LOW);
       digitalWrite(LEDARRAY_CLK, HIGH);               //上升沿发送数据
       delayMicroseconds(0);;
       digitalWrite(LEDARRAY_CLK, LOW);
       delayMicroseconds(0);
       ........
       if( dat&0x80 ) digitalWrite(LEDARRAY_DI, HIGH);
       else digitalWrite(LEDARRAY_DI, LOW);
       digitalWrite(LEDARRAY_CLK, HIGH);               //上升沿发送数据
       delayMicroseconds(0);;
       digitalWrite(LEDARRAY_CLK, LOW);
       delayMicroseconds(0);

  [1]: http://skpang.co.uk/blog/archives/323


body:
These lines

        digitalWrite(LEDARRAY_LAT, HIGH);                   //锁存数据
        delayMicroseconds(0.1);

        digitalWrite(LEDARRAY_LAT, LOW);
        delayMicroseconds(0.1);

        Scan_Line(i);                       //选择第i行

        digitalWrite(LEDARRAY_G, LOW);

        delayMicroseconds(100);;        //延时一段时间，让LED亮起来。

Reduce the time in the last one.
I don't think delayMicroseconds(0.1); does anything, nor does delayMicroseconds(0); found elsewhere.

I see individual pins being controlled

    #define LEDARRAY_D 5
    #define LEDARRAY_C 6
    #define LEDARRAY_B 7
    #define LEDARRAY_A 8
    #define LEDARRAY_G 9
    #define LEDARRAY_DI 10
    #define LEDARRAY_CLK 11
    #define LEDARRAY_LAT 12

You don't say what the hardware is, but I bet you replace writing individual pins with blasting data out serially to a shift register with 8 MHz SPI clock as a way speed things up. Or if you had a '1284P or '2560 board, then you could do port writes also.


message:
Program Arduino via UART from ESP8266 SPIFFS

I have built a custom board that has an ATmega328p connected to an ESP8266 module via UART. I am currently programming the ATmega328p using a USBtiny programmer via an SPI header. The ESP8266 module is programmed via an FTDI cable connected the the UART.

Firmware for both are created in Arduino IDE.

I have set up a webserver on the ESP that allows for files to be uploaded to the SPIFFS via FTP. I would like to be able to upload a hex file for the ATmega and then have the ESP program the ATmega via the UART connection. A GPIO on the ESP controls a transistor that can pull the reset pin on the ATmega to ground.

I know I need a bootloader on the ATmega (e.g. optiboot), but I don't know what I need to make the ESP do to trigger the bootloader and flash the ATmega. I'm thinking I need something like:

    void initialiseAtmegaFlash () {
      // Trigger the bootloader to accept incoming hex over UART
    }

    void flashHexToAtmega (File atmegaHex) {
      for (uint32_t i = 0; i < atmegaHex.size(); ++i) {
        // Handle timing of sending byte by byte over serial... or chunk by chunk?
      }
    }

body:
To answer my own question in case someone else ends up here, the library Juraj suggested ([https://github.com/ciminaghi/libdfu][1]) looks like it does the job. I also found another project doing something similar ([https://github.com/rene-win/esp_avr_programmer][2]). Also the STK500 docs linked to by Majenko ([http://ww1.microchip.com/downloads/en/AppNotes/doc2591.pdf][3]) are really useful for understanding the nuts and bolts!

  [1]: https://github.com/ciminaghi/libdfu
  [2]: https://github.com/rene-win/esp_avr_programmer
  [3]: http://ww1.microchip.com/downloads/en/AppNotes/doc2591.pdf


message:
How to connect MPU9250 with NodeMCU using SPI or I2C Slave?

I want to connect 3 MPU9250 sensors, but since there is just one I2C bus, so there are another 2 sensors I want to connect through SPI.

Library used - [https://github.com/bolderflight/MPU9250/blob/master/examples/Basic_SPI/Basic_SPI.ino][1]

There is an SPI example code written, but I don't know about the connections. There are no MISO and other pins on the sensor which i use but its SPI compatible. How do I connect 2 MPU9250 to NodeMCU with SPI?

If SPI connection is not possible then please post about I2C slave connection.

[![enter image description here][2]][2]

  [1]: https://github.com/bolderflight/MPU9250/blob/master/examples/Basic_SPI/Basic_SPI.ino
  [2]: https://i.stack.imgur.com/oOU7I.jpg

body:
To connect multiple SPI components, you only need 4 pins on each 'slave' (thus sensors): SLCK, MOSI, MISO and SS (Slave Select).

The Slave select pin depends to which the master (NodeMCU in your case) is 'talking too'. So on your NodeMCU you will have 3 SS pins (one for each slave sensor). The NodeMCU should talk exactly to one slave device at the same time by setting that SS pin LOW (while the other SS pins are high).

See for the full article: [Multiple-SPI-devices-to-an-arduino-microcontroller][1].

[![enter image description here][2]][2]

  [1]: http://www.learningaboutelectronics.com/Articles/Multiple-SPI-devices-to-an-arduino-microcontroller.php
  [2]: https://i.stack.imgur.com/7YtWd.png


body:
The MPU-9250 pins should be connected as:

--Vcc: this should be a 2.4V to 3.6V power source.

--GND: ground.

--FSYNC: not used, should be grounded.

--SDA / SDI: connect to MOSI.

--SCL / SCLK: connect to SCK.

--AD0 / SDO: connect to MISO.

--nCS: connect to chip select pin (Any digital pin but in your example is PIN 10).

Also, you can check the connection from:

https://learn.sparkfun.com/tutorials/mpu-9250-hookup-guide?_ga=1.139382715.926858641.1470020364


body:
If you want to use SPI-

[The homepage of the library you mentioned, clearly explains the circuit connections.][1]-

The MPU-9250 pins should be connected as:

 - VDD: this should be a 2.4V to 3.6V power source.
 - GND: ground.
 - VDDI: digital I/O supply voltage. This should be between 1.71V and
   VDD.
 - FSYNC: not used, should be grounded.
 - INT: (optional) used for the interrupt output setup in
   enableDataReadyInterrupt and enableWakeOnMotion. Connect to
   interruptable pin on microcontroller.
 - SDA / SDI: connect to MOSI.
 - SCL / SCLK: connect to SCK.
 - AD0 / SDO: connect to MISO.
 - nCS: connect to chip select pin. Pin 10 was used in the code snippets
   in this document  and the included examples, but any digital I/O pin
   can be used.
 - AUXDA: not used.
 - AUXCL: not used.

Each sensor's nCS (chip select pin) needs to be connected to a slave select pin (any digital pin) on the NodeMCU. This allows the NodeMCU toselect which sensor it wants to talk to.

Another easy way of connecting multiple sensors with the same I2C address is by using an I2C multiplexer like the [Adafruit TCA9548A][2]
[![TCA9548 I2C multiplexer][3]][3]
This would allow you to connect up to 8 sensors having the same I2C address. [Here's a youtube video explaining how to do so.][4]

However, if you just want connect two MPU9250s, you dont need to do any of this, as the board offers two unique addresses via the AD0 pin-

 - 0x68 if AD0 is grounded
 - 0x69 if AD0 is pulled high

  [1]: https://github.com/bolderflight/MPU9250
  [2]: https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout/overview
  [3]: https://i.stack.imgur.com/1jAwG.jpg
  [4]: https://www.youtube.com/watch?v=vV42fCpmCFg&ab_channel=DroneBotWorkshop


message:
Arduino should check the same way like a USB keyboard or a USB mouse, if turned on notebook is connected

I have a USB HUB and have connected to it a USB keyboard and a USB mouse. As long I have not connected a Notebook to it those devices don't turn on. 5V is always turned on! So I could charge my phone. How do they know there is no notebook connected? My Arduino is always on. I want to emulate this with an Arduino. Without the need of extra software on a notebook, the Arduino should be able to tell if a notebook is connected to the USB Hub or not. Please help.

body:
With Arduino Nano, you don't have control over the USB, because it is handled by the USB-to-TTL-Serial chip on the board. The MCU is to this adapter connected only with RX and TX of the Serial interface.

With Arduino Micro you could retrieve the state of the USB connection, because he MCU ATmega32u4 has a build in USB support an handles the USB connection from application (sketch).


message:
Arduino program to scan two different rfid cards in same program ? Im using nodemcu- esp8266 , rc522 reader and Firebase

/*My project is a Library management system using rfid cards. Im trying to generate a code wherein User first scan a book and then the record will be pushed in Issued_Books table in Firebase . Then the user scans his id to ensure that the book will be issued on his/her id.
But in my program is scanning only books id. It fails to scan users Id after that. Im a beginner so can anyone guide me? */

//My loop code is as following:

    void loop() {

      if ( !mfrc522.PICC_IsNewCardPresent() ) {
        delay(50);
        return;
      }

      if ( !mfrc522.PICC_ReadCardSerial() ) {
        delay(50);
        return;
      }
    String book;

      for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
        Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
        Serial.print(mfrc522.uid.uidByte[i], HEX);
        book.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
        book.concat(String(mfrc522.uid.uidByte[i], HEX));}
        book.toUpperCase();

        Firebase.pushString("Issued_Books/Book_rfid",book);

          Serial.println();

      if ( !mfrc522.PICC_IsNewCardPresent() ) {
        delay(50);
        return;
      }

      if ( !mfrc522.PICC_ReadCardSerial() ) {
        delay(50);
        return;
      }
      String user;

      //Serial.print("Scan your id: ");
        for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
        Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
        Serial.print(mfrc522.uid.uidByte[i], HEX);
        user.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
        user.concat(String(mfrc522.uid.uidByte[i], HEX));}
        user.toUpperCase();
        //Serial.print(F("Card UID: "));
        Firebase.setString("Issued_Books/Book_rfid/user_rfid",user);

        delay(3000);
    }

body:
also look into sprintf to get hex formatting
(I dont have these libraries so I cannot test, this is all written in stackexchange editor, so I might have a typo somewhere)

    unsigned long startScanTime;
    bool GotBookId = false, GotUserId = false;
    void loop() {
    GotBookId = false;
    GotUserId = false;

      if ( !mfrc522.PICC_IsNewCardPresent() ) {
        delay(50);
        return;
      }

      if ( !mfrc522.PICC_ReadCardSerial() ) {
        delay(50);
        return;
      }
    String book;

      for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
        Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
        Serial.print(mfrc522.uid.uidByte[i], HEX);
        book.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
        book.concat(String(mfrc522.uid.uidByte[i], HEX));
      }
        book.toUpperCase();
        if(book != "")
           GotBookId = true;

        Serial.println("Got Book");

    startScanTime = millis(); //timeout look to get user card
      while( !mfrc522.PICC_IsNewCardPresent() && (millis() - startScanTime < SCAN_TIMEOUT) ) {
       //do nothing but wait
      }

      if(!mfrc522.PICC_IsNewCardPresent())
      { //did not get the user id, return from loop
          return;
      }
      if ( !mfrc522.PICC_ReadCardSerial() ) {
        return; //should never hit this if library works correctly
      }
      String user;

      Serial.print("Scan your id: ");
        for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
        Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
        Serial.print(mfrc522.uid.uidByte[i], HEX);
        user.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
        user.concat(String(mfrc522.uid.uidByte[i], HEX));}
        user.toUpperCase();
        //Serial.print(F("Card UID: "));
        GotUserId = true;

       if(GotBookId && GotUserId){
           Firebase.pushString("Issued_Books/Book_rfid",book);
           Firebase.setString("Issued_Books/Book_rfid/user_rfid",user);
       }
    }


message:
Need little bit of help on testing I2C sketch

I have this code I got from YouTube for communicating between two Arduinos. By typing 'R' manually into the serial monitor of the 'master' Arduino, the 'slave' will print "Success". I'm trying all this for the basis of a project I'm starting.

After success with the code, I am now trying to make it automatic. I want the 'master' Arduino to print "R" itself and for the 'slave' to read this and print "Success". `println` doesn't work here, maybe it'll work if the slave code is changed? Both original codes are below, any ideas on how to do what I need?

Master:

    #include <Wire.h>
    char incomingByte;
    int x = 0;

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

    void loop()
    {
      Wire.beginTransmission(9);
      if (Serial.available()) {
        while (Serial.available() > 0) {
          incomingByte = Serial.read();
          Wire.write(incomingByte);
          Serial.println(incomingByte);
          Wire.endTransmission();
      }
      }

    }

Slave:

    #include <Wire.h>

    int x = 0;

    void setup() {
      Wire.begin(9);
      Wire.onReceive(recieveEvent);
      Serial.begin(9600);
    }

    void recieveEvent(int bytes) {
      x = Wire.read();

    }

    void loop() {

      if (x == 'R'){
        Serial.println("Success");
        delay(100);
      }
    }

body:
Here is my proposal to solve your issue:

 - Use the second Serial communication line of the master by connecting Rx and Tx Pins of Serial2 (this done only on master, practically a shortcut between Rx and Tx on Master)
 - Setup Serial2 if necessary: `HardwareSerial Serial2(2);` (that how it
   is necessary/done for my M5Stack)
 - Define baud rate for Serial2: `Serial2.begin(9600);`
 - Start your Automation by `Serial2.write("R\n");` at an appropriate place in your code
 - Change conditions of `if(..)` and `while(..)` in your master's code from `Serial.available()` to `Serial2.available()`
 - Change `incomingByte = Serial.read();` to `incomingByte =
   Serial2.read();`

With that solution you can still see your start signal printed out on your Serial monitor via the first Serial communication line. The communication to the slave is still working over IC2, Serial2 is only the proposal for the automation solution on master. Looks complicated, but this is how I understood the question, of course you also could directly use `incomingByte="R\n";` to start your Automation and skip all that stuff with Serial2 :-)


body:
The I2C communication is not easy and there are many things that can go wrong. Two Arduino boards instead of one board are often used for the wrong reason in the first place.

Using a serial port is easier. The Arduino Leonardo has an extra hardware serial port, you could use the serial port to communicate between two Arduino boards. The Arduino Mega 2560 has three extra serial ports.

Sometimes two Arduino boards are used because multiple things have to be done at the same time.
When you use the [Blink Without Delay][1] example with `millis`, then the Arduino can do many things at the same time.

Sometimes two Arduino boards are used because there is some distance between the Arduino boards.
The I2C bus is a "bus", but that does not mean that you can use a long cable. You can go up to 20 inch (50 cm).

When two Arduino Uno boards are connected with the I2C bus, then three wires are needed:

1. GND to GND
2. SDA to SDA  *(plus pullup resistor)*
3. SCL to SCL  *(plus pullup resistor)*

For a small test with short jumper wires, it is possible to do that without pullup resistors. For the final project pullup resistors should be used for SDA and SCL, for example 4k7 or 10k.

The example below uses a flag in the Slave Arduino. That extra variable makes it easier.
In the Slave `receiveEvent` function, there is a extra check to check if exactly one byte is received. That extra check is not required, but it can be useful.

I show this example as something to start with, because there are too many bad examples for I2C between Master and Slave.

**Master**

    #include <Wire.h>

    byte dataTransmit;

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

    void loop() {
      Wire.beginTransmission(9);   // sending to slave with i2c address 9
      Wire.write(dataTransmit);    // the data to send
      Wire.endTransmission();

      dataTransmit++;              // all numbers from 0 to 255

      delay(250);                  // 250ms delay, to send 4 times per second
    }

**Slave**

    #include <Wire.h>

    volatile byte dataReceive;
    volatile bool newData;    // a flag to indicate that new data has arrived

    void setup() {
      Wire.begin(9);          // create i2c slave at i2c address 9
      Wire.onReceive(receiveEvent);
      Serial.begin(9600);
    }

    void loop() {
      if(newData) {           // is there new data?
        Serial.print("Received: ");
        Serial.println(int(dataReceive)); // convert to integer to print the number
        newData = false;      // reset flag
      }
    }

    void receiveEvent(int howMany) {
      if(howMany == 1) {      // extra check, to check if one byte is received
        dataReceive = Wire.read();
        newData = true;       // set flag, there is new data
      }
    }

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay