text:
Driving stepper to follow sequential positions
I was exploring the stepper motor library AccelStepper and using it because of it's easy interface to control multiple stepper motors simultaneously. Recently I got a problem. I needed a stepper motor to follow position commands of the following kind :
int steps[] = { -0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 4, 4, 4,
                4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, -0, -1, -1, -1, -2, -2, -3,
                -13, -13, -13, -13, -13, -13, -13, -13, -13, -13, -13, -13, -13, -13, -13,
                6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 4, 4, 3, 3,
                3, 2, 2, 1, 1, 0, -0 };

This array is truncated in the middle. Actual command is continous throughout the first position to last position.These are the absolute steps that the motor needs to turn.
I generated the pulses to achieve this as following:
void loop() {
  delay(5000);

  int stepperDelay = 9000;

  for (int i = 0; i < 701; i++) {
    int moveTo = steps[i + 1] - steps[i];
    if (moveTo < 0) {
      digitalWrite(dirPin, LOW);
    } else {
      digitalWrite(dirPin, HIGH);
    }
    for (int x = 0; x < abs(moveTo); x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(stepperDelay);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(stepperDelay);
    }
  }

}

Writing the pulses myself gave me a satisfactory result in transition from one abs position to another abs position. The overall working was smooth to the extent I desired.
But, it's gonna take me a lot more effort to apply this to three different stepper motors simultaneously, so I tried to use AccelStepper to do the same thing. I tested the following code :
void setup() {
  st1.setMaxSpeed(maxSpeed);
  st1.setAcceleration(acc);
  st1.setCurrentPosition(0);
}
void loop() {
  delay(5000);

  for (int i = 0; i < 703; i++) {
    st1.moveTo(m1_steps[i]);
    while (st1.distanceToGo() != 0 ) {
      st1.run();
    }
  }

}

This code when I tested, made the motor to follow the same trajectory, but it failed to make it smooth. The movement is not smooth, appears to have some pause betweeen every step.
has anyone any clue what might be the appropriate way ?
I tested with both A4988 driver and TB6600, same issue.

Pause between steps is what a stepper motor does.  That's how it works.  If you want a shorter pause so it looks smoother then increase the speed.

for the A4988,  the STEP input does not have to be a square wave ... the motor moves on low/high transition only ... the input has to stay high for only 1 microsecond

@Delta_G Thanks for the reply !! I am not actually complaining about the pause between the steps, it's actually between two positions in the array. For some reasons library method seems to implement it more coarser at any speed for that matter. I ended up implementing a non-blocking for loop to simultaneously actuating three motors. I would love to hear your thoughts on that.

@jsotola thanks for the insight. I will try that to save extra microseconds.

Is it just that accelstepper is slowing down at the end of one and speeding up at the start of the next?

@Delta_G yes, something like that. Perhaps it's because of the run() method which tries to optimize the movement of due steps, but in my case since the due steps changes in a loop as it has to go through the positions given in the array resulting in lack of continuity. I tried to search how the 3D printers are coded since they have to loop through the gcode as well but didn't find useful information.

If you don't want acceleration and deceleration between steps, then pick a different stepper library.  AccelStepper is specifically written to add that acceleration and deceleration.  Try the normal Arduino Stepper library instead.


text:
Arduino Nano ESD crash despite ESD protection measures
Good day!
I've just ran into a problem with a project of mine that I can't really figure out myself anymore. So i'm hoping someone on here will be able to help...
First things first, I'm trying to replace the controller of a split air conditioner after it's microcontroller went up in smoke. The idea is quite simple, three temperature sensors, three relays and a VFD for the indoor fan. Add to that three buttons and a small display.
The system is built as follows:

The issue I run into is that the addition of the 'circled' section consisting of a seperate UI panel with three buttons and a 128.64px OLED causes random hangs on the Arduino's code but ONLY if the High voltage section is powered.
If the display is not connected, the system runs fine, even when the compressor starts up and shuts down. The same is true with the display connected but the line voltage off (I.e. powered over USB)
The curious thing is that this only happens with the display section on it's 10cm long shielded and grounded ribbon cable, whereas two of the temperature sensors are ziptied to the main power wire for a length of almost five meters.
I have already gone and tried the usual methods for ESD protection. Adding clipping diodes into the UI box, capacitors over the switches to dampen any induced current spikes and adding a low-value resistor pair to the I²C bus (not on schematic yet). The entirety of the cable connecting the UI enclosure to the Arduino is shielded internally as well as a seperate wrap of heavy duty aluminum tape.
The High and low voltage sections of the circuit are completely seperated by relais, System ground, Shield ground, Chasis ground and mains ground are shorted together. The Arduino is only connected trough one of it's GND pins so no outside power can flow trough it's ground plane.
Still, as soon as the UI section is connected, the Arduino hangs until the watchdog resets it a while later only for it to happen again in a few minutes.
At this point I've tried everything short of upgrading to a real PLC controller and thus would greatly appreciate any help or tips with this issue...
Here is a snap of the setup (I know about the Wagos but I was tired of unscrewing the wires every time):

And this is the UI-section with temperature+ temperature- and power button as well as the display:

Safety hint: I am a certified IT-Systems electrician with permits for working with refrigerants. Don't kill yourself with mains voltage projects

Maybe some extras, fast diodes over relay coils, all unused pins to outputs, test it without anything connected to the relay switches, maybe you'll need Boucherot cells on relay switches. You can go for opto couplers or try SSR

I've added all of the ideas to the circuit. Some fast shotky diodes across the relay coils, 0.1µ + 150Ω snubbers over all AC relay switches as well as a 10µ cap and diode over the DC relay as well as setting all unused pins to OUTPUT and LOW.
It hasn't helped the issue much though. The Arduino still randomly crashes with the display attached but runs fine without. Oddly enough it doesn't need a relay switching to crash it, it just happens inbetween.
I really appreciate the help though!

SSRs or optocouplers would be something for a rebuild of the board with tons of isolation as there is no room on the current design. I'm still contemplating though wether to accept the boards will to be run without UI or to actually bite the bullet and start over from scratch.

If it happens even without relays it might be some memory issue, overusing Strings or something. You can try much stronger pull-up on reset line. And check 5V line with scope or something (also there is reset reason register in AVRs, you can try to check that). That's all I can think of other than redoing board

ESD protection is for protecting from high power surge caused by irregular power surge or lightning, it does not filter any noise coming into the circuit. What if you disconnect 5m long cable for temperature sensors (or only connect two temperature sensors locally without cable), but connect the display unit, will it still hang? 5m temp sensor ziptied to the main power wire is not a good idea.

i tend to think 10cm (although it looks to me it is more than 30cm long)  I2C should be okay unless there are some software bug that caused memory leak. To further isolate the problem, add decoupling capacitors 1uF and 0.1uF in parallel to each of the 5V rail, and connecting the display uint without the cable, will it help?

BTW, all the relays should have diode connect across its coil to prevent inrush current.

Alrighty. I've checked the memory usage with the MemoryUsage Library and it doesn't seem to cross the 1500-byte mark at any point in the operation - With display or without. Additionally, the sketch is very light. It contains the display library, a temp-conversion for the thermistors as well as a few if's to turn the relays on and off. There are only few variables used.

I've removed the remote temp sensors from the circuit and replaced them with a 10k resistor each directly at the board. It still runs fine without the display section but crashes after a few seconds if the display section is attached.
The display-line decoupling caps didn't work for me as the display refused to work after adding them, sadly, the Arduino also still crashed after several seconds.
The supply rails seem to be stable at 4.89V with a max 52mV ripple at the arduino when the compressor starts or shuts down.

@hcheung The ULN2003 chip has internal diodes meant to achieve exactly that. However after KIIV's suggestion I've also added aditional shotky diodes over every relay coil

The 5v line which powers the Nano is also switched via a relay back to the VFD so I guess it is more than a few mA. I would begin to suspect that. You've marked two pins as +5v but I guess this is actually the same pin. If, however, you are using Vin then that needs around 7 volts depending on the on board regulator. You can't use decoupling caps on the I2C bus. Is that what you meant in your  comment above when you said it failed?
I'd also suspect the code even though you have said it can be stable depending on what is switched on and how it is powered. Can you show this code?

The backfeed of the 5v to the VFD draws around 105mA to drive the VFD's logic. The way the manufacturer handled the external start/stop is apparently by interupting the power to the VFD's microcontroller. And yeah, the Arduino only has one 5V pin which both sides connect to. It was just simpler to draw the shematic parted in two sides for inputs & outputs. I know that the I2C bus shouldn't be decoupled as the data transmission is technically AC coupled to ground trough caps but I figured it was worth a try given the Arduino can source and sink a few mA trough it's pins.

So... I've finally figured it out. After spending nearly two days trying to debug this weird case, it turns out that my Arduino was apparently broken.
For a short while I switched the Nano with an ESP8266 with PCA9685 output expansion and level shifters to try and figure out if the USB cable I had attached during programming was giving me false readings when using the Serial port to debug. With that ESP8266 it worked flawlessly.
I then got curious about what other boards it would work with and tried out an Arduino Leonardo (Atmega 32u4) and later a 3rd party Uno which worked too.
I was quite weirded out to see that it worked with what was basically just a Nano on a larger board. Suspecting foul play by my old Nano, I ordered a replacement one which arrived today.
With the same program and wiring it works flawlessly, running hours on end without crashing.
So either I had a broken controller all along or the new one I got is a lucky chip that can deal with interference better than the old one.
I now have an Arduino nano labeled with "Don't use I2C" in the parts bin
I thank everyone wholeheartedly here for their help!

source: Stack Exchange

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

sort: votes


text:
How do I convert a structure to a char[] for use in Wire.h, or is there a better way?
I need to interface an ATTiny88 MCU configured as an I²C slave with a Raspberry Pi configured as an I²C master.  I may be using the wrong approach, but I have a structure consisting of four different fixed length data types I want to pass back to the Master whenever it requests data.
Source Code:
#include <Wire.h>
struct Response // 7 bytes
  {
      byte Command;         // 1 byte
      float Temperature;    // 4 bytes
      byte FanValue;        // 1 byte
      bool CoolStat;        // 1 byte
  };

struct Response Reply;
bool True = 1;
bool False = 0

