text:
Using STL vector to create an array causes an error
I have installed the STL for arduino, and it has been working fine. Then I tried to create a vector using a custom class, and it gave me a massive error message. When using it on primitive data types (ex. int) it works fine, but in any one of my own classes (including classes from sample code) it gives this error:
Arduino: 1.6.3 (Windows 8.1), Board: "Arduino Uno"

Build options changed, rebuilding all

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++ -c -g -Os -w - fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD   -std=gnu++11 -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10603 -  DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files   (x86)\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files   (x86)\Arduino\hardware\arduino\avr\variants\standard   C:\Users\OWNER\AppData\Local\Temp\build7240665633604233053.tmp\Navigation.cpp -o    C:\Users\OWNER\AppData\Local\Temp\build7240665633604233053.tmp\Navigation.cpp.o

In file included from c:\program files     (x86)\arduino\hardware\tools\avr\avr\include\vector:33:0,

                 from Navigation.ino:2:

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h: In instantiation   of 'void std::__destroy_aux(_ForwardIterator, _ForwardIterator, __false_type)   [with _ForwardIterator = Obstacle*]':

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:78:55:   required  from 'void std::__destroy(_ForwardIterator, _ForwardIterator, _Tp*) [with  _ForwardIterator = Obstacle*; _Tp = Obstacle]'

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:83:51:   required from 'void std::_Destroy(_ForwardIterator, _ForwardIterator) [with _ForwardIterator = Obstacle*]'

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:115:27:   required  from 'void std::destroy(_ForwardIterator, _ForwardIterator) [with _ForwardIterator = Obstacle*]'

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:284:42:   required from 'std::vector<_Tp, _Alloc>::~vector() [with _Tp = Obstacle; _Alloc = std::allocator<Obstacle>]'

