body:
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

title: Too little current to trigger a relay?

Answers: 1

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.


body:
I intend to have both an Arduino Nano and an Uno connected to a PC via the on-board USB ports, but have them inter-connected with wires from one's GPIO pins to the other's (one reads the status of the other's pins). I've read that having two Arduinos communicate with each other requires them to share a common ground, so am not sure if this will work at all (the common power source in the PC may serve as the common ground, I'm not sure).

As some background, I would like the Nano to serve as an EEPROM programmer and have the Uno connected as a logic analyser to help debug the EEPROM programmer, both using serial to communicate with the PC in real-time.

How should I set up the Arduinos and power supply to make this possible in a safe way?

title: Setting up two arduinos connected to separate serial ports with wires in-between

Answers: 0


body:
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)...

title: Digispark ATtiny 85 - not recognised as HID device

Answers: 3

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.


body:
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!!!

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

Answers: 1

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.


body:
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.

title: Arduino security

Answers: 2

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.


body:
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

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

Answers: 1

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.


body:
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.

title: How to read analog pins from a second Arduino

Answers: 1

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.


body:
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:)

title: Door control with Arduino and limit switches

Answers: 1

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.


body:
So, I have an RGB matrix (using PL9823 LEDs) that's 32 x 8 that I'm trying to run a circular spinning rainbow pattern across in a continuous loop. Now, there's lots of code online for different ways to do this with a traditional daisy chained matrix, but I have mine set up to where each of the 8 rows of LEDs goes to a different pin on my Teensy 3.2 controller (pins 4-11) and I have no idea how to get this (or any) rainbow effect working on it. I'm using the FastLED library and this is how I have the program set up to address individual pins as the different rows of LEDs:

    #include "FastLED.h"
    #define LED_TYPE PL9823
    #define NUM_STRIPS 8
    #define NUM_LEDS_PER_STRIP 64
    #define NUM_LEDS NUM_LEDS_PER_STRIP * NUM_STRIPS

    #define COLOR_ORDER GRB

    uint8_t hue = 0;

    CRGB leds[NUM_STRIPS * NUM_LEDS_PER_STRIP];
    CRGB row_1[64];
    CRGB row_2[64];
    CRGB row_3[64];
    CRGB row_4[64];
    CRGB row_5[64];
    CRGB row_6[64];
    CRGB row_7[64];
    CRGB row_8[64];

    void setup() {
      FastLED.addLeds<PL9823, 4>(row_1, 0, NUM_LEDS_PER_STRIP);
      FastLED.addLeds<PL9823, 5>(row_2, 0, NUM_LEDS_PER_STRIP);
      FastLED.addLeds<PL9823, 6>(row_3, 0, NUM_LEDS_PER_STRIP);
      FastLED.addLeds<PL9823, 7>(row_4, 0, NUM_LEDS_PER_STRIP);
      FastLED.addLeds<PL9823, 8>(row_5, 0, NUM_LEDS_PER_STRIP);
      FastLED.addLeds<PL9823, 9>(row_6, 0, NUM_LEDS_PER_STRIP);
      FastLED.addLeds<PL9823, 10>(row_7, 0, NUM_LEDS_PER_STRIP);
      FastLED.addLeds<PL9823, 11>(row_8, 0, NUM_LEDS_PER_STRIP);

    }

Does anyone know how I can make this setup run a spinning wheel of fading color values in the form of a spinning rainbow? I'm hoping to use suggestions as a place to start to build other patterns with and without rainbows as well and I'm a bit of a noob, so an explanation is appreciated.

title: FastLED Rainbow Wheel Fade on an 8 Pin RGB Matrix

Answers: 0


body:
[![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

title: Can't flash ESP 32 Wroom

Answers: 2

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#


body:
```
////*************************************************************************
////----------------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;

 }
}
```

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

Answers: 2

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.


body:
I don't know how to connect 3 MPU9250 together on Node Mcu. There is not much information available. I am using bolder flight library for imu sensor - [https://github.com/bolderflight/MPU9250][1]

  [1]: https://github.com/bolderflight/MPU9250

Can anyone post the image of connection on sensor and example of code? Thanks a lot.

title: How to connect 3 MPU9250 to Node Mcu together?

Answers: 0


body:
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?
      }
    }

title: Program Arduino via UART from ESP8266 SPIFFS

Answers: 1

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


body:
I wrote a code that can send a file.
If I send a text file it will work perfectly, but when I try to send voice it will send the whole file form the Sender side, but in the receiver side he won't understand some data or he won't read it i don't know what happened
i tried to send 50k byte and the  receiver only receive 20K
. I tried to send .wav .mp3 .m4p.