void setup()
{
    pinMode(ADDR1, INPUT_PULLUP);   // Address Offset 0 or 1
    pinMode(ADDR2, INPUT_PULLUP);   // Address Offset 0 or 2
    I2C = (2 * digitalRead(ADDR1)) + digitalRead(ADDR1) + 8;    // Set I2C address 8 - 11
    Wire.begin(I2C);
    Wire.onRequest(requestEvent);   // Call requestEvent when data requested

    Reply.Command = 1;
    Reply.Temperature = 35.62;
    Reply.FanValue = 255
    Reply.CoolStat = True
}

// Function that executes whenever data is requested from master
void requestEvent() {
    Wire.write(Reply);         // respond with message as expected by master
    Responded = True;
}

This does not work, of course, because the library does not like the fact I am passing a structure, rather than a simple null terminated string.  I am not sure how best to pass the structure to the Wire.write() function.  I like the ability to change the variables in the structure to different values of different data types at different points in the code, but would I be better served to take a different approach and manually update the binary values in the string?

There is an overload of Wire.write that lets you send an arbitrary
array of bytes:
virtual size_t write(const uint8_t *, size_t);

In order to use it, you have to cast the address of your structure to a
pointer to uint8_t:
Wire.write((uint8_t *) &Reply, sizeof Reply);

Note, however, that this method, although very common, is not really
conformant to the C++ standard. I suggest you instead use a union that
lets you access the memory of the structure as a simple array of bytes:
union Response {
    struct {
        byte Command;         // 1 byte
        float Temperature;    // 4 bytes
        byte FanValue;        // 1 byte
        bool CoolStat;        // 1 byte
    };
    uint8_t bytes[7];
};

This can then be sent with:
Wire.write(Reply.bytes, sizeof Reply);

However: You may have a hard time parsing the structure back on the
Pi. Different computing platforms have different data-type sizes and
different alignments constraints. The structure you are using may be
7-bytes long on an Arduino Uno, but it will be larger on an ARM-based
Arduino, and also on a Raspberry Pi: for alignment reasons, you will
have three padding bytes before Temperature. Also, the CoolStat
field may be larger than one byte, and add some padding of its own. To
make things easier, I recommend you define the structure in a way that
its layout is platform-independent: use only fixed-size types, put the
larger items first, and manually pad to a multiple of the larger item's
size:
union Response {
    struct {
        float Temperature;  // 4 bytes
        uint8_t Command;    // 1 byte
        uint8_t FanValue;   // 1 byte
        uint8_t CoolStat;   // 1 byte
        uint8_t padding;    // 1 byte
    };
    uint8_t bytes[8];
};

This should have the exact same layout on any Arduino, and also on a
Raspberry Pi.

To avoid alignment, you can use #pragma pack(1)

@SBF: This probably works on x86_64. However, I prefer avoid it, as I have used computers where unaligned memory accesses crash the program with SIGBUS (Bus error).

Thank you, Sir!  Yours is a perfect answer.

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


text:
Can the ATTiny88 be programmed via I2C from a Raspberry Pi?
This is similar to Is it possible to program an AVR chip (atmega328p) via i2c?, but not exactly, and that thread is a little shy on details.
I have an ATTiny88 attached via I2C to a Raspberry Pi, with the Pi as master.  The system is remote from me, but I can contact the Raspberry Pi via a WiFi connection at the remote location.  Updating the software on the Pi is quite easy, of course, but it would be really great if I could upload a compiled file from the IDE to the Pi and then download to the ATTiny88 over I2C.  This would make firmware changes and updates to the Arduino easy.

what results did you get in your research?

Even if it is theoretically possible, you will not find any guidelines. You're supposed to program  ATTiny88 using hardware like USBASP.

Does it matter that's I2C?

there's an I2C bootloader project on GitHub

The only result I got is that it should be possible, but without details I am rather at an impasse.  Do you have a link to the  I2C bootloader project on GitHub?  It sounds like a good place to start,

@liaifat85: What I am "supposed" to do is irrelevant.  I have a Raspberry Pi I can contact and upgrade remotely that is attached to the Arduino.  I can easily have the Pi contact a server automatically when an upgrade is required.  If it is possible to upgrade the firmware over I2C, then it is a good idea.  Getting to the Arduino physically will present a problem if the device is halfway around the world in the hands of someone I have never met.

@timemage: Well, since the I2C bus is how the Raspberry Pi talks to the Arduino, then yeah, it matters.

According to the datasheet:

The device provides a self-programming mechanism for downloading and uploading program code by the MCU itself. The
self-programming can use any available data interface and associated protocol to read code and write (program) that code
into the program memory. The SPM instruction is disabled by default but it can be enabled by programming the SELFPRGEN fuse (to “0”).

So it would seem that it is possible. To be practical you would need to fit the code to do the self-programming, plus the code to actually do something useful, into the 8K of flash memory.
You would also need to organise the code in some way so that when reprogramming, you don't erase and overwrite the code doing the reprogramming during the process.
This could be a bit tricky to implement, but not impossible.

Assuming you are currently using the tiny with some i2c library, that library most likely won't allow it. If you want to simplify the task at hand, consider the problem from another viewpoint :

can you reset the tiny using the I2C interface ? (tip : create a "Reset" register)
Can you use the same pins for programming the tiny (but not using I2C, rather Serial or SPI).

If you can get the above two sub-projects done, you'll be able to do what you want. Simply set the pins to Serial (or SPI) at startup for a few seconds, then switch to I2C.


text:
How can I save an image from the ESP32-CAM to a separate SD card?
For a project, I need to take a picture with the ESP32-CAM, save it to an SD card, and then have the Arduino UNO access the image. I have the ESP32-CAM with OV2640 connected to the ESP32-CAM-MB, which is connected via USB to my laptop.
Currently, I'm using the following code to capture the image and save it to the microSD on the ESP32-CAM.
// Include Required Libraries

// Camera libraries
#include "esp_camera.h"
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "driver/rtc_io.h"

// MicroSD Libraries
#include "FS.h"
#include "SD_MMC.h"

// EEPROM Library
#include "EEPROM.h"

// Use 1 byte of EEPROM space
#define EEPROM_SIZE 1

// Counter for picture number
unsigned int pictureCount = 0;

// Pin definitions for CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27
#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

void configESPCamera() {
  // Configure Camera parameters

  // Object to store the camera configuration parameters
  camera_config_t config;

  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG; // Choices are YUV422, GRAYSCALE, RGB565, JPEG

  // Select lower framesize if the camera doesn't support PSRAM
  if (psramFound()) {
    config.frame_size = FRAMESIZE_XGA; // FRAMESIZE_ + QVGA|CIF|VGA|SVGA|XGA|SXGA|UXGA
    config.jpeg_quality = 10; //10-63 lower number means higher quality
    config.fb_count = 3;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }

  // Initialize the Camera
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  // Camera quality adjustments
  sensor_t * s = esp_camera_sensor_get();

  // BRIGHTNESS (-2 to 2)
  s->set_brightness(s, 1);
  // CONTRAST (-2 to 2)
  s->set_contrast(s, 2);
  // SATURATION (-2 to 2)
  s->set_saturation(s, -2);
  // SPECIAL EFFECTS (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia)
  s->set_special_effect(s, 0);
  // WHITE BALANCE (0 = Disable , 1 = Enable)
  s->set_whitebal(s, 1);
  // AWB GAIN (0 = Disable , 1 = Enable)
  s->set_awb_gain(s, 1);
  // WB MODES (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home)
  s->set_wb_mode(s, 0);
  // EXPOSURE CONTROLS (0 = Disable , 1 = Enable)
  s->set_exposure_ctrl(s, 0);
  // AEC2 (0 = Disable , 1 = Enable)
  s->set_aec2(s, 0);
  // AE LEVELS (-2 to 2)
  s->set_ae_level(s, 0);
  // AEC VALUES (0 to 1200)
  s->set_aec_value(s, 450);
  // GAIN CONTROLS (0 = Disable , 1 = Enable)
  s->set_gain_ctrl(s, 0);
  // AGC GAIN (0 to 30)
  s->set_agc_gain(s, 30);
  // GAIN CEILING (0 to 6)
  s->set_gainceiling(s, (gainceiling_t)0);
  // BPC (0 = Disable , 1 = Enable)
  s->set_bpc(s, 0);
  // WPC (0 = Disable , 1 = Enable)
  s->set_wpc(s, 1);
  // RAW GMA (0 = Disable , 1 = Enable)
  s->set_raw_gma(s, 1);
  // LENC (0 = Disable , 1 = Enable)
  s->set_lenc(s, 1);
  // HORIZ MIRROR (0 = Disable , 1 = Enable)
  s->set_hmirror(s, 0);
  // VERT FLIP (0 = Disable , 1 = Enable)
  s->set_vflip(s, 0);
  // DCW (0 = Disable , 1 = Enable)
  s->set_dcw(s, 1);
  // COLOR BAR PATTERN (0 = Disable , 1 = Enable)
  s->set_colorbar(s, 0);

}

void initMicroSDCard() {
  // Start the MicroSD card

  Serial.println("Mounting MicroSD Card");
  if (!SD_MMC.begin()) {
    Serial.println("MicroSD Card Mount Failed");
    return;
  }
  uint8_t cardType = SD_MMC.cardType();
  if (cardType == CARD_NONE) {
    Serial.println("No MicroSD Card found");
    return;
  }

}

void takeNewPhoto(String path) {
  // Take Picture with Camera

  // Setup frame buffer
  camera_fb_t  * fb = esp_camera_fb_get();

  if (!fb) {
    Serial.println("Camera capture failed");
    return;
  }

  // Save picture to microSD card
  fs::FS &fs = SD_MMC;
  File file = fs.open(path.c_str(), FILE_WRITE);
  if (!file) {
    Serial.println("Failed to open file in write mode");
  }
  else {
    file.write(fb->buf, fb->len); // payload (image), payload length
    Serial.printf("Saved file to path: %s\n", path.c_str());
  }
  // Close the file
  file.close();

  // Return the frame buffer back to the driver for reuse
  esp_camera_fb_return(fb);
}