Navigation.ino:36:23:   required from here

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:66:22: error: 'destroy' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]

     destroy(&*__first);

                  ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:114:13: note: 'template<class _ForwardIterator> void std::destroy(_ForwardIterator, _ForwardIterator)' declared here, later in the translation unit

 inline void destroy(_ForwardIterator __first, _ForwardIterator __last) {

             ^

Error compiling.

EDIT:
Here is the code:
#include <iterator>
#include <vector>
#include <pnew.cpp>

class Test {
public:
    int i;
};
std::vector<Test> test;

Change the last line to
std::vector<Test&> test

and:
        Arduino: 1.6.3 (Windows 8.1), Board: "Arduino Uno"

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -std=gnu++11 -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10603 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard C:\Users\OWNER\AppData\Local\Temp\build7240665633604233053.tmp\Navigation.cpp -o C:\Users\OWNER\AppData\Local\Temp\build7240665633604233053.tmp\Navigation.cpp.o

In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\vector:35:0,

                 from Navigation.ino:2:

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'class std::_Vector_alloc_base<Obstacle&, std::allocator<Obstacle&>, true>':

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:101:8:   required from 'struct std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >'

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:155:7:   required from 'class std::vector<Obstacle&>'

Navigation.ino:36:24:   required from here

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:89:8: error: forming pointer to reference type 'Obstacle&'

   _Tp* _M_start;

        ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:90:8: error: forming pointer to reference type 'Obstacle&'

   _Tp* _M_finish;

        ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:91:8: error: forming pointer to reference type 'Obstacle&'

   _Tp* _M_end_of_storage;

        ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:94:8: error: forming pointer to reference type 'Obstacle&'

   _Tp* _M_allocate(size_t __n)

        ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:96:8: error: forming pointer to reference type 'Obstacle&'

   void _M_deallocate(_Tp* __p, size_t __n)

        ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'class std::vector<Obstacle&>':

Navigation.ino:36:24:   required from here

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:165:23: error: forming pointer to reference type 'std::vector<Obstacle&>::value_type {aka Obstacle&}'

   typedef value_type* pointer;

                       ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:166:29: error: forming pointer to reference type 'std::vector<Obstacle&>::value_type {aka Obstacle&}'

   typedef const value_type* const_pointer;

                             ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:167:23: error: forming pointer to reference type 'std::vector<Obstacle&>::value_type {aka Obstacle&}'

   typedef value_type* iterator;

                       ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:168:29: error: forming pointer to reference type 'std::vector<Obstacle&>::value_type {aka Obstacle&}'

   typedef const value_type* const_iterator;

                             ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:178:49: error: forming pointer to reference type 'Obstacle&'

   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;

                                                 ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:179:43: error: forming pointer to reference type 'Obstacle&'

   typedef std::reverse_iterator<iterator> reverse_iterator;

                                           ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:189:16: error: no members matching 'std::vector<Obstacle&>::_Base {aka std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}::_M_allocate' in 'std::vector<Obstacle&>::_Base {aka struct std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}'

   using _Base::_M_allocate;

                ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:190:16: error: no members matching 'std::vector<Obstacle&>::_Base {aka std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}::_M_deallocate' in 'std::vector<Obstacle&>::_Base {aka struct std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}'

   using _Base::_M_deallocate;

                ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:191:16: error: no members matching 'std::vector<Obstacle&>::_Base {aka std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}::_M_start' in 'std::vector<Obstacle&>::_Base {aka struct std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}'

   using _Base::_M_start;

                ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:192:16: error: no members matching 'std::vector<Obstacle&>::_Base {aka std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}::_M_finish' in 'std::vector<Obstacle&>::_Base {aka struct std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}'

   using _Base::_M_finish;

                ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:193:16: error: no members matching 'std::vector<Obstacle&>::_Base {aka std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}::_M_end_of_storage' in 'std::vector<Obstacle&>::_Base {aka struct std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >}'

   using _Base::_M_end_of_storage;

                ^

In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\iosfwd:22:0,

                 from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\iterator:35,

                 from Navigation.ino:1:

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_alloc.h: In instantiation of 'class std::allocator<Obstacle&>':

Navigation.ino:36:24:   required from here

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_alloc.h:638:22: error: forming pointer to reference type 'Obstacle&'

   typedef _Tp*       pointer;

                      ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_alloc.h:639:22: error: forming pointer to reference type 'Obstacle&'

   typedef const _Tp* const_pointer;

                      ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_alloc.h:658:8: error: forming pointer to reference type 'Obstacle&'

   _Tp* allocate(size_type __n, const void* = 0) {

        ^

Navigation.ino: In constructor 'std::vector<_Tp, _Alloc>::vector(const allocator_type&) [with _Tp = Obstacle&; _Alloc = std::allocator<Obstacle&>; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Obstacle&>]':

Navigation.ino:36:24: note:   when instantiating default argument for call to std::vector<_Tp, _Alloc>::vector(const allocator_type&) [with _Tp = Obstacle&; _Alloc = std::allocator<Obstacle&>; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Obstacle&>]

In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\vector:35:0,

                 from Navigation.ino:2:

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'std::_Vector_base<_Tp, _Alloc>::~_Vector_base() [with _Tp = Obstacle&; _Alloc = std::allocator<Obstacle&>]':

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:240:16:   required from 'std::vector<_Tp, _Alloc>::vector(const allocator_type&) [with _Tp = Obstacle&; _Alloc = std::allocator<Obstacle&>; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Obstacle&>]'

Navigation.ino:36:24:   required from here

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:117:21: error: 'struct std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >' has no member named '_M_deallocate'

   ~_Vector_base() { this->_M_deallocate(_Base::_M_start, _Base::_M_end_of_storage - _Base::_M_start); }

                     ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:117:21: error: '_M_start' is not a member of 'std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >::_Base {aka std::_Vector_alloc_base<Obstacle&, std::allocator<Obstacle&>, true>}'

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:117:83: error: '_M_start' is not a member of 'std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >::_Base {aka std::_Vector_alloc_base<Obstacle&, std::allocator<Obstacle&>, true>}'

   ~_Vector_base() { this->_M_deallocate(_Base::_M_start, _Base::_M_end_of_storage - _Base::_M_start); }

                                                                                ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:117:83: error: '_M_end_of_storage' is not a member of 'std::_Vector_base<Obstacle&, std::allocator<Obstacle&> >::_Base {aka std::_Vector_alloc_base<Obstacle&, std::allocator<Obstacle&>, true>}'

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'std::_Vector_alloc_base<_Tp, _Allocator, true>::_Vector_alloc_base(const allocator_type&) [with _Tp = Obstacle&; _Allocator = std::allocator<Obstacle&>; std::_Vector_alloc_base<_Tp, _Allocator, true>::allocator_type = std::allocator<Obstacle&>]':

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:110:54:   required from 'std::_Vector_base<_Tp, _Alloc>::_Vector_base(const allocator_type&) [with _Tp = Obstacle&; _Alloc = std::allocator<Obstacle&>; std::_Vector_base<_Tp, _Alloc>::allocator_type = std::allocator<Obstacle&>]'

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:240:16:   required from 'std::vector<_Tp, _Alloc>::vector(const allocator_type&) [with _Tp = Obstacle&; _Alloc = std::allocator<Obstacle&>; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Obstacle&>]'

Navigation.ino:36:24:   required from here

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:85:53: error: using invalid field 'std::_Vector_alloc_base<_Tp, _Allocator, true>::_M_start'

     : _M_start(0), _M_finish(0), _M_end_of_storage(0)

                                                     ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:85:53: error: using invalid field 'std::_Vector_alloc_base<_Tp, _Allocator, true>::_M_finish'

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:85:53: error: using invalid field 'std::_Vector_alloc_base<_Tp, _Allocator, true>::_M_end_of_storage'

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'std::vector<_Tp, _Alloc>::~vector() [with _Tp = Obstacle&; _Alloc = std::allocator<Obstacle&>]':

Navigation.ino:36:24:   required from here

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:284:42: error: '_M_start' was not declared in this scope

   ~vector() { destroy(_M_start, _M_finish); }

                                          ^

c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:284:42: error: '_M_finish' was not declared in this scope

Error compiling.

Does the error occur on a POD class? say, a class with just one public integer member and the default constructor/deconstructor? Also, if it works for primatives, it should work with pointers to your class.

Please post the code, not just the error message. Make up a Minimal, Complete, and Verifiable example.

Yes, it occurs on a POD class, and it returns an even larger error message upon trying to use a pointer

std::vector<Test&> test

Yes, well I doubt you can make a vector of references. A vector of pointers I could believe.
See, for example: https://stackoverflow.com/questions/922360/why-cant-i-make-a-vector-of-references

I'm too used to java


text:
Can't get Arduino Leonardo working as a USB keyboard in Windows 7
I can't believe I am stumped by this, but this is my issue and I can't see any other solution for this anywhere.
I have an official Arduino Leonardo loaded up with the following code:
void setup() {
  Keyboard.begin();
}

void loop() {
  char keyToPress = random('A', 'Z'); // choose a random letter between 'A' and 'Z'
  delay(1900);
  Keyboard.press(keyToPress);
  delay(100);
  Keyboard.release(keyToPress); // overall loop time is ~2s, with a 100mS keypress length
}

On OSX and Linux, I get a predictable output - random capital letters typed by a keyboard, two seconds apart: FWTDXJP etc.
However, on Windows 7(x64), I get... nothing. I have the Leonardo appear correctly as a CDC COM port, drivers were installed from the latest 1.6.5 installer on their website. I have tried uninstalling the Leonardo in device manager while checking the "remove software" box so as to be sure that the driver I install is the one being used.
Has anyone seen this before? A search of the Arduino forum reveals some people having the same issue, a bit of a discussion and then usually "I don't know what I did but the problem has gone now".
This is the output from USB Device Tree Viewer, which seems to correctly show the USB HID descriptor:
    =========================== USB Port2 ===========================

Connection Status        : 0x01 (Device is connected)
Port Chain               : 1-2

      ======================== USB Device ========================

        +++++++++++++++++ Device Information ++++++++++++++++++
Friendly Name            : Arduino Leonardo (COM3)
Device Description       : Arduino Leonardo
Device Path              : \\?\usb#vid_2341&pid_8036#5&18f54cb7&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
Device ID                : USB\VID_2341&PID_8036\5&18F54CB7&0&2
Driver KeyName           : {4d36e978-e325-11ce-bfc1-08002be10318}\0001 (GUID_DEVCLASS_PORTS)
Driver                   : C:\Windows\system32\DRIVERS\usbser.sys (Version: 6.1.7601.18247  Date: 2013-08-29)
Driver Inf               : C:\Windows\inf\oem6.inf
Legacy BusType           : PNPBus
Class                    : Ports
Service                  : usbser
Enumerator               : USB
Location Info            : Port_#0002.Hub_#0001
Location IDs             : PCIROOT(0)#PCI(0600)#USBROOT(0)#USB(2)
Container ID             : {2d5fa232-297c-11e5-9565-080027ccdb00}
Manufacturer Info        : Arduino LLC (www.arduino.cc)
Capabilities             : 0x84 (Removable, SurpriseRemovalOK)
Address                  : 2
Problem Code             : 0
Power State              : D0 (supported: D0, D3, wake from D0)
COM-Port                 : COM3 (\Device\USBPDO-3)

        ---------------- Connection Information ---------------
Connection Index         : 0x02 (2)
Connection Status        : 0x01 (DeviceConnected)
Current Config Value     : 0x01
Device Address           : 0x02 (2)
Is Hub                   : 0x00 (no)
Number Of Open Pipes     : 0x04 (4)
Device Bus Speed         : 0x01 (Full-Speed)
Pipe0ScheduleOffset      : 0x04 (4)
Pipe1ScheduleOffset      : 0x00 (0)
Pipe2ScheduleOffset      : 0x00 (0)
Pipe3ScheduleOffset      : 0x00 (0)

        ------------------ Device Descriptor ------------------
bLength                  : 0x12 (18 bytes)
bDescriptorType          : 0x01 (Device Descriptor)
bcdUSB                   : 0x200 (USB Version 2.00)
bDeviceClass             : 0x02 (Communications and CDC Control)
bDeviceSubClass          : 0x00
bDeviceProtocol          : 0x00
bMaxPacketSize0          : 0x40 (64 bytes)
idVendor                 : 0x2341
idProduct                : 0x8036
bcdDevice                : 0x100
iManufacturer            : 0x01 (String Descriptor 1)
 Language 0x0409         : "Arduino LLC"
iProduct                 : 0x02 (String Descriptor 2)
 Language 0x0409         : "Arduino Leonardo"
iSerialNumber            : 0x00 (No String Descriptor)
bNumConfigurations       : 0x01

        ------------------ String Descriptors -----------------
             ------ String Descriptor 0 ------
bLength                  : 0x04 (4 bytes)
bDescriptorType          : 0x03 (String Descriptor)
Language ID[0]           : 0x0409 (English - United States)
             ------ String Descriptor 1 ------
bLength                  : 0x18 (24 bytes)
bDescriptorType          : 0x03 (String Descriptor)
Language 0x0409          : "Arduino LLC"
             ------ String Descriptor 2 ------
bLength                  : 0x22 (34 bytes)
bDescriptorType          : 0x03 (String Descriptor)
Language 0x0409          : "Arduino Leonardo"

        -------------- Configuration Descriptor ---------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x02 (Configuration Descriptor)
wTotalLength             : 0x0064 (100 bytes)
bNumInterfaces           : 0x03
bConfigurationValue      : 0x01
iConfiguration           : 0x00 (No String Descriptor)
bmAttributes             : 0x80
 D7: Reserved, set 1     : 0x01
 D6: Self Powered        : 0x00 (no)
 D5: Remote Wakeup       : 0x00 (no)
 D4..0: Reserved, set 0  : 0x00
MaxPower                 : 0xFA (500 mA)

        ------------------- IAD Descriptor --------------------
bLength                  : 0x08 (8 bytes)
bDescriptorType          : 0x0B
bFirstInterface          : 0x00
bInterfaceCount          : 0x02
bFunctionClass           : 0x02 (Communications and CDC Control)
bFunctionSubClass        : 0x02
bFunctionProtocol        : 0x01
iFunction                : 0x00 (No String Descriptor)

        ---------------- Interface Descriptor -----------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x04 (Interface Descriptor)
bInterfaceNumber         : 0x00
bAlternateSetting        : 0x00
bNumEndpoints            : 0x01 (1 Endpoint)
bInterfaceClass          : 0x02 (Communications and CDC Control)
bInterfaceSubClass       : 0x02
bInterfaceProtocol       : 0x00
iInterface               : 0x00 (No String Descriptor)

        -------------- CDC Interface Descriptor ---------------
bFunctionLength          : 0x05 (5 bytes)
bDescriptorType          : 0x24 (Interface)
bDescriptorSubType       : 0x00 (Header Functional Descriptor)
bcdCDC                   : 0x110 (CDC Version 1.10)

        -------------- CDC Interface Descriptor ---------------
bFunctionLength          : 0x05 (5 bytes)
bDescriptorType          : 0x24 (Interface)
bDescriptorSubType       : 0x01 (Call Management Functional Descriptor)
bmCapabilities           : 0x01
bDataInterface           : 0x01

        -------------- CDC Interface Descriptor ---------------
bFunctionLength          : 0x04 (4 bytes)
bDescriptorType          : 0x24 (Interface)
bDescriptorSubType       : 0x02 (Abstract Control Management Functional Descriptor)
bmCapabilities           : 0x06

        -------------- CDC Interface Descriptor ---------------
bFunctionLength          : 0x05 (5 bytes)
bDescriptorType          : 0x24 (Interface)
bDescriptorSubType       : 0x06 (Union Functional Descriptor)
bControlInterface        : 0x00
bSubordinateInterface[0] : 0x01

        ----------------- Endpoint Descriptor -----------------
bLength                  : 0x07 (7 bytes)
bDescriptorType          : 0x05 (Endpoint Descriptor)
bEndpointAddress         : 0x81 (Direction=IN  EndpointID=1)
bmAttributes             : 0x03 (TransferType=Interrupt)
wMaxPacketSize           : 0x0010 (16 bytes) (16 bytes)
bInterval                : 0x40 (64 ms)

        ---------------- Interface Descriptor -----------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x04 (Interface Descriptor)
bInterfaceNumber         : 0x01
bAlternateSetting        : 0x00
bNumEndpoints            : 0x02 (2 Endpoints)
bInterfaceClass          : 0x0A (CDC-Data)
bInterfaceSubClass       : 0x00
bInterfaceProtocol       : 0x00
iInterface               : 0x00 (No String Descriptor)

        ----------------- Endpoint Descriptor -----------------
bLength                  : 0x07 (7 bytes)
bDescriptorType          : 0x05 (Endpoint Descriptor)
bEndpointAddress         : 0x02 (Direction=OUT  EndpointID=2)
bmAttributes             : 0x02 (TransferType=Bulk)
wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
bInterval                : 0x00 (ignored)

        ----------------- Endpoint Descriptor -----------------
bLength                  : 0x07 (7 bytes)
bDescriptorType          : 0x05 (Endpoint Descriptor)
bEndpointAddress         : 0x83 (Direction=IN  EndpointID=3)
bmAttributes             : 0x02 (TransferType=Bulk)
wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
bInterval                : 0x00 (ignored)

        ---------------- Interface Descriptor -----------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x04 (Interface Descriptor)
bInterfaceNumber         : 0x02
bAlternateSetting        : 0x00
bNumEndpoints            : 0x01 (1 Endpoint)
bInterfaceClass          : 0x03 (HID - Human Interface Device)
bInterfaceSubClass       : 0x00 (None)
bInterfaceProtocol       : 0x00 (None)
iInterface               : 0x00 (No String Descriptor)

        ------------------- HID Descriptor --------------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x21 (HID Descriptor)
bcdHID                   : 0x0101 (HID Version 1.01)
bCountryCode             : 0x00 (00 = not localized)
bNumDescriptors          : 0x01
Descriptor 1:
bDescriptorType          : 0x22 (Class=Report)
wDescriptorLength        : 0x0065 (101 bytes)
  05 01             Usage Page (Generic Desktop Controls)
  09 02             Usage (Mouse)
  A1 01             Collection (Application)
  09 01               Usage (Pointer)
  A1 00               Collection (Physical)
  85 01                 Report ID (0x01)
  05 09                 Usage Page (Buttons)
  19 01                 Usage Minimum (1)
  29 03                 Usage Maximum (3)
  15 00                 Logical Minimum (0)
  25 01                 Logical Maximum (1)
  95 03                 Report Count (3)
  75 01                 Report Size (1)
  81 02                 Input (Var)
  95 01                 Report Count (1)
  75 05                 Report Size (5)
  81 03                 Input (Const, Var)
  05 01                 Usage Page (Generic Desktop Controls)
  09 30                 Usage (Direction-X)
  09 31                 Usage (Direction-Y)
  09 38                 Usage (Wheel)
  15 81                 Logical Minimum (-127)
  25 7F                 Logical Maximum (127)
  75 08                 Report Size (8)
  95 03                 Report Count (3)
  81 06                 Input (Var, Rel)
  C0                  End Collection
  C0                End Collection
  05 01             Usage Page (Generic Desktop Controls)
  09 06             Usage (Keyboard)
  A1 01             Collection (Application)
  85 02               Report ID (0x02)
  05 07               Usage Page (Keyboard)
  19 E0               Usage Minimum (-32)
  29 E7               Usage Maximum (-25)
  15 00               Logical Minimum (0)
  25 01               Logical Maximum (1)
  75 01               Report Size (1)
  95 08               Report Count (8)
  81 02               Input (Var)
  95 01               Report Count (1)
  75 08               Report Size (8)
  81 03               Input (Const, Var)
  95 06               Report Count (6)
  75 08               Report Size (8)
  15 00               Logical Minimum (0)
  25 65               Logical Maximum (101)
  05 07               Usage Page (Keyboard)
  19 00               Usage Minimum (0)
  29 65               Usage Maximum (101)
  81 00               Input ()
  C0                End Collection

        ----------------- Endpoint Descriptor -----------------
bLength                  : 0x07 (7 bytes)
bDescriptorType          : 0x05 (Endpoint Descriptor)
bEndpointAddress         : 0x84 (Direction=IN  EndpointID=4)
bmAttributes             : 0x03 (TransferType=Interrupt)
wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
bInterval                : 0x01 (1 ms)

And this is a screenshot from Device Manager, showing just one HID device (my keyboard / trackpad on my laptop):

Any ideas? I have obviously tried the example USB keyboard code from the Arduino IDE too - my code was just to get a minimum system to simplify testing. All help gratefully received.

What does Device Manager have to say about it?

@IgnacioVazquez-Abrams I have added a Device Manager screenshot - Leonardo shows up as CDC, nothing new in HID.

@stefandz Can you please confirm a few things for me.

Have you tried the same board on a different win7 machine?
Have you had all of your updates installed?
Were the current drivers installed automatically or are they from arduino?

Yup, and a Windows 8.1 machine 2. Yes, on both machines 3. They were installed by the Arduino installer and then picked up automatically by Windows

So you are saying that it didnt work on any windows machine correct? Have you also tried re uploading the bootloader (doubt it is the issue tho)

None of the three I have access to, no. I shall try the bootloader out of desperation, but it doesn't run when the user code is in operation. Will get back to you on this front when I am at my bench.

I just tested my leonardo on my windows 10 PC as well with your code and its fine. I doubt it is a driver issue as your screenshot does not show any unknown devices found. It could either be a defective PCB (which i doubt since it was working on a mac and linux machine), or a firmware issue
have you tested with a different arduino?

I've tested with 2 other Leonardos, hence my driver suspicion.

Let me try to help. This isn't a definitive "answer" but I need to post screenshots etc., so I am making it an answer.
I tried your code with my Arduino Micro. I believe it is the same as the Leonardo except for a byte difference in the bootloader identification (for the USB device).
First the good bad news. It worked under Windows 7. And let me tell you something: It is incredibly annoying to try to use the Windows 7 device manager when something is typing a key every two seconds! I recompiled it to type a key every minute to save my sanity.
I don't usually use Windows 7 (I use Ubuntu normally) so the device driver was not installed. It offered to install it, I told it to skip going to Windows Update, and it installed it thus:

Note that I did not use the device drivers (if any) supplied with the Arduino installation. I never got asked that question.

Locating the device in the Device Manager I see I got Windows drivers:

It showed up under Human Interface Devices as a USB Input Device:

These were the hardware IDs:

It also showed up as a Composite Device:

This was the report from the program you linked:
    =========================== USB Port1 ===========================

Connection Status        : 0x01 (Device is connected)
Port Chain               : 1-1-3-1

      ======================== USB Device ========================

        +++++++++++++++++ Device Information ++++++++++++++++++
Device Description       : USB Composite Device
Device Path              : \\?\usb#vid_2341&pid_8037#7&171b751b&0&1#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
Device ID                : USB\VID_2341&PID_8037\7&171B751B&0&1
Driver KeyName           : {36fc9e60-c465-11cf-8056-444553540000}\0026 (GUID_DEVCLASS_USB)
Driver                   : C:\Windows\system32\DRIVERS\usbccgp.sys (Version: 6.1.7601.18328  Date: 2013-11-27)
Driver Inf               : C:\Windows\inf\usb.inf
Legacy BusType           : PNPBus
Class                    : USB
Service                  : usbccgp
Enumerator               : USB
Location Info            : Port_#0001.Hub_#0005
Location IDs             : PCIROOT(0)#PCI(1D00)#USBROOT(0)#USB(1)#USB(3)#USB(1)
Container ID             : {821d8eeb-43cd-11e5-b4e1-10c37b50593b}
Manufacturer Info        : (Standard USB Host Controller)
Capabilities             : 0x84 (Removable, SurpriseRemovalOK)
Address                  : 1
Problem Code             : 0
Power State              : D0 (supported: D0, D2, D3, wake from D0, wake from D2)
 Child Device 1          : Arduino Micro
  Device ID              : USB\VID_2341&PID_8037&MI_00\8&6467A9E&0&0000
  Class                  : Ports
  COM-Port               : COM8 (\Device\USBSER000)
 Child Device 2          : USB Input Device
  Device ID              : USB\VID_2341&PID_8037&MI_02\8&6467A9E&0&0002
  Class                  : HIDClass
   Child Device 1        : HID-compliant mouse
    Device ID            : HID\VID_2341&PID_8037&MI_02&COL01\9&F900E83&0&0000
    Class                : Mouse
   Child Device 2        : HID Keyboard Device
    Device ID            : HID\VID_2341&PID_8037&MI_02&COL02\9&F900E83&0&0001
    Class                : Keyboard

        ---------------- Connection Information ---------------
Connection Index         : 0x01 (1)
Connection Status        : 0x01 (DeviceConnected)
Current Config Value     : 0x01
Device Address           : 0x08 (8)
Is Hub                   : 0x00 (no)
Number Of Open Pipes     : 0x04 (4)
Device Bus Speed         : 0x01 (Full-Speed)
Pipe0ScheduleOffset      : 0x01 (1)
Pipe1ScheduleOffset      : 0x00 (0)
Pipe2ScheduleOffset      : 0x00 (0)
Pipe3ScheduleOffset      : 0x00 (0)

        ------------------ Device Descriptor ------------------
bLength                  : 0x12 (18 bytes)
bDescriptorType          : 0x01 (Device Descriptor)
bcdUSB                   : 0x200 (USB Version 2.00)
bDeviceClass             : 0x00 (defined by the interface descriptors)
bDeviceSubClass          : 0x00
bDeviceProtocol          : 0x00
bMaxPacketSize0          : 0x40 (64 bytes)
idVendor                 : 0x2341
idProduct                : 0x8037
bcdDevice                : 0x100
iManufacturer            : 0x01 (String Descriptor 1)
 Language 0x0409         : "Arduino LLC"
iProduct                 : 0x02 (String Descriptor 2)
 Language 0x0409         : "Arduino Micro"
iSerialNumber            : 0x00 (No String Descriptor)
bNumConfigurations       : 0x01

        ------------------ String Descriptors -----------------
             ------ String Descriptor 0 ------
bLength                  : 0x04 (4 bytes)
bDescriptorType          : 0x03 (String Descriptor)
Language ID[0]           : 0x0409 (English - United States)
             ------ String Descriptor 1 ------
bLength                  : 0x18 (24 bytes)
bDescriptorType          : 0x03 (String Descriptor)
Language 0x0409          : "Arduino LLC"
             ------ String Descriptor 2 ------
bLength                  : 0x1C (28 bytes)
bDescriptorType          : 0x03 (String Descriptor)
Language 0x0409          : "Arduino Micro"

        -------------- Configuration Descriptor ---------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x02 (Configuration Descriptor)
wTotalLength             : 0x0064 (100 bytes)
bNumInterfaces           : 0x03
bConfigurationValue      : 0x01
iConfiguration           : 0x00 (No String Descriptor)
bmAttributes             : 0x80
 D7: Reserved, set 1     : 0x01
 D6: Self Powered        : 0x00 (no)
 D5: Remote Wakeup       : 0x00 (no)
 D4..0: Reserved, set 0  : 0x00
MaxPower                 : 0xFA (500 mA)

        ------------------- IAD Descriptor --------------------
bLength                  : 0x08 (8 bytes)
bDescriptorType          : 0x0B
bFirstInterface          : 0x00
bInterfaceCount          : 0x02
bFunctionClass           : 0x02 (Communications and CDC Control)
bFunctionSubClass        : 0x02
bFunctionProtocol        : 0x01
iFunction                : 0x00 (No String Descriptor)

        ---------------- Interface Descriptor -----------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x04 (Interface Descriptor)
bInterfaceNumber         : 0x00
bAlternateSetting        : 0x00
bNumEndpoints            : 0x01 (1 Endpoint)
bInterfaceClass          : 0x02 (Communications and CDC Control)
bInterfaceSubClass       : 0x02
bInterfaceProtocol       : 0x00
iInterface               : 0x00 (No String Descriptor)

        -------------- CDC Interface Descriptor ---------------
bFunctionLength          : 0x05 (5 bytes)
bDescriptorType          : 0x24 (Interface)
bDescriptorSubType       : 0x00 (Header Functional Descriptor)
bcdCDC                   : 0x110 (CDC Version 1.10)

        -------------- CDC Interface Descriptor ---------------
bFunctionLength          : 0x05 (5 bytes)
bDescriptorType          : 0x24 (Interface)
bDescriptorSubType       : 0x01 (Call Management Functional Descriptor)
bmCapabilities           : 0x01
bDataInterface           : 0x01

        -------------- CDC Interface Descriptor ---------------
bFunctionLength          : 0x04 (4 bytes)
bDescriptorType          : 0x24 (Interface)
bDescriptorSubType       : 0x02 (Abstract Control Management Functional Descriptor)
bmCapabilities           : 0x06

        -------------- CDC Interface Descriptor ---------------
bFunctionLength          : 0x05 (5 bytes)
bDescriptorType          : 0x24 (Interface)
bDescriptorSubType       : 0x06 (Union Functional Descriptor)
bControlInterface        : 0x00
bSubordinateInterface[0] : 0x01

        ----------------- Endpoint Descriptor -----------------
bLength                  : 0x07 (7 bytes)
bDescriptorType          : 0x05 (Endpoint Descriptor)
bEndpointAddress         : 0x81 (Direction=IN  EndpointID=1)
bmAttributes             : 0x03 (TransferType=Interrupt)
wMaxPacketSize           : 0x0010 (16 bytes) (16 bytes)
bInterval                : 0x40 (64 ms)

        ---------------- Interface Descriptor -----------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x04 (Interface Descriptor)
bInterfaceNumber         : 0x01
bAlternateSetting        : 0x00
bNumEndpoints            : 0x02 (2 Endpoints)
bInterfaceClass          : 0x0A (CDC-Data)
bInterfaceSubClass       : 0x00
bInterfaceProtocol       : 0x00
iInterface               : 0x00 (No String Descriptor)

        ----------------- Endpoint Descriptor -----------------
bLength                  : 0x07 (7 bytes)
bDescriptorType          : 0x05 (Endpoint Descriptor)
bEndpointAddress         : 0x02 (Direction=OUT  EndpointID=2)
bmAttributes             : 0x02 (TransferType=Bulk)
wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
bInterval                : 0x00 (ignored)

        ----------------- Endpoint Descriptor -----------------
bLength                  : 0x07 (7 bytes)
bDescriptorType          : 0x05 (Endpoint Descriptor)
bEndpointAddress         : 0x83 (Direction=IN  EndpointID=3)
bmAttributes             : 0x02 (TransferType=Bulk)
wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
bInterval                : 0x00 (ignored)

        ---------------- Interface Descriptor -----------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x04 (Interface Descriptor)
bInterfaceNumber         : 0x02
bAlternateSetting        : 0x00
bNumEndpoints            : 0x01 (1 Endpoint)
bInterfaceClass          : 0x03 (HID - Human Interface Device)
bInterfaceSubClass       : 0x00 (None)
bInterfaceProtocol       : 0x00 (None)
iInterface               : 0x00 (No String Descriptor)

        ------------------- HID Descriptor --------------------
bLength                  : 0x09 (9 bytes)
bDescriptorType          : 0x21 (HID Descriptor)
bcdHID                   : 0x0101 (HID Version 1.01)
bCountryCode             : 0x00 (00 = not localized)
bNumDescriptors          : 0x01
Descriptor 1:
bDescriptorType          : 0x22 (Class=Report)
wDescriptorLength        : 0x0065 (101 bytes)
  05 01             Usage Page (Generic Desktop Controls)
  09 02             Usage (Mouse)
  A1 01             Collection (Application)
  09 01               Usage (Pointer)
  A1 00               Collection (Physical)
  85 01                 Report ID (0x01)
  05 09                 Usage Page (Buttons)
  19 01                 Usage Minimum (1)
  29 03                 Usage Maximum (3)
  15 00                 Logical Minimum (0)
  25 01                 Logical Maximum (1)
  95 03                 Report Count (3)
  75 01                 Report Size (1)
  81 02                 Input (Var)
  95 01                 Report Count (1)
  75 05                 Report Size (5)
  81 03                 Input (Const, Var)
  05 01                 Usage Page (Generic Desktop Controls)
  09 30                 Usage (Direction-X)
  09 31                 Usage (Direction-Y)
  09 38                 Usage (Wheel)
  15 81                 Logical Minimum (-127)
  25 7F                 Logical Maximum (127)
  75 08                 Report Size (8)
  95 03                 Report Count (3)
  81 06                 Input (Var, Rel)
  C0                  End Collection
  C0                End Collection
  05 01             Usage Page (Generic Desktop Controls)
  09 06             Usage (Keyboard)
  A1 01             Collection (Application)
  85 02               Report ID (0x02)
  05 07               Usage Page (Keyboard)
  19 E0               Usage Minimum (-32)
  29 E7               Usage Maximum (-25)
  15 00               Logical Minimum (0)
  25 01               Logical Maximum (1)
  75 01               Report Size (1)
  95 08               Report Count (8)
  81 02               Input (Var)
  95 01               Report Count (1)
  75 08               Report Size (8)
  81 03               Input (Const, Var)
  95 06               Report Count (6)
  75 08               Report Size (8)
  15 00               Logical Minimum (0)
  25 65               Logical Maximum (101)
  05 07               Usage Page (Keyboard)
  19 00               Usage Minimum (0)
  29 65               Usage Maximum (101)
  81 00               Input ()
  C0                End Collection

        ----------------- Endpoint Descriptor -----------------
bLength                  : 0x07 (7 bytes)
bDescriptorType          : 0x05 (Endpoint Descriptor)
bEndpointAddress         : 0x84 (Direction=IN  EndpointID=4)
bmAttributes             : 0x03 (TransferType=Interrupt)
wMaxPacketSize           : 0x0040 (64 bytes) (64 bytes)
bInterval                : 0x01 (1 ms)

Hopefully you can compare this to your situation and see what is different.

(Edited to add)
I tried today on my son's Windows 7 PC, which I don't think had Arduino ever installed on it. Also I used my Leonardo instead of the Micro, just to be sure. First Windows tried to install the device drivers:

Then it only succeeded with the composite device and the keyboard:

However the keyboard worked (eg. in Notepad).

It shows up in the Device Manager:

Thank you very much for this @nick - I'm going to dig into this. You're completely correct about the keypresses being irritating! May I ask - was Arduino installed on the Windows 7 machine before you plugged in the micro or not? Trying to work backwards to find the actual .inf / .cat file that was used by the OS.

Yes, I had 1.0.6 installed for some reason. However as you know the device drivers themselves are triggered by inserting the USB device. If you can't resolve it with what I posted above, I'll try inserting the Micro into my son's Windows 7 machine and see what happens. I don't think that has Arduino on it. so as to be sure that the driver I install is the one being used. - when you wrote that, did you force the install of the Arduino driver, or let Windows install its one?

See further screen shots and testing in amended reply.

Very interesting indeed. So my next move is to Uninstall the device I have from Device Manager while checking the "remove software" box and see if that gets me to the same point you reached here. If it doesn't, I'll try a VM with a fresh Windows install. Thanks @Nick!

thanks for all of your assistance. For whatever reason, I can't recreate the same results as on your son's computer, but I do now have a definitive way out of this thanks to all of your help. Effectively, you need to make sure you install a generic composite device driver for the Leonardo, which then breaks out the other Interface Descriptors (HID, CDC, Mouse, MIDI etc). I am going to screenshot all the steps and answer my own question, but without your assistance this would not have been possible!

Re "It is incredibly annoying ...": Alternatively, use an I/O pin to control whether it should be actively or not.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Arduino does not make any sound when connected to laptop?
When I connect my Arduino through USB to my laptop, it does not make any sound like something is connected but green light is on. And port option in the Arduino IDE remains grayed out. I might have burned my Arduino, maybe? Please help.

Can you try 1) a different cable, 2) connecting to a different computer, or 3) a different Arduino? Has anything happened to the Arduino to make you suspect any damage? It does sound like a problem with the communication processor on the Arduino board, but best to be sure.

