message:
Python - Arduino communication not reliable

I'm trying to establish basic communication between python and my arduino due. I have managed to get a message sent to the arduino and sent back, but the code that achieves this task does not give consistent results. I'm running python 3.5 with pyserial 3.3.

My Arduino Code:

    String incoming;

    void setup() {
            Serial.begin(9600);     // 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:
                    incoming = Serial.readStringUntil('\n');

                    // say what you got:
                    Serial.print("I received: ");
                    Serial.println(incoming);
            }
    }

My Python Code

    import serial

    arduinoSerialData = serial.Serial("COM5",9600,timeout=1)

    print("Initial in waiting:")
    print(arduinoSerialData.in_waiting)
    print("Initial out waiting:")
    print(arduinoSerialData.out_waiting)

    while (arduinoSerialData.in_waiting>0):
     garbage = arduinoSerialData.readline()
     print(garbage)

    nummessages =0

    while (nummessages<5):
     if (arduinoSerialData.in_waiting>0):
      myData = arduinoSerialData.readline()
      myData = myData.decode('utf-8')
      myData = myData.strip()
      print("The Arduino says:")
      print(myData)
      nummessages=nummessages+1
     elif(arduinoSerialData.out_waiting>0):
      pass
     else:
      arduinoSerialData.write(b'Hello Arduino!\n')

    while (arduinoSerialData.in_waiting>0):
     garbage = arduinoSerialData.readline()
     print(garbage)

    print("In Waiting: ")
    print(arduinoSerialData.in_waiting)
    print("Out Waiting: ")
    print(arduinoSerialData.out_waiting)
    arduinoSerialData.close()

These print statements are largely my failed attempt to diagnose the problem. The "garbage" loops were my attempt to make sure conditions were as identical as possible when the python code starts up. If I start the arduino program running and then call this python program from my command line I get inconsistent results. Sometimes my first call to the python "works" and then others won't, sometime it works several times in a row, and that first line out output where it says "The Arduino Says: I" will have a varying amounts of the "I Received: Hello Arduino" message the arduino was supposed to send. Any Ideas what could be causing this lack of consistency? If I try starting the python code first, the arduino can't even start up.

![enter image description here][2]

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

body:
In case other people run into similar issues, I'll lay out what I've found today.

-The inconsistent output was due to the fact that when you open a serial connection with python, it resets the Arduino and so python can send signals without the arduino having finished its setup() function. If I put in a 1 second delay on the python side, inconsistency stops and I no longer run into byte errors at all. I'm looking into alternative means of preventing this reset since the time delay is a deal-breaker for me.

UPDATE:
Replacing

    arduinoSerialData("COM5",9600,timeout=1)

with

    arduinoSerialData = serial.Serial()
    arduinoSerialData.port = "COM5"
    arduinoSerialData.baudrate = 9600
    arduinoSerialData.timeout = 1
    arduinoSerialData.setDTR(False)
    #arduinoSerialData.setRTS(False)
    arduinoSerialData.open()

seems to bypass the reset. I included both the setDTR and SetRTS functions here because although setDTR works for DUE, it seems some other Arduino boards need setRTS instead.

-The decode() function has a keyword argument called errors, which can be set to "ignore" if you want the code to just ignore things that can't be interpreted in your desired format. With just this keyword setup, I never got errors but output was inconsistent due to reset.


sender: user

sender: assistant

body:
### Problem:
  Arduino being a **microcontroller** ( not a microprocessor ), is **not efficient enough**. If noticed carefully, messages sent to the Serial monitor gets **overlapped if the time interval between 2 messages is less than half a second** !! Also, there is an equal possibility of overlapping of data from Arduino resulting in **garbage data** !!
___
### Solution:
  To overcome these, python modules named **Arduino_Master** and **Arduino_Master_Delta** are available.

  These modules also help you to **visualize data** in the form of graphs as well as **filter data and remove garbage values**.

**Arduino_Master is used for approximation and easier interface**
whereas
**Arduino_Master_Delta is used for accurate data representation**!
___
### Links:
  Links to their documentation is given below :