void setup() {

  // Disable brownout detector
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);

  // Start Serial Monitor
  Serial.begin(115200);

  // Initialize the camera
  Serial.print("Initializing the camera module...");
  configESPCamera();
  Serial.println("Camera OK!");

  // Initialize the MicroSD
  Serial.print("Initializing the MicroSD card module... ");
  initMicroSDCard();

  // initialize EEPROM with predefined size
  EEPROM.begin(EEPROM_SIZE);
  pictureCount = EEPROM.read(0) + 1;

  // Path where new picture will be saved in SD Card
  String path = "/image" + String(pictureCount) + ".jpg";
  Serial.printf("Picture file name: %s\n", path.c_str());

  // Take and Save Photo
  takeNewPhoto(path);

  // Update EEPROM picture number counter
  EEPROM.write(0, pictureCount);
  EEPROM.commit();

  // Bind Wakeup to GPIO13 going LOW
  esp_sleep_enable_ext0_wakeup(GPIO_NUM_13, 0);

  Serial.println("Entering sleep mode");
  delay(1000);

  // Enter deep sleep mode
  esp_deep_sleep_start();

}

void loop() {

}

Is there a way to wire the ESP32-CAM so that the Arduino UNO can access the images on the SD card? Or is it possible to wire it to a separate data logging shield with an SD card, that the Arduino UNO could also access?

I think you can find your answer if you follow this tutorial: https://randomnerdtutorials.com/esp32-cam-take-photo-save-microsd-card/  This tutorial shows how to take photos with the ESP32-CAM board and save them to a microSD card using Arduino IDE. When you press the ESP32-CAM RESET button, it wakes up, takes a photo and saves it on the microSD card. You can also send pics from ESP32-CAM to telegram: https://www.pcbway.com/blog/25/ESP32_CAM_with_Telegram__Take_Photos__Control_Outputs__Sensor_Readings_and_Motio.html

That's not really what I'm looking for. How can the Arduino UNO access the data saved on the SD card in the ESP32-CAM?


text:
Why can my computer not see my Arduino Uno?
I've plugged my ELEGOO Uno R3 into a USB port on my computer with a USB cable. However, neither Arduino IDE nor my computer can see the device. When the Uno is connected, it shows no connected devices. The problem is not the USB port or cable; both work with the Arduino Mega 2560 and the Adafruit Metro 328.
The Uno still receives power from the computer; the green LED is on when the Uno is connected. Why can't the computer see the Arduino?

Has the Uno had any accidental damage such as short circuits, cross-connected power, or even physical damage?

how do you know that your computer cannot see the Arduino?

check cable (no reaction in device manager) or driver is not installed (but it would be shown as unknown usb device or similar)

I have some steps you can take to check your Uno and the Atmega16U2 chip, especially since you have extra Arduinos you can use in the testing process.

@JRobert As far as I know, the Uno isn't damaged, but that would explain why it isn't communicating. The power LED still turns on.

@KIIV When the Arduino is connected to the laptop via USB, the device manager doesn't show any devices connected to the ports, so it's not a driver issue. The cable works for other Arduinos, so it's not that either.

Which USB to serial converter does your Arduino UNO have?


text:
I want to have separate Keypad passcodes to light up an RGB and run a DC Motor in one code. 6113 for RGB and 4613 for the DC Motor
#include <Keypad.h>

const int ROW_NUM = 4; //four rows
const int COLUMN_NUM = 3; //three columns

const int PIN_RED = 2;
const int PIN_GREEN = 3;
const int PIN_BLUE = 4;

const int MOTOR_PIN1 = 5;
const int MOTOR_PIN2 = 13;

char keys[ROW_NUM][COLUMN_NUM] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

byte pin_rows[ROW_NUM] = {12, 11, 10, 9};
byte pin_column[COLUMN_NUM] = {8, 7, 6};

Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );

const String password_1 = "6113";
const String password_2 = "4613";
String input_password;

void setup(){
  Serial.begin(9600);
  input_password.reserve(32); // maximum input characters is 33, change if needed
}

void loop(){
     loop_RGB();
     loop_DCMOTOR();
}

void loop_RGB(){
  char key = keypad.getKey();

  if (key){
    Serial.println(key);

    if(key == '*') {
      input_password = ""; // reset the input password
    } else if(key == '#') {
      if(input_password == password_1) {
        Serial.println("password is correct");

  analogWrite(PIN_RED,   255);
  analogWrite(PIN_GREEN, 0);
  analogWrite(PIN_BLUE,  0);

  delay(1000); // keep the color 1 second

  analogWrite(PIN_RED,   0);
  analogWrite(PIN_GREEN, 255);
  analogWrite(PIN_BLUE,  0);

  delay(1000); // keep the color 1 second

  analogWrite(PIN_RED,   0);
  analogWrite(PIN_GREEN, 0);
  analogWrite(PIN_BLUE,  255);

  delay(1000);
      } else {
        Serial.println("password is incorrect, try again");
      }

      input_password = ""; // reset the input password
    } else {
      input_password += key; // append new character to input password string
    }
  }
}

void loop_DCMOTOR(){
  char key = keypad.getKey();

  if (key){
    Serial.println(key);

    if(key == '*') {
      input_password = ""; // reset the input password
    } else if(key == '#') {
      if(input_password == password_2) {
        Serial.println("password is correct");

     digitalWrite(MOTOR_PIN1, HIGH);
     digitalWrite(MOTOR_PIN2, LOW);
     delay (3000);

      } else {
        Serial.println("password is incorrect, try again");
      }

      input_password = ""; // reset the input password
    } else {
      input_password += key; // append new character to input password string
    }
  }
}

what's your question?

the keyboard code should not be part of the LED code, or part of the motor code ... the keyboard code should be completely separate ... it should simply update the value of a variable depending on which code is entered ... the motor code and led code should simply monitor the value of the variable and run accordingly

In this program, the functions loop_RGB() and loop_DCMOTOR() are
taking turns to try to read the password. If you hit # after typing
the password for the LED, and loop_DCMOTOR() happens to to read your
key press, it will tell you the password is wrong, and reset what you
have typed.
As already stated in a comment and an answer, the solution is to read
the keypad in only one place. You could write a dedicated function for
this, but I would instead just put this code in loop:
void loop() {
    char key = keypad.getKey();

    if (key) {
        Serial.print("key pressed: ");
        Serial.println(key);
        if (key == '*') {  // '*' means reset the input
            input_password = "";
        } else if (key == '#') {  // '#' means validate the input
            if (input_password == password_1) {
                Serial.println("Corect RGB LED password.");
                actuate_LED();
            } else if (input_password == password_2) {
                Serial.println("Corect motor password.");
                actuate_motor();
            } else {
                Serial.println("Incorrect password.");
            }
            input_password = "";  // reset the input
        } else {
            input_password += key;  // append new character
        }
    }
}

Here, actuate_LED() and actuate_motor() are supposed to be small
functions that do the device actuation and nothing more. They do not
concern themselves with the keypad or a password.

write 3 functions, one to receive the password, one to run the DC motor, one to drive the LED. Now in the function to receive the password use an array of 4 bytes to store the password and the 'x' button to clear the array. The function should run a for loop to receive all the 4 digits and the "x" key should break the loop and clear out the array.
You can write the RGB and Motor driver function as per your needs.
In the main loop, you should receive the password and then process this password to run the RGB or motor using a if-else condition.
For any further query feel free to clarify.


text:
HTTPClient post binary data to Prometheus pushgateway
I am a newbie in Arduino and IoT
and using M5StickC Plus2 on Arduino IDE.
I am trying to push data to Prometheus pushgateway, but only get 400 response code.
Pushgateway only accepts binary data. Everything works fine if I do it through curl.
Here is my code:
#include <WiFi.h>
#include <HTTPClient.h>

WiFiClient client;
HTTPClient http;
bool httpOK = http.begin(client, "192.168.0.63", 9091, "/metrics/job/pushgateway-orangepi");

if(httpOK) {
    String msg = String("temperatura{local=\"bsb\"} 24.12\n");
    http.addHeader("Content-Type", "application/octet-stream");
    http.addHeader("Content-Length", String(msg.length()));
    int httpResponseCode = http.POST(msg);
    http.end();
}

your code does not compile without error ... please present the minimal, compilable program that still exhibits the problem

Content-Length header must be http.addHeader("Content-Length", String(sizeof(msg)));

this can't be right. sizeof(msg) is the size of the String object which is not the size of the string managed by the String object


text:
Wiring for VescUart with CAN-Bus
I'm building an RC car with four motors, each of which is controlled by a VESC. The main board is an arduino mega with four serial interfaces, but I need one to connect to another device, so I end up with three serial interfaces vs four VESCs.
So far, for testing, I used VescUart with a single VESC which worked fine except if I try using software serial, so "faking" a serial interface via software serial doesn't work.
Now the readme of the VescUart library promises communication with multiple VESCs using CAN bus. I have absolutely no idea about CAN but as far as I found out it requires special hardware. My question is, how to set up the arduino mega and the four VESCs so I can communicate with all four VESCs with just one UART connection.
My guess would be, one VESC is connected to the arduino over UART and works as the interface to the CAN bus and has canID = 0 which results in the VESC never treating the message as CAN relevant but just as directed to this VESC. If canID > 0 the interface VESC will just forward the message to the CAN bus and the appropriate VESC will read and if necessary reply. So all the VESCS are connected to the CAN bus like here. Any idea on how to do it without CAN is also welcome!
I'm using the VESC Firmware 5.03 on all the boards.
I just want to make sure it's correct before investing money in the CAN.


text:
Controlling UCS2904 LED flood with Neopixel library
I'm attempting to control one of these UCS2904 floodlights using the Neopixel library; according to the chip documentation it uses 800khz and RGBW ordering, both of which are set in my arduino code which has been tested on both an Uno and a Mega. Regardless of board, the floodlight is powering on with its blue powerup behavior and then not appearing to respond to any instructions from either arduino. The same boards and code can operate 12V WS2811 strings without issue. I'm hoping someone has worked with these chips or lights before and can provide some insight!
Code:
#include <Adafruit_NeoPixel.h>

const int neoPixelPin = 10;  // control pin
const int numPixels = 1;    // number of pixels

// set up strip:
 // PARAMETERS BELOW ARE FOR UCS2904 CHIP - RGBW, 800khz
Adafruit_NeoPixel strip = Adafruit_NeoPixel(numPixels, neoPixelPin, NEO_RGBW + NEO_KHZ800);
unsigned long color = 0xFF;   // start with blue