the Sender code

    #include <Ethernet.h>
    #include <EthernetUdp.h>
    #include <SPI.h>
    #include <SD.h>

    const int push1 = 2;

    File myFile;
    char a[168];
    int c= 0;
    int counter = 0 ;
    unsigned long data;
    unsigned long result;
    unsigned long remaining ;

    // network parameters
    byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x05, 0x02 };  // ethernet interface MAC address
    IPAddress localIp(10,131,41,72);    // local ip address
    IPAddress destIp(10,131,41,74);      // destination ip address
    unsigned int port = 9631;               // destination port

    // EthernetUDP to send and receive messages.
    EthernetUDP Udp;

    // timing

    // setup the arduino and shields
    void setup() {

        pinMode(push1, INPUT);

      //Initialize serial and wait for port to open:
      Serial.begin(9600); // 19200
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.print("Initializing SD card...");

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }
      Serial.println("initialization done.");

      // start ethernet and udp
      Ethernet.begin(mac, localIp);   // static ip version
      //if(Ethernet.begin(mac) == 0) {     // dhcp version
      // report failure to obtain network parameters
      // Serial.println("DHCP error");

      // no point in carrying on, loop indefinitely:
      // while(true)
      // ;
      //}

      // open UDP port
      Udp.begin(port);

      // show the local ip address (useful for dhcp)
      Serial.print("Local IP: ");
      Serial.println(Ethernet.localIP());

    }

    // do tasks
    void loop() {

    if(digitalRead(push1) == LOW){

        myFile = SD.open("SV12.wav");
         data = myFile.size();

    //     result = myFile.position();

      if (myFile) {
        Serial.println("inside the file there's");
        // read from the file until there's nothing else in it:
        while (myFile.available()) {
          a[c] = myFile.read();
           Serial.print(a[c]);
           c++;
          if ( c==168){
            Serial.println("");
          Serial.println("i will send now");
          Udp.beginPacket(destIp, port);
          Udp.write(a,168);
          Udp.endPacket();
          delay(250);
          Serial.println("Sending UDP message");
           counter++;
           Serial.print("Sending packet#");
           Serial.println(counter);
    //         for (int x = 0 ; x<c ; x++){
    //
    //         a[x] = '\0';}
             c=0;

      Serial.println("clearing");}

    //  Serial.println(result);
        }

              if ( c<168 ){ // if (remaining)
          Serial.println("i will send now");
          Udp.beginPacket(destIp, port);
          Udp.write(a,168);
          Udp.endPacket();
          Serial.println("Sending UDP message Last segment");
    //      counter++;
    //         for (int x = 0 ; x<c ; x++){
    //
    //         a[x] = '\0';}
             c=0;}

        // close the file:
        myFile.close();
         Serial.println("im here");
        Serial.println(counter);
        Serial.println("END");
      } else {
       // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
     }

    }
    }

  the Reciver code

    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>
    #include <SD.h>

    int LED = 8;
    int x=0;

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x06
    };
    IPAddress ip(10,131,41,74);
    IPAddress remIp(10,131,41,72);

    unsigned int localPort = 9631;      // local port to listen on // 123456

    File myFile;
    char y[100];
    int c= 0;

    // An EthernetUDP instance to let us send and receive packets over UDP
    EthernetUDP Udp;

    char packetBuffer[168]; //buffer to hold incoming packet,
    //UDP_TX_PACKET_MAX_SIZE
    void setup()
    {
      // start the Ethernet and UDP:
      Ethernet.begin(mac, ip);
      Udp.begin(localPort);
      pinMode(LED, OUTPUT);
      Serial.begin(9600);//change and try
      Serial.print("Local IP: ");
      Serial.println(Ethernet.localIP());

        if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }
      Serial.println("initialization done.");

    }

    void loop()
    {

      int packetSize = Udp.parsePacket();

      if (packetSize)
      {
        Serial.print("Received packet of size ");
        Serial.println(packetSize);
        Serial.print("From ");
        IPAddress remote = Udp.remoteIP();
        for (int i = 0; i < 4; i++)
        {
          Serial.print(remote[i], DEC);
          if (i < 3)
          {
            Serial.print(".");
          }
        }
        Serial.print(", port ");
        Serial.println(Udp.remotePort());

        // read the packet into packetBufffer
        Udp.read(packetBuffer, 168);
        Serial.println("Contents:");

        RandS();
        Serial.println(x); //to check the message

      }

    }

    void RandS(){

       myFile = SD.open("Last123.mp3", FILE_WRITE);

      // if the file opened okay, write to it:
      if (myFile) {
        Serial.println("i'm Writing what i got from UDP");
        myFile.print(packetBuffer);
        x++;
        // close the file:
        myFile.close();

        Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }

    }

Can someone help please?

title: I got a problem in sending voice file

Answers: 0


body:
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

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

Answers: 3

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


body: 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.

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

Answers: 1

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).