An Arduino never makes a sound when connected.  Any such sound would be a function of the host operating system, which you have neglected to even mention in your question.

Is this a real Arduino, or a cheap Chinese CH340G based BoS?

The Arduino will not make a sound, but probably you refer to the sound Windows makes when a USB device is connected?
Try (except for the tips already given by JRobert)

different USB port
reinstall Arduino IDE
disable/enable or reinstall driver in Control panel/hardware/system/USB devices

There are a number of possible scenarios as to what is wrong:

The USB cable is a power only cable and has no data lines. However, this is unlikely because, whilst power-only USB cables are common with mobile phones (i.e. USB to Micro USB), a full on USB-A to USB-B cable, which is what the Uno uses, normally do not come in a power-only configuration.
The port is damaged on the laptop. This is unlikely, but it worth checking by connecting a keyboard or mouse to the same port, to see if data is transferred
You have no driver installed. This is the most likely scenario. Normally the Arduino will trigger a driver to be automatically installed. However, in the case of the cheap Chinese clones, which use the CH340G chip, then the CH340 driver will need to be installed, if you are using Windows. Check the Device Manager in Windows to see if you Uno is recognised when connected, or whether is is shown as an "Unknown Device". A quick google should provide you with the correct driver for the CH340G. Please note that, if you are using Linux, then no driver is required, see Majenko's answer to Safe place to download CH340G drivers from.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to detect cancelled download?
I have a server with files that may be downloaded.
How do I go about detecting when a download is cancelled by a client?
The function that handles reading files for download:
void readFile()
{

EthernetClient client = server.available();

// Open file for Reading.
SdFile webFile;
webFile.open(&root, &MyBuffer[1], O_READ);
if (!webFile.isOpen()) error("readFile");

do   // @ adafruit_support_rick's do-while loop
{
    int count = 0;
    char buffers[BUFSIZE];
    bool done = false;

    while ((!done) && (count < BUFSIZE) && (webFile.available()))
    {
        char c = webFile.read();
        if (0 > c)
        done = true;
        else
        buffers[count++] = c;
        delayMicroseconds(1000);
    }

    if (count)
    client.write( buffers, count);

} while (webFile.available());

webFile.close();

fileDownload = 0;  //File download has finished; allow logging since download has completed

delay(500);

MyBuffer[0] = '\0';

}