void setup() {
  strip.begin();    // initialize pixel strip
  strip.clear();    // turn all LEDs off
  strip.show();     // refresh strip
  Serial.begin(9600);
}

void loop() {

  // loop over all the pixels:
  for (int pixel = 0; pixel < numPixels; pixel++) {
    strip.setPixelColor(pixel, color);// set the color for this pixel
    if (pixel > 0) {
      strip.setPixelColor(pixel - 1, 0); // turn off the last pixel
    }
    Serial.println(color, HEX);
    strip.show();    // refresh the strip
    delay(500);
  }
  Serial.println(color, HEX);
 delay(3000);       // wait 1 sec before next color run.

   if (color == 0xFF000000) { // if the color is white (0xFF000000)
     color = 0xFF;            // then set it back to blue
     // note: if you are using RGB instead of RGBW pixels, use
     // 0xFF0000 for your highest color instead of 0xFF000000
   } else {
     color = color << 8;      // shift the lit color (value FF, or 255) to the next color
   }

  strip.clear();             // clear the strip at the end of a color run
}

please copy and paste the content of the serial monitor to your question ... no pictures, text only

how do you know that the LED is controlled same as a neopixel?

Assuming the UCS2904B VDD is 12 volts, this document appears to define logic high as 0.6 x VDD.

So for 12 volts VDD logic high would be 7.2 volts. Processors used in most Arduino designs produce either 3.3 or 5 volts logic high. Consider the possibility that the logic high voltage of the Arduinos you are using not high enough to be seen by the UCS2904B.
Consider adding level shifters between the Arduino and UCS2904B.


text:
Timer interrupt setup for one second is too slow (~ 4 seconds)
I am trying to use the timer interrupt on an Arduion Uno.
Here is a imple example code for displaying a progressive digit on a lcd display, which is updated with timer interupt every second:
#include <LCD_I2C.h>

LCD_I2C lcd(0x27);
volatile bool timerFlag = false; // Timer-Flag (timer-Interrupt)
int displayWidth = 16; // display width
int digit = 0; // current digit

void setup() {
  lcd.begin();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Initializing...");

  noInterrupts();
  TCCR1A = 0;
  TCCR1B = (1 << CS12) | (1 << CS10); // set Prescaler to 1024
  TCNT1 = 0;
  OCR1A = 15624; // should be 1 second with a prescaler of 102
  TIMSK1 |= (1 << OCIE1A); // Enable timer interrupt
  interrupts();
}

ISR(TIMER1_COMPA_vect) {
  timerFlag = true;
}

void loop() {
  static int position = 0;
  char displayString[17]; // +1 null termination

  if (timerFlag) {
    lcd.clear(); // clear display

    // update digit and progress
    digit = (digit + 1) % 10;
    position = (position + 1) % (displayWidth + 1);
    memset(displayString, ' ', displayWidth);
    displayString[displayWidth] = '\0'; add null termination
    displayString[position] = '0' + digit; // Character for the current digit

    // Show updated progress on the display
    lcd.setCursor(0, 1);
    lcd.print(displayString);

    timerFlag = false;
  }
}

The values for setting up he inteupt timer 1 for 1 second is arround everywhere.
BUt the updates generated by this code is clearly much slower than 1 second, it's more about 4 seconds.
So i did a comparison with a delay based version of the same example:
#include <LCD_I2C.h>

LCD_I2C lcd(0x27);
int displayWidth = 16; // display width

void setup() {
  lcd.begin();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Initializing...");
}

void loop() {
  for (int digit = 0; digit < 10; digit++) {
    char displayString[17]; // +1 null termination
    int position = digit % (displayWidth + 1);

    // Update progression
    memset(displayString, ' ', displayWidth);
    displayString[displayWidth] = '\0'; // add null termination
    displayString[position] = '0' + digit; // Character for the current digit

    // Show updated progress on the display
    lcd.clear(); // Clear display
    lcd.setCursor(0, 1);
    lcd.print(displayString);

    delay(1000);
  }
}

This one works as expected and updates every second.
So what is wrong with my interrupt settings?

There is a flag in TCCR1A/B called WGM12 which sets the wave generation mode (WGM) to Clear Timer on Compare Match (CTC).
This causes the timer to count up to the value in OCR1A and then automatically reset to 0.
This flag was forgotten, so the interrupt simply ignores the setting OCR1A = 15624; and counts through to 65535, which corresponds to the observed factor of about 4.
Therefore the setting line for TCCR1B must be changed to
TCCR1B = (1 << WGM12) | (1 << CS12) | (1 << CS10);
// Set CTC mode and set Prescaler to 1024

Now the interrupt is triggered correctly every second.

"This still got me some time to find out what it means and what i needed to do, so:" I'm pleased that it was a useful learning exercise for you and your description looks good. Much more valuable than receiving a ready made and complete solution.

It is ignoring this OCR1A = 15624; and simply rolling over at 65535 instead., hence the error factor of 4. You have to set the wave generation mode as CTC in registers TCCR1A/B.

Thank you for the answer.
Unfortunately, I won't be able to try it out until after the weekend.
I will see if it works (but I am pretty confident)

This still got me some time to find out what it means and what i needed to do, so:
The ctc mode means "Clear Timer on Compare Match" and is controled by the WGM12 flag in the TCCR1A/B register. As I'm using the TCCR1b, the line gets:
  TCCR1B = (1 << WGM12) | (1 << CS12) | (1 << CS10);


text:
Understanding ESP8266 OTA Updates: A Question on Limitations
I am currently researching OTA updates for ESP8266 firmware, and I have a question that I couldn't find an answer to:
Question: Is the number of OTA updates limited? According to the documentation, it states: "The flash chip size should be large enough to hold the old sketch (currently running) and the new sketch (OTA) at the same time." Does this mean that the old sketch always remains, and with each new update, the previous versions continue to exist? If so, does this imply that after multiple updates, the flash memory will eventually be full, preventing any further updates?
Thank you for your assistance.

No each update overrites the oldest one (if present) so there are only ever a maximum of 2 versions in flash

This statement takes mainly two reasons into account:

The OTA update needs a complete sketch that executes the update. Overwriting a running sketch with an update crashes in almost all cases.
An OTA update can be disrupted or fail, as a wireless connection is notoriously unreliable. The device needs a working sketch after such events.

That's why the device stores the new sketch in a space separated from the old sketch.
But as soon as the "download" is complete and hopefully checked (by a hash or other means of checksum) to be error-free and valid, the old sketch is not needed any more. The system "switches" from the old sketch to the new sketch, in your case the bootloader overwrites the old sketch with the new sketch, see the last part of the documentation you link to.
The space after the now running new sketch is again free for the next OTA update.
However, there is a physical limit caused by flash memory wear. Commonly this is far away from the number of OTA updates a device will have in its lifetime.


text:
What changed in the new Due?
I recently purchased a batch of Due boards and find that they are cosmetically different. After attaching the Atmel-ICE and reading the firmware from both processors, I find that the firmware is different. The green masked one had a sticker indicating a new IDE should be downloaded from arduino.
The back of the board shows silkscreen changes to the logo (DUE in an oval rather than rectangle) but both boards say BOARD MODEL DUE R3-E. The traces appear the same, the placement of parts appears the same, and other than different colored headers the parts are similar. The main processor has the same part number, but distinctly different markings. Internally the processors report the same device signature and revision.
What has changed in the firmware? Are there other changes I've missed? Other than needing an even newer IDE are there changes that will affect my sketches?
If I load the older firmware onto the newer Due processors, should it operate the same, allowing use of the old IDE, and in case my sketches do face a problem with the new version?

I obtained these from digikey, and both boards came in the same batch. They were packaged according to arduino's usual packaging with stickers, etc. I have no reason to believe I've received parts made by someone else.

It may have something to do with the fact that the arduino is no longer being made it Italy. The US ones are made by adafruit and the china ones by seeedstudio.

@evolutionizer Both are marked quite clearly in the back silkscreen MADE IN ITALY with the country's outline.

But looking carefully I see the 'new' one has ARDUINO.ORG and the other WWW.ARDUINO.CC So perhaps this is fallout from the founder breakup.  Which is which, though?  And why change the firmware?

I was right and wrong :)  The one you have is made by arduino.org who was already manufacturing the boards. I believe they have changed the silkscreen to differentiate. I believe Seeed Studio and Adafruit havent started selling it yet. As for the firmware, there will be no difference as they all still primarily maintained by arduino.cc

I believe the firmware changes are an attempt to lock out non-arduino.org boards from the arduino.org IDE, or the arduino.org boards from the arduino.cc IDE - one or the other.  Either way it's all because of the toys that are being thrown out of various Italian cots.

The 'new' board with green soldermask and the lighter headers is made by arduino.org.  The old one was probably made by the same company, but prior to the split in the founders.
Right now there is arduino.cc (the original website) and arduino.org (the website set up by the company that split from Arduino).  There is a lot of different perspectives about who really owns Arduino and I won't attempt to weigh in here.
The changes in firmware are still unknown.  It's likely that they are simple strings or response changes so the boards can be differentiated in software.  The new IDE is in alpha, and is yet another attempt to differentiate between the two Arduino groups.  I haven't attempted to program either with either group's IDE, but if I do I'll update this answer with the results.
At least there's a way to visually identify the difference once received - wish they had given them different part numbers so Digikey wouldn't have sent me a mixture...

Since the whole thing is a mess and there is only arduino.org still distributing the arduino, this is what you will be getting irrespective of where you order from.

it also looks like arduno.cc is only producing 2 boards https://www.arduino.cc/en/Main/GenuinoBrand

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


text:
What sensor would detect the black stripe on an analog electricity meter?
I have an analog electricity meter (AEM) and I would like to track my usage of electricity.
I've attempted to use the EE-SY310 photo sensor, but that's not sensitive enough it seems. I suspect the black stripe on the dial is too thin to be picked up. The other concern on using any photo sensor is its dependance on light (obviously) hence no reading would be picked up during the night.
Other: I've also found that AEMs work by using magnetic fields to move the dial. The magnetic field detector I used did not show much fluctuation when turning appliances on/off. The dial was pegged at the max. Therefore, I'm not so confident that a sensor to measure magnetic fields would work here, but I'm open to suggestions.
So, would anyone know what sensor would be good to detect the black stripe on AEMs?
Preferably to also work without light.
I know there are off-the-shelve products that do this already, but where's the fun in that?