[Arduino_Master](https://pypi.org/project/Arduino-Master/)

[Arduino_Master_Delta](https://pypi.org/project/Arduino-Master-Delta/)
___
### Examples:

The code for all these can be found in Arduino_Master_Delta 's documentation.

![Lights](https://github.com/SayadPervez/Arduino_Master_Delta/blob/master/Light Intensity.jpeg?raw=true)

![Impulse_Detection](https://github.com/SayadPervez/Arduino_Master_Delta/blob/master/Impulse Detection.png?raw=true)

![Impulse_Removal](https://github.com/SayadPervez/Arduino_Master_Delta/blob/master/Impulse Removal 3.jpeg?raw=true)


message:
What not to do to an Arduino

I may have been working with my Arduino UNO board improperly,
because now it fails to upload sketches (says some programmer is not responding)
and when I press the cute little restart button, the green LED doesn't do its blink anymore. I am aware what that means, but what I really wonder is how should I properly care the board. I probably will have no other chances to buy more arduinos so this information follows to be of a great importance.
___
As an example I would give, is touching the arduino board with bare hands risky, how much shock-tolerant it is, what if I mistake some pins, are there pins that cannot be mistaken, what will happen if I declare a pin as an output, but use it for input and the contrary, is loading a PWM program onto TFT touch screen shield unhealthy and so forth and briefly - **how should I properly care the arduino board.**

body:
A lot of things can happen to ruin an Arduino board, although so far I made mistakes and none has broken. However, possible causes can be:

- Electrostatic energy, you can prevent it by buying an ESD mat/wristband, or if you don't want to spend money, touch regularly some 'earth' like the central heating
- There should not be too much current on a pin ... so don't try to run too many leds or even a motor which is too big from a pin.
- Watch out with external power supplies
- Don't forget resistors where needed, because of the previous point
- Shaking should not matter much, unless you shake so hard that breadboard components are touching each other
- Running a program for something else (like PWM on touch screen) might be hard to explain ... it can ruin the device connected, and possibly the Arduino too.

Just some tips:

- Whenever you change some hardware/wiring, remove the power
- Check very carefully that everything is wired correctly
- Keep the Arduino on a solid place (don't let the USB cable let it overthrow/fall on the floor)


body:
it is okay to use for simple experiments directly. But while you choose to opt for a complex tasks read the details about all the components and their wiring techniques.
specifically try to check soldering is done correctly or not while connecting the wires to any component or to other wire. wrong soldering may damage your parts and arduino as well.
Be careful while using power supply, more when it comes to use multiple sources.
read carefully before you do anything. Dont be afraid just be careful.


message:
Use timer0 without affecting millis() and micros()

I'm writing a library which needs an ISR to turn off an LED some time after it was turned on. Since it's all about turning an LED on and off it doesn't need to be very precise. On the other hand I would like to use this library in a program where timer1 and timer2 are given out to other (more important) tasks, and I also need the `millis()` and `micros()` functions. Last, I'm using an ATmega328P microcontroller, which only has 3 timers (and I can't easily replace it with another one).
___
So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions, and – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...) and the disadvantages or side effects in using this timer in a non-Arduino library and the Arduino `millis()` and `micros()` functions.

Thanks in advance for any answer!

body:
An interrupt can only have one interrupt service routine. The only way you can do something else using an interrupt that is already handled elsewhere would be to modify that existing interrupt handler to also call your code. Not something that is practical for a library.

I can see no practical way of doing it short of modifying the entire `millis()` system in the main API to allow hooking of callback functions, which would be a really nice facility (chipKIT has a similar system with the Core Timer interrupt on the PIC32) and submitting it back to Arduino for inclusion in the main core - which would set a baseline version for compatibility of your library of course.


body:
> So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions,

Yes. A few ways, depending on your level of comfort:

1. You can declare the stock Arduino Timer0 OVF "weak" and write your own where you can insert your ISR. But you have to handle the interaction between the millis() / micros() related variables.

2. You can modify the stock Arduino Timer0 OVF to insert your own ISR.

    And – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...)

    The stock ISR would look like this:

        ISR(TIM0_OVF_vect) {
            ...
            timer0_fract = f;
            timer0_millis = m;
            timer0_overflow_count++;

            //insert your isr here
            _mytmr0_isrptr();
        }

    Where _mytmr0_isrptr() is a function pointer to your own ISR handler.

3. The simplest is probably to use the output compare interrupts. You can get it to behave like a virtual timer and can do lots of other stuff.

Obviously, you can think of tons of other ways and this is just a starting point.

> What are those interrupts? How can I use them? –

Timer0 has three interrupts associated with it: overflow and compare channel A and channel B. The overflow interrupt is already being used by the timing functions millis() and micros(), as shown earlier.

The compare channel A/B interrupts are unused. And this discussion is about using them for timing purposes.

The general ideal is demonstrated in blog post *[Using Spare Output Compare Channels as Timers – the Collection][1]*.

The task there is more complicated than what you are trying to do here, but the basic ideal is the same. To do what you wanted here it is much simpler than that.

If you still cannot figure it out, I can provide you with code pieces to get you started.

  [1]: https://dannyelectronics.wordpress.com/2017/06/23/using-spare-output-compare-channels-as-timers-collection/


body:
> So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions ...

No, because those functions use an already-attached interrupt.

>  it doesn't need to be very precise ...

Just test for the current time (eg. using `millis` or `micros`) in your main loop.

> the program main loop is sometimes quite long (e.g. sometimes it has to execute other loops) ...

Restructure so that it doesn't do that. You can use the [state machine](http://gammon.com.au/statemachine) concept to do things from time to time, without getting stuck in inner loops for a long time.


body:
I think the first solution suggested by dannyf's answer is wrong as ISR in AVR GCC can't be defined as weak function ([why][1]).

I think the best solution is to add handler (AKA hook) functions using function pointer to the Timer0 ISR inside the core wiring.c source file shipped with Arduino core, and assign latter (attache) this function pointer to any desired function in the other library/class or in the main application code.

More about this trick in this [article here][2].

  [1]: https://stackoverflow.com/questions/45481305/why-cant-avr-interrupt-vectors-be-attribute-weak
  [2]: https://atadiat.com/en/micros/e-arduino-trick-share-interrupt-service-routines-between-libraries-application/


message:
Arduino, Serial and wrapper class

I am working on an Arduino project, that would use HardwareSerial object reference stored in a class and call methods on it. However, there is problem with writing output using the reference.

Minimal use case to demonstrate behavior is in following files:

##main.ino

    #include <Arduino.h>
    #include "testclass.h"

    TestClass testClassInstance(Serial);

    void setup() {

    }

    void loop() {
        testClassInstance.print("Hi There\r\n");
        delay(1000);
    }

##testclass.h

    #ifndef TESTCLASS_H
    #define TESTCLASS_H

    #include <Arduino.h>

    class TestClass {
    public:
        TestClass(HardwareSerial &serial);
        void print(const char * text);

    private:
        HardwareSerial _serial;
    };

    #endif

##testclass.cpp

    #include "testclass.h"

    TestClass::TestClass(HardwareSerial &serial) : _serial(serial) {
        _serial.begin(9600);
        _serial.print("Initializing\r\n");
    }

    void TestClass::print(const char *text) {
        _serial.print(text);
    }

After reset, there are only two characters sent: "In"

In the example above, initialization is done before setup() method and Serial's state is probably reset before calling it. Having changed that to dynamic allocation in setup method did not change this behavior as well.

## modification of main.ino

    TestClass *testClassInstance;

    void setup() {
      testClassInstance = new TestClass(Serial);
    }

There might be problem with passing the reference to Serial, but in that case I would expect to not have any output at all.

Any help is greatly appreciated.

body:
You can't do complex tasks (or anything that relies on the Arduino API in any form) in your constructor. Simply because that all gets called *before* the Arduino API initializes, and in so doing the serial port gets disabled.

Instead you should do your complex operations and API-based operations in `.begin()`, which is why 99.99% of all libraries (*including HardwareSerial*) have a `.begin()` method.


body:
I have debugged deeper and the problem was somehow passing HardwareSerial to constructor as parameter with `HardwareSerial &serial`.

When changing it to pointer `HardwareSerial *serial` and using access via pointer-type variable, everything works.

Many thanks for suggestions.


message:
Arduino Mega, PWM analogWite doesn't work with Timer interrupt

Can anybody explain me, why the PWM doesn't work in such a simple example?

Generally, Timer interrupt is being called once per 100 ms and then in the interrupt function the bool flag (**state** ) is being set. Then in the main loop the flag is checked and when it is 1 (true) several instructions are being executed. Next, PWM is generated and measured via ADC and also displayed on the LCD.

The problem is that the PWM is generated as 0 or sligthly over the 0, even when the value put to the  **analogWrite** is 255 (max of 8 bit). Variable **counter** is incremented without problems and this value is being put to the **analogWrite** and despite it the PWM doesn't work.

I don't know, totally, what can be wrong.

Can anybody help me?

     #include<LiquidCrystal.h>
     #include<TimerOne.h>

      LiquidCrystal lcd(52, 50, 48, 46, 44, 42, 40);

      int out = 12;
      int in = A7;
      volatile bool state;

      int counter = 0;
      volatile int y;

      void setup()
      {
        lcd.begin(16, 2);
        lcd.clear();
        pinMode(out, OUTPUT);
        pinMode(in, INPUT);

        analogReference(DEFAULT);
        Timer1.initialize(100000);
        Timer1.attachInterrupt(functionInterrupt);

         state = 0;
          y = 0;
       }

       void loop()
       {
         y = analogRead(in);
         y = y / 4;
         y = y - 128;

        if (state == 1)
        {
          state = 0;

          counter++;
          if (counter > 255)
          //counter = 0;
          counter = 200;

          //state = 0;
         }

          analogWrite(out,counter);

          lcd.home();
          lcd.setCursor(0, 1);
          lcd.print(counter);
          lcd.setCursor(12,1);
          lcd.print(y);
         }

        void functionInterrupt()
        {
          state = 1;

         }

body:
When you use a timer to generate an Interrupt Service Routine (as you do with the TimerOne library) you change the configuration of that timer (in your case timer1). The timer is used by the TimerOne library to provide an interrupt, but also by the microcontroller itself to produce a PWM signal on some pins depending on the timer: in your case (Arduino Mega, timer 1) on the 11 and 12. If you use one of these pins as "analog" output while controlling an ISR with the same timer you won't get the expected output, because the timer isn't any more configured as needed by the PWM generation mechanism but as needed by you (you changed the configuration of the timer in the `Timer1.initialize(100000);` function call).
___
So, either you use another PWM pin as output either you use a timer library which uses another timer (or you implement it by yourself).


body:
>     if (state = 1)

This is setting `state` to 1, not testing if it is equal to 1. In other words, it will always be true.


message:
I bought ATmega328p with bootloader and I can't erase it

I bought an online deal which had 10x ATmega328p with bootloader installed. I thought I can erase the bootloader once I got the order (I want to write custom task without a bootloader) but my programmer does not seem to find the ATmega328p. I know it is the problem of the microcontroller because I have another ATmega328p which works fine and I can upload code to it. Is there a flag or switch I am missing when trying to overwrite the bootloader on the microcontroller?

Here are the components I am using:

- ATmega328p with bootloader
- SparkFun Pocket AVR Programmer (usbtiny)

Here are the commands I am using:

- To compile: `avr-gcc -std=c11 -mmcu=atmega328 -O -o main.o main.c`
- To generate hex: ` avr-objcopy -O ihex main.o main.hex`
- To upload: `sudo avrdude -c usbtiny -p m328p -U flash:w:main.hex`

Here is the output of the `avrdude` command:

    avrdude: Using SCK period of 10 usec
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

Anyone encountered similar situation before? How did youu managed to fix it? I appreciate any help :)

Thank you

**Edit #1** I tried setting the `-B` flag to various values but nothing seems to solve the problem.

**Edit #2** Here is the circuit I am using while programming the ATmega328p

* 2x Capacitors 22pf
* 1x Crystal oscillator 16Mhz
* 1x Resistor 10K ohm
* 1x ATmega328p
* 1x SparkFun Pocket AVR Programmer

<img src="https://i.stack.imgur.com/VZyDi.jpg"/>

body:
Your connections to the ATmega328p are incomplete.

You are missing the connection of ground to pin 22, and you must supply power to AVCC on pin 20.

You should also place the capacitors much closer to the crystal with a very direct route to ground, and try to place the crystal itself closer to the chip.

Additionally you should use supply bypass capacitors.

Please see the minimum wiring at [Arduino on a Breadboard][1], however this document itself is erroneous as it neglects to show the high frequency 0.1 uF bypass capacitors you should have *directly* across each pair of power pins.

That's not to say that there may not be additional issues as well - but you need to fix the circuit problems first.

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


message:
Possible reason for broken Uno

Yesterday I wrote in a comment that I didn't break much, except a LED and a LED matrix. However, exactly yesterday I think my Uno gave up, since I cannot upload a sketch anymore (timeouts). For the rest the board seems to work still ok.

I have two possible reasons, and would like to know what I can do to prevent this in future. I connected a 415 MHz RF transmitter and receiver to it, which are working.

1. To get more power I attached an adapter (12V), TOGETHER with the USB ... I thought always adapter power would be used, but it seems it is not a good idea to have both connected. Is this true?
2. The Uno was inside a case (with holes near the output pins). I know this causes some extra heat, but I would guess that adding just an RF receiver/transmitter would not cause the Uno to heat up more than allowed.

Which of these reasons is the possible cause ... or are there any other reasons I didn't think off. Everything worked fine until I plugged in the 12V adapter and it still worked for some time (until I tried to upload a new sketch).

body:
You should be OK as long as you use a 9 to 12 volt supply since there is an FET that disconnects the 5 volt USB power from the rest of the Arduino circuitry if VIN is greater than approximately 6.6 volts.

But... if your external voltage is less than 6.6 volts you may have a problem since both supplies will be powering the Arduino circuitry and they probably will not be providing exactly the same voltage.  If you get below the dropout voltage of the voltage regulator then you may have a bigger problem since the USB voltage will be backfeeding the voltage regulator.

There is a diode between the PWRIN connector and VIN so if you feed the Arduino from that connector the voltage will have to be greater than approximately 7.3 volts to activate the FET and anything less than 7.3 volts may cause the problems mentioned above.


body:
It is a mistaken belief that powering an Arduino from an external power source increases the power available. It doesn't. All it does is increase the amount of heat produced.

Unless you are powering your Arduino from an unpowered hub you will have around 500mA available from the USB power. The 5V regulator, which converts the incoming 12V to 5V, can supply at best between 800mA and 1A on a good day. However with 12V the amount of heat generated will cause thermal shutdown at those kind of currents due to lack of proper heatsinking. So you can't get anywhere near 800mA out of it - instead you are limited to around the same as (or even less than) the USB power source can provide.

All that excess heat (and at 12V you are throwing away about 58% of your power as heat) in an enclosed case will have caused nasty things to happen - at the very least your regulator should have gone into thermal shutdown. Worst case scenario your voltage regulator failed (especially if it's a cheap version) which would end with one of two scenarios:

1. No power getting through to the rest of the board
2. More than 5V getting through to the rest of the board

If it's (1) it'd be obvious - nothing works. No LEDs light, etc. However if it's (2) then more nasty things will ensue. One common one is that the ATMega16U2 chip (the USB interface chip) if it's a genuine Arduino will be fried. You may find it's getting excessively hot itself now. Of course, if it's a clone then the CH340G will no doubt have given up what little ghost it had.


message:
Interfacing Logitech Joystick to Arduino and interrupt a while loop

I am working on a project of a robot arm. The joints are made of servo motor. The basic function can be describe as:

- The robot arm (the servos) were moved manually by the Logitech joystick.
- The user could press a certain button to remember a position. I made 6 buttons for 6 positions, in detail.
- After the remembering, if an activating button was pressed, the robot arm would move repeatedly around those 6 positions **until a stopping button was pressed**.

The problem was the bold words.

In order to make the robot arm could move repeatedly with one pressing, I used a `while` loop.

However, when the program was in `while` loop, the joystick events stopped updating no matter how I pressed or pulled the joystick. Therefore, I couldn't program a stopping button.

I guessed that was because the joystick events were called outside the loop, but I don't know how to get it inside. My code was based on the example of the USB Host Shield library.

Here is the code. It contained 3 files. My robot also has some more function so I only quote the part that I had problem here.

.ino file:
<!-- language-all: lang-cpp -->

    #include <usbhid.h>
    #include <hiduniversal.h>
    #include <usbhub.h>
    #include "le3dp_rptparser.h"
    // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #include <SPI.h>
    #endif

    USB                                             Usb;
    USBHub                                          Hub(&Usb);
    HIDUniversal                                    Hid(&Usb);
    JoystickEvents                                  JoyEvents;
    JoystickReportParser                            Joy(&JoyEvents);

    //int waist_back, shoulder_back, wrist_back, gripper_back;

    void setup()
    {
      Serial.begin( 115200 );
    #if !defined(__MIPSEL__)
      while (!Serial);
    #endif
      Serial.println("Start");

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

      delay( 200 );

      if (!Hid.SetReportParser(0, &Joy))
          ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );

    }

    void loop()
    {
        Usb.Task();
    }

.cpp file: This was where I worked. Please look at the `JoystickEvents::OnGamePadChanged`

    #include "le3dp_rptparser.h"

    //Many parameters for robot here

    JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
     joyEvents(evt)
    {}

    void JoystickReportParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
    {
     bool match = true;

     // Checking if there are changes in report since the method was last called
     for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
      if( buf[i] != oldPad[i] ) {
       match = false;
       break;
      }
      }
       // Calling Game Pad event handler
     if (!match && joyEvents) {
      joyEvents->OnGamePadChanged((const GamePadEventData*)buf);

      for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
     }
    }

    void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
    {
      Serial.print("X: ");
      Serial.print(evt->x);
      Serial.print(" Y: ");
      Serial.print(evt->y);
      Serial.print(" Hat Switch: ");
      Serial.print(evt->hat);
      Serial.print(" Twist: ");
      Serial.print(evt->twist);
      Serial.print(" Slider: ");
      Serial.print(evt->slider);
      Serial.print(" Buttons A: ");
      Serial.print(evt->buttons_a);
      Serial.print(" Buttons B: ");
      Serial.print(evt->buttons_b);
      Serial.println("");

      // Manual control program here. I didn't post because it was so long.

      //Activation

      if (evt->buttons_a == 32){
        while (evt->slider == 0){

        //Robot working here, also a long code that was out of limit for a block here.

        Serial.print(evt->slider);
        }
      }
    }

.h file:

    #if !defined(__HIDJOYSTICKRPTPARSER_H__)
    #define __HIDJOYSTICKRPTPARSER_H__

    #include <usbhid.h>

    struct GamePadEventData
    {
      union { //axes and hut switch
        uint32_t axes;
        struct {
          uint32_t x : 10;
          uint32_t y : 10;
          uint32_t hat : 4;
          uint32_t twist : 8;
        };
      };
      uint8_t buttons_a;
      uint8_t slider;
      uint8_t buttons_b;
    };

    class JoystickEvents
    {
    public:
     virtual void OnGamePadChanged(const GamePadEventData *evt);
      static GamePadEventData mostRecentEvent;
    };

    #define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)

    class JoystickReportParser : public HIDReportParser
    {
     JoystickEvents  *joyEvents;

      uint8_t oldPad[RPT_GAMEPAD_LEN];

    public:
     JoystickReportParser(JoystickEvents *evt);

     virtual void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
    };

    #endif // __HIDJOYSTICKRPTPARSER_H__

After the `//Activation` under `JoystickEvents::OnGamePadChanged`, no matter how I pulled the slider of the joystick, the event was not updated, the `evt->slider` always returned zero and the robot arm couldn't be stopped.

Is there any method to update the joystick event inside the `while` loop?

Or another method other than `while` loop to make something move repeatedly after pressing one button, and can be stopped with another button?

Thank you so much for reading, and please help me!

body:
As full code is not posted I cant suggest you correctly but you should add the two buttons, START & STOP.

When STOP button is pressed all events (your code is performing on) should stop working.

Just make sure when you program for a joystick control, the code for START & STOP buttons  should fall under the joystick control loop.

    if (STOP PRESSED){

    }else if(START PRESSED){

        //INVOKE THE FUNCTIONS FOR ACTIONS TO BE PERFORMED
    }


body: The trick is to never use a while loop to wait for something physical to happen.  Instead write code that doesn't block execution of the rest of the code.  Write your code so that instead of sitting in a while loop, the function relies on being called over and over from the loop function.  Let the loop function do the looping.


message:
How to load Image in Arduino?

In my recent project, I want to load Image in my Arduino. Is there any library available that can be used for loading Image in Arduino. Give some suggestion. Thank you!

body:
Yes there is a library to load the image to Arduino called as "TFTLibrary".

Loads an image file from the SD card into a named instance of `PImage`. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. Images can be smaller or larger than the screen resolution (160x128), but there is no method on the Arduino for image manipulation. The images should be sized before you put them on the SD card. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. It is possible to load 24 bit bmp image only.

Syntax:

    screen.loadImage(name);

Details available on Arduino website:
https://www.arduino.cc/en/Reference/TFTLoadImage


message:
Include Adafruit_RGB LCD Shield library in class

I'm trying to make a class to expand on the functionality of the [Adafruit-RGB-LCD-Shield-Library](https://github.com/adafruit/Adafruit-RGB-LCD-Shield-Library) I'm creating this based on what I see [from this post.](https://stackoverflow.com/questions/1735990/using-classes-with-the-arduino)

    class LcdMenu
    {
     #include <Adafruit_MCP23017.h>
     #include <Adafruit_RGBLCDShield.h>
     public:
     Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
         void Setup()
         {
          lcd.begin(16, 2);
         }
         void Write(int line, char text[17])
         {
          lcd.clear();
         }
    };

    LcdMenu *LcdM;
    #define VIOLET 0x5

    void setup()
    {
      LcdM->Setup();
      LcdM->lcd.setBacklight(VIOLET);
    }

However, I'm getting the following error:
>C:\Users\jschere2\AppData\Local\Temp\ccUzvCmX.ltrans0.ltrans.o: In function `main':
>
>ccUzvCmX.ltrans0.o:(.text.startup+0xf0): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::begin(unsigned char, unsigned char, unsigned char)'
>
>ccUzvCmX.ltrans0.o:(.text.startup+0xf8): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::setBacklight(unsigned char)'
>
>collect2.exe: error: ld returned 1 exit status
>
>exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

body:
Move your `#include` statements outside the class definition.

You declare a pointer, but never allocate space for it with `new`. I see no need for a pointer.

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

    #include <Adafruit_MCP23017.h>
    #include <Adafruit_RGBLCDShield.h>

    class LcdMenu
    {
     public:
         // default ctor will be called here.
         Adafruit_RGBLCDShield lcd;

         void Setup()
         {
          lcd.begin(16, 2);
         }
         void Write(int line, char text[17])
         {
          lcd.clear();
         }
    };

    LcdMenu LcdM;
    #define VIOLET 0x5

    void setup()
    {
      LcdM.Setup();
      LcdM.lcd.setBacklight(VIOLET);
    }

Also note: you are not extending the `Adafruit_RGBLCDShield` class as in the example you linked. To do that:

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

    #include <Adafruit_MCP23017.h>
    #include <Adafruit_RGBLCDShield.h>

    class LcdMenu : public Adafruit_RGBLCDShield
    {
     public:
         void Setup()
         {
          begin(16, 2);
         }
         void Write(int line, char text[17])
         {
          clear();
         }
    };

    LcdMenu LcdM;
    #define VIOLET 0x5

    void setup()
    {
      LcdM.Setup();
      LcdM.setBacklight(VIOLET);
    }


message:
Saving EEPROM after programming on Arduino uno

I am using an Arduino Uno,  and I use the EEPROM to store some presets. It works fine. But, when I reprogram the Arduino, the EEPROM gets wiped out. Is there a way to prevent this, and have the EEPROM not change after the Arduino is programmed?

I am using a USBtinyISP programmer.

Thank you very much for your help, and advance.

Here is the verbose result of my programming:

    Sketch uses 5,298 bytes (16%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 286 bytes (13%) of dynamic memory, leaving 1,762 bytes for local variables. Maximum is 2,048 bytes.
    /Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/bin/avrdude -C/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cusbtiny -Uflash:w:/var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
            Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
            Copyright (c) 2007-2014 Joerg Wunsch

            System wide configuration file is "/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf"
            User configuration file is "/Users/fed/.avrduderc"
            User configuration file does not exist or is not a regular file, skipping

            Using Port                    : usb
            Using Programmer              : usbtiny
    avrdude: usbdev_open(): Found USBtinyISP, bus:device: 006:003
            AVR Part                      : ATmega328P
            Chip Erase delay              : 9000 us
            PAGEL                         : PD7
            BS2                           : PC2
            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  3600  3600 0xff 0xff
              flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
              lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
              hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
              efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
              lock           0     0     0    0 no          1    0      0  4500  4500 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 : USBtiny
            Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
    avrdude: programmer operation not supported

    avrdude: Using SCK period of 10 usec
    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.01s

    avrdude: Device signature = 0x1e950f (probably m328p)
    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
            To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: Using SCK period of 10 usec
    avrdude: reading input file "/var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex"
    avrdude: writing flash (5298 bytes):

    Writing | ################################################## | 100% 7.80s

    avrdude: 5298 bytes of flash written
    avrdude: verifying flash memory against /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:
    avrdude: load data flash data from input file /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:
    avrdude: input file /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex contains 5298 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 4.98s

    avrdude: verifying ...
    avrdude: 5298 bytes of flash verified

    avrdude done.  Thank you.

body:
You can change the fuses for `Atmega328` to preserve `EEPROM` during chip erase (for `ISP` programming). Basically, if you are using `USBTiny` connected to the `UNO` by `3x2` pin header, you are using `ISP programming`. Which means chip erase erases also `EEPROM` if fuse `EESAVE` is `1` (unprogrammed).

Uploading over the **`Arduino bootloader`** (it means you have the `UNO` connected directly into the computer and there is no other device like `USBTiny`). The `EEPROM` should be preserved then.


message:
Read and parse continuous serial stream

I'm trying to read in and parse a message in the form of `X123987` continuously streaming into a serial port. There are no new lines or control characters other than the `X` which marks the beginning/end of the message. The message contains two, three-character components, ex: `123`, and `987`. I'm trying to copy bytes as their read into a char array, and then on the control character, return the result, but while this compiles, I don't get any output, and it crashes constantly.

    #include <SoftwareSerial.h>

    SoftwareSerial RS485Serial(10, 11);

    char _byte_received;
    char _buffer[10];
    char _value[10];

    bool OnReceive()
    {
      if (RS485Serial.available())
       {
        digitalWrite(13, HIGH);
          _byte_received = RS485Serial.read();
          if (_byte_received == 'X') {
            strcpy(_value, _buffer);
            memset(_buffer, 0, 10);
            return true;
          } else {
            strcat(_buffer, _byte_received);
            return false;
          }
        digitalWrite(13, LOW);
       } else {
        return false;
       }
    }
    void setup() {
      Serial.begin(9600);
      Serial.println("Restarting...");
      pinMode(13, OUTPUT);
      pinMode(3, OUTPUT);
      digitalWrite(3, LOW);
      RS485Serial.begin(9600);
    }

    void loop()
    {
      if (OnReceive())
      {
        Serial.print("value: ");
        Serial.write(_value);
        Serial.println("");
      }
    }

Output:

    Restarting...
    value:
    Restarting...
    value:
    Restarting...
    value:
    Restarting...
    value:
    Restarting...
    value:

I expect to see `value: 123987`

body:
In `OnReceive`, you are concatening a string with a char. This may be the cause of the resets.

As a side note, you don't really need to use `strcat`, `strcpy` and other `str` functions. You can make your sketch lean by accesing the arrays directly, like this:

    char _buffer[10];
    int index = 0;

    bool OnReceive()
    {
      bool status = false;
      if (RS485Serial.available())
      {
        digitalWrite(Pin13LED, HIGH);
        char _byte_received = RS485Serial.read();
        if (_byte_received == 'X') {
          _buffer[index] = 0; // Mark the end of string.
          index = 0;
          status = true;
        } else {
          _buffer[index++] = _byte_received;
          // ToDo: check for overflow;
        }
        digitalWrite(Pin13LED, LOW);
      }

      return status;
    }
    void setup() {
      Serial.begin(9600);
      Serial.println("Restarting...");
      pinMode(Pin13LED, OUTPUT);
      pinMode(SSerialTxControl, OUTPUT);
      digitalWrite(SSerialTxControl, RS485Receive);
      RS485Serial.begin(9600);
    }

    void loop()
    {
      if (OnReceive())
      {
        Serial.print("value: ");
        Serial.print(_bufer);
        Serial.println("");
      }


message:
Writing serial data on a pin on Arduino

I want to write some data (GPS) to a digital port on Arduino.  As far as I understand sending data via a pin as if it were USB is possible. But I don't know what function to use. digital.Write doesn't expect any data or strings. How do I write serial data on to a digital pin

body:
The Aruduino Uno uses an ATmega328P which only has 1 hardware UART to help the software communicate serially with the outside world.  If you are already using this hardware resource (for example through the normal Arduino serial library), it is unavailable to talk to a 2nd external device.  In such a case you can [emulate a UART in software using this Software Serial Library][1] in exchange for some processor time (that is, using a software emulated serial port will slow down your program's execution).

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerial


body: Using the arduino library "software Serial" (https://www.arduino.cc/en/Reference/SoftwareSerial) you can use any pin to write/read serial data.


message:
Comparison of Board Shape between Arduino MEGA and Arduino DUE

I'm using KiCAD to design boards, and while it has a lot of Arduino templates, it doesn't have one for the Arduino Due. Now, I've did some searching, and it looks like the Arduino MEGA is very similar to the Arduino DUE, not the specifications, but the number of I/O pins and the overall shape of the board. I couldn't find a straight answer, so I decided to ask here: Can the template of the Arduino MEGA be used as a template for the Arduino DUE when designing custom 'shields' and such based on the number of I/O pins and overall layout?

body:
> The Due has the same footprint as the Mega 2560.

source


message:
Run two Loops Simultaneously on Arduino

I am not able to combine the below two sketches. What I require is to either run both the loops together or find a way to run both the functions inside a single loop.

Sketch 1

    #include <SevSeg.h>
    #include <DS1307RTC.h>
    #include <Time.h>
    #include <TimeLib.h>
    #include <Wire.h>

    // Create an instance of the object
    SevSeg sevseg;
    bool militaryTime = false; // true for 24 hour clock

    void setup() {
      byte numDigits = 4;
      byte digitPins[] = {2, 3, 4, 5};
      byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
      bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
      byte hardwareConfig = COMMON_ANODE; // See README.md for options
      bool updateWithDelays = false; // Default. Recommended
      bool leadingZeros = true; // Use 'true' if you'd like to keep the leading zeros

      sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros);
      sevseg.setBrightness(90);
    }

    void loop() {
      tmElements_t tm;
      int time;
      int dot;

      if (RTC.read(tm)) {
        time = tm.Hour * 100;
        if (time > 1200 && militaryTime == false) {
          time = time - 1200;
        }
        if (time == 0 && militaryTime == false) {
          time = 1200;
        }
        time += tm.Minute;
      }

      if ((tm.Second % 2) == 0) {
        dot = 4;
      } else {
        dot = 2;
      }

      //Produce an output on the display
      sevseg.refreshDisplay();
      sevseg.setNumber(time, dot);
    }

Sketch 2

    // Change this to the output pin you are using
    #define TICK_PIN A0

    void setup()
    {
      pinMode(TICK_PIN,OUTPUT);
      while (1) {
        tone(TICK_PIN,1000,2);
        delay(1000);
      }
    }

    void loop()
    {
    }

body:
One way is to use a timer callback.

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

    // Include the timer1 library
    #include "TimerOne.h"

    // Other code here...

    void setup()
    {
        // Other setup code here....

        // Setup timer
        Timer1.initialize(1000000);          // 1 second
        Timer1.attachInterrupt(callback);    // Set callback
    }

    void callback()
    {
        tone(TICK_PIN, 1000, 2);
    }

    void loop()
    {
        // Code from 1st loop here...
    }

If that doesn't work (if something else is using timer1) you could just keep track of the time between beeps:

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

    uint32_t last_beep = 0;
    const int beep_timeout = 1000;

    void loop() {
        // Code from first loop here

        uint32_t now = millis();
        if (now - last_beep >= beep_timeout) {
            tone(TICK_PIN, 1000, 2);
            last_beep = now;
        }
    }


body:
Basically you need to get rid of the delay and any other blocking loops. Here is a way to do it.

Define this variable globally.

    unsigned long lastTime = 0;

Then in your first loop, add the following code either to the beginning or the end:

    if (millis() - lastTime >= 1000 || !lastTime) {
        lastTime = millis();
        tone(TICK_PIN,1000,2);
    }


body:
I fund the easiest way to work on this challenge when you have to deal with a long delay and think you need a second loop, is to make make a counter in the main loop using centiseconds (10 milliseconds) and then trigger your required response when the counter reaches your time like
void loop(void) {
counter=counter +1;
if (counter==100){
tone(TICK_PIN, 1000, 2);
counter =0;
}
....rest of code


message:
Buzzing on computer speakers when LEDs are on

I have an Arduino Nano connected via USB to a Mac Mini. When the LEDs come on, an external speaker connected to the Mini starts to hum/buzz quite loudly. If the LEDs are turned off, the buzz stops.

The speaker and the Mac mini are both powered independently, and are plugged into one wall socket, while the 5V power supply to the LEDs and the Nano is plugged into a different socket (of the same outlet).

What could be causing the buzz and what are the possible remedies?

body:
If this is the same project you described in [this question][1](readers: "112 WS2811s in series" causing interference), your external speaker may not be filtered very well against energy radiated by nearby un-shielded wiring. Try a pair of headphones in place of the speaker - does it also buzz? If not, the speaker (system) is probably picking up the interference. If so, the pickup is probably within or near the Mac mini.

You could try a few simple solutions (or at least tests that might narrow the problem):

 - shielded audio cable from the Mac mini to the speaker;
 - shielding the speaker enclosure and grounding the shield;
 - shielding the connections to the LED string (obviously shielding the LED string itself is likely to be aesthetically undesirable);
 - separating the speaker from the LED strip by more distance;
 - powering the mini from batteries - at least long enough to learn whether the power wiring might be involved.

  [1]: https://arduino.stackexchange.com/questions/39459/leds-interfering-with-analog-sound-detection


message:
ESP Wemos D1 upload fails

I try to upload simple code (e.g. blink.ino) to my ESP8266-12 (I have the WeMos D1 breakout board). Until now, that worked without a problem: I had to pull GPIO0 down and then I could upload the compiled sketch.

Since today that does not work any more - but I did not change anything.

I get:

> error: espcomm_upload_mem failed

(I know that here are some questions / github issues out there that have the same error, but that was often because GPIO0 wasn't pulled down and the ESP was therefore not in FLASH mode.)

My config is: ESP8266, 80MHz, DIO, 115200, 512K (64K SPIFFS), ck, Serial

When I reset my board, having GPIO0 pulled down, the ESP sends this serial info:

> ets Jan  8 2013,rst cause:2, boot mode:(1,7)

The whole debug output is:

    esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
     setting board to ck
     setting baudrate from 115200 to 115200
     setting port from COM1 to COM6
     setting address from 0x00000000 to 0x00000000
     espcomm_upload_file
     espcomm_upload_mem
     setting serial port timeouts to 1000 ms
    opening bootloader
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
    Uploading 228624 bytes from D:\Users\myusr\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.bin to flash at 0x00000000
     erasing flash
     size: 037d10 address: 000000
     first_sector_index: 0
     total_sector_count: 56
     head_sector_count: 16
     adjusted_sector_count: 40
     erase_size: 028000
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     setting serial port timeouts to 15000 ms
     read 0, requested 1
     setting serial port timeouts to 1000 ms
    warning: espcomm_send_command: didn't receive command response
    warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed
    closing bootloader
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
    error: espcomm_upload_mem failed

body: As I found out, GPIO0 has to be LOW **AND** GPIO2 has to be HIGH. It is very important to use pin D3 as GPIO0 and pin D4 as GPIO2 at the WeMos D1 board, because this "routing" is different for other boards and therefore other digital pins are often described.


body: I was facing the same problem, I simply updated CH34x driver for esp8266 to v1.4 from v1.3 after that I was able to see a new port option named usbserial 1420 & wchusbserial 1420. after selecting wchusbserial 1420 I was able to upload program successfully. As  my MacOs running on Mojave


message:
Arduino: Connect UNO to A7 AI Thinker

I just cannot connect or send AT command from my UNO to A7 AI Thinker module. This is the connection:

    UNO    ->    A7
    TX     ->    RX
    RX     ->    TX
    USB    ||    5V    -> External Power Supply
    GND    ->    GND

Without any sketch, I tried to send AT command from serial monitor, and nothing happened.

Different case if I use USB TTL to A7

    USB TTL   ->   A7
    VCC (5v)  ->   5V
    GND       ->   GND
    TX        ->   RX
    RX        ->   TX

Then it is OK, I can send all AT command, SMS, Call, etc from the serial monitor.

Just what is happening with UNO? Does my UNO RX TX Faulty? How to check it?

body:
>Without any sketch, I tried to send AT command from serial monitor, and nothing happened.

The problem is with your connections to the Uno. Although it seems wrong, the correct connection when you're using the Uno as a USB-serial adapter to communicate with the A7 AI Thinker module from Serial Monitor is:

    Uno                A7
    TX (pin 1)   ->    TX
    RX (pin 0)   ->    RX

The RX and TX markings on the Uno refer to the pins on the ATmega328P microcontroller. But you're not using that microcontroller, you're communicating between the USB-serial chip on the Uno and the A7. The RX line of the USB-serial chip is connected to the TX pin of the ATmega328P and thus to pin 1, the TX pin of the USB-serial chip is connected to the RX pin of the ATmega328P and thus to pin 0. For this reason the connection between the Uno and A7 shown above are actually an RX-TX, TX-RX connection between the USB-serial chip and the A7.

If you were communicating between the ATmega328P on your Uno and the A7 then the connections you used would have been correct.


message:
Adafruit nRF52 feather board [SOLVED]

I am working on a project (the scenario is depicted in the attachment) involving Bluetooth Low Energy (BLE). As a master (central device) I am using the Adafruit nRF52 feather board (https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/introduction) and as slaves (peripheral devices) a pair of Adafruit nRF8001 modules (https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/pinouts?view=all#introduction). Moreover, I have to wire the nRF52 up with an Arduino Uno rev3.

I am trying to set up the very initial communication between central and peripheral devices, but if I even try to upload the blinky sketch into the nRF52 board the compiling phase returns to me the following error:

> exec: "nrfutil": executable file not found in $PATH

Does anyone have an idea what it means? I googled a lot but I am not able to figure it out on this problem.

Thanks in advance to anyone would be able to help me!

Filippo

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

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

**[EDIT]** Solved: just need to install the nfrutil first, as written in https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/arduino-bsp-setup#nrfutil-os-x-and-linux-only

body:
Step 2 solves this problem:

https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/arduino-bsp-setup

Also, read up about how to add something to Path Variable on Windows.


message:
CH340 max serial speed

With an Arduino-like board using a CH340 USB Serial chip, I'd like to send text lines as fast as possible to a Raspberry Pi through USB using the *Serial.println()* function. The problem is that when I set the serial speed to values above 230 400 with the *Serial.begin(speed)* function, the Arduino console crashes and the C program on the Rapsberry Pi displays garbage in its console, even though I set the same serial speed.

Short examples :

    Serial.begin(230400);
    Serial.println("Test !"); // Works fine.

    Serial.begin(250000);     // Or any speed above 250 000.
    Serial.println("Test !"); // Doesn't work at all.

[This answered question][1] states that 2 Mbauds is possible, so I'm a bit lost.

The Arduino IDE console offers various speed from 300 to 2 000 000 bauds, so why don't speeds above 230 400 work ?

  [1]: https://arduino.stackexchange.com/questions/296/how-high-of-a-baud-rate-can-i-go-without-errors

body:
CHG340 supports common baud rates: 50, 75, 100, 110, 134.5, 150, 300, 600, 900, 1200, 1800, 2400, 3600, 4800, 9600, 14400, 19200, 28800, 33600, 38400, 56000, 57600, 76800, 115200, 128000, 153600, 230400, 460800, 921600, 1500000, 2000000 baud.

**250 000 baud** isn't supported by that IC.

The Baud steps is either 200% or 150% of the previous value (There is exceptions).

**Tested and working Baud rates.**

I used putty as serial monitor since the built in monitor didn't have all baud rates preprogrammed.

**SpeedTest.ino**

    // Serial port Baudrates:
    // const int Speed = 115200;
    // const int Speed = 128000;
    // const int Speed = 153600;
    // const int Speed = 230400;
    // const int Speed = 460800;
    // const int Speed = 921600;
    // const int Speed = 1500000;
    const int Speed = 2000000;

    void setup() {
      // Initialize serial:
      Serial.begin(Speed);

      // Initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);
      delay(1000);
      digitalWrite(LED_BUILTIN, LOW);
      delay(1000);
      Serial.print("Speed :  ");
      Serial.println(Speed);
    }


message:
analogRead() hangs

With this code I try to send a measurement over 443MHz using RadioHead. All parts work but when combined they fail. This chip used is an ATtiny85.

The function 'measure' torpedoes the entire program. If it is used, it will compile but it will never run Setup or Loop. I know this because I use a Logic Analyzer and Software Serial. I can see the Serial Port, PB1, hanging high.

I would like to know what is so wrong about function `measure` that it undermines all code..

    #include <Arduino.h>
    #include <SoftwareSerial.h>
    #include <RH_ASK.h>   // local libs at
    #include <powernap.h> // /home/thijs/.platformio/lib

    #define TICKLE_ID 192

    #define SENSOR1_PIN 2
    #define SENSOR1_PWR 4
    #define SENSOR2_PIN -1
    #define SENSOR2_PWR -1

    #define SOFTWARE_SERIAL_TX_PIN 1
    #define SOFTWARE_SERIAL_RX_PIN -1

    #define RADIOHEAD_BAUD 2000
    #define RADIOHEAD_TX_PIN 0
    #define RADIOHEAD_RX_PIN -1

    struct tickle {
      uint16_t id = TICKLE_ID;
      uint16_t value1;
      uint16_t value2;
    };

    Napper napper;
    SoftwareSerial mySerial(SOFTWARE_SERIAL_RX_PIN, SOFTWARE_SERIAL_TX_PIN);
    RH_ASK driver(RADIOHEAD_BAUD, RADIOHEAD_RX_PIN, RADIOHEAD_TX_PIN);

    void senddata(int hygro) {
      mySerial.print("Senddata");
      struct tickle package; // make a Tickle package
      package.id = TICKLE_ID; // hard-coded device ID
      package.value1 = 0; // any positive int up to 2^16
      package.value2 = hygro; // any positive int up to 2^16
      driver.send((uint8_t *)&package, sizeof(package));
      driver.waitPacketSent(); // wait for it ~Barney
    }

    int measure() {
      mySerial.print("Measure");
      pinMode(SENSOR1_PWR, OUTPUT); // enable sensor
      pinMode(SENSOR1_PWR, HIGH); // turn on sensor
      delay(100); // wait for sensor to settle

      int i; // int for counter
      int data = 0; // data container

      for (i = 0; i < 5; i++){ // cumulate 5 measurements
        data = data + analogRead(SENSOR1_PIN);
      }

      data = data / 5; // avg of measurements
      pinMode(SENSOR1_PWR, LOW); // turn off sensor
      pinMode(SENSOR1_PWR, INPUT); // disable sensor
      mySerial.print(data);
      return data; // return avg measured value
    }

    void setup() {
      mySerial.begin(600); // 600 baud serial
      mySerial.print("Setup"); // logging the start
      driver.init(); // initialize the RadioHead library
      napper.setup_sleep(); // initialize the Napper library
    }

    void loop() {
      mySerial.print("Loop"); // start of loop
      int measurement = measure(); // measure data
      senddata(measurement); // send data
      napper.napminutes(1); // deep sleep for 1 minute
    }

**[EDIT]**
I thought the problem to be this, and then to be that. This is how I debug, I start somewhere and work my way back. Currently it looks like my own library [PowerNap][1] is the culprit, I have tested with other Sleep code and it works. I can only be sure after more tests and isolated code running.

  [1]: https://github.com/Thijxx/PowerNap

body:
> analogRead() hangs

you started this journey thinking a particular routine (measure()) is the problem and you now are blaming analogRead() to be the source of your ills.

it will serve you much better for you to step back and ask yourself if your thought process is at fault here.

while you haven't provided much information on what it is that's not working, you have provided more than enough information to suggest that the issue is not measure() nor analogRead().

you may find this hard to understand now but debugging is far less about convincing yourself where the wrongs are. instead, it is about convincing yourself what you think right is wrong.


body: Interesting question but nothing seems wrong in the `measure()` function unless the mistake `pinMode` is used instead of `digitalWrite`. I suggest in the for loop keep a slight interval between the measurements. lets say about 50ms. if the problem still presets lets start the debugging. set a serial message in every critical point and pin point the exact location the code hangs.


message:
Programming ATmega328p on external board with FT232R

I am making a 100W AC-DC linear power supply, for which I want to show output Voltage and Output current on LCD display. I already used shunt resistor and voltage resistor to bring both values to analog pins on my ATmega328P in DIP socket, which has an Arduino bootloader on it. I want to programm my ATmega328P on the board without taking it off everytime and putting it into Arduino UNO board to just programm it and put it back, so how can I integrate a programmer onto board?
I intend to use the FT232R ic, which I think would work more than fine for this application.
On finished product I want to have a USB connector on the case just to update/correct the software.

body:
I use an FTDI cable with my home-builds. Then the board doesn't need the interface hardware (it's in the cable) and the MCU doesn't need to be removed.

I put a 6-pin male header on the board to match 6-pin female socket my cables come with. The header is direct-wired to the Tx, Rx, +5, & Gnd pins. If you have an auto-reset circuit on your board, connect the RTS pins to that. Then, reprogramming is as simple as connecting your board and clicking 'upload'. Without the auto-reset circuit, you just hold the reset button while you click upload, count 3, and release the reset.

Update:

You can do it with only 4 pins on the board. If I understand correctly, just wire Tx, Rx, +5 & Ground of the Arduino to the 4 pins and replace the Arduino-end socket on the FTDI cable with one wired to match however you wired the board. If you use **L**-shaped male pins, they'll lie parallel to the board and won't add any height (above what is already on it).


body: I suggest use ICSP(In circuit serial programming) feature of the Atmega 328 chip. Grab the .hex file from the arduino IDE and a USB ISP external programmer to write the program to the chip. Here you will have to use a 6 pin header on your custom board to take out the pins which are used to program the atmega.


message:
Using Capacitive Sensing Library with a 74HC4067 multiplexer

I'm trying to use the Capacitive Sensing Library by Paul Badger in conjunction with one or more 74HC4067 multiplexers to achieve a lot of capacitive touch inputs. I came across [this youtube video][1] where the poster seems to have accomplished what I'm trying but I can't seem to replicate this.

Here is the setup I'm using with an arduino nano, some 1MΩ resistors and a CD74HC4067 breakout :

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

Here is my Arduino code :

    #include <CapacitiveSensor.h>

    #define muxS0Pin 7
    #define muxS1Pin 6
    #define muxS2Pin 5
    #define muxS3Pin 4
    #define muxSignalPin 3
    #define muxEnPin 8
    #define capSenseSendPin 2
    #define sampleRate 5

    int touch[4] = {};

    CapacitiveSensor capSense = CapacitiveSensor( capSenseSendPin, muxSignalPin );

    void setup() {
        digitalWrite( muxEnPin, LOW );
        Serial.begin( 115200 );
    }

    void loop(){
        byte touchIndex = 0;
        for ( byte channel = 0; channel < 4; ++channel ) {
            digitalWrite( muxS0Pin, ( channel & 1 ) >> 0 );
            digitalWrite( muxS1Pin, ( channel & 2 ) >> 1 );
            digitalWrite( muxS2Pin, ( channel & 4 ) >> 2 );
            digitalWrite( muxS3Pin, ( channel & 8 ) >> 3 );
            touch[touchIndex] = capSense.capacitiveSensor( sampleRate );
            ++touchIndex;
        }
        for ( byte i = 0; i < 10; ++i ) {
            Serial.print( touch[i] );
            Serial.print("\t");
        }
        Serial.println();
    }

This example attempts only four capacitive touch pads but eventually I plan to use all 16 and then another multiplexer, but right now I'm stuck on getting anything, I seem to be getting some readings on touching the last pad but it's not what I expect to see, and it affects all the reading.

I've successfully got a version of this running without a multiplexer just on ten IO pins and it worked great. I also got the multiplexer running fine in a separate example with 16 push buttons.

Could the problem be due to pad charge times or the send-recieve capsense signals getting stopped in the multiplexer?

Any and all help would be appreciated.

  [1]: https://www.youtube.com/watch?v=5-Bq7ox3oOU
  [2]: https://i.stack.imgur.com/gt8cC.png

body:
This is way late, but for anyone who runs across this, here was my solution. The two main thing is explicitly using analog input pins (which could be quantized to digital values in the software, and making sure you have resitors on each channel being sensed. Also, ground the EN pin on the multiplexer

```arduino
#include <CapacitiveSensor.h>

#define muxS0Pin 9  // I used these rather than 4-7
#define muxS1Pin 10
#define muxS2Pin 11
#define muxS3Pin 12

#define muxSignalPin A0      // explicitly set ro analog
#define capSenseSendPin A2   //

#define sampleRate 10
#define n_inputs 16

int touch[n_inputs] = {};

CapacitiveSensor capSense = CapacitiveSensor( capSenseSendPin, muxSignalPin );

int readMux(int channel) {
  int controlPin[] = {muxS0Pin, muxS1Pin, muxS2Pin, muxS3Pin};

  int muxChannel[16][4] = {
    {0, 0, 0, 0}, //channel 0
    {1, 0, 0, 0}, //channel 1
    {0, 1, 0, 0}, //channel 2
    {1, 1, 0, 0}, //channel 3
    {0, 0, 1, 0}, //channel 4
    {1, 0, 1, 0}, //channel 5
    {0, 1, 1, 0}, //channel 6
    {1, 1, 1, 0}, //channel 7
    {0, 0, 0, 1}, //channel 8
    {1, 0, 0, 1}, //channel 9
    {0, 1, 0, 1}, //channel 10
    {1, 1, 0, 1}, //channel 11
    {0, 0, 1, 1}, //channel 12
    {1, 0, 1, 1}, //channel 13
    {0, 1, 1, 1}, //channel 14
    {1, 1, 1, 1} //channel 15
  };

  //loop through the 4 contol pins
  for (int k = 0; k < 4; k ++) {
    digitalWrite(controlPin[k], muxChannel[channel][k]);
  }
  //read the value at the SIG pin
  return capSense.capacitiveSensor( sampleRate );
}

void setup() {
  // Very important to set control pins to output mode
  pinMode(muxS0Pin, OUTPUT);
  pinMode(muxS1Pin, OUTPUT);
  pinMode(muxS2Pin, OUTPUT);
  pinMode(muxS3Pin, OUTPUT);

  digitalWrite(muxS0Pin, LOW);
  digitalWrite(muxS1Pin, LOW);
  digitalWrite(muxS2Pin, LOW);
  digitalWrite(muxS3Pin, LOW);
  Serial.begin( 9600 );
}

void loop() {
  byte touchIndex = 0;
  for ( byte channel = 0; channel < n_inputs; ++channel ) {
    Serial.print( readMux(channel));
    Serial.print("\t");
  }
  Serial.println();
}

```


message:
SPI Arduino communication

I want two Arduino cards to communicate with each other using SPI and move the servo motor with potentiometer as a result. I've done the pre-burning led or the led burning led on the SPI, I am waiting for your help. I will give the code below.

MASTER Arduino code

    #include <SPI.h>
    /* SPI haberleşmesinde Master olarak görev yapan Arduino kodu */
    const int pot=A0;   // Servo kontrol potunu bağlayacağımız analog giriş.
    int potdurum=0;
    int pos = 0;
    const int SSpini = 8;
    /* Slave görevindeki Arduino'nun seçilmesi için 8 bumaralı pin SS olarak belirlendi */

    void setup()
    {
      Serial.begin(9600);
      pinMode(SSpini, OUTPUT);
      /* SS pini çıkış olarak ayarlandı */
      digitalWrite(SSpini, HIGH);
      /* Slave olan Arduino başlangıçta haberleşmeye geçmemesi için SS pini HIGH yapıldı */
      SPI.begin();
      /* SPI haberleşmesi başlatıldı */
    }

    void loop()
    {
      potdurum=analogRead(pot);
      pos= map(potdurum,0,1023,0,180);//Pottan okunan değeri  180e oranlıyoruz.
      veriGonder(pos,SSpini);
    }

    /* SPI üzerinden veri göndermek için yazılmış fonksiyondur */
    void veriGonder(int veri, int SSpini)
    {
      digitalWrite(SSpini, LOW);
      /* Diğer Arduino'nun veri dinlemeye başlaması için SS hattını LOW düzeyine çekmeliyiz */
      delay(1);
      /* Kısa bir süre bekleyelim */
      Serial.print("Aci Degeri = ");
      Serial.println(veri);
      delay(15);
      SPI.transfer(veri);
      /* veri karakteri diğer Arduino'ya yollandı
      * Fonksiyon diğer arduino'dan gelen veriyi vermektedir
      * Geri gelen veri LEDDurumu değişkeninde tutulmuştur
      * Bu değişken Seri port üzerinden bilgisayardaki Serial monitöre yollanmıştır
      */
      digitalWrite(SSpini, HIGH);
      /* Haberleşmeyi bitirmek için pin LOW konumuna çekilmiştir */
    }

SLAVE Arduino code

    #include <Servo.h>
    int i = 0;
    Servo myservomotor;

    void setup()
    {
      Serial.begin(115200);
      myservomotor.attach(3);
      pinMode(MISO, OUTPUT);
      pinMode(SS , INPUT);
      /* MISO pini OUTPUT, SS pini INPUT olarak ayarlandı */

      SPCR  |= 0b11000000;
      SPSR  |= 0b00000000;
      /* Slave mod ve interrupt için ayarlamalar yapıldı */

      sei();
      /* Interruptlar çalıştırıldı */
    }

    void loop()
    {
    }

    /* SPI kesmesi olduğunda çalışacak fonksiyon */
    ISR(SPI_STC_vect)
    {
      cli();
      /* Interruptlar durdurulmuştur */
      while(!digitalRead(SS))
      {
          SPDR = i;
          i ++;
          if ( i > 255)
            i = 0;
          while(!(SPSR & (1 << SPIF)));
          /* SPI hattında veri aktarımı bitene kadar bekle */
          int gelenVeri;
          gelenVeri = SPDR;
          myservomotor.write(gelenVeri);
          Serial.print("Aci Degeri Slave= ");
          Serial.println(gelenVeri);
          delay(15);

    //      if(gelenVeri == 'a'){
    //        digitalWrite(SERVO,HIGH);
    //      }else if(gelenVeri == 'b'){
    //        digitalWrite(SERVO,LOW);
    //      }
          /* SPI üzerinden gelen verinin değerine göre LED'in konumu değiştirildi */
      }
      sei();
      /* Interruptlar başlatılmıştır */
    }

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

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

body:
    /* SPI kesmesi olduğunda çalışacak fonksiyon */
    ISR(SPI_STC_vect)
    {
      cli();
     ...
          Serial.print("Aci Degeri Slave= ");
          Serial.println(gelenVeri);

Don't do serial prints inside an ISR.


message:
Millisecond timestamp (13 digits) in Arduino

How can I store a 13 digits int in Arduino?

For example, current timestamp is:
1500666822235

An uint32_t can only hold 10 digits max.

64 bits integer does not seem to be supported on RFduino.

body:
> How can I store a 13 digits int in Arduino?

create a multi-byte type.

a 40-bit (32+8 bits), or a 96-bit (32+32+32) would hold a ton.

or BCD.


body:
**18446744073709551615**
That 20 digits. It is the maximum value of a `uint64_t`. Even the Arduino Uno can use the `uint64_t`. Perhaps the `Serial.print` does not support it, but the compiler supports it.

Which processor does your RFduino have ?

Where does the timestamp come from ? Perhaps you are asking the wrong question. Perhaps this is a [xy-problem][1].

  [1]: http://xyproblem.info/


message:
What's in an Arduino?

I've been using an Arduino Uno Rev. 3 for a few projects and would like to switch to using a bare Atmega328 chip so I can keep everything on the same board. I've seen the Arduino on breadboard tutorial which is fine, but the Arduino board itself has a lot of other components that aren't in the tutorial. I realize I can go look up the actual design itself, but I'm looking for a high level description of what most of the components are used for.

I'm not interested in programming through the Arduino IDE, so I don't need parts for serial programming and such. But I'm wondering if leaving out some other components would leave me at a disadvantage. For example, the datasheet recommends connecting AVCC to VCC with an LC circuit for ADC noise cancellation, but the arduino on breadboard tutorial doesn't mention this and I otherwise never would have known.

body:
There is very little on an Arduino aside from the chip itself, the regulator (sometimes) and the crystal / oscillator (sometimes).

>  But I'm wondering if leaving out some other components would leave me at a disadvantage.

Leaving out some parts will give you a disadvantage for some applications but give you an advantage for others; the same for adding some parts.

The right question is to figure out what you want to achieve with a given application and design towards that goal.

For minimum implementations, I have done plenty of nothing but the MCU - ghetto style.

On the flip side, there are plenty of applications where the MCU is literally buried in a sea of other parts: C8051F350 based LCR meter for example. so what to put in and what to take out is really application dependent.


body:
It all depends on you want, and what you are talking or thinking about, when you ask What is an Arduino. There are two main things that I associate with Arduino: A family of Development Boards (maybe a hardware family of development boards) and a Software built to work with that development boards. This let me to answer you using that two focuses:

1. The hardware focus

I understand that the Arduino boards were intended to bring the electronics and programming, closer to artists. Also, as any development board, the Arduino boards allows the user to test the most quantity of features of the core microcontroller used in the board (for Arduino UNO, the Atmega328P). Thus implying that the most of components included are to allow you a "safe" development workaround.

Now, when you have worked in a project so many time that you are ready to replicate your design, maybe for a commercial implementation, an Arduino board can take up more space that if you design your own board, well by you are not going to use all the pins or well by that you noted that you are not going to mess up the microcontroller or other components (maybe you did it the necessary times to know it) and you want to choose a smaller package that don't needs an easy microcontroller replacement, or finally because you want to include in a single board all the components and circuitry you used for your project and remove the ones you are not going to use, that is the case you mention, and you can do more things... if you want to work from a CR2032 battery you won't need the regulator and so...

2. The software focus

When you decide to use your own circuitry, maybe you also want to program the IC by yourself, not through the 2K bootloader preprogrammed, but by your own ISP programmer. There are many workarounds [using the Arduino IDE][1], but as apparently you don't want to use the Arduino IDE, the ISP programmer would be your programming interface.

**A conclussion?**: The minimal things you have to bear in mind to put in run the Atmega328P (and maybe most of microcontrollers) are 3: polarization, clock and Reset. The other things (the LC network you mentioned, the RC network I will mention, and so...) can improve the microcontroller stability and performance.

1. Polarization. Depending on the board, the DC supply used can be either 5V or 3.3V. Check the voltage used by your board.
2. Clock/Oscillator. See and reply the oscillator configuration used in the board. Then search where you can set up (in your IDE or code) the oscillator speed. Overall if you decide or want to use the internal oscillator, obtaining a [minimal circuit][2] or by [playing with arduino config files][3]. Note that, as example with the 328P, using the internal oscillator means that you are not going to reach the max number of MIPS the 328P can reach (with the internal you have 8MIPS, but you can use an external crystal up to 20 MHz to get 20 MIPS)... It really matters if you are going to do many processing tasks.
3. Reset. Please do not let it open, send it to VCC through a 10Kohm resistor, and (if available) additionally to GND with a 100nF ceramic capacitor.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [2]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
  [3]: https://forum.arduino.cc/index.php?topic=124879.0


body:
You did not specify what Arduino board you are talking about. It would
have been useful to tag the question with the appropriate board name. In
the following, I assume you want something similar to an Arduino Uno,
i.e. an ATmega328P at 5 V and 16 MHz.

> I realize I can go look up the actual design itself [...]

You should. There really isn't that much to it.

Let us take a look at the Uno rev. 3 schematic, and see what may be
useful to you:

* ATmega16U2 and associated circuitry: This is for USB communication.
  You have no use of it if you are not doing USB.

* 3.3 V regulator: This is for providing the Arduino 3.3V output.
  Only a convenience feature, not used by the Arduino itself. You should
  leave this out unless you need a 3.3 V supply.

* 5 V regulator. Only you know how you want to power your board.
  This regulator is needed unless you have some reasonably stable
  5 V supply like, e.g., a USB bus.

* ISCP header: This is rarely used on an Arduino, but you are very
  likely to use it in your custom board, as ICSP is the easiest way to
  program an ATmega with no bootloader.

* Reset button: Not always needed, as you can just power-cycle your
  board.

* 10 kΩ pullup on RESET: Your board is very likely to work just
  fine without this, but there is a little risk that you suffer from
  random resets. You want this resistor on anything that is
  “production”-like, for reliability concerns.

* Decoupling capacitors: Just like the RESET pullup, the board may work
  without them, but they provide reliability.

* The MOSFET and OP-amp right before the 3.3 V regulator: This is
  for automatically switching between the Vin and USB power supplies.
  Unlikely to be useful on a custom board.

* Ceramic resonator: For running the ATmega at 16 MHz, you need
  either this or, for better timing characteristics, a quartz with
  suitable capacitors.

* LEDs: You know if you want them.

* AREF capacitor: Only useful if you do analog readings, as it reduces
  noise.


message:
inttypes vs Arduino defined integral types

In my Arduino projects I use both Arduino types and types defined in the "inttypes.h" file, which #includes stdint.h. So far I've always written code only for the ATmega328P microcontroller (either in the UNO board or "standalone").

To be clear, in this question I'm referring to the following types:

- "Arduino": `char`, `int`, `long`; `byte`, `word`, `unsigned long`
- inttypes: `int8_t`, `int16_t`, `int32_t`; `uint8_t`, `uint16_t`, `uint32_t`

___

- What is the actual difference between e.g. `int` and `int16_t`?
- Is implicit conversion between corresponding types always possible, or should I avoid it even if the compiler doesn't complain? (quite often in my programs I pass an `int16_t` as `int` argument to a function and it always works, but is it good practice to do it, in general?

body:
int can be depending on the hardware architecture and is mostly 16 or 32 bit.
However, an int16_t is always 16 bit, regardless of the hardware architecture.

It will go wrong when you have a 32 bit architecture (for an int), and you are going to cast it to an int16_t, than you lose the MSB 16 bits. Although I think the compiler will give a warning in this case (so in your case you are ok, but it can prevent a lot of work when you port your code to a 32 bit architecture).

However, all Arduinos have int defined as 16 bit, except the Due and SAMD based boards, see: [Arduino reference for int][1] (updated after the comment of per1234 below, thanks for that).

Normally I use integer when I don't care much about the type (and know it will stay under 32768, like for most indices in loops). But if you define a (large) array it's better to use an explicit type, or if you know for sure the value will never be higher than 32768 (int8_t) or nonnegative and 65535 (uint8_t).

Also, for the 'eye' unsigned char for an unsigned 'integer' value upto 255, uint8_t looks better than a 'char' which seems more like a character instead of a value.

  [1]: https://www.arduino.cc/en/Reference/Int


body:
> - "Arduino": `char`, `int`, `long`; `byte`, `word`, `unsigned long`
> - inttypes: `int8_t`, `int16_t`, `int32_t`; `uint8_t`, `uint16_t`, `uint32_t`

A better classification would be:

- C and C++: `char`, `int`, `long`, `unsigned long`
- "Arduino": `byte`, `word`
- inttypes: `int8_t`, `int16_t`, `int32_t`; `uint8_t`, `uint16_t`, `uint32_t`

I generally avoid the Arduino-specific types, as they are quite
non-standard, and do not usually exist outside the Arduino world. As for
the other types, just like Michel Keijzers suggests, I use the C types
when I do not care much about the exact size. `int` is guaranteed to be
at least 16 bits, but is likely to be 32 bits on a 32-bit architecture.
It is a good default type, as it is supposed to be efficiently handled
on any architecture. These types allow you to write portable code that
automatically selects the "right" integer width for whatever
architecture it is been compiled for.

If you care about the exact size, which can often be the case in a
memory-constrained environment, use the types from inttypes.h. And do
not worry about implicit conversions: as long as both types are wide
enough to hold the numbers you need to store, a type conversion, whether
implicit or explicit, always preserves the value.


message:
Reading an output analog pin with an input analog pin

I am having a hard time understanding why I can't read one analog pin's output with another analog pin. The docs state to put a delay in between, which I've done (I've tried up to one second with the same results). I've got this minimized code:

    void setup() {
        Serial.begin(9600);
        pinMode(A0, INPUT);
        pinMode(A5, OUTPUT);
    }

    void loop() {
        for (int i=0; i<1024; i++){
          analogWrite(A5, i);
          delay(100);
          Serial.println(analogRead(A0));
        }
        Serial.println("done");
        delay(10000);
    }

When it starts, it displays 6-9 for a few dozen iterations, then suddenly jumps to ~1018 and remains throughout the rest of the run.

`A5` is connected directly to `A0` via a 4" jumper cable. Nothing is connected to `AREF`. If I connect `AREF` to 5v, the output does not change but by a single digit. If I connect it to ground, it immediately outputs `1023`.

I'm hoping this is a "do'h" moment here. Can someone please let me know what I'm not doing correctly?

Update: This is a legit Arduino Uno R3 board. When I connect `A0` directly to 5v+, I get `1023` as expected as the output.

body:
Your program is correct and I suspect the error is in the hardware. Arduino uses its internal timer and creates a high frequency PWM on the corresponding pin upon a `analogueWrite()` is called. Here what we should notice is the DC switching in the appropriate pin is not noticeable in most cases. (If you give it to an LED you can adjust its brightness).

 But what you have done now is not correct. Since there is no current flowing in the pin there will not be a analogue voltage actuality. It is 5V and 0V switching in a high frequency. Those are the values which the `A0` pin will see.

So try fixing a capacitor between the pin and the ground. and a 1k resistor to create a slight current flow to stabilize the voltage. then let us know your readings.

<!-- 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/8XweH.png)

<!-- End schematic -->


body:
For a start, A5 is not a valid pin to do analogWrite to. On a Uno they are marked with the "~" symbol, and are pins: 3, 5, 6, 9, 10, 11.

Thus the code will treat it as a digitalWrite, and will write LOW up to 127 and HIGH after that. From the code in wiring_analog.c:

  case NOT_ON_TIMER:
  default:
   if (val < 128) {
    digitalWrite(pin, LOW);
   } else {
    digitalWrite(pin, HIGH);
   }

You are then just reading back (close to) 0 or 1023.

---

Second, PWM output is not what you can read back using analogRead. An analogRead reads a voltage level, whereas PWM output is just 0s and 1s interleaved at the PWM frequency, and with a width of the duty cycle.

See <https://www.arduino.cc/en/Reference/AnalogWrite>, in particular:

> The analogWrite function has nothing to do with the analog pins or the analogRead function.

---

Third, writing 1023 to analogWrite is out of range. See the documentation from the page linked above:

> **Parameters**
>
> pin: the pin to write to.
>
> value: the duty cycle: between 0 (always off) and 255 (always on).

You can see that the most you can write is 255 (not 1023).

---

### References

* More information about the ADC (analogRead) at [my page about the ADC converter](http://www.gammon.com.au/adc).

* More information about PWM output at [my page about timers](http://www.gammon.com.au/timers).


body:
> Can someone please let me know what I'm not doing correctly?

the analog (output) pins on those chips are not exactly analog: they are pwm output pins. as such, their output is either 0 or 1, nothing in between, with the chance of being 1 equal the duty cycle.

that kind of output can be a steady "analog" if you run it through a low pass filter - the simplest would be an rc filter where the r is in ***serial*** with the c.

so if you hook th epwm pin up to a rc filter and adc the output of that rc filter, you will get a real "analog".


message:
Sending string over serial to nodejs app. Why does it get chunked?

I'm sending a string from my sketch over Serial port as follows:

<!-- language: lang-js -->

    Serial.println(F("Found ILI9341 LCD driver"));

On the other side, I have a nodejs app using the [serialport][1] npm module, with something like this:

<!-- language: lang-js -->

    var SerialPort = require('serialport')
    var serialPort = new SerialPort('/dev/ttyACM1', {
      baudrate: 9600
    })

    // it opens the connection and register an event 'data'
    serialPort.on('open', function () {
      console.log('Communication is on!')
    })

    // when your app receives data, this event is fired
    // so you can capture the data and do what you need
    serialPort.on('data', function (data) {
      console.log('data received: ' + data)
    })

Communication works, but on nodejs side I get the output chunked, as if it had line breaks, like this:

    Communication is on!
    data received: Pa
    data received: int!
    data received:

    data received: Fou
    data received: nd I
    data received: LI93
    data received: 41 L
    data received: CD d
    data received: rive
    data received: r

Why does this happen?

  [1]: https://www.npmjs.com/package/serialport

body:
It seems I needed to add a `parser` to SerialPort nodejs module, in order to specify how the input should be treated.

I changed my code to this:

<!-- language: lang-js -->

    var SerialPort = require('serialport')
    var Readline = SerialPort.parsers.Readline

    var serialPort = new SerialPort('/dev/ttyACM0', {
      baudrate: 9600
    })

    var parser = new Readline()
    serialPort.pipe(parser)
    parser.on('data', function (data) {
      console.log('data received: ' + data)
    })

    serialPort.on('open', function () {
      console.log('Communication is on!')
    })

Basically, I'm specifying a `Readline` parser, which matches with the `Serial.println` function calls on my arduino sketch. Now the console output works as expected:

    Communication is on!
    data received: Found ILI9341 LCD driver


message:
UECIDE: linker error with U8g2 library

This sketch:

    #include <SPI.h>
    #include <Wire.h>
    #include <U8g2lib.h>

    //  OLED display.
    U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
    void setup() {
      u8g2.begin();
    }
    void loop() {
    }

Compile OK with Arduino 1.8.3, but under UECIDE 0.8.9-pre15 fails to link, with this message:

    Compiling...
    • Preprocessing...
    • Compiling sketch...
    • Compiling core...
    ‣ arduino
    • Compiling libraries...
    ‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
    ‣ SPI [/home/look/.uecide/libraries/Communications/arduino/SPI]
    ‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
    ‣ Wire [/home/look/.uecide/libraries/Communications/arduino/Wire]
    • Linking sketch...
    /tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::write(unsigned char)':
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:248: undefined reference to `u8g2_DrawGlyph'
    /tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::initDisplay()':
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:101: undefined reference to `u8x8_InitDisplay'
    /tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::clearDisplay()':
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:104: undefined reference to `u8g2_ClearDisplay'
    /tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::setPowerSave(unsigned char)':
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:107: undefined reference to `u8x8_SetPowerSave'
    /tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2':
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
    /tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::home()':
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:278: undefined reference to `u8x8_utf8_init'
    /tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2_SSD1306_128X64_NONAME_1_HW_I2C':
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
    /home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_Setup_ssd1306_i2c_128x64_noname_1'
    collect2: error: ld returned 1 exit status
    Compiling Fail

Both IDEs are set for Arduino Pro Mini 3.3V 8Mhz. In UECIDE I'm using GCC 4.9.2 for AVR. I copied the same U8g2 source code to both Arduino and UECIDE own libraries directory.

U8g2 library is version 2.15.2 by Oliver, installed via Arduino IDE and copied to the UECIDE libraries directory,

The problem, so far, only happens with U8g2 and not other libraries.

How do I solve this problem?

body:
The layout of that library is in a non-standard format with folders that UECIDE doesn't know to look for or how to deal with.

The main culpret is the inclusion of big chunks of code in a "clib" directory (why on earth?!?!) which doesn't get included in the compilation. Then on top of that you have header files in there that are referenced both from inside it and outside it.

The simplest fix is just to copy and move the files to better locations:

    $ cd ~/Documents/UECIDE/libraries/U8g2/src
    $ mv clib/*.c .
    $ cp clib/*.h .

Note you *move* the source, but *copy* the headers. That's to get around the problem of the headers being referenced from two locations with relative paths.

The problem stems from UECIDE having (by necessity) much stricter rules than the Arduino IDE over the layout of a library. This is to facilitate better identification and categorization of the libraries so that recursive dependency detection can take place.


message:
12V from Arduino Uno

I don't think it's possible, but I want to drive my 433 MHz transmitter (FS21000A) from a 12V 'supply', to get more power (and thus more range).

However, I don't have an external power supply. I can add an adapter (12V/1A) to my Arduino with the barrel input, but I wonder where to get 12V from? I only see 5V or 3.3V outputs.

And as far as I know all GPIO output 5V ... so how can I get 12V (or maybe a bit less but more than 5V) out of an Arduino? (and what safety measurements I should take to not ruin my Arduino?)

body:
In crude terms the power supply of the Arduino is along these lines:

<!-- 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/UomSQ.png)

<!-- End schematic -->

It's actually more complex than that, especially concerning the USB power input, but that doesn't matter here.

As you can see the barrel jack (your 12V supply) first goes through a diode. Then it gets fed to the 5V regulator. The VIN pin also goes to the same pin of the 5V regulator, so it will see 12V minus the voltage drop of the diode (~0.7V).

So you can provide 12V to the barrel jack and use the VIN pin as an 11.3V supply.


body:
>  I want to drive my 433 MHz transmitter (FS21000A) from a 12V 'supply', to get more power (and thus more range).

that only works if the transmitter works at 12v and isn't powered through a regulator.

if not, applying 12v to it does nothing but generating some heat or damage, worse yet.


message:
How to measure resistance of TFT Touchscreen

I'm using a TFT Touchscreen shield with my Arduino UNO, and I'm running "[tftpaint][1]" example by Adafruit.

I've noticed that when initializing the Touchscreen object, a resistance value must be provided. Library default is 300, but [a comment in the code][2] says:

    // For better pressure precision, we need to know the resistance
    // between X+ and X- Use any multimeter to read it

How should I perform such measurement? Where do I put the probes of my multimeter? FYI, my shield is this one:

[![TFT Touchscreen Arduino Shield][3]][3]

  [1]: https://github.com/adafruit/TFTLCD-Library/blob/master/examples/tftpaint/tftpaint.ino
  [2]: https://github.com/adafruit/TFTLCD-Library/blob/master/examples/tftpaint/tftpaint.ino#L57
  [3]: https://i.stack.imgur.com/UuLbj.png

body:
Your TFT seems like this: [TFT LCD SPFD5408][1]

I cannot find a datasheet, but normally the X+ and X- are shown on the device... if not, try to find the datasheet and look for the pin numbers.

  [1]: https://www.aliexpress.com/item/1sets-Special-promotions-2-4G-wireless-modules-1100-Meters-Long-Distance-NRF24L01-PA-LNA-wireless-modules/32787846044.html?spm=a2g0s.9042311.0.0.97LZRv


body:
As pointed out in other answers and comments, step one was trying to get a datasheet for this component. I couldn't find a datasheet for the shield, but here is [the link from the vendor][1] I bought it from, and they provided with some articles were they explained how to perform the resistance measure. However, I then noticed the answer was in the example code itself.

Btw, the shield it's indeed based on SPFD5408 as correctly suggested by user Michel Keijzers on his answer.

So, in turns out the hint to which pins were X+ and X- was actually in the example code I'm using. [Here][2] the Touchscreen object is initialized:

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

    TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

Notice the usage of constants `XP` and `XM`. The names stand for "X-plus" (X+) and "X-minus" (X-). Now if we look a couple of lines above where these constants are [defined][3], we see this:

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

    #define YP A3
    #define XM A2
    #define YM 9
    #define XP 8

In particular, we see that `XM` (i.e. "X-") is mapped to analog pin `A2`, and `XP` (i.e. "X+") is mapped to digital pin `8`.

Now, by looking at how the shield couples with arduino, we can see that analog pin `A2` of the Arduino board, connects with pin labeled "`LCD_RS`" in the shield, and that pin `8` connects with pin labeled "`LCD_D0`".

This is a picture (found online) of the bottom side of the shield, were we can see the labels for each pin:

[![TFT LCD Shield bottom][4]][4]

Finally, with a multimeter at those pins, I measured the resistance and it was 292 Ohms. Not so different from the default of `300` in the library, but it's still a good thing to have the correct value.

  [1]: http://www.monarcaelectronica.com.ar/pantalla-tactil-tft-lcd-color-24-lector-micro-sd-arduino-140186063xJM
  [2]: https://github.com/adafruit/TFTLCD-Library/blob/master/examples/tftpaint/tftpaint.ino#L60
  [3]: https://github.com/adafruit/TFTLCD-Library/blob/master/examples/tftpaint/tftpaint.ino#L48
  [4]: https://i.stack.imgur.com/2zJ4B.png