Well, assuming cancelling a download == incomplete download == client disconnected before server was done, you could create a flag like this at the top of the function:
bool dload_cancel = false;

Change the IF block, below the innermost WHILE loop, to this:
if (count){
  if (client.connected())
    client.write( buffers, count);
  else {
    dloadCancel = true;
    break;
  }
}

The flag will be set once your server checks and discovers that the client has been disconnected. You can check the state of the flag outside the DO-WHILE block to know if the download was completed or not.
if (dloadCancel){
  // client was disconnected; download did not complete
}

dloadCancel is also a better indicator of a completed download than your fileDownload flag.
You should also know that this:
if (0 > c)
    done = true;

is redundant. Its already taken care of by webFile.available().


text:
SoftwareSerial will not read all of the printed string when calling readString()
I have an Arduino UNO and an ESP32 that need to communicate to each other using SoftwareSerial. The problem I am coming across is that when I call readString and print it out using Serial, it will not give me everything that has been printed out from my ESP32.
I have my Arduino RX Pin hooked up to 4 and TX hooked up to 5
I have my ESP32 RX2 Pin hooked up to 16 and TX2 pin hooked up to 17, with the GND hooked up to directly to the Arduino GND
I am not using any resistors, straight up 5v of pure power
Arduino UNO Code:
// C-standard library
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include <SoftwareSerial.h>

#define RX_PIN 4
#define TX_PIN 5

SoftwareSerial ardSerial(RX_PIN, TX_PIN);

void setup(void) {
  // Get access to network
  pinMode(RX_PIN, INPUT);
  pinMode(TX_PIN, OUTPUT);
  Serial.begin(9600);
  while(!Serial) {}
  ardSerial.begin(9600);
  while(!ardSerial) {}
}

void loop(void) {
  while (ardSerial.available() > 0) {
    String payload = ardSerial.readString();
    Serial.println(payload);
  }
  delay(1000);

}

ESP32 Code
#include <stdlib.h>
#include <string.h>

#include <SoftwareSerial.h>

SoftwareSerial ardSerial;

void setup(void) {
  // Begin connections
  Serial.begin(115200);
  while (!Serial) {}

  ardSerial.begin(9600, SWSERIAL_8N1, RX2_PIN, TX2_PIN);
  while (!ardSerial) {}
  return;
}

void loop(void) {
  {
    String spotData = "Huge JSON File that needs transferred";
    ardSerial.print(spotData);
  }

  delay(5000);
}