Why not a reflectivity sensor?

I didnt think of that. Worth checking.

A low cost option is the TCRT5000 infrared proximity sensor. While this is designed to sense objects coming close to the sensor, by reflection of the infrared light emitted by the integrated IR LED, it also does very well in detecting black versus reflective surfaces placed near it.
There are two parts to making this work:

Reduce the drive current for the IR LED of the TCRT5000 to the bare minimum which causes detection of the non-black portion of the electricity meter disc. While the datasheet specifies a forward current of up to 60 mA absolute maximum, a quick experiment I conducted shows appreciable detected signal at as little as 4 mA forward current, for a metallic target surface 2 mm away. Tune the forward current to work with the actual distance and reflectivity of your particular electricity meter wheel.
Place a black piece of card or plastic in front of the detector part of the TCRT5000, with a thin slit cut in it to align with the black strip on the electricity meter wheel. I am getting good results using a 1.2 mm plastic sheet with a 0.3 x 1.5 mm slit cut in it.
Note that the two hemispherical plastic parts of the TCRT5000 look more or less the same, so you will have to identify which one is the detector, and ensure that you do not obstruct the emitter by mistake. The side with the angled vertical edges (right side of image below) is the emitter and must not be obstructed.

With this arrangement, the collector current through detector will dip significantly each time the black stripe passes in front of the detector.

On ALL mechanical watt-hour meters (those with a rotating disk), the disk will have either one or two holes, typically in the mid section or outer edge of the aluminum disk. Utilities used these holes to pass a light beam through (from the top of the meter to the bottom of the meter) to detect and count disk rotations. A simple light source and photo-transistor can be used to detect the presence of the disk hole to sense disk rotations.

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


text:
Does any board provide more than 1024 analog input values?
The Arduino boards provide an analog input range of 0V to 5V which translates to 0 to 1023 integer values. The range is determined by the on-board ADC, which in the case of the Uno is a 10 bit ADC (2^10 = 1024).
Do any of the official boards have a larger (>10 bits) ADC? Do any boards provide a wider range of analog input values?

AVR-based Arduinos only have 10-bit ADCs, but the ATSAM3X in the Due has 12-bit ADCs. Additionally, it is possible to interface to higher-resolution external ADCs via I2C or SPI.

Remember that more bits imply higher sensitivity to power supply various other sources of noise.

Could you please provide some references of external ADC chips that connect through I2C or SPI?

@jfpoilpret:http://www.ti.com/lsds/ti/data-converters/analog-to-digital-converter-products.page#p84=11;31&p158=Serial%20I2C;Serial%20SPI;Serial%20SPI%20Interface
http://www.microchip.com/ParamChartSearch/chart.aspx?branchID=11022&mid=10&lang=en&pageId=79
http://parametric.linear.com/analog-to-digital_converters_%28adc%29#!cols_1049,1030,2201,1097,1059,1058,1054,1367!s_1049,1!gtd_!1049_%3E=11!1054_Serial%20I2C|Serial%20SPI
http://www.analog.com/parametricsearch/en/10169?mtuid=MTS5KSkLdcfF-PC#10169?p7=11|12|13|14|15|16|18|20|22|24&d=sel|0|-1|7|165|4162|88|164|-3|4365&p4365=SPI|I%B2C/Ser%202-Wire

@jippie, remember that multi-sampling is always available for ADC chips that don't lock in their value...

How much accuracy do you really need? If it's just 1 or 2 extra bits of resolution you are after, you might be able to achieve that with a bit of oversampling.
Basically, you take a ton of readings and average them. It only works if there is at least a few mV of random noise in your signal or in your ADC, and if your input signal bandwidth is low enough to be averaging samples together.
Otherwise, go with a dedicated ADC chip.

They all do with oversampling. You can evaluate the quality of doing this for your own use.

Welcome to Arduino SE! Can you please add to your post to explain how you do this? Thanks!


text:
How much can an Uno be overclocked?
When running the board at room temperature (20 C) without any extra cooling mechanisms added, how much can the Arduino Uno be overclocked?
Also, what would I need to change/update to overclock the board?

Do you want to be able to program your Arduino once it has been overclocked? In that case the answer is probably 0%.

You probably get a higher and more reliable performance improvement by reviewing your code and ditching some standard Arduino libraries.

See the following question

With no active cooling, most ATmega328P will run at 30MHz but you will need to up the supply voltage to ~6V. I have never done this on an Arduino board, just an ATmega328P.
I provided an external clock from a signal generator.
The only way to achieve a speed faster than 16MHz is to change the crystal/oscillator/clock input for one faster than 16MHz.
As this was just an experiment, I didn't alter f_cpu in boards.txt, so all timers etc. would be incorrect. Baud rates would also be incorrect - the only way to upload code was to change back to 16MHz.

Very interesting data about the actual clock rate supported. As for the only way to upload code, maybe it would be easier to use ISP instead of a serial boot loader in such a setup?


text:
Is there a color LCD display for an arduino?
I currently have a Mega2560 with the LCD4884 Shield. The Shield is good for putting out text and simple pixel images. But I am wondering if there is something that has a full range of colours that would work with the Arduino? The screen size would only have to be a few inches in size.

I would personally think of this a shopping recommendation. To answer your question: https://www.google.com/#q=arduino+color+lcd

There are actually several shields that have color screens on them. Many of the shields are just regular mini TFT displays, however there are also touch screen ones.
Here is one from Adafruit that includes a MicroSD holder and a Joystick.
Here is one from Radio Shack that features a 2.8 inch screen with touch capabilities
As far as screen size, many of the screens are only about an 1 inch across, however the biggest I have ever been able to find are 2.8 in.

The 1.8" TFT from Adafruit with joystick & MicroSD is my favorite thing ever! Display + User Input. Majenko developed an epic library for it: https://github.com/cacycleworks/chipKIT_ST7735

Here is one from Elechouse in China on eBay, $30 3.2" TFT Color LCD with touch stylus and using the Adafruit GFX library.  Demo worked first try, instructions and software on the eBay page.

@Bob How responsive is it? Does it take a few moments to load new pictures? Resistive touchscreen?

@Anon you mean responsive to touch?  Interactive animation?  I don't recall any want for responsiveness but I only fired the demo up once.  I recall seeing a photo image and using the stylus in a simple "draw" program like in the eBay photos.  I could connect and load it again if you have anything specific you'd like me to look for.  I only got it working in the Arduino IDE, hadn't yet ported it to my favored AtmelStudio IDE.

There's also a 2.2" Adafruit TFT.
The nice things about the Adafruit displays are:
i) library support for both the display and the graphics core library. So it's easy to get it up and running.
The built in frame buffer reduces resource requirements on Arduino.

Another very cool screen is the official Arduino TFT LCD Screen. (Datasheet if you're curious.)
It's a 1.77" screen, with a resolution of 160x128. It has a micro-SD slot in it, which is easily accessible. It is a color screen, with up to 18 bit per pixel.
The extremely nice thing with this screen is that since it's officially supported, you don't need to do anything extra to support it. The official Arduino TFT library works perfectly with it. However, according to Jameco:

Library Update: There is a known issue with the TFT library supplied
  in IDE versions 1.0.5 and 1.5.4 Beta. You will need to replace the
  library. We have zipped up the updated TFT library for both versions
  available here. Just delete the existing library and copy in the
  replacement for the appropriate IDE version and restart the IDE. (IDE
  v1.0.5 or v1.5.4)

So beside that minor fix, everything should be easy and quick to work with. This page has some code samples which should make it easy to work with.


text:
Can two LEDs attached to different pins share their resistor?
I'm designing an Arduino style board with built-in LEDs for several of the pins. To simplify assembly of the board and save on components, I was wondering whether it would be safe for those LEDs to share a single resistor, as in this diagram:

Obviously, the power dissipated through the resistor (3mA per pin @ 3V) is not a real problem. The reason I was hesitating is that LEDs in a parallel configuration should not share resistors, but is it safe to think that separate microcontroller pins don't count as a common anode, even if both pins are high?

While not part of your question, generally speaking, if at all possible it is preferable to drive the cathode of the LED rather than the anode, as most microncontrollers and other IC's are better at driving negative outputs than positive, as N-channel FET's work better than P-channel ones.

@ChrisStratton, I've heard this before, but what are the practical implications of "better"? Faster switching speed? Closer to theoretical voltage? (I want these LEDs for diagnostic purposes, so having them active low is semantically undesirable anyway).

Can two LEDs attached to different pins share their resistor?

can : yes
should : probably not

Your resistor act here as a current limiter, say to 3mA
If you light one LED at a time, you give 3mA to that LED
If you light 2 LEDs, you give 3mA for both of them (more of less 1.5mA each)
If you light 3 LEDs, you give 3mA for all of them (on average 1mA each)
Things are even a little bit more subtle, as different LED might have different forward voltage, so one LED might very well drain 10% more current than an other.
As "Amps made LED bright", less Amp is less light. On LED light with that setup will give "full light on", and more LED you add, less would bright each one.

As an edit to that answer, there is one case I might consider that arrangement for "multi-LED lighting". This is if you are multiplexing your LEDs
That is lighting only one at a time, but cycling fast enough from one LED to the next so that the human eye would see them all lit at once.

Ah yes, that I had not properly considered, and for my purposes, it's a fatal objection.

Your circuit is safe from the electronic viewpoint, so long as the LEDs used can withstand a back-emf of 4v or so.
If only one LED is on at a time, all will be sweet. But if two or more are on, the brightness will drop and the brightness between LEDS will probably be inconsistent. The forward voltage drop of individual LEDS tend to vary a little, so one is likely to hog most of the available current.
A separate resistor per LED is probably best.

Mixing colors will give even wost results. If you have a blue and a red led (both ON), the blue led will not light up (or extremely dim), since blue leds have a higher voltage drop.

If one is making many thousands of something and there will never be any need to light more than one LED, using a shared resistor may save a half a penny each, which could add up to real money.  On the other hand, even if the application won't require lighting multiple LEDs being able to do so can be nice during debugging.  It's possible to make it look as though multiple LEDs are lit simultaneously, with predictable brightness, if one rapidly cycles among them, but sometimes during debugging it's more useful to be able to independently control the LEDs directly.


text:
Code to use an Arduino Mega 2560 to transfer UART <-> USB to debug an other Microcontroller
I have the following circuit and want to use the Arduino Mega 2560 as an debugger for an other Microcontroller.

So I am looking for the code to redirect the UART input from "P17 (RX2)" to the serial USB and the data coming from the serial USB to the output of "P16 (TX2)"

Is the Arduino going to do anything other than forward serial data?

@IgnacioVazquez-Abrams no just forwarding

Then why use an Arduino at all? USB-to-UART bridges are much cheaper.

@IgnacioVazquez-Abrams I know but i am not at home and here I have a Arduino Mega 2560 but no USB-to-UART bridge. So why not using the Arduino than not to be able to debug at all?

A very simple sketch to pass serial through looks like this:
void setup(){
  Serial1.begin(/*BAUD*/);
  Serial2.begin(/*BAUD*/);
}

void loop(){
  if(Serial1.available()){
    Serial2.print((char)Serial1.read());
  }
  if(Serial2.available()){
    Serial1.print((char)Serial2.read());
  }
}

I would advise both run at the same baud rate, otherwise you may need to do some extra buffering yourself if the arduino starts running out of buffer space. If you want to use the mega's USB connection instead of "Serial1" like your schematic, just switch "Serial1" to "Serial"


text:
ESP8266 Webserver ESP8266WebServer variable html page (not as one const char)
The aim is to display a non-static html page depending on some variable condition.
The code I created hast the problem, that the esp8266 is ressetting in the moment I request the page.
const char htmlIndexHeader[] PROGMEM = R"=====(

    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>

Hello World

)=====";