body:
/*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);
    }

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

Answers: 1

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);
       }
    }


body:
So, I have a very basic project where I cycle through 8 IR individual transmitters. After setting the individual transmitter high, I cycle through all 8 IR receivers and print their values, RX_CYCLES many times. I need a huge amount, quality data from these loops to train a neural net, so
I want to optimize my code to where I can `analogRead` each receiver the fastest, but keep the maximum resolution possible.

I'm having trouble understanding Teensy's documentation and provided libraries and finding any relevant resources that are clear enough for me to weave through the jargon.
___
My questions are:

 1. What would be or how do I go about calculating the optimization or balance of the fastest baudrate I can match with the Teensy 3.6, with the highest quality resolution possible?
 2. How to optimize `analogRead`? I've read that the fastest way is to use continuous `analogRead` instead of single `analogRead`? I'm having trouble finding clear examples of what this actually does and how to use it effectively. I definitely could be wrong about it this.
 3. Am I outputting data the best way possible? I was wondering if there would be any reason in my case to use `print()` or `println()` or if I should be using `flush()` after every cycle

___
These are a lot of questions, and I don't expect anyone to optimize my code for me, so if you can help point me in the direction of clear material I can use to direct me in this problem.

I'd also really appreciate any other suggestions or insight anyone would like to offer that I may be missing.

___
 This is my very basic code:

    const uint8_t RX_CYCLES = 1;
    const uint8_t RX_START = 14, RX_END = 21;
    const uint8_t TX_START = 0, TX_END = 7;

    void setup() {
        Serial.begin(115200);
        while (!Serial);
        for (uint8_t reciever = RX_START; reciever <= RX_END; reciever++) pinMode(reciever, INPUT);
        for (uint8_t transmitter = TX_START; transmitter <= TX_END; transmitter++) pinMode(transmitter, OUTPUT);
    }

    void loop() {
        for (uint8_t transmitter = TX_START; transmitter <= TX_END; transmitter++) {
            digitalWriteFast(transmitter, HIGH);
            for (uint8_t i = 0; i < RX_CYCLES; i++) {
                for (uint8_t reciever = RX_START; reciever <= RX_END; reciever++) Serial.println(analogRead(reciever));
            }
            digitalWriteFast(transmitter, LOW);
        }
    }

title: Optimizing Teensy 3.6 for data sampling?

Answers: 0


body:
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);
      }
    }

title: Need little bit of help on testing I2C sketch

Answers: 2

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


body:
I'm thinking of using something like this: https://www.amazon.ca/Dolity-Converter-Isolated-Switching-Transformer/dp/B07CSZ1174?SubscriptionId=AKIAILSHYYTFIVPWUY6Q&tag=duc12-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=B07CSZ1174

or this: https://www.amazon.ca/Voltage-Regulator-Converter-Transformer-Protection/dp/B07LC1C4ZZ?SubscriptionId=AKIAILSHYYTFIVPWUY6Q&tag=duc12-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=B07LC1C4ZZ

to power my arduino.

The reason for this is I have a contained box with a few pieces of equipment (all on ac power) controlled by an Uno. There is a single AC power cord (North American) running from the box to power the whole unit. Obviously this just leaves the Uno.

Sure the standard 5V barrel adapter prongs could be shrink wrapped to the raw AC wires but that's not very clean. I was imagining a module like those converters that could be wired into the VIN pin and gnd after converting the AC input from the main power line going to the box.

The uno is powering an ethernet shield, 4 port relay, sht20 sensor, mh-z16 sensor, and 16x2 lcd display.

Thoughts? Honestly this isn't really my call. My boss doesn't want any plugs or standard outlets inside the box. It's like he only wants it to be formal circuit boards and soldering. No shrink wrap or electrical tape. Yes I realize standard adapters that plug into a wall are already at a price that won't be possible to beat.

title: Will this buck converter power my arduino?

Answers: 1

body:
> Sure the standard 5V barrel adapter prongs could be shrink wrapped to the raw AC wires but that's not very clean.

Also very deadly.  **DO NOT DO THIS!!!!**  The Arduino will explode (literally. I am **NOT** joking here!!!) and potentially electrocute you.

----

Those modules you show are not "buck" regulators. They are SMPS modules - an entirely different thing.

Yes, one of those would be suitable for powering an Arduino from a mains supply, but given your supposition above I rather suspect your skills and knowledge would make wiring it up a dangerous prospect.

Better would be to use a proper off-the-shelf power plug and have someone qualified install a suitable socket inside the enclosure.


body:
I followed this guy's [guide][1] with regards to wiring, etc., and all I seem to be getting is a white screen, as shown in these [pictures][2]. Is there an issue with the guy's guide, I'm missing or there is an issue with my wiring (pictures also included in above link) Any help would be appreciated.

  [1]: http://henrysbench.capnfatz.com/henrys-bench/arduino-displays/1-8tft-v1-0-st7736-arduino-tutorial-1-hello-world/
  [2]: https://i.stack.imgur.com/xjc9C.jpg

title: What am I missing? ST7735 TFT white screen

Answers: 0


body:
I want to control a servo motor in a way that

- if you push the button, you can control it by potentiometer a
- if you push double time, you can control servo with infrared
- if you hold button step motor start to to rotate from one position to another

I have a problem that when I press button it goes to an infinite loop and I can not stop it .
I try different button library but I still have a same problem.
Here is my code :

    // includes the Servo library
    #include <Servo.h>
    #include <IRremote.h>
    #include <OneButton.h>

    int state = 0;
    int RECV_PIN = 12;
    const char type ='W';// W for white, B for black. Must keep single quotes like 'B' or 'W'
    const boolean PCB = 0;// if receiver is PCB set to 1, if not set to 0. See video for details
    boolean displayCode = true;// to display remote code. if not, set to false

    const int SERVO_PIN = 8;  // analog pin used to connect the potentiometer
    int angle =90;    // initial angle  for servo
    int angleStep =10;
    const int ANGLE_CENTRE =90;// the centre/reset angle of your servo
    //**** Servo settings settings ends

    // remote settings
    const String RIGHT="CH+";// move servo to the right with this key on remote
    const String LEFT ="CH-";// move servo to the left with this key on remote
    const String CENTRE ="CH";// move servo to centre with this key on remote
    // remote settings end

    IRrecv irrecv(RECV_PIN);
    // Defines Tirg and Echo pins of the Ultrasonic Sensor
    const int trigPin = 10;
    const int echoPin = 11;
    const int potPin = 0;
    const int pushButton = 8;
    OneButton button(A1, true);
    int value;

    // Variables for the duration and the distance
    long duration;
    int distance_cm;
    Servo myServo; // Creates a servo object for controlling the servo motor

    // this is array holding codes for White Remote when used with non-PCB version of receiver
    unsigned int whiteRemote[] ={
                0xFFA25D, // CH-
                0xFF629D,   // CH
                0xFFE21D,  // CH+

                0xFF22DD, // |<<
                0xFF02FD, // >>|
                0xFFC23D, // >||

                0xFFE01F, // -
                0xFFA857, // +
                0xFF906F, // EQ

                0xFF6897, // 0
                0xFF9867, // 100+
                0xFFB04F, // 200+

                0xFF30CF, // 1
                0xFF18E7, // 2
                0xFF7A85, // 3

                0xFF10EF, // 4
                0xFF38C7, // 5
                0xFF5AA5,  // 6

                0xFF42BD, // 7
                0xFF4AB5, // 8
                0xFF52AD  // 9
                };
    // key lables of white remote
     String whiteRemoteKey[] ={
                "CH-",
                "CH",
                "CH+",

                "|<<",
                ">>|",
                ">||",

                "-",
                "+",
                "EQ",

                "0",
                "100+",
                "200+",

                "1",
                "2",
                "3",

                "4",
                "5",
                "6",

                "7",
                "8",
                "9"
                };

    // this is array holding codes for Black Remote when used with non-PCB version of receiver
     unsigned int blackRemote[] ={
                0xFF629D, // ^
                0x38D3975C,   // <
                0x9334F738,  // OK
                0x320412D8, // >
                0xFFA857, // v

                0xFF6897, // 1
                0xFF9867, // 2
                0xF0C41643, // 3

                0xFF30CF, // 4
                0xFF18E7, // 5
                0xFF7A85,  // 6

                0xFF10EF, // 7
                0xFF38C7, // 8
                0xFF5AA5,  // 9

                0xFF42BD, // *
                0xFF4AB5, // 0
                0xFF52AD  // #
                };
    // Black remote key names
     String blackRemoteKey[] ={
                "^",
                "<",
                "OK",
                ">",
                "v",

                "1",
                "2",
                "3",

                "4",
                "5",
                "6",

                "7",
                "8",
                "9",

                "*",
                "0",
                "#"
                };

    decode_results results;

    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an input
      Serial. begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      myServo.attach(SERVO_PIN); // Defines on which pin is the servo motor attached

      button.attachDoubleClick(doubleClick);            // link the function to be called on a doubleClick event.
      button.attachClick(singleClick);                  // link the function to be called on a singleClick event.
      button.attachLongPressStop(longClick);            // link the function to be called on a longpress event.

    }
    void loop() {
      button.tick();                                    // check the status of the button
      delay(10);                                        // a short wait between checking the button
    }

    // Function for calculating the distance measured by the Ultrasonic sensor
    int calculateDistance(){
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      // Sets the trigPin on HiGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
      //Comment by me!
      //distance= duration*0.034/2;
      //
      distance_cm = (duration/2) / 29.1;
      return distance_cm;
    }
    void doubleClick() {                                // what happens when button is double-clicked
      while(1) {
        if (irrecv.decode(&results)) {
          if(displayCode)Serial.println(results.value, HEX);
          validateCode(results.value);// used the "robojaxValidateCode" bellow
          irrecv.resume(); // Receive the next value
        }
        delay(50);// 50 melisecond delay
        break;
      }
    }

    void singleClick(){                                 // what happens when the button is clicked
      while(1) {
        value = analogRead(potPin);
        value = map(value, 0, 1023, 15, 165);
        myServo.write(value);
        delay(30);
        distance_cm = calculateDistance();

        Serial.print(value); // Sends the current degree into the Serial Port
        Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing iDE for indexing
        Serial.print(distance_cm); // Sends the distance value into the Serial Port
        Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing iDE for indexin
      }
    }

    void longClick(){                                   // what happens when buton is long-pressed
      for(int i=15;i<=165;i++){
        myServo.write(i);
        delay(30);
        distance_cm = calculateDistance();// Calls a function for calculating the distance measured by the Ultrasonic sensor for each degree

        Serial.print(i); // Sends the current degree into the Serial Port
        Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing iDE for indexing
        Serial.print(distance_cm); // Sends the distance value into the Serial Port
        Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing iDE for indexin
      }
      // Repeats the previous lines from 165 to 15 degrees
      for(int i=165;i>15;i--){
        myServo.write(i);
        delay(30);
        distance_cm = calculateDistance();

        Serial.print(i);
        Serial.print(",");
        Serial.print(distance_cm);
        Serial.print(".");
      }
    }
    /*
     * function: validateCode
     * validates the remote code and prints correct key name
     * cd is code poassed from the loop
     * Written by A. S. for Robojax
     */
    void validateCode(int cd)
    {

      // Robojax IR Remote decoder
      int found=0;

     if(type =='W' && !PCB)
     {
        // Robojax IR White Remote decoder
        // if tyepe is set to 'W' (white remote) and PCB=0 then check Black remote code
          for(int i=0; i< sizeof(whiteRemote)/sizeof(int); i++)
          {
            if(whiteRemote[i] ==cd)
            {

              Serial.print("Key pressed:");
              Serial.println(whiteRemoteKey[i]);
              servoAction(whiteRemoteKey[i]);// take action
              found=1;
            }// if matched
          }// for
     }else{

          // if tyepe is set to 'B' (black remote) and PCB =0 then check Black remote code
           for(int i=0; i< sizeof(blackRemote)/sizeof(int); i++)
          {
            // Robojax IR black Remote decoder
            if(blackRemote[i] ==cd)
            {

              Serial.print("Key pressed:");
              Serial.println(blackRemoteKey[i]);
              servoAction(blackRemoteKey[i]);// take action

              found=1;
            }// if matched
          }// for
     }// else
      if(!found){
        if(cd !=0xFFFFFFFF)
          {
        Serial.println("Key unkown");
          }
      }// found
    }// validateCode end

    /*
     *
     * servoAction()
     * receives string "value" as input and based on the settings,
     * sends translates it to servo value and controls servo
     * either
     * rotates servo to right
     * rotates servo to left
     * moves the servo to middle
     *
     */
    void servoAction(String value){
      // Servo button demo with IR remote by Robojax.com
      while(value == RIGHT){

        if (angle > 0 && angle <= 180) {
          angle = angle - angleStep;
           if(angle < 0){
            angle = 0;
           }else{
          myServo.write(angle); // move the servo to desired angle
          Serial.print("Moved to: ");
          Serial.print(angle);   // print the angle
          Serial.println(" degree");
           }
        }// if
        value =".";
        delay(100);
      }// while for RIGHT
      while(value == LEFT){

        // Servo button demo with IR remote by Robojax.com
        if (angle >= 0 && angle <= 180) {
          angle = angle + angleStep;
          if(angle >180){
            angle =180;
           }else{
          myServo.write(angle); // move the servo to desired angle
          Serial.print("Moved to: ");
          Serial.print(angle);   // print the angle
          Serial.println(" degree");
           }
        }
        value =".";
        delay(100);
      }// while for LEFT

      if(value == CENTRE)
      {
        angle = ANGLE_CENTRE;
        myServo.write(angle); // move the servo to centre at 90 degree angle
      }
        // Robojax IR Servo control
    }//relayAction end