Expected result:

Able to retrieve every little bit of the JSON file that was printed out

Actual result:

Only receive like half of the JSON file

How big is the JSON file? How many bytes did the Uno manage to retrieve?

@EdgarBonet it's a huge JSON file, can't tell you exactly how many bytes the JSON holds since it is random each time. I grab it from the Spotify API if that tells you anything. It retrieves from the beginning of the JSON to a random part near the middle, then it just cuts communication until the JSON is sent again

does it fit into the RAM of the Uno?

I see 2 problems with your code:

You wrote in the comments, that the JSON file is huge. The Uno has only 2kB of RAM and you are trying to lead the complete file into RAM at once. Such a JSON file from Spotify will easily exceed the 2kB (in fact you have even less, because the Arduino framework and SoftwareSerial also use some of the RAM). So you just cannot handle the complete file at once with an Uno.

You use readString(). This function is sure easy, but also has some pitfalls. It uses the String class, which utilizes dynamic memory allocation. It allocates a bigger character array in RAM, if the current array is not big enough. That means, that you would need up to 2 versions of your String fitting into RAM while receiving, leaving only about 1kB. Also it will read from the SoftwareSerial interface, until a timeout is hit (1s by default I think). For building a robust communication between the two devices you should read until you reach a special character, for example via readStringUntil(). That special character is often the newline character '\n'.

Possible solution: First we should talk about the limited RAM problem. As stated above you cannot handle the full file at once. You need to handle it in chunks. Whatever you want to do with the data in the end, the Uno will need some time handling the current chunk of data. So you need to pause the transmission of data at the ESP, until the Uno is ready to receive more. Here you can go two ways:

Send the data in chunks of predefined size (small enough for the Uno to hold at once in its RAM) and wait a predefined time between each chunk, that is long enough for the Uno to handle every data it might have gotten in that chunk. This is the easiest to program, but will necessarily take more execution time.
Let the Uno signal to the ESP, that its buffer is full, for example by sending a special character to the ESP. The ESP should then stop sending, until it gets the OK from the Uno to proceed the transmission. To send without loosing data the Uno should probably also send the number of bytes received in that chunk. That way the ESP knows exactly, where in the data String the Uno is currently. This is a bit more difficult, though still easy enough and robust.

To handle the sending in chunks I would use the write(const uint8_t *buffer, size_t size) method of SoftwareSerial (actually this function comes from the Print class, from which SoftwareSerial inherits). The buffer is the pointer to the first element of the current chunk in the char array with the data. You can get the char array via spotData.c_str() and you can get the pointer to the n-th element of it via &(spotData.c_str()[n]). The second parameter is the size of the chunk in bytes. This needs to be small enough, that the data will fit into the RAM of the UNO, together with all the RAM needed for processing the data.
On the Uno I would then do the reading bytewise. Something like this:
char data[BUFFER_SIZE]="";
int pos=0;

void loop(){
    if(ardSerial.available()){
        data[pos] = ardSerial.read();
        if(pos == BUFFER_SIZE - 1){
            // Handle chunk of data
            pos = 0; // reset position to reuse buffer
        } else {
            pos++;
        }
    }
}

I have left out some parts to only demonstrate the principle. Also you need to define BUFFER_SIZE yourself, depending on the available RAM.
Obviously this does not implement the second option with the pause signal, which is more complex.

Apart from sending and receiving you will need to think about how to process the chunks of data. This depends largely on what exactly you want to do with that data. Just sending them via Serial is easy. Interpreting the data in chunks is more difficult.

There are two ways to implement a parser for a language like JSON or
XML:

Have the parser swallow the whole document at once, and produce an
in-memory representation of the same data.

Have the parser return control to the caller for each “event” it
detects, where an “event” is typically a primitive data item, or the
start or the end of a container.

Parsers of the first kind are much easier to use, but this can be
expensive in RAM usage if you want to parse a alrge document. The second
kind of parsers are harder to use, but they are able to parse huge
documents using a minimal amount of memory.
On an Arduino, you would typically use ArduinoJson, which is a parser of
the first kind, not ideal for parsing huge documents on little memory. A
quick search for “event driven C++ JSON parser” got me JsonReader. I
did not try it, and do not know whether that would work on Arduino, but
it shows that at least this kind of parsers do exist for JSON in C++.
You may want to search further along this way.
Before you dig into this, however, I suggest you give ArduinoJson a
second chance. ArduinoJson has a couple of tricks that can help dealing
with large documents:

You can ask it to filter the data as it reads it, in order to only
keep in memory the items you are actually interested in.

You can deserialize in chunks, and use the data extracted from one
chunk at a time.

Both techniques are explained in the tutorial How to deserialize a very
large document?.
Also, let's not forget the obvious: you should not attempt to store the
raw JSON document in memory. Instead, you should give ArduinoJson a
reference to your stream (namely ardSerial), and let it directly pull
the bytes as it parses.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Bluetooth (HC_06) on the Attiny85
I'm trying to make a hc_06 Bluetooth controller work on the attiny85-20pu.
In the end, I want to control a stepper motor through Bluetooth.
But for now to keep it simple I'm searching for a working code that can turn a simple LED on and off or something like that.
I've searched for a code like that, and I found a few, but they all don't seem to work when I try it.
I checked if the hc_06 maybe wasn't receiving any data or maybe that my wiring was wrong, but at this point I doubt it since I've tried so many different codes and re-wired it so much that I feel like at least 1 should've worked by now
For reference, here are 2 codes I've tried so far but didn't seem to work
source1: https://community.appinventor.mit.edu/t/attiny85-microcontroller-bluetooth-hc-06-arduino-ide/20252/2
source2: https://community.appinventor.mit.edu/t/attiny85-microcontroller-bluetooth-hc-06-arduino-ide/20252/2
#include <SoftwareSerial.h> //Software Serial Port
#define TxD 0 //pin 5 de l'ATtiny à relier au pin RXD du module bluetooth (pin5)
#define RxD 1 //pin 6 de l'ATtiny à relier au pin TXD du module bluetooth (pin4)

SoftwareSerial blueToothSerial(RxD,TxD);
int relais = 4; // pin 3 de l'ATtiny qui commande le relais

void setup()
{
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
  blueToothSerial.begin(9600);
  //delay(2000); // délai nécessaire
  blueToothSerial.print("Bluetooth connecté !\n");
  delay(4000); //Vérifie que tous les relais sont bien inactifs après un reset
  pinMode(relais, OUTPUT);
  digitalWrite(relais, LOW); // ouvre le relais
}

void loop()
{
  char recvChar;
  while (1) {
    //vérifie s'il y a des données envoyées à partir du module bluetooth
    if (blueToothSerial.available()) {
      recvChar = blueToothSerial.read();
      if (recvChar == '1')
        digitalWrite(relais, HIGH);
      else
        digitalWrite(relais, LOW);
    }
  }
}

Or this one
// Tiny85 y Bluetooth HC-06
// Juan A. Villalpando
// kio4.com

#include <SoftSerial.h>
#include <TinyPinChange.h>
#define LED4 4

SoftSerial Bluetooth(2, 3);
char caracter;

void setup()
{
  Bluetooth.begin(9600);
  pinMode(LED4, OUTPUT);
}

void loop()
{
  while (Bluetooth.available() > 0) {
    caracter = Bluetooth.read();
    if (caracter == '1') {
      digitalWrite(LED4, HIGH);
      Bluetooth.println('E');
    }
    if (caracter == '0') {
      digitalWrite(LED4, LOW);
      Bluetooth.println('A');
    }
  }
}

UPDATE
With this code it works but only if I disconnect TX from the HC_06 to RX to the attiny85. If I do that the LED will turn on after a few seconds
and if I then send a 0 it works fine.
hopefully this helps?
#define RxD 1
#define TxD 0

#define DEBUG_ENABLED  1

SoftwareSerial blueToothSerial(RxD,TxD);

int led = 4 ;

void setup()
{
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
  setupBlueToothConnection();

  pinMode(led,OUTPUT);

}

void loop()
{
  char recvChar;
  while(1){
    //check if there's any data sent from the remote bluetooth shield
    if(blueToothSerial.available()){
      recvChar = blueToothSerial.read();

        if(recvChar==0)
          digitalWrite(4,HIGH);

        else
          digitalWrite(4,LOW);
    }
  }
}