const char htmlIndexProgress1[] PROGMEM = R"=====(

lorem

)=====";

const char htmlIndexProgress2[] PROGMEM = R"=====(

ipsum

)=====";

const char htmlIndexFooter[] PROGMEM = R"=====(

)=====";

char htmlIndexAll[2000];

void handleRoot()
{
  Serial.println("GET /");

   strcpy(htmlIndexAll, htmlIndexHeader);

   if(var1==true)
   {
     strcat(htmlIndexAll, htmlIndexProgress1);
   }

   if(var2==true)
   {
     strcat(htmlIndexAll, htmlIndexProgress2);
   }

   strcat(htmlIndexAll, htmlIndexFooter);

  server.send(200, "text/html", htmlIndexAll);
}

If I display a static page the esp8266 does not restart at page request.

try strcpy_P and strcat_P

@Juraj it is working!

Compiler can't differentiate the PROGMEM strings from constant strings in SRAM strings. Both are const char*. But the PROGMEM string must be handled differently. For that reason _P variants of functions exists.
You should use stcpy_P and strcat_P functions.
Note: On esp8266 some functions of Arduino core use a trick to identify PROGMEM strings by their specific address range.


text:
ESP8266 Webserver ESP8266WebServer move Handler-Function in separate .h .c file
The plan is to create a bigger project and to split the ESP8266 webserver-code over several modules (.h .c files). The main problem is that the ESP8266WebServer server is not declared in the index.h and index.c files.
What I've been trying to do:
Content main.c
#include <ESP8266WiFi.h>
#include "ESP8266WebServer.h"
#include "index.h"

ESP8266WebServer server(80);
const char* ssid =     "test";
const char* password = "12345678";

void setup()
{
  WiFi.softAP(ssid, password);
  server.on("/", handleRoot(server));           // <-- use of deleted function 'esp8266webserver::ESP8266WebServerTemplate<WiFiServer>::ESP8266WebServerTemplate(const esp8266webserver::ESP8266WebServerTemplate<WiFiServer>&)'
  server.begin();
}

void loop()
{
  server1.handleClient();
}

Content index.h:
void handleRoot(ESP8266WebServer server);

const char htmlIndex[] PROGMEM = R"=====(

    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>

Hello World!

)=====";

Content index.c:
#include "webpages/index.h"

void handleRoot(ESP8266WebServer server)
{
  Serial.println("GET /");
  server.send(200, "text/html", htmlIndex);
}

How can I use the ESP8266WebServer server created in the main.c in index.c?

Move the webserver to index.c and include the webserver type:
ESP8266WebServer server(80);

Add an external reference in index.h and include it:
#include "ESP8266WebServer.h"

extern ESP8266WebServer server;

Index.h is included by both main.c and index.c so it will know about server being an ESP8266WebServer type, but does not allocate memory for it; that is done in index.c
This is called a forward reference.

I shifted
#include "ESP8266WebServer.h" extern ESP8266WebServer server; to main.h and included it in index.c but in the end it is your idea. thx.

Yes, in principle it does not matter where you place the external variable, as long as it is not in a header file (or at least not one that is included twice). Good luck with your project.


text:
Calibrate Watchdog Timer
Is there any good way to calibrate the watchdog timer? I'm trying to use it as a time source, even when asleep, but it's woefully inaccurate. Some simple testing showed it loosing 2 minutes every hour!

Not only is it uncalibrateable, but it's actually pretty rubbish (as you've discovered). If you check the datasheet you'll see that it can vary between about 109kHz and 119kHz, even though its nominal frequency is 128kHz.
With the ATmegaXX8(A/P) you can reconfigure the system to run its CPU off the internal RC oscillator and timer 2 from a crystal across TOSC1/TOSC2 (pins 9/10 [DIP] or 7/8 [TQFP]) by setting ASSR[6:5] to 0b01 and changing the CKSEL[3:0] fuse bits to 0b0010. Take careful note of the warning on AS2 in the datasheet though. If you want to use a watch crystal instead of prescaling the existing crystal on an Arduino board then you'll need some soldering skill as well.
If you need crystal accuracy for the CPU as well then you'll need to move up to an AVR family that has a separate asynchronous timer that can be supplied with a watch crystal, such as the ATmegaXX4(P) (Sanguino) or ATmegaXXX0 (Mega/Mega 2560).

Supposedly the regular 328p can handle a watch crystal in place of the 8/16Mhz crystal. I've been looking into that as an option, but can't really find any good documentation.

That will slow down your entire system though; you may as well just turn on the prescaler in that case.

Also, section 9 of the datasheet, "System Clock and Clock Options".

According to the datasheet you can use the XTAL/TOSC pins in asynchronous low frequency timer mode but then use the internal crystal for system time.

You're correct; I'll amend my answer.


text:
ATMega32u4 (Leonardo) Serial Baud Rate
Does anyone know what the actual baud rate that the CDC Based virtual serial port on the Leonardo runs at is? Serial::being() for the CDC version is just empty, so it's not setting a baud rate anywhere.
Basically, I'm debating between using the 32u4 or the 328p with an FTDI chip and trying to figure out if the 32u4 will be slower... since it uses a virtual COM port I'm assuming it is, but I'd be happy if I was wrong :)

I'm not sure if the concept of an "actual baud rate" is really meaningful in a pure USB connection.
In my experience, the 32u4 is faster than the 328p at serial-heavy tasks. There is no intermediate chip, and USB has much larger hardware buffers than the serial port does. I don't know how much processing you're planning to do on your data, but I would expect that a 32u4 can process serial data pretty much as fast as you can generate/process it.
On the host side, it seems to me that there is very little difference in whether the "virtual COM port" has an FTDI or a 32u4 on the other end, so I don't see why one should be faster than the other (though admittedly they go through different device drivers).


text:
Teensy USB Core on Leonardo
The USB Serial speed on the teensy is WAY faster then on the Leonardo. Looks like because they have greatly improved the USB code. Has anyone had any luck using the Teensy core libraries on a Leonardo? I would imagine it should work as the hardware is basically the same.

Have you tried selecting a higher speed in your serial client?

Yes, I've cranked it all the way to 1Mbps.

Looking at the schematics of both, I don't see why it wouldn't work. Just note that e.g. you'll lose the tx and rx led functionality (which might account to the slower speed), but you could reuse those leds for something else (-:. Also be aware that pin numbering is a bit different.

Unless you are comparing to the teensy 2.0 (not +), the hardware is much different (i.e. microprocessor) - that alone could account for a large performance difference