sorry about my English.
I hope someone help me.

title: Hold button / press button/ push button

Answers: 1

body:
You have infinite loops in the click event call functions, after a button event you never return to the main loop.

Use the event functions just to set a status variable then, in the main loop use switch case case to select the code used by the servo control like this:

     ....
     unsigned int status = 0;
     ....
     void doubleClick(){
        status = 0;
     }
     void singleClick(){
        status = 1;
     }
     void longClick(){
        status = 2;
     }
     void setup() {
     ....
     }
     void loop {
       button.tick();                                    // check the status of the button
       //delay(10); // this is not needed.
       switch (status){
         case 0:{
           //action for double click
         }
         case 1:{
           //action for single click
         }
         case 2:{
           //action for long click
         }
     }

Inside each case insert the corresponding code code you have in the while(1) loops of the button event functions.

Another option is to insert inside the forever loops a return when the button is pressed like this:

  if (button pressed)  return;


body:
I am trying to implement cascaded control system, with velocity inner loop and position outer loop.

Separately and without cascaded control, I have implemented position control and velocity control easily, thanks to the "pid library."

I have no idea how to convert position output from position pid to reference velocity.

Any help would be appreciated, since I am blank on this topic.
Thanks and best regards

![enter image description here](https://i.stack.imgur.com/TlAlo.jpg)

title: Cascaded Control loop Arduino

Answers: 1

body:
This is not an Arduino specific topic, but here is just a pragmatic answer:

Use the output of the PID controller directly as your reference velocity, subtract your actual velocity and use it as input for the PID velocity. Units do not care in this case.

You have to make sure that the paramters of your PID position are well adjusted, this will set the problem with the units.

Here is an example to understand (only P gain considered):

If you want to drive from A to B with your car and the distance from A to B is 10 km, then your desired position is 10km and i would choose to drive about 100km/h. So in this example you start with a control deviation of 10km - 0km = 10km. If you choose a P gain of 10 the output of the PID will be 100, which is an ideal refernce Velocity, if velocity is given in km/h.

But if you are measuring your distance not in km but in m, the control deviation will be (10.000m - 0m = 10.000m), with a P gain of 10 you will end up with a refernce velocity of 100.000km/h, which is not an appropriate reference velocity in this case.

Now someone may object that in my example if you want do drive from A to C and C is 1.000km away, you will end up with an reference velocity of 10.000km/h, which is also not appropriate, but that is where the limitations in a PID controller are usefull, just set them for this example to 130km/h and you will end up stil with an appropriate reference velocity, and also your integrator part will not wind up endlessly.

You can look at I and D gain in a similar manner.


body:
I can't seem to figure out what the numbers after 0x27 mean. I understand that 0x27 stands for the I2C address and POSITIVE stands for the backlight, but what do the other number mean?

> LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE)

title: What do the numbers behind lcd (0x27) mean?

Answers: 1

body:
Assuming You're using the same LCD library I'm using, there is a longer form of the constructor that takes pin assignments for the different pins on the I2C module, as Majenko says.

I'm at work, so I don't have access to my code, but your constructor looks a whole lot like the one I use for my module, which has non-standard pin assignment. (I got my LCD modules from oddWires, and they came without documentation. I had to do quite a bit of detective work to figure out how to make them work.)

**EDIT**

I use the Newliquidcrystal_1.3.5 library in my project, to interface the above-mentioned oddWires I2C LCD display. That library has various constructors, one of which takes all the parameters you list. Those extra numbers indicate the pins that connect to the I2C module.

My oddWires LCDs need exactly the settings you list in the constructor. Your milage may vary.

The long form is defined in the library header with

    LiquidCrystal_I2C(
        uint8_t lcd_Addr,
        uint8_t En,
        uint8_t Rw,
        uint8_t Rs,

        uint8_t d4,
        uint8_t d5,
        uint8_t d6,
        uint8_t d7,
        uint8_t backlighPin,
        t_backlighPol pol
    );

From the naming of the parameters you can deduce most of them:

 - En is an enable line
 - Rw is a read/write line?
 - Rs is ?
 - d4-47 are the data pins
 - backlightPin is the pin that turns backlight on and off
 - pol indicates the backlight polarity (`POSITIVE` probably means pull the line high to enable the backlight.


body:
I am using an Arduino Uno and a USB Host shield for Barcode Scanner. The whole scenario is that when I scan the barcode through USB Barcode Scanner, it scans and gives a code. Now the question is how to connect the ESP8266 with the USB Host Shield to transfer data to the web server. I have set the pins to 2, 3 for receiving data from server. Send Data and Receive data with ESP8266.

The Arduino Code:

    #include <SoftwareSerial.h>
    #include <hid.h>
    #include <hiduniversal.h>
    #include <LiquidCrystal.h>
    #include <avr/pgmspace.h>
    #include <Usb.h>
    #include <usbhub.h>
    #include <avr/pgmspace.h>
    #include <hidboot.h>
    String result = "";
    #define DISPLAY_WIDTH 16

    // initialize the LCD library with the numbers of the interface pins
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
    SoftwareSerial esp(3, 2);

    USB     Usb;
    USBHub     Hub(&Usb);
    HIDUniversal Hid(&Usb);
    HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);

    class KbdRptParser : public KeyboardReportParser
    {
     void PrintKey(uint8_t mod, uint8_t key);
    protected:
      virtual void OnKeyDown  (uint8_t mod, uint8_t key);
      virtual void OnKeyPressed(uint8_t key);
    };

    void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
    {

        uint8_t c = OemToAscii(mod, key);

        if (c)
            delay(100);
           OnKeyPressed(c);

    }

    /* what to do when symbol arrives */
    void KbdRptParser::OnKeyPressed(uint8_t key)
    {
    static uint32_t next_time = 0;      //watchdog
    static uint8_t current_cursor = 0;  //tracks current cursor position

        if( millis() > next_time ) {
          lcd.clear();
          result = "";
          current_cursor = 0;
          delay( 5 );  //LCD-specific
          lcd.setCursor( 0,0 );
        }//if( millis() > next_time ...

        next_time = millis() + 200;  //reset watchdog

        if( current_cursor++ == ( DISPLAY_WIDTH + 1 )) {  //switch to second line if cursor outside the screen
          lcd.setCursor( 0,1 );
        }

     result += (char)key;//Serial.print("Result "+result+"\n");
     delay( 50 );
        //Serial.print((char)key );
        //lcd.print((char)key );
    };

    KbdRptParser Prs;

    void setup()
    {
        Serial.begin(9600);
        Serial.println("Start");
        esp.begin(115200);
        if (Usb.Init() == -1) {
            Serial.println("OSC did not start.");
        }

        delay( 200 );

        Hid.SetReportParser(0, (HIDReportParser*)&Prs);
        // set up the LCD's number of columns and rows:
        lcd.begin(DISPLAY_WIDTH, 2);
        lcd.clear();
        lcd.noAutoscroll();
        lcd.print("Ready");
        delay( 200 );

    }

    void loop()
    {
      String content = "";
      char character;
      Usb.Task();
      if(result != ""){
        delay(10);
        Serial.println(result);
        }
       /*while(Serial.available()){
        character = Serial.read();
        content.concat(character);
        Serial.print("Serial Result : "+content);

        }*/
        if (esp.available())
       {

        char c = esp.read();
        if(isDigit(c)){
          lcd.clear();
          lcd.print(c);
            Serial.print(c);

           }
        }

    }
The ESP8266 Code is:

    #include <ESP8266WiFi.h>

    const char* ssid     = "stormfiber"; //Wi-Fi SSID
    const char* password = "11223344"; //Wi-Fi Password

    //Server IP or domain name
    const char* host = "192.168.100.228";
    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(9600);
      WiFi.begin(ssid, password);
      Serial.println(ssid);
      while (WiFi.status() != WL_CONNECTED) { //Wait till connects
        delay(500);
        Serial.print(".");
      }

    }

    void loop()
    {
      char character;
      String content = "";
      delay(5000);

      //Serial.print("connecting to ");
      //Serial.println(host);
      while(Serial1.available()){
        character = Serial1.read();
        content.concat(character);
        }
        if(content == ""){
          content = "123";
         }
      WiFiClient client; //Client to handle TCP Connection
      const int httpPort = 2124;
      if (!client.connect(host, httpPort)) { //Connect to server using port httpPort
        Serial.println("connection failed");
        return;
      }

      // We now create a URI for the request
      String url = "/test/index.php?code="+content; //File or Server page you want to communicate with. along with data

      // This will send the request to the server
      client.print(String("GET ") + url + "\r\n");

      unsigned long timeout = millis();
      while (client.available() == 0) {
        if (millis() - timeout > 25000) { //Try to fetch response for 25 seconds
          Serial.println(">>> Client Timeout !");
          client.stop();
          return;
        }
      }

      // Read all the lines of the reply from server and print them to Serial
      while(client.available()){
        String line = client.readStringUntil('\r');
        Serial.print(line);
      }
      Serial.println();
      //Serial.println("closing connection");
      client.stop(); //Close Connection
      /*static unsigned long timer = 0;
      unsigned long interval = 5000;
      static unsigned int index = 0;
      if (millis() - timer >= interval)
      {
        timer = millis();
        Serial.print("The index ");
        Serial.println(index);
        index++;
      }*/
    }