void setupBlueToothConnection()
{
  blueToothSerial.begin(38400); //Set BluetoothBee BaudRate to default baud rate 38400
  blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
  blueToothSerial.print("\r\n+STNA=MAVA_bluetoothcr\r\n"); //set the bluetooth name as "HC-05"
  blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
  blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here

  delay(2000); // This delay is required.
  //blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
  blueToothSerial.print("bluetooth connected!\n");

  delay(2000); // This delay is required.
  blueToothSerial.flush();
}```

how is everything connected and how is it powered?

depends on which of the 2 codes you mean. but I'm pretty sure its not a wiring problem. And as for the power I'm using a Arduino uno which only use is to power the Attiny85 and hc_06.

Does the HC-06 work correctly with the Unos Serial connection? It might be configured to the wrong baudrate

Its not hooked up to an Arduino but to the attiny85 itself but I did test it on the Arduino and it works just fine. the hc_06 still receives data no problem but somehow nothing happens with that data.

Mhh, is the Attiny running at the frequency, that the compiler is expecting? If you compile lets say for an 8MHz clock frequency, but the fuses still are set to 1MHz, that would also mess with the timing of the software serial interface

I'm not sure what you mean with the fuses of the attiny85 but I did calculate that I should put de baud rate on 38400 if I compile it with 8MHz I'm not sure if that helps?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
RGB LED randomized colors and LDR fading at the same time
Im trying too make an RGB LED that keeps changing color's randomly, and makes the brightness fade at the same time with an LDR, yet I keep getting an error that says too many arguments to functions.
could anyone possibly help me?
EDIT:
(this is the correct code sorry)
 const int LED_D_RGB_G_PIN = 11;
const int LED_D_RGB_B_PIN = 10;
const int LED_D_RGB_R_PIN = 9;
const int LDR = A1;

int inputval=0;
int outval =0;

void setup() {
  pinMode(LED_D_RGB_R_PIN, OUTPUT);
  pinMode(LED_D_RGB_G_PIN, OUTPUT);
  pinMode(LED_D_RGB_B_PIN, OUTPUT);
  pinMode(LDR, INPUT);

}

void loop() {
    inputval = analogRead(LDR);
    outval = map(inputval, 0, 380, 255, 0);

    int lightval = constrain(outval, 0,255);

    analogWrite(LED_D_RGB_R_PIN, lightval, random(0,255));
    analogWrite(LED_D_RGB_G_PIN, lightval, random(0,255));
    analogWrite(LED_D_RGB_B_PIN, lightval, random(0,255));
    delay (50);
}

If you get an error during compilation, please include the full error (including the information where the error happened) in the question. Also: Doing two analogWrite calls on the same pins directly after another will not work. Only the second call for each pin will have any effect.

you have a logic error in your code ... you want to choose a random color, and then adjust the brightness of that color ... that is not what happens in your code ...  the code sets the three LEDs to random brightness... that sets a random color and random brightness at the same time ... you have to  choose a random full brightness color and then adjust the brightness without changing the color

I want it to keep changing colors randomly with the RGB while at the same time adjusting the brightness with an LDR. I just dont know how to make them do it separately. also I accidently unloaded the wrong code. sorry. The code I had the problem with was  with this at the end:
analogWrite(LED_D_RGB_R_PIN, lightval, random(0,255));
analogWrite(LED_D_RGB_G_PIN, lightval, random(0,255));
analogWrite(LED_D_RGB_B_PIN, lightval, random(0,255));
delay (50);

}

You need to put that code into your question, not into the comments where we cannot read it easily. So is there still a compilation error? Please inprove your question by editing it

analogWrite() accepts two arguments ... analogWrite(LED_D_RGB_R_PIN, lightval, random(0,255)); has three arguments ... that's why you received the compiler error message

like I already said, choose the color ... then adjust the brightness ... then output the value to the analog pins ... if you set the color directly, as in analogWrite(LED_D_RGB_G_PIN, random(0,255)), then you will have to replace the 255 with an LDR dependent value

I will assume that you can correct any errors in your code and I want to get at a suggestion for a possibly better approach to what I think that you are trying to do.
When you are setting the "color", you are setting the brightness of each of the LEDs; R,G,B, or at least you are trying to do that when you generate a random PWM using analogWrite https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/.
Then, you are trying to set the brightness again, presumably based on the ambient light value from the LDR AND it is set for the combined output of the 3 LEDs which are likely at different intensity values, since intensity was randomly chosen. The problem is, how can you scale the values perfectly so that you get the same color but at a lower intensity? I think that is much more difficult than you might believe...for a bunch of reasons.
I would suggest you try something along these lines, but keep some low expectations....

Use a variable called maxb, which changes the maximum possible value used in the analogWrite() values so that it it not always 255. You can adjust that value based on reading the LDR. You will have to do some experimenting and don't expect a huge range of values. Now, your color will still be picked at random, but with an adjustment for intensity.

You "should" try to use resistors on each of the RGB LEDs that will produce something close to equivalent brightness. This will vary somewhat between RGB LEDs. Below is a graph of where I looked at this for a color fader project many years ago. I used an old BH1750 ambient light sensor to get the lux values. That dashed line is for the equivalent brightness of the individual LEDs by resistor value (ohms) used [220-Red, 750-Green, 470-Blue]. This is not an ideal way, but it is easy.

That might get you near where you want to be, but for "extra credit", note that brightness scaling is not an equal interval scale. So, a PWM value of 250 is NOT 10 times brighter than a PWM value of 25. Brightness is, more or less, on an exponential scale except for very dim values, which are, again, more-or-less, linear. Look into the CIE 1931 perceived lightness formula and Weber and Stevens and so on. Since this is not a psychophysics lab, let me cut to the chase. The array below represents an intensity scale as I have described and includes values of 0 and 255 as per an 8 bit width (which is what analogWrite uses). You could use a minimum value of 4 or 8 instead of 0 if you wanted to guarantee a visible output every time. Test that out, but for the sake of discussion, let's assume you are using all values in the array.

A[13]{0,1,2,4,8,17,32,51,75,106,145,194,255};
You would scale your LDR range to 13 possible values (0-12) and then get your maximum value for analogWrite from the array. Then, you would pick a random value for 0 to maxb for each of your analogWrites to the RGB.

I don't know how brightness is represented by your LDR and you should consider that when you are determining your ambient light intensity values - ideally, you would want 13 equal intensity values from your LDR - right?. I suppose something about that is probably in the data sheet.

That is how I would do it anyways :)

Thank you! this helps a lot! I didn't think it would be easy from the start but this helped me understand just how difficult it is. I will definitely start to experiment with the code some more and hopefully ill get a satisfactory result!


text:
LiquidCrystal_I2C, lcd.begin() causes runtime error on Arduino Mega2560
I have tested the library and LCD with simple script and everything worked fine. Now I am trying to add the LCD functionality to my working program but the code reaches the lcd.begin(); function it causes a runtime error and no following lines are executed. I have tried many different configurations and none of them have worked; including have lcd.begin() in the setup(), in the InitSM(), loop(), and RunSM() and it crashes every time.
I am wondering if I am running into a similar issue described here.
Following thebusybee's advice, I started with a simple working script that could print to the LCD screen. I then started adding initializing functions in the setup until it stopped working. InitSM(&AFC); is the line that causes the LCD functions to stop working. InitSM(&AFC); calls millis(), enables watchdog timer interrupts, and external interrupt on digital pin 2. Below is the exam code.
// Library
#include <Arduino.h>
#include <EventTimers.h>
#include <EventCheckers.h>
#include <avr/sleep.h>
#include <Timeout.h>
#include <AFCSM.h>
#include <DoorServo.h>
#include <EventTypes.h>
#include <HardwareInterrupts.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);
//LiquidCrystal_I2C *lcdA; //0x27,20,4
//lcdA = &lcd;
//lcdA->begin();

// global variables
static uint8_t TimerCheck = 0;
static uint8_t Timer30;
static EventType LCDButton;
static EventType BatteryEvents;
static EventType BumperEvents;
static EventType FogEvents;
static EventType CurrentEvent;
static EventType FrontDoor;
static EventType BackDoor;
static AFCDATA AFC;
static AFCState PreviousState;

void setup() {
  // set up serial communication with computer
  Serial.begin(9600);

  // uart for MiniOFS to MCU
  Serial1.begin(1200, SERIAL_8N1);

  /*** set up interrupts, not init ***/
  SetUpWatchdogT(); // 8sec interrval counter for 32sec environ sensor check
  SetUpButtonInt(); // external button interrupt for LCD screen

  // init LCD
  lcd.begin();

  // Enable interrupts
  sei();

  // Set the sleep mode to Power-Down
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  // initi doors
  initDoor();

  // init statemachine
  InitSM(&AFC);
  PreviousState = AFC.State;
}

void loop() {
  Serial.flush();

  lcd.clear();
  // lcd.setCursor(2,0);   //Set cursor to character 2 on line 0
  lcd.print("LED INIT!");
  Serial.println("printed");
}

ISR(WDT_vect) {
  // Add to timer
  TimerCheck += 1;

  // check if 30secs have elapsed time has
  if (TimerCheck >= 3){
    TimerCheck = 0; // reset counter
    Timer30 = true; // raise flag
  }

}

void Buttonisr(){
  // Button Flag
  LCDButton = BUTTON_ON;
}

I narrowed it down to being the external interrupt enable on digital pin 2. Below are the functions for the setup and enable of the external interrupt.
void SetUpButtonInt(){

    // set up the pin as an input and attach a isr
    pinMode(ButtonPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(ButtonPin), Buttonisr, RISING); // interrupt on rising edge of pin

    return;
}

void EnableButtonInt(){

    EIMSK |= (1 << INT0); // enable external interrupt
    Serial.println("enable external interrupt");
    return;
}

How can this setup affect the lcd I2C setup?

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". Then come back and format your code, it is easy. Then add the specific error message or explain what you mean by "runtime error". To help us help you, minimize your program to the absolute minimum that still shows the erroneous behavior.

Initialize the LCD only once in setup and not with every update

@KIIV I tried this first and it would never make it past setup

If you suspect the line lcdA->begin(); to crash your program, PLEASE write a minimized sketch just with this initialization in setup() and an experimental output. I don't think anyone will rebuild your full hardware setup and debug the complete thing. Investigate step by step. Please [edit] your question and add this minimal sketch and its outcome.

Just a guess. The minimum timeout for the watchdog timer is 16ms. This lcd.begin() may well block for longer than that since the begin method if filled with delay() statements. Just for a test, replace lcd.begin() with delay(1000) to see if you get the same symptoms. Where, incidentally,  is this defined: SetUpWatchdogT()


text:
Project concerning wireless communication between Raspberry Pi and Arduino Uno using NRF24L01
We are trying to send a message using NRF24L01, with a Raspberry Pi as transmitter and an Arduino Uno as receiver.
Our concern is that the receiver Arduino might not be working because we are not getting the proper output message on the serial monitor.
Code for the transmitter side (Python code):
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev

GPIO.setmode(GPIO.BCM)

pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0, 17)

radio.setPayloadSize(32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openWritingPipe(pipes[0])
radio.openReadingPipe(1, pipes[1])
radio.printDetails()
#radio.startListening()

message = list("GETSTRING")
while len(message) < 32:
    message.append(0)

while True:
    start = time.time()
    radio.write(message)
    print("Sent the message: {}".format(message))
    radio.startListening()

    while not radio.available(0):
        time.sleep(1/100)
        if time.time() - start > 2:
            print("Timed out.")
            break

    receivedMessage = []
    radio.read(receivedMessage, radio.getDynamicPayloadSize())
    print("Received: {}".format(receivedMessage))

    print("Translating our received Message into unicode characters...")
    string = ""

    for n in receivedMessage:
        if (n >= 32 and n <= 126):
            string += chr(n)
    print("Our received message decodes to: {}".format(string))

    radio.stopListening()
    time.sleep(1)

Code used for the receiver side (Arduino):
#include<SPI.h>
#include<RF24.h>

// ce, csn pins
RF24 radio(9, 10);

void setup(void) {
  while (!Serial);
  Serial.begin(9600);

  radio.begin() ;
  radio.setPALevel(RF24_PA_MAX) ;
  radio.setChannel(0x76);
  radio.openWritingPipe(0xF0F0F0F0E1LL);
  const uint64_t pipe = 0xE8E8F0F0E1LL;
  radio.openReadingPipe(1, pipe);

  radio.enableDynamicPayloads();
  radio.powerUp();
}

void loop(void) {
  radio.startListening();
  Serial.println("Starting loop. Radio on.");
  char receivedMessage[32] = {0};
  if (radio.available()) {
    radio.read(receivedMessage, sizeof(receivedMessage));
    Serial.println(receivedMessage);
    Serial.println("Turning off the radio.");
    radio.stopListening();

    String stringMessage(receivedMessage);

    if (stringMessage == "GETSTRING") {
      Serial.println("Looks like they want a string!");
      const char text[] = "Hello World!";
      radio.write(text, sizeof(text));
      Serial.println("We sent our message.");
    }
  }
  delay(100);
}

why would you single out the receiver as being the cause of the problem?

I am getting the output in raspberry pi as successfully sent the message. But the message is not showing in arduino serial monitor. That's why I think the problem is with the receiver side.Maybe the receiver is not decoding the message properly.

What is "Proper output" you're expecting with your code?

I am trying to send the message "GETSTRING" in the form of a list from raspberry pi which I want to get in the serial monitor of the arduino. In the arduino I am giving the command Serial.println(receivedMessage), but it is not getting printed.


text:
How can we get a timer interrupt at a specific time or date?
How can we get a timer interrupt at a specific time or date?
For example: I want to make a project with an Uno and I'm using sleep mode and the wake-up source is timer2, as per the ATMega328p datasheet.
I want to turn on an LED, for example every day at 3pm, and the chip is in sleep mode on other times of the day.
So, how can I set the timer?
I think I have to use CTC mode of timer2 and set the OCR amount but I'm not sure how to do it.
There's a project on (Link) this link on the Arduino site that is perfect for this project, but when I compile it, it gives me an error saying that it can't be compiled for the Uno.

Use an RTC chip. The Arduino timers have no concept of real time, only relative time, and that usually over very short periods.

Incidentally, that project uses an RTC that is built in to some of the more advanced (ARM) chips.

16.38 ms is the longest period you can get out of Timer 2. And 4.19 s  is the longest you can get out of any timer of the Uno.


text:
making power harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are)
i have been  intendng to make a power frequency harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are examples for making spectrum analyser with fft library's here is the example for the kosome made fft library
   #include <arduinoFFT.h>

   #define SAMPLES 128             //Must be a power of 2
   #define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC

   arduinoFFT FFT = arduinoFFT();

   unsigned int sampling_period_us;
   unsigned long microseconds;

   double vReal[SAMPLES];
   double vImag[SAMPLES];

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

        sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
   }

   void loop() {

        /*SAMPLING*/
        for(int i=0; i<SAMPLES; i++)
        {
            microseconds = micros();    //Overflows after around 70 minutes!

            vReal[i] = analogRead(0);
            vImag[i] = 0;

            while(micros() < (microseconds + sampling_period_us)){
            }
        }

        /*FFT*/
        FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
        FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
        FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
        double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

        /*PRINT RESULTS*/
        //Serial.println(peak);     //Print out what frequency is the most dominant.

        for(int i=0; i<(SAMPLES/2); i++)
        {
            /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

            //Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
            //Serial.print(" ");
            Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
        }

        //delay(1000);  //Repeat the process every second OR:
        while(1);       //Run code once
   }

how can i seperate the amplitudes for particular frequencies like amplitude of 50hz = ?, 150hz = ? and store them in other variables

please use the {} button to format your code

The general idea of your code looks OK, but consider using a hardware timer rather than the for loop for data acquisition.  The sampling rate will be much more accurate and uniform because you eliminate (possibly cumulative) errors in timing.  See this post for an example.
Do you know how the FFT.MajorPeak function works?  If it simply finds the frequency of the largest point in the magnitude spectrum, this may not be a good measure of the 50 Hz peak etc.  Instead, consider taking the area under the curve around the frequency of interest f_0, say f_0 - 2 Hz to f_0 + 2 Hz.  The same code should be usable to measure the spectral power around any of the harmonics.
Also note that the mains electricity frequency is not exactly 50 Hz / 60 Hz.  The short-term variation is around plus/minus 1 Hz.  The above approach will also help make reliable readings.


text:
expected unqualified-id before 'if' if (!client.connected() && lastConnected)
#include <PulseSensorPlayground.h>
#include <Timer.h>
#include <SPI.h>
#include <Ethernet.h>

Timer t;
PulseSensorPlayground pulseSensor;

// Local Network Settings
byte mac[] = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "UVGOLIA40B9YHKU8";
const int updateThingSpeakInterval = 16 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
// Variable Setup
const int PulseWire = A0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           //for heart rate sensor
float myTemp;
int myBPM;
String BPM;
String temp;
int error;
int panic;
int raw_myTemp;
float Voltage;
float tempC;

long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;
// Initialize Arduino Ethernet Client
EthernetClient client;
void setup()
{
  // Start Serial for debugging on the Serial Monitor
  Serial.begin(9600);
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }

  // Start Ethernet on Arduino
  void startEthernet();
}
void loop()
{
  // Read value from Analog Input Pin 0
  String analogPin0 = String(analogRead(A0), DEC);
  // Print Update Response to Serial Monitor
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }
  //temp---
  raw_myTemp = analogRead(A1);
  Voltage = (raw_myTemp / 1023.0) * 5000; // 5000 to get millivots.
  tempC = Voltage * 0.1;
  Serial.println(tempC);

  //Serial.print(temp);
  //Serial.print(" ");

  //-----BMP180-----------
  //
  int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
  // "myBPM" hold this BPM value now.
  if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".

    Serial.println(myBPM);
    char buffer1[10];
    char buffer2[10];
    String BPM = dtostrf(myBPM, 4, 1, buffer1);
    String temp = dtostrf(tempC, 4, 1, buffer2);
    // Print the value inside of myBPM.
  }
}
//----------------
void panic_button() {
  panic = digitalRead(8);
  if (panic == HIGH) {
    Serial.println(panic);
  }
}
// Disconnect from ThingSpeak
if (!client.connected() && lastConnected)
{
  Serial.println("...disconnected");
  Serial.println();
  client.stop();
}
// Update ThingSpeak
if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))
{
  updateThingSpeak("field1=" + BPM + "&field2=" + temp + "&field3=" + panic);
}
// Check if Arduino Ethernet needs to be restarted
if (failedCounter > 3 ) {
  startEthernet();
}
lastConnected = client.connected();
}
void updateThingSpeak(String tsData)
{
  if (client.connect(thingSpeakAddress, 80))
  {
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + UVGOLIA40B9YHKU8 + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(tsData.length());
    client.print("\n\n");
    client.print(tsData);
    lastConnectionTime = millis();
    if (client.connected())
    {
      Serial.println("Connecting to ThingSpeak...");
      Serial.println();
      failedCounter = 0;
    }
    else
    {
      failedCounter++;
      Serial.println("Connection to ThingSpeak failed (" + String(failedCounter, DEC) + ")");
      Serial.println();
    }
  }
  else
  {
    failedCounter++;
    Serial.println("Connection to ThingSpeak Failed (" + String(failedCounter, DEC) + ")");
    Serial.println();
    lastConnectionTime = millis();
  }
}
void startEthernet()
{
  client.stop();
  Serial.println("Connecting Arduino to network...");
  Serial.println();
  delay(1000);
  // Connect to network amd obtain an IP address using DHCP
  if (Ethernet.begin(mac) == 0)
  {
    Serial.println("DHCP Failed, reset Arduino to try again");
    Serial.println();
  }
  else
  {
    Serial.println("Arduino connected to network using DHCP");
    Serial.println();
  }
  delay(1000);
}

You did not actually write a question!  Please edit

If you look at this fragment of your code:
void panic_button(){
  panic = digitalRead(8);
    if(panic == HIGH){
    Serial.println(panic);
    }
}
// Disconnect from ThingSpeak
if (!client.connected() && lastConnected)

You see that the function panic_button() stops at the last }, the next is a statement which is not part of a function.
I think the } should be removed, but your code is aligned quite badly, so:

First align all { and }
Indent each level with a tab or 2, 3 or 4 spaces
You will see a misalignment, add/remove a { (like above) or }.


text:
freeRTOS tasks never run on Lightblue Bean
Although Punchthrough no longer supports the Bean and Bean+ they still maintain the online compiler and reference materials:
Bean Github
Bean reference
One of the external libraries they've included in the cloud compiler is FreeRTOS, linked libs Arduino FreeRTOS port, and the cloud compiler/BeanLoader seems to properly link to the lib and download my compiled app to the bean:
// minimal test for freeRTOS

// works on UNO, fails on Bean

#include <Arduino_FreeRTOS.h>

// Logging hackery
// 0 disables, 1 enables
// #define LogConstantly 0
#define LogConstantly 1

#if(LogConstantly)
  #define Dump(x) Serial.print(x)
  #define Dumpln(x) Serial.println(x)
  #define DumpS Serial
#else // ! LogConstantly
  #define Dump(x)
  #define Dumpln(x)
  #define DumpS
#endif // LogConstantly

// LED handling
// Find the Bean files in [apps]Bean\ Loader[vers?].app/Contents/Resources/Arduino/hardware/bean/avr/cores/bean/
// Defined in bean.h:  BEAN_BEAN_BEAN_H
#ifdef BEAN_BEAN_BEAN_H
  #define LED_ON  Bean.setLed(0,0,127)  // light the blue segment at 50%
  #define LED_OFF Bean.setLed(0,0,0)
#else
  #define LED_ON  digitalWrite(LED_BUILTIN, HIGH);
  #define LED_OFF digitalWrite(LED_BUILTIN, LOW);
#endif // BEAN_BEAN_BEAN_H

#define RELAYOUTPUT 2 // pin for relay control.

// tasks for RTOS scheduling

void TaskBlink(void *pvParameters)  // This is a task.
{
  (void) pvParameters;
  while(true) { // A Task never exits.
    LED_ON;
    Dumpln("BlinkenLit");
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    LED_OFF;
    Dumpln("BlinkenDark");
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskRelay(void *pvParameters)
{
  (void) pvParameters;
  while(true) { // A Task never exits.
    digitalWrite(RELAYOUTPUT, HIGH);   // engage the relay
    Dumpln("relay enabled");
    vTaskDelay( 2500 / portTICK_PERIOD_MS ); // wait for 2.5 seconds
    digitalWrite(RELAYOUTPUT, LOW);    // disengage the relay
    Dumpln("relay disabled");
    vTaskDelay( 900 / portTICK_PERIOD_MS ); // wait for .9 second
  }
}

// setup runs once on reset/power
void setup() {

  Serial.begin(115200);
  while (!Serial) { ; } // wait for USB serial port on 32u4 boards.

  pinMode(RELAYOUTPUT, OUTPUT);
#ifndef BEAN_BEAN_BEAN_H        // Bean's tricolor LED is already initialized.
  pinMode(LED_BUILTIN, OUTPUT); // just in case UNO LED line uninitialized.
#endif

  // test and display hardware connections
  LED_ON;
  digitalWrite(RELAYOUTPUT, HIGH);
  Dumpln("everybody lit?");
  delay(2000); // 2 second nap
  LED_OFF;
  digitalWrite(RELAYOUTPUT, LOW);
  Dumpln("everybody should be unlit, RTOS schedule starts in 5 seconds...");
  delay(5000);

  // set up tasks to run independently.
  xTaskCreate(
    TaskBlink
    ,  (const portCHAR *)"Blink"   // A name just for humans
    ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
    ,  NULL
    ,  1  // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
    ,  NULL );

  xTaskCreate(
    TaskRelay
    ,  (const portCHAR *) "Relay"
    ,  128  // Stack size
    ,  NULL
    ,  1  // Priority
    ,  NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop()
{
  // Empty. Things are done in Tasks.
}

This code works as expected on an UNO, but never seems to execute its tasks on a Bean+. The Bean clearly passes through the setup function, triggering both LED and relay for 2 seconds as expected, but then it never manages to execute a task.
FreeRTOS uses the AVR's Watchdog timer for scheduling. My suspicion is that the Bean may use the AVR's watchdog timer for Bean.sleep() and there's a conflict there. But their docs imply that the Bluetooth chip manages AVR sleep. From Power Management::

What wakes up Bean? What actually happens in Bean sleep is that the
  ATmega (the microcontroller running your Arduino sketch) goes fully to
  sleep. Meanwhile, the Bluetooth chip sleeps in between small periods
  of Bluetooth stack activity. This means the Bluetooth chip can wake up
  the ATmega for a variety of events:
A client connecting to Bean can wake the ATmega if Bean is configured
  for wake-on-connect A received serial message will wake the ATmega Any
  type of interrupt will wake the ATmega A common practice is to have
  Bean sleep for as long as possible using Bean.sleep(0xFFFFFFFF). This
  way, Bean will stay asleep indefinitely, and you can wake up Bean with
  a serial message or interrupt.

OTOH, this subsequent line in the Bean Docs is very suspicious, because FreeRTOS docs note that the AVR watchdog timer's granularity is 15 ms. That's an odd coincidence, I'd expect the BLE chip to have finer grained timers available, and I seem to recall the AVR chips need about 7 ms to wake from deep sleep.

Minimum Sleep Time It’s important to keep in mind that Bean.sleep()
  has a minimum sleep time of 15 ms. If you need delays under 15 ms, you
  will have to use delay or delayMicroseconds instead.

So, finally the questions:
Does the Bean sleep implementation depend upon the watchdog timer?
If so, can FreeRTOS and/or the Bean be persuaded to play nice?
If not, what might be breaking FreeRTOS in the Bean?
(And yes, I know the Beans, unsupported and (slightly) obsolete are now a poor choice for a real-time control task. But I like the Bean and Bean+, still have a few in my parts bin, and have a task that's a perfect match for the Bean. I don't blame Punchthrough for abandoning the Bean, though I do wish they'd left up, or at least archived, the user forum.)

A minor rant: I know the arduino is intended as an inexpensive gentle entry to low-power, connected computing, but it's a crime that the environment provides so little support or guidance for its natural uses: sensing, machine control, environmental reporting, etc. No builtin example I've seen shows proper interrupt management. All the timing examples use power hogging, cycle wasting, busy-wait delays. Where's the scheduler? Maybe a task queue? Libdispatch lite, anyone?
I guess the moral is: if I want it, why aren't I contributing? :( Insert usual lame excuses ):

to your comment: it wouldn't be Arduino then. you can do it all without Arduino or mixed with Arduino

@Juraj Yeah, true ... but the Arduino environment is sooo convenient :) I've done a lot of bare-metal real-time, but the setup time for new hardware, and the often-crummy dev tools, makes it tedious for hobby hackery. I'm planning to explore this as an alternative: https://platformio.org/platformio-ide

I use Eclipse plugin Sloeber. With it I can very fast solve questions like yours by 'drilling' down into source code of the core and libraries. It is like x-ray vision compared to Arduino IDE. But first I would need to install the 'bean' core.


text:
Arduino leonardo. Encoder mouse movement
I want to connect my sensonrs to an arduino leonardo.
The principal idea is use it like a scratch (like dj hero or beatmania??), if I move the scratsh up, the mouse will go up ( y Axis ), and if it go down, the y Axis down.
The middle is for gnd and the other four to 0 to 3 pin in the arduino.
So my problem is I am not sure about the conecction and also the code to run my program, beacuse all the thing that i try to do, had no work in my computer.

That's a quadrature encoder implemented using photo interrupters. Use a DMM to suss out which half of each is the diode and which is the phototransistor, connect both halves as you would were they independent, and decode the quadrature output.

Thanks you very much, I did not know the name. I searched and found the map to connect to my arduino.


text:
Arduino Uno with 6x 5V solenoids + 9V battery - Not enough power?
I have 6 5V solenoids connected to an Arduino Uno, each of them with a TIP120 transistor, diode and resistor. Exactly like https://core-electronics.com.au/tutorials/solenoid-control-with-arduino.html but 6 times. I'm using a 9V battery connected to the DC input, as well as USB input to my PC.
Now the problem is that if I activate 5 or 6 solenoids at once, the Arduino seems to get interrupted / lose all power for a second (disconnect sound from the PC and no activity). I've tested them one by one and everything works, but I can activate at most 4 solenoids at once.
What am I missing? Do I need more power?

I'm using a 9V battery connected to the DC input

Well, there's your problem. Those 9V PP3 batteries are barely enough to power the Arduino by itself. Add anything like motors and solenoids and you're going to have problems. Big problems.
Ditch the PP3 battery. It's only suitable for very low current devices, like smoke alarms. For anything more you need at least multiple series AA batteries.
Also the solenoids must be powered direct from your power source (or through their own regulator if needed), since the Arduino's on-board regulator will go into thermal shutdown quite quickly with 9V in and a large current draw.

I should've mentioned I've also tried a 6x AA battery pack on DC, it gave the same results. And I'm not sure how I can connect them directly to my power source?

@SJ19 Take the wire out of the 5V pin on the Arduino and connect it to your battery + (assuming the battery isn't too high a voltage for your solenoid).

Thank you! Guess I should be looking for a battery connector with wires then. Excuse my ignorance but do you reckon a 9V battery will be too much for the 5V solenoids?

@SJ19 If they are actually 5V solenoids, then yes probably. You will want a 5V regulator. Get a UBEC from an RC model seller - they're the simplest option.

You're experiencing a lack of available current. When the solenoids are operating, the system is trying to draw more current than the battery can provide, so what happens instead is the voltage starts to drop. (I can't remember exactly why this happens right now). When this happens the arduinos power supply detects an under-voltage condition and shuts down, but as soon as it shuts down the current draw tanks and the voltage rises again causing the system to restart. Essentially, the answer to this is to provide your system with a larger current source and the problem should go away.

Another possibility is to use latching solenoids controlled by an H-bridge so that they only need power to turn on or turn off. However, I don't know if they are available for your application. When I looked into latching irrigation valves they were much more expensive than simple solenoid valves.


text:
ESP8266 with RTC DS1307 shield - WS2818B shield won't blink - I2C issue?
Dear Ladies and Gentlemen,
I'd like to let a LED blink base on the time of the day. So I took Wemos D1 mini and a WS2818B shield and a RTC DS107 Shield for the before mentioned ESP8266 model.
Based on my observation, I can let the LED blink on its own without starting the initialization of the RTC. As soon as I initialize the communication with the DS1307 shield, the LED shield won't translate any commands toward the desired behavior (e.g. the LED won't blink anymore).
What am I doing wrong?
I'm using the Ardunio IDE to program the D1 mini.
I stacked the shields and kept an eye on the pins to be sure I did wire everything the right way.
Libraries in use:
RTC: https://github.com/Makuna/Rtc
LED: Adafruit NeoPixel
Code:
// WIFI
#include <ESP8266WiFi.h>

// RTC
#include <RtcDateTime.h>
#include <RtcUtility.h>
#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS1307.h>
RtcDS1307<TwoWire> Rtc(Wire);

// LED
#include <Adafruit_NeoPixel.h>
#define PIN        D2
#define NUMPIXELS 1
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ400);

int DELAYVAL = 1000; // Time (in milliseconds) to pause between pixels

void setup() {

  Serial.begin(57600);
  Serial.println();
  Serial.flush();

  setupLed();

  setupWifiConnection();

  setupRtc();

}

void loop() {

  pixels.clear(); // Set all pixel colors to 'off'
  pixels.show();   // Send the updated pixel colors to the hardware.
  delay(DELAYVAL); // Pause before next pass through loop

  pixels.setPixelColor(0, pixels.Color(0, 150, 0));
  pixels.show();   // Send the updated pixel colors to the hardware.
  delay(DELAYVAL); // Pause before next pass

}

void setupRtc () {

  Rtc.Begin();

  RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
  Serial.println();

  if (!Rtc.IsDateTimeValid())
  {
      if (Rtc.LastError() != 0)
      {
          // we have a communications error
          // see https://www.arduino.cc/en/Reference/WireEndTransmission for
          // what the number means
          Serial.print("RTC communications error = ");
          Serial.println(Rtc.LastError());
      }
      else
      {
          // Common Causes:
          //    1) first time you ran and the device wasn't running yet
          //    2) the battery on the device is low or even missing

          Serial.println("RTC lost confidence in the DateTime!");
          // following line sets the RTC to the date & time this sketch was compiled
          // it will also reset the valid flag internally unless the Rtc device is
          // having an issue

          Rtc.SetDateTime(compiled);
      }
  }

  if (!Rtc.GetIsRunning())
  {
      Serial.println("RTC was not actively running, starting now");
      Rtc.SetIsRunning(true);
  }

  RtcDateTime now = Rtc.GetDateTime();
  if (now < compiled)
  {
      Serial.println("RTC is older than compile time!  (Updating DateTime)");
      Rtc.SetDateTime(compiled);
  }
  else if (now > compiled)
  {
      Serial.println("RTC is newer than compile time. (this is expected)");
  }
  else if (now == compiled)
  {
      Serial.println("RTC is the same as compile time! (not expected but all is fine)");
  }

  // never assume the Rtc was last configured by you, so
  // just clear them to your needed state
  Rtc.SetSquareWavePin(DS1307SquareWaveOut_Low);
}

void setupLed () {

  pixels.begin();

  pixels.clear();
  pixels.show();
}

void setupWifiConnection () {

  WiFi.begin("some ap", "some password");

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

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

Can you check, if and where the code gets stuck? You can do this by inserting serial prints at several positions to track down the exact problem location

please describe what you observe ... add the description to your post, not to comments ... it looks like setupRtc should be generating some output to the serial monitor

According to your code, you’ve connected the Neopixel to D2. The RTC is an I2C device, so it’s also connected to D2. How is that supposed to work? The Neopixel isn’t an I2C device.
Move the Neopixel to a different pin that’s not used by anything else - so not D1. Try D3. Update your code to use D3. There may be other issues but at least you won’t be trying to use the same pin to talk to two very different devices.

Absolutely correct. What I oversaw was the fact the Neopixel LED shield is no I2C device. As suggested I wired the pin to D3 and it worked right away. Thank you @romkey.