The discontinued Arduino Leonardo uses an ATmega32U, (https://www.arduino.cc/en/Main/ArduinoBoardLeonardo)  as is the Teensy2.0, which, USB-hardware-wise is very similar to the AT90USB1286.  Teensy's hardware USB system acts as a virtual serial port and completely ignores the Serial.begin(xxxx) baud rate and operates at a full 12Mbi ratet:  https://www.pjrc.com/teensy/td_serial.html


text:
Disable Boot Flash completely on ATMega
I want to reclaim the space reserved for the bootloader on my ATMega32u4 (Leonardo chip).
But the lowest boot flash size I can see is BOOTSZ=11 which is 256 words (512 bytes). Is it not possible to completely disable it?
Basing this off of this: http://www.engbedded.com/fusecalc

It is not possible to set the bootloader space to 0, but it is possible to unlock the bootloader space entirely by unprogramming the lock bits as well as to enable normal booting by unprogramming BOOTRST in the high fuse byte. Access to the entire chip will then be fully unrestricted.


text:
Arduino: Hardware SPI hangs, bit-bang does not
I'm using FastLED with a custom board built around the ATMega32u4. When I set it to use Software SPI, everything works fine, but when I use hardware SPI it just hangs whenever it tries to write out the data (FastLED.show()).
I originally mocked this up on an Arduino Pro Micro and it worked fine there. That makes me think that it's a hardware issue but, as I mentioned, SPI output does work, but only when bit-banged. Which really doesn't make much sense.
I tested this by also just using the built in SPI classes and I get the same thing. No luck with hardware SPI.
Anyone else ever see something like this?
The schematic of my circuit is below.

Have you checked SCK/MOSI with an oscilloscope to verify if some signal was sent?

According to ATmega32u4 datasheet, section 17.2.1 (SPI / SS Pin Functionality / Master Mode:

If SS is configured as an input, it must be held high to ensure Master SPI operation.

In your circuit, SS pin (#8 on package), also labeled as "(SS/PCINT0) PB0", is left unconnected.
Is it possible that PB0 is also configured as input somewhere in your program or libraries? In this case, it should be connected to Vcc.

YOU ARE MY FAVORITE PERSON RIGHT NOW!! I was testing on a Pro Micro and it just happened to have that pin connected to VCC through an LED and resistor. So, it made it work. pinMode(0, OUTPUT) made it all work again :) THANKS!

Just to add. Instead of connecting to vcc you can also just enable the internal pull-up resistor.

Or just configure the pin is OUTPUT which is the easiest way, and it enables you to use that pin for something else. That's probably the best option.


text:
Get board.vid and board.pid value in code
I'm working on a custom Arduino core based on the teensy code and want to be able to get the board USB VID/PID from boards.txt, as in .board.vid and .board.pid
From what I can tell, Arduino already does this for the Leonardo and similar since if I change the VID/PID in boards.txt then the sketch will run with those values.
But how do I actually get at them? Right now the code I have has hard coded values, but it would be great to make them dynamic.

The preprocessor will sub in the values for the names "USB_PID" and "USB_VID"
this line in "platform.txt" grabs them and makes build flags for them:
build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'

the -D* option in the build is equivalent to the following lines being in the code
#define USB_VID /*value of build.vid*/
#define USB_PID /*value of build.pid*/
#define USB_MANUFACTURER /*value of build.usb_manufacturer*/
#define USB_PRODUCT /*value of build.usb_product*/

If you are curious, they are used by the libraries in "USBCore.cpp". Also, they will never be defined for devices they don't apply to.

Weird though... could not get manufacturer and product to work. VID/PID worked fine though.

That is odd. What version of arduino are you using? That came from 1.5.8

No wonder I couldn't find platform.txt... I'm using 1.0.5
I swear there was a reason I hadn't upgraded to the beta yet, but can't remember what that was at the moment... think it was incompatible with something I needed.


text:
Send Keyboard Media Keys with Keyboard Library
I have an Arduino Pro Micro (ATMega32u4) that I want to use as an IR receiver for a media PC and need to send codes like Volume Up, Media Home, Play, etc. But when I look up the scan codes for those and send them to Keyboard.press() it just prints out '0' every time.
Any way to send those keyboard commands?

Include your sketch.  Provide a ref for where you looked up the scan codes etc, as most charts don't have media keys listed

I used an app I wrote in C# a long time ago to capture scan codes. Media Home is 128 apparently.

It is indeed possible and also without the requirement to modify the Arduino environment itself. Just register an HID descriptor for the "report ID" for "Consumer Control" (the code is 4 (constant kHID_ReportID_ConsumerControl), where the "report ID" code for keyboard and mouse are 2 and 1, respectively):
static HIDSubDescriptor node(HID_ReportDescriptor_ConsumerControl,
                             sizeof(HID_ReportDescriptor_ConsumerControl));

HID().AppendDescriptor(&node);

After the registration, HID().SendReport() now works for "report ID" equal to 4 (the first parameter), and the audio volume can be changed, etc.
The registration needs to done once and can be put into the init() function, for instance, after the Keyboard.begin(); and Mouse.begin(); calls.
Usage
Example usage, increasing the audio volume by one step:
uint8_t data[2];
data[0] = kVolumeUp;
data[1] = 0;
HID().SendReport(kHID_ReportID_ConsumerControl, data, 2);

The constants are at the end.
Notes
"Consumer Control" has the multimedia controls Volume up, Volume down, Mute, Play, etc.
The registration is similar to the way the constructors for the built-in keyboard and mouse libraries do it. HID_ReportDescriptor_ConsumerControl and constants are listed at the end because it is quite long, but they must come first (for instance, in the beginning of the file).
All this could be packaged into a reusable form. Here I have demonstrated it in a paste-and-forget form to keep it short.
HID().SendReport() looks strange, but HID() is a global function that returns an instance of the class HID_ (all built into the standard Arduino libraries, presumably to avoid some initialisation order problems with global/static objects - I thought Scott Meyers had solved that a long time ago (47. in the first book)).
HID().SendReport() can also be used to circumvent the limitation of a presumption of a US keyboard. E.g. using code 100, page 56 (and kHID_ReportID_Keyboard, like in the standard class keyboard_) to emulate the 102th key on European keyboards (e.g. a Spanish keyboard).
Only volume up and volume down were tested.
Definition of HID_ReportDescriptor_ConsumerControl and constants:

// For direct use of USB HID (yes, 3 is left out)
const uint8_t kHID_ReportID_Mouse           =  1;
const uint8_t kHID_ReportID_Keyboard        =  2;
const uint8_t kHID_ReportID_ConsumerControl =  4;
const uint8_t kHID_ReportID_SystemControl   =  5;
const uint8_t kHID_ReportID_Gamepad         =  6;
const uint8_t kHID_ReportID_MouseAbsolute   =  7;
const uint8_t kHID_ReportID_NKRO_keyboard   =  8;
const uint8_t kHID_ReportID_TeensyKeyboard  =  9;
const uint8_t kHID_ReportID_SurfaceDial     = 10;

// For use in "Consumer Control". They are bit coded.
const uint8_t kVolumeUp   = 1 << 0; // Bit 0
const uint8_t kVolumeDown = 1 << 1; // Bit 1
const uint8_t kVolumeMute = 1 << 2; // Bit 2

static const uint8_t HID_ReportDescriptor_ConsumerControl[] PROGMEM =
{
    0x05, 0x0c,                           // Usage Page ("Consumer Devices")
    0x09, 0x01,                           // Usage (Consumer Control)
    0xa1, 0x01,                           // Collection (Application)
    0x85, kHID_ReportID_ConsumerControl,  // "Report ID"
    0x15, 0x00,                           // Logical Minimum (0)
    0x25, 0x01,                           // Logical Maximum (1)
    0x09, 0xe9,                           // Usage (Volume Up)
    0x09, 0xea,                           // Usage (Volume Down)
    0x75, 0x01,                           // Report Size (1)
    0x95, 0x02,                           // Report Count (2)
    0x81, 0x06,                           // Input (Data, Variable, Relative)

    0x09, 0xe2,                           // Usage (Mute)
    0x95, 0x01,                           // Report Count (1)
    0x81, 0x06,                           // Input (Data, Variable, Relative)

    0x09, 0xb0,                           // Usage (Play)
    0x95, 0x01,                           // Report Count (1)
    0x81, 0x06,                           // Input (Data, Variable, Relative)

    0x09, 0xb1,                           // Usage (Pause)
    0x95, 0x01,                           // Report Count (1)
    0x81, 0x06,                           // Input (Data, Variable, Relative)

    0x09, 0xb7,                           // Usage (Stop)
    0x95, 0x01,                           // Report Count (1)
    0x81, 0x06,                           // Input (Data, Variable, Relative)

    0x09, 0xb5,                           // Usage (Next)
    0x95, 0x01,                           // Report Count (1)
    0x81, 0x06,                           // Input (Data, Variable, Relative)

    0x09, 0xb6,                           // Usage (Previous)
    0x95, 0x01,                           // Report Count (1)
    0x81, 0x06,                           // Input (Data, Variable, Relative)

    0x09, 0xb3,                           // Usage (Fast Forward)
    0x95, 0x01,                           // Report Count (1)
    0x81, 0x06,                           // Input (Data, Variable, Relative)

    0x09, 0xb4,                           // Usage (Rewind)
    0x95, 0x01,                           // Report Count (1)
    0x81, 0x06,                           // Input (Data, Variable, Relative)

    0x95, 0x06,                           // Report Count (6) Number of bits remaining in byte
    0x81, 0x07,                           // Input (Constant, Variable, Relative)
    0xc0                                  // End Collection
}; // Table for USB HID "Consumer Control" (for audio volume control, etc.)

Platform
This was tested with:

Arduino Leonardo (already used as a macro keyboard, using an old PS/2 keyboard. Two new macro keys were assigned for testing audio volume up / down).
The Arduino Leonardo connected to an extra current port of a D-Link USB hub (necessary, for unknown reasons - probably a local problem)
Arduino IDE v. 1.18.10
Linux, Ubuntu 19.10 (Eoan Ermine), but with the buggy GNOME replaced by Cinnamon.

I had the same problem, and the existing information here was not sufficient. Later, I found and tested a solution. And here is the result!

Some trivia: This started because the volume wheel on the keyboard exhibited strange behaviour. The emulation was an effort to try to isolate the problem. It turned out it is most likely a mechanical issue (it has had problems before with some keys (that resoldering solved)).

Though, are the report IDs entirely arbitrary (self-defined)? Do they just happen to be 2 and 1 for keyboard and mouse in the Arduino standard library? Or are there some conventions/default values/standard?

Thank you for this recipe, it was the only one that worked for me! Using an Arduino Micro (not Pro) with an IR receiver+remote, working well on Ubuntu 20.04.

The Spanish keyboard reference was meant to be a reference to this how-to guide (on this site), but I will not bump it at this time.

You have to do some tweaks to the usbkeyboard libraries that comes with the IDE.
For a video tutorial, take a look at this:
Arduino Leonardo as a multimedia keyboard
Which uses the information from this site, if you prefer text only:
Arduino Leonardo multimedia keys
The Leonardo and ProMicro both use the ATMega32u4 and should both work with theses tweaks. If you need more functionality than the ones that this tweak gives you, you have to dig down into usb descriptors on usb.org for the commands you need.

What is the meaning of "4" for the first parameter to HID_SendReport()? Is it for pretending to be an IR remote control?

OK, after a long, long search I found it: 4 is for "Consumer control" (for "report ID"). A more complete list (only 3 is left out) is in a library, with symbolic names: 1: Mouse, 2: Keyboard, 4: Consumer control (with the volume controls/multimedia control), 5: System control, 6: Gamepad, 7: Mouse absolute, 8: NKRO keyboard, 9: Teensy keyboard, 10: Surface dial

cont' - (defines (constants) HID_REPORTID_MOUSE, HID_REPORTID_KEYBOARD, HID_REPORTID_CONSUMERCONTROL, HID_REPORTID_SYSTEMCONTROL, HID_REPORTID_GAMEPAD, HID_REPORTID_MOUSE_ABSOLUTE, HID_REPORTID_NKRO_KEYBOARD, HID_REPORTID_TEENSY_KEYBOARD, HID_REPORTID_SURFACEDIAL, respectively).

Though the report IDs may be arbitrary (self-defined)?

If you are getting zeros, the most probably cause is it's the library for the IR. Reinstall or update the library. Sometimes you have to reinstall more than one time. That should work.
About media keys, the keyboard library doesn't have media keys functionality, so you need to use another one. This one worked for me: https://github.com/NicoHood/HID
After you install this library, you have to change your code. The code for pressing media keys is different. You have to use Consumer.write, for example, Consumer.write(MEDIA_VOLUME_UP) for volume up. You can find the name of every key here: https://github.com/NicoHood/HID/wiki/Consumer-API
For normal keys, just use Keyboard.write(). If you want, I can send you the code I made to do this.

Keyboard.press() presses a key and “holds it down” until a Keyboard.release() or releaseAll() is issued.  That is, Keyboard.press() isn't appropriate for simulation of just tapping and releasing a key, unless you follow it with a delay and a release.
Also see Keyboard.write().  But note the following, from Keyboard.write()'s documentation:

Only ASCII characters that are on the keyboard are supported. For example, ASCII 8 (backspace) would work, but ASCII 25 (Substitution) would not.

On my linux system, xev (used via xev -event keyboard) shows the following data for media keys labeled as shown.
  Excerpt from info displayed by xev           Picture
keycode 180 (keysym 0x1008ff18, XF86HomePage)   house
keycode 179 (keysym 0x1008ff81, XF86Tools)   quarter-notes
keycode 163 (keysym 0x1008ff19, XF86Mail)      envelope
keycode 172 (keysym 0x1008ff14, XF86AudioPlay)  >/||
keycode 122 (keysym 0x1008ff11, XF86AudioLowerVolume)  speaker
keycode 123 (keysym 0x1008ff13, XF86AudioRaiseVolume)  speaker
keycode 121 (keysym 0x1008ff12, XF86AudioMute)  x'd-speaker
keycode 148 (keysym 0x1008ff1d, XF86Calculator)  Calculator

I know... I'm doing press();delay();releaseAll().
But if I give it code 128 for example, it does nothing.

Peter's answer probably is the way to go from scratch. But if you want to start from somewhere there's also another library by BleKeyboard https://github.com/T-vK/ESP32-BLE-Keyboard/blob/master/BleKeyboard.cpp. It shows you pretty much the whole process how the media report is created.
// ------------------------------------------------- Media Keys
  USAGE_PAGE(1),      0x0C,          // USAGE_PAGE (Consumer)
  USAGE(1),           0x01,          // USAGE (Consumer Control)
  COLLECTION(1),      0x01,          // COLLECTION (Application)
  REPORT_ID(1),       MEDIA_KEYS_ID, //   REPORT_ID (3)
  USAGE_PAGE(1),      0x0C,          //   USAGE_PAGE (Consumer)
  LOGICAL_MINIMUM(1), 0x00,          //   LOGICAL_MINIMUM (0)
  LOGICAL_MAXIMUM(1), 0x01,          //   LOGICAL_MAXIMUM (1)
  REPORT_SIZE(1),     0x01,          //   REPORT_SIZE (1)
  REPORT_COUNT(1),    0x10,          //   REPORT_COUNT (16)
  USAGE(1),           0xB5,          //   USAGE (Scan Next Track)     ; bit 0: 1
  USAGE(1),           0xB6,          //   USAGE (Scan Previous Track) ; bit 1: 2
  USAGE(1),           0xB7,          //   USAGE (Stop)                ; bit 2: 4
  USAGE(1),           0xCD,          //   USAGE (Play/Pause)          ; bit 3: 8
  USAGE(1),           0xE2,          //   USAGE (Mute)                ; bit 4: 16
  USAGE(1),           0xE9,          //   USAGE (Volume Increment)    ; bit 5: 32
  USAGE(1),           0xEA,          //   USAGE (Volume Decrement)    ; bit 6: 64
  USAGE(2),           0x23, 0x02,    //   Usage (WWW Home)            ; bit 7: 128
  USAGE(2),           0x94, 0x01,    //   Usage (My Computer) ; bit 0: 1
  USAGE(2),           0x92, 0x01,    //   Usage (Calculator)  ; bit 1: 2
  USAGE(2),           0x2A, 0x02,    //   Usage (WWW fav)     ; bit 2: 4
  USAGE(2),           0x21, 0x02,    //   Usage (WWW search)  ; bit 3: 8
  USAGE(2),           0x26, 0x02,    //   Usage (WWW stop)    ; bit 4: 16
  USAGE(2),           0x24, 0x02,    //   Usage (WWW back)    ; bit 5: 32
  USAGE(2),           0x83, 0x01,    //   Usage (Media sel)   ; bit 6: 64
  USAGE(2),           0x8A, 0x01,    //   Usage (Mail)        ; bit 7: 128
  HIDINPUT(1),        0x02,          //   INPUT (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
  END_COLLECTION(0)                  // END_COLLECTION

If you are curious why these media button works, you can checkout the USB doc https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf, Page 75, where it states why each key usage is used.


text:
Arduino core for ATMega16u2
I've looked around a ton so it's probably not available but does anyone know if there is a usable core for the ATMega16u2 (the chip the Uno and Due uses for USB to Serial). I have a project I was going to use the 32u4 for but they aren't really available for several months and the 16u2 has all the functionality that I would really need.

"171 in stock"

I need the actual IC, NOT a board that already has it.

:O I... I don't think I've ever seen so many 0s before... Newark has a few -MUs, but I think someone bought up the world's supply of -AUs.

Yup :( Was very dissapointed that basically no one has them...

I think it's pretty much the same as the 32u4 but has less flash memory and less RAM. I think avr-gcc handles the RAM part. As for the flash memory, just copy and modify the atmega32u4 section in boards.txt to handle that.

I forgot about the bootloader. But I think you can just recompile it for the atmega16u2 without many, if any, changes.

Or use a programmer and forgo the bootloader entirely.

Don't need the bootloader actually. As long as it can be programmed via an ISP I'm good.

A thought just occurred to me. If a 16U2 will do, then why not use a 16U4 instead? All you'd need to change is the amount of flash available. And DigiKey has a few hundred of those in stock in -AU.

As @IgnacioVazquez-Abrams said, a 16u4 is virtually identical with a 32u4, so you can use a Leonardo or Micro core with a tiny modification to boards.txt. A 16u2 is a rather different animal, with fewer timers, many fewer pins, and no A/D converter, so you’d have to do a fair amount of editing to obtain a usable Arduino core.
That said, if you’re reasonably fluent in C++, building your own Arduino core is not very difficult, and I found it an instructive exercise. If you care about getting your project up as quickly as possible and not get sidetracked, however, go with the 16u4.


text:
Light LED when 2 others are disconnected
I need to make circuit in which orange LED will light only when yellow and red are disconnected. When one of buttons is pushed orange LED should turn off.
See my attempt at it below.
I am new to electronics so your help is very appreciated.

EDIT:
After many atemps I managed to build this circuit as on left side of schematic (tested on live breadboard)

but my primary goal is to make this work with RGB LED. I took Common Anode RGB LED for this and build circuit on right side of schematic. I do not have such RGB LED to test it live so I ask you to review if that schematic will work as it has few changes to one with 3 LED's. Thank you
SOLUTION:
Thanks to Bruce's help my circuit now works.
3 separate LEDs emulate common anode RGB LED (as I do not have one to test circuit)
Q2 is BC 560B transistor with CBE type pinout

CODE:
void setup() {
  pinMode(2,INPUT);
  pinMode(4,INPUT);
  Serial.begin(9600);
  digitalWrite(2,HIGH);
  digitalWrite(4,HIGH);
}

void loop() {
  Serial.println(digitalRead(2));
  Serial.println(digitalRead(4));
}

I'm a newbie too, but are you planning on using an Arduino by any chance?

Yes I plan to use Arduino and using Arduino is easy way for that. But need this circuit because I need to have about 20 circuits like that and this make use of 60 arduino I/O's which I want to use for some other things than light this LED

By being disconnected, I'm assuming that you mean the buttons for the red and yellow LED's are not pressed down?

yes, when button is pressed LED is ON, when not pressed LED is OFF, when both(red, yellow) LED's are OFF orange LED should turn ON

I haven't done any of this myself, but I think you could use a MOSFET and hook up all the orange LED's to the drain pin. Have the Arduino read buttonState (google this). Then if the buttonState is LOW, meaning disconnected, have the Arduino digitalWrite HIGH to the gate of the MOSFET controlling the orange LED. If the buttonState is LOW, have the Arduino digitalWrite LOW to the gate. Just a general idea, although I'm sure there are better ways to do this.

I want to make this circuit without using Arduino. Using only electronic parts but I do not know which and how to connect that circuit.

I have edited my question with more details

I'd just use DPDT buttons instead.

You want the green LED to be on only when the red and blue LEDs are both off. In other words, you want the voltage on the green LED to be LOW only when the voltages on the red and blue LEDs are both HIGH. That is a logical NAND function.
Your right-hand circuit with the RGB LED won't work because the transistor's collector is connected to the wrong place - it's shorting out the battery! Another problem is that the Arduino can only switch to Ground or +5V, so it can't replace a 'floating' switch.
You need a configuration that produces a logical NAND function. Your left-hand circuit is doing it, but won't work with a common anode RGB LED. So swap the transistor to a PNP  type, and add a couple of resistors to switch it on when either input goes low, like this:-

To clarify my goal for RGB LED ... when buttons are open (not pushed) Green LED should be OFF, when one of buttons are closed (pushed) certain LED (red or blue) should be ON and green should turn OFF

my bad english .... sorry Bruce ... correct "when buttons are open (not pushed) Green LED should be ON"

I have bought PNP transistor CTBC 560B (lowest voltage they had in store) and your circuit does not work with it. when I remove this transistor D3 (on your schematics) turns ONO. When I return it to circuit D3 turns OFF. I used R1,R2,R3 220ohm and R4,R5 10k ohm. Is it problem with resistors or with this transistor?

this is my breadboard and schematics based on your example: http://i.imgur.com/QYzJe9z.png http://i.imgur.com/7tt6VYs.png - my later goal is to replace switches with limit stop switches and read on arduino INs state of limit stop circuits (blue, red LEDs), green LED is indicator which is supposed to work without arduino connection.

YAY it works :D thank you Bruce very much. you mean connecting after switch to arduino IN instead of GND?

Thanks Bruce again after some trial & error I managed to read state in arduino from this circuit. Your help was priceless.