body:
I'm getting the following error when I try to enroll fingerprints using the Arduino Mega 2560 microcontroller along with a Fingerprint Scanner:

> Did not find fingerprint sensor :(

The exact devices I'm using are as shown in the links below:

https://www.gearbest.com/development-boards/pp_70487.html?lkid=11637831
https://www.gearbest.com/boards-shields/pp_009769796663.html?wid=1433363

My circuit connection is:

- (Green) TX  => Pin 0 [PWM]

- (White) RX => Pin 1 [PWM]

//It doesn't respond when connected to 5V, it only heats up

- (Red) VCC  => 3.3v

- (Black) GND => GND

The connection is illustrated below:

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

The code is shown below:

    #include <Adafruit_Fingerprint.h>

    // On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
    // uncomment this line:
     #define mySerial Serial1

    // For UNO and others without hardware serial, we must use software serial...
    // pin #2 is IN from sensor (GREEN wire)
    // pin #3 is OUT from arduino  (WHITE wire)
    // comment these two lines if using hardware serial
    //#include <SoftwareSerial.h>
    //SoftwareSerial mySerial(10, 11);

    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    uint8_t id;

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);  // For Yun/Leo/Micro/Zero/...
      delay(100);
      Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

      // set the data rate for the sensor serial port
      finger.begin(57600);

      if (finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
      } else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) { delay(1); }
      }
    }

    uint8_t readnumber(void) {
      uint8_t num = 0;

      while (num == 0) {
        while (! Serial.available());
        num = Serial.parseInt();
      }
      return num;
    }

    void loop()                     // run over and over again
    {
      Serial.println("Ready to enroll a fingerprint!");
      Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
      id = readnumber();
      if (id == 0) {// ID #0 not allowed, try again!
         return;
      }
      Serial.print("Enrolling ID #");
      Serial.println(id);

      while (!  getFingerprintEnroll() );
    }

    uint8_t getFingerprintEnroll() {

      int p = -1;
      Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger.image2Tz(1);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      Serial.println("Remove finger");
      delay(2000);
      p = 0;
      while (p != FINGERPRINT_NOFINGER) {
        p = finger.getImage();
      }
      Serial.print("ID "); Serial.println(id);
      p = -1;
      Serial.println("Place same finger again");
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.print(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger.image2Tz(2);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      Serial.print("Creating model for #");  Serial.println(id);

      p = finger.createModel();
      if (p == FINGERPRINT_OK) {
        Serial.println("Prints matched!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_ENROLLMISMATCH) {
        Serial.println("Fingerprints did not match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      Serial.print("ID "); Serial.println(id);
      p = finger.storeModel(id);
      if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
      } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }
    }

I used the Adafruit Fingerprint library found here:

https://github.com/adafruit/Adafruit-Fingerprint-Sensor-Library

I also soldered the wires from the sensor onto Male Pin Headers for greater connection stability.

All I get is the fingerprint sensor blinking continuously which makes me think it's not faulty but when I try to run the enroll code I get the error message highlighted above.

I also tried connecting using the Software Serial approach like below but that wasn't the solution either:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11);

What could be the problem? Is my connection and code okay? Anyone have an idea on how to fix this?

The heat occurs on the encircled area below:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/fn5wj.png
  [2]: https://i.stack.imgur.com/EhdCJ.jpg

title: Did not find fingerprint sensor :( Arduino Mega 2560 Adafruit Fingerprint Sensor

Answers: 1

body:
Thanks for your responses @HavocRC and @Juraj

I've successfully come to the following working parameters that I have tested and have given positive results:

> **When using Arduino Mega 2560 with the SFG Demo, we use:**
>
> (Green) TX  => Pin 1
>
> (White) RX => Pin 0
>
> (Red) VCC  => 5V
>
> (Black) GND => GND
>
>
> **When using Arduino Mega 2560 with the Adafruit Library, we use:**
>
> **Using Hardware Serial Port (Serial1) [Recommended]**
>
> (Green) TX  => Pin 19
>
> (White) RX => Pin 18
>
> (Red) VCC  => 5V
>
> (Black) GND => GND
>
> //Note that you'll comment out the Software Serial initialization
>
> //as directed by the code in the Adafruit Library
>
>     #define mySerial Serial1
>
>
> **When using Arduino Mega 2560 with the Adafruit Library, we use:**
>
> **Using Software Serial**
>
> (Green) TX  => Pin 10
>
> (White) RX => Pin 11
>
> (Red) VCC  => 5V
>
> (Black) GND => GND
>
> //The order of the PINs in the code is
>
>     SoftwareSerial mySerial(10, 11);

In the process of testing I also used an older version of Arduino IDE, version 1.0.5 which may have helped to get the sensor working (just a hunch). It turns out the sensor only works with 5V although it heats up a bit (not to fiery levels at a go but I wouldn't leave it turned on if I was away from my laptop for a while).

By the way, for the SFG Demo to work, upload the 'blank' example first, close Arduino and then run SFG Demo. If it works then your fingerprint scanner is in working order.

For the hardware Serial options you can also use alternative PINs as follows:

> **Serial2 on pins 17 (RX) and 16 (TX)**
>
> **Serial3 on pins 15 (RX) and 14(TX)**

Links

http://www.adafruit.com/datasheets/SFGDemoV2.0.rar

https://www.arduino.cc/en/main/OldSoftwareReleases

https://www.arduino.cc/reference/en/language/functions/communication/serial/


body:
First off, got my Elegoo Uno board as Christmas gift, so this is all new to me.

Here is my problem, I built an motor project and the chip has been programmed. Can I remove the chip from the Uno board?

Or can I placing a new chip onto the Uno board?

Best regards.

title: Can Arduino Uno R3 board remove chip on the board

Answers: 2

body:
It depends, if the chip has not been soldered, but placed in an IC (DIP) socket, than you can remove the programmed chip, and use it in another circuit and place another (same) IC in the IC socket of the Uno to be reprogrammed.

You also could desolder it, but I would not advice that; also most of the Uno's having a soldered IC use SMD instead of DIP.

Also, to replace the IC, you need to install a bootloader on the IC to be placed in the new Arduino (thanks for the addition Roberto Lo Giacco).

Below is a version with DIP that easily can be replaced, hence the big IC and the socket:

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

Below is a version with SMD that cannot easily be replaced, hence the small IC without a socket:

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

  [1]: https://i.stack.imgur.com/48UrM.jpg
  [2]: https://i.stack.imgur.com/oKCui.jpg

body:
Yes, you can pull the DIP chip off the board, and use it elsewhere. It will require a 16 MHz crystal and two 22pF caps (or a 16MHz resonator), at least three 0.1uF (aka 100nF) caps (connect one each from VCC, AVCC, AREF to gnd - do not connect Aref to VCC), a 10K resistor from Reset to Vcc.

If you have a  hot air rework station and decide to pull off the SMD part, that chip has two VCC pins, so another 0.1uF cap is needed.


body:
I've got an Leonardo board, it seems to be official, in that it has the Arduino branding and Made In Italy on the bottom.

However I cannot get anything to run with external power supply. Everything when powered via the USB from the computer runs fine. As soon as I use any sort of external power, and I've tried both the barrel jack with 4x AA batteries, 6x AA batteries, 9v square battery and a Shield with 2x 3.7v lithium batteries - it turns on but doesn't do anything - the USB device doesn't even appear to the computer at all unless I pull the external power out again.

Is this a faulty board? Do I need to change the jumper arrangement on the board so it'll run with external power?

title: Arduino Leonardo board - not running or appearing a USB on external power

Answers: 0


body:
I am working on ws2815 led strip with the esp8266 on **arduino 1.6.6** [fast led][1] library.Using CD40109B level shifter to convert 3.3V of esp output to 12V .It's working fine upto 31 leds according to the program pattern if i increase the led count it's giving random pattern .What can be the issue.
This is the code that i am using

    #include <FastLED.h>
    #define LED_PIN     5
    #define NUM_LEDS    50

    CRGB leds[NUM_LEDS];

    void setup() {
      FastLED.addLeds<WS2813, LED_PIN, GRB>(leds, NUM_LEDS);
    }

    void loop() {
      for (int i = 0; i <=NUM_LEDS ; i++) {
        leds[i] = CRGB (255,0 , 0);
        FastLED.show();
        delay(40);
      }
      for (int i = NUM_LEDS; i >= 0; i--) {
        leds[i] = CRGB ( 0, 255, 0);
        FastLED.show();
        delay(40);
      }
    }

**EDIT**
We checked in oscilloscope and we observed that after internal signal reshaping of the ws2815 IC ,the RGB values are not as intended.This is also seen on the led strip with changing colour of the leds.
We are trying to generate a single colour on the strip so this colour changing is quite clear.

  [1]: http://fastled.io/

---

The current rating of the power supply I am using is 12.5A, which is enough to drive the LEDs, and the voltage is also 12V at the 32nd LED.

title: What's the required voltage for ws2815?

Answers: 0


body:
I'll try to explain my need:

1. I have a generic library I created, called `myIOT.h`.
2. This class have a pre-configured  MQTT and wifi setup.
3.  Inside this library there is a `mqtt_callback` function, for all generic commands, such as `boot_time` and `connection_status`.
4. BUT, this library serves in several of my iot device's code, that each one has a few more mqtt commands, that is tailored just for s specific device, and I looking for a way that `iot.mqtt_callback(ext_mqtt_func)` will get as parameter a local ( which belong to the sketch and not to the library ), that will have the additional code needed.

I'll try to explain more clearly:

    void myIOT::mqtt_callback(ext_mqtt_func){
    if (a == true ) {
    do something

    };

    else {

    ext_mqtt_func()); // calling another fucntion that belongs to sketch and not library

    }

title: Calling external function from a class function

Answers: 1

body:
Yes, you can do it.

You pass function pointer as function parameter.

See this stackoverflow question:

https://stackoverflow.com/questions/2582161/c-function-pointer-as-parameter


body:
`topicArray` defined as follows:

    const char* msgTopic = "Home/Messages";
    const char* groupTopic = "Home/All";
    char* deviceName = deviceTopic;
    const char* topicArry[2] = {deviceTopic, groupTopic};

But `deviceTopic` can be changed during code run, and I wish that `topicArray` containg `deviceTopic` will have the correct value after `deviceTopic` has changed.

What is the right way doing so ?

title: Dynamic allocation/ Pointer to Pointer to update an Array containing parameter

Answers: 1

body:
You may try something like this:

    const char* topicArry[2] = {NULL, groupTopic};
    const char** const pDeviceTopic = &topicArry[0];
    #define deviceTopic (*pDeviceTopic)

Arguably not very elegant, but now when you assign, e.g.

    deviceTopic = msgTopic;

you are actually writing into `topicArry[0]`.


body:
I was wondering if anyone knew how to read in a random string from a file named "PhraseList.csv" or "PhraseList.xlsx" (whatever is easier)? There is a list of 10k.

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

    File myFile;

    void setup()
    {

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

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

      if (!SD.begin(chipSelect)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

      // re-open the file for reading:
      myFile = SD.open("PhraseList.xlsx");
      if (myFile) {
        Serial.println("PhraseList.xlsx":);

        // read from the file until there's nothing else in it:
        while (myFile.available()) {
         Serial.write(myFile.read());
        }
        // close the file:
        myFile.close();
      } else {
       // if the file didn't open, print an error:
        Serial.println("error opening Phrase List");
      }
    }

    void loop()
    {
     // nothing happens after setup
    }

title: Attempting to read random string from SD card

Answers: 1

body:
Reading an individual string from a list in a file is not a simple operation. Well, it's "simple", but takes a lot of work.

It's not possible to say "Get me line number 2984 from the file" with a normal text file.  You, instead, have to get each line in turn, discarding the ones you don't want, until you get to line 2984.

A better way would be to create custom "indexed" file format with a file header structure describing the rest of the file.  That header structure would contain (amongst other possible things) the offset within the file of each string it contains.

For example you may choose to have the simplest arrangement - a list of 32 bit integers (4 bytes each), each one a simple offset from the start of the file for the string that corresponds to the same number, and have the strings NULL terminated in the file.

Such as:

    00000000: 0c000000 17000000 22000000 53747269  ........"...Stri
    00000010: 6e67206f 6e650053 7472696e 67207477  ng one.String tw
    00000020: 6f005374 72696e67 20746872 656500    o.String three.

The idea with this now is you can seek in the file to "String no * 4" and read 4 bytes as an `unsigned long` (arranged *little endian*, like the Arduino uses), then use that value to do another seek. From there you can read bytes until you hit `\0`, at which point you know you have finished the string.

In the example above the string "String one" is located at offset 12 within the file.  That's 0x0C in hexadecimal, or 0x0c 0x00 0x00 0x00 as a little-endian 32-bit integer.  That's the first 4 bytes in the file.  So you read those, interpret them as a 32-bit integer (12), then seek to that location in the file to get your string.

    void readString(int num) {
        // Seek to the index entry
        myFile.seek(num * 4);

        // Read the index entry
        unsigned long offset = 0;
        myFile.read(&offset, 4);

        // You might want to add some sanity checking here

        // Seek to where the index points to
        myFile.seek(offset);

        // Read each character until you get a NULL.
        char c = myFile.read();
        while (c > 0) {
            Serial.write(c);
            c = myFile.read();
        }
        Serial.println();
    }


body:
I am pretty new to Arduino.

I've created a code with the help of many YouTube tutorials to control a servo with a button. I decided it has gotten a little un-exciting so I've been trying to add a sound sensor module to it so that if you clap or whatever, it will control the servo in the same way the servo did. Is it possible to control the servo with the button *and* the sound sensor so that I have to ways of turning on the servo at the same instance.

The code I currently have just runs the servo constantly and does not stop, you'll probably see what I mean when I attach the code below.
I'm just looking for help on this issue as I don't have a lot of experience with this, but my guess is it is not possible.

<!-- language: lang-cpp -->

        #include <Servo.h>;

        const int buttonPin = 8;
        int soundSensor = 2;
        Servo servo;

        int buttonState = 0;

        void setup()
        {
          servo.attach(3);
          servo.write(80);

          pinMode(buttonPin, INPUT);

          pinMode (soundSensor, INPUT);
        }

        void loop() {
          int statusSensor = digitalRead (soundSensor);

          if (statusSensor == 1)
          {
            servo.write(0);
            delay(1000);
            servo.write(180);
            delay(500);
          }
          else
          {
            servo.write(80);
          }

          buttonState = digitalRead(buttonPin);
          if (buttonState == HIGH)
          {
            servo.write(80);
          }
          if (buttonState == LOW)
          {
            servo.write(0);
            delay(1000);
            servo.write(180);
            delay(500);
          }
        }

title: Am I able to set up a code where I can have two ways of turning something on?

Answers: 1

body:
Just cobled this together,
untested but should give you some hints in the right direction.

In the main loop it checks the condition of the button and also the sound detector.
If either are active it sets a bool to true.
at the end of the loop, if either are true it calls the servo function that then powers the servo.
hopefully you will be able to pull this apart to add more triggers

    #include <Servo.h>;

    const int buttonPin = 8;
    int soundSensor = 2;
    Servo servo;

    int buttonState = 0;
    int statusSensor = 0;

    bool runServo = false;  // bool setting to start the servo

    void setup()
    {
      servo.attach(3);
      servo.write(80);

      pinMode(buttonPin, INPUT);
      pinMode (soundSensor, INPUT);
    }

    void loop() {
      statusSensor = digitalRead (soundSensor);
      buttonState = digitalRead(buttonPin);

        runServo = false;  // start of loop reset the runServo flag

      if (statusSensor == 1)
      {
        runServo = true;
      }

      if (buttonState == HIGH)
      {
        runServo = true
      }

      if (runServo == true)
      {
        servoFunction();//call the servoFunction code
      }

    };

    void servoFunction(){
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(500);

    }

Spriggsy


body:
I've just bought a new pro-micro and I want to simulate some keyboard inputs with it, the thing is the Arduino IDE (version 2:1.0.5) can't seem to find neither HID.h or Keyboard.h libraries. The steps to reproduce the problem are:

- plug the device using usb cable on the pc
- Open arduino ide
- try to compile my code
- it fails with the error

>test_keyboard.ino:27:22: fatal error: Keyboard.h: No such file or directory
compilation terminated.

The code is:

    #include <Keyboard.h>

    void typeKey(int key)
    {
      Keyboard.press(key);
      delay(50);
      Keyboard.release(key);
    }

    /* Init function */
    void setup()
    {
      // Begining the Keyboard stream
      Keyboard.begin();

      delay(400);

      //Keyboard.press(KEY_LEFT_GUI);

      Keyboard.press(KEY_CTRL);
      Keyboard.press(KEY_ALT);
      Keyboard.press(KEY_T);

      Keyboard.releaseAll();

      delay(100);

      Keyboard.print("echo 'hello world'");

      typeKey(KEY_RETURN);

      delay(100);

      // Ending stream
      Keyboard.end();
    }

    /* Unused endless loop */
    void loop() {}

By the way, I'm running this on linux, after pluging it and running `lsusb` on terminal I got:
  `Bus 002 Device 071: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)`

title: Keyboard.h: No such file or directory - Arduino pro micro (leonardo)

Answers: 2

body:
The Keyboard functions were moved into their own library in Arduino IDE 1.6.6/Arduino AVR Boards 1.6.9. In previous Arduino AVR Boards versions, those functions were part of the core library and there was no Keyboard library or Keyboard.h. Since you're using a very outdated version of the Arduino IDE, you don't have a Keyboard library, thus the error. There are two options to solve this problem:

- Remove the line `#include <Keyboard.h>` from your sketch.
- Update to a modern version of the Arduino IDE. Note that when you install the Arduino IDE via `sudo apt-get install arduino`, [you end up with the very outdated IDE version](https://github.com/arduino/Arduino/pull/2703) you're using. I recommend always installing the official Arduino IDE downloaded from https://www.arduino.cc/en/Main/Software.

----
For anyone wanting to write code that's backwards compatible with old IDE versions, you can do this:

<!-- language: lang-cpp -->

    #if ARDUINO > 10605
    #include <Keyboard.h>
    #endif

----
Reference: https://github.com/arduino/Arduino/pull/3304

body:
Don't hang around in the stone age, step forward to 2019 and join us with the newest Arduino IDE.

Do you use the newest linux version, for example Ubuntu 18.10?

Remove all arduino related packages from the repositories.
Be sure to remove the package librxtx-java.
You don't need to install Java, jdk, openjdk, jre or any of those.
If you use snap, remove the Java and Arduino from the snap as well.

When you have used such an old version, I suggest to delete the hidden `.arduino15` folder from your HOME folder.

Perhaps you have downloaded libraries that are now included with the Arduino IDE. You could check the "libraries" folder (in the same folder as the folders of your projects) and delete unused libraries.

Download the Arduino IDE [from the arduino.cc website][1].
The 32-bit version for a 32-bit linux system, and the 64-bit version for a 64-bit linux system.
Unpack it somewhere in under your HOME folder. You can make a shortcut to the file "arduino" and run the shortcut.
Don't make changes to the stardard Arduino system files (the Arduino IDE that you have downloaded and unpacked). Sometimes it is needed to make changes to the files in the hidden `.arduino15` folder.

  [1]: https://www.arduino.cc/en/Main/Software


body: I read somewhere that having the main clock be 32768Hz messes not only with micros() and millis(), but with some other stuff too. Is this true? Will I have to forgo the Arduino IDE to program for an avr running at 32768Hz?

title: Can the IDE handle a 32khz main clock?

Answers: 1

body:
Yes, things will break. The main culpret is this:

    #define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )

With any value below 1000000 the result of that calculation will be 0.

That means code like `micros()` will break, since it uses:

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());

64/0 is ... um ... yes... And whatever that ends up being is then multiplying the tick count. So ... the result of `micros()` is ... um ... yes...

In fact, when trying to compile anything you get (certainly on UECIDE):

    • Error at line 103 in file wiring.c:
        ‣ division by zero [-Werror=div-by-zero]

Since that's erroring when compiling code there's not a lot you can do about it.

However, one idea does spring to mind - one that is a little "crazy" I guess.

* Set your boards.txt entry to 3276800Hz

The calculations will all then be valid - however, they will all be *out by a factor of 100*.

With the board actually running at 32768, and the API thinking it runs at 3276800, all you need to do is use values 100x less than you would normally in your calculations.

For instance, to delay 1 second you'd use `delay(10);` instead of `delay(1000);`.  Or you'd multiply the return value of `millis()` by 100 to get the real number of milliseconds.

Baud rates will have to be 100x faster - so use `Serial.begin(960000);` instead of `Serial.begin(9600);`.

Of course, the `clockCyclesPerMicrosecond()` is not geared towards working with values like 3276800, and `F_CPU/1000000L` will result in `3` not `3.2768` as you'd like, so timing calculations will be a little bit off. You may need to tweak things like baud rates accordingly to compensate.


body:
I use a MKR 1010 (firmware 1.2.1), download WifiNINA library (version 1.3.0) and started to play with it.

I can connect to my Wifi network, and WifiNINA library examples such a WifiPing (which repeatedly pings www.google.com) works fine.

However, I can't get any of the server examples (e.g. WifiWebServer) to work.

I can see that the board connects to the network and gets an IP and the Serial monitor is printing this :

    09:11:15.989 -> SSID: OfficeNet
    09:11:15.989 -> IP Address: 192.168.1.44
    09:11:15.989 -> signal strength (RSSI):-36 dBm
    09:11:15.989 -> To see this page in action, open a browser to http://192.168.1.44

But if I browser to http://192.168.1.44, I never get any answer.

The loop code is just from the example :

    void loop() {
      WiFiClient client = server.available();   // listen for incoming clients

      if (client)
      {                             // if you get a client,
        Serial.println("new client");           // print a message out the serial port
    (...)
      }
      // close the connection:
      client.stop();
      Serial.println("client disonnected");
    }

I am never getting inside the `if client()`loop ("new client" never printed).

Any suggestions?

title: WifiNINA WebServer not receiving connections

Answers: 0


body: I need to control 4 DC brushless motors. I have no experience with arduino or coding. After some research the cleanest setup seems to be using the Adafruit motor shield, however the motors I'm using have 5 wires. Can I still make this work? I envision the motors being connected to the shield via the negative and positive power wires, but what do I do with the rest?  Thank you in advance.

title: Can I control 4 DC Brushless motors with arduino uno and Adafruit motor shield?

Answers: 1

body:
You don't need the motor shield at all. The motor you link to has its own driver built in.

According to the connection table on the page you link to:

* Red wire to +24V
* Green wire is for sensing the RPM - you can ignore it
* Yellow wire is the direction select - connect to any GPIO
* Black wire is ground - connect to 24V GND *and* Arduino GND.
* Blue wire is PWM control. Connect to any PWM output on the Arduino

Note that the motor will probably spin immediately power is applied until your sketch tells it to stop by driving the PWM output LOW (or 0% duty cycle).  There appears to be a 15-25kΩ (typical) pullup resistor on that pin, so adding a smaller pulldown resistor (say 1kΩ) on it should force it to be off until you turn it on.


body:
I want to use RX(0) and TX(1) Pins to make Arduino as an RS485 slave. To do this I am using MAX485 IC (Breakout board) https://datasheets.maximintegrated.com/en/ds/MAX1487-MAX491.pdf

The problem here is that I don't have any other pins remaining to interface with the module in order to pull the DE/RE pin HIGH/LOW.

Can anyone suggest a way to do this without using one additional pin?

title: Arduino as Modbus RS485 slave using only 2 Digital pins

Answers: 0


body:
Today i've been playing with my monochrome oled 128x64 adafruit screen. I've got it connected using SPI. Previously today i had no problems att all and i was able to print messages and variables on the screen. But suddenly my functions causes the arduino Nano to restart and initialise Setup() again!
It is very frustrating and i cannot figure out what part of my code is causing the crash!
I have tried running the adafruit example code to test the screen and it is working, so the screen is not broken and the wires must be correct.

Here is the code for my display:
display.h :

    #include <Adafruit_GFX.h>  // Include core graphics library for the display
    #include <Adafruit_SSD1306.h>  // Include Adafruit_SSD1306 library to drive the display

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels

    // Define SPI pins:

    #define OLED_MOSI   9
    #define OLED_CLK   6
    #define OLED_DC    7
    #define OLED_CS    8
    #define OLED_RESET 13

    // Create display
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
      OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

    #include <Fonts/FreeMonoBold12pt7b.h>  // Add a custom font
    #include <Fonts/FreeMono9pt7b.h>  // Add a custom font

    void initDisplay(){

      delay(100);

      display.begin(SSD1306_SWITCHCAPVCC);

      display.clearDisplay();  // Clear the buffer

      display.setTextColor(WHITE);  // Set color of the text

      display.setRotation(0);  // Set orientation. Goes from 0, 1, 2 or 3

      display.setTextWrap(false);  // By default, long lines of text are set to automatically “wrap” back to the leftmost column.
                                   // To override this behavior (so text will run off the right side of the display - useful for
                                   // scrolling marquee effects), use setTextWrap(false). The normal wrapping behavior is restored
                                   // with setTextWrap(true).

      display.dim(0);  //Set brightness (0 is maximun and 1 is a little dim)

      Serial.println("Display initiated..");

    }

    void printMessage(String message){
      display.setFont(&FreeMono9pt7b);  // Set a custom font
      display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0
      display.setTextColor(WHITE);
      display.setCursor(0,50);
      display.clearDisplay();
      display.print(message);
      display.display();
      Serial.println("printing message on display");
      delay(1000);

    }
    void printTemp(long temp){

      display.setFont(&FreeMono9pt7b);  // Set a custom font
      display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0

      display.clearDisplay();  // Clear the display so we can refresh
      // Print text:
      display.setCursor(25, 15);  // (x,y)
      display.println("temp:");  // Text or value to print
      // Draw rectangle:
      display.drawRect(79, 0, 35, 27, WHITE);  // Draw rectangle (x,y,width,height,color)
                                               // It draws from the location to down-right

      display.setFont(&FreeMonoBold12pt7b);  // Set a custom font
      // Print variable with left alignment:
      display.setCursor(83, 20);  // (x,y)
      display.println(temp);  // Text or value to print

      display.display();  // Print everything we set previously
      Serial.println("Printing temp..");

    }

main.ino:

    #include "display.h";
    #include "DHT.h";
    #include "Radiocom.h";

    long temperature;

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

      initDHT();
      initDisplay();
      //initRF();
    }

    void loop()
    {
      //temperature = readTemp();
      //delay(1000);
      //printTemp(temperature);
      String message = "123456789abc";
      printMessage(message);
      //sendMsg();
      //RFlisten();
      delay(1000);
    }

If anyone can help me out in any way, i would be really thankfull!

title: code for OLED display suddenly crashes arduino Nano

Answers: 0


body:
I have some AK4524 ADC/DAC chips from an old M-Audio Delta 10/10 sound card in my hand.

I would like to use them for precision sensor reading and voltage generating with a arduino nano.

My experience with digital electronics is limited, i have used mcp4822 as a dac before with arduino and a bit familiar with SPI.

Would you point me to the right direction on this matter.

https://people.freebsd.org/~lofi/4524.pdf

This is the datasheet.

Thank you.

title: AK4524 with Arduino

Answers: 0


body:
i want to turn on an led with two buttons. If either of the buttons is pressed i want the led to turn on while the button is pressed and stay off if nothing is pressed. i have two sets of code, they both do the same thing, but the second set of code causes the led to stay in the on position even when nothing is being pushed and i dont understand why.. i am using pulldown resistors on both the buttons.

This is the first set of code that works properly:

    class Button {

      public:

        int pin;
        int state;
        int location;
        int Speed;
        int Direction;
        int active;
        int prevstate;

        Button(int pin1, int state1, int location1, int active1, int previousState)
        {
          pin = pin1;
          state = state1;
          location = location1;
          active = active1;
          prevstate = previousState;
        }
    };

    Button button(7,0,0,0,0);
    Button button2(8,0,0,0,0);
    Button buttons[2] = {button, button2};

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

    void loop() {
       if (digitalRead(button2.pin) == HIGH){
                 digitalWrite(ledPin, HIGH);
              } else {
              // turn LED off:
              digitalWrite(ledPin, LOW);
              }
           if (digitalRead(button.pin) == HIGH){
                 digitalWrite(ledPin, HIGH);
              } else {
              // turn LED off:
              digitalWrite(ledPin, LOW);
              }
    }

this is the code i want to use but it is not working.. the led stays in the on position:

    void loop(){
      for (int i = 0; i<sizeof(buttons); i++){
        if(digitalRead(buttons[i].pin) == HIGH){
              digitalWrite(ledPin, HIGH);
              } else {
              // turn LED off:
              digitalWrite(ledPin, LOW);
              }
        }
    }

also if i change

    if(digitalRead(buttons[i].pin) == HIGH)

to

    if(digitalRead(buttons[0].pin) == HIGH)

the code works for the first or second button alone in the array.. but not both???

title: Array is affecting digitalread values

Answers: 2

body:
I have to disagree that your first sketch is working. I suppose that a very fast blinking led seems to be "on".

When you describe what should happen in a logic way, then you can put that into code.

The logic is: The led is on, if at least one of the buttons is pressed.
In other words: The led is off, if no button is pressed, else the led is on.

This logic has as a result that the led stays on if a second button is pressed and after that the first button is released. I assume this is okay.

For **two buttons** it is possible to check both conditions.

    if (digitalRead(button.pin) == HIGH || digitalRead(button2.pin) == HIGH)
      digitalWrite(ledPin, HIGH);
    else
      digitalWrite(ledPin, LOW);

Or test for LOW:

    if (digitalRead(button.pin) == LOW && digitalRead(button2.pin) == LOW)
      digitalWrite(ledPin, LOW);
    else
      digitalWrite(ledPin, HIGH);

For **multiple buttons**, a `bool` can be used or the number of pressed buttons can be counted.

A fixed number for the array size is easy and has less chance for a mistake:

    #define BUTTONS_COUNT 2

It is also possible to use `sizeof()`. The total size has to be divided by the size of one element:

    int count = 0;
    for (int i = 0; i<sizeof(buttons)/sizeof(Button); i++) {
      if (digitalRead(buttons[i].pin) == HIGH) {
        count++;
      }
    }

    if (count == 0)
      digitalWrite(ledPin, LOW);
    else
      digitalWrite(ledPin, HIGH);

body:
You seem to have made 4 button objects: button, button2, and buttons[2]. buttons[0] and buttons[1] are full button objects whose first member, .pin, is initialized to the addresses of `button` and `button2`, respectively. This is probably not what you intended.

Did you mean to create:

    Button buttons[2] = {
       {7,0,0,0,0},
       {8,0,0,0,0}
    };

, an array of two initialized button objects?


body:
I’m using an Arduino Uno and a fastLed WS2812B.
I have the leds set up correctly. Every 2 seconds, the lights pause of about a second and display seemingly random colors.

Does anyone know what's wrong?

My code:

    #include <FastLED.h>

    #define LED_PIN   7
    #define NUM_LEDS  10

    CRGB leds[NUM_LEDS];

    void setup() {
      FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

    }

    void loop() {
      for (int i = 0; i < NUM_LEDS; i++){
        leds[i] = CRGB(0,0,255);
        FastLED.show();
        delay(100);
      }
      for (int i = 0; i < NUM_LEDS; i++){
        leds[i] = CRGB(255,0,0);
        FastLED.show();
        delay(100);
      }
    }

title: Arduino Uno and FastLED WS2812B Glitching

Answers: 1

body:
I have run the code on the Arduino simulator online. If it is working in the Arduino Simulator **chances are less that it has to do something with the code itself**.

Hence, also as the root cause was found to be about sharing the ground @Majenko

This is also one example of solving the problem step by step. validating one section after the other. using the simulator you can verify that the code is working fine. later, proceed to verify the hardware. I hope this helps.

You can verify the FastLED code [here][1] (you can modify the parameters)

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

  [1]: https://wokwi.com/arduino/libraries/FastLED/ColorPalette
  [2]: https://i.stack.imgur.com/WQhiN.gif


body:
I am trying to make a device which will turn a turn key with a servo.

However, I want it to stop turning the turn key if the resistance is too great (meaning it is locked and will not ever turn).

How do I do this? Would I just tell it to turn and then have it turn back after a time (because if it is locked or not it should be done within that time)?

I do not want to damage my servo by having it try to turn something that it can't turn.

I am using an Arduino Uno and the library "Servo.h". The servo being used is a Batan S1123.

title: How do I make a Servo Stop if it Hits Resistance?

Answers: 4

body:
The best way is use external feedback. Hall sensor for example.
200-250ms after using servo check status of hall sensor

body:
You could either:

 1. Use a limit-switch to sense that the servo has completed it move. If it doesn't complete it a reasonable time, return it to its original position. Or,

 2. Measure the motor current by putting a low value resistor inline with the ground side of the motor's power supply. With one of the A/D pins, measure the voltage on the motor side of the resistor, which increases with motor current. You'll need to have figured out how much current the motor draws when operating normally. If the motor stalls, your controller could sense that by seeing that current increase. Pick a value (try 150%, for example) of over-current as an indicator that the motor is stalled, and return it to its original position.

The first way is easier to implement but possibly lets the motor stall while you wait for the expected move time to expire. The second way lets you detect stalling and take action immediately.

body: I suggest detecting the current flowing through the servo or using a potentiometer to detect whether the servo is moving. You could also put a clutch between the servo and the key, but then you wouldn't know the angle of the key at any given time.

body:
It depends on what kind of failure you expect. If you're afraid the motor may break your linkage (the gears, cranks, belts, whatever you have in place), you have to react very fast, and it's only feasible with a current measurement. That would require sensing the current and reacting very quickly on over-current to be effective.

If you know for a fact that your linkage can withstand the stall torque of the motor, you just have to worry about overheating the motor. Such a protection can be done with a position sensor or a limit switch if you happen to have one. You could even implement a protection with no sensors at all: drive the motor for just long enough to do its job and then stop: either it will turn the key or it won't, but it won't overheat if stalled for a second or two.


body:
I am working on a specific project that requires a database.
I have done the 'connection' and the "write" of data using a PHP file.
I have even reconfigured everything so it would be possible to access the database through a different device that is connected to the same wifi network as my computer.
All tested and working properly.

The Arduino for some reason is not connecting to the server, where Serial.println(client.connect(serv, 8095)); is returning 0, I have tried every possible solution but nothing seems to work.
I am using xampp, and I changed the port to 8095.
any possible information would be much appreciated.

    #include <SPI.h>
    #include <Ethernet.h>
    byte mac[] = {
      0xFDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    byte sensorInterrupt = A2;
    byte sensorPin       = A2;
    float calibrationFactor = 4.5;
    volatile byte pulseCount;
    float flowRate;
    unsigned int flowMilliLitres;
    unsigned long totalMilliLitres;
    unsigned long oldTime;
    char valvestatus= 'ON';
    byte ip[] = {192, 168, 1, 4 }; //Read the code explanation https://102.159.198.42/
    byte serv[] = {192, 168, 1, 3} ; //Read the code explanation  192.168.1.3
    EthernetClient client;

    void setup() {
      Ethernet.begin(mac, ip);
      Serial.begin(9600);
    delay(1000);
       pinMode(sensorPin, INPUT);
      digitalWrite(sensorPin, HIGH);

      pulseCount        = 0;
      flowRate          = 0.0;
      flowMilliLitres   = 0;
      totalMilliLitres  = 0;
      oldTime           = 0;
      attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

    }

    void loop() {

      if((millis() - oldTime) > 1000) {
        detachInterrupt(sensorInterrupt);
        flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;
        oldTime = millis();
        flowMilliLitres = (flowRate / 60) * 1000;
        totalMilliLitres += flowMilliLitres;
         unsigned int frac;
        Serial.print(int(flowRate));  ////////
        Serial.print(totalMilliLitres); /////////////
       pulseCount = 0;
      attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

        }

        Serial.println(client.connect(serv, 8095));
        if (client.connect(serv, 8095)) { //Connecting at the IP address and port we saved before
    client.print("GET /ost/write_data.php?"); //Connecting and Sending values to database
    client.print(flowRate);
    client.print(totalMilliLitres);
    client.print(valvestatus);
     client.stop(); //Closing the connection
        }
     while(!client.available()){}

    }

    void pulseCounter()
    {
      // Increment the pulse counter
      pulseCount++;
    }

title: Can't connect to the server

Answers: 0


body:
I'm trying to make a door sensor with a reed switch. Each time the there is a change, the ESP8266 sends an HTTP request to web service.

Unfortunately, the ESP8266 serial monitor dumps a huge stack trace when I'm approaching the magnet to the reed switch:

    Exception (9):
    epc1=0x40104b14 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000003 depc=0x00000000

    ctx: sys
    sp: 3fffeb20 end: 3fffffb0 offset: 01a0

    >>>stack>>>
    3fffecc0:  00000002 00000006 3ffefdc4 40227108
    3fffecd0:  3ffefa74 00000002 00000014 401004e4
    3fffece0:  3ffeffbc 3ffeffc0 00000006 00000001
    3fffecf0:  402253bc 00000000 00000010 00000000
    3fffed00:  00000000 4bc6a7f0 81cac083 00000000
    3fffed10:  00000000 00000000 4bc6a7f0 00000000
    3fffed20:  40104d40 0037d809 3ffeecd0 00000000
    3fffed30:  3ffee520 3ffeecd0 3ffeffbc 40224398
    3fffed40:  00000000 00200085 40201578 00001388
    3fffed50:  3ffeecd0 00000000 00000050 00000050
    3fffed60:  00000000 3fffedd0 3ffefd34 402032e5
    3fffed70:  1301a8c0 00000031 3ffeebbc 402039cc
    3fffed80:  3ffeedb8 000000ef 000000ef 00000020
    3fffed90:  ffffffff 00000050 3fffedd0 40202d5c
    3fffeda0:  40204738 1301a8c0 40204738 1301a8c0
    3fffedb0:  3ffe8a64 00000005 000...

I think it's because the ESP8266 tries to make concurrent HTTP calls...
How can I solve this?

Here is the code:

    // https://www.instructables.com/id/Arduino-Software-debouncing-in-interrupt-function/
    // #include "util/atomic.h"
    #include "ESP8266WiFi.h"
    #include "ESP8266HTTPClient.h"
    #include "Wire.h"

    const char* ssid = "****";
    const char* pass = "****";
    const byte interruptPin = 5;
    long debouncing_time = 50; //Debouncing Time in Milliseconds
    volatile unsigned long last_micros;
    const char* host= "192.168.1.19";
    const char* doorStates[2] = {"closed", "opened"};

    void connection()
    {
      // Establish a WIFI connection
    }

    void setup()
    {
      Serial.begin(115200);
      connection();
      pinMode(interruptPin, OUTPUT);

      // Attaching interrupt
      attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE);
    }

    void loop()
    {
      delay(1000);
    }

    void handleInterrupt() {
      if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
        int val = digitalRead(interruptPin);
          notify(val);
      }
      last_micros = micros();
    }
    // Make HTTP Call to web service
    void notify(int val)
    {
      WiFiClient client;
      const String frontDoorState = doorStates[val];
      String url = "http://192.168.1.19/alarm/front-door/state/" + frontDoorState;
      client.connect(host, 80);
        client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                     "Host: 192.168.1.19\r\n" +
                     "Connection: close\r\n\r\n");
                     client.stop();
    }

title: How to handle concurrent HTTP request when using interrupt

Answers: 1

body:
Simple: don't do HTTP requests in the interrupt.

It's usually bad to do anything heavy like that in an interrupt.  Instead you should just set a flag in the interrupt (`volatile bool`) and examine that flag in `loop()`.

    volatile bool sendNotification = false;
    volatile int notifyVal = 0;

    void loop() {
        if (sendNotification) {
            notify(notifyVal);
            sendNotification = false;
        }
    }

    void handleInterrupt() {
        if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
            notifyVal = digitalRead(interruptPin);
            sendNotification = true;
        }
        last_micros = micros();
    }


body:
I'm trying to upload a Blink example to run on a pro-micro (leonardo) but it is not working anymore (it was just working yesterday).

Steps to reproduce:

- Plug the device in USB port
- Open Blink example in Arduino IDE (version 1.8.8)
- Select the port and board accordingly to Arduino Leonardo
- Compile and try to upload it.

The code compile successfully but when uploading it just halts. The ide console displays:

> avrdude: error: programmer did not respond to command: exit bootloader
>
> Forcing reset using 1200bps open/close on port /dev/ttyACM0 PORTS
> {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
> {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
> PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
> / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
> {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS
> {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
> {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
> PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
> / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
> {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS
> {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
> {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
> PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
> / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
> {} Uploading using selected port: /dev/ttyACM0
> /home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/bin/avrdude
> -C/home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf
> -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/arduino_build_350609/Blink.ino.hex:i
>
> avrdude: Version 6.3-20171130
>          Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
>          Copyright (c) 2007-2014 Joerg Wunsch
>
>          System wide configuration file is "/home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf"
>          User configuration file is "/home/fabio/.avrduderc"
>          User configuration file does not exist or is not a regular file, skipping
>
>          Using Port                    : /dev/ttyACM0
>          Using Programmer              : avr109
>          Overriding Baud Rate          : 57600
>          AVR Part                      : ATmega32U4
>          Chip Erase delay              : 9000 us
>          PAGEL                         : PD7
>          BS2                           : PA0
>          RESET disposition             : dedicated
>          RETRY pulse                   : SCK
>          serial program mode           : yes
>          parallel program mode         : yes
>          Timeout                       : 200
>          StabDelay                     : 100
>          CmdexeDelay                   : 25
>          SyncLoops                     : 32
>          ByteDelay                     : 0
>          PollIndex                     : 3
>          PollValue                     : 0x53
>          Memory Detail                 :
>
>                                   Block Poll               Page                       Polled
>            Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
>            ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
>            eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
>            flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
>            lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
>            signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
>
>          Programmer Type : butterfly
>          Description     : Atmel AppNote AVR109 Boot Loader
>
> Connecting to programmer: .avrdude: butterfly_recv(): programmer is
> not responding
>
> avrdude: butterfly_recv(): programmer is not responding

A strange behavior I noticed is each time I plug the device again in the usb port different leds are light up, some times only RX, sometimes only TX and sometimes none (the power led is always on)

What could be happening here? Can it be the problem on the hardware?

title: Can't upload sketch - avrdude: butterfly_recv(): programmer is not responding

Answers: 2

body:
I have successfully solved this a year ago and I am trying to remember how I did it. So while it's fresh in my head this thing has to do with the bootloder.

The first and most obvious thing you can do is try to doubletap the reset and ground contact. Double tapping it will force the Arduino to reset and start in the bootloader for 8 seconds.

This is how I managed to install the driver for my pro-micro, it wouldn't install unless you did it when Arduino was in bootloader mode. But this strategy doesn't work for the code upload for some reason although many people claim it was the only thing that helped.

Another thing that could maybe help is clearing the Arduino's cache. When I was trying to compile a year ago, after many attempts I had to clear the pro-micro with another Arduino once in a while (you may need this later on). *[thebusybee's note: I never heard about a cache in AVR micros. If a sketch is uploaded it will be flashed into the non-volatile memory overwriting all that was at its place before.]*

Something else I remembered (if this is the case it would make things very problematic for me) is the USB cable. Again before my 1 year break I remembered that uploading the sketch for me only worked with 1 out of like 15 micro-USB cables I had (the one that's the shortest and thickest). That cable is broken now so I can't really check this unless I start researching microUSB cables right this instant.

Finally it may be the system. If nothing works try uploading the sketch from another preferably clean system.

Anyway, I hope you solve this because I am trying to solve the same issue.

Good luck

body:
I experienced the same frustrating issue for days. It was Ubuntu.

The fix was also so easy: sudo apt purge modemmanager

Until I discovered it, I suffered headache for days.

The auto upgrader may cause issues with this command. It can be solved
with the following command:

sudo dpkg-reconfigure -plow unattended-upgrades

At the first prompt, choose not to download and install updates.
Then reboot.


body:
I am learning how to create a soft latch power switch, using an N channel mosfet.

Currently, I have this:

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

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

<!-- End schematic -->

The idea is (so far) that I can turn it on with the switch, the Arduino immediately brings the power control high (ensuring the FET stays on), and brings that same pin low after 1.5s (simulating a timed shutdown).

However; when the power control goes low, I still see about 1.8v in the power control line (I'm presuming its floating?), which leaves this particular FET partially open.

If I disconnect the power control line from the MCU, I get the behaviour I expect. I can touch the power control to +ve and the FET will switch on.  If I lift the control line from +ve, the FET closes the gate, due to the pull down resistor.

I'm struggling to understand why the FET works in isolation, but does not work when connected to the MCU output pin.  The pinMode is OUTPUT.

FET (3055VL): https://www.onsemi.com/pub/Collateral/MTP3055VL-D.PDF

Here's the test code I'm using.
It simply flashes a build in LED 10 times then does a power off.

    int ledPIN = 17;
    int controlPin = 11;
    int lDelay = 150;

    bool shouldBeUp = true;

    void setup()
    {
      pinMode(ledPIN, OUTPUT);
      pinMode(controlPin, OUTPUT);
      digitalWrite(controlPin, HIGH);
    }

    void loop()
    {
      if (shouldBeUp) {
        for (int i = 0; i < 10; i++)
        {
          digitalWrite(ledPIN, LOW); // on
          delay(lDelay);
          digitalWrite(ledPIN, HIGH); // off
          delay(lDelay / 2);
        }

        // Leave the LED low
        digitalWrite(ledPIN, LOW);
        digitalWrite(controlPin, LOW);
        shouldBeUp = false;
      }
    }

Any help is appreciated! Thank you :)

title: How to drive N channel gate correctly from Adafruit Feather pinout?

Answers: 1

body:
Your problem is that the GPIO pin is referenced to ground - and the MOSFET is isolating that ground.

You need instead to switch the power not the ground - and for that, you use a P-channel MOSFET.

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

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

<!-- End schematic -->

To hold the power on you now set the GPIO LOW instead of HIGH.

If you need to switch a higher voltage than the operating voltage of the MCU you will need to add another N-channel MOSFET to pull down the P-channel's gate.


body:
I have a Rostock Max 3d with an Arduino Uno as the controller. The OEM has a firmware version I would like to upload, but it is in the hex file format.

I have looked all over the Arduino IDE, but did not found a way to upload a hex file to the Arduino. I tried using AVRDUDE, but the Arduino only communicates with my PC when I set the "Programmer" to AVRISP. I have uploaded other codes for blink, and hello_world, but haven't been able to compile the firmware source. I was hoping I could just use the hexfile included in the firmware package.

My OS is Linux.

title: how can I upload a hex file to an arduino uno?

Answers: 4

body:
I recommend looking at the arduino IDE files located at **"(install path)/hardware/arduino/avr/"** (on windows anyway, I should assume the same on linux).

I am unsure if the following files have the .txt extension on them, but if not use just the file name.

----------

Open and look in "boards.txt" and find the associated entries starting with "**uno.**" keeping this file open.

Next open "platform.txt" looking for the entries "**tools.avrdude**" (the avrdude part comes from boards.txt "uno.upload.tool" entry) and copy into a new text editor the value of "**tools.avrdude.upload.pattern**" you can fill in the parameters later.

With the command you copied replace the following:

from platform.txt

 - "**{cmd.path}**" = "**tools.avrdude.cmd.path**"
 - "**{config.path}**" = "**tools.avrdude.config.path**"
 - "**{upload.verbose}**" = "**tools.avrdude.upload.params.verbose**"
 - "**{upload.verify}** = "**tools.avrdude.upload.verify**"

now from boards.txt

 - "**{build.mcu}**" = "**uno.build.mcu**"
 - "**{upload.protocol}** = "**uno.upload.protocol**
 - "**{{serial.port}**" = Your serial port (according to research something like **/dev/ttyS0**)
 - "**{upload.speed}**" = "**uno.upload.speed**"
 - "**{build.path}**" and "**{build.project_name}** = path to file you are trying to upload

So with the above set out for me to upload a program to an Arduino uno I would use something like the following in windows:

assuming install path was "C:\Arduino\"
> "C:\Arduino\hardware\tools\avr\bin\avrdude.exe" "-CC:\Arduino\hardware\tools\avr\etc\avrdude.conf" -v -patmega328p -carduino "-PCOM1" -b115200 -D "-Uflash:w:C:\MyArduinoProject\build.hex:i"

for linux it could possibly be (I really am unsure):

assuming install path was "/opt/Arduino/"
> "/opt/Arduino/hardware/tools/avr/bin/avrdude" "-C/opt/Arduino/hardware/tools/avr/etc/avrdude.conf" -v -patmega328p -carduino "-P/dev/ttyS0" -b115200 -D "-Uflash:w:/usr/MyArduinoProject/build.hex:i"

----------

The above should work for you, I have previously written my own program to upload a hex file to the Arduino utilizing the above commands and avrdude.

body:
I use a standalone programmer that uploads a .hex file from an SD card via the ICSP interface.

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

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

body:
I think you can use this software http://www.mediafire.com/file/tx2l85gsdkpf5d4/HEXtoArduino_V1.0.0.zip/file
[![enter image description here][1]][1]

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

body:
I found the definitive answer to this.

1. Start Arduino IDE
2. To to File...Preferences...
3. Turn on Show verbose output during: [X] upload (image 1 below)
4. Upload a sketch to your Arduino Uno
5. I used the sample blink sketch and saw the following (image 2 below):

**AVRDude: is used to upload**

You want that first line shown in white --- when you expand it you'll see that it is the entire line of code that is used to upload the HEX file of your program to the Uno.

The entire command on my computer looks like the following:

    C:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\<username>\dev\arduino\STK2UPDI\build\blink.ino.hex:i

I'm going to break this down into a few lines:

First, it's the full path to the avrdude exe.
Then it is passing the -C argument with the full path to the `avrdude.conf` file

`c:\longpath\avrdude -C C:\avrdude.conf`

Then a bunch of params to set up avrdude properly:
`-v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:`

And finally the full path to the HEX file you want to upload

`c:\longpath\blink.ino.hex:i`

**All You Have To Do**

All you have to do is take that extremely long line and replace the full-path to the hex file to be your target HEX file and then run the entire command and you'll see something **like what is shown in image 3 below**.

**Image 1**

[![verbose output][1]][1]

**Image 2**

[![upload info][2]][2]

**Image 3**
[![upload success][3]][3]

  [1]: https://i.stack.imgur.com/7zllb.png
  [2]: https://i.stack.imgur.com/hykpi.png
  [3]: https://i.stack.imgur.com/O7KUL.png


body:
I have been following [this tutorial](http://www.deviceplus.com/how-tos/arduino-guide/esp8266-setup-tutorial-using-arduino/) to set up my ESP8266. I have also recreated on a perfboard the circuit provided in the tutorial, and I intend to use this perfboard circuit in my project.

The problem arises when I plug my ESP into the perfboard and try to talk to it through the serial monitor. When using a baud rate of 115200, the ESP responds to commands but in a garbled format. Also, the blue LED stays on after powerup for increasingly long periods of time. Now the blue LED is always on and the ESP no longer responds to any commands, except when reset and asked for the startup firmware info. I suspect that the ESP is now broken but am not sure how to check.

Also note that the ESP was working fine on a breadboard at 9600 baud, prior to the blue LED incident. Now it won't work with the breadboard either.

All commands were sent with newline and carriage return.

Is the ESP8266 broken? Could there be something wrong with my perfboard circuit? The circuit is rather dense and contains wiring for several other components in addition to the ESP-8266.

title: ESP-8266 stopped working due to possibly faulty perfboard layout

Answers: 1

body: It turns out the real culprit was the `AT+IPR=9600` command bricking the board. The board was "fixed" by obtaining the [firmware](https://github.com/espressif/ESP8266_NONOS_SDK) and flashing it to the board using `esptool.py`. Download the repo's source code, navigate to the directory `bin/at/`, and see the file `README.md` to see which addresses to flash the different parts to.


body:
My goal is to be able to send/receive IR messages in my own custom format and send messages ~10 bytes long. My message object will get serialized down to individual bits, which are transmitted by turning the IR LED on/off at specific timings of my choosing to represent logical ones and zeros. From what I've seen, an IR LED can be turned on/off in either a while loop or as a PWM signal in order to transmit the message. I'm under the assumption the only thing gained by using a PWM signal is that the work there is done on a timer callback and let other code run seemingly simultaneously. For simplicity, I opted for the while loop approach.

The issue I am seeing is one of two. Either the receiver is not reading the timings right, or the transmitter is not turning the LED on/off as fast as I would expect.

For the example code below, the IR LED is turned on for 600 microseconds, and off for 300. (Eventually, my custom messages will be built up using something along these lines.) However, as you can see in the Sample Outputs below the receiver is not seeing the IR signal as on or off for anywhere near that amount of time.

Not sure if this is a setup issue, or something else. The two Arduino boards I'm using are both Arduino Pro ATmega328p boards. For the board sending the IR signal, Pin 6 goes to a 330 Ohm resistor, then to the LED, then to ground. The IR Receiver on the other board has no resistors, just direct connections to pins. When reading the IR signals, I hold the receiver a few centimeters away from the LED.

My questions are:

  1. Is this a viable setup? Should this work? Or am I all wrong in my assumptions and need to look some other way of doing this?
  1. Is my assumption about turning the LED on/off with a while loop vs. a PWM signal true? Or should I remove the loop concept and only use a PWM signal.

IR Transmit Code:
```
#define IRpin          6

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

void loop() {
  //LED On
  PORTD |= (1 << IRpin);
  delayMicroseconds(600);

  //LED Off
  PORTD &= ~(1 << IRpin);
  delayMicroseconds(300);
}
```

IR Receive Code (taken from an online example, only modifications are to output text):
```
#define IRpin_PIN      PIND
#define IRpin          2

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000
#define RESOLUTION 20

uint16_t pulses[300][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse;  // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length

  while (IRpin_PIN & (1 << IRpin)) {
    // count off another few microseconds
    highpulse++;
    delayMicroseconds(RESOLUTION);

    // If the pulse is too long, we 'timed out' - either nothing
    // was received or the code is finished, so print what
    // we've grabbed so far, and then reset
    if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
      printpulses();
      currentpulse = 0;
      return;
    }
  }
  // we didn't time out so lets stash the reading
  pulses[currentpulse][0] = highpulse;

  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
    // pin is still LOW
    lowpulse++;
    delayMicroseconds(RESOLUTION);
    if ((lowpulse >= MAXPULSE)  && (currentpulse != 0)) {
      Serial.println("Breaking - Hit max Pulse Low");
      printpulses();
      currentpulse = 0;
      return;
    }
  }
  pulses[currentpulse][1] = lowpulse;

  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  uint32_t totalMicroseconds = 0;
  for (uint8_t i = 0; i < currentpulse - 1; i++) {
    Serial.print("On(");
    Serial.print(pulses[i][1] * RESOLUTION , DEC);
    Serial.print(");");
    Serial.println("");
    Serial.print("   Off(");
    Serial.print(pulses[i + 1][0] * RESOLUTION , DEC);
    Serial.println(");");

    totalMicroseconds += pulses[i][1] * RESOLUTION;
    totalMicroseconds += pulses[i + 1][0] * RESOLUTION;

    if (i % 8 == 0) {
      Serial.println("");
    }
  }

  Serial.print("On(");
  Serial.print(pulses[currentpulse - 1][1] * RESOLUTION, DEC);
  Serial.print(");");
  totalMicroseconds += pulses[currentpulse - 1][1] * RESOLUTION;

  Serial.println("");
  Serial.print("Total Microseconds: ");
  Serial.println(totalMicroseconds, DEC);
}
```

Sample Outputs:
```
Ready to decode IR!
On(20);
   Off(62064);

On(0);
   Off(12060);
On(360);
   Off(1860);
On(440);
   Off(8940);
On(20);
   Off(15460);
On(80);
   Off(25672);
On(40);
Total Microseconds: 127016
On(40);
   Off(6740);

On(300);
   Off(6740);
On(20);
   Off(8520);
On(40);
   Off(6740);
On(1540);
   Off(15720);
On(40);
   Off(34860);
On(20);
Total Microseconds: 81320

On(3000);
   Off(35384);

On(40);
   Off(14180);
On(1220);
   Off(54440);
On(980);
Total Microseconds: 109244

On(200);
Total Microseconds: 200
On(20);
   Off(29160);

On(60);
   Off(26700);
On(60);
   Off(22880);
On(20);
   Off(2928);
On(20);
Total Microseconds: 81848
```

title: Precise On/Off control for IR LED

Answers: 1

body:
I ended up also asking this question at electronics.stackexchange.com. I know that's frowned upon, but the topic really did toe the line between being an Arduino subject or electronics.

To summarize the accepted answer, no IR messages cannot be sent/received the way I thought. The IR LED needs to be on/off at a frequency that matches what the receiver is set to be able to receive. Generally 38kh. So On for 13 microseconds, then Off for 13 microseconds. Then repeat.

https://electronics.stackexchange.com/questions/417387/precise-on-off-control-for-ir-led/417391


body:
This is my `loop()`function:

    if(Serial.read() == 't') {
      tarestate = true;
    }

    while(tarestate == true) {
      timeNowTare = mills();
      if(mills() - timeNowTare >= 3000) {
        Serial.println("Tare");
      }
      tareState = false;
    }

Where `tareStare` is a boolean, `timeNowTare` is a long.

I need to print on serial:

> Tare

three seconds after I enter "t" into serial.

With everything I have tried to date, the program either stops or tares immediately after entering “t”.

EDIT: Thanks to everyone who responded with answers.
The solution was simply to move the timeNowTare = true; declaration up to the Serial.read() if statement. I also changed the while loop to an if statement because it seemed to make my code run quicker.

[![final code][1]][1]

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

title: Please Correct my Delay Code without using delay();

Answers: 2

body:
Move `timeNowTare = millis();` inside first `if`:

    if (Serial.read() == 't') {
      tareState = true;
      timeNowTare = millis();
    }

and `tareState = false` inside second `if`:

    while (tareState) {
      if (millis() - timeNowTare >= 3000) {
        Serial.println(F("Tare"));
        tareState = false;
      }
    }

body:
The easiest solution is to just use `delay()`:

<!-- language-all: lang-c++ -->

    if (Serial.read() == 't') {
        delay(3000);
        Serial.println(F("Tare"));
    }

What? You said “no `delay()`”? OK, then just write your own
implementation of `delay()` and inline it in place of the actual call to
`delay()`:

    if (Serial.read() == 't') {
        uint32_t timeNowTare = millis();
        while (millis() - timeNowTare < 3000) continue;  // wait
        Serial.println(F("Tare"));
    }

This seems to be more or less what you attempted. You write a `while`
loop that blocks the program for three seconds. It is also what leoc7's
answer does.

However, doing so is completely foolish. Why would you write your own
version of `delay()` when the Arduino core provides you with a well
tested one? Why would you want to avoid the standard `delay()` in the
first place?

It turns out there is a very good reason to avoid `delay()`. The reason
is that `delay()` _blocks_ your program for the entire delay duration.
If your code needs to be responsive to some external inputs (as any non
trivial program at some point needs), this means within that time window
the program will be completely unresponsive. The bad thing about
`delay()` is not the implementation (there is no point in replacing it
with your own), it's the fact that it blocks your program. If you
replace `delay()` by your own blocking code you have won nothing.

The real solution is to think in terms of a finite state machine. Either
the program is running in “tare mode” or not. The possible state
transitions are:

* upon reading a `'t'` on the serial port, you enter tare mode and take
  note of the current time
* if you are already in tare mode and three seconds have elapsed since
  you entered that mode, then you print out `"Tare"` and exit tare mode.

Here is a straight forward implementation of such state machine:

    static bool tare_mode = false;
    static uint32_t tare_start_time;  // meaningful only in tare_mode
    if (Serial.read() == 't') {
        tare_mode = true;
        tare_start_time = millis();
    }
    if (tare_mode && millis() - tare_start_time >= 3000) {
        Serial.println(F("Tare"));
        tare_mode = false;
    }

Now you can add more code to `loop()` and this extra code will never be
blocked by your “tare” feature.


body:
I want to read 30 differential ended analog sensors.
Using ADS1115 16 bit this is possible, but we end up having only 4 address on I2C, so i chose TCA9548A breakout board with 8 I2C multiplex channels,
Is it possible to read the ADC as shown in the block diagram [![Block Diagram][1]][1]
if yes, please help with code.

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

title: Using TCA9548A to read 30 ADCs

Answers: 0


body:
I've been struggeling with this assignment for school for a couple of days. I have finally figured out where the problem lies.
I have an oled screen that is supposed to print out the temperature of a DHT11, at the same time a RF sender should transmit the temperature to another microcontroller. The first microcontroller should also be able to recieve messages via RF and display them on the screen.

I've been having trouble with the oled screen. When i include my RF communication .head file, the oled wont work!!! I Cant understand why and it's really bugging me, I'm thinking it might be a memory problem, but the arduino IDE tells me it is only using 61% of the storage space. I'm using a arduino nano but i also have an Uno and a Mega laying around.
Do you think i should try the Uno or is there a problem in the code somehow?
Thank you so much!

main.ino:

    #include "display.h";
    //#include "DHT.h";
    #include "Radiocom.h";

    //long temperature;
    String message = "abc123";

    void setup()
    {
      Serial.begin(115200);
      //initDHT();
      initDisplay();
      //initRF();
    }

    void loop()
    {
      //temperature = readTemp();
      //delay(1000);
      //printTemp(temperature);
      printMessage(message);
      //sendMsg();
      //RFlisten();
      delay(1000);
    }

radiocom.h:

    #include <RH_ASK.h>
    //for feather huzzah ESP:
    //RH_ASK rf_driver(2000,13, 12, 14);
    RH_ASK rf_driver;

    void initRF(){
      rf_driver.init();
      Serial.println("Radio transmitter initiated..");
    }

    void sendMsg(){
      const char *msg = "testing testing, one two";
      rf_driver.send((uint8_t *)msg, 24);
      rf_driver.waitPacketSent();
      delay(1000);

    }

    void RFlisten(){
      uint8_t buf[24];
      uint8_t buflen = sizeof(buf);
      if(rf_driver.recv(buf, &buflen)){
        Serial.print("Message received: ");
        Serial.println((char*)buf);

      }

    }

display.h:

    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>  // Include core graphics library for the display
    #include <Adafruit_SSD1306.h>  // Include Adafruit_SSD1306 library to drive the display

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels

    // Define SPI pins:

    #define OLED_MOSI   9
    #define OLED_CLK   6
    #define OLED_DC    7
    #define OLED_CS    8
    #define OLED_RESET 13

    // Create display
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
      OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

    void initDisplay(){

      delay(100);

      display.begin(SSD1306_SWITCHCAPVCC);

      display.clearDisplay();  // Clear the buffer

      display.setTextColor(WHITE);  // Set color of the text

      display.setRotation(0);  // Set orientation. Goes from 0, 1, 2 or 3

      display.setTextWrap(false);  // By default, long lines of text are set to automatically “wrap” back to the leftmost column.
                                   // To override this behavior (so text will run off the right side of the display - useful for
                                   // scrolling marquee effects), use setTextWrap(false). The normal wrapping behavior is restored
                                   // with setTextWrap(true).

      display.dim(0);  //Set brightness (0 is maximun and 1 is a little dim)

      Serial.println("Display initiated..");

    }

    void printMessage(String message){
      display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0
      display.setTextColor(WHITE);
      display.setCursor(0,50);
      display.clearDisplay();
      display.print(message);
      display.display();
      Serial.println("printing message on display");
      delay(1000);

    }
    void printTemp(long temp){

      display.setTextSize(0);  // Set text size. We are using a custom font so you should always use the text size of 0

      display.clearDisplay();  // Clear the display so we can refresh
      // Print text:
      display.setCursor(25, 15);  // (x,y)
      display.println("temp:");  // Text or value to print
      // Draw rectangle:
      display.drawRect(79, 0, 35, 27, WHITE);  // Draw rectangle (x,y,width,height,color)
                                               // It draws from the location to down-right

      // Print variable with left alignment:
      display.setCursor(83, 20);  // (x,y)
      display.println(temp);  // Text or value to print

      display.display();  // Print everything we set previously
      Serial.println("Printing temp..");

    }

title: Radio tx/rx makes my oled screen not work

Answers: 0


body:
I am reading from [wireless temperature sensor][1] with help of gateway receiver connected to Arduino UNO, using this [code][2]

I need to display the data of the wireless sensor on the webpage.
Any suggestion on which help to start working using serial com or should I have to use Ethernet port for this?

  [1]: https://store.ncd.io/product/industrial-long-range-wireless-temperature-humidity-sensor/
  [2]: https://github.com/bhaskar-anil429/Long-Range-wireless-temperature-Humidity-sensor-Arduino/blob/master/Long_Range_Wireless_Temperature_Humidity_Sensor_Arduino.ino

title: Display Wireless Temperature Sensor data to Web page by using Serial communication

Answers: 1

body:
So you want to read serial port data from a webpage, I am not a web developer, but I suggest you to read the following links.<br>
You can use a local server to read the data (NodeJs, php) :

 - https://stackoverflow.com/questions/20549151/how-to-read-serial-port-data-from-javascript
 - https://stackoverflow.com/questions/29619929/read-data-form-serial-port-on-windows-with-php


body:
I'm trying to connect to an arduino Mega At2560 unit connected via usb serial port in my linux based PC.
Using C code, I'm trying to send and receive simple text strings, just I'm able to send and receive on both sides.

On arduino:

    int incomingByte = 0;    // for incoming serial data

    void setup() {
        Serial.begin(19200);    // opens serial port, sets data rate to 9600 bps
    }

    void loop() {
      // send data only when you receive data:
      if (Serial.available() > 0) {

        // read the incoming byte:
        incomingByte = Serial.read();

        // say what you got:
        Serial.print((char)incomingByte);
      }

    }
basically just a loop that checks if there is serial data, and if so reads it and prints it back. there's a (char) conversion so I'll see right away the sent data is what I got back (linux side)

For the linux code I use the pretty standard code for opening a port which I found [here][1]

I call the Arduino "Table" as it will eventually operate a moving table through USB commands.

C file:

    #include "TableFunctions.h"

    bool connected=false;
    int fd;
    char *portname;

    int set_interface_attribs (int fd, int speed, int parity)
    {
            connected=false;
            struct termios tty;
            struct termios tty_old;
            memset(&tty, 0, sizeof tty);
            if (tcgetattr (fd, &tty) != 0)
            {
                    printf("PC: Error %d from tcgetattr  \n", errno);
                    return -1;
            }
            tty_old = tty;

            cfsetospeed (&tty, (speed_t)B19200);
            cfsetispeed (&tty, (speed_t)B19200);

            //tty.c_cflag |= B19200;
            tty.c_cflag     &=  ~PARENB;            // Make 8n1
            tty.c_cflag     &=  ~CSTOPB;
            tty.c_cflag     &=  ~CSIZE;
            tty.c_cflag     |=  CS8;

            tty.c_cflag     &=  ~CRTSCTS;           // no flow control
            tty.c_cc[VMIN]   =  1;                  // read doesn't block
            tty.c_cc[VTIME]  =  5;                  //
            tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines
            cfmakeraw(&tty);
            tcflush( fd, TCIFLUSH );

            if (tcsetattr (fd, TCSANOW, &tty) != 0)
            {
                    printf("PC: Error %d from tcsetattr  \n", errno);
                    return -1;
            }
            return 0;
    }

    void set_blocking(int fd, int should_block)
    {
            struct termios tty;
            memset(&tty, 0, sizeof tty);
            if (tcgetattr (fd, &tty) != 0)
            {
                    printf("PC: Error %d from tggetattr  \n", errno);
                    return;
            }

            tty.c_cc[VMIN]  = should_block ? 1 : 0;
            tty.c_cc[VTIME] = 10;            // 0.5 seconds read timeout

            if (tcsetattr (fd, TCSANOW, &tty) != 0)
                    printf("PC: Error %d setting term attributes  \n", errno);
    }

    void OpenSerialPort()
    {
        char *portname = "/dev/ttyACM0";

        printf("PC: Opening port to table \n");

        int fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);

        usleep(2000000);
        if (fd < 0)
        {
            printf("PC: Error %d opening %s: %s  \n", errno, portname, strerror(errno));
            return;
        }

        set_interface_attribs(fd, B19200, 0);  // set speed to 19,200 bps, 8n1 (no parity)
        set_blocking(fd, 0);                // set no blocking
        printf("PC: Connected\n");
        connected = true;
    }
    void PrepareWriteCommand(int numberOfCommands, const char *commands[numberOfCommands])
    {
        if(connected) //check if arduino still connected
        {
            for(int i = 0; i<numberOfCommands; i++) //go through commands
            {
                int bufferSize = strlen(commands[i]); //get the buffer size needed for this command
                char charArray[bufferSize]; //helper char array
                memcpy(charArray,commands[i],bufferSize);//copy command to the char array
                charArray[bufferSize]=0; //make sure there is a stop symbok at the end
                WriteSerialPort(charArray); //command is ready to be sent, send it.
            }
        }
    }
    int WriteSerialPort(const char *buffer)
    {
        printf("PC: Now writing: ");
        int n_written = 0; //how many bytes were written

        n_written = write(fd, buffer, strlen(buffer)); //write the command and return how many bytes were written

        printf("\n");

        //check bytes send and return ouput (error, nothing or x bytes sent)
        if(n_written<0)
        {
            printf("PC: Error %d from %s \n",errno, strerror(errno));
        }
        else if(n_written == 0)
        {
            printf("PC: Nothing was written  \n");
        }
        else
        {
            printf("PC: Written %i bytes  \n", n_written);
        }

    }

    int ReadSerialPort(char *buffer, unsigned int buff_size)
    {
        //check if arduino still connected
        if(connected)
        {
            //read the serial data
            if(read(fd,buffer,buff_size))
                return sizeof(buffer); //return how much bytes were read
            else
            {
                //else print nothing received
                printf("PC: Arduino not Connected (ReadSerialPort) \n");
            }
        }
    }

in OpenSerialPort I basically open a new fd, and call the functions that set the communication settings.
I use PrepareWriteCommand to make sure commands input from users are with a stop symbol and send them to WriteSerialPort where I use write() and print how many bytes were sent.

H file:

    #include <errno.h>
    #include <fcntl.h>
    #include <termios.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <stdbool.h>

    #define MAX_DATA_LENGTH 256

    int set_interface_attribs (int fd, int speed, int parity);
    void set_blocking(int fd, int should_block);
    void OpenSerialPort();
    void PrepareWriteCommand(int numberOfCommands, const char *commands[numberOfCommands]);
    int WriteSerialPort(const char *buffer);
    int ReadSerialPort(char *buffer, unsigned int buff_size);

Main:

    #include "TableFunctions.h"
    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char *argv[])
        {
            char output[MAX_DATA_LENGTH]; //char array to hold arduino output
            int received = 0; // check if read() got any bytes
            const char* commands[]={"test"}; //test command

            OpenSerialPort(); // open serial port

            PrepareWriteCommand((sizeof(commands)/sizeof(commands[1])),commands); //prepare command for sending

            usleep(500000); //wait for arduino response

            while(true)
            {
                ReadSerialPort(output,MAX_DATA_LENGTH);//check serial port for response
                if(strlen(output)>0) //if anything received
                {
                    printf("PC: received %i\n",received); //if yes, how many bytes
                    printf("PC: %s\n",output); //and what was received
                    usleep(500000);
                }
                else if(strlen(output)<=0) //else print nothing received
                {
                    printf("PC: Nothing received\n");
                }
            }
            return 0; //finish program
        }

I tried tweaking the tty flags settings with no success. Each time I run the C code I see the arduino resets (and after opening a new fd I give it some time for bootloading) but no communication is sent between the two.

Output:

    PC: Opening port to table
    PC: Connected
    testPC: Now writing:
    PC: Written 4 bytes

    PC: received 0
    PC:
Any help with understanding why the C code can't communicate with the Arduino will be highly appreciated!

  [1]: https://stackoverflow.com/questions/6947413/how-to-open-read-and-write-from-serial-port-in-c

title: C: No communication to a connected serial port?

Answers: 1

body:
Problem was in OpenSerialPort(). I set another variable fd which is local, thus given priority. then when OpenSerialPort() is done, it is deleted, and the global fd remain unset. This is why I can't send anything from or to the PC.

Thanks.


body: I was wondering this, because realized it takes quite time consuming due to all the lines of code I have to write.

title: Is there software to make an interactive GUI for my TFT touch screen shield?

Answers: 0