Please help how to connect the ESP8266 with the host shield. Although it works fine with Arduino only.
Any help regarding this will be appreciated.
Thanks

title: Arduino + USB Host Shield + ESP8266

Answers: 0


body:
I try to communicate with 2 RS485 sensors (pH and EC), but I have some troubles with my code. First, I tried to get data from just one:

The function in charge of request sending:

    String GET_probe(String probe){

    if(probe == "pH"){
    Serial.println("Sending request pH...");
    digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
    digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
    byte  RTUrequest[] = {0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x85, 0xDB};
    RS485Serial.write(RTUrequest, sizeof(RTUrequest));
    }

    if(probe == "EC"){
    Serial.println("Sending request EC...");

    digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
    digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
    byte  RTUrequest[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
    RS485Serial.write(RTUrequest, sizeof(RTUrequest));
    }

    RS485Serial.flush();
    RS485Serial.listen();
    }

The function in charge of reading sensor's answer:

    void ReadRx() {
         digitalWrite(modbusModuleRE, RS485Receive);
         digitalWrite(modbusModuleDE, RS485Receive);
         if(RS485Serial.available()) {
         Serial.print("Answer: ");
          for(int i=0; i<7; i++){
              String myByte = String(RS485Serial.read(), HEX);// Read the byte

              if (myByte.length() == 1)
              {
                myByte = "0"+myByte;
              }
              modbusHexBuffer[i] = myByte;

              Serial.print(myByte);
              Serial.print(" ");
          }
          Serial.println();
        }
       }

And the loop, sending the request each 5s:

    void loop(){

      static uint32_t ts = millis();

      if (millis() - ts >= 5000) {
          ts = millis();
          GET_probe("pH");
      }

    ReadRx();
    }

The loop runs fine once and fails the second time, as shown in terminal. Can you tell me why and help me to fix it?

    Sending request pH...
    Answer: 00 03 02 05 78 86 f6
    Sending request pH...

title: Cannot read modbus data repetitively

Answers: 1

body:
I have found why !!!

1st: buf[8] instead buf[7] in declaration
2nd: reinit byte buf[8] before EC request part.

So the code who works fine is:

    byte buf[8];
    void loop(){

          Serial.print("pH: ");
          digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
          digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
          byte  pHrequest[] = {0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x85, 0xDB};
          RS485Serial.write(pHrequest, sizeof(pHrequest));
          RS485Serial.flush();
          digitalWrite(modbusModuleRE, RS485Receive);
          digitalWrite(modbusModuleDE, RS485Receive);
          RS485Serial.readBytes(buf, 8);
         Serial.print(buf[3], HEX);Serial.println(buf[4], HEX);

    byte buf[8];

          Serial.print("EC: ");
          digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
          digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
          byte  ECrequest[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
          RS485Serial.write(ECrequest, sizeof(ECrequest));
          RS485Serial.flush();
          digitalWrite(modbusModuleRE, RS485Receive);
          digitalWrite(modbusModuleDE, RS485Receive);
          RS485Serial.readBytes(buf, 8);
          Serial.print(buf[3], HEX);Serial.print(buf[4], HEX);Serial.print(buf[5], HEX);Serial.println(buf[6], HEX);

    Serial.println();

    }


body:
Name of study: AUTOMATIC ELECTRIC FAN

We used an ultrasonic sensor for the switching on/off of our Fan and an LM35 SENSOR to control the speed regulation.
During our experiment, we use a LED instead of a Fan before we proceed to fan. Here is our code:

Description: Codes for LM35 Sensor using LED and Arduino Uno as Microcontroller)

    #define led 9
    float temp;

    void setup ()
    {
       pinMode(led, OUTPUT);
       Serial.begin(9600);
    }

     void loop ()
    {
        temp = analogRead (A0);
        temp = temp*0.48828125;
         if (temp < 31 )
      {
        digitalWrite(led, HIGH);
      }
      else {

        digitalWrite(led, LOW);
      }
        Serial.print("TEMPERATURE: ");
        Serial.print(temp);
        Serial.print("*C");
         Serial.println();
         delay(1000);
     }

Description: Code for ULTRASONIC SENSOR using two LED’s AND Arduinbo Uno as Microcontroller

    #define trigPin 13
    #define echoPin 12
    #define led 6
    #define led 5
    {
      digitalWrite(trigPin, LOW);
      delayMicroseconds (2);

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

      duration = pulseIn(echoPin, HIGH);
      distance = duration*0.034/2;
      if (distance < 100 )
      {
        digitalWrite(led, HIGH);
      }
      else {

        digitalWrite(led, LOW);
      }
      Serial.print("Distance:");
      Serial.println(distance);
      Serial.print("cm");
      delay(1000);
    }

title: How should I combine the codes for two sensors in 1 Arduino sketch?

Answers: 1

body:
You don't have two codes; the 2nd section has no setup() or loop().

If it did, then you could do this:

- The stuff before setup() gets put together.
- The stuff in setup() from one gets moved into the other. The empty setup() gets deleted.
- The stuff in loop() from one gets moved into the other. The empty loop() gets deleted.

Take care of any duplicate names, pin assignments, etc.

Review the combined loop() code and adjust as needed to do what you want.